rayzee 11.11.0 → 11.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{ArchiveImporter-D5XOC3tN.js → ArchiveImporter-vUowipjh.js} +3 -3
- package/dist/{BidirectionalIntegrator-DqG0BEIz.js → BidirectionalIntegrator-DPh6PSYb.js} +2 -2
- package/dist/{ColorManagement-B_HjAiy2.js → ColorManagement-3xw0xXRg.js} +859 -374
- package/dist/{NeuralRetouch-BkxZPOYq.js → NeuralRetouch-wwAwssFM.js} +1 -1
- package/dist/{NeuralSuperRes-a8xDtvXM.js → NeuralSuperRes-DqV4v_gQ.js} +6 -6
- package/dist/{PathTracer-C_gliSWI.js → PathTracer-DW-ElMON.js} +1 -1
- package/dist/{PhysicalSky-DWK8pS0U.js → PhysicalSky-Ispr77Lf.js} +1 -1
- package/dist/{RayzeeRenderer-B4ZehMg_.js → RayzeeRenderer-CPbY683A.js} +349 -289
- package/dist/{SceneMetadata-Bb3iwWhh.js → SceneMetadata-BNA22-m3.js} +1 -1
- package/dist/addons/archives.es.js +1 -1
- package/dist/addons/bidirectional.es.js +1 -1
- package/dist/addons/color.es.js +2 -2
- package/dist/addons/physical-sky.es.js +1 -1
- package/dist/rayzee-core.es.js +4 -4
- package/dist/rayzee.es.js +637 -627
- package/dist/rayzee.umd.js +9 -9
- package/dist/{sceneCachePolicy-BHNKvrHR.js → sceneCachePolicy-BLvdjkVh.js} +1 -1
- package/package.json +1 -1
- package/src/Color/BakedViews.js +5 -2
- package/src/Color/BasicColor.js +27 -0
- package/src/Color/ColorManagement.js +255 -11
- package/src/Color/Displays.js +149 -7
- package/src/Color/OcioRuntime.js +19 -4
- package/src/Color/OcioViews.js +251 -37
- package/src/Passes/AIUpscaler.js +6 -2
- package/src/PathTracerApp.js +2 -0
- package/src/RayzeeRenderer.js +54 -9
- package/src/Stages/Compositor.js +86 -3
- package/src/addons/color.js +2 -2
- package/src/index.js +2 -2
- package/src/managers/DenoisingManager.js +18 -4
- package/src/managers/VideoRenderManager.js +10 -1
- package/src/neural/NeuralSuperRes.js +5 -5
package/dist/rayzee.umd.js
CHANGED
|
@@ -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 cs(){ds.length=0,ds.push(...Jo),fs.clear();for(let e of ds)fs.set(e.id,e);Xo()}var ls,us,ds,fs,ps,ms,hs,gs,_s,vs=g((()=>{Yo(),ls=200,us=12,ds=[...Jo],fs=new Map(ds.map(e=>[e.id,e])),ps=1,ms=new Set,hs=fs,gs=r.NoToneMapping,_s=r.AgXToneMapping}));vs();var ys=e=>(t,n,r,i,a)=>e(t>0?t:0,n>0?n:0,r>0?r:0,i,a),bs=new Map;function xs(){bs.clear();for(let e of hs.values())bs.set(e.id,ys(e.cpu))}xs(),Qo(xs);function Ss(e){return $o(e)?.outputEncoded===!0}function Cs(e){return e<=.0031308?12.92*e:1.055*e**(1/2.4)-.055}function ws(e,t){let n=$o(t);return n?n.appliesExposure?e:1:t===r.NoToneMapping?1:e}function Ts(e,t,n){return ws(e,n)/ws(t,n)}function Es(e,t,n){return e+(t-e)*(1-Math.min(Math.max(n,0),1))}var Ds=.2126,Os=.7152,ks=.0722;function As(e,t){if(t===1)return;let n=e[0]*Ds+e[1]*Os+e[2]*ks;e[0]=n+(e[0]-n)*t,e[1]=n+(e[1]-n)*t,e[2]=n+(e[2]-n)*t}function js(e,{exposure:t,toneMapping:n,saturation:i=1,preserveAlpha:a=!1,pixelGain:o=null}){let s=bs.get(n)??bs.get(r.NoToneMapping),c=ws(t,n),l=Ss(n),u=new Uint8ClampedArray(e.length),d=[0,0,0],f=Math.log2(t);for(let t=0;t<e.length;t+=4){let n=c;if(o){let r=1;if(o.fn){let n=t>>2,i=n%o.width,a=(n-i)/o.width,s=e[t]*.2126+e[t+1]*.7152+e[t+2]*.0722;r=o.fn((i+.5)/o.width,(a+.5)/o.height,s,f)}o.backdrop>0&&(r=Es(r,o.backdrop,e[t+3])),n*=r}d[0]=e[t]*n,d[1]=e[t+1]*n,d[2]=e[t+2]*n,As(d,i),s(d[0],d[1],d[2],1,d),l?(u[t]=d[0]*255+.5,u[t+1]=d[1]*255+.5,u[t+2]=d[2]*255+.5):(u[t]=Cs(d[0])*255+.5,u[t+1]=Cs(d[1])*255+.5,u[t+2]=Cs(d[2])*255+.5),u[t+3]=a?e[t+3]*255+.5:255}return u}Ft(),en(),an(),Ae(),Fr();var Ms=ve(`textures`),Ns={MAX_BUFFER_MEMORY:1024*1024*1024,MAX_TEXTURE_MEMORY:2048*1024*1024,CLEANUP_THRESHOLD:.8,STREAM_BATCH_SIZE:4},Ps=8*2**20,Fs=16,Is=4,Ls=8192*8192,Rs={busy:0,waiting:[]};async function zs(){return Rs.busy<Math.max(1,Or()-1)?Rs.busy++:await new Promise(e=>Rs.waiting.push(e)),()=>{let e=Rs.waiting.shift();e?e():Rs.busy--}}var Bs={toSRGB:null,toLinear:null};function Vs(e){if(!Bs[e]){let t=new Uint8Array(256);for(let n=0;n<256;n++){let r=n/255,i=e===`toSRGB`?Cs(r):r<=.04045?r/12.92:((r+.055)/1.055)**2.4;t[n]=Math.max(0,Math.min(255,Math.round(i*255)))}Bs[e]=t}return Bs[e]}var Hs=class{constructor(){this.canvasContextPairs=[],this.maxPoolSize=Qt.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=[]}},Us=class{constructor(e={}){this.pools=new Map,this.memoryUsage=0,this.maxMemoryUsage=e.maxMemory||Ns.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*Ns.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<Qt.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`}},Ws=class{constructor(e=Qt.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=[]}},Gs=class{constructor(e={}){this.useWorkers=typeof Worker<`u`,this.maxConcurrentWorkers=Qt.MAX_CONCURRENT_WORKERS,this.activeWorkers=0,this._issues=e.issues??null,this.maxTextureSize=this._clampTextureSize(e.maxTextureSize??Qt.DEFAULT_MAX_TEXTURE_SIZE),this.canvasPool=new Hs,this.bufferPool=new Us({maxMemory:e.maxBufferMemory||Ns.MAX_BUFFER_MEMORY,sizeStrategy:e.bufferSizeStrategy||`adaptive`}),this.textureCache=new Ws,this.capabilities=this.detectCapabilities(),this.optimalMethod=this.selectOptimalMethod()}_reportTextureFailure(e,t){if(t instanceof nn)throw t;this._issues?.record(X.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(X.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)||Qt.DEFAULT_MAX_TEXTURE_SIZE);return Math.max(Qt.MIN_TEXTURE_WIDTH,Math.min(t,Qt.MAX_TEXTURE_SIZE))}setMaxTextureSize(e){let t=this._clampTextureSize(e);return t===this.maxTextureSize?t:(this.maxTextureSize=t,this.textureCache?.dispose(),this.textureCache=new Ws,this.maxTextureSize)}detectCapabilities(){return{offscreenCanvas:typeof OffscreenCanvas<`u`,imageBitmap:typeof createImageBitmap<`u`,workers:typeof Worker<`u`,hardwareConcurrency:Or()}}selectOptimalMethod(){return this.capabilities.workers&&this.capabilities.offscreenCanvas?`worker-offscreen`:this.capabilities.imageBitmap?`imageBitmap`:`canvas`}_applyColorManagement(e,t,n,i=new Set){let a=$r();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){Ms.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(X.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(X.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,Ms.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=Vs(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?Ms.info(`re-encoded ${l.length}/${o.length} linear-declared colour map(s) to sRGB so the GPU decode round-trips: ${u}`):Ms.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=$r()?.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 nn)throw n;this._issues?.warn(X.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>Ns.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 Ao;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)<Ls)return 0;let t=this.maxConcurrentWorkers-this.activeWorkers;return Math.max(0,Math.min(e.length,Is,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=Mr(Ao);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=Mr(Ao);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>=Ns.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>Fs&&(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=e?.isCompressedTexture?r?.data:qs(e);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=Ar()&&i*t.length>=Ps?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)=>Po(e,o,t*i,n,r)),this.createDataArrayTextureFromBuffer(o,n,r,t.length)}async _packInWorker(e,t,n){let r=await zs(),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=Mr(No),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(X.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%Ns.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++)Ht(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=Qt.VEC4_PER_BVH_NODE*Qt.FLOATS_PER_VEC4;yt(t.length,`BVH node count`);let i=t.length*r,a=new Float32Array(i),o=G(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]=Tt.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 Ws;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:Ut(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:Ks(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);let r=qs(n);i.push({index:e,flipY:n.flipY,promise:r?Ks(r,n.image.width,n.image.height):Promise.reject(Error(`pixels in a layout the texture arrays cannot take`))});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()}};async function Ks(e,t,n){let r=new Uint8ClampedArray(e.buffer,e.byteOffset,e.byteLength);return createImageBitmap(new ImageData(r,t,n))}function qs(e){let t=e?.image,n=t?.data;if(!n||!(t.width>0)||!(t.height>0))return null;let i=t.width*t.height;if(n instanceof Uint8Array||n instanceof Uint8ClampedArray)return n.byteLength>=i*4?new Uint8Array(n.buffer,n.byteOffset,i*4):null;let a={[r.RGBAFormat]:4,[r.RGFormat]:2,[r.RedFormat]:1}[e.format]??Math.round(n.length/i);if(!(a>=1&&a<=4)||n.length<i*a)return null;let o=e.type===r.HalfFloatType,s=e.type===r.UnsignedShortType?1/65535:1,c=new Uint8Array(i*4);for(let e=0;e<i;e++)for(let t=0;t<4;t++){let i=t<a?n[e*a+t]:null,l=i===null?t===3?1:c[e*4]/255:o?r.DataUtils.fromHalfFloat(i):i*s;c[e*4+t]=Math.max(0,Math.min(255,Math.round(l*255)))}return c}var Js=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=Xs(E,Ys(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=Xs(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 Ys(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 Xs(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)}}Ft(),Ae(),tr();var Zs=Object.freeze({r:0,g:0,b:0});function Qs(e){if(!e)return Zs;if(!Yn())return e;let t=[e.r,e.g,e.b];return Zn(t),{r:t[0],g:t[1],b:t[2]}}var $s=ve(`emissive`),ec=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]&bt,h=n[p+o],g=t[m];if(!g)continue;let _=d.get(g);_===void 0&&(_=Qs(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.matrixRow(t):0,a=n?r.rowArray:null,o=(e,t,n)=>a?a[i]*e+a[i+4]*t+a[i+8]*n+a[i+12]:e,s=(e,t,n)=>a?a[i+1]*e+a[i+5]*t+a[i+9]*n+a[i+13]:t,c=(e,t,n)=>a?a[i+2]*e+a[i+6]*t+a[i+10]*n+a[i+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),z=Math.max(E,k,M),ue=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:z,bMaxZ:ue,nx:I,ny:L,nz:ee,twoSided:ne}),this.totalEmissivePower+=F}}return this.emissiveCount=this.emissiveTriangles.length,this.emissiveCount>0&&$s.debug(`${V.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;this.totalEmissivePower=0;for(let e of this.emissiveTriangles){let o=n?r.chunkFor(e.triangleIndex):i,s=n?n.baseOf(e.triangleIndex):e.triangleIndex*a,c=[o[s],o[s+1],o[s+2],o[s+4],o[s+5],o[s+6],o[s+8],o[s+9],o[s+10]],l=t.placementRunOf?.(e.meshIndex)?.start??-1;if(l>=0&&t.isSet[l]){let e=t.matrixRow(l),n=t.rowArray;for(let t=0;t<9;t+=3){let r=c[t],i=c[t+1],a=c[t+2];c[t]=n[e]*r+n[e+4]*i+n[e+8]*a+n[e+12],c[t+1]=n[e+1]*r+n[e+5]*i+n[e+9]*a+n[e+13],c[t+2]=n[e+2]*r+n[e+6]*i+n[e+10]*a+n[e+14]}}let[u,d,f,p,m,h,g,_,v]=c,y=this._calculateTriangleArea(u,d,f,p,m,h,g,_,v),b=e.emissive;e.power=(.2126*b.r+.7152*b.g+.0722*b.b)*e.emissiveIntensity*y,e.area=y;let x=(m-d)*(v-f)-(h-f)*(_-d),S=(h-f)*(g-u)-(p-u)*(v-f),C=(p-u)*(_-d)-(m-d)*(g-u),w=(Math.sqrt(x*x+S*S+C*C)||1)/e.sideSign;e.nx=x/w,e.ny=S/w,e.nz=C/w,e.cx=(u+p+g)/3,e.cy=(d+m+_)/3,e.cz=(f+h+v)/3,e.bMinX=Math.min(u,p,g),e.bMinY=Math.min(d,m,_),e.bMinZ=Math.min(f,h,v),e.bMaxX=Math.max(u,p,g),e.bMaxY=Math.max(d,m,_),e.bMaxZ=Math.max(f,h,v),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,$s.debug(`emissive texture ${V.px(t,n)} · ${V.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 $s.debug(`emissive raw data ${V.n(this.emissiveCount)} entries (${V.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=Qs(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(4).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 Js().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,$s.debug(`rebuilt sorted emissive data · ${V.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 tc=class{constructor(e=`Build`,{namespace:t=`build`,level:n=`debug`}={}){this.label=e,this.level=n,this.logger=ve(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=V.list([this.label,...e,V.ms(t)]);return this.level===`info`?this.logger.summary(r,n):this.logger.debug(V.list([r,n.join(` · `)])),{steps:Object.fromEntries(this.order.map(e=>[e,Math.round(this.entries.get(e)?.duration??0)])),total:Math.round(t)}}};hn();var nc=1<<20,rc=1<<21,ic=()=>new Promise(e=>setTimeout(e,0)),ac=[0,1,2,4,5,6,8,9,10];function oc(e,t,n,r=ac){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 sc(e,t){let n=[],r=0;for(let{triOffset:i,triCount:a}of t)n.push(oc(e,i,a)),r+=a,r>=rc&&(r=0,await ic());return n}async function cc(e,t){let n=await e?.area(mn.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 lc(e,t,{index:n,bvh:r,orders:i,isStale:a,label:o=``}){let s=e?.area(mn.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,nc),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+=nc*4)await u.write(`order.u32`,e.subarray(t,Math.min(e.length,t+nc*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 uc(e,t,n,r){for(let i=0;i<r;i+=nc){let a=Math.min(nc,r-i),o=await e.slice(i*64,(i+a)*64).arrayBuffer();t.setRecords(n+i,new Float32Array(o))}}async function dc(e,t,n){return new Uint32Array(await e.slice(t*4,(t+n)*4).arrayBuffer())}Ft();var fc=16,pc=K.POSITION_A_OFFSET,mc=K.POSITION_B_OFFSET,hc=K.POSITION_C_OFFSET;async function gc(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+pc]+o[n+mc]+o[n+hc],c[r]=o[n+pc+1]+o[n+mc+1]+o[n+hc+1],l[r]=o[n+pc+2]+o[n+mc+2]+o[n+hc+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 vc(u,o,_c(o,e,t),e,t,n),{left:f(e,n),right:f(n,t)}},p=f(0,n);return await i?.(),await yc(e,t,n,u,i),{order:u,pieces:d,tree:p}}function _c(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 vc(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 yc(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 bc(e,t,n,r){let i=t.length-1,a=[],o=i;for(let{bvhData:e}of n)a.push(o),o+=e.length/fc;let s=new Float32Array(i*fc),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];Ui(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*fc;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 xc,Sc=g((()=>{xc=`11.11.0`})),Cc,wc=g((()=>{Sc(),Cc=xc}));function Tc(e,t,n=Ec){return e>=n&&t/Dc<e/3}var Ec,Dc,Oc=g((()=>{Ec=1e4,Dc=15e5}));wc(),Oc();var kc="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,CLUSTER_LEAF:1073741827},r=new Float32Array(1),i=new Uint32Array(r.buffer);function a(e){let t=Math.fround(e);return t<=e?t:(r[0]=t,i[0]+=t>0?-1:1,r[0])}function o(e,t){return Math.max(Math.abs(e),Math.abs(t),1e-30)*2**-21}const s=[2,4,5];function c(e,t,n,r,i,c,u){let d=0;for(let f=0;f<3;f++){let p=1/0,m=-1/0;for(let e=0;e<i;e++)p=Math.min(p,r[e*6+f]),m=Math.max(m,r[e*6+3+f]);if(c&&(c[u+f]=p,c[u+3+f]=m),!(p<=m)){e[n+s[f]]=l,t[n+6+f]=0,t[n+9+f]=0;continue}let h=o(p,m),g=a(p-h),_=Math.max(-126,Math.ceil(Math.log2((m+h-g)/255)));for(;Math.fround(g+255*2**_)<m+h;)_++;let v=2**_;e[n+s[f]]=g,d|=_+127<<f*8;let y=0,b=0;for(let e=0;e<i;e++){let t=r[e*6+f],n=r[e*6+3+f],i=o(t,n);y|=Math.max(0,Math.min(255,Math.floor((t-i-g)/v)))<<e*8,b|=Math.max(0,Math.min(255,Math.ceil((n+i-g)/v)))<<e*8}t[n+6+f]=y>>>0,t[n+9+f]=b>>>0}t[n+1]=d>>>0}const l=1e30;n.TRIANGLE_LEAF;const u=e=>e>=2147483648,d=e=>~e>>>0>>>4,f=e=>~e&15,p=e.FLOATS_PER_TRIANGLE,m=e=>e instanceof Float32Array?e:new Float32Array(e.buffer,e.byteOffset,e.length),h=e=>e instanceof Uint32Array?e:new Uint32Array(e.buffer,e.byteOffset,e.length),g=e=>{let t=e&&e.chunks?e:null;return{chunked:t,f:e,idx:t?e.viewAs(Uint32Array):h(e)}},_=(e,t)=>e.chunked?e.f.chunkFor(t):e.f,v=(e,t)=>e.chunked?e.idx.chunkFor(t):e.idx,y=(e,t)=>e.chunked?e.chunked.baseOf(t):t*x,b=e=>{let t=e&&e.chunks?e:null;return{chunked:t,f:t?t.viewAs(Float32Array):m(e),u:t?e:h(e)}},x=16,S=n.TRIANGLE_LEAF,C=n.BLAS_POINTER_LEAF,w=n.CLUSTER_LEAF;function T(e,t,n,r,i,a){if(n[r]>n[r+3]){for(let e=0;e<6;e++)i[a+e]=n[r+e];return}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 E(t,n,r,i,a){let o=e.POSITION_A_OFFSET,s=e.POSITION_B_OFFSET,c=e.POSITION_C_OFFSET,l=1/0,u=1/0,d=1/0,f=-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*p;l=Math.min(l,i[a+o],i[a+s],i[a+c]),u=Math.min(u,i[a+o+1],i[a+s+1],i[a+c+1]),d=Math.min(d,i[a+o+2],i[a+s+2],i[a+c+2]),f=Math.max(f,i[a+o],i[a+s],i[a+c]),m=Math.max(m,i[a+o+1],i[a+s+1],i[a+c+1]),h=Math.max(h,i[a+o+2],i[a+s+2],i[a+c+2])}i[a]=l,i[a+1]=u,i[a+2]=d,i[a+3]=f,i[a+4]=m,i[a+5]=h}const D=new Float32Array(12),O=(e,t)=>e[t]>=l*.5;function k(e,t,n,r){let i=n[r]>n[r+3];e[t]=i?l:n[r],e[t+1]=i?l:n[r+1],e[t+2]=i?l:n[r+2],e[t+4]=i?l:n[r+3],e[t+5]=i?l:n[r+4],e[t+6]=i?l:n[r+5]}function A(e,t,n,r){let i=_(e,t),a=v(e,t),o=y(e,t);if(a[o+3]===S){E(n,a[o],a[o+1],r,0);return}let s=!O(i,o),c=!O(i,o+8);for(let e=0;e<3;e++)r[e]=Math.min(s?i[o+e]:1/0,c?i[o+8+e]:1/0),r[3+e]=Math.max(s?i[o+4+e]:-1/0,c?i[o+12+e]:-1/0)}const j=new Float32Array(16),M=new Float32Array(6),N=new Float32Array(24);function P(e,t,n,r,i,a){let o=_(e,t),s=v(e,t),l=y(e,t),u=s[l]&268435455,d=(s[l]>>>28&3)+1;for(let t=0;t<d;t++){let i=s[l+12+t];if(A(e,i&1073741823,n,M),i&1073741824){for(let e=0;e<6;e++)N[t*6+e]=M[e];continue}let a=r*16+(u+t)*3*4;for(let t=0;t<12;t++){let n=a+t>>4;j[4+t]=_(e,n)[y(e,n)+(a+t&15)]}T(j,0,M,0,N,t*6)}c(o,s,l,N,d,i,a)}function F(e,t,n,r,i,a=-1){let o=_(e,t),s=v(e,t),c=y(e,t),l=(t-i)*6,p=s[c+3];if(p===S){E(n,s[c],s[c+1],r,l);return}if(p===w){P(e,t,n,a,r,l);return}if(p===C){T(o,c,r,(s[c]-i)*6,r,l);return}let m=s[c+7],h=r,g=(p-i)*6;u(p)&&(E(n,d(p),f(p),D,0),h=D,g=0);let b=r,x=(m-i)*6;u(m)&&(E(n,d(m),f(m),D,6),b=D,x=6),k(o,c,h,g),k(o,c+8,b,x);for(let e=0;e<3;e++)r[l+e]=Math.min(h[g+e],b[x+e]),r[l+3+e]=Math.max(h[g+3+e],b[x+3+e])}var I=class{constructor(){this._bounds=null,this._boundsNodeCount=0,this._tlasBounds=null,this._rootBox=null}updateTrianglePositions(n,r,i){let a=i.length,o=b(n);for(let n=0;n<a;n++){let a=i[n],s=o.chunked?o.f.chunkFor(n):o.f,c=o.chunked?o.u.chunkFor(n):o.u,l=o.chunked?o.chunked.baseOf(n):n*p,u=a*9,d=r[u],f=r[u+1],m=r[u+2],h=r[u+3],g=r[u+4],_=r[u+5],v=r[u+6],y=r[u+7],b=r[u+8];s[l+e.POSITION_A_OFFSET]=d,s[l+e.POSITION_A_OFFSET+1]=f,s[l+e.POSITION_A_OFFSET+2]=m,s[l+e.POSITION_B_OFFSET]=h,s[l+e.POSITION_B_OFFSET+1]=g,s[l+e.POSITION_B_OFFSET+2]=_,s[l+e.POSITION_C_OFFSET]=v,s[l+e.POSITION_C_OFFSET+1]=y,s[l+e.POSITION_C_OFFSET+2]=b;let x=h-d,S=g-f,C=_-m,w=v-d,T=y-f,E=b-m,D=t(S*E-C*T,C*w-x*E,x*T-S*w);c[l+e.NORMAL_A_PACKED_OFFSET]=D,c[l+e.NORMAL_B_PACKED_OFFSET]=D,c[l+e.NORMAL_C_PACKED_OFFSET]=D}}refitRange(e,t,n,r){let i=b(t);r>this._boundsNodeCount&&(this._bounds=new Float32Array(r*6),this._boundsNodeCount=r);let a=g(e);for(let e=n+r-1;e>=n;e--)F(a,e,i,this._bounds,n)}refitPartial(e,t,n,r,i=null,a=-1){for(let r=0;r<n.length;r+=2)this.refitRange(e,t,n[r],n[r+1]);let o=b(t),s=g(e);i&&this.refitGroups(s,o,i[0],i[1]),(!this._tlasBounds||this._tlasBounds.length<r*6)&&(this._tlasBounds=new Float32Array(r*6));let c=this._tlasBounds;for(let e=r-1;e>=0;e--){let t=v(s,e),n=y(s,e);t[n+3]===C?(A(s,t[n],o,M),T(_(s,e),n,M,0,c,e*6)):F(s,e,o,c,0,a)}}refitGroups(e,t,n,r){let i=this._groupBox||=new Float32Array(6);for(let a=n+r-1;a>=n;a--){let n=_(e,a),r=v(e,a),o=y(e,a);r[o+3]!==S&&(A(e,r[o+3],t,i),k(n,o,i,0),A(e,r[o+7],t,i),k(n,o+8,i,0))}}refit(e,t,n,r=-1){let i=b(t);n!==this._boundsNodeCount&&(this._bounds=new Float32Array(n*6),this._boundsNodeCount=n);let a=g(e);for(let e=n-1;e>=0;e--)F(a,e,i,this._bounds,0,r)}};const L=64*1024*1024;function R(e,t,n){return n?new e(new SharedArrayBuffer(t*e.BYTES_PER_ELEMENT)):new e(t)}var z=class e{constructor(e,t,n,r=L,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(R(n,e*t,i)),s-=e}this.chunks.length===0&&this.chunks.push(R(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=L,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]=R(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=R(this.LaneType,t,this.shared),r=new Uint8Array(n.buffer,n.byteOffset,n.byteLength);this._store.readInto?await this._store.readInto(e,r):r.set(new Uint8Array(await this._store.read(e,r.byteLength))),this.chunks[e]=n;for(let t of this._liveViews())t.chunks[e]=new t.LaneType(n.buffer,n.byteOffset,n.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=R(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 B=new I;let V=null,H=null,U=0;self.onmessage=function(e){let{type:t}=e.data;if(t===`init`){V=z.adopt(e.data.sharedBvhBufs.map(e=>new Float32Array(e)),e.data.bvhRecordCount,16,e.data.bvhRecordsPerChunk),H=z.adopt(e.data.sharedTriBufs.map(e=>new Uint32Array(e)),e.data.triRecordCount,e.data.triLanesPerRecord,e.data.triRecordsPerChunk),U=V.recordCount;return}if(t===`refit`)try{let t=performance.now(),{blasRanges:n,tlasNodeCount:r,groupRange:i,treeNodeCount:a,recordNodeStart:o=-1}=e.data;n?B.refitPartial(V,H,n,r,i,o):B.refit(V,H,a??U,o),self.postMessage({type:`refitComplete`,refitTimeMs:performance.now()-t})}catch(e){console.error(`[BVHRefitWorker] Refit error:`,e),self.postMessage({type:`error`,error:e.message})}};",Ac=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,kc],{type:`text/javascript;charset=utf-8`});function jc(e){let t;try{if(t=Ac&&(self.URL||self.webkitURL).createObjectURL(Ac),!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(kc),{type:`module`,name:e?.name})}}var Mc="const e={TRIANGLE_LEAF:1073741824,BLAS_POINTER_LEAF:1073741825,FRONTIER:1073741826,CLUSTER_LEAF:1073741827};new Uint32Array(new Float32Array(1).buffer);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]);Object.freeze([]);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=e.clusterCount>0,n=t?e.clusterBounds:new Float64Array(e.entryCount*6);t||e.writeEntryWorldAABBs(n);let i=this.buildStructure(n,t?e.clusterCount:e.entryCount);return r.fillLeaves(i.data,i.nodeCount,e),i}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=t(n);if(a.clusterCount>0){for(let t=0;t<i;t++){let r=t*16;o[r+3]===e.BLAS_POINTER_LEAF&&a.writeClusterLeaf(n,o,r,o[r+1],a.clusterWorld,t)}return}for(let t=0;t<i;t++){let i=t*16;if(o[i+3]!==e.BLAS_POINTER_LEAF)continue;let s=o[i+1]&1073741823;o[i]=a.entryRoot(s),n[i+2]=+!!a.entryVisible(s),r.writeLeafMatrix(n,o,i,a,a.repOf(s),s),a.setLeafOf(s,t)}}static writeLeafMatrix(e,t,n,r,i,s=i){let l=c,u=r.matrixRow(i),d=r.rowArray;a(d,u,l),e[n+4]=l[0],e[n+5]=l[4],e[n+6]=l[8],e[n+7]=l[12],e[n+8]=l[1],e[n+9]=l[5],e[n+10]=l[9],e[n+11]=l[13],e[n+12]=l[2],e[n+13]=l[6],e[n+14]=l[10],e[n+15]=l[14],t[n+1]=(s|(o(d,u)?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})}};",Nc=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,Mc],{type:`text/javascript;charset=utf-8`});function Pc(e){let t;try{if(t=Nc&&(self.URL||self.webkitURL).createObjectURL(Nc),!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(Mc),{type:`module`,name:e?.name})}}fn(),qn(),Ae(),Ft(),en(),an(),ii(),yn(),On(),ui(),Fr();var Fc=5e4,Ic=2e5,Lc=2e6,Rc=1<<19,zc=4e7,Bc=1e6,Vc=1024**3,Hc=1024**3,Uc=32*1024*1024,Wc=64*1024*1024,Gc=256*1024*1024,Kc=ve(`scene`),qc=Object.freeze([`maps`,`normalMaps`,`bumpMaps`,`roughnessMaps`,`metalnessMaps`,`emissiveMaps`,`displacementMaps`,`anisotropyMaps`,`transmissionMaps`,`clearcoatMaps`,`clearcoatRoughnessMaps`,`clearcoatNormalMaps`,`sheenColorMaps`,`sheenRoughnessMaps`,`iridescenceMaps`,`iridescenceThicknessMaps`,`specularIntensityMaps`,`specularColorMaps`,`diffuseTransmissionMaps`,`diffuseTransmissionColorMaps`]),Jc=e=>Array.isArray(e)?e:[e],Yc=e=>Jc(e).reduce((e,t)=>e+t.byteLength,0),Xc=64*1024*1024;async function Zc(e,t,n){for(let r of Jc(n))await e.writeAt(t,r),t+=r.byteLength}function Qc(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 $c=1024,el=64;function tl(e){let t=Int32Array.from(e).sort(),n=[],r=t[0],i=r;for(let e=1;e<=t.length;e++){if(e<t.length&&t[e]-i<=$c){i=t[e];continue}n.push({offset:r*16,count:(i-r+1)*16}),r=i=t[e]}return n.length>el?[{offset:t[0]*16,count:(t.at(-1)-t[0]+1)*16}]:n}var nl=class{constructor(e={}){this.config={useWorkers:!0,bvhDepth:30,maxLeafSize:4,verbose:!1,useFloat32Array:!0,textureQuality:`adaptive`,maxTextureSize:Qt.DEFAULT_MAX_TEXTURE_SIZE,enableTextureCache:!0,maxConcurrentTextureTasks:Math.min(Or(),6),maxSceneBytes:bo,sceneCache:!0,sceneCacheMinBuildMs:Ec,...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.clearcoatNormalMaps=[],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 Eo,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 Kn({issues:this.config.issues}),this.bvhBuilder=new Qi,this.bvhBuilder.maxLeafSize=this.config.maxLeafSize,this.textureCreator=new Gs({maxTextureSize:this.config.maxTextureSize,issues:this.config.issues}),this.emissiveTriangleBuilder=new ec,this.tlasBuilder=new so,this._tlasWorker=null,this._tlasWorkerFailed=!1}_log(e,t){t===void 0?Kc.debug(e):Kc.debug(e,t)}needsSpill(e){return lo(this.geometryExtractor.surveyScene(e)).total>yo}get spilling(){return!!this._progressive&&(this.triangles?.chunks?.length??0)>1}_preflightMemory(e){let t=this.config.maxSceneBytes??9663676416,n=this.geometryExtractor.surveyScene(e),r=lo(n);if(this._streaming){let t=Vc+Qc(e)*(K.FLOATS_PER_TRIANGLE*4+44);r.total=uo(r,n.placements,Math.min(r.triangles,t))}else this._progressive&&(r.total-=r.bvh);let i={...n,estimate:r,safeBytes:yo,maxBytes:t,fits:r.total<=yo};if(this.memoryPreflight=i,r.total<1610612736)return i;if(Kc.debug(V.list([`memory preflight: ${V.mb(r.total)} estimated`,`triangles ${V.mb(r.triangles)} · bvh ${V.mb(r.bvh)} · geometry ${V.mb(r.geometry)}`,`${V.n(n.triangles)} tris · ${V.n(n.placements)} placements`])),r.total>t){let e=`Scene needs about ${V.mb(r.total)} of CPU memory, past the ${V.mb(t)} a browser tab can hold — loading it would crash the tab rather than fail. Reduce the scene (it has ${V.n(n.triangles)} triangles), or raise maxSceneBytes to try anyway.`;throw this.config.issues?.record(X.SCENE_MEMORY_BUDGET,e,{...n,estimate:r,maxBytes:t}),Error(e)}return i.fits||this.config.issues?.warn(X.SCENE_MEMORY_BUDGET,`Scene needs about ${V.mb(r.total)} of CPU memory, above the ${V.mb(yo)} 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:yo}),i}_checkAssemblyHeadroom(e){let t=e*64;if(t<1610612736)return!0;let n=fo(Math.ceil(t*wo),{shared:ln});return this.memoryPreflight&&(this.memoryPreflight.assemblyProbed=n.placed),n.exhausted&&this.config.issues?.warn(X.SCENE_MEMORY_BUDGET,`BVH assembly needs ${V.mb(t)} but only ${V.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?.matrixBytes??0,blasScratch:0,orderMaps:0};if(e){for(let n of e.blasData.values())t.blasScratch+=n?Yc(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;if(!this.bvh.isResident(0,1))return this._spilledRootBounds??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} ${V.mb(n[e].allocated)}`),i=this.memoryPreflight?.estimate?.total;Kc.debug(V.list([`memory: peak live ${V.mb(t)}`,`allocated ${V.mb(e)}`,i?`predicted ${V.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,on(e=>this.memory.alloc(e));let r=new tc(e.name??``,{namespace:`scene`});try{this._geometryOwner===e&&await Promise.all([this._restoreGeometry(e),this.ensureMovable()]),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>zc,this.textureCoordinates=Rn(e),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=Mn(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`,this._streaming&&this._geometrySpill?.bytes>=Hc?this._geometryOwner=e: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=>Kc.debug(`storing BLASes failed:`,e))),this}catch(e){throw this.processingStage=`error`,Kc.error(`processing failed:`,e),z({status:`Error: ${e.message}`,failed:!0,progress:100}),e}finally{this._geometryOwner||this._disposeGeometrySpill(),on(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 Kc.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:`Large scene: building through disk to save memory...`,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=dn.lazy(o,K.FLOATS_PER_TRIANGLE,Uint32Array),c=s.recordsPerChunk*s.lanesPerRecord*4,l=await vn.create(r,`${a}:tri`,c,{label:`Triangle records`,expectedBytes:o*c/s.recordsPerChunk}),u=l&&await vn.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 Dn.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);Ka.rootAABB(Jc(r)[0],v,t.start,t.count,i,0),p.set(e,{result:n,aabb:i});let a=f.blasBytes;f.blasBytes+=Yc(r),f.blasAt.set(e,a),n.nodeCount=Yc(r)/64,n.bvhData=null,this._queueSpill(f,()=>Zc(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`,{textureCoordinates:this.textureCoordinates})},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>Gc&&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>Vc&&(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),Kc.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=yt(e.triangleCount,`triangle count`),this._foldLeaves&&this.triangleCount>134217728)throw RangeError(`${this.triangleCount.toLocaleString()} triangles is past the ${Nt.toLocaleString()} a folded BVH leaf can address`);this.expandedTriangleCount=e.expandedTriangleCount??e.triangleCount,this.instanceSource=e.instanceSource||null,this.matrixRuns=e.matrixRuns||null,this.instanceCount=e.instanceCount||0,this.instanceGroups=e.instanceGroups??[],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._adoptTextureLists(e),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.matrixRuns:null,o=e=>n?i[e]:e;this.instanceTable=new Ka,this.instanceTable.allocate(r,t.length,a,n?i:null),this.instanceTable.tplBakeInverse=this.bakeInverse,this.instanceTable.setGroups(n?this.instanceGroups:null);let s=this._clusterCopies(this.instanceTable);s&&this.instanceTable.planClusters();let c=s?this.instanceTable.clusterCount:this.instanceTable.entryCount,l=so.nodeCountFor(c)+this.instanceTable.groupNodeCount,u=this._streamed;this._streamed=null;let d=[],f=[],p=[],m=new Int32Array(r).fill(-1),h=new Map;for(let e=0;e<r;e++){let n=t[o(e)];if(!n||n.count===0)continue;let r=h.get(n.start);if(r!==void 0){m[e]=r;continue}h.set(n.start,e),u?p.push({m:e,range:n}):this._isLargeMesh(n)?f.push({m:e,range:n}):d.push({m:e,range:n})}let g=this._blasWorkerOpts(),_=d.length+f.length,v=0,y=()=>{v++,z({status:`Building BLAS ${v}/${_}...`,progress:25+Math.floor(v/_*45)})},b=[...d,...f].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),x=u?null:await this._restoreBLASes(b,l,g),S=u?u.state:!x&&this._progressive&&this.triangles.chunks.length>1?await this._beginProgressiveSpill(b):null,C=S&&!u?(e,t,n)=>this._onBLASBuilt(S,o(e),t,n):null;if(u)for(let[e,t]of u.templates)this.instanceTable.tplObjectAABB.set(t.aabb,e*6);x&&(d.length=0,f.length=0,z({status:`Restored stored BVHs`,progress:68}));let w=x?Promise.resolve(x.results):u?Promise.resolve(p.map(({m:e,range:t})=>({m:e,range:t,result:u.templates.get(o(e)).result}))):this._buildBLASesWithPool(d,g,y,C),T=[],E=(async()=>{for(let{m:e,range:t}of f){let n=await this._buildLargeBLAS(t,g);C?.(e,t,n),T.push({m:e,range:t,result:n}),y()}})(),[D]=await Promise.all([w,E]);if(S&&(await S.chain,S.error))throw S.error;let O={sah:0,objMed:0,spatMed:0,failed:0};for(let{m:e,range:t,result:r}of[...D,...T]){let i=r.splitStats;i&&(O.sah+=i.sahSplits??0,O.objMed+=i.objectMedianSplits??0,O.spatMed+=i.spatialMedianSplits??0,O.failed+=i.failedSplits??0,this.performanceMetrics.blasWorkerTime+=i.totalBuildTime??0),this.instanceTable.setEntry({meshIndex:e,blasNodeCount:r.nodeCount??Yc(r.bvhData)/64,triOffset:t.start,triCount:t.count,originalToBvhMap:r.originalToBvh||null,bvhData:r.bvhData,matrixWorld:n?za:this.meshes?.[e]?.matrixWorld?.elements??null,expandedStart:t.expandedStart,sourceMesh:o(e)})}for(let e=0;e<r;e++){let r=m[e];r<0||this.instanceTable.setAlias(e,r,n?za:this.meshes?.[e]?.matrixWorld?.elements??null,t[o(e)].expandedStart,o(e))}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 k=performance.now(),A=this.instanceTable;this.instanceTable.computeAABBs(this.triangles,{owners:!S}),this.instanceTable.computeGroupAABBs(),s&&(A.clusterWorld=new Float32Array(A.entryCount*6),A.writeEntryWorldAABBs(A.clusterWorld),A.clusterBounds=A.formClusters(A.clusterWorld)),this.instanceTable.assignOffsets(so.nodeCountFor(c));let j=this.instanceTable.totalNodeCount,M=await this._buildTLAS(A);if(this._streaming&&s){let e=A.clusterWorld;this._spillMeshBounds=this._instancedMeshBounds((t,n)=>{for(let r=0;r<6;r++)n[r]=e[t*6+r]})}A.clusterWorld=null,A.clusterBounds=null,this.performanceMetrics.tlasBuildTime=performance.now()-k,this.memory.mark(`assemble`);let N=performance.now();S||this._checkAssemblyHeadroom(j),this._setBVHData(dn.lazy(j,16,Float32Array,void 0,ln));let P=S?await this._beginBVHSpill(S,A.blasBase):null;this.bvh.setRecords(0,M),A.groupNodeCount&&this.bvh.setRecords(A.groupNodeStart,A.groupNodeBlock()),M=null,this.tlasBuilder.releaseFlattenBuffer();let F=Math.max(1,Math.ceil(A.templateCount/32));if(x){try{let e=performance.now();await uc(x.nodes,this.bvh,A.blasBase,A.totalBLASNodes),this.performanceMetrics.blasRestore.readMs=performance.now()-e}finally{x.release()}A.blasData.clear()}else{for(let e=0;e<A.templateCount;e++){let t=S?await this._readSpilledBLAS(S,e):A.blasData.get(e);if(!t)continue;let n=A.tplBlasOffset[e],r=n;for(let e of Jc(t))this.bvh.setRecords(r,e),r+=e.length/16;this._offsetBLASInPlace(n,r-n,n,A.tplTriOffset[e]),A.blasData.delete(e),await P?.(r),e%F===0&&this._sampleMemory(`assembling ${e}/${A.templateCount}`)}s&&await this._writeCopyRecords(P),await P?.(j,!0),S&&await S.blasStore.dispose()}if(s&&x&&await this._writeCopyRecords(null),this._setBVHData(this.bvh.materializeAll()),x)for(let[e,t]of x.orders)A.bvhToOriginal.set(e,t);else this._buildBvhToOriginalMaps();this.performanceMetrics.bvhAssembleTime=performance.now()-N,A.originalToBvhMap.clear(),A.blasData.clear(),this.bvhRoot=!0,this._disposeRefitWorker();let I=performance.now()-e;Kc.debug(V.list([`${V.n(A.setCount)} BLASes + TLAS`,`${V.n(this.bvh.recordCount)} nodes`,`SAH ${V.n(O.sah)} · objMed ${O.objMed} · spatMed ${O.spatMed} · failed ${O.failed}`,V.ms(I)])),z({status:`BVH construction complete`,progress:75})}catch(e){throw Kc.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>=Ic&&La(e.count)}async _buildLargeBLAS(e,t){if(e.count>Lc)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 Pa(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 gc(n,e.start,e.count,Rc,{pause:()=>new Promise(e=>setTimeout(e,0))}),o=this._blasPool(t,null,null,Math.min(Or(),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),Ka.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{...bc(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:${Cc}:${JSON.stringify(t)}:${n}:${this._sceneKey}`}async _restoreBLASes(e,t,n){if(!this._sceneKey||this.config.sceneCache===!1)return null;let r=ni(si().cacheNamespace);if(!r)return null;this._blasKey=this._blasCacheKey(n);let i=await cc(r,this._blasKey);if(!i)return null;let a=e=>(Kc.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 sc(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 dc(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},Kc.debug(`restored ${V.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=ni(si().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 sc(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 lc(t,r,{index:{v:2,tlasNodeCount:n.blasBase,totalNodes:n.treeNodeCount,templates:d},bvh:this.bvh,orders:u,isStale:a,label:e});return f&&Kc.debug(`stored ${V.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 vn.create(t,`${i}:tri`,a,{label:`Triangle records`,expectedBytes:r.byteLength}),s=o&&await vn.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`,{textureCoordinates:this.textureCoordinates}),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(Jc(a)[0],t,this.triangles,i.tplObjectAABB,t*6);let o=e.blasBytes;e.blasBytes+=Yc(a),e.blasAt.set(t,o),r.nodeCount=Yc(a)/64,r.bvhData=null,this._queueSpill(e,()=>Zc(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;await 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+=Xc)i.push(new Float32Array(await e.blasStore.readAt(n+t,Math.min(Xc,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 vn.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),this._bvhSpillStore=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),await 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),await 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);Ui(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=Mr(Ea);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 Kc.error(`texture creation failed:`,e),e}}_bucketTextures(){let e=this.config.maxTextureSize,t=Qt.MATERIAL_BUCKET_COUNT,n=Qt.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.clearcoatNormalMaps,this.sheenRoughnessMaps,this.iridescenceMaps,this.iridescenceThicknessMaps,this.specularIntensityMaps,this.diffuseTransmissionMaps],o=Y(r(i),e,t),s=Y(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(X.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=Xt(e.image.width,e.image.height,a),s=e.source?.uuid??e.uuid,c=r[o].get(s);if(c!==void 0)return Zt(o,c);if(t[o].length>=n)return Kc.warn(`texture bucket ${o} full (${n}); dropping a map`),f||this.config.issues?.record(X.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=Zt(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),clearcoatNormal:h(this.clearcoatNormalMaps,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.clearcoatNormalMap=t(n.clearcoatNormalMap,e.clearcoatNormal),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._disposeMatrixSpill(),this._orderSpill?.store.dispose().catch(()=>{}),this._orderSpill=null,this._spilledAfterLoad=!1,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.clearcoatNormalMaps=[],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){Kc.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._adoptTextureLists(n),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 Kc.error(`material rebuild failed:`,e),e}finally{this.isProcessing=!1}}_adoptTextureLists(e){for(let t of qc)this[t]=e[t]??[]}_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=dn.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.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||=Mr(jc),!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=[],l=0;for(let e=0;e<i.count;e++){if(!i.isSet[e]||!i.isOwner(e))continue;l++;let t=n(e);if(!t)continue;if(this._updateMeshTrianglePositions(e,t),s.push(i.blasOffsetOf(e),i.blasNodeCountOf(e)),c.push(e),r){let t=r(e);t&&this._patchMeshSmoothNormals(e,t)}let u=i.triOffsetOf(e)*a,d=i.triCountOf(e)*a,f=o.at(-1);f&&f.offset+f.count===u?f.count+=d:o.push({offset:u,count:d})}let u=i.tlasNodeCount,d=u>0&&s.length/2<l,f=d?[this.computeTLASDirtyRange()]:null;for(let e=0;d&&e<s.length;e+=2)f.push({offset:s[e]*16,count:s[e+1]*16});return new Promise((e,t)=>{this._refitWorker.onmessage=n=>{let r=n.data;if(r.type===`refitComplete`){for(let e of c)i.recomputeAABB(e,this.bvh,this.triangles);i.computeGroupAABBs();let t=this._hiddenGroupLeaves();t.length&&this._refitTLAS(t),e({refitTimeMs:r.refitTimeMs,triRanges:o,bvhRanges:f})}else r.type===`error`&&t(Error(r.error))},this._refitWorker.postMessage({type:`refit`,blasRanges:d?s:null,tlasNodeCount:u,groupRange:i.groupNodeCount?[i.groupNodeStart,i.groupNodeCount]:null,treeNodeCount:i.treeNodeCount,recordNodeStart:i.clusterCount?i.recordNodeStart:-1})})}_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 Ca;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(X.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._writeGroupNodes(),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),i=[];for(let t of this._withGroupSiblings(e)){let e=this.meshes?.[t],a=n.placementRunOf(t);if(!e||!a)continue;e.updateMatrixWorld(!0);let o=e.matrixWorld.elements,s=e.isInstancedMesh?e.instanceMatrix?.array??null:null,c=n.tplBakeInverse?.get(n.sourceMesh[a.start])??null;for(let e=0;e<a.count;e++){let t=a.start+e;if(!n.isSet[t])continue;s?(Ha(o,s,e*16,r),n.setPlacementMatrix(t,r)):c?(Ha(o,c,0,r),n.setPlacementMatrix(t,r)):n.setPlacementMatrix(t,o),this._writeLeafMatrix(t);let l=n.leafOfPlacement(t);l>=0&&i.push(l)}}return this._refitTLAS(i),{refitTimeMs:performance.now()-t,placements:i.length}}_hiddenGroupLeaves(){let e=this.instanceTable,t=[];for(let n of e.groups)if(!n.members.every((t,r)=>e.visible[n.starts[r]]))for(let r=0;r<n.count;r++)t.push(e.leafOfPlacement(n.starts[0]+r));return t}_withGroupSiblings(e){let t=this.instanceTable;if(!t.groups.length)return e;let n=new Set(e),i=new Set,a=this._parentInverse??=new r.Matrix4;for(let r of e){let e=t.groupOfTemplate[r]??-1;if(e<0||i.has(e))continue;i.add(e);let o=this.meshes?.[r];if(o){o.updateMatrixWorld(!0);for(let r of t.groups[e].members){n.add(r);let e=this.meshes[r];!e||e===o||(e.parent&&e.parent.updateMatrixWorld(!0),e.matrix.copy(o.matrixWorld),e.parent&&e.matrix.premultiply(a.copy(e.parent.matrixWorld).invert()),e.matrix.decompose(e.position,e.quaternion,e.scale),e.updateMatrixWorld(!0))}}}return n}_writeLeafMatrix(e){let t=this.instanceTable,n=t.tlasLeafIndex[e];if(!(n<0)){if(t.clusterCount){this._writeCopyRecord(n,t.repOf(t.entryOf(e)));return}so.writeLeafMatrix(this.bvh.chunkFor(n),this.bvhIndexChunks.chunkFor(n),this.bvh.baseOf(n),t,e,t.entryOf(e))}}_writeCopyRecord(e,t){let n=this.instanceTable,r=this._recordScratch??=new Float32Array(12);n.writeRecord(r,0,t);let i=n.recordNodeStart*16+e*3*4;for(let e=0;e<12;e++){let t=i+e>>4;this.bvh.chunkFor(t)[this.bvh.baseOf(t)+(i+e&15)]=r[e]}let a=n.clusterLeaf[n.clusterOf(e)],o=this.bvhIndexChunks.chunkFor(a),s=this.bvh.baseOf(a)+n.copyWordSlot(e),c=Ua(n.matrixWorldOf(t));o[s]=(o[s]&~Ct|(c?Ct:0))>>>0;let l=this._movedRecords??=new Map,u=this.bvh.recordsPerChunk*16;for(let e=i,t=i+12;e<t;){let n=Math.floor(e/u),r=Math.min(t,(n+1)*u),i=l.get(n);i?(i.lo=Math.min(i.lo,e),i.hi=Math.max(i.hi,r)):l.set(n,{lo:e,hi:r}),e=r}}takeMoveRanges(){let e=this._tlasRanges??[this.computeTLASDirtyRange()];return this._tlasRanges=null,[...e,...this.takeMovedRecordRanges()]}takeMovedRecordRanges(){let e=this._movedRecords;return this._movedRecords=null,e?[...e.values()].map(e=>({offset:e.lo,count:e.hi-e.lo})):[]}_writeGroupNodes(){let e=this.instanceTable;!e?.groupNodeCount||!this.bvh||(e.computeGroupAABBs(),this.bvh.setRecords(e.groupNodeStart,e.groupNodeBlock()))}computeTLASDirtyRange(){return{offset:0,count:this.instanceTable.blasBase*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.blasBase*16}),{triRanges:n,bvhRanges:r}}async uploadChunks(e){for(let[t,n]of[[this.triangles,`triangles`],[this.bvh,`bvh`]]){if(!t?.chunks||t.chunks.length<2||t._gpuUpload)continue;let r=e(t,n,{textureCoordinates:this.textureCoordinates});for(let e=0;e<t.chunks.length;e++)t.chunks[e]&&await r(e)}}uploadToPathTracer(e,t,n,r,{keepUserLights:i=!1}={}){return this.triangles?(e.setTriangleData(this.triangles,this.triangleCount,{textureCoordinates:this.textureCoordinates}),this.bvh?(e.setBVHData(this.bvh),e.setInstanceTable(this.instanceTable),this.materialData?e.materialData.setMaterialData(this.materialData,this.materials.map(e=>e.sources)):Kc.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):(Kc.error(`failed to get BVH data`),!1)):(Kc.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||this._orderSpill)}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 vn.create(e,`${a}:tri`,o(t),{label:`Triangle records`,expectedBytes:t.byteLength}),c=s&&await vn.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?.blasBase??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 Kc.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?.(),await this._restoreOrderMaps(),this.spilled||this._disposeSpill()})().finally(()=>{this._paging=null}),this._paging}get geometryOnDisk(){return!!this._geometryOwner}ensureGeometryResident(){let e=this._geometryOwner?this._geometryReading??=this._restoreGeometry(this._geometryOwner).finally(()=>{this._geometryReading=null}):null;return Promise.all([e,this.ensureMovable()])}get matricesOnDisk(){return!!this._matrixSpill}async ensureMovable(e=[]){this._movePageIns=(this._movePageIns??0)+1;try{await this._afterLoadSpill;let t=this._matrixSpill;t&&await(this._matrixReading??=t.restore().then(()=>this._disposeMatrixSpill()).finally(()=>{this._matrixReading=null}));let n=this.instanceTable,r=this.bvh;if(!e.length||!n||!r?.spilledChunks)return;await r.ensureResident(0,n.blasBase);for(let t of this._recordChunksOf(e))await r.ensureResident(t*r.recordsPerChunk,1)}finally{this._movePageIns--}}async _spillMatrices(e=!1){let t=this.instanceTable,n=t?.adoptedMatrices()??[],i=this._spillMeshBounds;if(this._spillMeshBounds=null,!n.length||!this._progressive?.storage)return;let a=await Dn.create(this._progressive.storage,`spill:${Date.now().toString(36)}:${Math.random().toString(36).slice(2)}:mat`);if(!a)return;for(let[n,a]of i??this._instancedMeshBounds((e,n)=>t.writeEntryWorldAABB(e,n,0),e))n.boundingBox=new r.Box3(new r.Vector3(a[0],a[1],a[2]),new r.Vector3(a[3],a[4],a[5])),n.boundingSphere=n.boundingBox.getBoundingSphere(new r.Sphere);let o=n.reduce((e,t)=>e+t.array.byteLength,0);a.addAttributes(n),this._matrixSpill=a,Kc.info(`${V.mb(o)} of instance matrices left for disk`)}async _spillTLAS(){let e=this.instanceTable,t=this.bvh,n=this._bvhSpillStore;if(!n||!e?.clusterCount)return;let r=t.recordsPerChunk,i=e.groupNodeStart/r|0,a=(e.groupNodeStart+Math.max(1,e.groupNodeCount)-1)/r|0;this._spilledRootBounds=this.sceneBounds();let o=await t.spill(n,{keep:t=>e.groupNodeCount>0&&t>=i&&t<=a});Kc.info(`spilled ${V.mb(o)} of TLAS to disk`)}async _spillOrderMaps(){let e=this.instanceTable,t=this._progressive?.storage;if(!e?.bvhToOriginal.size||!t)return;let n=0;for(let t of e.bvhToOriginal.values())n+=t.byteLength;let r=await vn.create(t,`spill:${Date.now().toString(36)}:${Math.random().toString(36).slice(2)}:order`,0,{label:`Triangle order maps`,expectedBytes:n});if(!r)return;let i=[],a=new Uint8Array(Uc),o=0,s=0,c=async()=>{s&&await r.writeAt(o-s,a.subarray(0,s)),s=0};for(let[t,n]of e.bvhToOriginal){let e=new Uint8Array(n.buffer,n.byteOffset,n.byteLength);i.push(t,o,n.length),s+e.length>a.length&&await c(),e.length>a.length?await r.writeAt(o,e):(a.set(e,s),s+=e.length),o+=e.length}await c(),await r.flush(),e.bvhToOriginal.clear(),this._orderSpill={store:r,index:i,bytes:n}}async _restoreOrderMaps(){let e=this._orderSpill;if(!e)return;this._orderSpill=null;let{store:t,index:n,bytes:r}=e,i=this.instanceTable.bvhToOriginal,a=0,o=null;for(let e=0;e<n.length;e+=3){let s=n[e],c=n[e+1],l=n[e+2]*4;if(l>Wc){i.set(s,new Uint32Array(await t.readAt(c,l)));continue}(!o||c+l>a+o.byteLength)&&(a=c,o=await t.readAt(c,Math.min(Wc,r-c))),i.set(s,new Uint32Array(o.slice(c-a,c-a+l)))}await t.dispose()}spillAfterLoad(){return!this._geometryOwner||this._spilledAfterLoad?this._afterLoadSpill??Promise.resolve():(this._spilledAfterLoad=!0,this._spillUnused(!1))}respill(){return!this._geometryOwner||!this._spilledAfterLoad||this._afterLoadSpill?this._afterLoadSpill??Promise.resolve():this._matrixReading||this._tlasReading||this._movePageIns?Promise.resolve():this._spillUnused(!0)}_spillUnused(e){return this._afterLoadSpill=(async()=>{await this._spillMatrices(e),await this._spillTLAS(),await this._spillOrderMaps()})().finally(()=>{this._afterLoadSpill=null}),this._afterLoadSpill}whenTLASEditable(){if(this._afterLoadSpill)return this._afterLoadSpill.then(()=>this.whenTLASEditable());let e=this.bvh,t=this.instanceTable;return!e||!t||e.isResident(0,t.blasBase)?null:this._tlasReading??=e.ensureResident(0,t.blasBase).finally(()=>{this._tlasReading=null})}needsPageInForMove(e){if(this._matrixSpill||this._afterLoadSpill)return!0;let t=this.instanceTable,n=this.bvh;if(!t||!n?.spilledChunks)return!1;if(!n.isResident(0,t.blasBase))return!0;for(let t of this._recordChunksOf(e))if(!n.isResident(t*n.recordsPerChunk,1))return!0;return!1}_recordChunksOf(e){let t=this.instanceTable,n=this.bvh.recordsPerChunk,r=new Set;if(!t.clusterCount)return r;let i=new Set(e);for(let n of e){let e=t.groupOfTemplate?.[n]??-1;if(e>=0)for(let n of t.groups[e].members)i.add(n)}for(let e of i){let i=t.placementRunOf(e);if(i)for(let e=i.start;e<i.start+i.count;e++){let i=t.tlasLeafIndex[e];if(i<0)continue;let a=t.recordNodeStart*16+i*3*4;r.add(Math.floor(a/16/n)),r.add(Math.floor((a+11)/16/n))}}return r}_instancedMeshBounds(e,t=!1){let n=this.instanceTable,r=new Set(n.adoptedMatrices()),i=new Map,a=new Float64Array(6);return(this.meshes??[]).forEach((o,s)=>{if(!o?.isInstancedMesh||!r.has(o.instanceMatrix)||t&&o.boundingBox)return;let c=n.placementRunOf(s);if(!c)return;let l=[1/0,1/0,1/0,-1/0,-1/0,-1/0];for(let t=c.start;t<c.start+c.count;t++){e(n.entryOf(t),a);for(let e=0;e<3;e++)a[e]<l[e]&&(l[e]=a[e]),a[3+e]>l[3+e]&&(l[3+e]=a[3+e])}i.set(o,l)}),i}_disposeMatrixSpill(){let e=this._matrixSpill;this._matrixSpill=null,e?.dispose().catch(()=>{})}async _restoreGeometry(e){let t=this._geometrySpill;if(!t?.bytes){this._geometryOwner=null;return}this._geometryOwner||z({status:`Reading scene geometry back...`,progress:84});let n=performance.now(),r=t.bytes;await t.restore(),this._disposeGeometrySpill(),this._geometryBytes=Mn(e),Kc.info(`read ${V.mb(r)} of scene geometry back from disk in ${V.ms(performance.now()-n)}`),t.error&&Kc.warn(`some scene geometry stayed in memory, its spill write failed:`,t.error)}_disposeGeometrySpill(){let e=this._geometrySpill;this._geometrySpill=null,this._geometryOwner=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)}_clusterCopies(e){let t=this.config.clusterCopies??`auto`;return t===`auto`?e.entryCount>=Bc:t===!0}async _writeCopyRecords(e){let t=this.instanceTable,n=t.entryCount,r=4096,i=r*3/4,a=new Float32Array(i*16);for(let o=0;o<n;o+=r){let s=Math.min(r,n-o);a.fill(0);for(let e=0;e<s;e++)t.writeRecord(a,e*3*4,t.repOf(t.recordEntry[o+e]));let c=t.recordNodeStart+o*3/4,l=Math.ceil(s*3/4);this.bvh.setRecords(c,l===i?a:a.subarray(0,l*16)),await e?.(c+l)}}async _buildTLAS(e){let t=e.clusterCount>0,n=t?e.clusterCount:e.entryCount;if(n>=Fc&&!this._tlasWorkerFailed)try{let r=t?e.clusterBounds:new Float64Array(n*6);t||e.writeEntryWorldAABBs(r);let{tlasData:i,nodeCount:a}=await this._runTLASWorker(r,n);return so.fillLeaves(i,a,e),i}catch(e){this._tlasWorkerFailed=!0,Kc.warn(`TLAS worker unavailable (${e.message}); building on the main thread`)}return this.tlasBuilder.build(e).data}_runTLASWorker(e,t){this._tlasWorker||=Mr(Pc);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){let t=e?e instanceof dn?e:dn.adopt([e],e.length/16,16,e.length/16):null;this.bvh=t,t&&this._foldLeaves&&(t.foldedLeaves=!0),t&&this.instanceTable?.clusterCount&&(t.copyRecordBase=this.instanceTable.recordNodeStart*4),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 dn?e:dn.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=ht(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]]=ht(f,p,m)}}}_refitTLAS(e=null){let t=this.instanceTable,n=t.tlasNodeCount,r=e?Int32Array.from(e).sort():null;if(this._tlasRanges=r?[]:null,!n||r?.length===0)return;let i=r?Array.from(r):null,a=this._refitStack??=new Int32Array(256),o=0,s=0,c=this._refitBox??=new Float32Array(6),l=(e,t,n,r)=>{if(o+4>a.length){let e=new Int32Array(a.length*2);e.set(a),a=this._refitStack=e}a[o++]=e,a[o++]=t,a[o++]=n,a[o++]=r};for(l(0,n,-1,0);o;){let e=a[--o],n=a[--o],u=a[--o],d=a[--o],f=this.bvh.chunkFor(d),p=this.bvh.baseOf(d);if(e)c[0]=Math.min(f[p],f[p+8]),c[1]=Math.min(f[p+1],f[p+9]),c[2]=Math.min(f[p+2],f[p+10]),c[3]=Math.max(f[p+4],f[p+12]),c[4]=Math.max(f[p+5],f[p+13]),c[5]=Math.max(f[p+6],f[p+14]);else{if(r){for(;s<r.length&&r[s]<d;)s++;if(s===r.length||r[s]>=u)continue}let e=this.bvhIndexChunks.chunkFor(d),i=e[p+3];if(i===Tt.BLAS_POINTER_LEAF){let n=e[p+1]&wt;if(n>=t.entryCount)continue;t.writeEntryWorldAABB(n,c,0)}else if(i===Tt.CLUSTER_LEAF)t.encodeClusterBoxes(f,e,p,t.clusterOf(e[p]&Et),null,c,0);else if(i<Tt.TRIANGLE_LEAF){let t=e[p+7];l(d,u,n,1),l(t,u,d*2+1,0),l(i,t,d*2,0);continue}else continue}if(n<0)continue;let m=n>>1,h=this.bvh.chunkFor(m),g=this.bvh.baseOf(m)+(n&1)*8;h[g]=c[0],h[g+1]=c[1],h[g+2]=c[2],h[g+4]=c[3],h[g+5]=c[4],h[g+6]=c[5],i?.push(m)}i&&(this._tlasRanges=tl(i))}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){Kc.error(`background BLAS rebuild failed (mesh ${e}):`,o.error);return}n===this._rebuildGeneration&&this._swapBLAS(e,r,o,t)},i.onerror=t=>{Kc.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,foldLeaves:this._foldLeaves===!0,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,Mr(Ea))}}_swapBLAS(e,t,n,r){this._geometryVersion=(this._geometryVersion??0)+1;let i=n.bvhData,a=i.length/16;if(a>t.blasNodeCount){Kc.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}},rl=[[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]],il=[[-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]],al=[[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 ol(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=rl[i],o=il[i],s=al[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)]}tr();var sl=1/(4*Math.PI);function cl(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]=ol(t.temperature??6500);i[0]*=e,i[1]*=n,i[2]*=r}return Zn(i),{r:i[0],g:i[1],b:i[2],intensity:r}}var ll=e=>Math.max(0,Number(e.userData?.radius)||0),ul=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=cl(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=cl(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=cl(e);this.pointLightCache.push({data:[t.x,t.y,t.z,i.r,i.g,i.b,i.intensity*sl,e.distance||0,e.decay===void 0?2:e.decay,ll(e)],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=cl(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*sl,e.angle||Math.PI/4,e.penumbra||0,e.distance||0,e.decay===void 0?2:e.decay,o,c,u,d,ll(e),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}))}}},dl,fl,pl,ml,hl,gl,_l,vl,yl,bl,xl,Sl,Cl,wl,Tl,El,Dl=g((()=>{dl=x({origin:`vec3`,direction:`vec3`}),fl=x({color:`vec4`,emissive:`vec3`,emissiveIntensity:`float`,roughness:`float`,metalness:`float`,ior:`float`,transmission:`float`,thickness:`float`,clearcoat:`float`,clearcoatRoughness:`float`,clearcoatNormalMapIndex:`int`,clearcoatNormalScale:`float`,clearcoatNormal:`vec3`,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`,displacementBias:`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`,diffuseRoughness:`float`}),pl=x({transmission:`float`,clearcoat:`float`,clearcoatRoughness:`float`,sheenColor:`vec3`,sheenRoughness:`float`,iridescence:`float`,iridescenceThickness:`float`,specularIntensity:`float`,specularColor:`vec3`,diffuseTransmission:`float`,diffuseTransmissionColor:`vec3`}),ml=x({color:`vec4`,ior:`float`,transmission:`float`,attenuationColor:`vec3`,attenuationDistance:`float`,albedoMapIndex:`int`,opacity:`float`,transparent:`bool`,alphaTest:`float`,alphaMode:`int`,albedoTransform:`mat3`}),hl=x({shadowed:`vec3`,unoccluded:`vec3`}),x({position:`vec3`,radius:`float`,material:fl}),gl=x({didHit:`bool`,dst:`float`,hitPoint:`vec3`,normal:`vec3`,uv:`vec2`,materialIndex:`int`,meshIndex:`int`,instanceLeaf:`int`,triangleIndex:`int`,boxTests:`int`,triTests:`int`}),x({posA:`vec3`,posB:`vec3`,posC:`vec3`,uvA:`vec2`,uvB:`vec2`,uvC:`vec2`,normalA:`vec3`,normalB:`vec3`,normalC:`vec3`,material:fl,materialIndex:`int`,meshIndex:`int`}),x({color:`vec4`,samples:`int`}),_l=x({direction:`vec3`,value:`vec3`,pdf:`float`,isTransmission:`bool`,colorWeight:`vec3`,isDiffuseTransmission:`bool`}),vl=x({specular:`float`,diffuse:`float`,sheen:`float`,clearcoat:`float`,transmission:`float`,iridescence:`float`,diffuseTransmission:`float`}),yl=x({Ta:`vec3`,Ba:`vec3`}),bl=x({NoL:`float`,NoV:`float`,NoH:`float`,VoH:`float`,LoH:`float`,ToH:`float`,BoH:`float`,ToV:`float`,BoV:`float`,ToL:`float`,BoL:`float`,coatNoL:`float`,coatNoV:`float`,coatNoH:`float`}),xl=x({compensation:`vec3`,E_total:`vec3`}),Sl=x({f0:`vec3`,f90:`float`,eta:`float`,F0m:`vec3`,F0:`vec3`}),Cl=x({albedo:`vec4`,emissive:`vec3`,metalness:`float`,roughness:`float`,normal:`vec3`,hasTextures:`bool`}),wl=x({isMetallic:`bool`,isRough:`bool`,isSmooth:`bool`,isTransmissive:`bool`,hasClearcoat:`bool`,isEmissive:`bool`,complexityScore:`float`}),Tl=x({albedoUV:`vec2`,normalUV:`vec2`,metalnessUV:`vec2`,emissiveUV:`vec2`,bumpUV:`vec2`,roughnessUV:`vec2`,normalBumpSameUV:`bool`,metalRoughSameUV:`bool`,albedoEmissiveSameUV:`bool`,allSameUV:`bool`}),El=x({invRoughness:`float`,metalFactor:`float`,iorFactor:`float`,maxSheenColor:`float`}),x({traversals:`int`,transmissiveTraversals:`int`,rayType:`int`,isPrimaryRay:`bool`,actualBounceDepth:`int`})}));function Ol(e,t,n){return e.length===1?e[0]:{isSplitStorage:!0,parts:e,perPart:t,type:n,value:e[0].value}}function kl(e,t,r){let{parts:i,perPart:a}=e,o=(0,n.int)(t).toVar(),s=r.map(()=>({uvec4:n.uvec4,uvec2:n.uvec2}[e.type]??n.vec4)(0).toVar()),c=e=>()=>{let t=e===0?o:o.sub((0,n.int)(a*e));r.forEach((r,a)=>s[a].assign(i[e].element(r===0?t:t.add((0,n.int)(r)))))},l=(0,n.If)(o.lessThan((0,n.int)(a)),c(0));for(let e=1;e<i.length-1;e++)l=l.ElseIf(o.lessThan((0,n.int)(a*(e+1))),c(e));return l.Else(c(i.length-1)),s}function Al(e,t){return e.isSplitStorage?kl(e,t,[0])[0]:e.element(t)}var jl,Ml,Nl,Pl,Fl,Il,Ll,Rl,zl,Bl,Vl,Hl,Ul,Wl,Gl,Kl,ql,Jl,Yl,Xl,Zl,Ql,$l,eu,tu,nu,ru,iu,au,ou,su,cu,lu,uu,du,fu,pu,mu,hu,gu,_u,vu,yu,bu,xu=g((()=>{Dl(),pr(),Ft(),jl=(0,n.wgslFn)(`
|
|
247
|
+
`,bindings:n}}function cs(){ds.length=0,ds.push(...Jo),fs.clear();for(let e of ds)fs.set(e.id,e);Xo()}var ls,us,ds,fs,ps,ms,hs,gs,_s,vs=g((()=>{Yo(),ls=200,us=12,ds=[...Jo],fs=new Map(ds.map(e=>[e.id,e])),ps=1,ms=new Set,hs=fs,gs=r.NoToneMapping,_s=r.AgXToneMapping}));vs();var ys=e=>(t,n,r,i,a)=>e(t>0?t:0,n>0?n:0,r>0?r:0,i,a),bs=new Map;function xs(){bs.clear();for(let e of hs.values())bs.set(e.id,ys(e.cpu))}xs(),Qo(xs);function Ss(e){return $o(e)?.outputEncoded===!0}function Cs(e){return e<=.0031308?12.92*e:1.055*e**(1/2.4)-.055}function ws(e,t){let n=$o(t);return n?n.appliesExposure?e:1:t===r.NoToneMapping?1:e}function Ts(e,t,n){return ws(e,n)/ws(t,n)}function Es(e,t,n){return e+(t-e)*(1-Math.min(Math.max(n,0),1))}var Ds=.2126,Os=.7152,ks=.0722;function As(e,t){if(t===1)return;let n=e[0]*Ds+e[1]*Os+e[2]*ks;e[0]=n+(e[0]-n)*t,e[1]=n+(e[1]-n)*t,e[2]=n+(e[2]-n)*t}function js(e,{exposure:t,toneMapping:n,saturation:i=1,preserveAlpha:a=!1,pixelGain:o=null}){let s=bs.get(n)??bs.get(r.NoToneMapping),c=ws(t,n),l=Ss(n),u=new Uint8ClampedArray(e.length),d=[0,0,0],f=Math.log2(t);for(let t=0;t<e.length;t+=4){let n=c;if(o){let r=1;if(o.fn){let n=t>>2,i=n%o.width,a=(n-i)/o.width,s=e[t]*.2126+e[t+1]*.7152+e[t+2]*.0722;r=o.fn((i+.5)/o.width,(a+.5)/o.height,s,f)}o.backdrop>0&&(r=Es(r,o.backdrop,e[t+3])),n*=r}d[0]=e[t]*n,d[1]=e[t+1]*n,d[2]=e[t+2]*n,As(d,i),s(d[0],d[1],d[2],1,d),l?(u[t]=d[0]*255+.5,u[t+1]=d[1]*255+.5,u[t+2]=d[2]*255+.5):(u[t]=Cs(d[0])*255+.5,u[t+1]=Cs(d[1])*255+.5,u[t+2]=Cs(d[2])*255+.5),u[t+3]=a?e[t+3]*255+.5:255}return u}Ft(),en(),an(),Ae(),Fr();var Ms=ve(`textures`),Ns={MAX_BUFFER_MEMORY:1024*1024*1024,MAX_TEXTURE_MEMORY:2048*1024*1024,CLEANUP_THRESHOLD:.8,STREAM_BATCH_SIZE:4},Ps=8*2**20,Fs=16,Is=4,Ls=8192*8192,Rs={busy:0,waiting:[]};async function zs(){return Rs.busy<Math.max(1,Or()-1)?Rs.busy++:await new Promise(e=>Rs.waiting.push(e)),()=>{let e=Rs.waiting.shift();e?e():Rs.busy--}}var Bs={toSRGB:null,toLinear:null};function Vs(e){if(!Bs[e]){let t=new Uint8Array(256);for(let n=0;n<256;n++){let r=n/255,i=e===`toSRGB`?Cs(r):r<=.04045?r/12.92:((r+.055)/1.055)**2.4;t[n]=Math.max(0,Math.min(255,Math.round(i*255)))}Bs[e]=t}return Bs[e]}var Hs=class{constructor(){this.canvasContextPairs=[],this.maxPoolSize=Qt.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=[]}},Us=class{constructor(e={}){this.pools=new Map,this.memoryUsage=0,this.maxMemoryUsage=e.maxMemory||Ns.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*Ns.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<Qt.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`}},Ws=class{constructor(e=Qt.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=[]}},Gs=class{constructor(e={}){this.useWorkers=typeof Worker<`u`,this.maxConcurrentWorkers=Qt.MAX_CONCURRENT_WORKERS,this.activeWorkers=0,this._issues=e.issues??null,this.maxTextureSize=this._clampTextureSize(e.maxTextureSize??Qt.DEFAULT_MAX_TEXTURE_SIZE),this.canvasPool=new Hs,this.bufferPool=new Us({maxMemory:e.maxBufferMemory||Ns.MAX_BUFFER_MEMORY,sizeStrategy:e.bufferSizeStrategy||`adaptive`}),this.textureCache=new Ws,this.capabilities=this.detectCapabilities(),this.optimalMethod=this.selectOptimalMethod()}_reportTextureFailure(e,t){if(t instanceof nn)throw t;this._issues?.record(X.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(X.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)||Qt.DEFAULT_MAX_TEXTURE_SIZE);return Math.max(Qt.MIN_TEXTURE_WIDTH,Math.min(t,Qt.MAX_TEXTURE_SIZE))}setMaxTextureSize(e){let t=this._clampTextureSize(e);return t===this.maxTextureSize?t:(this.maxTextureSize=t,this.textureCache?.dispose(),this.textureCache=new Ws,this.maxTextureSize)}detectCapabilities(){return{offscreenCanvas:typeof OffscreenCanvas<`u`,imageBitmap:typeof createImageBitmap<`u`,workers:typeof Worker<`u`,hardwareConcurrency:Or()}}selectOptimalMethod(){return this.capabilities.workers&&this.capabilities.offscreenCanvas?`worker-offscreen`:this.capabilities.imageBitmap?`imageBitmap`:`canvas`}_applyColorManagement(e,t,n,i=new Set){let a=$r();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){Ms.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(X.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(X.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,Ms.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=Vs(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?Ms.info(`re-encoded ${l.length}/${o.length} linear-declared colour map(s) to sRGB so the GPU decode round-trips: ${u}`):Ms.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=$r()?.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 nn)throw n;this._issues?.warn(X.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>Ns.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 Ao;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)<Ls)return 0;let t=this.maxConcurrentWorkers-this.activeWorkers;return Math.max(0,Math.min(e.length,Is,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=Mr(Ao);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=Mr(Ao);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>=Ns.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>Fs&&(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=e?.isCompressedTexture?r?.data:qs(e);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=Ar()&&i*t.length>=Ps?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)=>Po(e,o,t*i,n,r)),this.createDataArrayTextureFromBuffer(o,n,r,t.length)}async _packInWorker(e,t,n){let r=await zs(),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=Mr(No),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(X.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%Ns.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++)Ht(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=Qt.VEC4_PER_BVH_NODE*Qt.FLOATS_PER_VEC4;yt(t.length,`BVH node count`);let i=t.length*r,a=new Float32Array(i),o=G(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]=Tt.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 Ws;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:Ut(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:Ks(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);let r=qs(n);i.push({index:e,flipY:n.flipY,promise:r?Ks(r,n.image.width,n.image.height):Promise.reject(Error(`pixels in a layout the texture arrays cannot take`))});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()}};async function Ks(e,t,n){let r=new Uint8ClampedArray(e.buffer,e.byteOffset,e.byteLength);return createImageBitmap(new ImageData(r,t,n))}function qs(e){let t=e?.image,n=t?.data;if(!n||!(t.width>0)||!(t.height>0))return null;let i=t.width*t.height;if(n instanceof Uint8Array||n instanceof Uint8ClampedArray)return n.byteLength>=i*4?new Uint8Array(n.buffer,n.byteOffset,i*4):null;let a={[r.RGBAFormat]:4,[r.RGFormat]:2,[r.RedFormat]:1}[e.format]??Math.round(n.length/i);if(!(a>=1&&a<=4)||n.length<i*a)return null;let o=e.type===r.HalfFloatType,s=e.type===r.UnsignedShortType?1/65535:1,c=new Uint8Array(i*4);for(let e=0;e<i;e++)for(let t=0;t<4;t++){let i=t<a?n[e*a+t]:null,l=i===null?t===3?1:c[e*4]/255:o?r.DataUtils.fromHalfFloat(i):i*s;c[e*4+t]=Math.max(0,Math.min(255,Math.round(l*255)))}return c}var Js=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=Xs(E,Ys(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=Xs(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 Ys(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 Xs(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)}}Ft(),Ae(),tr();var Zs=Object.freeze({r:0,g:0,b:0});function Qs(e){if(!e)return Zs;if(!Yn())return e;let t=[e.r,e.g,e.b];return Zn(t),{r:t[0],g:t[1],b:t[2]}}var $s=ve(`emissive`),ec=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]&bt,h=n[p+o],g=t[m];if(!g)continue;let _=d.get(g);_===void 0&&(_=Qs(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.matrixRow(t):0,a=n?r.rowArray:null,o=(e,t,n)=>a?a[i]*e+a[i+4]*t+a[i+8]*n+a[i+12]:e,s=(e,t,n)=>a?a[i+1]*e+a[i+5]*t+a[i+9]*n+a[i+13]:t,c=(e,t,n)=>a?a[i+2]*e+a[i+6]*t+a[i+10]*n+a[i+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),z=Math.max(E,k,M),ue=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:z,bMaxZ:ue,nx:I,ny:L,nz:ee,twoSided:ne}),this.totalEmissivePower+=F}}return this.emissiveCount=this.emissiveTriangles.length,this.emissiveCount>0&&$s.debug(`${V.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;this.totalEmissivePower=0;for(let e of this.emissiveTriangles){let o=n?r.chunkFor(e.triangleIndex):i,s=n?n.baseOf(e.triangleIndex):e.triangleIndex*a,c=[o[s],o[s+1],o[s+2],o[s+4],o[s+5],o[s+6],o[s+8],o[s+9],o[s+10]],l=t.placementRunOf?.(e.meshIndex)?.start??-1;if(l>=0&&t.isSet[l]){let e=t.matrixRow(l),n=t.rowArray;for(let t=0;t<9;t+=3){let r=c[t],i=c[t+1],a=c[t+2];c[t]=n[e]*r+n[e+4]*i+n[e+8]*a+n[e+12],c[t+1]=n[e+1]*r+n[e+5]*i+n[e+9]*a+n[e+13],c[t+2]=n[e+2]*r+n[e+6]*i+n[e+10]*a+n[e+14]}}let[u,d,f,p,m,h,g,_,v]=c,y=this._calculateTriangleArea(u,d,f,p,m,h,g,_,v),b=e.emissive;e.power=(.2126*b.r+.7152*b.g+.0722*b.b)*e.emissiveIntensity*y,e.area=y;let x=(m-d)*(v-f)-(h-f)*(_-d),S=(h-f)*(g-u)-(p-u)*(v-f),C=(p-u)*(_-d)-(m-d)*(g-u),w=(Math.sqrt(x*x+S*S+C*C)||1)/e.sideSign;e.nx=x/w,e.ny=S/w,e.nz=C/w,e.cx=(u+p+g)/3,e.cy=(d+m+_)/3,e.cz=(f+h+v)/3,e.bMinX=Math.min(u,p,g),e.bMinY=Math.min(d,m,_),e.bMinZ=Math.min(f,h,v),e.bMaxX=Math.max(u,p,g),e.bMaxY=Math.max(d,m,_),e.bMaxZ=Math.max(f,h,v),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,$s.debug(`emissive texture ${V.px(t,n)} · ${V.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 $s.debug(`emissive raw data ${V.n(this.emissiveCount)} entries (${V.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=Qs(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(4).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 Js().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,$s.debug(`rebuilt sorted emissive data · ${V.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 tc=class{constructor(e=`Build`,{namespace:t=`build`,level:n=`debug`}={}){this.label=e,this.level=n,this.logger=ve(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=V.list([this.label,...e,V.ms(t)]);return this.level===`info`?this.logger.summary(r,n):this.logger.debug(V.list([r,n.join(` · `)])),{steps:Object.fromEntries(this.order.map(e=>[e,Math.round(this.entries.get(e)?.duration??0)])),total:Math.round(t)}}};hn();var nc=1<<20,rc=1<<21,ic=()=>new Promise(e=>setTimeout(e,0)),ac=[0,1,2,4,5,6,8,9,10];function oc(e,t,n,r=ac){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 sc(e,t){let n=[],r=0;for(let{triOffset:i,triCount:a}of t)n.push(oc(e,i,a)),r+=a,r>=rc&&(r=0,await ic());return n}async function cc(e,t){let n=await e?.area(mn.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 lc(e,t,{index:n,bvh:r,orders:i,isStale:a,label:o=``}){let s=e?.area(mn.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,nc),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+=nc*4)await u.write(`order.u32`,e.subarray(t,Math.min(e.length,t+nc*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 uc(e,t,n,r){for(let i=0;i<r;i+=nc){let a=Math.min(nc,r-i),o=await e.slice(i*64,(i+a)*64).arrayBuffer();t.setRecords(n+i,new Float32Array(o))}}async function dc(e,t,n){return new Uint32Array(await e.slice(t*4,(t+n)*4).arrayBuffer())}Ft();var fc=16,pc=K.POSITION_A_OFFSET,mc=K.POSITION_B_OFFSET,hc=K.POSITION_C_OFFSET;async function gc(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+pc]+o[n+mc]+o[n+hc],c[r]=o[n+pc+1]+o[n+mc+1]+o[n+hc+1],l[r]=o[n+pc+2]+o[n+mc+2]+o[n+hc+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 vc(u,o,_c(o,e,t),e,t,n),{left:f(e,n),right:f(n,t)}},p=f(0,n);return await i?.(),await yc(e,t,n,u,i),{order:u,pieces:d,tree:p}}function _c(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 vc(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 yc(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 bc(e,t,n,r){let i=t.length-1,a=[],o=i;for(let{bvhData:e}of n)a.push(o),o+=e.length/fc;let s=new Float32Array(i*fc),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];Ui(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*fc;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 xc,Sc=g((()=>{xc=`11.12.0`})),Cc,wc=g((()=>{Sc(),Cc=xc}));function Tc(e,t,n=Ec){return e>=n&&t/Dc<e/3}var Ec,Dc,Oc=g((()=>{Ec=1e4,Dc=15e5}));wc(),Oc();var kc="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,CLUSTER_LEAF:1073741827},r=new Float32Array(1),i=new Uint32Array(r.buffer);function a(e){let t=Math.fround(e);return t<=e?t:(r[0]=t,i[0]+=t>0?-1:1,r[0])}function o(e,t){return Math.max(Math.abs(e),Math.abs(t),1e-30)*2**-21}const s=[2,4,5];function c(e,t,n,r,i,c,u){let d=0;for(let f=0;f<3;f++){let p=1/0,m=-1/0;for(let e=0;e<i;e++)p=Math.min(p,r[e*6+f]),m=Math.max(m,r[e*6+3+f]);if(c&&(c[u+f]=p,c[u+3+f]=m),!(p<=m)){e[n+s[f]]=l,t[n+6+f]=0,t[n+9+f]=0;continue}let h=o(p,m),g=a(p-h),_=Math.max(-126,Math.ceil(Math.log2((m+h-g)/255)));for(;Math.fround(g+255*2**_)<m+h;)_++;let v=2**_;e[n+s[f]]=g,d|=_+127<<f*8;let y=0,b=0;for(let e=0;e<i;e++){let t=r[e*6+f],n=r[e*6+3+f],i=o(t,n);y|=Math.max(0,Math.min(255,Math.floor((t-i-g)/v)))<<e*8,b|=Math.max(0,Math.min(255,Math.ceil((n+i-g)/v)))<<e*8}t[n+6+f]=y>>>0,t[n+9+f]=b>>>0}t[n+1]=d>>>0}const l=1e30;n.TRIANGLE_LEAF;const u=e=>e>=2147483648,d=e=>~e>>>0>>>4,f=e=>~e&15,p=e.FLOATS_PER_TRIANGLE,m=e=>e instanceof Float32Array?e:new Float32Array(e.buffer,e.byteOffset,e.length),h=e=>e instanceof Uint32Array?e:new Uint32Array(e.buffer,e.byteOffset,e.length),g=e=>{let t=e&&e.chunks?e:null;return{chunked:t,f:e,idx:t?e.viewAs(Uint32Array):h(e)}},_=(e,t)=>e.chunked?e.f.chunkFor(t):e.f,v=(e,t)=>e.chunked?e.idx.chunkFor(t):e.idx,y=(e,t)=>e.chunked?e.chunked.baseOf(t):t*x,b=e=>{let t=e&&e.chunks?e:null;return{chunked:t,f:t?t.viewAs(Float32Array):m(e),u:t?e:h(e)}},x=16,S=n.TRIANGLE_LEAF,C=n.BLAS_POINTER_LEAF,w=n.CLUSTER_LEAF;function T(e,t,n,r,i,a){if(n[r]>n[r+3]){for(let e=0;e<6;e++)i[a+e]=n[r+e];return}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 E(t,n,r,i,a){let o=e.POSITION_A_OFFSET,s=e.POSITION_B_OFFSET,c=e.POSITION_C_OFFSET,l=1/0,u=1/0,d=1/0,f=-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*p;l=Math.min(l,i[a+o],i[a+s],i[a+c]),u=Math.min(u,i[a+o+1],i[a+s+1],i[a+c+1]),d=Math.min(d,i[a+o+2],i[a+s+2],i[a+c+2]),f=Math.max(f,i[a+o],i[a+s],i[a+c]),m=Math.max(m,i[a+o+1],i[a+s+1],i[a+c+1]),h=Math.max(h,i[a+o+2],i[a+s+2],i[a+c+2])}i[a]=l,i[a+1]=u,i[a+2]=d,i[a+3]=f,i[a+4]=m,i[a+5]=h}const D=new Float32Array(12),O=(e,t)=>e[t]>=l*.5;function k(e,t,n,r){let i=n[r]>n[r+3];e[t]=i?l:n[r],e[t+1]=i?l:n[r+1],e[t+2]=i?l:n[r+2],e[t+4]=i?l:n[r+3],e[t+5]=i?l:n[r+4],e[t+6]=i?l:n[r+5]}function A(e,t,n,r){let i=_(e,t),a=v(e,t),o=y(e,t);if(a[o+3]===S){E(n,a[o],a[o+1],r,0);return}let s=!O(i,o),c=!O(i,o+8);for(let e=0;e<3;e++)r[e]=Math.min(s?i[o+e]:1/0,c?i[o+8+e]:1/0),r[3+e]=Math.max(s?i[o+4+e]:-1/0,c?i[o+12+e]:-1/0)}const j=new Float32Array(16),M=new Float32Array(6),N=new Float32Array(24);function P(e,t,n,r,i,a){let o=_(e,t),s=v(e,t),l=y(e,t),u=s[l]&268435455,d=(s[l]>>>28&3)+1;for(let t=0;t<d;t++){let i=s[l+12+t];if(A(e,i&1073741823,n,M),i&1073741824){for(let e=0;e<6;e++)N[t*6+e]=M[e];continue}let a=r*16+(u+t)*3*4;for(let t=0;t<12;t++){let n=a+t>>4;j[4+t]=_(e,n)[y(e,n)+(a+t&15)]}T(j,0,M,0,N,t*6)}c(o,s,l,N,d,i,a)}function F(e,t,n,r,i,a=-1){let o=_(e,t),s=v(e,t),c=y(e,t),l=(t-i)*6,p=s[c+3];if(p===S){E(n,s[c],s[c+1],r,l);return}if(p===w){P(e,t,n,a,r,l);return}if(p===C){T(o,c,r,(s[c]-i)*6,r,l);return}let m=s[c+7],h=r,g=(p-i)*6;u(p)&&(E(n,d(p),f(p),D,0),h=D,g=0);let b=r,x=(m-i)*6;u(m)&&(E(n,d(m),f(m),D,6),b=D,x=6),k(o,c,h,g),k(o,c+8,b,x);for(let e=0;e<3;e++)r[l+e]=Math.min(h[g+e],b[x+e]),r[l+3+e]=Math.max(h[g+3+e],b[x+3+e])}var I=class{constructor(){this._bounds=null,this._boundsNodeCount=0,this._tlasBounds=null,this._rootBox=null}updateTrianglePositions(n,r,i){let a=i.length,o=b(n);for(let n=0;n<a;n++){let a=i[n],s=o.chunked?o.f.chunkFor(n):o.f,c=o.chunked?o.u.chunkFor(n):o.u,l=o.chunked?o.chunked.baseOf(n):n*p,u=a*9,d=r[u],f=r[u+1],m=r[u+2],h=r[u+3],g=r[u+4],_=r[u+5],v=r[u+6],y=r[u+7],b=r[u+8];s[l+e.POSITION_A_OFFSET]=d,s[l+e.POSITION_A_OFFSET+1]=f,s[l+e.POSITION_A_OFFSET+2]=m,s[l+e.POSITION_B_OFFSET]=h,s[l+e.POSITION_B_OFFSET+1]=g,s[l+e.POSITION_B_OFFSET+2]=_,s[l+e.POSITION_C_OFFSET]=v,s[l+e.POSITION_C_OFFSET+1]=y,s[l+e.POSITION_C_OFFSET+2]=b;let x=h-d,S=g-f,C=_-m,w=v-d,T=y-f,E=b-m,D=t(S*E-C*T,C*w-x*E,x*T-S*w);c[l+e.NORMAL_A_PACKED_OFFSET]=D,c[l+e.NORMAL_B_PACKED_OFFSET]=D,c[l+e.NORMAL_C_PACKED_OFFSET]=D}}refitRange(e,t,n,r){let i=b(t);r>this._boundsNodeCount&&(this._bounds=new Float32Array(r*6),this._boundsNodeCount=r);let a=g(e);for(let e=n+r-1;e>=n;e--)F(a,e,i,this._bounds,n)}refitPartial(e,t,n,r,i=null,a=-1){for(let r=0;r<n.length;r+=2)this.refitRange(e,t,n[r],n[r+1]);let o=b(t),s=g(e);i&&this.refitGroups(s,o,i[0],i[1]),(!this._tlasBounds||this._tlasBounds.length<r*6)&&(this._tlasBounds=new Float32Array(r*6));let c=this._tlasBounds;for(let e=r-1;e>=0;e--){let t=v(s,e),n=y(s,e);t[n+3]===C?(A(s,t[n],o,M),T(_(s,e),n,M,0,c,e*6)):F(s,e,o,c,0,a)}}refitGroups(e,t,n,r){let i=this._groupBox||=new Float32Array(6);for(let a=n+r-1;a>=n;a--){let n=_(e,a),r=v(e,a),o=y(e,a);r[o+3]!==S&&(A(e,r[o+3],t,i),k(n,o,i,0),A(e,r[o+7],t,i),k(n,o+8,i,0))}}refit(e,t,n,r=-1){let i=b(t);n!==this._boundsNodeCount&&(this._bounds=new Float32Array(n*6),this._boundsNodeCount=n);let a=g(e);for(let e=n-1;e>=0;e--)F(a,e,i,this._bounds,0,r)}};const L=64*1024*1024;function R(e,t,n){return n?new e(new SharedArrayBuffer(t*e.BYTES_PER_ELEMENT)):new e(t)}var z=class e{constructor(e,t,n,r=L,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(R(n,e*t,i)),s-=e}this.chunks.length===0&&this.chunks.push(R(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=L,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]=R(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=R(this.LaneType,t,this.shared),r=new Uint8Array(n.buffer,n.byteOffset,n.byteLength);this._store.readInto?await this._store.readInto(e,r):r.set(new Uint8Array(await this._store.read(e,r.byteLength))),this.chunks[e]=n;for(let t of this._liveViews())t.chunks[e]=new t.LaneType(n.buffer,n.byteOffset,n.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=R(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 B=new I;let V=null,H=null,U=0;self.onmessage=function(e){let{type:t}=e.data;if(t===`init`){V=z.adopt(e.data.sharedBvhBufs.map(e=>new Float32Array(e)),e.data.bvhRecordCount,16,e.data.bvhRecordsPerChunk),H=z.adopt(e.data.sharedTriBufs.map(e=>new Uint32Array(e)),e.data.triRecordCount,e.data.triLanesPerRecord,e.data.triRecordsPerChunk),U=V.recordCount;return}if(t===`refit`)try{let t=performance.now(),{blasRanges:n,tlasNodeCount:r,groupRange:i,treeNodeCount:a,recordNodeStart:o=-1}=e.data;n?B.refitPartial(V,H,n,r,i,o):B.refit(V,H,a??U,o),self.postMessage({type:`refitComplete`,refitTimeMs:performance.now()-t})}catch(e){console.error(`[BVHRefitWorker] Refit error:`,e),self.postMessage({type:`error`,error:e.message})}};",Ac=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,kc],{type:`text/javascript;charset=utf-8`});function jc(e){let t;try{if(t=Ac&&(self.URL||self.webkitURL).createObjectURL(Ac),!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(kc),{type:`module`,name:e?.name})}}var Mc="const e={TRIANGLE_LEAF:1073741824,BLAS_POINTER_LEAF:1073741825,FRONTIER:1073741826,CLUSTER_LEAF:1073741827};new Uint32Array(new Float32Array(1).buffer);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]);Object.freeze([]);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=e.clusterCount>0,n=t?e.clusterBounds:new Float64Array(e.entryCount*6);t||e.writeEntryWorldAABBs(n);let i=this.buildStructure(n,t?e.clusterCount:e.entryCount);return r.fillLeaves(i.data,i.nodeCount,e),i}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=t(n);if(a.clusterCount>0){for(let t=0;t<i;t++){let r=t*16;o[r+3]===e.BLAS_POINTER_LEAF&&a.writeClusterLeaf(n,o,r,o[r+1],a.clusterWorld,t)}return}for(let t=0;t<i;t++){let i=t*16;if(o[i+3]!==e.BLAS_POINTER_LEAF)continue;let s=o[i+1]&1073741823;o[i]=a.entryRoot(s),n[i+2]=+!!a.entryVisible(s),r.writeLeafMatrix(n,o,i,a,a.repOf(s),s),a.setLeafOf(s,t)}}static writeLeafMatrix(e,t,n,r,i,s=i){let l=c,u=r.matrixRow(i),d=r.rowArray;a(d,u,l),e[n+4]=l[0],e[n+5]=l[4],e[n+6]=l[8],e[n+7]=l[12],e[n+8]=l[1],e[n+9]=l[5],e[n+10]=l[9],e[n+11]=l[13],e[n+12]=l[2],e[n+13]=l[6],e[n+14]=l[10],e[n+15]=l[14],t[n+1]=(s|(o(d,u)?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})}};",Nc=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,Mc],{type:`text/javascript;charset=utf-8`});function Pc(e){let t;try{if(t=Nc&&(self.URL||self.webkitURL).createObjectURL(Nc),!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(Mc),{type:`module`,name:e?.name})}}fn(),qn(),Ae(),Ft(),en(),an(),ii(),yn(),On(),ui(),Fr();var Fc=5e4,Ic=2e5,Lc=2e6,Rc=1<<19,zc=4e7,Bc=1e6,Vc=1024**3,Hc=1024**3,Uc=32*1024*1024,Wc=64*1024*1024,Gc=256*1024*1024,Kc=ve(`scene`),qc=Object.freeze([`maps`,`normalMaps`,`bumpMaps`,`roughnessMaps`,`metalnessMaps`,`emissiveMaps`,`displacementMaps`,`anisotropyMaps`,`transmissionMaps`,`clearcoatMaps`,`clearcoatRoughnessMaps`,`clearcoatNormalMaps`,`sheenColorMaps`,`sheenRoughnessMaps`,`iridescenceMaps`,`iridescenceThicknessMaps`,`specularIntensityMaps`,`specularColorMaps`,`diffuseTransmissionMaps`,`diffuseTransmissionColorMaps`]),Jc=e=>Array.isArray(e)?e:[e],Yc=e=>Jc(e).reduce((e,t)=>e+t.byteLength,0),Xc=64*1024*1024;async function Zc(e,t,n){for(let r of Jc(n))await e.writeAt(t,r),t+=r.byteLength}function Qc(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 $c=1024,el=64;function tl(e){let t=Int32Array.from(e).sort(),n=[],r=t[0],i=r;for(let e=1;e<=t.length;e++){if(e<t.length&&t[e]-i<=$c){i=t[e];continue}n.push({offset:r*16,count:(i-r+1)*16}),r=i=t[e]}return n.length>el?[{offset:t[0]*16,count:(t.at(-1)-t[0]+1)*16}]:n}var nl=class{constructor(e={}){this.config={useWorkers:!0,bvhDepth:30,maxLeafSize:4,verbose:!1,useFloat32Array:!0,textureQuality:`adaptive`,maxTextureSize:Qt.DEFAULT_MAX_TEXTURE_SIZE,enableTextureCache:!0,maxConcurrentTextureTasks:Math.min(Or(),6),maxSceneBytes:bo,sceneCache:!0,sceneCacheMinBuildMs:Ec,...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.clearcoatNormalMaps=[],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 Eo,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 Kn({issues:this.config.issues}),this.bvhBuilder=new Qi,this.bvhBuilder.maxLeafSize=this.config.maxLeafSize,this.textureCreator=new Gs({maxTextureSize:this.config.maxTextureSize,issues:this.config.issues}),this.emissiveTriangleBuilder=new ec,this.tlasBuilder=new so,this._tlasWorker=null,this._tlasWorkerFailed=!1}_log(e,t){t===void 0?Kc.debug(e):Kc.debug(e,t)}needsSpill(e){return lo(this.geometryExtractor.surveyScene(e)).total>yo}get spilling(){return!!this._progressive&&(this.triangles?.chunks?.length??0)>1}_preflightMemory(e){let t=this.config.maxSceneBytes??9663676416,n=this.geometryExtractor.surveyScene(e),r=lo(n);if(this._streaming){let t=Vc+Qc(e)*(K.FLOATS_PER_TRIANGLE*4+44);r.total=uo(r,n.placements,Math.min(r.triangles,t))}else this._progressive&&(r.total-=r.bvh);let i={...n,estimate:r,safeBytes:yo,maxBytes:t,fits:r.total<=yo};if(this.memoryPreflight=i,r.total<1610612736)return i;if(Kc.debug(V.list([`memory preflight: ${V.mb(r.total)} estimated`,`triangles ${V.mb(r.triangles)} · bvh ${V.mb(r.bvh)} · geometry ${V.mb(r.geometry)}`,`${V.n(n.triangles)} tris · ${V.n(n.placements)} placements`])),r.total>t){let e=`Scene needs about ${V.mb(r.total)} of CPU memory, past the ${V.mb(t)} a browser tab can hold — loading it would crash the tab rather than fail. Reduce the scene (it has ${V.n(n.triangles)} triangles), or raise maxSceneBytes to try anyway.`;throw this.config.issues?.record(X.SCENE_MEMORY_BUDGET,e,{...n,estimate:r,maxBytes:t}),Error(e)}return i.fits||this.config.issues?.warn(X.SCENE_MEMORY_BUDGET,`Scene needs about ${V.mb(r.total)} of CPU memory, above the ${V.mb(yo)} 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:yo}),i}_checkAssemblyHeadroom(e){let t=e*64;if(t<1610612736)return!0;let n=fo(Math.ceil(t*wo),{shared:ln});return this.memoryPreflight&&(this.memoryPreflight.assemblyProbed=n.placed),n.exhausted&&this.config.issues?.warn(X.SCENE_MEMORY_BUDGET,`BVH assembly needs ${V.mb(t)} but only ${V.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?.matrixBytes??0,blasScratch:0,orderMaps:0};if(e){for(let n of e.blasData.values())t.blasScratch+=n?Yc(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;if(!this.bvh.isResident(0,1))return this._spilledRootBounds??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} ${V.mb(n[e].allocated)}`),i=this.memoryPreflight?.estimate?.total;Kc.debug(V.list([`memory: peak live ${V.mb(t)}`,`allocated ${V.mb(e)}`,i?`predicted ${V.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,on(e=>this.memory.alloc(e));let r=new tc(e.name??``,{namespace:`scene`});try{this._geometryOwner===e&&await Promise.all([this._restoreGeometry(e),this.ensureMovable()]),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>zc,this.textureCoordinates=Rn(e),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=Mn(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`,this._streaming&&this._geometrySpill?.bytes>=Hc?this._geometryOwner=e: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=>Kc.debug(`storing BLASes failed:`,e))),this}catch(e){throw this.processingStage=`error`,Kc.error(`processing failed:`,e),z({status:`Error: ${e.message}`,failed:!0,progress:100}),e}finally{this._geometryOwner||this._disposeGeometrySpill(),on(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 Kc.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:`Large scene: building through disk to save memory...`,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=dn.lazy(o,K.FLOATS_PER_TRIANGLE,Uint32Array),c=s.recordsPerChunk*s.lanesPerRecord*4,l=await vn.create(r,`${a}:tri`,c,{label:`Triangle records`,expectedBytes:o*c/s.recordsPerChunk}),u=l&&await vn.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 Dn.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);Ka.rootAABB(Jc(r)[0],v,t.start,t.count,i,0),p.set(e,{result:n,aabb:i});let a=f.blasBytes;f.blasBytes+=Yc(r),f.blasAt.set(e,a),n.nodeCount=Yc(r)/64,n.bvhData=null,this._queueSpill(f,()=>Zc(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`,{textureCoordinates:this.textureCoordinates})},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>Gc&&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>Vc&&(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),Kc.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=yt(e.triangleCount,`triangle count`),this._foldLeaves&&this.triangleCount>134217728)throw RangeError(`${this.triangleCount.toLocaleString()} triangles is past the ${Nt.toLocaleString()} a folded BVH leaf can address`);this.expandedTriangleCount=e.expandedTriangleCount??e.triangleCount,this.instanceSource=e.instanceSource||null,this.matrixRuns=e.matrixRuns||null,this.instanceCount=e.instanceCount||0,this.instanceGroups=e.instanceGroups??[],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._adoptTextureLists(e),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.matrixRuns:null,o=e=>n?i[e]:e;this.instanceTable=new Ka,this.instanceTable.allocate(r,t.length,a,n?i:null),this.instanceTable.tplBakeInverse=this.bakeInverse,this.instanceTable.setGroups(n?this.instanceGroups:null);let s=this._clusterCopies(this.instanceTable);s&&this.instanceTable.planClusters();let c=s?this.instanceTable.clusterCount:this.instanceTable.entryCount,l=so.nodeCountFor(c)+this.instanceTable.groupNodeCount,u=this._streamed;this._streamed=null;let d=[],f=[],p=[],m=new Int32Array(r).fill(-1),h=new Map;for(let e=0;e<r;e++){let n=t[o(e)];if(!n||n.count===0)continue;let r=h.get(n.start);if(r!==void 0){m[e]=r;continue}h.set(n.start,e),u?p.push({m:e,range:n}):this._isLargeMesh(n)?f.push({m:e,range:n}):d.push({m:e,range:n})}let g=this._blasWorkerOpts(),_=d.length+f.length,v=0,y=()=>{v++,z({status:`Building BLAS ${v}/${_}...`,progress:25+Math.floor(v/_*45)})},b=[...d,...f].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),x=u?null:await this._restoreBLASes(b,l,g),S=u?u.state:!x&&this._progressive&&this.triangles.chunks.length>1?await this._beginProgressiveSpill(b):null,C=S&&!u?(e,t,n)=>this._onBLASBuilt(S,o(e),t,n):null;if(u)for(let[e,t]of u.templates)this.instanceTable.tplObjectAABB.set(t.aabb,e*6);x&&(d.length=0,f.length=0,z({status:`Restored stored BVHs`,progress:68}));let w=x?Promise.resolve(x.results):u?Promise.resolve(p.map(({m:e,range:t})=>({m:e,range:t,result:u.templates.get(o(e)).result}))):this._buildBLASesWithPool(d,g,y,C),T=[],E=(async()=>{for(let{m:e,range:t}of f){let n=await this._buildLargeBLAS(t,g);C?.(e,t,n),T.push({m:e,range:t,result:n}),y()}})(),[D]=await Promise.all([w,E]);if(S&&(await S.chain,S.error))throw S.error;let O={sah:0,objMed:0,spatMed:0,failed:0};for(let{m:e,range:t,result:r}of[...D,...T]){let i=r.splitStats;i&&(O.sah+=i.sahSplits??0,O.objMed+=i.objectMedianSplits??0,O.spatMed+=i.spatialMedianSplits??0,O.failed+=i.failedSplits??0,this.performanceMetrics.blasWorkerTime+=i.totalBuildTime??0),this.instanceTable.setEntry({meshIndex:e,blasNodeCount:r.nodeCount??Yc(r.bvhData)/64,triOffset:t.start,triCount:t.count,originalToBvhMap:r.originalToBvh||null,bvhData:r.bvhData,matrixWorld:n?za:this.meshes?.[e]?.matrixWorld?.elements??null,expandedStart:t.expandedStart,sourceMesh:o(e)})}for(let e=0;e<r;e++){let r=m[e];r<0||this.instanceTable.setAlias(e,r,n?za:this.meshes?.[e]?.matrixWorld?.elements??null,t[o(e)].expandedStart,o(e))}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 k=performance.now(),A=this.instanceTable;this.instanceTable.computeAABBs(this.triangles,{owners:!S}),this.instanceTable.computeGroupAABBs(),s&&(A.clusterWorld=new Float32Array(A.entryCount*6),A.writeEntryWorldAABBs(A.clusterWorld),A.clusterBounds=A.formClusters(A.clusterWorld)),this.instanceTable.assignOffsets(so.nodeCountFor(c));let j=this.instanceTable.totalNodeCount,M=await this._buildTLAS(A);if(this._streaming&&s){let e=A.clusterWorld;this._spillMeshBounds=this._instancedMeshBounds((t,n)=>{for(let r=0;r<6;r++)n[r]=e[t*6+r]})}A.clusterWorld=null,A.clusterBounds=null,this.performanceMetrics.tlasBuildTime=performance.now()-k,this.memory.mark(`assemble`);let N=performance.now();S||this._checkAssemblyHeadroom(j),this._setBVHData(dn.lazy(j,16,Float32Array,void 0,ln));let P=S?await this._beginBVHSpill(S,A.blasBase):null;this.bvh.setRecords(0,M),A.groupNodeCount&&this.bvh.setRecords(A.groupNodeStart,A.groupNodeBlock()),M=null,this.tlasBuilder.releaseFlattenBuffer();let F=Math.max(1,Math.ceil(A.templateCount/32));if(x){try{let e=performance.now();await uc(x.nodes,this.bvh,A.blasBase,A.totalBLASNodes),this.performanceMetrics.blasRestore.readMs=performance.now()-e}finally{x.release()}A.blasData.clear()}else{for(let e=0;e<A.templateCount;e++){let t=S?await this._readSpilledBLAS(S,e):A.blasData.get(e);if(!t)continue;let n=A.tplBlasOffset[e],r=n;for(let e of Jc(t))this.bvh.setRecords(r,e),r+=e.length/16;this._offsetBLASInPlace(n,r-n,n,A.tplTriOffset[e]),A.blasData.delete(e),await P?.(r),e%F===0&&this._sampleMemory(`assembling ${e}/${A.templateCount}`)}s&&await this._writeCopyRecords(P),await P?.(j,!0),S&&await S.blasStore.dispose()}if(s&&x&&await this._writeCopyRecords(null),this._setBVHData(this.bvh.materializeAll()),x)for(let[e,t]of x.orders)A.bvhToOriginal.set(e,t);else this._buildBvhToOriginalMaps();this.performanceMetrics.bvhAssembleTime=performance.now()-N,A.originalToBvhMap.clear(),A.blasData.clear(),this.bvhRoot=!0,this._disposeRefitWorker();let I=performance.now()-e;Kc.debug(V.list([`${V.n(A.setCount)} BLASes + TLAS`,`${V.n(this.bvh.recordCount)} nodes`,`SAH ${V.n(O.sah)} · objMed ${O.objMed} · spatMed ${O.spatMed} · failed ${O.failed}`,V.ms(I)])),z({status:`BVH construction complete`,progress:75})}catch(e){throw Kc.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>=Ic&&La(e.count)}async _buildLargeBLAS(e,t){if(e.count>Lc)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 Pa(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 gc(n,e.start,e.count,Rc,{pause:()=>new Promise(e=>setTimeout(e,0))}),o=this._blasPool(t,null,null,Math.min(Or(),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),Ka.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{...bc(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:${Cc}:${JSON.stringify(t)}:${n}:${this._sceneKey}`}async _restoreBLASes(e,t,n){if(!this._sceneKey||this.config.sceneCache===!1)return null;let r=ni(si().cacheNamespace);if(!r)return null;this._blasKey=this._blasCacheKey(n);let i=await cc(r,this._blasKey);if(!i)return null;let a=e=>(Kc.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 sc(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 dc(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},Kc.debug(`restored ${V.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=ni(si().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 sc(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 lc(t,r,{index:{v:2,tlasNodeCount:n.blasBase,totalNodes:n.treeNodeCount,templates:d},bvh:this.bvh,orders:u,isStale:a,label:e});return f&&Kc.debug(`stored ${V.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 vn.create(t,`${i}:tri`,a,{label:`Triangle records`,expectedBytes:r.byteLength}),s=o&&await vn.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`,{textureCoordinates:this.textureCoordinates}),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(Jc(a)[0],t,this.triangles,i.tplObjectAABB,t*6);let o=e.blasBytes;e.blasBytes+=Yc(a),e.blasAt.set(t,o),r.nodeCount=Yc(a)/64,r.bvhData=null,this._queueSpill(e,()=>Zc(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;await 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+=Xc)i.push(new Float32Array(await e.blasStore.readAt(n+t,Math.min(Xc,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 vn.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),this._bvhSpillStore=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),await 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),await 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);Ui(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=Mr(Ea);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 Kc.error(`texture creation failed:`,e),e}}_bucketTextures(){let e=this.config.maxTextureSize,t=Qt.MATERIAL_BUCKET_COUNT,n=Qt.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.clearcoatNormalMaps,this.sheenRoughnessMaps,this.iridescenceMaps,this.iridescenceThicknessMaps,this.specularIntensityMaps,this.diffuseTransmissionMaps],o=Y(r(i),e,t),s=Y(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(X.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=Xt(e.image.width,e.image.height,a),s=e.source?.uuid??e.uuid,c=r[o].get(s);if(c!==void 0)return Zt(o,c);if(t[o].length>=n)return Kc.warn(`texture bucket ${o} full (${n}); dropping a map`),f||this.config.issues?.record(X.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=Zt(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),clearcoatNormal:h(this.clearcoatNormalMaps,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.clearcoatNormalMap=t(n.clearcoatNormalMap,e.clearcoatNormal),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._disposeMatrixSpill(),this._orderSpill?.store.dispose().catch(()=>{}),this._orderSpill=null,this._spilledAfterLoad=!1,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.clearcoatNormalMaps=[],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){Kc.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._adoptTextureLists(n),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 Kc.error(`material rebuild failed:`,e),e}finally{this.isProcessing=!1}}_adoptTextureLists(e){for(let t of qc)this[t]=e[t]??[]}_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=dn.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.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||=Mr(jc),!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=[],l=0;for(let e=0;e<i.count;e++){if(!i.isSet[e]||!i.isOwner(e))continue;l++;let t=n(e);if(!t)continue;if(this._updateMeshTrianglePositions(e,t),s.push(i.blasOffsetOf(e),i.blasNodeCountOf(e)),c.push(e),r){let t=r(e);t&&this._patchMeshSmoothNormals(e,t)}let u=i.triOffsetOf(e)*a,d=i.triCountOf(e)*a,f=o.at(-1);f&&f.offset+f.count===u?f.count+=d:o.push({offset:u,count:d})}let u=i.tlasNodeCount,d=u>0&&s.length/2<l,f=d?[this.computeTLASDirtyRange()]:null;for(let e=0;d&&e<s.length;e+=2)f.push({offset:s[e]*16,count:s[e+1]*16});return new Promise((e,t)=>{this._refitWorker.onmessage=n=>{let r=n.data;if(r.type===`refitComplete`){for(let e of c)i.recomputeAABB(e,this.bvh,this.triangles);i.computeGroupAABBs();let t=this._hiddenGroupLeaves();t.length&&this._refitTLAS(t),e({refitTimeMs:r.refitTimeMs,triRanges:o,bvhRanges:f})}else r.type===`error`&&t(Error(r.error))},this._refitWorker.postMessage({type:`refit`,blasRanges:d?s:null,tlasNodeCount:u,groupRange:i.groupNodeCount?[i.groupNodeStart,i.groupNodeCount]:null,treeNodeCount:i.treeNodeCount,recordNodeStart:i.clusterCount?i.recordNodeStart:-1})})}_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 Ca;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(X.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._writeGroupNodes(),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),i=[];for(let t of this._withGroupSiblings(e)){let e=this.meshes?.[t],a=n.placementRunOf(t);if(!e||!a)continue;e.updateMatrixWorld(!0);let o=e.matrixWorld.elements,s=e.isInstancedMesh?e.instanceMatrix?.array??null:null,c=n.tplBakeInverse?.get(n.sourceMesh[a.start])??null;for(let e=0;e<a.count;e++){let t=a.start+e;if(!n.isSet[t])continue;s?(Ha(o,s,e*16,r),n.setPlacementMatrix(t,r)):c?(Ha(o,c,0,r),n.setPlacementMatrix(t,r)):n.setPlacementMatrix(t,o),this._writeLeafMatrix(t);let l=n.leafOfPlacement(t);l>=0&&i.push(l)}}return this._refitTLAS(i),{refitTimeMs:performance.now()-t,placements:i.length}}_hiddenGroupLeaves(){let e=this.instanceTable,t=[];for(let n of e.groups)if(!n.members.every((t,r)=>e.visible[n.starts[r]]))for(let r=0;r<n.count;r++)t.push(e.leafOfPlacement(n.starts[0]+r));return t}_withGroupSiblings(e){let t=this.instanceTable;if(!t.groups.length)return e;let n=new Set(e),i=new Set,a=this._parentInverse??=new r.Matrix4;for(let r of e){let e=t.groupOfTemplate[r]??-1;if(e<0||i.has(e))continue;i.add(e);let o=this.meshes?.[r];if(o){o.updateMatrixWorld(!0);for(let r of t.groups[e].members){n.add(r);let e=this.meshes[r];!e||e===o||(e.parent&&e.parent.updateMatrixWorld(!0),e.matrix.copy(o.matrixWorld),e.parent&&e.matrix.premultiply(a.copy(e.parent.matrixWorld).invert()),e.matrix.decompose(e.position,e.quaternion,e.scale),e.updateMatrixWorld(!0))}}}return n}_writeLeafMatrix(e){let t=this.instanceTable,n=t.tlasLeafIndex[e];if(!(n<0)){if(t.clusterCount){this._writeCopyRecord(n,t.repOf(t.entryOf(e)));return}so.writeLeafMatrix(this.bvh.chunkFor(n),this.bvhIndexChunks.chunkFor(n),this.bvh.baseOf(n),t,e,t.entryOf(e))}}_writeCopyRecord(e,t){let n=this.instanceTable,r=this._recordScratch??=new Float32Array(12);n.writeRecord(r,0,t);let i=n.recordNodeStart*16+e*3*4;for(let e=0;e<12;e++){let t=i+e>>4;this.bvh.chunkFor(t)[this.bvh.baseOf(t)+(i+e&15)]=r[e]}let a=n.clusterLeaf[n.clusterOf(e)],o=this.bvhIndexChunks.chunkFor(a),s=this.bvh.baseOf(a)+n.copyWordSlot(e),c=Ua(n.matrixWorldOf(t));o[s]=(o[s]&~Ct|(c?Ct:0))>>>0;let l=this._movedRecords??=new Map,u=this.bvh.recordsPerChunk*16;for(let e=i,t=i+12;e<t;){let n=Math.floor(e/u),r=Math.min(t,(n+1)*u),i=l.get(n);i?(i.lo=Math.min(i.lo,e),i.hi=Math.max(i.hi,r)):l.set(n,{lo:e,hi:r}),e=r}}takeMoveRanges(){let e=this._tlasRanges??[this.computeTLASDirtyRange()];return this._tlasRanges=null,[...e,...this.takeMovedRecordRanges()]}takeMovedRecordRanges(){let e=this._movedRecords;return this._movedRecords=null,e?[...e.values()].map(e=>({offset:e.lo,count:e.hi-e.lo})):[]}_writeGroupNodes(){let e=this.instanceTable;!e?.groupNodeCount||!this.bvh||(e.computeGroupAABBs(),this.bvh.setRecords(e.groupNodeStart,e.groupNodeBlock()))}computeTLASDirtyRange(){return{offset:0,count:this.instanceTable.blasBase*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.blasBase*16}),{triRanges:n,bvhRanges:r}}async uploadChunks(e){for(let[t,n]of[[this.triangles,`triangles`],[this.bvh,`bvh`]]){if(!t?.chunks||t.chunks.length<2||t._gpuUpload)continue;let r=e(t,n,{textureCoordinates:this.textureCoordinates});for(let e=0;e<t.chunks.length;e++)t.chunks[e]&&await r(e)}}uploadToPathTracer(e,t,n,r,{keepUserLights:i=!1}={}){return this.triangles?(e.setTriangleData(this.triangles,this.triangleCount,{textureCoordinates:this.textureCoordinates}),this.bvh?(e.setBVHData(this.bvh),e.setInstanceTable(this.instanceTable),this.materialData?e.materialData.setMaterialData(this.materialData,this.materials.map(e=>e.sources)):Kc.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):(Kc.error(`failed to get BVH data`),!1)):(Kc.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||this._orderSpill)}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 vn.create(e,`${a}:tri`,o(t),{label:`Triangle records`,expectedBytes:t.byteLength}),c=s&&await vn.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?.blasBase??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 Kc.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?.(),await this._restoreOrderMaps(),this.spilled||this._disposeSpill()})().finally(()=>{this._paging=null}),this._paging}get geometryOnDisk(){return!!this._geometryOwner}ensureGeometryResident(){let e=this._geometryOwner?this._geometryReading??=this._restoreGeometry(this._geometryOwner).finally(()=>{this._geometryReading=null}):null;return Promise.all([e,this.ensureMovable()])}get matricesOnDisk(){return!!this._matrixSpill}async ensureMovable(e=[]){this._movePageIns=(this._movePageIns??0)+1;try{await this._afterLoadSpill;let t=this._matrixSpill;t&&await(this._matrixReading??=t.restore().then(()=>this._disposeMatrixSpill()).finally(()=>{this._matrixReading=null}));let n=this.instanceTable,r=this.bvh;if(!e.length||!n||!r?.spilledChunks)return;await r.ensureResident(0,n.blasBase);for(let t of this._recordChunksOf(e))await r.ensureResident(t*r.recordsPerChunk,1)}finally{this._movePageIns--}}async _spillMatrices(e=!1){let t=this.instanceTable,n=t?.adoptedMatrices()??[],i=this._spillMeshBounds;if(this._spillMeshBounds=null,!n.length||!this._progressive?.storage)return;let a=await Dn.create(this._progressive.storage,`spill:${Date.now().toString(36)}:${Math.random().toString(36).slice(2)}:mat`);if(!a)return;for(let[n,a]of i??this._instancedMeshBounds((e,n)=>t.writeEntryWorldAABB(e,n,0),e))n.boundingBox=new r.Box3(new r.Vector3(a[0],a[1],a[2]),new r.Vector3(a[3],a[4],a[5])),n.boundingSphere=n.boundingBox.getBoundingSphere(new r.Sphere);let o=n.reduce((e,t)=>e+t.array.byteLength,0);a.addAttributes(n),this._matrixSpill=a,Kc.info(`${V.mb(o)} of instance matrices left for disk`)}async _spillTLAS(){let e=this.instanceTable,t=this.bvh,n=this._bvhSpillStore;if(!n||!e?.clusterCount)return;let r=t.recordsPerChunk,i=e.groupNodeStart/r|0,a=(e.groupNodeStart+Math.max(1,e.groupNodeCount)-1)/r|0;this._spilledRootBounds=this.sceneBounds();let o=await t.spill(n,{keep:t=>e.groupNodeCount>0&&t>=i&&t<=a});Kc.info(`spilled ${V.mb(o)} of TLAS to disk`)}async _spillOrderMaps(){let e=this.instanceTable,t=this._progressive?.storage;if(!e?.bvhToOriginal.size||!t)return;let n=0;for(let t of e.bvhToOriginal.values())n+=t.byteLength;let r=await vn.create(t,`spill:${Date.now().toString(36)}:${Math.random().toString(36).slice(2)}:order`,0,{label:`Triangle order maps`,expectedBytes:n});if(!r)return;let i=[],a=new Uint8Array(Uc),o=0,s=0,c=async()=>{s&&await r.writeAt(o-s,a.subarray(0,s)),s=0};for(let[t,n]of e.bvhToOriginal){let e=new Uint8Array(n.buffer,n.byteOffset,n.byteLength);i.push(t,o,n.length),s+e.length>a.length&&await c(),e.length>a.length?await r.writeAt(o,e):(a.set(e,s),s+=e.length),o+=e.length}await c(),await r.flush(),e.bvhToOriginal.clear(),this._orderSpill={store:r,index:i,bytes:n}}async _restoreOrderMaps(){let e=this._orderSpill;if(!e)return;this._orderSpill=null;let{store:t,index:n,bytes:r}=e,i=this.instanceTable.bvhToOriginal,a=0,o=null;for(let e=0;e<n.length;e+=3){let s=n[e],c=n[e+1],l=n[e+2]*4;if(l>Wc){i.set(s,new Uint32Array(await t.readAt(c,l)));continue}(!o||c+l>a+o.byteLength)&&(a=c,o=await t.readAt(c,Math.min(Wc,r-c))),i.set(s,new Uint32Array(o.slice(c-a,c-a+l)))}await t.dispose()}spillAfterLoad(){return!this._geometryOwner||this._spilledAfterLoad?this._afterLoadSpill??Promise.resolve():(this._spilledAfterLoad=!0,this._spillUnused(!1))}respill(){return!this._geometryOwner||!this._spilledAfterLoad||this._afterLoadSpill?this._afterLoadSpill??Promise.resolve():this._matrixReading||this._tlasReading||this._movePageIns?Promise.resolve():this._spillUnused(!0)}_spillUnused(e){return this._afterLoadSpill=(async()=>{await this._spillMatrices(e),await this._spillTLAS(),await this._spillOrderMaps()})().finally(()=>{this._afterLoadSpill=null}),this._afterLoadSpill}whenTLASEditable(){if(this._afterLoadSpill)return this._afterLoadSpill.then(()=>this.whenTLASEditable());let e=this.bvh,t=this.instanceTable;return!e||!t||e.isResident(0,t.blasBase)?null:this._tlasReading??=e.ensureResident(0,t.blasBase).finally(()=>{this._tlasReading=null})}needsPageInForMove(e){if(this._matrixSpill||this._afterLoadSpill)return!0;let t=this.instanceTable,n=this.bvh;if(!t||!n?.spilledChunks)return!1;if(!n.isResident(0,t.blasBase))return!0;for(let t of this._recordChunksOf(e))if(!n.isResident(t*n.recordsPerChunk,1))return!0;return!1}_recordChunksOf(e){let t=this.instanceTable,n=this.bvh.recordsPerChunk,r=new Set;if(!t.clusterCount)return r;let i=new Set(e);for(let n of e){let e=t.groupOfTemplate?.[n]??-1;if(e>=0)for(let n of t.groups[e].members)i.add(n)}for(let e of i){let i=t.placementRunOf(e);if(i)for(let e=i.start;e<i.start+i.count;e++){let i=t.tlasLeafIndex[e];if(i<0)continue;let a=t.recordNodeStart*16+i*3*4;r.add(Math.floor(a/16/n)),r.add(Math.floor((a+11)/16/n))}}return r}_instancedMeshBounds(e,t=!1){let n=this.instanceTable,r=new Set(n.adoptedMatrices()),i=new Map,a=new Float64Array(6);return(this.meshes??[]).forEach((o,s)=>{if(!o?.isInstancedMesh||!r.has(o.instanceMatrix)||t&&o.boundingBox)return;let c=n.placementRunOf(s);if(!c)return;let l=[1/0,1/0,1/0,-1/0,-1/0,-1/0];for(let t=c.start;t<c.start+c.count;t++){e(n.entryOf(t),a);for(let e=0;e<3;e++)a[e]<l[e]&&(l[e]=a[e]),a[3+e]>l[3+e]&&(l[3+e]=a[3+e])}i.set(o,l)}),i}_disposeMatrixSpill(){let e=this._matrixSpill;this._matrixSpill=null,e?.dispose().catch(()=>{})}async _restoreGeometry(e){let t=this._geometrySpill;if(!t?.bytes){this._geometryOwner=null;return}this._geometryOwner||z({status:`Reading scene geometry back...`,progress:84});let n=performance.now(),r=t.bytes;await t.restore(),this._disposeGeometrySpill(),this._geometryBytes=Mn(e),Kc.info(`read ${V.mb(r)} of scene geometry back from disk in ${V.ms(performance.now()-n)}`),t.error&&Kc.warn(`some scene geometry stayed in memory, its spill write failed:`,t.error)}_disposeGeometrySpill(){let e=this._geometrySpill;this._geometrySpill=null,this._geometryOwner=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)}_clusterCopies(e){let t=this.config.clusterCopies??`auto`;return t===`auto`?e.entryCount>=Bc:t===!0}async _writeCopyRecords(e){let t=this.instanceTable,n=t.entryCount,r=4096,i=r*3/4,a=new Float32Array(i*16);for(let o=0;o<n;o+=r){let s=Math.min(r,n-o);a.fill(0);for(let e=0;e<s;e++)t.writeRecord(a,e*3*4,t.repOf(t.recordEntry[o+e]));let c=t.recordNodeStart+o*3/4,l=Math.ceil(s*3/4);this.bvh.setRecords(c,l===i?a:a.subarray(0,l*16)),await e?.(c+l)}}async _buildTLAS(e){let t=e.clusterCount>0,n=t?e.clusterCount:e.entryCount;if(n>=Fc&&!this._tlasWorkerFailed)try{let r=t?e.clusterBounds:new Float64Array(n*6);t||e.writeEntryWorldAABBs(r);let{tlasData:i,nodeCount:a}=await this._runTLASWorker(r,n);return so.fillLeaves(i,a,e),i}catch(e){this._tlasWorkerFailed=!0,Kc.warn(`TLAS worker unavailable (${e.message}); building on the main thread`)}return this.tlasBuilder.build(e).data}_runTLASWorker(e,t){this._tlasWorker||=Mr(Pc);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){let t=e?e instanceof dn?e:dn.adopt([e],e.length/16,16,e.length/16):null;this.bvh=t,t&&this._foldLeaves&&(t.foldedLeaves=!0),t&&this.instanceTable?.clusterCount&&(t.copyRecordBase=this.instanceTable.recordNodeStart*4),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 dn?e:dn.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=ht(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]]=ht(f,p,m)}}}_refitTLAS(e=null){let t=this.instanceTable,n=t.tlasNodeCount,r=e?Int32Array.from(e).sort():null;if(this._tlasRanges=r?[]:null,!n||r?.length===0)return;let i=r?Array.from(r):null,a=this._refitStack??=new Int32Array(256),o=0,s=0,c=this._refitBox??=new Float32Array(6),l=(e,t,n,r)=>{if(o+4>a.length){let e=new Int32Array(a.length*2);e.set(a),a=this._refitStack=e}a[o++]=e,a[o++]=t,a[o++]=n,a[o++]=r};for(l(0,n,-1,0);o;){let e=a[--o],n=a[--o],u=a[--o],d=a[--o],f=this.bvh.chunkFor(d),p=this.bvh.baseOf(d);if(e)c[0]=Math.min(f[p],f[p+8]),c[1]=Math.min(f[p+1],f[p+9]),c[2]=Math.min(f[p+2],f[p+10]),c[3]=Math.max(f[p+4],f[p+12]),c[4]=Math.max(f[p+5],f[p+13]),c[5]=Math.max(f[p+6],f[p+14]);else{if(r){for(;s<r.length&&r[s]<d;)s++;if(s===r.length||r[s]>=u)continue}let e=this.bvhIndexChunks.chunkFor(d),i=e[p+3];if(i===Tt.BLAS_POINTER_LEAF){let n=e[p+1]&wt;if(n>=t.entryCount)continue;t.writeEntryWorldAABB(n,c,0)}else if(i===Tt.CLUSTER_LEAF)t.encodeClusterBoxes(f,e,p,t.clusterOf(e[p]&Et),null,c,0);else if(i<Tt.TRIANGLE_LEAF){let t=e[p+7];l(d,u,n,1),l(t,u,d*2+1,0),l(i,t,d*2,0);continue}else continue}if(n<0)continue;let m=n>>1,h=this.bvh.chunkFor(m),g=this.bvh.baseOf(m)+(n&1)*8;h[g]=c[0],h[g+1]=c[1],h[g+2]=c[2],h[g+4]=c[3],h[g+5]=c[4],h[g+6]=c[5],i?.push(m)}i&&(this._tlasRanges=tl(i))}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){Kc.error(`background BLAS rebuild failed (mesh ${e}):`,o.error);return}n===this._rebuildGeneration&&this._swapBLAS(e,r,o,t)},i.onerror=t=>{Kc.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,foldLeaves:this._foldLeaves===!0,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,Mr(Ea))}}_swapBLAS(e,t,n,r){this._geometryVersion=(this._geometryVersion??0)+1;let i=n.bvhData,a=i.length/16;if(a>t.blasNodeCount){Kc.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}},rl=[[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]],il=[[-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]],al=[[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 ol(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=rl[i],o=il[i],s=al[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)]}tr();var sl=1/(4*Math.PI);function cl(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]=ol(t.temperature??6500);i[0]*=e,i[1]*=n,i[2]*=r}return Zn(i),{r:i[0],g:i[1],b:i[2],intensity:r}}var ll=e=>Math.max(0,Number(e.userData?.radius)||0),ul=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=cl(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=cl(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=cl(e);this.pointLightCache.push({data:[t.x,t.y,t.z,i.r,i.g,i.b,i.intensity*sl,e.distance||0,e.decay===void 0?2:e.decay,ll(e)],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=cl(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*sl,e.angle||Math.PI/4,e.penumbra||0,e.distance||0,e.decay===void 0?2:e.decay,o,c,u,d,ll(e),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}))}}},dl,fl,pl,ml,hl,gl,_l,vl,yl,bl,xl,Sl,Cl,wl,Tl,El,Dl=g((()=>{dl=x({origin:`vec3`,direction:`vec3`}),fl=x({color:`vec4`,emissive:`vec3`,emissiveIntensity:`float`,roughness:`float`,metalness:`float`,ior:`float`,transmission:`float`,thickness:`float`,clearcoat:`float`,clearcoatRoughness:`float`,clearcoatNormalMapIndex:`int`,clearcoatNormalScale:`float`,clearcoatNormal:`vec3`,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`,displacementBias:`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`,diffuseRoughness:`float`}),pl=x({transmission:`float`,clearcoat:`float`,clearcoatRoughness:`float`,sheenColor:`vec3`,sheenRoughness:`float`,iridescence:`float`,iridescenceThickness:`float`,specularIntensity:`float`,specularColor:`vec3`,diffuseTransmission:`float`,diffuseTransmissionColor:`vec3`}),ml=x({color:`vec4`,ior:`float`,transmission:`float`,attenuationColor:`vec3`,attenuationDistance:`float`,albedoMapIndex:`int`,opacity:`float`,transparent:`bool`,alphaTest:`float`,alphaMode:`int`,albedoTransform:`mat3`}),hl=x({shadowed:`vec3`,unoccluded:`vec3`}),x({position:`vec3`,radius:`float`,material:fl}),gl=x({didHit:`bool`,dst:`float`,hitPoint:`vec3`,normal:`vec3`,uv:`vec2`,materialIndex:`int`,meshIndex:`int`,instanceLeaf:`int`,triangleIndex:`int`,boxTests:`int`,triTests:`int`}),x({posA:`vec3`,posB:`vec3`,posC:`vec3`,uvA:`vec2`,uvB:`vec2`,uvC:`vec2`,normalA:`vec3`,normalB:`vec3`,normalC:`vec3`,material:fl,materialIndex:`int`,meshIndex:`int`}),x({color:`vec4`,samples:`int`}),_l=x({direction:`vec3`,value:`vec3`,pdf:`float`,isTransmission:`bool`,colorWeight:`vec3`,isDiffuseTransmission:`bool`}),vl=x({specular:`float`,diffuse:`float`,sheen:`float`,clearcoat:`float`,transmission:`float`,iridescence:`float`,diffuseTransmission:`float`}),yl=x({Ta:`vec3`,Ba:`vec3`}),bl=x({NoL:`float`,NoV:`float`,NoH:`float`,VoH:`float`,LoH:`float`,ToH:`float`,BoH:`float`,ToV:`float`,BoV:`float`,ToL:`float`,BoL:`float`,coatNoL:`float`,coatNoV:`float`,coatNoH:`float`}),xl=x({compensation:`vec3`,E_total:`vec3`}),Sl=x({f0:`vec3`,f90:`float`,eta:`float`,F0m:`vec3`,F0:`vec3`}),Cl=x({albedo:`vec4`,emissive:`vec3`,metalness:`float`,roughness:`float`,normal:`vec3`,hasTextures:`bool`}),wl=x({isMetallic:`bool`,isRough:`bool`,isSmooth:`bool`,isTransmissive:`bool`,hasClearcoat:`bool`,isEmissive:`bool`,complexityScore:`float`}),Tl=x({albedoUV:`vec2`,normalUV:`vec2`,metalnessUV:`vec2`,emissiveUV:`vec2`,bumpUV:`vec2`,roughnessUV:`vec2`,normalBumpSameUV:`bool`,metalRoughSameUV:`bool`,albedoEmissiveSameUV:`bool`,allSameUV:`bool`}),El=x({invRoughness:`float`,metalFactor:`float`,iorFactor:`float`,maxSheenColor:`float`}),x({traversals:`int`,transmissiveTraversals:`int`,rayType:`int`,isPrimaryRay:`bool`,actualBounceDepth:`int`})}));function Ol(e,t,n){return e.length===1?e[0]:{isSplitStorage:!0,parts:e,perPart:t,type:n,value:e[0].value}}function kl(e,t,r){let{parts:i,perPart:a}=e,o=(0,n.int)(t).toVar(),s=r.map(()=>({uvec4:n.uvec4,uvec2:n.uvec2}[e.type]??n.vec4)(0).toVar()),c=e=>()=>{let t=e===0?o:o.sub((0,n.int)(a*e));r.forEach((r,a)=>s[a].assign(i[e].element(r===0?t:t.add((0,n.int)(r)))))},l=(0,n.If)(o.lessThan((0,n.int)(a)),c(0));for(let e=1;e<i.length-1;e++)l=l.ElseIf(o.lessThan((0,n.int)(a*(e+1))),c(e));return l.Else(c(i.length-1)),s}function Al(e,t){return e.isSplitStorage?kl(e,t,[0])[0]:e.element(t)}var jl,Ml,Nl,Pl,Fl,Il,Ll,Rl,zl,Bl,Vl,Hl,Ul,Wl,Gl,Kl,ql,Jl,Yl,Xl,Zl,Ql,$l,eu,tu,nu,ru,iu,au,ou,su,cu,lu,uu,du,fu,pu,mu,hu,gu,_u,vu,yu,bu,xu=g((()=>{Dl(),pr(),Ft(),jl=(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 );
|
|
@@ -855,7 +855,7 @@ ${t?`
|
|
|
855
855
|
let ndcDepth = clipPos.z / clipPos.w * 0.5f + 0.5f;
|
|
856
856
|
return clamp( ndcDepth, 0.0f, 1.0f );
|
|
857
857
|
}
|
|
858
|
-
`),x_=(0,n.Fn)(([e,t,r,i,a,o,s,c,l,u,d,f,p,m,h,g])=>{let _=(0,n.vec4)(1,0,1,1).toVar(),v=dl({origin:e,direction:t}),y=gl.wrap(Rf(v,r,i).toVar());return(0,n.If)(u.equal((0,n.int)(7)),()=>{let e=(0,n.float)(y.triTests).div(d);_.assign((0,n.select)(e.lessThan(1),(0,n.vec4)((0,n.vec3)(e),1),(0,n.vec4)(1,0,0,1)))}),(0,n.If)(u.equal((0,n.int)(8)),()=>{let e=(0,n.float)(y.boxTests).div(d);_.assign((0,n.select)(e.lessThan(1),(0,n.vec4)((0,n.vec3)(e),1),(0,n.vec4)(1,0,0,1)))}),(0,n.If)(u.equal((0,n.int)(10)),()=>{(0,n.If)(l,()=>{let e=rp({tex:o,samp:(0,n.sampler)(o),direction:t,environmentMatrix:s,environmentIntensity:c,enableEnvironmentLight:l}).toVar(),r=(0,n.dot)(e.xyz,Bl).toVar(),i=r,a=(0,n.max)(d.mul(.1),.001),u=r.div(a),m=(0,n.log)(r.add(1e-6)).add(10).div(10),h=(0,n.select)(d.greaterThan(1),u,m).toVar(),g=(0,n.vec3)(0).toVar();(0,n.If)(h.lessThan(.2),()=>{g.assign((0,n.mix)((0,n.vec3)(0,0,0),(0,n.vec3)(0,0,.5),h.mul(5)))}).ElseIf(h.lessThan(.4),()=>{g.assign((0,n.mix)((0,n.vec3)(0,0,.5),(0,n.vec3)(0,0,1),h.sub(.2).mul(5)))}).ElseIf(h.lessThan(.6),()=>{g.assign((0,n.mix)((0,n.vec3)(0,0,1),(0,n.vec3)(0,1,0),h.sub(.4).mul(5)))}).ElseIf(h.lessThan(.8),()=>{g.assign((0,n.mix)((0,n.vec3)(0,1,0),(0,n.vec3)(1,1,0),h.sub(.6).mul(5)))}).ElseIf(h.lessThan(1),()=>{g.assign((0,n.mix)((0,n.vec3)(1,1,0),(0,n.vec3)(1,0,0),h.sub(.8).mul(5)))}).Else(()=>{g.assign((0,n.mix)((0,n.vec3)(1,0,0),(0,n.vec3)(1,1,1),(0,n.min)(h.sub(1),1)))});let v=f.div(p);(0,n.If)(v.x.lessThan(.1).and(v.y.lessThan(.1)),()=>{let e=i.mul(1);g.assign((0,n.vec3)(e))}).ElseIf(v.x.greaterThan(.9).and(v.y.lessThan(.1)),()=>{g.assign(e.xyz.mul(1))}),_.assign((0,n.vec4)(g,1))}).Else(()=>{_.assign((0,n.vec4)(1,0,1,1))})}),(0,n.If)(u.equal((0,n.int)(4)),()=>{(0,n.If)(y.didHit.not(),()=>{_.assign((0,n.vec4)(0,0,0,1))}).Else(()=>{let t=fl.wrap(fu(y.materialIndex,a)).toVar(),r=Cl.wrap(Np(t,y.uv,y.normal,(0,n.vec4)(0))).toVar().emissive.toVar(),i=(0,n.length)(r).toVar();(0,n.If)(i.greaterThan(0),()=>{let t=r.div((0,n.max)(i.mul(.1),.001)).toVar(),a=(0,n.length)(e.sub(y.hitPoint)),o=(0,n.clamp)((0,n.float)(1).sub(a.div(10)),0,1),s=(0,n.mix)(t,t.mul((0,n.vec3)(1,.8,.6)),o.mul(.3));_.assign((0,n.vec4)(s,1))}).Else(()=>{_.assign((0,n.vec4)(0,0,.1,1))})})}),(0,n.If)(u.equal((0,n.int)(1)),()=>{(0,n.If)(y.didHit.not(),()=>{_.assign((0,n.vec4)(.5,.5,1,1))}).Else(()=>{let e=fl.wrap(fu(y.materialIndex,a)).toVar(),t=(0,n.normalize)(Cl.wrap(Np(e,y.uv,y.normal,(0,n.vec4)(0))).toVar().normal);_.assign((0,n.vec4)(y_({normal:t}),1))})}),(0,n.If)(u.equal((0,n.int)(2)),()=>{(0,n.If)(y.didHit.not(),()=>{_.assign((0,n.vec4)((0,n.vec3)(1),1))}).Else(()=>{let e=b_({worldPos:y.hitPoint,cameraProjectionMatrix:m,cameraViewMatrix:h});_.assign((0,n.vec4)(v_({depth:e}),1))})}),(0,n.If)(u.equal((0,n.int)(3)),()=>{(0,n.If)(y.didHit.not(),()=>{_.assign((0,n.vec4)(0,0,0,1))}).Else(()=>{let e=fl.wrap(fu(y.materialIndex,a)).toVar(),t=Cl.wrap(Np(e,y.uv,y.normal,(0,n.vec4)(0))).toVar().albedo.rgb;_.assign((0,n.vec4)(t,1))})}),(0,n.If)(u.equal((0,n.int)(5)),()=>{(0,n.If)(y.didHit.not(),()=>{_.assign((0,n.vec4)(0,0,0,1))}).Else(()=>{let e=fl.wrap(fu(y.materialIndex,a)).toVar(),t=Cl.wrap(Np(e,y.uv,y.normal,(0,n.vec4)(0))).toVar(),u=t.albedo.rgb,d=(0,n.normalize)(t.normal).toVar(),p=Be({state:Ve({seed:(0,n.uint)(f.x).mul((0,n.uint)(1973)).add((0,n.uint)(f.y).mul((0,n.uint)(9277))).add(g.mul((0,n.uint)(26699)))})}).toVar(),m=cp({N:d,xi:(0,n.vec2)(Ue(p).toVar(),Ue(p).toVar())}).toVar(),h=dl({origin:jl(y.hitPoint,d),direction:m}),v=gl.wrap(Rf(h,r,i,(0,n.bool)(!1),(0,n.bool)(!1)).toVar()),b=(0,n.vec3)(0).toVar();(0,n.If)(v.didHit.not(),()=>{(0,n.If)(l,()=>{b.assign(rp({tex:o,samp:(0,n.sampler)(o),direction:m,environmentMatrix:s,environmentIntensity:c,enableEnvironmentLight:l}).xyz)})}).Else(()=>{let e=fl.wrap(fu(v.materialIndex,a)).toVar(),t=Cl.wrap(Np(e,v.uv,v.normal,(0,n.vec4)(0))).toVar();b.assign(t.emissive),(0,n.If)(l,()=>{let e=(0,n.normalize)(t.normal).toVar(),r=rp({tex:o,samp:(0,n.sampler)(o),direction:e,environmentMatrix:s,environmentIntensity:c,enableEnvironmentLight:l}).xyz;b.addAssign(t.albedo.rgb.mul(r))})});let x=u.mul(b);_.assign((0,n.vec4)(x,1))})}),(0,n.If)(u.equal((0,n.int)(6)),()=>{(0,n.If)(y.didHit,()=>{let e=y.normal.toVar(),r=(0,n.normalize)(t.sub(e.mul((0,n.dot)(t,e).mul(2)))).toVar(),i=rp({tex:o,samp:(0,n.sampler)(o),direction:r,environmentMatrix:s,environmentIntensity:c,enableEnvironmentLight:l}).xyz,a=i.div(i.add(1));_.assign((0,n.vec4)(a,1))}).Else(()=>{let e=rp({tex:o,samp:(0,n.sampler)(o),direction:t,environmentMatrix:s,environmentIntensity:c,enableEnvironmentLight:l}).xyz,r=e.div(e.add(1));_.assign((0,n.vec4)(r,1))})}),_});Dl();function S_(e){let{writeColorTex:t,writeNDTex:r,writeAlbedoTex:i,resolution:a,renderWidth:o,renderHeight:s,cameraWorldMatrix:c,cameraProjectionMatrixInverse:l,cameraProjectionMatrix:u,cameraViewMatrix:d,cameraProjection:f,panoLonRange:p,panoLatRange:m,panoLevelHorizon:h,enableDOF:g,focalLength:_,aperture:v,focusDistance:y,unitsPerMetre:b,apertureScale:x,anamorphicRatio:S,dofMode:C,dofBlur:w,cameraClipStart:T,bvhBuffer:E,triangleBuffer:D,materialBuffer:O,envTexture:k,environmentMatrix:A,environmentIntensity:j,enableEnvironmentLight:M,visMode:N,debugVisScale:P,frame:F}=e;return(0,n.Fn)(()=>{let e=(0,n.int)(n.workgroupId.x).mul(16).add((0,n.int)(n.localId.x)),I=(0,n.int)(n.workgroupId.y).mul(16).add((0,n.int)(n.localId.y));(0,n.If)(e.lessThan(o).and(I.lessThan(s)),()=>{let o=(0,n.vec2)((0,n.float)(e).add(.5),(0,n.float)(I).add(.5)),s=Be({state:(0,n.uint)(I.mul((0,n.int)(a.x)).add(e)).add((0,n.uint)(1))}).toVar(),L=dl.wrap(pf(o.div(a),s,c,l,f,p,m,h,g,_,v,y,b,x,S,C,w)),ee=(0,n.vec4)(1,0,1,1).toVar();(0,n.If)(N.equal((0,n.int)(9)),()=>{let e=tt(o,(0,n.int)(0),s,a,F);ee.assign((0,n.vec4)(e,1,1))}).Else(()=>{ee.assign(x_(L.origin.add(L.direction.mul(uf(L.direction,T,c,f))),L.direction,E,D,O,k,A,j,M,N,P,o,a,u,d,F))});let te=(0,n.uvec2)((0,n.uint)(e),(0,n.uint)(I));(0,n.textureStore)(t,te,ee).toWriteOnly(),(0,n.textureStore)(r,te,(0,n.vec4)(.5,.5,1,1)).toWriteOnly(),(0,n.textureStore)(i,te,(0,n.vec4)(ee.xyz,1)).toWriteOnly()})})}Vd();function C_({sortGlobalHistogram:e,bins:t=256}){return(0,n.Fn)(()=>{(0,n.If)(n.instanceIndex.lessThan((0,n.uint)(t)),()=>{(0,n.atomicStore)(e.element(n.instanceIndex),(0,n.uint)(0))})})}function w_({hitBufferRO:e,activeIndicesReadRO:t,sortGlobalHistogram:r,counters:i,bins:a=256}){return(0,n.Fn)(()=>{let o=n.instanceIndex,s=n.localId.x,c=(0,n.workgroupArray)(`uint`,a).toAtomic();(0,n.If)(s.lessThan((0,n.uint)(a)),()=>{(0,n.atomicStore)(c.element(s),(0,n.uint)(0))}),(0,n.workgroupBarrier)();let l=(0,n.atomicLoad)(i.element((0,n.uint)(Z.ENTERING_COUNT)));(0,n.If)(o.lessThan(l),()=>{let r=(0,n.uint)(cd(e,t.element(o))).clamp((0,n.uint)(0),(0,n.uint)(a-1));(0,n.atomicAdd)(c.element(r),(0,n.uint)(1))}),(0,n.workgroupBarrier)(),(0,n.If)(s.lessThan((0,n.uint)(a)),()=>{let e=(0,n.atomicLoad)(c.element(s));(0,n.If)(e.greaterThan((0,n.uint)(0)),()=>{(0,n.atomicAdd)(r.element(s),e)})})})}function T_({sortGlobalHistogram:e,bins:t=256}){return(0,n.Fn)(()=>{(0,n.If)(n.instanceIndex.equal((0,n.uint)(0)),()=>{let r=(0,n.uint)(0).toVar();(0,n.Loop)({start:(0,n.uint)(0),end:(0,n.uint)(t),type:`uint`},({i:t})=>{let i=e.element(t),a=(0,n.atomicLoad)(i);(0,n.atomicStore)(i,r),r.addAssign(a)})})})}function E_({hitBufferRO:e,activeIndicesReadRO:t,sortedIndicesRW:r,sortGlobalHistogram:i,counters:a,bins:o=256}){return(0,n.Fn)(()=>{let s=n.instanceIndex,c=n.localId.x,l=(0,n.workgroupArray)(`uint`,o).toAtomic();(0,n.If)(c.lessThan((0,n.uint)(o)),()=>{(0,n.atomicStore)(l.element(c),(0,n.uint)(0))}),(0,n.workgroupBarrier)();let u=(0,n.atomicLoad)(a.element((0,n.uint)(Z.ENTERING_COUNT))),d=s.lessThan(u),f=(0,n.uint)(0).toVar(),p=(0,n.uint)(0).toVar();(0,n.If)(d,()=>{f.assign(t.element(s)),p.assign((0,n.uint)(cd(e,f)).clamp((0,n.uint)(0),(0,n.uint)(o-1))),(0,n.atomicAdd)(l.element(p),(0,n.uint)(1))}),(0,n.workgroupBarrier)(),(0,n.If)(c.lessThan((0,n.uint)(o)),()=>{let e=l.element(c),t=(0,n.atomicLoad)(e);(0,n.If)(t.greaterThan((0,n.uint)(0)),()=>{(0,n.atomicStore)(e,(0,n.atomicAdd)(i.element(c),t))})}),(0,n.workgroupBarrier)(),(0,n.If)(d,()=>{r.element((0,n.atomicAdd)(l.element(p),(0,n.uint)(1))).assign(f)})})}async function D_(e,t,n,r,i=0){let a=await e.readRenderTargetPixelsAsync(t,0,0,n,r,i),o=n*4,s=Math.ceil(o*a.BYTES_PER_ELEMENT/256)*256/a.BYTES_PER_ELEMENT;if(s===o)return a;let c=new a.constructor(o*r);for(let e=0;e<r;e++)c.set(a.subarray(e*s,e*s+o),e*o);return c}var O_=class{constructor(e){this.renderer=e,this.target=null,this.material=new t.NodeMaterial,this.material.name=`rayzee:texture-readback`,this.quad=new t.QuadMesh(this.material),this._node=null,this._source=null}_ensureTarget(e,t){this.target&&this.target.width===e&&this.target.height===t||(this.target?.dispose(),this.target=new r.RenderTarget(e,t,{type:r.FloatType,format:r.RGBAFormat,depthBuffer:!1,minFilter:r.NearestFilter,magFilter:r.NearestFilter}))}async read(e,t,n){try{return await D_(this.renderer,this.draw(e,t,n),t,n)}finally{this.release()}}draw(e,t,r){this._ensureTarget(t,r),this._source!==e&&(this._node=(0,n.texture)(e).load((0,n.ivec2)(n.screenCoordinate.xy)),this.material.outputNode=this._node,this.material.needsUpdate=!0,this._source=e);let i=this.renderer.getRenderTarget();return this.renderer.setRenderTarget(this.target),this.quad.render(this.renderer),this.renderer.setRenderTarget(i),this.target}release(){this.target?.dispose(),this.target=null}dispose(){this.target?.dispose(),this.material.dispose(),this.target=null,this._source=null,this._node=null}};O(),Vd(),pr(),lt(),an(),Ae(),Do();var k_=ve(`wavefront`),A_=[`two`,`one`],j_=[`all`,...A_],M_=[`extend`,`shade`,`connect`,`merge`,`globalHist`,`globalScatter`,`compact`,`compactCopyback`,`lightCopyback`],N_=class extends ku{constructor(e,t,r,i={}){super(e,t,r,i),this.name=`PathTracer`,this._packedBuffers=null,this._queueManager=null,this._kernelManager=null,this._m2Attr=null,this._streakAttr=null,this._frozenMaskAttr=null,this._convDebugSource=null,this._dilateFrozenUniform=(0,n.uniform)(1,`int`),this._wavefrontReady=!1,this._kernelsCompiling=null,this._kernelGeneration=0,this._auxGBufferEnabled=!1,this._auxGBufferUniform=(0,n.uniform)(0,`uint`),this._cleanAuxNormalEnabled=!1,this._cleanAuxNormalUniform=(0,n.uniform)(0,`uint`),this._auxSamples=0,this._auxSeedPending=!1,this._useDynamicDispatch=!0,this.sortMaterials=i.sortMaterials??H.wavefrontSortMaterials,this._sortMaterials=!1,this._useSubgroupCompact=!1,this._lastBounceCounts=null,this._lastBounceEnergy=null,this._lastBounceCountsBudget=-1,this._lastBounceCountsLoopBound=-1,this._readbackPending=!1,this._readbackEveryNFrames=4,this._readbackFrameCounter=0,this._readbackGeneration=0,this._curveSizingValid=!1,this._bounceEarlyExitThreshold=1e-4,this._convergedFraction=0,this._convergedGeometryFraction=0,this._geometryPixelCount=0,this._convergedReadbackPending=!1,this._lockstep=!1,this._lockstepRead=null,this._accumulationLockstep=!1,this._lastActivePixelCount=0,this._wfRenderWidth=(0,n.uniform)(1920,`int`),this._wfRenderHeight=(0,n.uniform)(1080,`int`),this._wfMaxRayCount=(0,n.uniform)(0,`uint`),this._wfCurrentBounce=(0,n.uniform)(0,`int`),this._wfChunkRowBase=(0,n.uniform)(0,`int`),this._wfChunkRows=(0,n.uniform)(0,`int`),this._wfIsFirstChunk=(0,n.uniform)(1,`uint`),this._pathBudget=0,this._pathBudgetOverride=0,this.hostMemoryGB=i.hostMemoryGB,this._chunkRows=0,this._numChunks=1,this._outputs=new Map,this._outputsChanged=!1,this._compiledLayers=null,this._shadowRays=`all`,this._compiledPick=null,this._learnsVisibility=!1,this._integratorFactories=new Map,this._integratorInstances=new Map,this._integrator=null,this.vramTracker=new ef(this.renderer),this._registerVRAMProviders(),k_.debug(`initialized (wavefront)`)}_registerVRAMProviders(){let e=this.vramTracker;e.register(`rays`,()=>{let e=this._packedBuffers?._attrs;return e?[e.ray,e.hit]:null}),e.register(`integrator`,()=>this._integrator?.gpuResources()??null),e.register(`queues`,()=>{let e=this._queueManager;return e?[e._countersAttr,e._bounceCountsAttr,e._attrA,e._attrB,e._sortAttr]:null}),e.register(`gbuffer`,()=>{let e=[];return this._m2Attr&&e.push(this._m2Attr),this._streakAttr&&e.push(this._streakAttr),this._frozenMaskAttr&&e.push(this._frozenMaskAttr),e.length?e:null}),e.register(`accum`,()=>{let e=this.storageTextures;return e?[e.writeColor,e.writeNormalDepth,e.writeAlbedo,e.readTarget]:null}),e.register(`geometry`,()=>[...this._geoParts?.attrs??[],...this._shadeParts?.attrs??[],...this._bvhParts?.attrs??[this.bvhStorageAttr]]),e.register(`materials`,()=>{let e=this.materialData;return e?[e.materialStorageAttr,...(e.srgbBuckets||[]).filter(Boolean),...(e.linearBuckets||[]).filter(Boolean)]:null}),e.register(`environment`,()=>{let e=this.environment;return e?[e.environmentTexture,e.envCDFTexture]:null})}setupMaterial(){super.setupMaterial(),this.materialData?.materialCount>0&&(this._kernelManager&&this._kernelManager.dispose(),this._wavefrontReady=!1,this._buildWavefrontKernels())}requestOutput(e,t={}){return this._outputs.set(e,t),this._outputsChanged=!0,()=>{this._outputs.get(e)===t&&(this._outputs.delete(e),this._outputsChanged=!0)}}registerIntegrator(e,t){for(let n of[e].flat())this._integratorFactories.set(n,t)}setIntegrator(e){let t=null;if(e!==`path`){let n=this._integratorFactories.get(e);if(!n){this.issues?.record(X.CAPABILITY_MISSING,`integrator "${e}" is not installed: pathTracer.registerIntegrator(), or rayzee/addons/bidirectional`,{capability:e});return}t=this._integratorInstances.get(n),t||this._integratorInstances.set(n,t=n(this))}t===this._integrator&&(!t||t.name===e)||(this._integrator&&this._integrator!==t&&this._integrator.dispose(),t?.select(e),this._integrator=t,this._pathBudget=0,this._packedBuffers&&this.materialData?.materialCount>0&&(this._kernelManager&&this._kernelManager.dispose(),this._wavefrontReady=!1,this._buildWavefrontKernels()))}setShadowRays(e){j_.includes(e)||(k_.warn(`shadowRays: unknown mode "${e}", using 'all'`),e=`all`),this._shadowRays!==e&&(this._shadowRays=e,this._outputsChanged=!0)}_pickedShadowRays(){if(this._integrator||!A_.includes(this._shadowRays))return null;let e=this.enableEnvironment.value>0,t=this.numDirectionalLights.value+this.numAreaLights.value+this.numPointLights.value+this.numSpotLights.value;return Number(t>0)+Number(e&&this.envTotalSum.value>0)+Number(e&&this.hasSun.value>0)+Number(this.enableEmissiveTriangleSampling.value>0&&this.emissiveTriangleCount.value>0)>(this._shadowRays===`two`?2:1)?this._shadowRays:null}_lightRadiusNeeded(){if(this._integrator)return!1;let e=(e,t,n)=>{if(!t)return!1;let r=this[`${e}LightsBufferNode`].array;for(let i=0;i<t;i++)if(r[i*dt[e]+n]>0)return!0;return!1};return e(`point`,this.numPointLights.value,9)||e(`spot`,this.numSpotLights.value,18)}get integrator(){return this._integrator?.name??`path`}get activeIntegrator(){return this._integrator}render(e){if(!this.isReady||!this._wavefrontReady)return;if(this._materialFeaturesChanged){this._materialFeaturesChanged=!1;let e=this._layersToCompile();dr.some(t=>e[t]&&!this._compiledLayers?.[t])&&(this._outputsChanged=!0),!this._compiledTransmissionMaps&&this.materialData.hasTransmissionMaps()&&(this._outputsChanged=!0),!this._compiledClearcoatNormals&&this._clearcoatNormalsNeeded()&&(this._outputsChanged=!0)}if(A_.includes(this._shadowRays)&&this._pickedShadowRays()!==this._compiledPick&&(this._outputsChanged=!0),this._lightRadiusNeeded()!==this._compiledLightRadius&&(this._outputsChanged=!0),(this._lightBufferRealloc||this._outputsChanged)&&(this._kernelManager&&this._kernelManager.dispose(),this._wavefrontReady=!1,this._buildWavefrontKernels(),!this._wavefrontReady))return;let t=this._lockstepRead;if(t&&this.frameCount>=t.due){if(!t.apply)return;this._lockstepRead=null,t.apply()}if(this.isComplete||this.frameCount>=this.completionThreshold||this._isConvergedComplete())if(this._auxSeedPending)this.isComplete=!1;else{this.isComplete||=!0;return}this.performanceMonitor?.start();let n=this.frameCount,r=this.renderMode.value,i=null;r===1&&n===0&&(i=this.maxBounces.value,this.maxBounces.value=1),this._handleResize(),this.resetHistoryOnRenderModeChange(r),e&&e.setState(`tileRenderingComplete`,!0),this.cameraChanged=this._updateCameraUniforms(),this.cameraOptimizer?.updateInteractionMode(this.cameraChanged),this.cameraChanged&&(this._curveSizingValid=!1,this._readbackGeneration++,this._convergedFraction=0,this._convergedGeometryFraction=0,this._lastActivePixelCount=0),this._updateAccumulationUniforms(n);let a=this._updateAuxAccumulationUniforms(n);this.frame.value=n,this.seedFrame.value=this._seedTick++,this.tracedFrames++,this._lockstep||(this._accumulationLockstep=!1),this._setWfDispatch();let o=this.storageTextures.getReadTextures();this.shaderBuilder.prevColorTexNode&&(this.shaderBuilder.prevColorTexNode.value=o.color,this.shaderBuilder.prevAlbedoTexNode.value=o.albedo,this.shaderBuilder.prevNormalDepthTexNode.value=o.normalDepth),this._refreshWfTextureNodes();let s=this._kernelManager;if((this.visMode?.value|0)>0&&this.visMode.value!==11){s.dispatch(`debug`),this.storageTextures.copyToReadTargets(this.renderer);let t=this.storageTextures.getReadTextures();e&&this._publishTexturesToContext(e,t),this._emitStateEvents(),this.cameraOptimizer?.isInInteractionMode()||this.frameCount++,i!==null&&(this.maxBounces.value=i),this.performanceMonitor?.end();return}let c=this.maxBounces.value,l=this._bounceLoopBound(),u=this._wfRenderHeight.value,d=this._chunkRows,f=this._numChunks<=1;l>this._lastBounceCountsLoopBound&&(this._curveSizingValid=!1);let p=this._lastBounceCounts,m=c<=this._lastBounceCountsBudget&&l<=this._lastBounceCountsLoopBound,h=f&&p?m?l+1:Math.min(this._lastBounceCountsBudget,this._lastBounceCountsLoopBound):0,g=this._integrator?.beginFrame(l)?this._integrator:null;this._learnsVisibility&&n===0&&(this._pinSeedToFrame||this._lockstep||!this.cameraChanged)&&s.dispatch(`visibilityClear`);for(let e=0,t=0;t<u;t+=d,e++){let r=Math.min(d,u-t),i=this._setChunk(t,r,e),a=this.usePixelFreeze.value>0&&!this._auxSeedPending,o=f&&a&&this._curveSizingValid&&this._lastActivePixelCount>0?this._lastActivePixelCount:i;if(a){let e=Math.min(i,Math.ceil(o*1.5)+1024);s.setDispatchForCount(`generateList`,e),s.dispatch(`resetFrameCounters`),s.dispatch(`buildActivePixels`),s.dispatch(`seedEnter`),s.dispatch(`generateList`)}else s.dispatch(`generate`),s.dispatch(`initActiveIndices`);e===0&&n>0&&this.useAdaptiveSampling.value>0&&this._willReadCountersThisFrame()&&s.dispatch(`countConvergedDilated`);let c=this._lastBounceEnergy,m=this._bounceEarlyExitThreshold>=0?this._bounceEarlyExitThreshold*i*64:-1;for(let e=0;e<=l;e++){this._wfCurrentBounce.value=e;let t=this._useDynamicDispatch;if(t){let t=i;if(f&&e>0&&this._curveSizingValid){let n=e-1,r;n<h&&p[n]!==void 0?r=p[n]:h>0&&(r=p[h-1]),t=r>0?r:i}else e===0&&a&&(t=o);let n=Math.min(i,Math.ceil(t*1.5)+1024);for(let e of M_)s.setDispatchForCount(e,n)}else{s.dispatch(`enterFull`);for(let e of M_)s.setDispatchForCount(e,i)}if(s.dispatch(`extend`),this._sortMaterials&&(s.dispatch(`resetGlobalHist`),s.dispatch(`globalHist`),s.dispatch(`globalPrefix`),s.dispatch(`globalScatter`)),g?.beforeShade(),s.dispatch(`shade`),g?.afterShade(s),s.dispatch(`compact`),t?s.dispatch(`compactCopyback`):s.dispatch(`snapshotBounceCount`),m>=0&&e<h&&e<l&&c?.[e]!==void 0&&c[e]<=m)break}g?.resolve(s),s.dispatch(`finalWrite`)}this._learnsVisibility&&s.dispatch(`visibilityFold`),this._maybeReadbackCounters(),this.storageTextures.copyToReadTargets(this.renderer,this._auxGBufferEnabled);let _=this.storageTextures.getReadTextures();e&&this._publishTexturesToContext(e,_),this._emitStateEvents(),this.cameraOptimizer?.isInInteractionMode()||this.frameCount++,this._auxGBufferEnabled&&(this._auxSamples=a?this._auxSamples+1:1),this._auxSeedPending=!1,i!==null&&(this.maxBounces.value=i),this.performanceMonitor?.end()}_isConvergedComplete(){return this.useAdaptiveSampling.value>0&&this.frameCount>=this.adaptiveMinSamples.value&&this._convergedFraction>=this.adaptiveStopFraction.value&&this._convergedGeometryFraction>=this.adaptiveStopFraction.value}async captureAccumulation(){let e=this.storageTextures,t=e.renderWidth,n=e.renderHeight,r=t*n,i=r=>D_(this.renderer,e.readTarget,t,n,r),a=async(e,t)=>e?new t(await this.renderer.getArrayBufferAsync(e,null,0,r*4)):null,o=this._auxGBufferEnabled&&this._auxSamples>0,s={frameCount:this.frameCount,seedTick:this._seedTick,auxSamples:o?this._auxSamples:0,convergedFraction:this._convergedFraction,convergedGeometryFraction:this._convergedGeometryFraction,isComplete:this.isComplete},c=[i(0),o?i(1):null,o?i(2):null,a(this._m2Attr,Float32Array),a(this._streakAttr,Uint32Array),a(this._frozenMaskAttr,Uint32Array)],[l,u,d,f,p,m]=await Promise.all(c);return{width:t,height:n,state:s,color:l,normalDepth:u,albedo:d,m2:f,streak:p,frozenMask:m}}restoreAccumulation(e){let t=this.storageTextures,{width:n,height:r,state:i}=e;if(t.renderWidth!==n||t.renderHeight!==r)throw Error(`checkpoint is ${n}×${r}; the render is ${t.renderWidth}×${t.renderHeight}`);let a=this.renderer.backend,o=a.device;a.get(t.readTarget.textures[0]).texture||this.renderer.initRenderTarget(t.readTarget);let s=(e,i)=>o.queue.writeTexture({texture:a.get(t.readTarget.textures[e]).texture},i,{bytesPerRow:n*16,rowsPerImage:r},{width:n,height:r}),c=(e,t)=>{e&&t&&o.queue.writeBuffer(a.get(e).buffer,0,t)};s(0,e.color),e.normalDepth&&s(1,e.normalDepth),e.albedo&&s(2,e.albedo),c(this._m2Attr,e.m2),c(this._streakAttr,e.streak),c(this._frozenMaskAttr,e.frozenMask),this.frameCount=i.frameCount,this.frame.value=i.frameCount,this._seedTick=i.seedTick,this.hasPreviousAccumulated.value=+(i.frameCount>0),this._auxSamples=e.normalDepth?i.auxSamples:0,this._auxSeedPending=this._auxGBufferEnabled&&!e.normalDepth,this._convergedFraction=i.convergedFraction??0,this._convergedGeometryFraction=i.convergedGeometryFraction??0,this.isComplete=!1,this._accumulationLockstep=!1}reset(){super.reset(),this._convergedFraction=0,this._convergedGeometryFraction=0,this._lastActivePixelCount=0,this._auxSamples=0,this._auxSeedPending=!1,this._lockstep&&(this._lockstepRead=null,this._readbackGeneration++,this._lastBounceCounts=null,this._lastBounceEnergy=null,this._lastBounceCountsBudget=-1,this._lastBounceCountsLoopBound=-1,this._curveSizingValid=!1)}setLockstepReadbacks(e){e=!!e,e!==this._lockstep&&(this._lockstep=e,this._lockstepRead=null,this._readbackGeneration++)}get lockstepReadbacks(){return this._lockstep}get accumulationLockstep(){return this.frameCount>0?this._accumulationLockstep:this._lockstep}readbackWait(){if(this._kernelsCompiling)return this._kernelsCompiling;let e=this._lockstepRead;return e&&!e.apply&&this.frameCount>=e.due?e.read:null}_compileKernels(){let e=++this._kernelGeneration;if(!nf.canCompileInBackground){this._kernelsCompiling=null,this._wavefrontReady=!0;return}let t=this._kernelManager;this.emit(`pathtracer:compiling`,{compiling:!0}),this._kernelsCompiling=t.compile().catch(e=>k_.warn(`background kernel compile failed — compiling at first dispatch: ${e?.message??e}`)).then(()=>{e===this._kernelGeneration&&(this._kernelsCompiling=null,this._wavefrontReady=!0,this.emit(`pathtracer:compiling`,{compiling:!1}))})}getConvergenceDebugSource(){return!this._m2Attr||!this._frozenMaskAttr?null:(this._convDebugSource?.m2===this._m2Attr&&this._convDebugSource.frozenMask===this._frozenMaskAttr||(this._convDebugSource={m2:this._m2Attr,frozenMask:this._frozenMaskAttr,frame:this.frame,renderWidth:this._wfRenderWidth,renderHeight:this._wfRenderHeight,noiseThreshold:this.noiseThreshold,pixelFreezeThreshold:this.pixelFreezeThreshold,usePixelFreeze:this.usePixelFreeze,adaptiveMinSamples:this.adaptiveMinSamples}),this._convDebugSource)}getConvergenceStats(){let e=this._wfRenderWidth.value*this._wfRenderHeight.value;return{converged:this._convergedFraction,convergedGeometry:this._convergedGeometryFraction,geometryPixels:this._geometryPixelCount,activePixels:this._lastActivePixelCount,totalPixels:e,frame:this.frameCount}}_handleResize(){let e=this.storageTextures.renderWidth,t=this.storageTextures.renderHeight;super._handleResize(),this._rebuildKernelsIfResized(e,t)}setAuxGBufferEnabled(e){e=!!e,e&&!this._outputs.has(`gBuffer`)&&this.requestOutput(`gBuffer`),this._auxGBufferEnabled!==e&&(this._auxGBufferEnabled=e,this._auxGBufferUniform.value=+!!e,this.restartAuxAccumulation())}setCleanAuxNormal(e){e=!!e,this._cleanAuxNormalEnabled!==e&&(this._cleanAuxNormalEnabled=e,this._cleanAuxNormalUniform.value=+!!e,this.restartAuxAccumulation())}restartAuxAccumulation(){this._auxSamples=0,this._auxSeedPending=this._auxGBufferEnabled}_updateAuxAccumulationUniforms(e){let t=this.accumulationEnabled&&!this.cameraIsMoving.value&&e>0&&this.hasPreviousAccumulated.value>0&&this.visMode.value!==11,n=this._auxGBufferEnabled&&t&&!this._auxSeedPending&&this._auxSamples>0;return this.hasPreviousAux.value=+!!n,this.auxAccumulationAlpha.value=n?1/(this._auxSamples+1):1,n}setSize(e,t){let n=this.storageTextures.renderWidth,r=this.storageTextures.renderHeight;super.setSize(e,t),this._rebuildKernelsIfResized(n,r)}_willReadCountersThisFrame(){return this.cameraOptimizer?.isInInteractionMode()?!1:this._lockstep?!this._lockstepRead&&this.frameCount%this._readbackEveryNFrames===0:this.cameraChanged||this._readbackPending||this._convergedReadbackPending?!1:this._readbackFrameCounter+1>=this._readbackEveryNFrames}_bounceLoopBound(){return this.maxBounces.value+this.transmissiveBounces.value+this.maxSubsurfaceSteps.value+1}_maybeReadbackCounters(){if(this._lockstep){this._issueLockstepReadback();return}if(this.cameraChanged||this.cameraOptimizer?.isInInteractionMode()){this._readbackFrameCounter=this._readbackEveryNFrames;return}if(this._readbackPending||((this.maxBounces.value!==this._lastBounceCountsBudget||this._bounceLoopBound()!==this._lastBounceCountsLoopBound)&&(this._readbackFrameCounter=this._readbackEveryNFrames),this._readbackFrameCounter++,this._readbackFrameCounter<this._readbackEveryNFrames))return;this._readbackFrameCounter=0;let e=this._queueManager?.getBounceCountsAttribute();if(!e)return;this._readbackPending=!0;let t=this._readbackGeneration,n=this.maxBounces.value,r=this._bounceLoopBound(),i=this._queueManager.MAX_BOUNCE_SNAPSHOTS,a=this._integrator?.curveKey??null;if(this.renderer.getArrayBufferAsync(e).then(e=>{t===this._readbackGeneration&&this._applyBounceCounts(e,n,r,i,a),this._readbackPending=!1}).catch(e=>{k_.warn(`bounceCounts readback failed:`,e),this._readbackPending=!1}),!this._convergedReadbackPending){let e=this._queueManager?.getCountersAttribute();if(e){this._convergedReadbackPending=!0;let t=this._readbackGeneration,n=this._wfRenderWidth.value*this._wfRenderHeight.value;this.renderer.getArrayBufferAsync(e,null,0,Z.COUNT*4).then(e=>{t===this._readbackGeneration&&n>0&&this._applyCounters(e,n),this._convergedReadbackPending=!1}).catch(()=>{this._convergedReadbackPending=!1})}}}_issueLockstepReadback(){if(this._lockstepRead||this.frameCount%this._readbackEveryNFrames!==0||this.cameraOptimizer?.isInInteractionMode())return;let e=this._queueManager?.getBounceCountsAttribute(),t=this._queueManager?.getCountersAttribute();if(!e||!t)return;let n=this._readbackGeneration,r=this.maxBounces.value,i=this._bounceLoopBound(),a=this._queueManager.MAX_BOUNCE_SNAPSHOTS,o=this._wfRenderWidth.value*this._wfRenderHeight.value,s=this._integrator?.curveKey??null,c={due:this.frameCount+this._readbackEveryNFrames,read:null,apply:null};c.read=Promise.all([this.renderer.getArrayBufferAsync(e),this.renderer.getArrayBufferAsync(t,null,0,Z.COUNT*4)]).then(([e,t])=>{c.apply=()=>{n===this._readbackGeneration&&(this._applyBounceCounts(e,r,i,a,s),o>0&&this._applyCounters(t,o))}},e=>{k_.warn(`lockstep readback failed:`,e),c.apply=()=>{}}),this._lockstepRead=c}_applyBounceCounts(e,t,n,r,i=null){let a=new Uint32Array(e.slice(0));this._lastBounceCounts=a.subarray(0,r),this._lastBounceEnergy=a.subarray(r,2*r),this._integrator?.applyLightCurve(a.subarray(2*r,3*r),a.subarray(3*r,4*r),i),this._lastBounceCountsBudget=t,this._lastBounceCountsLoopBound=n,this._curveSizingValid=!0}_applyCounters(e,t){let n=new Uint32Array(e);this._convergedFraction=n[Z.CONVERGED_COUNT]/t;let r=n[Z.GEOMETRY_COUNT];this._geometryPixelCount=r,this._convergedGeometryFraction=r>0?n[Z.CONVERGED_GEOMETRY_COUNT]/r:1,this._lastActivePixelCount=n[Z.ACTIVE_PIXEL_COUNT]}_refreshWfTextureNodes(){let e=this._wfTexNodes;if(!e)return;let t=this.environment?.environmentTexture;t&&e.envTex&&(e.envTex.value=t),this.environment?.envCDFTexture&&e.envCDFTex&&(e.envCDFTex.value=this.environment.envCDFTexture);let n=this.materialData;n&&(_p(e.srgbBuckets,n.srgbBuckets),_p(e.linearBuckets,n.linearBuckets))}_rebuildKernelsIfResized(e,t){let n=this.storageTextures.renderWidth,r=this.storageTextures.renderHeight;if(!(n===e&&r===t||!(this.materialData?.materialCount>0))){if(this._lastBounceCounts&&this._numChunks<=1&&e>0&&t>0){let i=n*r/(e*t),a=e=>Math.min(4294967295,Math.round(e*i));this._lastBounceCounts=this._lastBounceCounts.map(a),this._lastBounceEnergy=this._lastBounceEnergy.map(a)}else this._lastBounceCounts=null,this._lastBounceEnergy=null,this._lastBounceCountsBudget=-1,this._lastBounceCountsLoopBound=-1;this._curveSizingValid=!1,this._readbackFrameCounter=0,this._readbackGeneration++,this._convergedFraction=0,this._convergedGeometryFraction=0,this._lastActivePixelCount=0,this._packedBuffers?this._resizeWavefrontInPlace(n,r):(this._kernelManager&&this._kernelManager.dispose(),this._wavefrontReady=!1,this._buildWavefrontKernels())}}_resizeWavefrontInPlace(e,t){this._wfRenderWidth.value=e,this._wfRenderHeight.value=t,this._updateChunkLayout()}_computePathBudget(){let e=((this._integrator?.hitStride??3)+1)*16,t=112+e+4+4+4,n=this.renderer?.backend?.device?.limits,r=n?.maxStorageBufferBindingSize||128*1024*1024,i=n?.maxBufferSize||r,a=co(this.hostMemoryGB).gb*1024*1024*1024,o=this._integrator?.cacheBytes(r,a)??0;if(this._pathBudgetOverride>0)return this._pathBudgetOverride;let s=Math.floor(Math.min(r*.9/112,(r*.9-o)/e)),c=Math.min(a*.25,i*4)-o,l=Math.floor(c/t),u=Math.min(s,l,2048*2048);return u=Math.max(262144,u),u}_updateChunkLayout(){let e=Math.max(1,this.storageTextures.renderWidth),t=this.storageTextures.renderHeight,n=this._pathBudget||e*t;this._chunkRows=Math.max(1,Math.min(Math.floor(n/e),t)),this._numChunks=Math.max(1,Math.ceil(t/this._chunkRows))}reallocateReservedStorage(){if(!this.storageTextures.writeColor)return;let e=Math.min(this.storageTextures.renderWidth||1,Me),t=Math.min(this.storageTextures.renderHeight||1,Me);this.storageTextures.create(e,t),this.resolution.value.set(e,t),!(!this._packedBuffers||!(this.materialData?.materialCount>0))&&(this._kernelManager&&this._kernelManager.dispose(),this._wavefrontReady=!1,this._buildWavefrontKernels())}_clearcoatNormalsNeeded(){return!this._integrator&&this.materialData.hasClearcoatNormals()}_layersToCompile(){return this.materialData.materialLayers()}get _gBufferCompiled(){return this._outputs.has(`gBuffer`)||this._outputs.has(`hitDistance`)}_buildWavefrontKernels(){let e=this.shaderBuilder.getSceneTextureNodes();if(!e)return;this._lightBufferRealloc=!1,this._outputsChanged=!1,this._integrator?.beforeKernelBuild();let t=this.storageTextures.renderWidth,r=this.storageTextures.renderHeight;this._pathBudget||=this._computePathBudget();let i=this._pathBudget;this._updateChunkLayout();let a=this._chunkRows*t,o=this._integrator?.lightVertices??0;this._packedBuffers?this._packedBuffers.resize(i,o):this._packedBuffers=new Ru(i,this.renderer,o);let s=this._packedBuffers.hitBuffer.rw,c=this._packedBuffers.hitBuffer.ro,l=Me*Me;(!this._m2Attr||this._m2Attr.count<l)&&(Au(this.renderer,this._m2Attr),this._m2Attr=v(l,1),Au(this.renderer,this._streakAttr),this._streakAttr=v(l,1,Uint32Array),Au(this.renderer,this._frozenMaskAttr),this._frozenMaskAttr=v(l,1,Uint32Array)),this._integrator?.allocate(l);let u=(0,n.storage)(this._m2Attr,`float`),d=(0,n.storage)(this._streakAttr,`uint`),f=(0,n.storage)(this._streakAttr,`uint`).toReadOnly(),p=(0,n.storage)(this._frozenMaskAttr,`uint`),m=(0,n.storage)(this._frozenMaskAttr,`uint`).toReadOnly();this._queueManager?this._queueManager.resize(this._packedBuffers.capacity):this._queueManager=new Jd(this._packedBuffers.capacity,this.renderer),this._kernelManager||=new nf(this.renderer);let h=this._packedBuffers,g=this._queueManager;this._wfRenderWidth.value=t,this._wfRenderHeight.value=r,this._wfMaxRayCount.value=Math.min(i,this._chunkRows*t);let _=this.shaderBuilder.prevColorTexNode,y=this.shaderBuilder.prevAlbedoTexNode,b=this.shaderBuilder.prevNormalDepthTexNode,x=this.storageTextures.getWriteTextures(),S=this._pickedShadowRays();this._compiledPick=S;let C=S!==null;this._learnsVisibility=C,g.setVisibilityTable(C);let w=g.getCounters(),T=g.getBounceCounts(),E=this._wfCurrentBounce,D=(0,n.Fn)(()=>{let e=(0,n.atomicLoad)(w.element((0,n.uint)(Z.ACTIVE_RAY_COUNT))),t=(0,n.uint)(E).clamp((0,n.uint)(0),(0,n.uint)(g.MAX_BOUNCE_SNAPSHOTS-1));T.element(t).assign(e),T.element(t.add((0,n.uint)(g.MAX_BOUNCE_SNAPSHOTS))).assign((0,n.atomicLoad)(w.element((0,n.uint)(Z.ACTIVE_ENERGY)))),(0,n.atomicStore)(w.element((0,n.uint)(Z.ENTERING_COUNT)),e)});this._kernelManager.register(`snapshotBounceCount`,D().compute([1,1,1],[1,1,1]));let O=g.activeIndices.a,k=(0,n.Fn)(()=>{let e=n.instanceIndex;(0,n.If)(e.lessThan(this._wfMaxRayCount),()=>{O.element(e).assign(e)}),(0,n.If)(e.equal((0,n.uint)(0)),()=>{(0,n.atomicStore)(w.element((0,n.uint)(Z.ACTIVE_RAY_COUNT)),this._wfMaxRayCount),(0,n.atomicStore)(w.element((0,n.uint)(Z.ENTERING_COUNT)),this._wfMaxRayCount),(0,n.If)(this._wfIsFirstChunk.greaterThan((0,n.uint)(0)),()=>{(0,n.atomicStore)(w.element((0,n.uint)(Z.CONVERGED_COUNT)),(0,n.uint)(0)),(0,n.atomicStore)(w.element((0,n.uint)(Z.GEOMETRY_COUNT)),(0,n.uint)(0)),(0,n.atomicStore)(w.element((0,n.uint)(Z.CONVERGED_GEOMETRY_COUNT)),(0,n.uint)(0))})})});this._kernelManager.register(`initActiveIndices`,k().compute([Math.ceil(this._chunkRows*t/256),1,1],[256,1,1]));let A={rayBufferRW:h.rayBuffer.rw,hitBufferRW:h.hitBuffer.rw,gBufferRW:s,resolution:this.resolution,frame:this.seedFrame,cameraWorldMatrix:this.cameraWorldMatrix,cameraProjectionMatrixInverse:this.cameraProjectionMatrixInverse,cameraProjection:this.cameraProjection,panoLonRange:this.panoLonRange,panoLatRange:this.panoLatRange,panoLevelHorizon:this.panoLevelHorizon,enableDOF:this.enableDOF,focalLength:this.focalLength,aperture:this.aperture,focusDistance:this.focusDistance,unitsPerMetre:this.unitsPerMetre,apertureScale:this.apertureScale,anamorphicRatio:this.anamorphicRatio,dofMode:this.dofMode,dofBlur:this.dofBlur,cameraClipStart:this.cameraClipStart,renderWidth:this._wfRenderWidth,renderHeight:this._wfRenderHeight,chunkRowBase:this._wfChunkRowBase,chunkRows:this._wfChunkRows,transmissiveBounces:this.transmissiveBounces,transparentBackground:this.transparentBackground,auxGBufferEnabled:this._auxGBufferUniform,gBuffer:this._gBufferCompiled,bidirectional:this._integrator?.uniforms??null},j=mf(A);this._kernelManager.register(`generate`,j().compute([Math.ceil(t/16),Math.ceil(this._chunkRows/16),1],[16,16,1]));let M=this.pixelFreezeStability,N=(0,n.Fn)(()=>{(0,n.atomicStore)(w.element((0,n.uint)(Z.ACTIVE_RAY_COUNT)),(0,n.uint)(0)),(0,n.If)(this._wfIsFirstChunk.greaterThan((0,n.uint)(0)),()=>{(0,n.atomicStore)(w.element((0,n.uint)(Z.CONVERGED_COUNT)),(0,n.uint)(0)),(0,n.atomicStore)(w.element((0,n.uint)(Z.GEOMETRY_COUNT)),(0,n.uint)(0)),(0,n.atomicStore)(w.element((0,n.uint)(Z.CONVERGED_GEOMETRY_COUNT)),(0,n.uint)(0))})});this._kernelManager.register(`resetFrameCounters`,N().compute([1,1,1],[1,1,1]));let P=(0,n.Fn)(()=>{let e=n.instanceIndex;(0,n.If)(e.lessThan(this._wfMaxRayCount),()=>{let t=(0,n.uint)((0,n.int)(e).add(this._wfChunkRowBase.mul(this._wfRenderWidth))).toVar(),r=(0,n.uint)(0).toVar();(0,n.If)(this.frame.greaterThan((0,n.uint)(0)).and(f.element(t).bitAnd((0,n.uint)(1073741823)).greaterThanEqual((0,n.uint)(M))),()=>{r.assign((0,n.uint)(1)),(0,n.If)(this._dilateFrozenUniform.greaterThan((0,n.int)(0)),()=>{let e=(0,n.int)(t).mod(this._wfRenderWidth),i=(0,n.int)(t).div(this._wfRenderWidth);for(let[t,a]of[[-1,-1],[0,-1],[1,-1],[-1,0],[1,0],[-1,1],[0,1],[1,1]]){let o=e.add((0,n.int)(t)),s=i.add((0,n.int)(a));(0,n.If)(o.greaterThanEqual((0,n.int)(0)).and(o.lessThan(this._wfRenderWidth)).and(s.greaterThanEqual((0,n.int)(0))).and(s.lessThan(this._wfRenderHeight)),()=>{(0,n.If)(f.element((0,n.uint)(s.mul(this._wfRenderWidth).add(o))).bitAnd((0,n.uint)(1073741823)).lessThan((0,n.uint)(M)),()=>{r.assign((0,n.uint)(0))})})}})}),p.element(t).assign(r),(0,n.If)(r.equal((0,n.uint)(0)),()=>{let t=(0,n.atomicAdd)(w.element((0,n.uint)(Z.ACTIVE_RAY_COUNT)),(0,n.uint)(1));O.element(t).assign(e)})})});this._kernelManager.register(`buildActivePixels`,P().compute([Math.ceil(this._chunkRows*t/256),1,1],[256,1,1]));let F=(0,n.Fn)(()=>{let e=n.instanceIndex,t=this._wfRenderWidth,r=this._wfRenderHeight;(0,n.If)(e.lessThan((0,n.uint)(t.mul(r))),()=>{let i=(0,n.int)(e).mod(t),a=(0,n.int)(e).div(t),o=(0,n.uint)(2147483648),s=(0,n.uint)(1073741824),c=f.element(e).toVar(),l=c.bitAnd(s).notEqual((0,n.uint)(0)),u=c.bitAnd(o).notEqual((0,n.uint)(0)).toVar();(0,n.If)(u,()=>{for(let[e,s]of[[-1,-1],[0,-1],[1,-1],[-1,0],[1,0],[-1,1],[0,1],[1,1]]){let c=i.add((0,n.int)(e)),l=a.add((0,n.int)(s));(0,n.If)(c.greaterThanEqual((0,n.int)(0)).and(c.lessThan(t)).and(l.greaterThanEqual((0,n.int)(0))).and(l.lessThan(r)),()=>{(0,n.If)(f.element((0,n.uint)(l.mul(t).add(c))).bitAnd(o).equal((0,n.uint)(0)),()=>{u.assign(!1)})})}}),(0,n.If)(u,()=>{(0,n.atomicAdd)(w.element((0,n.uint)(Z.CONVERGED_COUNT)),(0,n.uint)(1))}),(0,n.If)(l,()=>{(0,n.atomicAdd)(w.element((0,n.uint)(Z.GEOMETRY_COUNT)),(0,n.uint)(1)),(0,n.If)(u,()=>{(0,n.atomicAdd)(w.element((0,n.uint)(Z.CONVERGED_GEOMETRY_COUNT)),(0,n.uint)(1))})})})});this._kernelManager.register(`countConvergedDilated`,F().compute([Math.ceil(t*r/256),1,1],[256,1,1]));let I=(0,n.Fn)(()=>{let e=(0,n.atomicLoad)(w.element((0,n.uint)(Z.ACTIVE_RAY_COUNT)));(0,n.atomicStore)(w.element((0,n.uint)(Z.ENTERING_COUNT)),e),(0,n.atomicStore)(w.element((0,n.uint)(Z.ACTIVE_PIXEL_COUNT)),e)});this._kernelManager.register(`seedEnter`,I().compute([1,1,1],[1,1,1]));let L=mf({...A,listDriven:!0,activeIndicesRO:g.activeIndicesRO.a,counters:w});this._kernelManager.register(`generateList`,L().compute([Math.ceil(a/256),1,1],[256,1,1]));let ee=this.bvhStorageNode,te=this.triangleStorageNode,R=this.materialData.materialStorageNode,ne=(0,n.texture)(this.environment.envCDFTexture),re=this.lightDataNode,ie=this.materialData,ae=this.environment,oe=gp(ie.srgbBuckets),se=gp(ie.linearBuckets),ce={srgbBuckets:oe,linearBuckets:se,shadowAlbedoMaps:oe,goboMaps:e.goboMapsTex,iesProfiles:e.iesProfilesTex,alphaShadows:this.uniforms.get(`enableAlphaShadows`),materialLayers:this._compiledLayers=this._layersToCompile(),lightRadius:this._compiledLightRadius=this._lightRadiusNeeded(),transmissionMaps:this._compiledTransmissionMaps=this.materialData.hasTransmissionMaps(),clearcoatNormals:this._compiledClearcoatNormals=this._clearcoatNormalsNeeded()},le=e=>ur(e,ce),z=ae.environmentTexture?(0,n.texture)(ae.environmentTexture):e.envTex;this._wfTexNodes={envTex:z,envCDFTex:ne,srgbBuckets:oe,linearBuckets:se},this._sortMaterials=this.sortMaterials&&(this.materialData?.materialCount??0)>8;let ue=Yf({bvhBuffer:ee,triangleBuffer:te,rayBufferRO:h.rayBuffer.ro,hitBufferRW:h.hitBuffer.rw,activeIndicesRO:g.getActiveReadRO(),counters:w,maxRayCount:this._wfMaxRayCount,shadowTerminatorOffset:this.shadowTerminatorOffset});if(this._kernelManager.register(`extend`,ue().compute([Math.ceil(a/256),1,1],[256,1,1])),this._sortMaterials){let e=g.getSortGlobalHistogram(),t=Math.min(256,this.materialData?.materialCount??256);this._kernelManager.register(`resetGlobalHist`,C_({sortGlobalHistogram:e,bins:t})().compute([1,1,1],[256,1,1])),this._kernelManager.register(`globalHist`,w_({hitBufferRO:h.hitBuffer.ro,activeIndicesReadRO:g.getActiveReadRO(),sortGlobalHistogram:e,counters:w,bins:t})().compute([Math.ceil(a/256),1,1],[256,1,1])),this._kernelManager.register(`globalPrefix`,T_({sortGlobalHistogram:e,bins:t})().compute([1,1,1],[1,1,1])),this._kernelManager.register(`globalScatter`,E_({hitBufferRO:h.hitBuffer.ro,activeIndicesReadRO:g.getActiveReadRO(),sortedIndicesRW:g.getSortedRW(),sortGlobalHistogram:e,counters:w,bins:t})().compute([Math.ceil(a/256),1,1],[256,1,1]))}let de=f_({gBufferRW:s,bvhBuffer:ee,triangleBuffer:te,materialBuffer:R,envCDFTexture:ne,lightBuffer:re,rayBufferRW:h.rayBuffer.rw,hitBufferRW:h.hitBuffer.rw,counters:w,activeIndicesRO:this._sortMaterials?g.getSortedRO():g.getActiveReadRO(),envTexture:z,environmentIntensity:this.environmentIntensity,envMatrix:this.environmentMatrix,enableEnvironmentLight:this.enableEnvironment,groundProjectionEnabled:this.groundProjectionEnabled,groundProjectionRadius:this.groundProjectionRadius,groundProjectionHeight:this.groundProjectionHeight,groundProjectionLevel:this.groundProjectionLevel,enableGroundCatcher:this.enableGroundCatcher,groundCatcherHeight:this.groundCatcherHeight,envTotalSum:this.envTotalSum,envResolution:this.envResolution,directionalLightsBuffer:this.directionalLightsBufferNode,numDirectionalLights:this.numDirectionalLights,areaLightsBuffer:this.areaLightsBufferNode,numAreaLights:this.numAreaLights,pointLightsBuffer:this.pointLightsBufferNode,numPointLights:this.numPointLights,spotLightsBuffer:this.spotLightsBufferNode,numSpotLights:this.numSpotLights,maxBounceCount:this.maxBounces,maxSubsurfaceSteps:this.maxSubsurfaceSteps,maxTransparentBounces:this.maxTransparentBounces,transparentBackground:this.transparentBackground,backgroundIntensity:this.backgroundIntensity,backgroundColor:this.backgroundColor,backgroundBlurriness:this.backgroundBlurriness,backgroundBlurSamples:this.backgroundBlurSamples,showBackground:this.showBackground,globalIlluminationIntensity:this.globalIlluminationIntensity,cameraProjectionMatrix:this.cameraProjectionMatrix,cameraViewMatrix:this.cameraViewMatrix,fireflyThreshold:this.fireflyThreshold,shadowTerminatorOffset:this.shadowTerminatorOffset,frame:this.seedFrame,accumFrame:this.frame,resolution:this.resolution,emissiveTriangleCount:this.emissiveTriangleCount,emissiveVec4Offset:this.emissiveVec4Offset,emissiveTotalPower:this.emissiveTotalPower,emissiveBoost:this.emissiveBoost,enableEmissiveTriangleSampling:this.enableEmissiveTriangleSampling,lightBVHNodeCount:this.lightBVHNodeCount,reverseMapVec4Offset:this.reverseMapVec4Offset,currentBounce:this._wfCurrentBounce,maxRayCount:this._wfMaxRayCount,chunkRowBase:this._wfChunkRowBase,auxGBufferEnabled:this._auxGBufferUniform,gBuffer:this._gBufferCompiled,hasSun:this.hasSun,sunDirection:this.sunDirection,sunRadiance:this.sunRadiance,sunParams:this.sunParams,bidirectional:this._integrator?.uniforms??null,hitDistanceEncode:this._outputs.get(`hitDistance`)?.encode??null,materialLayers:this._compiledLayers,shadowRays:S,cameraWorldMatrix:this.cameraWorldMatrix});this._kernelManager.register(`shade`,le(de()).compute([Math.ceil(a/256),1,1],[256,1,1])),C&&(this._kernelManager.register(`visibilityClear`,Gh({counters:w})),this._kernelManager.register(`visibilityFold`,Wh({counters:w})));let fe=this._useSubgroupCompact&&(this.renderer.hasFeature?this.renderer.hasFeature(`subgroups`):!1);this._compactIsSubgroup=fe;let pe=(fe?h_:m_)({rayBufferRO:h.rayBuffer.ro,activeIndicesReadRO:g.getActiveReadRO(),activeIndicesWriteRW:g.getActiveWrite(),counters:w,currentActiveCount:this._wfMaxRayCount});this._kernelManager.register(`compact`,pe().compute([Math.ceil(a/256),1,1],[256,1,1]));let me=(0,n.Fn)(()=>{(0,n.atomicStore)(w.element((0,n.uint)(Z.ENTERING_COUNT)),this._wfMaxRayCount)});this._kernelManager.register(`enterFull`,me().compute([1,1,1],[1,1,1]));let he=g.activeIndicesRO.b,ge=g.activeIndices.a,_e=(0,n.Fn)(()=>{let e=n.instanceIndex,t=(0,n.atomicLoad)(w.element((0,n.uint)(Z.ACTIVE_RAY_COUNT)));(0,n.If)(e.equal((0,n.uint)(0)),()=>{let e=(0,n.uint)(E).clamp((0,n.uint)(0),(0,n.uint)(g.MAX_BOUNCE_SNAPSHOTS-1));T.element(e).assign(t),T.element(e.add((0,n.uint)(g.MAX_BOUNCE_SNAPSHOTS))).assign((0,n.atomicLoad)(w.element((0,n.uint)(Z.ACTIVE_ENERGY)))),(0,n.atomicStore)(w.element((0,n.uint)(Z.ENTERING_COUNT)),t)}),(0,n.If)(e.greaterThanEqual(t),()=>{(0,n.Return)()}),ge.element(e).assign(he.element(e))});this._kernelManager.register(`compactCopyback`,_e().compute([Math.ceil(a/256),1,1],[256,1,1])),this._integrator?.registerKernels({km:this._kernelManager,qm:g,pb:h,counters:w,bounceCountsBuf:T,wfCurrentBounce:E,copyReadB:he,copyWriteA:ge,maxRays:a,w:t,own:le,freshLight:re,freshTri:te,freshBvh:ee,freshMat:R,freshEnvTex:z,freshEnvCDF:ne,materialLayers:this._compiledLayers});let ve=__({rayBufferRO:h.rayBuffer.ro,gBufferRO:c,writeColorTex:x.color,writeNDTex:x.normalDepth,writeAlbedoTex:x.albedo,resolution:this.resolution,frame:this.frame,enableAccumulation:this.enableAccumulation,hasPreviousAccumulated:this.hasPreviousAccumulated,accumulationAlpha:this.accumulationAlpha,hasPreviousAux:this.hasPreviousAux,auxAccumulationAlpha:this.auxAccumulationAlpha,cameraIsMoving:this.cameraIsMoving,prevAccumTexture:_,prevAlbedoTexture:y,prevNormalDepthTexture:b,renderWidth:this._wfRenderWidth,renderHeight:this._wfRenderHeight,visMode:this.visMode,auxGBufferEnabled:this._auxGBufferUniform,gBuffer:this._gBufferCompiled,cleanAuxNormalEnabled:this._cleanAuxNormalUniform,m2BufferRW:u,useAdaptiveSampling:this.useAdaptiveSampling,noiseThreshold:this.noiseThreshold,adaptiveMinSamples:this.adaptiveMinSamples,usePixelFreeze:this.usePixelFreeze,pixelFreezeThreshold:this.pixelFreezeThreshold,streakBufferRW:d,frozenMaskRO:m,convergenceOverlay:this.convergenceOverlay,chunkRowBase:this._wfChunkRowBase,chunkRows:this._wfChunkRows});this._kernelManager.register(`finalWrite`,ve().compute([Math.ceil(t/16),Math.ceil(this._chunkRows/16),1],[16,16,1]));let ye=S_({writeColorTex:x.color,writeNDTex:x.normalDepth,writeAlbedoTex:x.albedo,resolution:this.resolution,renderWidth:this._wfRenderWidth,renderHeight:this._wfRenderHeight,cameraWorldMatrix:this.cameraWorldMatrix,cameraProjectionMatrixInverse:this.cameraProjectionMatrixInverse,cameraProjectionMatrix:this.cameraProjectionMatrix,cameraViewMatrix:this.cameraViewMatrix,cameraProjection:this.cameraProjection,panoLonRange:this.panoLonRange,panoLatRange:this.panoLatRange,panoLevelHorizon:this.panoLevelHorizon,enableDOF:this.enableDOF,focalLength:this.focalLength,aperture:this.aperture,focusDistance:this.focusDistance,unitsPerMetre:this.unitsPerMetre,apertureScale:this.apertureScale,anamorphicRatio:this.anamorphicRatio,dofMode:this.dofMode,dofBlur:this.dofBlur,cameraClipStart:this.cameraClipStart,bvhBuffer:ee,triangleBuffer:te,materialBuffer:R,envTexture:z,environmentMatrix:this.environmentMatrix,environmentIntensity:this.environmentIntensity,enableEnvironmentLight:this.enableEnvironment,visMode:this.visMode,debugVisScale:this.debugVisScale,frame:this.frame});this._kernelManager.register(`debug`,le(ye()).compute([Math.ceil(t/16),Math.ceil(r/16),1],[16,16,1]),{eager:!1}),this._compileKernels();let be=(this._packedBuffers?.totalBytes??0)+(this._queueManager?.totalBytes??0);k_.info(V.list([V.px(t,r),`${V.mb(be)} wavefront buffers`,`budget ${V.n(i)} paths`,this._numChunks>1?`${this._numChunks} chunks of ≤${this._chunkRows} rows`:null,this._integrator?.describe()??null]))}_setWfDispatch(){let e=this._wfRenderWidth.value,t=this._wfRenderHeight.value;this._kernelManager.setDispatchForGrid(`debug`,e,t),this._kernelManager.setDispatchForCount(`countConvergedDilated`,e*t)}_setChunk(e,t,n){let r=this._wfRenderWidth.value,i=t*r;this._wfChunkRowBase.value=e,this._wfChunkRows.value=t,this._wfIsFirstChunk.value=+(n===0),this._wfMaxRayCount.value=i;let a=this._kernelManager;return a.setDispatchForGrid(`generate`,r,t),a.setDispatchForGrid(`finalWrite`,r,t),a.setDispatchForGrid(`splatResolve`,r,t),a.setDispatchForCount(`initActiveIndices`,i),a.setDispatchForCount(`buildActivePixels`,i),i}dispose(){super.dispose(),this._packedBuffers?.dispose(),this._queueManager?.dispose(),this._kernelManager?.dispose(),this._m2Attr?.dispose?.(),this._streakAttr?.dispose?.(),this._frozenMaskAttr?.dispose?.();for(let e of this._integratorInstances.values())e.dispose();this._integratorInstances.clear(),this._integrator=null,this._packedBuffers=null,this._queueManager=null,this._kernelManager=null,this._m2Attr=null,this._streakAttr=null,this._frozenMaskAttr=null,this._convDebugSource=null,this._wavefrontReady=!1,this._kernelGeneration++,this._kernelsCompiling=null}};xu();var P_=class extends j{constructor(e,i={}){super(`Compositor`,{...i,executionMode:A.ALWAYS}),this.renderer=e,this._lightSources=[...i.displaySources??[],`pathtracer:color`],this.saturation=(0,n.uniform)(i.saturation??1),this._transparentBackground=(0,n.uniform)(0,`int`),this._pathTracer=i.pathTracer??null,this._convergenceOverlay=!1,this._debugMaterial=null,this._debugQuad=null,this._debugTexNode=null,this._debugM2Attr=null,this._debugMaskAttr=null,this._debugExposureComp=(0,n.uniform)(1),this._sourceTexNode=new t.TextureNode,this._displayGain=null,this._backdropExposure=null,this._holdBackdrop=(0,n.uniform)(0,`int`),this._backdropGain=(0,n.uniform)(1),this.compositorMaterial=new t.MeshBasicNodeMaterial,this.compositorMaterial.blending=r.NoBlending,this._buildColorNode(),this.compositorQuad=new t.QuadMesh(this.compositorMaterial)}_buildColorNode(){let e=this._sourceTexNode.sample((0,n.uv)()),t=this._displayGain?this._displayGain(e.xyz,n.screenUV):null;if(this._backdropExposure!==null){let r=t??(0,n.float)(1),i=r.add(this._backdropGain.sub(r).mul(e.w.clamp(0,1).oneMinus()));t=(0,n.select)(this._holdBackdrop.greaterThan((0,n.int)(0)),i,r)}let r=t?e.xyz.mul(t):e.xyz,i=(0,n.mix)((0,n.vec3)((0,n.dot)(r,Bl)),r,this.saturation),a=(0,n.select)(this._transparentBackground,e.w,1);this.compositorMaterial.colorNode=(0,n.vec4)(i,a),this.compositorMaterial.needsUpdate=!0}setDisplayGain(e){e!==this._displayGain&&(this._displayGain=e,this._buildColorNode())}setBackdropExposure(e){let t=e===null!=(this._backdropExposure===null);this._backdropExposure=e,t&&this._buildColorNode()}resolveLightTexture(e){return this.resolveLightSource(e)?.texture??null}resolveLightSource(e){for(let t of this._lightSources){let n=e.getTexture(t);if(n)return{key:t,texture:n}}return null}_ensureDebugMaterial(){let e=this._pathTracer?.getConvergenceDebugSource?.();if(!e)return!1;if(this._debugMaterial&&this._debugM2Attr===e.m2&&this._debugMaskAttr===e.frozenMask)return!0;this._debugMaterial?.dispose(),this._debugTexNode?.dispose(),this._debugM2Attr=e.m2,this._debugMaskAttr=e.frozenMask,this._debugTexNode=new t.TextureNode;let i=(0,n.Fn)(()=>{let t=(0,n.dot)(this._debugTexNode.sample((0,n.uv)()).toVar().xyz,Bl).toVar(),r=e.renderWidth,i=e.renderHeight,a=(0,n.int)((0,n.uv)().x.mul((0,n.float)(r))).min(r.sub((0,n.int)(1))).max((0,n.int)(0)),o=(0,n.uint)((0,n.int)((0,n.uv)().y.mul((0,n.float)(i))).min(i.sub((0,n.int)(1))).max((0,n.int)(0)).mul(r).add(a)).toVar(),s=(0,n.storage)(e.m2,`float`).toReadOnly().element(o).toVar(),c=(0,n.storage)(e.frozenMask,`uint`).toReadOnly().element(o).toVar(),l=s.sub(t.mul(t)).max((0,n.float)(0)).div((0,n.float)(e.frame).add(1)).sqrt().toVar(),u=e.usePixelFreeze.greaterThan((0,n.int)(0)),d=(0,n.select)(t.lessThan((0,n.float)(1)),t.sqrt(),t).toVar(),f=(0,n.select)(u,l.div(t.add((0,n.float)(1e-4))),l.div(d.add((0,n.float)(1e-4)))).toVar(),p=(0,n.select)(u,e.pixelFreezeThreshold,e.noiseThreshold).toVar(),m=f.div(p.max((0,n.float)(1e-6))).toVar(),h=(0,n.vec3)(t.div(t.add((0,n.float)(1))).sqrt().mul(.55)).toVar(),g=h.toVar(),_=(0,n.float)(e.frame).greaterThanEqual((0,n.float)(e.adaptiveMinSamples));return(0,n.If)(m.greaterThanEqual((0,n.float)(1)).or(_.not()),()=>{let e=(0,n.mix)((0,n.vec3)(1,.8,.1),(0,n.vec3)(1,.1,.05),m.sub(1).div(3).clamp(0,1));g.assign((0,n.mix)(h,e,.85))}),(0,n.If)(c.equal((0,n.uint)(1)).and(u),()=>{g.assign((0,n.mix)(h,(0,n.vec3)(.1,.45,1),.55))}),g});return this._debugMaterial=new t.MeshBasicNodeMaterial,this._debugMaterial.colorNode=(0,n.vec4)(i().pow(2.2).mul(this._debugExposureComp),1),this._debugMaterial.blending=r.NoBlending,this._debugQuad=new t.QuadMesh(this._debugMaterial),!0}render(e){if(!this.enabled)return;if(this._convergenceOverlay&&this._ensureDebugMaterial()){let t=e.getTexture(`pathtracer:color`);if(t){this._debugTexNode.value=t;let e=this.renderer.toneMapping!==r.NoToneMapping;this._debugExposureComp.value=e?1/Math.max(this.renderer.toneMappingExposure,1e-4):1,this.renderer.setRenderTarget(null),this._debugQuad.render(this.renderer);return}}let t=this.resolveLightTexture(e);if(t){if(this._backdropExposure!==null){let t=e.getState(`pathtracer:backdrop`)===`color`;this._holdBackdrop.value=+!!t,t&&(this._backdropGain.value=Ts(this._backdropExposure,this.renderer.toneMappingExposure,this.renderer.toneMapping))}this._sourceTexNode.value=t,this.renderer.setRenderTarget(null),this.compositorQuad.render(this.renderer)}}setConvergenceOverlay(e){this._convergenceOverlay=!!e}setSaturation(e){this.saturation.value=e}setTransparentBackground(e){this._transparentBackground.value=+!!e}dispose(){this._sourceTexNode?.dispose(),this.compositorMaterial?.dispose(),this._debugTexNode?.dispose(),this._debugMaterial?.dispose(),this.compositorQuad=null,this._debugQuad=null,this._debugMaterial=null,this._debugTexNode=null,this._pathTracer=null}},F_=class{constructor(){this.textures=new Map,this.renderTargets=new Map,this.uniforms=new Map,this.state={frame:0,accumulatedFrames:0,renderMode:0,isComplete:!1,tileInfo:null,currentTile:0,totalTiles:0,cameraChanged:!1,cameraMoving:!1,width:0,height:0,time:0,deltaTime:0},this._stateChangeCallbacks=new Map}setTexture(e,t){this.textures.set(e,t)}getTexture(e){return this.textures.get(e)}hasTexture(e){return this.textures.has(e)}removeTexture(e){this.textures.delete(e)}getTextureNames(){return Array.from(this.textures.keys())}clearTextures(){this.textures.clear()}setRenderTarget(e,t){this.renderTargets.set(e,t)}getRenderTarget(e){return this.renderTargets.get(e)}hasRenderTarget(e){return this.renderTargets.has(e)}removeRenderTarget(e){this.renderTargets.delete(e)}getRenderTargetNames(){return Array.from(this.renderTargets.keys())}clearRenderTargets(){this.renderTargets.clear()}setUniform(e,t){this.uniforms.has(e)?this.uniforms.get(e).value=t:this.uniforms.set(e,{value:t})}getUniform(e){return this.uniforms.get(e)}getUniformValue(e){return this.uniforms.get(e)?.value}hasUniform(e){return this.uniforms.has(e)}removeUniform(e){this.uniforms.delete(e)}getUniformNames(){return Array.from(this.uniforms.keys())}clearUniforms(){this.uniforms.clear()}setState(e,t){let n=this.state[e],r=n!==t;return r&&(this.state[e]=t,this._notifyStateChange(e,t,n)),r}getState(e){return this.state[e]}getAllState(){return this.state}setStates(e){let t=[];for(let[n,r]of Object.entries(e))this.setState(n,r)&&t.push(n);return t}hasState(e){return e in this.state}watchState(e,t){this._stateChangeCallbacks.has(e)||this._stateChangeCallbacks.set(e,[]),this._stateChangeCallbacks.get(e).push(t)}unwatchState(e,t){if(!this._stateChangeCallbacks.has(e))return;let n=this._stateChangeCallbacks.get(e),r=n.indexOf(t);r>-1&&n.splice(r,1)}_notifyStateChange(e,t,n){if(!this._stateChangeCallbacks.has(e))return;let r=this._stateChangeCallbacks.get(e);for(let i of r)try{i(t,n)}catch(t){console.error(`Error in state change callback for '${e}':`,t)}}reset(){this.state.frame=0,this.state.accumulatedFrames=0,this.state.isComplete=!1,this.state.cameraChanged=!0,this.state.currentTile=0}incrementFrame(){return this.state.frame++,this.state.accumulatedFrames++,this.state.frame}dispose(){this.textures.clear(),this.renderTargets.clear(),this.uniforms.clear(),this._stateChangeCallbacks.clear(),this.state={}}},I_=class extends r.EventDispatcher{constructor(){super(),this._onceCallbacks=new Map}on(e,t){this.addEventListener(e,t)}once(e,t){let n=r=>{t(r),this.off(e,n),this._onceCallbacks.delete(t)};this._onceCallbacks.set(t,n),this.on(e,n)}off(e,t){let n=this._onceCallbacks.get(t);n?(this.removeEventListener(e,n),this._onceCallbacks.delete(t)):this.removeEventListener(e,t)}emit(e,t){t&&typeof t==`object`&&t.type?this.dispatchEvent(t):this.dispatchEvent({type:e,...t})}removeAllListeners(e){if(e){for(let[t,n]of this._onceCallbacks.entries())this.hasEventListener(e,n)&&(this.removeEventListener(e,n),this._onceCallbacks.delete(t));this._listeners&&this._listeners[e]&&delete this._listeners[e]}else this._onceCallbacks.clear(),this._listeners&&={}}listenerCount(e){return!this._listeners||!this._listeners[e]?0:this._listeners[e].length}clear(){this.removeAllListeners()}eventNames(){return this._listeners?Object.keys(this._listeners):[]}},L_=!1,R_=[],z_=new WeakMap;function B_(e){L_=!!e}function V_(){return R_.slice()}function H_(){R_.length=0}function U_(e){let t=[];for(let n of Object.keys(e))e[n]?.isTextureNode===!0&&t.push(n);return t}var W_=e=>!e||!e.image||!(e.image.width>0);function G_(e,t,n){if(!L_){n();return}let r=z_.get(e);if(r||(r={phase:`pending`,unboundAtCompile:[]},z_.set(e,r)),r.phase!==`pending`){n(),r.phase===`watch`&&K_(e,r);return}let i=Object.prototype.hasOwnProperty.call(t,`compute`),a=t.compute;t.compute=function(...t){return r.phase===`pending`&&(r.unboundAtCompile=U_(e).filter(t=>W_(e[t].value)),r.phase=r.unboundAtCompile.length<2?`done`:`watch`),a.apply(this,t)};try{n()}finally{i?t.compute=a:delete t.compute}}function K_(e,t){let n=[];for(let r of t.unboundAtCompile){let t=e[r]?.value;if(W_(t))return;t.isStorageTexture!==!0&&n.push(r)}t.phase=`done`,n.length!==0&&R_.push({stage:e.name,nodes:n,unboundAtCompile:t.unboundAtCompile.slice(),message:`${e.name}: ${n.join(`, `)} ${n.length===1?`was`:`were`} still holding EmptyTexture when the stage first dispatched, alongside ${t.unboundAtCompile.length-n.length} other unbound node(s), and later received a non-storage texture. Two nodes unbound at compile time can share one GPU binding and then both resolve to whichever is assigned last. Assign these before the first dispatch.`})}an();var q_=class{_reportStageFailure(e,t,n){console.error(`[Pipeline] Error in stage '${e}' (${t}):`,n);let r=`${e}:${t}`;this._reportedStageFailures.has(r)||(this._reportedStageFailures.add(r),this._issues?.record(X.STAGE_RENDER_FAILED,`stage "${e}" threw during ${t} — the frame is incomplete`,{stage:e,phase:t,cause:String(n?.message??n)}))}constructor(e,t,n,{issues:r=null}={}){this.renderer=e,this._issues=r,this._reportedStageFailures=new Set,this.width=t,this.height=n,this.stages=[],this.context=new F_,this.eventBus=new I_,this.context.setState(`width`,t),this.context.setState(`height`,n),this.stats={enabled:!1,logSkipped:!1,timings:new Map,frameCount:0}}addStage(e){this.stages.push(e),e.initialize(this.context,this.eventBus),this.stats.enabled&&console.log(`[Pipeline] Added stage: ${e.name}`)}getStage(e){return this.stages.find(t=>t.name===e)}removeStage(e){let t=this.stages.findIndex(t=>t.name===e);if(t>-1){let e=this.stages[t];return this.stages.splice(t,1),e.dispose&&e.dispose(),this.stats.timings.delete(e.name),!0}return!1}setStageEnabled(e,t){let n=this.getStage(e);n&&(t?n.enable():n.disable())}render(e=null){let t=this.stats.enabled?performance.now():0;for(let t of this.stages){if(!t.shouldExecuteThisFrame(this.context)){this.stats.enabled&&this.stats.logSkipped&&console.log(`[Pipeline] Skipped stage '${t.name}' (executionMode: ${t.executionMode})`);continue}try{let n=this.stats.enabled?performance.now():0;if(G_(t,this.renderer,()=>t.render(this.context,e)),this.stats.enabled){let e=performance.now()-n;this.stats.timings.has(t.name)||this.stats.timings.set(t.name,[]);let r=this.stats.timings.get(t.name);r.push(e),r.length>60&&r.shift()}}catch(e){this._reportStageFailure(t.name,`render`,e)}}if(this.context.incrementFrame(),this.eventBus.emit(`frame:complete`,{frame:this.context.getState(`frame`),accumulatedFrames:this.context.getState(`accumulatedFrames`)}),this.stats.enabled){let e=performance.now()-t;this.stats.timings.has(`_total`)||this.stats.timings.set(`_total`,[]);let n=this.stats.timings.get(`_total`);n.push(e),n.length>60&&n.shift(),this.stats.frameCount++}}reset(){this.eventBus.emit(`pipeline:reset`);for(let e of this.stages)if(e.reset)try{e.reset()}catch(t){this._reportStageFailure(e.name,`reset`,t)}this.context.reset(),this.stats.enabled&&(this.stats.timings.clear(),this.stats.frameCount=0)}setSize(e,t){this.width=e,this.height=t,this.context.setState(`width`,e),this.context.setState(`height`,t),this.eventBus.emit(`pipeline:resize`,{width:e,height:t});for(let n of this.stages)if(n.setSize)try{n.setSize(e,t)}catch(e){console.error(`[Pipeline] Error resizing stage '${n.name}':`,e)}}dispose(){for(let e of this.stages)if(e.dispose)try{e.dispose()}catch(t){console.error(`[Pipeline] Error disposing stage '${e.name}':`,t)}this.stages=[],this.context.dispose(),this.eventBus.clear(),this.stats.timings.clear()}setStatsEnabled(e){this.stats.enabled=e,e||(this.stats.timings.clear(),this.stats.frameCount=0)}getStats(){if(!this.stats.enabled)return null;let e={frameCount:this.stats.frameCount,stages:{},total:0};for(let[t,n]of this.stats.timings.entries()){if(n.length===0)continue;let r=n.reduce((e,t)=>e+t,0)/n.length,i=Math.min(...n),a=Math.max(...n);t===`_total`?(e.total=r,e.totalMin=i,e.totalMax=a):e.stages[t]={avg:r,min:i,max:a}}return e}logStats(){let e=this.getStats();if(!e){console.log(`[Pipeline] Stats not enabled`);return}console.group(`[Pipeline] Performance Stats`),console.log(`Frames: ${e.frameCount}`),e.totalMin===void 0?console.log(`Total: no frames recorded yet (pipeline.render() has not run since stats were enabled — the path tracer may have converged and stopped its animation loop)`):console.log(`Total: ${e.total.toFixed(2)}ms (min: ${e.totalMin.toFixed(2)}ms, max: ${e.totalMax.toFixed(2)}ms)`);for(let[t,n]of Object.entries(e.stages))console.log(` ${t}: ${n.avg.toFixed(2)}ms (min: ${n.min.toFixed(2)}ms, max: ${n.max.toFixed(2)}ms)`);console.groupEnd()}getInfo(){return{stageCount:this.stages.length,enabledStages:this.stages.filter(e=>e.enabled).length,stages:this.stages.map(e=>({name:e.name,enabled:e.enabled})),contextState:this.context.getAllState(),textures:this.context.getTextureNames(),renderTargets:this.context.getRenderTargetNames(),uniforms:this.context.getUniformNames(),events:this.eventBus.eventNames()}}logInfo(){let e=this.getInfo();console.group(`[Pipeline] Info`),console.log(`Stages:`,e.stages),console.log(`Context Textures:`,e.textures),console.log(`Context Render Targets:`,e.renderTargets),console.log(`Context Uniforms:`,e.uniforms),console.log(`Event Types:`,e.events),console.log(`State:`,e.contextState),console.groupEnd()}};Ae();var J_=ve(`engine`),Y_=class{constructor(){this.timeElapsed=0,this.lastResetTime=performance.now(),this.renderCompleteDispatched=!1,this.budgetOverrun=!1,this._budgetHeldWarned=!1}updateTime(){this.timeElapsed=(performance.now()-this.lastResetTime)/1e3}isTimeLimitReached(e,t,n){return this.budgetOverrun=!1,t!==`time`&&t!==`timeOnly`||!(n>0)||this.timeElapsed<n?!1:e?.frameCount>0?(this.budgetOverrun=!0,!0):(this._budgetHeldWarned||(this._budgetHeldWarned=!0,J_.warn(`render time limit (${n}s) expired before the first sample landed — holding the deadline open to avoid capturing an empty frame`)),!1)}isLimitReached(e,t,n){return e?this.isTimeLimitReached(e,t,n)?!0:this.stopCondition(e)!==null:!1}stopCondition(e){return this.budgetOverrun?`timeLimit`:e?e.frameCount>=e.completionThreshold?`samples`:e._isConvergedComplete?.()?`converged`:null:null}markComplete(){return this.renderCompleteDispatched?!1:(this.renderCompleteDispatched=!0,!0)}reset(){this.timeElapsed=0,this.lastResetTime=performance.now(),this.renderCompleteDispatched=!1,this.budgetOverrun=!1,this._budgetHeldWarned=!1}resumeFromPause(){this.renderCompleteDispatched=!1,this.lastResetTime=performance.now()-this.timeElapsed*1e3}};hn(),ii(),ui();var X_=864e5,Z_=Object.freeze({IMMUTABLE:`immutable`,REVALIDATE:`revalidate`,NETWORK:`network`}),Q_=(e,t)=>({loaded:e,total:t,lengthComputable:t>0&&e<=t}),$_=(e,t)=>e.headers?.get?.(t)??null,ev=e=>e.reason??new DOMException(`aborted`,`AbortError`);function tv(e){try{let t=new URL(e,globalThis.location?.href??`http://localhost/`).pathname;return decodeURIComponent(t.split(`/`).pop())||`download`}catch{return`download`}}async function nv(e,{onProgress:t,signal:n}){let r=Number($_(e,`content-length`))||0,i=$_(e,`content-type`)??``;if(!e.body)return new Blob([await e.arrayBuffer()],{type:i});let a=e.body.getReader(),o=[],s=0;for(;;){if(n?.aborted)throw a.cancel().catch(()=>{}),ev(n);let{done:e,value:i}=await a.read();if(e)break;o.push(i),s+=i.length,t?.(Q_(s,r))}return new Blob(o,{type:i})}var rv=(e,t,n)=>new File([e],t,{type:n||e.type,lastModified:e.lastModified??Date.now()}),iv=()=>{},av=class{constructor(e){this._storage=e,this._revalidating=new Set}get _area(){return this._storage?.area(mn.DOWNLOADS)??null}async fetch(e,{key:t=e,name:n=tv(e),policy:r=Z_.REVALIDATE,maxAgeMs:i=X_,onProgress:a=null,signal:o=null,fetchOptions:s={}}={}){let c=this._area;if(c&&r!==Z_.NETWORK){let o=await c.open(t);if(o){let c=await o.file(`data`);if(c)return r===Z_.REVALIDATE&&Date.now()-(o.extra.checkedAt??0)>=i&&this._revalidate(e,t,n,o.extra,s),a?.(Q_(c.size,c.size)),{file:rv(c,n,o.extra.contentType),release:()=>o.release(),fromCache:!0};o.release()}}return this._download(e,t,n,{onProgress:a,signal:o,fetchOptions:s,cache:!!c})}async has(e){return await this._area?.has(e)===!0}async _download(e,t,n,{onProgress:r,signal:i,fetchOptions:a,cache:o}){if(i?.aborted)throw ev(i);let s=await fetch(e,{...a,signal:i});if(!s.ok)throw Error(`HTTP ${s.status} fetching ${e}`);let c=Number($_(s,`content-length`))||0,l={url:e,contentType:$_(s,`content-type`)??``,lastModified:$_(s,`last-modified`),contentLength:c||null,checkedAt:Date.now()},u=o&&s.body?await this._area.create(t,{label:n,expectedBytes:c}):null;if(!u)return{file:rv(await nv(s,{onProgress:r,signal:i}),n,l.contentType),release:iv,fromCache:!1};try{await u.writeStream(`data`,s.body,{signal:i,onProgress:e=>r?.(Q_(e,c))}),await u.commit(l)}catch(o){if(await u.abort(),o?.name!==`QuotaExceededError`)throw o;return this._download(e,t,n,{onProgress:r,signal:i,fetchOptions:a,cache:!1})}let d=await this._area.open(t,{wait:!0}),f=d&&await d.file(`data`);if(!f)throw d?.release(),Error(`storage: ${n} vanished right after it was saved`);return{file:rv(f,n,l.contentType),release:()=>d.release(),fromCache:!1}}async _revalidate(e,t,n,r,i){if(this._revalidating.has(t))return;this._revalidating.add(t);let a=!1;try{let t=new Headers(i?.headers);t.set(`Range`,`bytes=0-0`);let n=await fetch(e,{...i,headers:t});if(n.body?.cancel().catch(()=>{}),n.ok){let e=$_(n,`last-modified`),t=n.status===206?Number($_(n,`content-range`)?.match(/\/(\d+)$/)?.[1])||null:Number($_(n,`content-length`))||null;a=!!(e&&r.lastModified&&e!==r.lastModified||t&&r.contentLength&&t!==r.contentLength)}}catch{}try{if(a){let{release:r}=await this._download(e,t,n,{fetchOptions:i,cache:!0});r()}else await this._area.patchMeta(t,{extra:{...r,checkedAt:Date.now()}})}catch{}finally{this._revalidating.delete(t)}}};function ov(e,t,n){return new av(t).fetch(e,n)}function sv(){return new av(ni(si().cacheNamespace))}async function cv(e,{downloads:t=sv(),...n}={}){if(!t._storage||!/^https?:/i.test(e))return{url:e,release:iv,cached:!1};let{file:r,release:i}=await t.fetch(e,n),a=URL.createObjectURL(r);return{url:a,cached:!0,release:()=>{URL.revokeObjectURL(a),i()}}}function lv(e){let t=``;for(let n of e)t+=n.toString(16).padStart(2,`0`);return t}async function uv(e){let t=typeof e==`string`?_v.encode(e):e;return lv(new Uint8Array(await crypto.subtle.digest(`SHA-256`,t)))}async function dv(e){return(await uv(e)).slice(0,32)}async function fv(e){if(e.size<=vv+yv+xv*bv)return uv(new Uint8Array(await e.arrayBuffer()));let t=[e.slice(0,vv)],n=e.size-vv-yv-bv;for(let r=0;r<xv;r++){let i=vv+Math.floor(n*(r+.5)/xv);t.push(e.slice(i,i+bv))}return t.push(e.slice(e.size-yv)),uv(new Uint8Array(await new Blob(t).arrayBuffer()))}async function pv(e){return{name:e.name??``,size:e.size,lastModified:e.lastModified??0,sample:await fv(e)}}async function mv(e){let t=0,n=0,r=e.files.map(({path:e,file:r})=>(t+=r.size,n=Math.max(n,r.lastModified??0),`${e}|${r.size}|${r.lastModified??0}`));return{name:e.name,size:t,lastModified:n,sample:await uv(r.join(`
|
|
858
|
+
`),x_=(0,n.Fn)(([e,t,r,i,a,o,s,c,l,u,d,f,p,m,h,g])=>{let _=(0,n.vec4)(1,0,1,1).toVar(),v=dl({origin:e,direction:t}),y=gl.wrap(Rf(v,r,i).toVar());return(0,n.If)(u.equal((0,n.int)(7)),()=>{let e=(0,n.float)(y.triTests).div(d);_.assign((0,n.select)(e.lessThan(1),(0,n.vec4)((0,n.vec3)(e),1),(0,n.vec4)(1,0,0,1)))}),(0,n.If)(u.equal((0,n.int)(8)),()=>{let e=(0,n.float)(y.boxTests).div(d);_.assign((0,n.select)(e.lessThan(1),(0,n.vec4)((0,n.vec3)(e),1),(0,n.vec4)(1,0,0,1)))}),(0,n.If)(u.equal((0,n.int)(10)),()=>{(0,n.If)(l,()=>{let e=rp({tex:o,samp:(0,n.sampler)(o),direction:t,environmentMatrix:s,environmentIntensity:c,enableEnvironmentLight:l}).toVar(),r=(0,n.dot)(e.xyz,Bl).toVar(),i=r,a=(0,n.max)(d.mul(.1),.001),u=r.div(a),m=(0,n.log)(r.add(1e-6)).add(10).div(10),h=(0,n.select)(d.greaterThan(1),u,m).toVar(),g=(0,n.vec3)(0).toVar();(0,n.If)(h.lessThan(.2),()=>{g.assign((0,n.mix)((0,n.vec3)(0,0,0),(0,n.vec3)(0,0,.5),h.mul(5)))}).ElseIf(h.lessThan(.4),()=>{g.assign((0,n.mix)((0,n.vec3)(0,0,.5),(0,n.vec3)(0,0,1),h.sub(.2).mul(5)))}).ElseIf(h.lessThan(.6),()=>{g.assign((0,n.mix)((0,n.vec3)(0,0,1),(0,n.vec3)(0,1,0),h.sub(.4).mul(5)))}).ElseIf(h.lessThan(.8),()=>{g.assign((0,n.mix)((0,n.vec3)(0,1,0),(0,n.vec3)(1,1,0),h.sub(.6).mul(5)))}).ElseIf(h.lessThan(1),()=>{g.assign((0,n.mix)((0,n.vec3)(1,1,0),(0,n.vec3)(1,0,0),h.sub(.8).mul(5)))}).Else(()=>{g.assign((0,n.mix)((0,n.vec3)(1,0,0),(0,n.vec3)(1,1,1),(0,n.min)(h.sub(1),1)))});let v=f.div(p);(0,n.If)(v.x.lessThan(.1).and(v.y.lessThan(.1)),()=>{let e=i.mul(1);g.assign((0,n.vec3)(e))}).ElseIf(v.x.greaterThan(.9).and(v.y.lessThan(.1)),()=>{g.assign(e.xyz.mul(1))}),_.assign((0,n.vec4)(g,1))}).Else(()=>{_.assign((0,n.vec4)(1,0,1,1))})}),(0,n.If)(u.equal((0,n.int)(4)),()=>{(0,n.If)(y.didHit.not(),()=>{_.assign((0,n.vec4)(0,0,0,1))}).Else(()=>{let t=fl.wrap(fu(y.materialIndex,a)).toVar(),r=Cl.wrap(Np(t,y.uv,y.normal,(0,n.vec4)(0))).toVar().emissive.toVar(),i=(0,n.length)(r).toVar();(0,n.If)(i.greaterThan(0),()=>{let t=r.div((0,n.max)(i.mul(.1),.001)).toVar(),a=(0,n.length)(e.sub(y.hitPoint)),o=(0,n.clamp)((0,n.float)(1).sub(a.div(10)),0,1),s=(0,n.mix)(t,t.mul((0,n.vec3)(1,.8,.6)),o.mul(.3));_.assign((0,n.vec4)(s,1))}).Else(()=>{_.assign((0,n.vec4)(0,0,.1,1))})})}),(0,n.If)(u.equal((0,n.int)(1)),()=>{(0,n.If)(y.didHit.not(),()=>{_.assign((0,n.vec4)(.5,.5,1,1))}).Else(()=>{let e=fl.wrap(fu(y.materialIndex,a)).toVar(),t=(0,n.normalize)(Cl.wrap(Np(e,y.uv,y.normal,(0,n.vec4)(0))).toVar().normal);_.assign((0,n.vec4)(y_({normal:t}),1))})}),(0,n.If)(u.equal((0,n.int)(2)),()=>{(0,n.If)(y.didHit.not(),()=>{_.assign((0,n.vec4)((0,n.vec3)(1),1))}).Else(()=>{let e=b_({worldPos:y.hitPoint,cameraProjectionMatrix:m,cameraViewMatrix:h});_.assign((0,n.vec4)(v_({depth:e}),1))})}),(0,n.If)(u.equal((0,n.int)(3)),()=>{(0,n.If)(y.didHit.not(),()=>{_.assign((0,n.vec4)(0,0,0,1))}).Else(()=>{let e=fl.wrap(fu(y.materialIndex,a)).toVar(),t=Cl.wrap(Np(e,y.uv,y.normal,(0,n.vec4)(0))).toVar().albedo.rgb;_.assign((0,n.vec4)(t,1))})}),(0,n.If)(u.equal((0,n.int)(5)),()=>{(0,n.If)(y.didHit.not(),()=>{_.assign((0,n.vec4)(0,0,0,1))}).Else(()=>{let e=fl.wrap(fu(y.materialIndex,a)).toVar(),t=Cl.wrap(Np(e,y.uv,y.normal,(0,n.vec4)(0))).toVar(),u=t.albedo.rgb,d=(0,n.normalize)(t.normal).toVar(),p=Be({state:Ve({seed:(0,n.uint)(f.x).mul((0,n.uint)(1973)).add((0,n.uint)(f.y).mul((0,n.uint)(9277))).add(g.mul((0,n.uint)(26699)))})}).toVar(),m=cp({N:d,xi:(0,n.vec2)(Ue(p).toVar(),Ue(p).toVar())}).toVar(),h=dl({origin:jl(y.hitPoint,d),direction:m}),v=gl.wrap(Rf(h,r,i,(0,n.bool)(!1),(0,n.bool)(!1)).toVar()),b=(0,n.vec3)(0).toVar();(0,n.If)(v.didHit.not(),()=>{(0,n.If)(l,()=>{b.assign(rp({tex:o,samp:(0,n.sampler)(o),direction:m,environmentMatrix:s,environmentIntensity:c,enableEnvironmentLight:l}).xyz)})}).Else(()=>{let e=fl.wrap(fu(v.materialIndex,a)).toVar(),t=Cl.wrap(Np(e,v.uv,v.normal,(0,n.vec4)(0))).toVar();b.assign(t.emissive),(0,n.If)(l,()=>{let e=(0,n.normalize)(t.normal).toVar(),r=rp({tex:o,samp:(0,n.sampler)(o),direction:e,environmentMatrix:s,environmentIntensity:c,enableEnvironmentLight:l}).xyz;b.addAssign(t.albedo.rgb.mul(r))})});let x=u.mul(b);_.assign((0,n.vec4)(x,1))})}),(0,n.If)(u.equal((0,n.int)(6)),()=>{(0,n.If)(y.didHit,()=>{let e=y.normal.toVar(),r=(0,n.normalize)(t.sub(e.mul((0,n.dot)(t,e).mul(2)))).toVar(),i=rp({tex:o,samp:(0,n.sampler)(o),direction:r,environmentMatrix:s,environmentIntensity:c,enableEnvironmentLight:l}).xyz,a=i.div(i.add(1));_.assign((0,n.vec4)(a,1))}).Else(()=>{let e=rp({tex:o,samp:(0,n.sampler)(o),direction:t,environmentMatrix:s,environmentIntensity:c,enableEnvironmentLight:l}).xyz,r=e.div(e.add(1));_.assign((0,n.vec4)(r,1))})}),_});Dl();function S_(e){let{writeColorTex:t,writeNDTex:r,writeAlbedoTex:i,resolution:a,renderWidth:o,renderHeight:s,cameraWorldMatrix:c,cameraProjectionMatrixInverse:l,cameraProjectionMatrix:u,cameraViewMatrix:d,cameraProjection:f,panoLonRange:p,panoLatRange:m,panoLevelHorizon:h,enableDOF:g,focalLength:_,aperture:v,focusDistance:y,unitsPerMetre:b,apertureScale:x,anamorphicRatio:S,dofMode:C,dofBlur:w,cameraClipStart:T,bvhBuffer:E,triangleBuffer:D,materialBuffer:O,envTexture:k,environmentMatrix:A,environmentIntensity:j,enableEnvironmentLight:M,visMode:N,debugVisScale:P,frame:F}=e;return(0,n.Fn)(()=>{let e=(0,n.int)(n.workgroupId.x).mul(16).add((0,n.int)(n.localId.x)),I=(0,n.int)(n.workgroupId.y).mul(16).add((0,n.int)(n.localId.y));(0,n.If)(e.lessThan(o).and(I.lessThan(s)),()=>{let o=(0,n.vec2)((0,n.float)(e).add(.5),(0,n.float)(I).add(.5)),s=Be({state:(0,n.uint)(I.mul((0,n.int)(a.x)).add(e)).add((0,n.uint)(1))}).toVar(),L=dl.wrap(pf(o.div(a),s,c,l,f,p,m,h,g,_,v,y,b,x,S,C,w)),ee=(0,n.vec4)(1,0,1,1).toVar();(0,n.If)(N.equal((0,n.int)(9)),()=>{let e=tt(o,(0,n.int)(0),s,a,F);ee.assign((0,n.vec4)(e,1,1))}).Else(()=>{ee.assign(x_(L.origin.add(L.direction.mul(uf(L.direction,T,c,f))),L.direction,E,D,O,k,A,j,M,N,P,o,a,u,d,F))});let te=(0,n.uvec2)((0,n.uint)(e),(0,n.uint)(I));(0,n.textureStore)(t,te,ee).toWriteOnly(),(0,n.textureStore)(r,te,(0,n.vec4)(.5,.5,1,1)).toWriteOnly(),(0,n.textureStore)(i,te,(0,n.vec4)(ee.xyz,1)).toWriteOnly()})})}Vd();function C_({sortGlobalHistogram:e,bins:t=256}){return(0,n.Fn)(()=>{(0,n.If)(n.instanceIndex.lessThan((0,n.uint)(t)),()=>{(0,n.atomicStore)(e.element(n.instanceIndex),(0,n.uint)(0))})})}function w_({hitBufferRO:e,activeIndicesReadRO:t,sortGlobalHistogram:r,counters:i,bins:a=256}){return(0,n.Fn)(()=>{let o=n.instanceIndex,s=n.localId.x,c=(0,n.workgroupArray)(`uint`,a).toAtomic();(0,n.If)(s.lessThan((0,n.uint)(a)),()=>{(0,n.atomicStore)(c.element(s),(0,n.uint)(0))}),(0,n.workgroupBarrier)();let l=(0,n.atomicLoad)(i.element((0,n.uint)(Z.ENTERING_COUNT)));(0,n.If)(o.lessThan(l),()=>{let r=(0,n.uint)(cd(e,t.element(o))).clamp((0,n.uint)(0),(0,n.uint)(a-1));(0,n.atomicAdd)(c.element(r),(0,n.uint)(1))}),(0,n.workgroupBarrier)(),(0,n.If)(s.lessThan((0,n.uint)(a)),()=>{let e=(0,n.atomicLoad)(c.element(s));(0,n.If)(e.greaterThan((0,n.uint)(0)),()=>{(0,n.atomicAdd)(r.element(s),e)})})})}function T_({sortGlobalHistogram:e,bins:t=256}){return(0,n.Fn)(()=>{(0,n.If)(n.instanceIndex.equal((0,n.uint)(0)),()=>{let r=(0,n.uint)(0).toVar();(0,n.Loop)({start:(0,n.uint)(0),end:(0,n.uint)(t),type:`uint`},({i:t})=>{let i=e.element(t),a=(0,n.atomicLoad)(i);(0,n.atomicStore)(i,r),r.addAssign(a)})})})}function E_({hitBufferRO:e,activeIndicesReadRO:t,sortedIndicesRW:r,sortGlobalHistogram:i,counters:a,bins:o=256}){return(0,n.Fn)(()=>{let s=n.instanceIndex,c=n.localId.x,l=(0,n.workgroupArray)(`uint`,o).toAtomic();(0,n.If)(c.lessThan((0,n.uint)(o)),()=>{(0,n.atomicStore)(l.element(c),(0,n.uint)(0))}),(0,n.workgroupBarrier)();let u=(0,n.atomicLoad)(a.element((0,n.uint)(Z.ENTERING_COUNT))),d=s.lessThan(u),f=(0,n.uint)(0).toVar(),p=(0,n.uint)(0).toVar();(0,n.If)(d,()=>{f.assign(t.element(s)),p.assign((0,n.uint)(cd(e,f)).clamp((0,n.uint)(0),(0,n.uint)(o-1))),(0,n.atomicAdd)(l.element(p),(0,n.uint)(1))}),(0,n.workgroupBarrier)(),(0,n.If)(c.lessThan((0,n.uint)(o)),()=>{let e=l.element(c),t=(0,n.atomicLoad)(e);(0,n.If)(t.greaterThan((0,n.uint)(0)),()=>{(0,n.atomicStore)(e,(0,n.atomicAdd)(i.element(c),t))})}),(0,n.workgroupBarrier)(),(0,n.If)(d,()=>{r.element((0,n.atomicAdd)(l.element(p),(0,n.uint)(1))).assign(f)})})}async function D_(e,t,n,r,i=0){let a=await e.readRenderTargetPixelsAsync(t,0,0,n,r,i),o=n*4,s=Math.ceil(o*a.BYTES_PER_ELEMENT/256)*256/a.BYTES_PER_ELEMENT;if(s===o)return a;let c=new a.constructor(o*r);for(let e=0;e<r;e++)c.set(a.subarray(e*s,e*s+o),e*o);return c}var O_=class{constructor(e){this.renderer=e,this.target=null,this.material=new t.NodeMaterial,this.material.name=`rayzee:texture-readback`,this.quad=new t.QuadMesh(this.material),this._node=null,this._source=null}_ensureTarget(e,t){this.target&&this.target.width===e&&this.target.height===t||(this.target?.dispose(),this.target=new r.RenderTarget(e,t,{type:r.FloatType,format:r.RGBAFormat,depthBuffer:!1,minFilter:r.NearestFilter,magFilter:r.NearestFilter}))}async read(e,t,n){try{return await D_(this.renderer,this.draw(e,t,n),t,n)}finally{this.release()}}draw(e,t,r){this._ensureTarget(t,r),this._source!==e&&(this._node=(0,n.texture)(e).load((0,n.ivec2)(n.screenCoordinate.xy)),this.material.outputNode=this._node,this.material.needsUpdate=!0,this._source=e);let i=this.renderer.getRenderTarget();return this.renderer.setRenderTarget(this.target),this.quad.render(this.renderer),this.renderer.setRenderTarget(i),this.target}release(){this.target?.dispose(),this.target=null}dispose(){this.target?.dispose(),this.material.dispose(),this.target=null,this._source=null,this._node=null}};O(),Vd(),pr(),lt(),an(),Ae(),Do();var k_=ve(`wavefront`),A_=[`two`,`one`],j_=[`all`,...A_],M_=[`extend`,`shade`,`connect`,`merge`,`globalHist`,`globalScatter`,`compact`,`compactCopyback`,`lightCopyback`],N_=class extends ku{constructor(e,t,r,i={}){super(e,t,r,i),this.name=`PathTracer`,this._packedBuffers=null,this._queueManager=null,this._kernelManager=null,this._m2Attr=null,this._streakAttr=null,this._frozenMaskAttr=null,this._convDebugSource=null,this._dilateFrozenUniform=(0,n.uniform)(1,`int`),this._wavefrontReady=!1,this._kernelsCompiling=null,this._kernelGeneration=0,this._auxGBufferEnabled=!1,this._auxGBufferUniform=(0,n.uniform)(0,`uint`),this._cleanAuxNormalEnabled=!1,this._cleanAuxNormalUniform=(0,n.uniform)(0,`uint`),this._auxSamples=0,this._auxSeedPending=!1,this._useDynamicDispatch=!0,this.sortMaterials=i.sortMaterials??H.wavefrontSortMaterials,this._sortMaterials=!1,this._useSubgroupCompact=!1,this._lastBounceCounts=null,this._lastBounceEnergy=null,this._lastBounceCountsBudget=-1,this._lastBounceCountsLoopBound=-1,this._readbackPending=!1,this._readbackEveryNFrames=4,this._readbackFrameCounter=0,this._readbackGeneration=0,this._curveSizingValid=!1,this._bounceEarlyExitThreshold=1e-4,this._convergedFraction=0,this._convergedGeometryFraction=0,this._geometryPixelCount=0,this._convergedReadbackPending=!1,this._lockstep=!1,this._lockstepRead=null,this._accumulationLockstep=!1,this._lastActivePixelCount=0,this._wfRenderWidth=(0,n.uniform)(1920,`int`),this._wfRenderHeight=(0,n.uniform)(1080,`int`),this._wfMaxRayCount=(0,n.uniform)(0,`uint`),this._wfCurrentBounce=(0,n.uniform)(0,`int`),this._wfChunkRowBase=(0,n.uniform)(0,`int`),this._wfChunkRows=(0,n.uniform)(0,`int`),this._wfIsFirstChunk=(0,n.uniform)(1,`uint`),this._pathBudget=0,this._pathBudgetOverride=0,this.hostMemoryGB=i.hostMemoryGB,this._chunkRows=0,this._numChunks=1,this._outputs=new Map,this._outputsChanged=!1,this._compiledLayers=null,this._shadowRays=`all`,this._compiledPick=null,this._learnsVisibility=!1,this._integratorFactories=new Map,this._integratorInstances=new Map,this._integrator=null,this.vramTracker=new ef(this.renderer),this._registerVRAMProviders(),k_.debug(`initialized (wavefront)`)}_registerVRAMProviders(){let e=this.vramTracker;e.register(`rays`,()=>{let e=this._packedBuffers?._attrs;return e?[e.ray,e.hit]:null}),e.register(`integrator`,()=>this._integrator?.gpuResources()??null),e.register(`queues`,()=>{let e=this._queueManager;return e?[e._countersAttr,e._bounceCountsAttr,e._attrA,e._attrB,e._sortAttr]:null}),e.register(`gbuffer`,()=>{let e=[];return this._m2Attr&&e.push(this._m2Attr),this._streakAttr&&e.push(this._streakAttr),this._frozenMaskAttr&&e.push(this._frozenMaskAttr),e.length?e:null}),e.register(`accum`,()=>{let e=this.storageTextures;return e?[e.writeColor,e.writeNormalDepth,e.writeAlbedo,e.readTarget]:null}),e.register(`geometry`,()=>[...this._geoParts?.attrs??[],...this._shadeParts?.attrs??[],...this._bvhParts?.attrs??[this.bvhStorageAttr]]),e.register(`materials`,()=>{let e=this.materialData;return e?[e.materialStorageAttr,...(e.srgbBuckets||[]).filter(Boolean),...(e.linearBuckets||[]).filter(Boolean)]:null}),e.register(`environment`,()=>{let e=this.environment;return e?[e.environmentTexture,e.envCDFTexture]:null})}setupMaterial(){super.setupMaterial(),this.materialData?.materialCount>0&&(this._kernelManager&&this._kernelManager.dispose(),this._wavefrontReady=!1,this._buildWavefrontKernels())}requestOutput(e,t={}){return this._outputs.set(e,t),this._outputsChanged=!0,()=>{this._outputs.get(e)===t&&(this._outputs.delete(e),this._outputsChanged=!0)}}registerIntegrator(e,t){for(let n of[e].flat())this._integratorFactories.set(n,t)}setIntegrator(e){let t=null;if(e!==`path`){let n=this._integratorFactories.get(e);if(!n){this.issues?.record(X.CAPABILITY_MISSING,`integrator "${e}" is not installed: pathTracer.registerIntegrator(), or rayzee/addons/bidirectional`,{capability:e});return}t=this._integratorInstances.get(n),t||this._integratorInstances.set(n,t=n(this))}t===this._integrator&&(!t||t.name===e)||(this._integrator&&this._integrator!==t&&this._integrator.dispose(),t?.select(e),this._integrator=t,this._pathBudget=0,this._packedBuffers&&this.materialData?.materialCount>0&&(this._kernelManager&&this._kernelManager.dispose(),this._wavefrontReady=!1,this._buildWavefrontKernels()))}setShadowRays(e){j_.includes(e)||(k_.warn(`shadowRays: unknown mode "${e}", using 'all'`),e=`all`),this._shadowRays!==e&&(this._shadowRays=e,this._outputsChanged=!0)}_pickedShadowRays(){if(this._integrator||!A_.includes(this._shadowRays))return null;let e=this.enableEnvironment.value>0,t=this.numDirectionalLights.value+this.numAreaLights.value+this.numPointLights.value+this.numSpotLights.value;return Number(t>0)+Number(e&&this.envTotalSum.value>0)+Number(e&&this.hasSun.value>0)+Number(this.enableEmissiveTriangleSampling.value>0&&this.emissiveTriangleCount.value>0)>(this._shadowRays===`two`?2:1)?this._shadowRays:null}_lightRadiusNeeded(){if(this._integrator)return!1;let e=(e,t,n)=>{if(!t)return!1;let r=this[`${e}LightsBufferNode`].array;for(let i=0;i<t;i++)if(r[i*dt[e]+n]>0)return!0;return!1};return e(`point`,this.numPointLights.value,9)||e(`spot`,this.numSpotLights.value,18)}get integrator(){return this._integrator?.name??`path`}get activeIntegrator(){return this._integrator}render(e){if(!this.isReady||!this._wavefrontReady)return;if(this._materialFeaturesChanged){this._materialFeaturesChanged=!1;let e=this._layersToCompile();dr.some(t=>e[t]&&!this._compiledLayers?.[t])&&(this._outputsChanged=!0),!this._compiledTransmissionMaps&&this.materialData.hasTransmissionMaps()&&(this._outputsChanged=!0),!this._compiledClearcoatNormals&&this._clearcoatNormalsNeeded()&&(this._outputsChanged=!0)}if(A_.includes(this._shadowRays)&&this._pickedShadowRays()!==this._compiledPick&&(this._outputsChanged=!0),this._lightRadiusNeeded()!==this._compiledLightRadius&&(this._outputsChanged=!0),(this._lightBufferRealloc||this._outputsChanged)&&(this._kernelManager&&this._kernelManager.dispose(),this._wavefrontReady=!1,this._buildWavefrontKernels(),!this._wavefrontReady))return;let t=this._lockstepRead;if(t&&this.frameCount>=t.due){if(!t.apply)return;this._lockstepRead=null,t.apply()}if(this.isComplete||this.frameCount>=this.completionThreshold||this._isConvergedComplete())if(this._auxSeedPending)this.isComplete=!1;else{this.isComplete||=!0;return}this.performanceMonitor?.start();let n=this.frameCount,r=this.renderMode.value,i=null;r===1&&n===0&&(i=this.maxBounces.value,this.maxBounces.value=1),this._handleResize(),this.resetHistoryOnRenderModeChange(r),e&&e.setState(`tileRenderingComplete`,!0),this.cameraChanged=this._updateCameraUniforms(),this.cameraOptimizer?.updateInteractionMode(this.cameraChanged),this.cameraChanged&&(this._curveSizingValid=!1,this._readbackGeneration++,this._convergedFraction=0,this._convergedGeometryFraction=0,this._lastActivePixelCount=0),this._updateAccumulationUniforms(n);let a=this._updateAuxAccumulationUniforms(n);this.frame.value=n,this.seedFrame.value=this._seedTick++,this.tracedFrames++,this._lockstep||(this._accumulationLockstep=!1),this._setWfDispatch();let o=this.storageTextures.getReadTextures();this.shaderBuilder.prevColorTexNode&&(this.shaderBuilder.prevColorTexNode.value=o.color,this.shaderBuilder.prevAlbedoTexNode.value=o.albedo,this.shaderBuilder.prevNormalDepthTexNode.value=o.normalDepth),this._refreshWfTextureNodes();let s=this._kernelManager;if((this.visMode?.value|0)>0&&this.visMode.value!==11){s.dispatch(`debug`),this.storageTextures.copyToReadTargets(this.renderer);let t=this.storageTextures.getReadTextures();e&&this._publishTexturesToContext(e,t),this._emitStateEvents(),this.cameraOptimizer?.isInInteractionMode()||this.frameCount++,i!==null&&(this.maxBounces.value=i),this.performanceMonitor?.end();return}let c=this.maxBounces.value,l=this._bounceLoopBound(),u=this._wfRenderHeight.value,d=this._chunkRows,f=this._numChunks<=1;l>this._lastBounceCountsLoopBound&&(this._curveSizingValid=!1);let p=this._lastBounceCounts,m=c<=this._lastBounceCountsBudget&&l<=this._lastBounceCountsLoopBound,h=f&&p?m?l+1:Math.min(this._lastBounceCountsBudget,this._lastBounceCountsLoopBound):0,g=this._integrator?.beginFrame(l)?this._integrator:null;this._learnsVisibility&&n===0&&(this._pinSeedToFrame||this._lockstep||!this.cameraChanged)&&s.dispatch(`visibilityClear`);for(let e=0,t=0;t<u;t+=d,e++){let r=Math.min(d,u-t),i=this._setChunk(t,r,e),a=this.usePixelFreeze.value>0&&!this._auxSeedPending,o=f&&a&&this._curveSizingValid&&this._lastActivePixelCount>0?this._lastActivePixelCount:i;if(a){let e=Math.min(i,Math.ceil(o*1.5)+1024);s.setDispatchForCount(`generateList`,e),s.dispatch(`resetFrameCounters`),s.dispatch(`buildActivePixels`),s.dispatch(`seedEnter`),s.dispatch(`generateList`)}else s.dispatch(`generate`),s.dispatch(`initActiveIndices`);e===0&&n>0&&this.useAdaptiveSampling.value>0&&this._willReadCountersThisFrame()&&s.dispatch(`countConvergedDilated`);let c=this._lastBounceEnergy,m=this._bounceEarlyExitThreshold>=0?this._bounceEarlyExitThreshold*i*64:-1;for(let e=0;e<=l;e++){this._wfCurrentBounce.value=e;let t=this._useDynamicDispatch;if(t){let t=i;if(f&&e>0&&this._curveSizingValid){let n=e-1,r;n<h&&p[n]!==void 0?r=p[n]:h>0&&(r=p[h-1]),t=r>0?r:i}else e===0&&a&&(t=o);let n=Math.min(i,Math.ceil(t*1.5)+1024);for(let e of M_)s.setDispatchForCount(e,n)}else{s.dispatch(`enterFull`);for(let e of M_)s.setDispatchForCount(e,i)}if(s.dispatch(`extend`),this._sortMaterials&&(s.dispatch(`resetGlobalHist`),s.dispatch(`globalHist`),s.dispatch(`globalPrefix`),s.dispatch(`globalScatter`)),g?.beforeShade(),s.dispatch(`shade`),g?.afterShade(s),s.dispatch(`compact`),t?s.dispatch(`compactCopyback`):s.dispatch(`snapshotBounceCount`),m>=0&&e<h&&e<l&&c?.[e]!==void 0&&c[e]<=m)break}g?.resolve(s),s.dispatch(`finalWrite`)}this._learnsVisibility&&s.dispatch(`visibilityFold`),this._maybeReadbackCounters(),this.storageTextures.copyToReadTargets(this.renderer,this._auxGBufferEnabled);let _=this.storageTextures.getReadTextures();e&&this._publishTexturesToContext(e,_),this._emitStateEvents(),this.cameraOptimizer?.isInInteractionMode()||this.frameCount++,this._auxGBufferEnabled&&(this._auxSamples=a?this._auxSamples+1:1),this._auxSeedPending=!1,i!==null&&(this.maxBounces.value=i),this.performanceMonitor?.end()}_isConvergedComplete(){return this.useAdaptiveSampling.value>0&&this.frameCount>=this.adaptiveMinSamples.value&&this._convergedFraction>=this.adaptiveStopFraction.value&&this._convergedGeometryFraction>=this.adaptiveStopFraction.value}async captureAccumulation(){let e=this.storageTextures,t=e.renderWidth,n=e.renderHeight,r=t*n,i=r=>D_(this.renderer,e.readTarget,t,n,r),a=async(e,t)=>e?new t(await this.renderer.getArrayBufferAsync(e,null,0,r*4)):null,o=this._auxGBufferEnabled&&this._auxSamples>0,s={frameCount:this.frameCount,seedTick:this._seedTick,auxSamples:o?this._auxSamples:0,convergedFraction:this._convergedFraction,convergedGeometryFraction:this._convergedGeometryFraction,isComplete:this.isComplete},c=[i(0),o?i(1):null,o?i(2):null,a(this._m2Attr,Float32Array),a(this._streakAttr,Uint32Array),a(this._frozenMaskAttr,Uint32Array)],[l,u,d,f,p,m]=await Promise.all(c);return{width:t,height:n,state:s,color:l,normalDepth:u,albedo:d,m2:f,streak:p,frozenMask:m}}restoreAccumulation(e){let t=this.storageTextures,{width:n,height:r,state:i}=e;if(t.renderWidth!==n||t.renderHeight!==r)throw Error(`checkpoint is ${n}×${r}; the render is ${t.renderWidth}×${t.renderHeight}`);let a=this.renderer.backend,o=a.device;a.get(t.readTarget.textures[0]).texture||this.renderer.initRenderTarget(t.readTarget);let s=(e,i)=>o.queue.writeTexture({texture:a.get(t.readTarget.textures[e]).texture},i,{bytesPerRow:n*16,rowsPerImage:r},{width:n,height:r}),c=(e,t)=>{e&&t&&o.queue.writeBuffer(a.get(e).buffer,0,t)};s(0,e.color),e.normalDepth&&s(1,e.normalDepth),e.albedo&&s(2,e.albedo),c(this._m2Attr,e.m2),c(this._streakAttr,e.streak),c(this._frozenMaskAttr,e.frozenMask),this.frameCount=i.frameCount,this.frame.value=i.frameCount,this._seedTick=i.seedTick,this.hasPreviousAccumulated.value=+(i.frameCount>0),this._auxSamples=e.normalDepth?i.auxSamples:0,this._auxSeedPending=this._auxGBufferEnabled&&!e.normalDepth,this._convergedFraction=i.convergedFraction??0,this._convergedGeometryFraction=i.convergedGeometryFraction??0,this.isComplete=!1,this._accumulationLockstep=!1}reset(){super.reset(),this._convergedFraction=0,this._convergedGeometryFraction=0,this._lastActivePixelCount=0,this._auxSamples=0,this._auxSeedPending=!1,this._lockstep&&(this._lockstepRead=null,this._readbackGeneration++,this._lastBounceCounts=null,this._lastBounceEnergy=null,this._lastBounceCountsBudget=-1,this._lastBounceCountsLoopBound=-1,this._curveSizingValid=!1)}setLockstepReadbacks(e){e=!!e,e!==this._lockstep&&(this._lockstep=e,this._lockstepRead=null,this._readbackGeneration++)}get lockstepReadbacks(){return this._lockstep}get accumulationLockstep(){return this.frameCount>0?this._accumulationLockstep:this._lockstep}readbackWait(){if(this._kernelsCompiling)return this._kernelsCompiling;let e=this._lockstepRead;return e&&!e.apply&&this.frameCount>=e.due?e.read:null}_compileKernels(){let e=++this._kernelGeneration;if(!nf.canCompileInBackground){this._kernelsCompiling=null,this._wavefrontReady=!0;return}let t=this._kernelManager;this.emit(`pathtracer:compiling`,{compiling:!0}),this._kernelsCompiling=t.compile().catch(e=>k_.warn(`background kernel compile failed — compiling at first dispatch: ${e?.message??e}`)).then(()=>{e===this._kernelGeneration&&(this._kernelsCompiling=null,this._wavefrontReady=!0,this.emit(`pathtracer:compiling`,{compiling:!1}))})}getConvergenceDebugSource(){return!this._m2Attr||!this._frozenMaskAttr?null:(this._convDebugSource?.m2===this._m2Attr&&this._convDebugSource.frozenMask===this._frozenMaskAttr||(this._convDebugSource={m2:this._m2Attr,frozenMask:this._frozenMaskAttr,frame:this.frame,renderWidth:this._wfRenderWidth,renderHeight:this._wfRenderHeight,noiseThreshold:this.noiseThreshold,pixelFreezeThreshold:this.pixelFreezeThreshold,usePixelFreeze:this.usePixelFreeze,adaptiveMinSamples:this.adaptiveMinSamples}),this._convDebugSource)}getConvergenceStats(){let e=this._wfRenderWidth.value*this._wfRenderHeight.value;return{converged:this._convergedFraction,convergedGeometry:this._convergedGeometryFraction,geometryPixels:this._geometryPixelCount,activePixels:this._lastActivePixelCount,totalPixels:e,frame:this.frameCount}}_handleResize(){let e=this.storageTextures.renderWidth,t=this.storageTextures.renderHeight;super._handleResize(),this._rebuildKernelsIfResized(e,t)}setAuxGBufferEnabled(e){e=!!e,e&&!this._outputs.has(`gBuffer`)&&this.requestOutput(`gBuffer`),this._auxGBufferEnabled!==e&&(this._auxGBufferEnabled=e,this._auxGBufferUniform.value=+!!e,this.restartAuxAccumulation())}setCleanAuxNormal(e){e=!!e,this._cleanAuxNormalEnabled!==e&&(this._cleanAuxNormalEnabled=e,this._cleanAuxNormalUniform.value=+!!e,this.restartAuxAccumulation())}restartAuxAccumulation(){this._auxSamples=0,this._auxSeedPending=this._auxGBufferEnabled}_updateAuxAccumulationUniforms(e){let t=this.accumulationEnabled&&!this.cameraIsMoving.value&&e>0&&this.hasPreviousAccumulated.value>0&&this.visMode.value!==11,n=this._auxGBufferEnabled&&t&&!this._auxSeedPending&&this._auxSamples>0;return this.hasPreviousAux.value=+!!n,this.auxAccumulationAlpha.value=n?1/(this._auxSamples+1):1,n}setSize(e,t){let n=this.storageTextures.renderWidth,r=this.storageTextures.renderHeight;super.setSize(e,t),this._rebuildKernelsIfResized(n,r)}_willReadCountersThisFrame(){return this.cameraOptimizer?.isInInteractionMode()?!1:this._lockstep?!this._lockstepRead&&this.frameCount%this._readbackEveryNFrames===0:this.cameraChanged||this._readbackPending||this._convergedReadbackPending?!1:this._readbackFrameCounter+1>=this._readbackEveryNFrames}_bounceLoopBound(){return this.maxBounces.value+this.transmissiveBounces.value+this.maxSubsurfaceSteps.value+1}_maybeReadbackCounters(){if(this._lockstep){this._issueLockstepReadback();return}if(this.cameraChanged||this.cameraOptimizer?.isInInteractionMode()){this._readbackFrameCounter=this._readbackEveryNFrames;return}if(this._readbackPending||((this.maxBounces.value!==this._lastBounceCountsBudget||this._bounceLoopBound()!==this._lastBounceCountsLoopBound)&&(this._readbackFrameCounter=this._readbackEveryNFrames),this._readbackFrameCounter++,this._readbackFrameCounter<this._readbackEveryNFrames))return;this._readbackFrameCounter=0;let e=this._queueManager?.getBounceCountsAttribute();if(!e)return;this._readbackPending=!0;let t=this._readbackGeneration,n=this.maxBounces.value,r=this._bounceLoopBound(),i=this._queueManager.MAX_BOUNCE_SNAPSHOTS,a=this._integrator?.curveKey??null;if(this.renderer.getArrayBufferAsync(e).then(e=>{t===this._readbackGeneration&&this._applyBounceCounts(e,n,r,i,a),this._readbackPending=!1}).catch(e=>{k_.warn(`bounceCounts readback failed:`,e),this._readbackPending=!1}),!this._convergedReadbackPending){let e=this._queueManager?.getCountersAttribute();if(e){this._convergedReadbackPending=!0;let t=this._readbackGeneration,n=this._wfRenderWidth.value*this._wfRenderHeight.value;this.renderer.getArrayBufferAsync(e,null,0,Z.COUNT*4).then(e=>{t===this._readbackGeneration&&n>0&&this._applyCounters(e,n),this._convergedReadbackPending=!1}).catch(()=>{this._convergedReadbackPending=!1})}}}_issueLockstepReadback(){if(this._lockstepRead||this.frameCount%this._readbackEveryNFrames!==0||this.cameraOptimizer?.isInInteractionMode())return;let e=this._queueManager?.getBounceCountsAttribute(),t=this._queueManager?.getCountersAttribute();if(!e||!t)return;let n=this._readbackGeneration,r=this.maxBounces.value,i=this._bounceLoopBound(),a=this._queueManager.MAX_BOUNCE_SNAPSHOTS,o=this._wfRenderWidth.value*this._wfRenderHeight.value,s=this._integrator?.curveKey??null,c={due:this.frameCount+this._readbackEveryNFrames,read:null,apply:null};c.read=Promise.all([this.renderer.getArrayBufferAsync(e),this.renderer.getArrayBufferAsync(t,null,0,Z.COUNT*4)]).then(([e,t])=>{c.apply=()=>{n===this._readbackGeneration&&(this._applyBounceCounts(e,r,i,a,s),o>0&&this._applyCounters(t,o))}},e=>{k_.warn(`lockstep readback failed:`,e),c.apply=()=>{}}),this._lockstepRead=c}_applyBounceCounts(e,t,n,r,i=null){let a=new Uint32Array(e.slice(0));this._lastBounceCounts=a.subarray(0,r),this._lastBounceEnergy=a.subarray(r,2*r),this._integrator?.applyLightCurve(a.subarray(2*r,3*r),a.subarray(3*r,4*r),i),this._lastBounceCountsBudget=t,this._lastBounceCountsLoopBound=n,this._curveSizingValid=!0}_applyCounters(e,t){let n=new Uint32Array(e);this._convergedFraction=n[Z.CONVERGED_COUNT]/t;let r=n[Z.GEOMETRY_COUNT];this._geometryPixelCount=r,this._convergedGeometryFraction=r>0?n[Z.CONVERGED_GEOMETRY_COUNT]/r:1,this._lastActivePixelCount=n[Z.ACTIVE_PIXEL_COUNT]}_refreshWfTextureNodes(){let e=this._wfTexNodes;if(!e)return;let t=this.environment?.environmentTexture;t&&e.envTex&&(e.envTex.value=t),this.environment?.envCDFTexture&&e.envCDFTex&&(e.envCDFTex.value=this.environment.envCDFTexture);let n=this.materialData;n&&(_p(e.srgbBuckets,n.srgbBuckets),_p(e.linearBuckets,n.linearBuckets))}_rebuildKernelsIfResized(e,t){let n=this.storageTextures.renderWidth,r=this.storageTextures.renderHeight;if(!(n===e&&r===t||!(this.materialData?.materialCount>0))){if(this._lastBounceCounts&&this._numChunks<=1&&e>0&&t>0){let i=n*r/(e*t),a=e=>Math.min(4294967295,Math.round(e*i));this._lastBounceCounts=this._lastBounceCounts.map(a),this._lastBounceEnergy=this._lastBounceEnergy.map(a)}else this._lastBounceCounts=null,this._lastBounceEnergy=null,this._lastBounceCountsBudget=-1,this._lastBounceCountsLoopBound=-1;this._curveSizingValid=!1,this._readbackFrameCounter=0,this._readbackGeneration++,this._convergedFraction=0,this._convergedGeometryFraction=0,this._lastActivePixelCount=0,this._packedBuffers?this._resizeWavefrontInPlace(n,r):(this._kernelManager&&this._kernelManager.dispose(),this._wavefrontReady=!1,this._buildWavefrontKernels())}}_resizeWavefrontInPlace(e,t){this._wfRenderWidth.value=e,this._wfRenderHeight.value=t,this._updateChunkLayout()}_computePathBudget(){let e=((this._integrator?.hitStride??3)+1)*16,t=112+e+4+4+4,n=this.renderer?.backend?.device?.limits,r=n?.maxStorageBufferBindingSize||128*1024*1024,i=n?.maxBufferSize||r,a=co(this.hostMemoryGB).gb*1024*1024*1024,o=this._integrator?.cacheBytes(r,a)??0;if(this._pathBudgetOverride>0)return this._pathBudgetOverride;let s=Math.floor(Math.min(r*.9/112,(r*.9-o)/e)),c=Math.min(a*.25,i*4)-o,l=Math.floor(c/t),u=Math.min(s,l,2048*2048);return u=Math.max(262144,u),u}_updateChunkLayout(){let e=Math.max(1,this.storageTextures.renderWidth),t=this.storageTextures.renderHeight,n=this._pathBudget||e*t;this._chunkRows=Math.max(1,Math.min(Math.floor(n/e),t)),this._numChunks=Math.max(1,Math.ceil(t/this._chunkRows))}reallocateReservedStorage(){if(!this.storageTextures.writeColor)return;let e=Math.min(this.storageTextures.renderWidth||1,Me),t=Math.min(this.storageTextures.renderHeight||1,Me);this.storageTextures.create(e,t),this.resolution.value.set(e,t),!(!this._packedBuffers||!(this.materialData?.materialCount>0))&&(this._kernelManager&&this._kernelManager.dispose(),this._wavefrontReady=!1,this._buildWavefrontKernels())}_clearcoatNormalsNeeded(){return!this._integrator&&this.materialData.hasClearcoatNormals()}_layersToCompile(){return this.materialData.materialLayers()}get _gBufferCompiled(){return this._outputs.has(`gBuffer`)||this._outputs.has(`hitDistance`)}_buildWavefrontKernels(){let e=this.shaderBuilder.getSceneTextureNodes();if(!e)return;this._lightBufferRealloc=!1,this._outputsChanged=!1,this._integrator?.beforeKernelBuild();let t=this.storageTextures.renderWidth,r=this.storageTextures.renderHeight;this._pathBudget||=this._computePathBudget();let i=this._pathBudget;this._updateChunkLayout();let a=this._chunkRows*t,o=this._integrator?.lightVertices??0;this._packedBuffers?this._packedBuffers.resize(i,o):this._packedBuffers=new Ru(i,this.renderer,o);let s=this._packedBuffers.hitBuffer.rw,c=this._packedBuffers.hitBuffer.ro,l=Me*Me;(!this._m2Attr||this._m2Attr.count<l)&&(Au(this.renderer,this._m2Attr),this._m2Attr=v(l,1),Au(this.renderer,this._streakAttr),this._streakAttr=v(l,1,Uint32Array),Au(this.renderer,this._frozenMaskAttr),this._frozenMaskAttr=v(l,1,Uint32Array)),this._integrator?.allocate(l);let u=(0,n.storage)(this._m2Attr,`float`),d=(0,n.storage)(this._streakAttr,`uint`),f=(0,n.storage)(this._streakAttr,`uint`).toReadOnly(),p=(0,n.storage)(this._frozenMaskAttr,`uint`),m=(0,n.storage)(this._frozenMaskAttr,`uint`).toReadOnly();this._queueManager?this._queueManager.resize(this._packedBuffers.capacity):this._queueManager=new Jd(this._packedBuffers.capacity,this.renderer),this._kernelManager||=new nf(this.renderer);let h=this._packedBuffers,g=this._queueManager;this._wfRenderWidth.value=t,this._wfRenderHeight.value=r,this._wfMaxRayCount.value=Math.min(i,this._chunkRows*t);let _=this.shaderBuilder.prevColorTexNode,y=this.shaderBuilder.prevAlbedoTexNode,b=this.shaderBuilder.prevNormalDepthTexNode,x=this.storageTextures.getWriteTextures(),S=this._pickedShadowRays();this._compiledPick=S;let C=S!==null;this._learnsVisibility=C,g.setVisibilityTable(C);let w=g.getCounters(),T=g.getBounceCounts(),E=this._wfCurrentBounce,D=(0,n.Fn)(()=>{let e=(0,n.atomicLoad)(w.element((0,n.uint)(Z.ACTIVE_RAY_COUNT))),t=(0,n.uint)(E).clamp((0,n.uint)(0),(0,n.uint)(g.MAX_BOUNCE_SNAPSHOTS-1));T.element(t).assign(e),T.element(t.add((0,n.uint)(g.MAX_BOUNCE_SNAPSHOTS))).assign((0,n.atomicLoad)(w.element((0,n.uint)(Z.ACTIVE_ENERGY)))),(0,n.atomicStore)(w.element((0,n.uint)(Z.ENTERING_COUNT)),e)});this._kernelManager.register(`snapshotBounceCount`,D().compute([1,1,1],[1,1,1]));let O=g.activeIndices.a,k=(0,n.Fn)(()=>{let e=n.instanceIndex;(0,n.If)(e.lessThan(this._wfMaxRayCount),()=>{O.element(e).assign(e)}),(0,n.If)(e.equal((0,n.uint)(0)),()=>{(0,n.atomicStore)(w.element((0,n.uint)(Z.ACTIVE_RAY_COUNT)),this._wfMaxRayCount),(0,n.atomicStore)(w.element((0,n.uint)(Z.ENTERING_COUNT)),this._wfMaxRayCount),(0,n.If)(this._wfIsFirstChunk.greaterThan((0,n.uint)(0)),()=>{(0,n.atomicStore)(w.element((0,n.uint)(Z.CONVERGED_COUNT)),(0,n.uint)(0)),(0,n.atomicStore)(w.element((0,n.uint)(Z.GEOMETRY_COUNT)),(0,n.uint)(0)),(0,n.atomicStore)(w.element((0,n.uint)(Z.CONVERGED_GEOMETRY_COUNT)),(0,n.uint)(0))})})});this._kernelManager.register(`initActiveIndices`,k().compute([Math.ceil(this._chunkRows*t/256),1,1],[256,1,1]));let A={rayBufferRW:h.rayBuffer.rw,hitBufferRW:h.hitBuffer.rw,gBufferRW:s,resolution:this.resolution,frame:this.seedFrame,cameraWorldMatrix:this.cameraWorldMatrix,cameraProjectionMatrixInverse:this.cameraProjectionMatrixInverse,cameraProjection:this.cameraProjection,panoLonRange:this.panoLonRange,panoLatRange:this.panoLatRange,panoLevelHorizon:this.panoLevelHorizon,enableDOF:this.enableDOF,focalLength:this.focalLength,aperture:this.aperture,focusDistance:this.focusDistance,unitsPerMetre:this.unitsPerMetre,apertureScale:this.apertureScale,anamorphicRatio:this.anamorphicRatio,dofMode:this.dofMode,dofBlur:this.dofBlur,cameraClipStart:this.cameraClipStart,renderWidth:this._wfRenderWidth,renderHeight:this._wfRenderHeight,chunkRowBase:this._wfChunkRowBase,chunkRows:this._wfChunkRows,transmissiveBounces:this.transmissiveBounces,transparentBackground:this.transparentBackground,auxGBufferEnabled:this._auxGBufferUniform,gBuffer:this._gBufferCompiled,bidirectional:this._integrator?.uniforms??null},j=mf(A);this._kernelManager.register(`generate`,j().compute([Math.ceil(t/16),Math.ceil(this._chunkRows/16),1],[16,16,1]));let M=this.pixelFreezeStability,N=(0,n.Fn)(()=>{(0,n.atomicStore)(w.element((0,n.uint)(Z.ACTIVE_RAY_COUNT)),(0,n.uint)(0)),(0,n.If)(this._wfIsFirstChunk.greaterThan((0,n.uint)(0)),()=>{(0,n.atomicStore)(w.element((0,n.uint)(Z.CONVERGED_COUNT)),(0,n.uint)(0)),(0,n.atomicStore)(w.element((0,n.uint)(Z.GEOMETRY_COUNT)),(0,n.uint)(0)),(0,n.atomicStore)(w.element((0,n.uint)(Z.CONVERGED_GEOMETRY_COUNT)),(0,n.uint)(0))})});this._kernelManager.register(`resetFrameCounters`,N().compute([1,1,1],[1,1,1]));let P=(0,n.Fn)(()=>{let e=n.instanceIndex;(0,n.If)(e.lessThan(this._wfMaxRayCount),()=>{let t=(0,n.uint)((0,n.int)(e).add(this._wfChunkRowBase.mul(this._wfRenderWidth))).toVar(),r=(0,n.uint)(0).toVar();(0,n.If)(this.frame.greaterThan((0,n.uint)(0)).and(f.element(t).bitAnd((0,n.uint)(1073741823)).greaterThanEqual((0,n.uint)(M))),()=>{r.assign((0,n.uint)(1)),(0,n.If)(this._dilateFrozenUniform.greaterThan((0,n.int)(0)),()=>{let e=(0,n.int)(t).mod(this._wfRenderWidth),i=(0,n.int)(t).div(this._wfRenderWidth);for(let[t,a]of[[-1,-1],[0,-1],[1,-1],[-1,0],[1,0],[-1,1],[0,1],[1,1]]){let o=e.add((0,n.int)(t)),s=i.add((0,n.int)(a));(0,n.If)(o.greaterThanEqual((0,n.int)(0)).and(o.lessThan(this._wfRenderWidth)).and(s.greaterThanEqual((0,n.int)(0))).and(s.lessThan(this._wfRenderHeight)),()=>{(0,n.If)(f.element((0,n.uint)(s.mul(this._wfRenderWidth).add(o))).bitAnd((0,n.uint)(1073741823)).lessThan((0,n.uint)(M)),()=>{r.assign((0,n.uint)(0))})})}})}),p.element(t).assign(r),(0,n.If)(r.equal((0,n.uint)(0)),()=>{let t=(0,n.atomicAdd)(w.element((0,n.uint)(Z.ACTIVE_RAY_COUNT)),(0,n.uint)(1));O.element(t).assign(e)})})});this._kernelManager.register(`buildActivePixels`,P().compute([Math.ceil(this._chunkRows*t/256),1,1],[256,1,1]));let F=(0,n.Fn)(()=>{let e=n.instanceIndex,t=this._wfRenderWidth,r=this._wfRenderHeight;(0,n.If)(e.lessThan((0,n.uint)(t.mul(r))),()=>{let i=(0,n.int)(e).mod(t),a=(0,n.int)(e).div(t),o=(0,n.uint)(2147483648),s=(0,n.uint)(1073741824),c=f.element(e).toVar(),l=c.bitAnd(s).notEqual((0,n.uint)(0)),u=c.bitAnd(o).notEqual((0,n.uint)(0)).toVar();(0,n.If)(u,()=>{for(let[e,s]of[[-1,-1],[0,-1],[1,-1],[-1,0],[1,0],[-1,1],[0,1],[1,1]]){let c=i.add((0,n.int)(e)),l=a.add((0,n.int)(s));(0,n.If)(c.greaterThanEqual((0,n.int)(0)).and(c.lessThan(t)).and(l.greaterThanEqual((0,n.int)(0))).and(l.lessThan(r)),()=>{(0,n.If)(f.element((0,n.uint)(l.mul(t).add(c))).bitAnd(o).equal((0,n.uint)(0)),()=>{u.assign(!1)})})}}),(0,n.If)(u,()=>{(0,n.atomicAdd)(w.element((0,n.uint)(Z.CONVERGED_COUNT)),(0,n.uint)(1))}),(0,n.If)(l,()=>{(0,n.atomicAdd)(w.element((0,n.uint)(Z.GEOMETRY_COUNT)),(0,n.uint)(1)),(0,n.If)(u,()=>{(0,n.atomicAdd)(w.element((0,n.uint)(Z.CONVERGED_GEOMETRY_COUNT)),(0,n.uint)(1))})})})});this._kernelManager.register(`countConvergedDilated`,F().compute([Math.ceil(t*r/256),1,1],[256,1,1]));let I=(0,n.Fn)(()=>{let e=(0,n.atomicLoad)(w.element((0,n.uint)(Z.ACTIVE_RAY_COUNT)));(0,n.atomicStore)(w.element((0,n.uint)(Z.ENTERING_COUNT)),e),(0,n.atomicStore)(w.element((0,n.uint)(Z.ACTIVE_PIXEL_COUNT)),e)});this._kernelManager.register(`seedEnter`,I().compute([1,1,1],[1,1,1]));let L=mf({...A,listDriven:!0,activeIndicesRO:g.activeIndicesRO.a,counters:w});this._kernelManager.register(`generateList`,L().compute([Math.ceil(a/256),1,1],[256,1,1]));let ee=this.bvhStorageNode,te=this.triangleStorageNode,R=this.materialData.materialStorageNode,ne=(0,n.texture)(this.environment.envCDFTexture),re=this.lightDataNode,ie=this.materialData,ae=this.environment,oe=gp(ie.srgbBuckets),se=gp(ie.linearBuckets),ce={srgbBuckets:oe,linearBuckets:se,shadowAlbedoMaps:oe,goboMaps:e.goboMapsTex,iesProfiles:e.iesProfilesTex,alphaShadows:this.uniforms.get(`enableAlphaShadows`),materialLayers:this._compiledLayers=this._layersToCompile(),lightRadius:this._compiledLightRadius=this._lightRadiusNeeded(),transmissionMaps:this._compiledTransmissionMaps=this.materialData.hasTransmissionMaps(),clearcoatNormals:this._compiledClearcoatNormals=this._clearcoatNormalsNeeded()},le=e=>ur(e,ce),z=ae.environmentTexture?(0,n.texture)(ae.environmentTexture):e.envTex;this._wfTexNodes={envTex:z,envCDFTex:ne,srgbBuckets:oe,linearBuckets:se},this._sortMaterials=this.sortMaterials&&(this.materialData?.materialCount??0)>8;let ue=Yf({bvhBuffer:ee,triangleBuffer:te,rayBufferRO:h.rayBuffer.ro,hitBufferRW:h.hitBuffer.rw,activeIndicesRO:g.getActiveReadRO(),counters:w,maxRayCount:this._wfMaxRayCount,shadowTerminatorOffset:this.shadowTerminatorOffset});if(this._kernelManager.register(`extend`,ue().compute([Math.ceil(a/256),1,1],[256,1,1])),this._sortMaterials){let e=g.getSortGlobalHistogram(),t=Math.min(256,this.materialData?.materialCount??256);this._kernelManager.register(`resetGlobalHist`,C_({sortGlobalHistogram:e,bins:t})().compute([1,1,1],[256,1,1])),this._kernelManager.register(`globalHist`,w_({hitBufferRO:h.hitBuffer.ro,activeIndicesReadRO:g.getActiveReadRO(),sortGlobalHistogram:e,counters:w,bins:t})().compute([Math.ceil(a/256),1,1],[256,1,1])),this._kernelManager.register(`globalPrefix`,T_({sortGlobalHistogram:e,bins:t})().compute([1,1,1],[1,1,1])),this._kernelManager.register(`globalScatter`,E_({hitBufferRO:h.hitBuffer.ro,activeIndicesReadRO:g.getActiveReadRO(),sortedIndicesRW:g.getSortedRW(),sortGlobalHistogram:e,counters:w,bins:t})().compute([Math.ceil(a/256),1,1],[256,1,1]))}let de=f_({gBufferRW:s,bvhBuffer:ee,triangleBuffer:te,materialBuffer:R,envCDFTexture:ne,lightBuffer:re,rayBufferRW:h.rayBuffer.rw,hitBufferRW:h.hitBuffer.rw,counters:w,activeIndicesRO:this._sortMaterials?g.getSortedRO():g.getActiveReadRO(),envTexture:z,environmentIntensity:this.environmentIntensity,envMatrix:this.environmentMatrix,enableEnvironmentLight:this.enableEnvironment,groundProjectionEnabled:this.groundProjectionEnabled,groundProjectionRadius:this.groundProjectionRadius,groundProjectionHeight:this.groundProjectionHeight,groundProjectionLevel:this.groundProjectionLevel,enableGroundCatcher:this.enableGroundCatcher,groundCatcherHeight:this.groundCatcherHeight,envTotalSum:this.envTotalSum,envResolution:this.envResolution,directionalLightsBuffer:this.directionalLightsBufferNode,numDirectionalLights:this.numDirectionalLights,areaLightsBuffer:this.areaLightsBufferNode,numAreaLights:this.numAreaLights,pointLightsBuffer:this.pointLightsBufferNode,numPointLights:this.numPointLights,spotLightsBuffer:this.spotLightsBufferNode,numSpotLights:this.numSpotLights,maxBounceCount:this.maxBounces,maxSubsurfaceSteps:this.maxSubsurfaceSteps,maxTransparentBounces:this.maxTransparentBounces,transparentBackground:this.transparentBackground,backgroundIntensity:this.backgroundIntensity,backgroundColor:this.backgroundColor,backgroundBlurriness:this.backgroundBlurriness,backgroundBlurSamples:this.backgroundBlurSamples,showBackground:this.showBackground,globalIlluminationIntensity:this.globalIlluminationIntensity,cameraProjectionMatrix:this.cameraProjectionMatrix,cameraViewMatrix:this.cameraViewMatrix,fireflyThreshold:this.fireflyThreshold,shadowTerminatorOffset:this.shadowTerminatorOffset,frame:this.seedFrame,accumFrame:this.frame,resolution:this.resolution,emissiveTriangleCount:this.emissiveTriangleCount,emissiveVec4Offset:this.emissiveVec4Offset,emissiveTotalPower:this.emissiveTotalPower,emissiveBoost:this.emissiveBoost,enableEmissiveTriangleSampling:this.enableEmissiveTriangleSampling,lightBVHNodeCount:this.lightBVHNodeCount,reverseMapVec4Offset:this.reverseMapVec4Offset,currentBounce:this._wfCurrentBounce,maxRayCount:this._wfMaxRayCount,chunkRowBase:this._wfChunkRowBase,auxGBufferEnabled:this._auxGBufferUniform,gBuffer:this._gBufferCompiled,hasSun:this.hasSun,sunDirection:this.sunDirection,sunRadiance:this.sunRadiance,sunParams:this.sunParams,bidirectional:this._integrator?.uniforms??null,hitDistanceEncode:this._outputs.get(`hitDistance`)?.encode??null,materialLayers:this._compiledLayers,shadowRays:S,cameraWorldMatrix:this.cameraWorldMatrix});this._kernelManager.register(`shade`,le(de()).compute([Math.ceil(a/256),1,1],[256,1,1])),C&&(this._kernelManager.register(`visibilityClear`,Gh({counters:w})),this._kernelManager.register(`visibilityFold`,Wh({counters:w})));let fe=this._useSubgroupCompact&&(this.renderer.hasFeature?this.renderer.hasFeature(`subgroups`):!1);this._compactIsSubgroup=fe;let pe=(fe?h_:m_)({rayBufferRO:h.rayBuffer.ro,activeIndicesReadRO:g.getActiveReadRO(),activeIndicesWriteRW:g.getActiveWrite(),counters:w,currentActiveCount:this._wfMaxRayCount});this._kernelManager.register(`compact`,pe().compute([Math.ceil(a/256),1,1],[256,1,1]));let me=(0,n.Fn)(()=>{(0,n.atomicStore)(w.element((0,n.uint)(Z.ENTERING_COUNT)),this._wfMaxRayCount)});this._kernelManager.register(`enterFull`,me().compute([1,1,1],[1,1,1]));let he=g.activeIndicesRO.b,ge=g.activeIndices.a,_e=(0,n.Fn)(()=>{let e=n.instanceIndex,t=(0,n.atomicLoad)(w.element((0,n.uint)(Z.ACTIVE_RAY_COUNT)));(0,n.If)(e.equal((0,n.uint)(0)),()=>{let e=(0,n.uint)(E).clamp((0,n.uint)(0),(0,n.uint)(g.MAX_BOUNCE_SNAPSHOTS-1));T.element(e).assign(t),T.element(e.add((0,n.uint)(g.MAX_BOUNCE_SNAPSHOTS))).assign((0,n.atomicLoad)(w.element((0,n.uint)(Z.ACTIVE_ENERGY)))),(0,n.atomicStore)(w.element((0,n.uint)(Z.ENTERING_COUNT)),t)}),(0,n.If)(e.greaterThanEqual(t),()=>{(0,n.Return)()}),ge.element(e).assign(he.element(e))});this._kernelManager.register(`compactCopyback`,_e().compute([Math.ceil(a/256),1,1],[256,1,1])),this._integrator?.registerKernels({km:this._kernelManager,qm:g,pb:h,counters:w,bounceCountsBuf:T,wfCurrentBounce:E,copyReadB:he,copyWriteA:ge,maxRays:a,w:t,own:le,freshLight:re,freshTri:te,freshBvh:ee,freshMat:R,freshEnvTex:z,freshEnvCDF:ne,materialLayers:this._compiledLayers});let ve=__({rayBufferRO:h.rayBuffer.ro,gBufferRO:c,writeColorTex:x.color,writeNDTex:x.normalDepth,writeAlbedoTex:x.albedo,resolution:this.resolution,frame:this.frame,enableAccumulation:this.enableAccumulation,hasPreviousAccumulated:this.hasPreviousAccumulated,accumulationAlpha:this.accumulationAlpha,hasPreviousAux:this.hasPreviousAux,auxAccumulationAlpha:this.auxAccumulationAlpha,cameraIsMoving:this.cameraIsMoving,prevAccumTexture:_,prevAlbedoTexture:y,prevNormalDepthTexture:b,renderWidth:this._wfRenderWidth,renderHeight:this._wfRenderHeight,visMode:this.visMode,auxGBufferEnabled:this._auxGBufferUniform,gBuffer:this._gBufferCompiled,cleanAuxNormalEnabled:this._cleanAuxNormalUniform,m2BufferRW:u,useAdaptiveSampling:this.useAdaptiveSampling,noiseThreshold:this.noiseThreshold,adaptiveMinSamples:this.adaptiveMinSamples,usePixelFreeze:this.usePixelFreeze,pixelFreezeThreshold:this.pixelFreezeThreshold,streakBufferRW:d,frozenMaskRO:m,convergenceOverlay:this.convergenceOverlay,chunkRowBase:this._wfChunkRowBase,chunkRows:this._wfChunkRows});this._kernelManager.register(`finalWrite`,ve().compute([Math.ceil(t/16),Math.ceil(this._chunkRows/16),1],[16,16,1]));let ye=S_({writeColorTex:x.color,writeNDTex:x.normalDepth,writeAlbedoTex:x.albedo,resolution:this.resolution,renderWidth:this._wfRenderWidth,renderHeight:this._wfRenderHeight,cameraWorldMatrix:this.cameraWorldMatrix,cameraProjectionMatrixInverse:this.cameraProjectionMatrixInverse,cameraProjectionMatrix:this.cameraProjectionMatrix,cameraViewMatrix:this.cameraViewMatrix,cameraProjection:this.cameraProjection,panoLonRange:this.panoLonRange,panoLatRange:this.panoLatRange,panoLevelHorizon:this.panoLevelHorizon,enableDOF:this.enableDOF,focalLength:this.focalLength,aperture:this.aperture,focusDistance:this.focusDistance,unitsPerMetre:this.unitsPerMetre,apertureScale:this.apertureScale,anamorphicRatio:this.anamorphicRatio,dofMode:this.dofMode,dofBlur:this.dofBlur,cameraClipStart:this.cameraClipStart,bvhBuffer:ee,triangleBuffer:te,materialBuffer:R,envTexture:z,environmentMatrix:this.environmentMatrix,environmentIntensity:this.environmentIntensity,enableEnvironmentLight:this.enableEnvironment,visMode:this.visMode,debugVisScale:this.debugVisScale,frame:this.frame});this._kernelManager.register(`debug`,le(ye()).compute([Math.ceil(t/16),Math.ceil(r/16),1],[16,16,1]),{eager:!1}),this._compileKernels();let be=(this._packedBuffers?.totalBytes??0)+(this._queueManager?.totalBytes??0);k_.info(V.list([V.px(t,r),`${V.mb(be)} wavefront buffers`,`budget ${V.n(i)} paths`,this._numChunks>1?`${this._numChunks} chunks of ≤${this._chunkRows} rows`:null,this._integrator?.describe()??null]))}_setWfDispatch(){let e=this._wfRenderWidth.value,t=this._wfRenderHeight.value;this._kernelManager.setDispatchForGrid(`debug`,e,t),this._kernelManager.setDispatchForCount(`countConvergedDilated`,e*t)}_setChunk(e,t,n){let r=this._wfRenderWidth.value,i=t*r;this._wfChunkRowBase.value=e,this._wfChunkRows.value=t,this._wfIsFirstChunk.value=+(n===0),this._wfMaxRayCount.value=i;let a=this._kernelManager;return a.setDispatchForGrid(`generate`,r,t),a.setDispatchForGrid(`finalWrite`,r,t),a.setDispatchForGrid(`splatResolve`,r,t),a.setDispatchForCount(`initActiveIndices`,i),a.setDispatchForCount(`buildActivePixels`,i),i}dispose(){super.dispose(),this._packedBuffers?.dispose(),this._queueManager?.dispose(),this._kernelManager?.dispose(),this._m2Attr?.dispose?.(),this._streakAttr?.dispose?.(),this._frozenMaskAttr?.dispose?.();for(let e of this._integratorInstances.values())e.dispose();this._integratorInstances.clear(),this._integrator=null,this._packedBuffers=null,this._queueManager=null,this._kernelManager=null,this._m2Attr=null,this._streakAttr=null,this._frozenMaskAttr=null,this._convDebugSource=null,this._wavefrontReady=!1,this._kernelGeneration++,this._kernelsCompiling=null}};xu();var P_=class extends j{constructor(e,i={}){super(`Compositor`,{...i,executionMode:A.ALWAYS}),this.renderer=e,this._lightSources=[...i.displaySources??[],`pathtracer:color`],this.saturation=(0,n.uniform)(i.saturation??1),this._transparentBackground=(0,n.uniform)(0,`int`),this._pathTracer=i.pathTracer??null,this._convergenceOverlay=!1,this._debugMaterial=null,this._debugQuad=null,this._debugTexNode=null,this._debugM2Attr=null,this._debugMaskAttr=null,this._debugExposureComp=(0,n.uniform)(1),this._sourceTexNode=new t.TextureNode,this._displayGain=null,this._backdropExposure=null,this._holdBackdrop=(0,n.uniform)(0,`int`),this._backdropGain=(0,n.uniform)(1),this._canvasTransform=null,this._canvasMaterial=null,this._canvasQuad=null,this.compositorMaterial=new t.MeshBasicNodeMaterial,this.compositorMaterial.blending=r.NoBlending,this._buildColorNode(),this.compositorQuad=new t.QuadMesh(this.compositorMaterial),this.setCanvasTransform(i.canvasTransform??null)}_buildColorNode(){let e=this._sourceTexNode.sample((0,n.uv)()),t=this._displayGain?this._displayGain(e.xyz,n.screenUV):null;if(this._backdropExposure!==null){let r=t??(0,n.float)(1),i=r.add(this._backdropGain.sub(r).mul(e.w.clamp(0,1).oneMinus()));t=(0,n.select)(this._holdBackdrop.greaterThan((0,n.int)(0)),i,r)}let r=t?e.xyz.mul(t):e.xyz,i=(0,n.mix)((0,n.vec3)((0,n.dot)(r,Bl)),r,this.saturation),a=(0,n.select)(this._transparentBackground,e.w,1);this._graded=i,this._alpha=a,this.compositorMaterial.colorNode=(0,n.vec4)(i,a),this.compositorMaterial.needsUpdate=!0,this._buildCanvasNode()}_buildCanvasNode(){this._canvasMaterial&&(this._canvasMaterial.colorNode=(0,n.vec4)(this._canvasTransform(this._graded,n.toneMappingExposure),this._alpha),this._canvasMaterial.needsUpdate=!0)}setCanvasTransform(e){e!==this._canvasTransform&&(this._canvasTransform=e,this._canvasMaterial?.dispose(),this._canvasMaterial=null,this._canvasQuad=null,e&&(this._canvasMaterial=new t.MeshBasicNodeMaterial,this._canvasMaterial.blending=r.NoBlending,this._canvasQuad=new t.QuadMesh(this._canvasMaterial),this._buildCanvasNode()))}get showsCanvasTransform(){return this._canvasQuad!==null}setDisplayGain(e){e!==this._displayGain&&(this._displayGain=e,this._buildColorNode())}setBackdropExposure(e){let t=e===null!=(this._backdropExposure===null);this._backdropExposure=e,t&&this._buildColorNode()}resolveLightTexture(e){return this.resolveLightSource(e)?.texture??null}resolveLightSource(e){for(let t of this._lightSources){let n=e.getTexture(t);if(n)return{key:t,texture:n}}return null}_ensureDebugMaterial(){let e=this._pathTracer?.getConvergenceDebugSource?.();if(!e)return!1;if(this._debugMaterial&&this._debugM2Attr===e.m2&&this._debugMaskAttr===e.frozenMask)return!0;this._debugMaterial?.dispose(),this._debugTexNode?.dispose(),this._debugM2Attr=e.m2,this._debugMaskAttr=e.frozenMask,this._debugTexNode=new t.TextureNode;let i=(0,n.Fn)(()=>{let t=(0,n.dot)(this._debugTexNode.sample((0,n.uv)()).toVar().xyz,Bl).toVar(),r=e.renderWidth,i=e.renderHeight,a=(0,n.int)((0,n.uv)().x.mul((0,n.float)(r))).min(r.sub((0,n.int)(1))).max((0,n.int)(0)),o=(0,n.uint)((0,n.int)((0,n.uv)().y.mul((0,n.float)(i))).min(i.sub((0,n.int)(1))).max((0,n.int)(0)).mul(r).add(a)).toVar(),s=(0,n.storage)(e.m2,`float`).toReadOnly().element(o).toVar(),c=(0,n.storage)(e.frozenMask,`uint`).toReadOnly().element(o).toVar(),l=s.sub(t.mul(t)).max((0,n.float)(0)).div((0,n.float)(e.frame).add(1)).sqrt().toVar(),u=e.usePixelFreeze.greaterThan((0,n.int)(0)),d=(0,n.select)(t.lessThan((0,n.float)(1)),t.sqrt(),t).toVar(),f=(0,n.select)(u,l.div(t.add((0,n.float)(1e-4))),l.div(d.add((0,n.float)(1e-4)))).toVar(),p=(0,n.select)(u,e.pixelFreezeThreshold,e.noiseThreshold).toVar(),m=f.div(p.max((0,n.float)(1e-6))).toVar(),h=(0,n.vec3)(t.div(t.add((0,n.float)(1))).sqrt().mul(.55)).toVar(),g=h.toVar(),_=(0,n.float)(e.frame).greaterThanEqual((0,n.float)(e.adaptiveMinSamples));return(0,n.If)(m.greaterThanEqual((0,n.float)(1)).or(_.not()),()=>{let e=(0,n.mix)((0,n.vec3)(1,.8,.1),(0,n.vec3)(1,.1,.05),m.sub(1).div(3).clamp(0,1));g.assign((0,n.mix)(h,e,.85))}),(0,n.If)(c.equal((0,n.uint)(1)).and(u),()=>{g.assign((0,n.mix)(h,(0,n.vec3)(.1,.45,1),.55))}),g});return this._debugMaterial=new t.MeshBasicNodeMaterial,this._debugMaterial.colorNode=(0,n.vec4)(i().pow(2.2).mul(this._debugExposureComp),1),this._debugMaterial.blending=r.NoBlending,this._debugQuad=new t.QuadMesh(this._debugMaterial),!0}render(e){this._draw(e,!1)}renderPicture(e){this._draw(e,!0)}_draw(e,t){if(!this.enabled)return;if(this._convergenceOverlay&&this._ensureDebugMaterial()){let t=e.getTexture(`pathtracer:color`);if(t){this._debugTexNode.value=t;let e=this.renderer.toneMapping!==r.NoToneMapping;this._debugExposureComp.value=e?1/Math.max(this.renderer.toneMappingExposure,1e-4):1,this.renderer.setRenderTarget(null),this._debugQuad.render(this.renderer);return}}let n=this.resolveLightTexture(e);if(!n)return;if(this._backdropExposure!==null){let t=e.getState(`pathtracer:backdrop`)===`color`;this._holdBackdrop.value=+!!t,t&&(this._backdropGain.value=Ts(this._backdropExposure,this.renderer.toneMappingExposure,this.renderer.toneMapping))}if(this._sourceTexNode.value=n,this.renderer.setRenderTarget(null),t||!this._canvasQuad){this.compositorQuad.render(this.renderer);return}let{toneMapping:i,outputColorSpace:a}=this.renderer;this.renderer.toneMapping=r.NoToneMapping,this.renderer.outputColorSpace=r.ColorManagement.workingColorSpace;try{this._canvasQuad.render(this.renderer)}finally{this.renderer.toneMapping=i,this.renderer.outputColorSpace=a}}setConvergenceOverlay(e){this._convergenceOverlay=!!e}setSaturation(e){this.saturation.value=e}setTransparentBackground(e){this._transparentBackground.value=+!!e}dispose(){this._sourceTexNode?.dispose(),this.compositorMaterial?.dispose(),this._canvasMaterial?.dispose(),this._canvasMaterial=null,this._canvasQuad=null,this._canvasTransform=null,this._debugTexNode?.dispose(),this._debugMaterial?.dispose(),this.compositorQuad=null,this._debugQuad=null,this._debugMaterial=null,this._debugTexNode=null,this._pathTracer=null}},F_=class{constructor(){this.textures=new Map,this.renderTargets=new Map,this.uniforms=new Map,this.state={frame:0,accumulatedFrames:0,renderMode:0,isComplete:!1,tileInfo:null,currentTile:0,totalTiles:0,cameraChanged:!1,cameraMoving:!1,width:0,height:0,time:0,deltaTime:0},this._stateChangeCallbacks=new Map}setTexture(e,t){this.textures.set(e,t)}getTexture(e){return this.textures.get(e)}hasTexture(e){return this.textures.has(e)}removeTexture(e){this.textures.delete(e)}getTextureNames(){return Array.from(this.textures.keys())}clearTextures(){this.textures.clear()}setRenderTarget(e,t){this.renderTargets.set(e,t)}getRenderTarget(e){return this.renderTargets.get(e)}hasRenderTarget(e){return this.renderTargets.has(e)}removeRenderTarget(e){this.renderTargets.delete(e)}getRenderTargetNames(){return Array.from(this.renderTargets.keys())}clearRenderTargets(){this.renderTargets.clear()}setUniform(e,t){this.uniforms.has(e)?this.uniforms.get(e).value=t:this.uniforms.set(e,{value:t})}getUniform(e){return this.uniforms.get(e)}getUniformValue(e){return this.uniforms.get(e)?.value}hasUniform(e){return this.uniforms.has(e)}removeUniform(e){this.uniforms.delete(e)}getUniformNames(){return Array.from(this.uniforms.keys())}clearUniforms(){this.uniforms.clear()}setState(e,t){let n=this.state[e],r=n!==t;return r&&(this.state[e]=t,this._notifyStateChange(e,t,n)),r}getState(e){return this.state[e]}getAllState(){return this.state}setStates(e){let t=[];for(let[n,r]of Object.entries(e))this.setState(n,r)&&t.push(n);return t}hasState(e){return e in this.state}watchState(e,t){this._stateChangeCallbacks.has(e)||this._stateChangeCallbacks.set(e,[]),this._stateChangeCallbacks.get(e).push(t)}unwatchState(e,t){if(!this._stateChangeCallbacks.has(e))return;let n=this._stateChangeCallbacks.get(e),r=n.indexOf(t);r>-1&&n.splice(r,1)}_notifyStateChange(e,t,n){if(!this._stateChangeCallbacks.has(e))return;let r=this._stateChangeCallbacks.get(e);for(let i of r)try{i(t,n)}catch(t){console.error(`Error in state change callback for '${e}':`,t)}}reset(){this.state.frame=0,this.state.accumulatedFrames=0,this.state.isComplete=!1,this.state.cameraChanged=!0,this.state.currentTile=0}incrementFrame(){return this.state.frame++,this.state.accumulatedFrames++,this.state.frame}dispose(){this.textures.clear(),this.renderTargets.clear(),this.uniforms.clear(),this._stateChangeCallbacks.clear(),this.state={}}},I_=class extends r.EventDispatcher{constructor(){super(),this._onceCallbacks=new Map}on(e,t){this.addEventListener(e,t)}once(e,t){let n=r=>{t(r),this.off(e,n),this._onceCallbacks.delete(t)};this._onceCallbacks.set(t,n),this.on(e,n)}off(e,t){let n=this._onceCallbacks.get(t);n?(this.removeEventListener(e,n),this._onceCallbacks.delete(t)):this.removeEventListener(e,t)}emit(e,t){t&&typeof t==`object`&&t.type?this.dispatchEvent(t):this.dispatchEvent({type:e,...t})}removeAllListeners(e){if(e){for(let[t,n]of this._onceCallbacks.entries())this.hasEventListener(e,n)&&(this.removeEventListener(e,n),this._onceCallbacks.delete(t));this._listeners&&this._listeners[e]&&delete this._listeners[e]}else this._onceCallbacks.clear(),this._listeners&&={}}listenerCount(e){return!this._listeners||!this._listeners[e]?0:this._listeners[e].length}clear(){this.removeAllListeners()}eventNames(){return this._listeners?Object.keys(this._listeners):[]}},L_=!1,R_=[],z_=new WeakMap;function B_(e){L_=!!e}function V_(){return R_.slice()}function H_(){R_.length=0}function U_(e){let t=[];for(let n of Object.keys(e))e[n]?.isTextureNode===!0&&t.push(n);return t}var W_=e=>!e||!e.image||!(e.image.width>0);function G_(e,t,n){if(!L_){n();return}let r=z_.get(e);if(r||(r={phase:`pending`,unboundAtCompile:[]},z_.set(e,r)),r.phase!==`pending`){n(),r.phase===`watch`&&K_(e,r);return}let i=Object.prototype.hasOwnProperty.call(t,`compute`),a=t.compute;t.compute=function(...t){return r.phase===`pending`&&(r.unboundAtCompile=U_(e).filter(t=>W_(e[t].value)),r.phase=r.unboundAtCompile.length<2?`done`:`watch`),a.apply(this,t)};try{n()}finally{i?t.compute=a:delete t.compute}}function K_(e,t){let n=[];for(let r of t.unboundAtCompile){let t=e[r]?.value;if(W_(t))return;t.isStorageTexture!==!0&&n.push(r)}t.phase=`done`,n.length!==0&&R_.push({stage:e.name,nodes:n,unboundAtCompile:t.unboundAtCompile.slice(),message:`${e.name}: ${n.join(`, `)} ${n.length===1?`was`:`were`} still holding EmptyTexture when the stage first dispatched, alongside ${t.unboundAtCompile.length-n.length} other unbound node(s), and later received a non-storage texture. Two nodes unbound at compile time can share one GPU binding and then both resolve to whichever is assigned last. Assign these before the first dispatch.`})}an();var q_=class{_reportStageFailure(e,t,n){console.error(`[Pipeline] Error in stage '${e}' (${t}):`,n);let r=`${e}:${t}`;this._reportedStageFailures.has(r)||(this._reportedStageFailures.add(r),this._issues?.record(X.STAGE_RENDER_FAILED,`stage "${e}" threw during ${t} — the frame is incomplete`,{stage:e,phase:t,cause:String(n?.message??n)}))}constructor(e,t,n,{issues:r=null}={}){this.renderer=e,this._issues=r,this._reportedStageFailures=new Set,this.width=t,this.height=n,this.stages=[],this.context=new F_,this.eventBus=new I_,this.context.setState(`width`,t),this.context.setState(`height`,n),this.stats={enabled:!1,logSkipped:!1,timings:new Map,frameCount:0}}addStage(e){this.stages.push(e),e.initialize(this.context,this.eventBus),this.stats.enabled&&console.log(`[Pipeline] Added stage: ${e.name}`)}getStage(e){return this.stages.find(t=>t.name===e)}removeStage(e){let t=this.stages.findIndex(t=>t.name===e);if(t>-1){let e=this.stages[t];return this.stages.splice(t,1),e.dispose&&e.dispose(),this.stats.timings.delete(e.name),!0}return!1}setStageEnabled(e,t){let n=this.getStage(e);n&&(t?n.enable():n.disable())}render(e=null){let t=this.stats.enabled?performance.now():0;for(let t of this.stages){if(!t.shouldExecuteThisFrame(this.context)){this.stats.enabled&&this.stats.logSkipped&&console.log(`[Pipeline] Skipped stage '${t.name}' (executionMode: ${t.executionMode})`);continue}try{let n=this.stats.enabled?performance.now():0;if(G_(t,this.renderer,()=>t.render(this.context,e)),this.stats.enabled){let e=performance.now()-n;this.stats.timings.has(t.name)||this.stats.timings.set(t.name,[]);let r=this.stats.timings.get(t.name);r.push(e),r.length>60&&r.shift()}}catch(e){this._reportStageFailure(t.name,`render`,e)}}if(this.context.incrementFrame(),this.eventBus.emit(`frame:complete`,{frame:this.context.getState(`frame`),accumulatedFrames:this.context.getState(`accumulatedFrames`)}),this.stats.enabled){let e=performance.now()-t;this.stats.timings.has(`_total`)||this.stats.timings.set(`_total`,[]);let n=this.stats.timings.get(`_total`);n.push(e),n.length>60&&n.shift(),this.stats.frameCount++}}reset(){this.eventBus.emit(`pipeline:reset`);for(let e of this.stages)if(e.reset)try{e.reset()}catch(t){this._reportStageFailure(e.name,`reset`,t)}this.context.reset(),this.stats.enabled&&(this.stats.timings.clear(),this.stats.frameCount=0)}setSize(e,t){this.width=e,this.height=t,this.context.setState(`width`,e),this.context.setState(`height`,t),this.eventBus.emit(`pipeline:resize`,{width:e,height:t});for(let n of this.stages)if(n.setSize)try{n.setSize(e,t)}catch(e){console.error(`[Pipeline] Error resizing stage '${n.name}':`,e)}}dispose(){for(let e of this.stages)if(e.dispose)try{e.dispose()}catch(t){console.error(`[Pipeline] Error disposing stage '${e.name}':`,t)}this.stages=[],this.context.dispose(),this.eventBus.clear(),this.stats.timings.clear()}setStatsEnabled(e){this.stats.enabled=e,e||(this.stats.timings.clear(),this.stats.frameCount=0)}getStats(){if(!this.stats.enabled)return null;let e={frameCount:this.stats.frameCount,stages:{},total:0};for(let[t,n]of this.stats.timings.entries()){if(n.length===0)continue;let r=n.reduce((e,t)=>e+t,0)/n.length,i=Math.min(...n),a=Math.max(...n);t===`_total`?(e.total=r,e.totalMin=i,e.totalMax=a):e.stages[t]={avg:r,min:i,max:a}}return e}logStats(){let e=this.getStats();if(!e){console.log(`[Pipeline] Stats not enabled`);return}console.group(`[Pipeline] Performance Stats`),console.log(`Frames: ${e.frameCount}`),e.totalMin===void 0?console.log(`Total: no frames recorded yet (pipeline.render() has not run since stats were enabled — the path tracer may have converged and stopped its animation loop)`):console.log(`Total: ${e.total.toFixed(2)}ms (min: ${e.totalMin.toFixed(2)}ms, max: ${e.totalMax.toFixed(2)}ms)`);for(let[t,n]of Object.entries(e.stages))console.log(` ${t}: ${n.avg.toFixed(2)}ms (min: ${n.min.toFixed(2)}ms, max: ${n.max.toFixed(2)}ms)`);console.groupEnd()}getInfo(){return{stageCount:this.stages.length,enabledStages:this.stages.filter(e=>e.enabled).length,stages:this.stages.map(e=>({name:e.name,enabled:e.enabled})),contextState:this.context.getAllState(),textures:this.context.getTextureNames(),renderTargets:this.context.getRenderTargetNames(),uniforms:this.context.getUniformNames(),events:this.eventBus.eventNames()}}logInfo(){let e=this.getInfo();console.group(`[Pipeline] Info`),console.log(`Stages:`,e.stages),console.log(`Context Textures:`,e.textures),console.log(`Context Render Targets:`,e.renderTargets),console.log(`Context Uniforms:`,e.uniforms),console.log(`Event Types:`,e.events),console.log(`State:`,e.contextState),console.groupEnd()}};Ae();var J_=ve(`engine`),Y_=class{constructor(){this.timeElapsed=0,this.lastResetTime=performance.now(),this.renderCompleteDispatched=!1,this.budgetOverrun=!1,this._budgetHeldWarned=!1}updateTime(){this.timeElapsed=(performance.now()-this.lastResetTime)/1e3}isTimeLimitReached(e,t,n){return this.budgetOverrun=!1,t!==`time`&&t!==`timeOnly`||!(n>0)||this.timeElapsed<n?!1:e?.frameCount>0?(this.budgetOverrun=!0,!0):(this._budgetHeldWarned||(this._budgetHeldWarned=!0,J_.warn(`render time limit (${n}s) expired before the first sample landed — holding the deadline open to avoid capturing an empty frame`)),!1)}isLimitReached(e,t,n){return e?this.isTimeLimitReached(e,t,n)?!0:this.stopCondition(e)!==null:!1}stopCondition(e){return this.budgetOverrun?`timeLimit`:e?e.frameCount>=e.completionThreshold?`samples`:e._isConvergedComplete?.()?`converged`:null:null}markComplete(){return this.renderCompleteDispatched?!1:(this.renderCompleteDispatched=!0,!0)}reset(){this.timeElapsed=0,this.lastResetTime=performance.now(),this.renderCompleteDispatched=!1,this.budgetOverrun=!1,this._budgetHeldWarned=!1}resumeFromPause(){this.renderCompleteDispatched=!1,this.lastResetTime=performance.now()-this.timeElapsed*1e3}};hn(),ii(),ui();var X_=864e5,Z_=Object.freeze({IMMUTABLE:`immutable`,REVALIDATE:`revalidate`,NETWORK:`network`}),Q_=(e,t)=>({loaded:e,total:t,lengthComputable:t>0&&e<=t}),$_=(e,t)=>e.headers?.get?.(t)??null,ev=e=>e.reason??new DOMException(`aborted`,`AbortError`);function tv(e){try{let t=new URL(e,globalThis.location?.href??`http://localhost/`).pathname;return decodeURIComponent(t.split(`/`).pop())||`download`}catch{return`download`}}async function nv(e,{onProgress:t,signal:n}){let r=Number($_(e,`content-length`))||0,i=$_(e,`content-type`)??``;if(!e.body)return new Blob([await e.arrayBuffer()],{type:i});let a=e.body.getReader(),o=[],s=0;for(;;){if(n?.aborted)throw a.cancel().catch(()=>{}),ev(n);let{done:e,value:i}=await a.read();if(e)break;o.push(i),s+=i.length,t?.(Q_(s,r))}return new Blob(o,{type:i})}var rv=(e,t,n)=>new File([e],t,{type:n||e.type,lastModified:e.lastModified??Date.now()}),iv=()=>{},av=class{constructor(e){this._storage=e,this._revalidating=new Set}get _area(){return this._storage?.area(mn.DOWNLOADS)??null}async fetch(e,{key:t=e,name:n=tv(e),policy:r=Z_.REVALIDATE,maxAgeMs:i=X_,onProgress:a=null,signal:o=null,fetchOptions:s={}}={}){let c=this._area;if(c&&r!==Z_.NETWORK){let o=await c.open(t);if(o){let c=await o.file(`data`);if(c)return r===Z_.REVALIDATE&&Date.now()-(o.extra.checkedAt??0)>=i&&this._revalidate(e,t,n,o.extra,s),a?.(Q_(c.size,c.size)),{file:rv(c,n,o.extra.contentType),release:()=>o.release(),fromCache:!0};o.release()}}return this._download(e,t,n,{onProgress:a,signal:o,fetchOptions:s,cache:!!c})}async has(e){return await this._area?.has(e)===!0}async _download(e,t,n,{onProgress:r,signal:i,fetchOptions:a,cache:o}){if(i?.aborted)throw ev(i);let s=await fetch(e,{...a,signal:i});if(!s.ok)throw Error(`HTTP ${s.status} fetching ${e}`);let c=Number($_(s,`content-length`))||0,l={url:e,contentType:$_(s,`content-type`)??``,lastModified:$_(s,`last-modified`),contentLength:c||null,checkedAt:Date.now()},u=o&&s.body?await this._area.create(t,{label:n,expectedBytes:c}):null;if(!u)return{file:rv(await nv(s,{onProgress:r,signal:i}),n,l.contentType),release:iv,fromCache:!1};try{await u.writeStream(`data`,s.body,{signal:i,onProgress:e=>r?.(Q_(e,c))}),await u.commit(l)}catch(o){if(await u.abort(),o?.name!==`QuotaExceededError`)throw o;return this._download(e,t,n,{onProgress:r,signal:i,fetchOptions:a,cache:!1})}let d=await this._area.open(t,{wait:!0}),f=d&&await d.file(`data`);if(!f)throw d?.release(),Error(`storage: ${n} vanished right after it was saved`);return{file:rv(f,n,l.contentType),release:()=>d.release(),fromCache:!1}}async _revalidate(e,t,n,r,i){if(this._revalidating.has(t))return;this._revalidating.add(t);let a=!1;try{let t=new Headers(i?.headers);t.set(`Range`,`bytes=0-0`);let n=await fetch(e,{...i,headers:t});if(n.body?.cancel().catch(()=>{}),n.ok){let e=$_(n,`last-modified`),t=n.status===206?Number($_(n,`content-range`)?.match(/\/(\d+)$/)?.[1])||null:Number($_(n,`content-length`))||null;a=!!(e&&r.lastModified&&e!==r.lastModified||t&&r.contentLength&&t!==r.contentLength)}}catch{}try{if(a){let{release:r}=await this._download(e,t,n,{fetchOptions:i,cache:!0});r()}else await this._area.patchMeta(t,{extra:{...r,checkedAt:Date.now()}})}catch{}finally{this._revalidating.delete(t)}}};function ov(e,t,n){return new av(t).fetch(e,n)}function sv(){return new av(ni(si().cacheNamespace))}async function cv(e,{downloads:t=sv(),...n}={}){if(!t._storage||!/^https?:/i.test(e))return{url:e,release:iv,cached:!1};let{file:r,release:i}=await t.fetch(e,n),a=URL.createObjectURL(r);return{url:a,cached:!0,release:()=>{URL.revokeObjectURL(a),i()}}}function lv(e){let t=``;for(let n of e)t+=n.toString(16).padStart(2,`0`);return t}async function uv(e){let t=typeof e==`string`?_v.encode(e):e;return lv(new Uint8Array(await crypto.subtle.digest(`SHA-256`,t)))}async function dv(e){return(await uv(e)).slice(0,32)}async function fv(e){if(e.size<=vv+yv+xv*bv)return uv(new Uint8Array(await e.arrayBuffer()));let t=[e.slice(0,vv)],n=e.size-vv-yv-bv;for(let r=0;r<xv;r++){let i=vv+Math.floor(n*(r+.5)/xv);t.push(e.slice(i,i+bv))}return t.push(e.slice(e.size-yv)),uv(new Uint8Array(await new Blob(t).arrayBuffer()))}async function pv(e){return{name:e.name??``,size:e.size,lastModified:e.lastModified??0,sample:await fv(e)}}async function mv(e){let t=0,n=0,r=e.files.map(({path:e,file:r})=>(t+=r.size,n=Math.max(n,r.lastModified??0),`${e}|${r.size}|${r.lastModified??0}`));return{name:e.name,size:t,lastModified:n,sample:await uv(r.join(`
|
|
859
859
|
`)),files:e.files.length}}function hv(e){return`${e.files===void 0?`file`:`folder`}:${e.name}|${e.size}|${e.lastModified}|${e.sample}`}function gv(e,t){return!!e&&!!t&&e.size===t.size&&e.sample===t.sample&&e.name===t.name}var _v,vv,yv,bv,xv,Sv=g((()=>{_v=new TextEncoder,vv=1<<20,yv=1<<20,bv=65536,xv=14}));function Cv({name:e=null,files:t},{isModel:n=()=>!1}={}){let r=new Map;for(let e of t){let t=Tv(e)?e:e.file,n=Tv(e)?e.webkitRelativePath||e.name:e.path,i=String(n??``).replace(/\\/g,`/`).split(`/`).filter(e=>e&&e!==`.`).join(`/`);!i||!t||i.split(`/`).some(Dv)||r.set(i,{path:i,file:t})}let i=[...r.values()].sort((e,t)=>e.path<t.path?-1:+(e.path>t.path)),a=i[0]?.path.split(`/`)[0],o=i.length>0&&i.every(e=>e.path.startsWith(a+`/`))?a:null;return{name:e??o??(i.find(e=>n(e.path))??i[0])?.path.split(`/`).pop()??`Folder`,files:i,flat:o===null&&i.every(e=>!e.path.includes(`/`))}}var wv,Tv,Ev,Dv,Ov=g((()=>{wv=Object.freeze({zip:{type:`archive`,name:`ZIP Archive`},gz:{type:`archive`,name:`Gzipped TAR Archive`},tgz:{type:`archive`,name:`Gzipped TAR Archive`},tar:{type:`archive`,name:`TAR Archive`}}),Tv=e=>typeof Blob<`u`&&e instanceof Blob,Ev=e=>!!e&&typeof e==`object`&&!Tv(e)&&e.files!=null,Dv=e=>e.startsWith(`.`)||e===`__MACOSX`}));Sv(),Ov(),lt(),F(),an();var kv={maxBounces:{uniform:`maxBounces`,reset:!0},transmissiveBounces:{uniform:`transmissiveBounces`,reset:!0},maxSubsurfaceSteps:{uniform:`maxSubsurfaceSteps`,reset:!0},maxTransparentBounces:{uniform:`maxTransparentBounces`,reset:!0},environmentIntensity:{uniform:`environmentIntensity`,reset:!0},backgroundIntensity:{uniform:`backgroundIntensity`,reset:!0},backgroundBlurriness:{uniform:`backgroundBlurriness`,reset:!0},backgroundBlurSamples:{uniform:`backgroundBlurSamples`,reset:!0},showBackground:{uniform:`showBackground`,reset:!0},enableEnvironment:{uniform:`enableEnvironment`,reset:!0},groundProjectionEnabled:{uniform:`groundProjectionEnabled`,reset:!0},groundProjectionRadius:{uniform:`groundProjectionRadius`,reset:!0},groundProjectionHeight:{uniform:`groundProjectionHeight`,reset:!0},groundProjectionLevel:{uniform:`groundProjectionLevel`,reset:!0},enableGroundCatcher:{uniform:`enableGroundCatcher`,reset:!0},groundCatcherHeight:{uniform:`groundCatcherHeight`,reset:!0},globalIlluminationIntensity:{uniform:`globalIlluminationIntensity`,reset:!0},panoramaLevelHorizon:{uniform:`panoLevelHorizon`,reset:!0},enableDOF:{uniform:`enableDOF`,reset:!0},focusDistance:{uniform:`focusDistance`,reset:!1},focalLength:{uniform:`focalLength`,reset:!0},aperture:{uniform:`aperture`,reset:!0},apertureScale:{uniform:`apertureScale`,reset:!0},anamorphicRatio:{uniform:`anamorphicRatio`,reset:!0},unitsPerMetre:{uniform:`unitsPerMetre`,reset:!0},dofMode:{handler:`handleDofMode`,reset:!0},dofBlur:{uniform:`dofBlur`,reset:!0},samplingTechnique:{uniform:`samplingTechnique`,reset:!0},fireflyThreshold:{uniform:`fireflyThreshold`,reset:!0},shadowTerminatorOffset:{uniform:`shadowTerminatorOffset`,reset:!0},enableAlphaShadows:{uniform:`enableAlphaShadows`,reset:!0},useAdaptiveSampling:{uniform:`useAdaptiveSampling`,reset:!0},noiseThreshold:{uniform:`noiseThreshold`,reset:!0},adaptiveMinSamples:{uniform:`adaptiveMinSamples`,reset:!0},adaptiveStopFraction:{uniform:`adaptiveStopFraction`,reset:!0},usePixelFreeze:{uniform:`usePixelFreeze`,reset:!0},pixelFreezeThreshold:{uniform:`pixelFreezeThreshold`,reset:!0},pixelFreezeStability:{uniform:`pixelFreezeStability`,reset:!0},convergenceOverlay:{handler:`handleConvergenceOverlay`,reset:!1},enableEmissiveTriangleSampling:{uniform:`enableEmissiveTriangleSampling`,reset:!0},emissiveBoost:{uniform:`emissiveBoost`,reset:!0},visMode:{uniform:`visMode`,reset:!0},debugVisScale:{uniform:`debugVisScale`,reset:!0},cameraProjection:{handler:`handleCameraProjection`,reset:!0},panoramaLonRange:{handler:`handlePanoramaLonRange`,reset:!0},panoramaLatRange:{handler:`handlePanoramaLatRange`,reset:!0},interactionModeEnabled:{handler:`handleInteractionModeEnabled`,reset:!1},maxSamples:{handler:`handleMaxSamples`,reset:!1},transparentBackground:{handler:`handleTransparentBackground`},backgroundColor:{handler:`handleBackgroundColor`,reset:!0},exposure:{handler:`handleExposure`},saturation:{handler:`handleSaturation`},renderLimitMode:{handler:`handleRenderLimitMode`},renderTimeLimit:{handler:`handleRenderTimeLimit`,reset:!1},renderMode:{handler:`handleRenderMode`},integrator:{handler:`handleIntegrator`,reset:!0},shadowRays:{handler:`handleShadowRays`,reset:!0},environmentRotation:{handler:`handleEnvironmentRotation`},wavefrontSortMaterials:{handler:`handleWavefrontSortMaterials`,reset:!1},maxTextureSize:{reset:!1},areaLightIntensityScale:{reset:!1}},Av=Object.freeze({DEFAULT:`default`,HOST:`host`,SCENE_METADATA:`scene-metadata`,MODE_PRESET:`mode-preset`}),jv=class extends r.EventDispatcher{constructor(e=H,{issues:t=null}={}){super(),this._issues=t,this._defaults=e,this._routes=new Map(Object.entries(kv)),this._values=new Map,this._sources=new Map,this._pathTracer=null,this._resetCallback=null,this._handlers={},this._initDefaults(e)}bind(e){this._pathTracer=e.stages.pathTracer,this._resetCallback=e.resetCallback,this._handlers=this._buildHandlers(e)}define(e,{default:t,apply:n,reset:r=!0}){if(this._routes.has(e))throw Error(`setting "${e}" is already defined`);this._routes.set(e,{apply:n,reset:r});let i=t===void 0?this._defaults[e]:t;!this._values.has(e)&&i!==void 0&&(this._values.set(e,i),this._sources.set(e,Av.DEFAULT))}_buildHandlers({stages:e,resetCallback:t,reconcileCompletion:n,applyExposure:i,onCameraProjection:a}){let o=new r.Vector2,s=(t,n)=>{o.set(n?.[0]??0,n?.[1]??0).multiplyScalar(r.MathUtils.DEG2RAD),e.pathTracer?.setUniform(t,o)};return{handleCameraProjection:t=>{e.pathTracer?.setUniform(`cameraProjection`,at[t]??at.perspective),a?.(t)},handleDofMode:t=>e.pathTracer?.setUniform(`dofMode`,+(t===`look`)),handlePanoramaLonRange:e=>s(`panoLonRange`,e),handlePanoramaLatRange:e=>s(`panoLatRange`,e),handleTransparentBackground:t=>{e.pathTracer?.setUniform(`transparentBackground`,t),e.compositor?.setTransparentBackground(t)},handleBackgroundColor:t=>{let n=t?.isColor?t:new r.Color(t);e.pathTracer?.setUniform(`backgroundColor`,n)},handleExposure:e=>{i?.(e)},handleSaturation:t=>{e.compositor?.setSaturation(t)},handleConvergenceOverlay:n=>{e.pathTracer?.setUniform(`convergenceOverlay`,n),e.compositor?.setConvergenceOverlay(n),n&&!this.get(`useAdaptiveSampling`)&&t?.()},handleRenderLimitMode:t=>{e.pathTracer?.setRenderLimitMode?.(t,this.get(`renderTimeLimit`)),n?.()},handleMaxSamples:t=>{e.pathTracer?.setUniform(`maxSamples`,t),e.pathTracer?.updateCompletionThreshold(),n?.()},handleRenderTimeLimit:t=>{e.pathTracer?.setRenderLimitMode?.(this.get(`renderLimitMode`),t),n?.()},handleRenderMode:t=>{e.pathTracer?.setUniform(`renderMode`,parseInt(t))},handleIntegrator:t=>{e.pathTracer?.setIntegrator?.(t)},handleShadowRays:t=>{e.pathTracer?.setShadowRays?.(t)},handleEnvironmentRotation:t=>{e.pathTracer?.environment.setEnvironmentRotation(t)},handleWavefrontSortMaterials:t=>{e.pathTracer&&(e.pathTracer.sortMaterials=t)},handleInteractionModeEnabled:t=>{e.pathTracer?.setInteractionModeEnabled(t)}}}set(e,t,{reset:n,silent:r,source:i=Av.HOST}={}){let a=this._applyOne(e,t,i);a?.route&&((n===void 0?a.route.reset??!0:n)&&this._resetCallback?.(),r||this.dispatchEvent({type:N.SETTING_CHANGED,key:e,value:t,prev:a.prev}))}setMany(e,{silent:t,reset:n,source:r=Av.HOST}={}){let i=!1;for(let[n,a]of Object.entries(e)){let e=this._applyOne(n,a,r);e?.route&&((e.route.reset??!0)&&(i=!0),t||this.dispatchEvent({type:N.SETTING_CHANGED,key:n,value:a,prev:e.prev}))}(n===void 0?i:n)&&this._resetCallback?.()}_applyOne(e,t,n){let r=this._values.get(e);if(r===t)return null;this._values.set(e,t),this._sources.set(e,n);let i=this._routes.get(e);return i?(this._applyRoute(i,t,r),{route:i,prev:r}):(this._reportUnknownKey(e),{route:null,prev:r})}_reportUnknownKey(e){this._issues?.record(X.SETTING_UNKNOWN_KEY,`unknown setting "${e}" — stored but never applied to any stage`,{key:e})}get(e){return this._values.get(e)}getEffective(){let e={};for(let[t,n]of this._values)e[t]={value:n,source:this._sources.get(t)??Av.DEFAULT,routed:this._routes.has(t)};return e}getAll(){return Object.fromEntries(this._values)}serialize(){let e={};for(let[t,n]of this._values){if(this._sources.get(t)!==Av.HOST||!this._routes.has(t))continue;let r=nr(n);r!==void 0&&(e[t]=r)}return e}restore(e){let t={},n=[];for(let[r,i]of Object.entries(e??{}))this._routes.has(r)?t[r]=rr(i):n.push(r);return this.setMany(t),n}applyAll(){for(let[e,t]of this._values){let n=this._routes.get(e);n&&this._applyRoute(n,t,void 0)}}_applyRoute(e,t,n){e.uniform?this._pathTracer?.setUniform(e.uniform,t):e.handler?this._handlers[e.handler]?.(t,n):e.apply?.(t,n)}_initDefaults(e){for(let t of Object.keys(kv))t in e&&(this._values.set(t,e[t]),this._sources.set(t,Av.DEFAULT))}};function Mv(){let{wgsl:e,bindings:t}=ss({group:Nv,firstBinding:Pv});return{wgsl:e,bindings:t,version:Zo()}}var Nv,Pv,Fv,Iv,Lv,Rv,zv,Bv,Vv=g((()=>{vs(),Nv=0,Pv=3,Mv().wgsl,Fv={packed:`
|
|
860
860
|
@group(0) @binding(0) var<storage, read> src: array<u32>;
|
|
861
861
|
|
|
@@ -923,7 +923,7 @@ fn main( @builtin(global_invocation_id) gid: vec3<u32> ) {
|
|
|
923
923
|
let rgb = linear.rgb * g;
|
|
924
924
|
rayzee_store( gid.y * params.width + gid.x, linear, rayzee_tone_map( rgb, params.mode, params.exposure, params.saturation ) );
|
|
925
925
|
}
|
|
926
|
-
`,zv=32,Bv=class{constructor(e,t=`rayzee:tonemap`,{input:n=`packed`,output:r=`rgba8`}={}){this.device=e,this.label=t,this.input=n,this.output=r,this.width=0,this.height=0,this._pipelines=new Map,this._storage=null,this._map=null,this._params=null,this._paramData=new ArrayBuffer(zv),this._paramU32=new Uint32Array(this._paramData),this._paramF32=new Float32Array(this._paramData),this._shaderVersion=-1,this._bindings=[],this._tables=new Map,this.disposed=!1}_ensurePipeline(e=null){let{wgsl:t,bindings:n,version:r}=Mv();this._shaderVersion!==r&&(this._pipelines.clear(),this._bindings=n,this._shaderVersion=r);let i=e?.wgsl?e.key:``,a=this._pipelines.get(i);return a||(a=this.device.createComputePipeline({label:this.label,layout:`auto`,compute:{module:this.device.createShaderModule({label:this.label,code:Rv(t,this.input,this.output,e?.wgsl)}),entryPoint:`main`}}),this._pipelines.set(i,a),a)}_ensureTables(){let e=new Set;for(let{index:t,transform:n}of this._bindings){let{data:r,size:i}=n.table;e.add(t);let a=this._tables.get(t);if(a&&a.data===r)continue;a?.texture.destroy();let o=this.device.createTexture({label:`${this.label}-${n.wgslConst}`,size:[i,i,i],dimension:`3d`,format:`rgba16float`,usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST});this.device.queue.writeTexture({texture:o},r,{bytesPerRow:i*8,rowsPerImage:i},[i,i,i]),this._tables.set(t,{texture:o,data:r,view:o.createView()})}for(let[t,n]of this._tables)e.has(t)||(n.texture.destroy(),this._tables.delete(t))}ensureSize(e,t){if(this._ensurePipeline(),this._ensureTables(),this.width===e&&this.height===t&&this._storage)return;this._releaseBuffers();let n=e*t*Lv[this.output];this._storage=this.device.createBuffer({label:`${this.label}-out`,size:n,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC}),this._map=this.device.createBuffer({label:`${this.label}-map`,size:n,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),this._params=this.device.createBuffer({label:`${this.label}-params`,size:zv,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this.width=e,this.height=t}async toRGBA8(e,t){return new Uint8ClampedArray(await this._run(e,t))}async toPlanar(e,t){return new Float32Array(await this._run(e,t))}async _run(e,t={}){let n=t.gain;if(!n?.wgsl||!n.device||n.device===this.device)return this._dispatch(e,t);let r=await n.copyTo(this.device);try{return await this._dispatch(e,{...t,gain:{...r,backdrop:n.backdrop}})}finally{r.destroy()}}async _dispatch(e,{exposure:t=1,toneMapping:n=0,saturation:r=1,flipY:i=!1,preserveAlpha:a=!1,gain:o=null}={}){if(this.disposed)throw Error(`PackedToneMapper: disposed`);if(!this._storage)throw Error(`PackedToneMapper: call ensureSize() first`);let s=this._ensurePipeline(o);this._ensureTables();let{width:c,height:l}=this,u=c*l*Lv[this.output];this._paramU32[0]=c,this._paramU32[1]=l,this._paramU32[2]=n>>>0,this._paramU32[3]=+!!i,this._paramF32[4]=t,this._paramF32[5]=r,this._paramU32[6]=+!!a,this._paramF32[7]=o?.backdrop>0?o.backdrop:0,this.device.queue.writeBuffer(this._params,0,this._paramData);let d=[...this._tables.entries()].map(([e,t])=>({binding:e,resource:t.view})),f=this.device.createBindGroup({layout:s.getBindGroupLayout(0),entries:[...d,{binding:0,resource:this.input===`texture`?e.createView():{buffer:e,size:c*l*8}},{binding:1,resource:{buffer:this._storage}},{binding:2,resource:{buffer:this._params}}]}),p=this.device.createCommandEncoder({label:this.label}),m=p.beginComputePass();m.setPipeline(s),m.setBindGroup(0,f),o?.wgsl&&m.setBindGroup(1,this.device.createBindGroup({layout:s.getBindGroupLayout(1),entries:o.entries})),m.dispatchWorkgroups(Math.ceil(c/8),Math.ceil(l/8)),m.end(),p.copyBufferToBuffer(this._storage,0,this._map,0,u),this.device.queue.submit([p.finish()]),await this._map.mapAsync(GPUMapMode.READ);let h=this._map.getMappedRange().slice(0);return this._map.unmap(),h}release(){this._releaseBuffers(),this.width=this.height=0}_releaseBuffers(){this._storage?.destroy(),this._map?.destroy(),this._params?.destroy(),this._storage=null,this._map=null,this._params=null}dispose(){if(!this.disposed){this.disposed=!0,this._releaseBuffers();for(let e of this._tables.values())e.texture.destroy();this._tables.clear(),this._pipelines.clear()}}}}));Vv(),vs(),tr(),an();var Hv=class{constructor({issues:e=null}={}){this._issues=e,this._renderer=null,this._offRegistry=Qo(()=>{this._renderer&&os(this._renderer)})}get hasConfig(){return!1}get workingSpace(){return Zr}get workingSpaceAdopted(){return!1}get inputKey(){return`-`}attachRenderer(e){this._renderer=e;let t=os(e);return e.outputColorSpace=r.SRGBColorSpace,t}listViews(){return es()}get activeView(){return null}setActiveView(e){let t=$o(e);if(!t)throw Error(`no view transform with id ${e}`);if(t.outputEncoded)throw Error(`"${t.name}" returns display-encoded colour: it needs rayzee/addons/color`);return this._renderer&&(this._renderer.toneMapping=e),t}_publishWorkingMatrix(){Jn(null,Zr)}loadConfig(){let e=`colour configs need the OCIO pipeline: renderer.setColorManagement( ColorManagement ), from rayzee/addons/color`;return this._issues?.record(X.CAPABILITY_MISSING,e,{capability:`color`}),Promise.reject(Error(e))}unloadConfig(){}setWorkingSpace(){}exportPixels(e){return{rgba:e,colorSpace:Zr}}status(){let e=this._renderer?$o(this._renderer.toneMapping):null;return{config:null,workingSpace:Zr,workingSpaceAdopted:!1,activeTransform:e?{id:e.id,name:e.name,source:e.source}:null,activeView:null,context:null,exportSpace:null,views:es(),registryVersion:Zo(),bakeError:e?.error??null}}dispose(){this._offRegistry?.(),this._renderer=null,this._issues=null,$r()===this&&(Jn(null),ei(null))}};function Uv(e){return e.mimeType?e.mimeType:e.uri?.startsWith(`data:`)?e.uri.slice(5,e.uri.indexOf(`;`)):ey.find(([t])=>t.test(e.uri??``))?.[1]??`image/png`}function Wv(e){for(let t=8;t+12<=e.length;){let n=(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0,r=t+12+n;if(e[t+4]===73&&e[t+5]===69&&e[t+6]===78&&e[t+7]===68)return e.subarray(0,r);t=r}return e}function Gv({data:e,width:t,height:n},{shared:i=!1}={}){let a=new Uint8Array(e.buffer,e.byteOffset,t*n*4),o=a;i&&typeof SharedArrayBuffer<`u`&&!(a.buffer instanceof SharedArrayBuffer)&&(o=new Uint8Array(new SharedArrayBuffer(a.byteLength)),o.set(a));let s=new r.DataTexture(o,t,n,r.RGBAFormat,r.UnsignedByteType);return s.needsUpdate=!0,s}function Kv(e,t){return Dr().decodeImage(t===`image/png`?Wv(e):e,t)}async function qv(e){let t=await fetch(e);if(!t.ok)throw Error(`HTTP ${t.status}`);return new Uint8Array(await t.arrayBuffer())}function Jv(e,t){return t.bufferView===void 0?qv(e.options.manager.resolveURL(r.LoaderUtils.resolveURL(t.uri,e.options.path))):e.getDependency(`bufferView`,t.bufferView).then(e=>new Uint8Array(e))}function Yv(e,t,n){if(e.sourceCache[t]!==void 0)return e.sourceCache[t].then(e=>e.clone());let r=Jv(e,e.json.images[t]).then(e=>new Promise((t,r)=>{n.parse(e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength),t,r)}));return e.sourceCache[t]=r,r}async function Xv(e,t=Uv({uri:e})){let n=Gv(await Kv(await qv(e),t));return n.flipY=!0,n}async function Zv(e,t){let n=Gv(await Kv(e,Uv({uri:t})),{shared:!0});return n.flipY=!0,n}function Qv(e,t=null){return e.loadImageSource=function(e,n){if(ty(this,n))return Yv(this,e,n);let r=this.json.images[e],i=Error(`no image decoder in this runtime: configurePlatform( nodePlatform( { decodeImage } ) ) — see "Running in Node"`);return t?.(r.uri??`bufferView ${r.bufferView}`,i),Promise.reject(i)},{name:`RAYZEE_missing_image_decoder`}}function $v(e,t=null){return e.loadImageSource=function(e,n){if(ty(this,n))return Yv(this,e,n);if(this.sourceCache[e]!==void 0)return this.sourceCache[e].then(e=>e.clone());let r=this.json.images[e],i=Uv(r),a=r.uri??`bufferView ${r.bufferView}`,o=Jv(this,r).then(e=>Kv(e,i)).then(e=>{let t=Gv(e,{shared:!0});return r.extras&&typeof r.extras==`object`&&Object.assign(t.userData,r.extras),t.userData.mimeType=i,t}).catch(e=>{throw t?.(a,e),e});return this.sourceCache[e]=o,o},{name:`RAYZEE_platform_images`}}var ey,ty,ny=g((()=>{Fr(),ey=[[/\.jpe?g(\?|#|$)/i,`image/jpeg`],[/\.webp(\?|#|$)/i,`image/webp`],[/\.avif(\?|#|$)/i,`image/avif`]],ty=(e,t)=>!!t&&t!==e.textureLoader&&typeof t.parse==`function`}));ny();var ry=`KHR_materials_diffuse_transmission`;function iy(e){let t=(t,n,r,i)=>{let a={};return e.assignTexture(a,n,r,i).then(()=>{a[n]&&(t[n]=a[n])})};return{name:ry,afterRoot(n){let i=e.json.materials??[],a=new Set,o=[];for(let s of n.scenes??[])s.traverse(n=>{let s=Array.isArray(n.material)?n.material:n.material?[n.material]:[];for(let n of s){if(a.has(n))continue;a.add(n);let s=e.associations.get(n)?.materials,c=s===void 0?null:i[s]?.extensions?.[ry];if(!c)continue;n.diffuseTransmission=c.diffuseTransmissionFactor??0;let[l,u,d]=c.diffuseTransmissionColorFactor??[1,1,1];n.diffuseTransmissionColor=new r.Color().setRGB(l,u,d,r.LinearSRGBColorSpace),c.diffuseTransmissionTexture&&o.push(t(n,`diffuseTransmissionMap`,c.diffuseTransmissionTexture)),c.diffuseTransmissionColorTexture&&o.push(t(n,`diffuseTransmissionColorMap`,c.diffuseTransmissionColorTexture,r.SRGBColorSpace))}});return Promise.all(o)}}}ui();var ay=`KHR_draco_mesh_compression`,oy=`KHR_texture_basisu`,sy=[`EXT_meshopt_compression`,`KHR_meshopt_compression`],cy=new TextDecoder;function ly(e){if(typeof e==`string`)return e;if(!(e instanceof ArrayBuffer))return JSON.stringify(e?.extensionsUsed??[]);let t=new DataView(e);if(!(e.byteLength>=20&&t.getUint32(0,!0)===1179937895))return cy.decode(e);let n=Math.min(t.getUint32(12,!0),e.byteLength-20);return cy.decode(new Uint8Array(e,20,n))}async function uy(e,t,n){let{dracoDecoderPath:r,ktx2TranscoderPath:i}=si(),[a,o,s]=await Promise.all([t.includes(ay)&&!e.dracoLoader?import(`three/addons/loaders/DRACOLoader.js`):null,t.includes(oy)&&!e.ktx2Loader?import(`three/addons/loaders/KTX2Loader.js`):null,sy.some(e=>t.includes(e))&&!e.meshoptDecoder?import(`three/addons/libs/meshopt_decoder.module.js`):null]);if(a){let t=new a.DRACOLoader;t.setDecoderConfig({type:`js`}),t.setDecoderPath(r),e.setDRACOLoader(t)}if(o){let t=new o.KTX2Loader;t.setTranscoderPath(i),n&&(t.detectSupport(n),t.workerConfig={astcSupported:!1,etc1Supported:!1,etc2Supported:!1,dxtSupported:!1,bptcSupported:!1,pvrtcSupported:!1}),e.setKTX2Loader(t)}s&&e.setMeshoptDecoder(s.MeshoptDecoder)}function dy(e,t){let n=e.parse.bind(e);return e.parse=(r,i,a,o)=>{uy(e,ly(r),t).then(()=>n(r,i,a,o),e=>o?.(e))},e}function fy(e){if(typeof e==`string`)try{let t=JSON.parse(e);return t&&typeof t==`object`?t:null}catch{return null}return e&&typeof e==`object`?e:null}function py(e){let t=typeof e==`string`?parseFloat(e):e;return Number.isFinite(t)?t:void 0}function my(e){let t=fy(e);if(!t)return null;let n=e=>e&&(e.environment!==void 0||e.render!==void 0),r=fy(t.rayzee);return n(r)?r:n(t)?t:null}function hy(e){let t=fy(e);if(!t)return null;let n=yy.map(e=>t[e]).find(e=>typeof e==`string`&&e.trim());if(!n)return null;let r=py(t.rotation),i=py(t.intensity),a={sourceFile:n.trim()};return r!==void 0&&(a.rotation=r),i!==void 0&&(a.intensity=Math.max(0,i)),a}function gy(e){let t=fy(e);if(!t)return null;let n={};for(let e of by){let r=py(t[e]);r!==void 0&&r>0&&(n[e]=Math.round(r))}return Object.keys(n).length?n:null}function _y(e){let t=my(e);if(!t)return null;let n=hy(t.environment),r=gy(t.render);return!n&&!r?null:{...n?{environment:n}:{},...r?{render:r}:{}}}function vy(e){if(!e)return null;let t=[e.userData,e.asset?.extras,e.scene?.userData];Array.isArray(e.scenes)&&t.push(...e.scenes.map(e=>e?.userData));for(let e of t){let t=_y(e);if(t)return t}return null}var yy,by,xy=g((()=>{yy=[`sourceFile`,`url`,`file`],by=[`maxBounces`,`samples`,`width`,`height`]}));yi(),de(),Fr(),xy(),an(),lt(),Ae();var Sy=ve(`assets`),Cy={glb:{type:`model`,name:`GLB (GLTF Binary)`},gltf:{type:`model`,name:`GLTF`},hdr:{type:`environment`,name:`HDR (High Dynamic Range)`},png:{type:`image`,name:`PNG`},jpg:{type:`image`,name:`JPEG`},jpeg:{type:`image`,name:`JPEG`},webp:{type:`image`,name:`WebP`}},wy={addOn:`rayzee/addons/archives`,install:`assetLoader.setArchiveImporter()`},Ty={addOn:`rayzee/addons/formats`,install:`assetLoader.registerFormat()`},Ey={zip:wy,gz:wy,tgz:wy,tar:wy,fbx:Ty,obj:Ty,stl:Ty,ply:Ty,dae:Ty,"3mf":Ty,usd:Ty,usda:Ty,usdc:Ty,usdz:Ty,exr:Ty};function Dy(e){let t=new r.BufferGeometry;for(let n in e.attributes)t.setAttribute(n,e.attributes[n]);e.index&&t.setIndex(e.index);for(let n of e.groups)t.addGroup(n.start,n.count,n.materialIndex);return t}var Oy={name:`RAYZEE_camera_clip`,afterRoot(e){for(let t of e.scenes)t.traverse(e=>{e.isCamera&&e.near>0&&(e.userData.clipStart=e.near)})}},ky=683;function Ay(e,t,n,i){if(!(i.normalize??!0))return Math.PI;let a=i.shape===`ellipse`||i.shape===`disk`?Math.PI/4:1,o=e.getWorldScale(new r.Vector3),s=Math.PI*a*Math.abs(t*o.x*n*o.y);return Number.isFinite(s)?s:Math.PI}var jy=class e extends r.EventDispatcher{constructor(e,t,n,{issues:i=null,areaLightIntensityScale:a=null}={}){super(),this.scene=e,this.camera=t,this.controls=n,this.targetModel=null,this.floorPlane=null,this.sceneScale=1,this.sceneSize=new r.Vector3(1,1,1),this.loaderCache={},this.uploadedFileInfo=null,this.animations=[],this.renderer=null,this.sceneMetadata=null,this._loadingManager=new r.LoadingManager,this._loadCancelled=!1,this._urlAbort=null,this.storage=null,this._downloads=null,this._sourceKey=null,this._appended=!1,this.archives=null,this._archiveLoader=null,this._formats=new Map,this._issues=i,this._areaLightIntensityScale=a??(()=>H.areaLightIntensityScale),this._loadingManager.onError=e=>{this._loadCancelled||this._issues?.record(X.ASSET_UNREACHABLE,`asset "${e}" could not be fetched — anything depending on it renders without it`,{url:e})}}cancelActiveLoad(){this._loadCancelled=!0,this._loadingManager.abort(),this._urlAbort?.abort()}async _viaCache(t,n,r,{cacheKey:i=t,cachePolicy:a}={}){if(!this.storage||!e._isNetworkUrl(t)||/\.gltf$/i.test(t.split(/[?#]/)[0]))return{url:t,release:()=>{},cached:!1};let o=new AbortController;this._urlAbort=o;try{return await cv(t,{downloads:this.downloads,key:i,policy:a,name:tv(t),signal:o.signal,onProgress:this._downloadProgress(n,r)})}catch(e){throw this._isCancellation(e)?this._cancellationError():e}finally{this._urlAbort=null}}get sceneSourceKey(){return this._appended?null:this._sourceKey}_keyed(e,t){return t?`${e}::${t}`:null}get downloads(){return this._downloads?._storage!==this.storage&&(this._downloads=new av(this.storage)),this._downloads}_isCancellation(e){return this._loadCancelled||e?.name===`AbortError`||e?.code===`LOAD_CANCELLED`}_cancellationError(){let e=Error(`Load cancelled`);return e.code=`LOAD_CANCELLED`,e}_downloadProgress(e,t){return n=>{let r=n?.loaded||0,i=n?.lengthComputable&&n.total||0;z({isLoading:!0,status:e,loadedBytes:r,totalBytes:i,canCancel:!!t,progress:i?Math.min(60,2+Math.round(r/i*58)):2})}}_downloadComplete(e=`Processing Data...`,t=62){z({status:e,progress:t,canCancel:!1,loadedBytes:null,totalBytes:null})}static _isNetworkUrl(e){return typeof e==`string`&&/^https?:/i.test(e)}_adoptExternalObject(e){let t;try{t=(0,l.clone)(e)}catch(t){throw Error(`Cannot render "${e.name||e.type}": its userData must be JSON-serializable.`,{cause:t})}return t.userData.__rayzeeExternal=!0,this.scene?.children.some(t=>t.uuid===e.uuid)||(t.uuid=e.uuid),e.parent&&(e.parent.updateWorldMatrix(!0,!1),t.applyMatrix4(e.parent.matrixWorld)),t}releaseTargetModel(){this.sceneMetadata=null,this._sourceKey=null,this._appended=!1,this.archives?.release(),this.targetModel&&(this.removeModelRoot(this.targetModel),this.targetModel=null,this.animations=[])}setRenderer(e){this.renderer=e}setArchiveImporter(e){this.archives=e}setArchiveImporterLoader(e,t){this._archiveLoader={load:e,formats:t,pending:null}}async _archiveImporter(){return!this.archives&&this._archiveLoader&&(this.archives=await(this._archiveLoader.pending??=this._archiveLoader.load())),this.archives}get _archiveFormats(){return this.archives?.constructor.FORMATS??this._archiveLoader?.formats??null}registerFormat(...e){for(let t of e)for(let e of t.extensions)this._formats.set(e,t);return this}getFileFormat(e){let t=e.split(`.`).pop().toLowerCase();return Cy[t]||this._formats.get(t)||this._archiveFormats?.[t]||null}formatError(e){let t=Ey[e.split(`.`).pop().toLowerCase()];return Error(t?`${e}: this format is read by ${t.addOn} — install it with ${t.install}`:`Unsupported file format: ${e}`)}async inspectArchive(e){let t=await this._archiveImporter();if(!t)throw this.formatError(e.name??`archive.zip`);return await t.inspectArchive(e)}flushPendingGraph(e){this.archives?.flushPendingGraph(e)}commitPendingGraph(e){this.archives?.commitPendingGraph(e)}readFileAsArrayBuffer(e){return e.arrayBuffer()}readFileAsText(e){return e.text()}async loadAssetFromFile(e,t={}){let n=e.name,r=this.getFileFormat(n);if(!r)throw this.formatError(n);z({isLoading:!0,status:`Loading ${r.name}...`,progress:2});try{let i;switch(r.type){case`model`:i=await this.loadModelFromFile(e,n);break;case`environment`:case`image`:i=await this.loadEnvironmentFromFile(e,n);break;case`archive`:i=await(await this._archiveImporter()).loadArchiveFromFile(e,n,t);break;default:throw Error(`Unknown asset type: ${r.type}`)}return i}catch(e){throw e?.code!==`ARCHIVE_NEEDS_ELEMENT`&&this.dispatchEvent({type:`error`,message:e.message,filename:n}),e}}async loadFolder(e,t={}){let n=await this._archiveImporter();if(!n)throw Error(`${e.name}: folders are read by ${wy.addOn} — install it with ${wy.install}`);z({isLoading:!0,status:`Loading ${e.name}...`,progress:2});try{return await n.loadFolder(e,t)}catch(t){throw t?.code===`ARCHIVE_NEEDS_ELEMENT`?t.file=e:this.dispatchEvent({type:`error`,message:t.message,filename:e.name}),t}}async loadAssetFromUrl(t,n={}){let{filename:r=tv(t),cacheKey:i=t,cachePolicy:a,...o}=n;if(!this.getFileFormat(r))throw this.formatError(r);this._loadCancelled=!1;let s=e._isNetworkUrl(t),c=`Downloading ${r}...`,l=new AbortController;this._urlAbort=l,z({isLoading:!0,status:c,progress:2,canCancel:s,loadedBytes:0,totalBytes:0});let u;try{u=await this.downloads.fetch(t,{key:i,name:r,policy:a,signal:l.signal,onProgress:this._downloadProgress(c,s)})}catch(e){throw this._isCancellation(e)?this._cancellationError():e}finally{this._urlAbort=null}this._downloadComplete();try{return await this.loadAssetFromFile(u.file,o)}catch(e){throw e?.code===`ARCHIVE_NEEDS_ELEMENT`&&(e.file=u.file),e}finally{u.release()}}async loadModelFromFile(e,t){let n=this.storage?this._keyed(`file`,hv(await pv(e))):null,r=/\.(usd|usda|usdc)$/i.test(t)?await this._archiveImporter():null,i=r?await r.loadUSDScene({[t]:e},t):await this._loadModelFileByExtension(e,t);return this._sourceKey=n,i}async _loadModelFileByExtension(e,t){let n=t.split(`.`).pop().toLowerCase();if(n===`glb`||n===`gltf`)return await this.loadGLBFromArrayBuffer(await this.readFileAsArrayBuffer(e),t);let r=this._formats.get(n);if(r?.type!==`model`)throw this.formatError(t);return await this._loadModelWithFormat(r,e,t)}async _loadModelWithFormat(e,t,n){try{z({isLoading:!0,status:`Processing ${e.label} Data...`,progress:5}),await new Promise(e=>setTimeout(e,0));let{model:r,result:i=r}=await e.parse(t,{filename:n,cache:this.loaderCache});return this.releaseTargetModel(),this.targetModel=r,z({isLoading:!0,status:`Processing Data...`,progress:10}),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:r,filename:n}),i}catch(t){throw console.error(`Error loading ${e.label}:`,t),this.dispatchEvent({type:`error`,message:t.message,filename:n}),t}}async loadEnvironmentFromFile(e,t){let n=URL.createObjectURL(e);this.uploadedFileInfo={name:t,type:e.type,size:e.size};try{let r=await this.loadEnvironment(n);return di(r,hv(await pv(e))),this.dispatchEvent({type:`load`,texture:r,filename:t}),r}finally{URL.revokeObjectURL(n)}}async loadEnvironment(t){this._loadCancelled=!1;try{this.dispatchEvent({type:`beforeEnvironmentLoad`,url:t});let n;if(t.startsWith(`blob:`))n=await this.loadEnvironmentFromBlob(t);else{let e=t.split(/[?#]/)[0].split(`.`).pop().toLowerCase();n=await this.loadEnvironmentByExtension(t,e)}return n.generateMipmaps=!0,e._isNetworkUrl(t)&&di(n,t),this.applyEnvironmentToScene(n),this.dispatchEvent({type:`load`,texture:n,url:t,filename:t.split(/[?#]/)[0].split(`/`).pop()}),n}catch(e){throw this._isCancellation(e)?this._cancellationError():(console.error(`Error loading environment:`,e),this.dispatchEvent({type:`error`,message:e.message,filename:t}),e)}}async loadEnvironmentFromBlob(e){let t=await(await fetch(e)).blob(),n=this.determineEnvironmentExtension(t,e),r=URL.createObjectURL(t);try{return await this.loadEnvironmentByExtension(r,n)}finally{URL.revokeObjectURL(r)}}determineEnvironmentExtension(e,t){let n;if(e.type===`image/x-exr`||e.type.includes(`exr`))n=`exr`;else if(e.type===`image/vnd.radiance`||e.type.includes(`hdr`))n=`hdr`;else{let e=t.split(`/`).pop();if(e){let t=e.match(/\.([^.]+)$/);t&&(n=t[1].toLowerCase())}}return!n&&this.uploadedFileInfo&&(n=this.uploadedFileInfo.name.split(`.`).pop().toLowerCase()),n}async loadEnvironmentByExtension(t,n,{loader:i=null}={}){let a=this._formats.get(n);if(!i&&a?.type===`environment`&&(i=this.loaderCache[n]??=await a.createLoader(this._loadingManager)),!i&&n===`hdr`&&(i=this.loaderCache.hdr??=new s.HDRLoader(this._loadingManager).setDataType(r.FloatType)),!i&&Ey[n])throw this.formatError(`environment.${n}`);let o=e._isNetworkUrl(t),c=`Downloading Environment...`,l=await this._viaCache(t,c,o),u=l.cached?void 0:this._downloadProgress(c,o),d;try{i?d=await i.loadAsync(l.url,u):Dr().decodeImage?(d=await Xv(l.url,`image/${n===`jpg`?`jpeg`:n}`),d.colorSpace=r.SRGBColorSpace):(this.loaderCache.texture||(this.loaderCache.texture=new r.TextureLoader(this._loadingManager)),d=await this.loaderCache.texture.loadAsync(l.url,u),d.colorSpace=r.SRGBColorSpace)}finally{l.release()}return this._downloadComplete(`Processing Environment...`,62),this.maxEnvironmentWidth&&My(d,this.maxEnvironmentWidth),d.mapping=r.EquirectangularReflectionMapping,d.minFilter=r.LinearFilter,d.magFilter=r.LinearFilter,d}applyEnvironmentToScene(e){this.scene.background=e,this.scene.environment=e}async createGLTFLoader(){let e=dy(new o.GLTFLoader(this._loadingManager),this.renderer),t=(e,t)=>this._reportImageFailure(e,t);return Dr().decodeImage?e.register(e=>$v(e,t)):kr()||e.register(e=>Qv(e,t)),e.register(e=>iy(e)),e.register(()=>Oy),e}_reportImageFailure(e,t){try{this._issues?.record(X.TEXTURE_BUILD_FAILED,`image ${e} could not be decoded (${t?.message??t}) — the surfaces using it render untextured`,{image:e,cause:String(t?.message??t)})}catch(e){this._deferredError??=e}}_throwDeferred(){let e=this._deferredError;if(this._deferredError=null,e)throw e}_disposeGLTFLoader(e){e&&(e.dracoLoader?.dispose(),e.ktx2Loader?.dispose())}async loadExampleModels(e,t){if(!t||!t[e])throw Error(`No model file at index ${e}`);let n=`${t[e].url}`;return await this.loadModel(n)}async loadModel(t,n={}){this._loadCancelled=!1;let i=await this.createGLTFLoader(),a=e._isNetworkUrl(t),o=null;try{z({isLoading:!0,status:`Downloading Model...`,progress:2,canCancel:a,loadedBytes:0,totalBytes:0}),o=await this._viaCache(t,`Downloading Model...`,a,n),o.cached&&i.setResourcePath(r.LoaderUtils.extractUrlBase(t));let e=await jr(()=>i.loadAsync(o.url,o.cached?void 0:this._downloadProgress(`Downloading Model...`,a)));return this._downloadComplete(),this._throwDeferred(),this.releaseTargetModel(),this._sourceKey=a?this._keyed(`url`,n.cacheKey??t):null,this.targetModel=e.scene,this.animations=e.animations||[],this.sceneMetadata=vy(e),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:e.scene,filename:t.split(`/`).pop()}),e}catch(e){throw this._isCancellation(e)?this._cancellationError():(console.error(`Error loading model:`,e),this.dispatchEvent({type:`error`,message:e.message,filename:t}),e)}finally{o?.release(),this._disposeGLTFLoader(i)}}_processAndParent(e){this.processModelObjects(e),this.scene.add(e),e.updateMatrixWorld(!0)}async appendModel(t,n={}){this._loadCancelled=!1;let i=await this.createGLTFLoader(),a=e._isNetworkUrl(t),o=null;try{z({isLoading:!0,status:`Downloading Model...`,progress:2,canCancel:a,loadedBytes:0,totalBytes:0}),o=await this._viaCache(t,`Downloading Model...`,a,n),o.cached&&i.setResourcePath(r.LoaderUtils.extractUrlBase(t));let e=await jr(()=>i.loadAsync(o.url,o.cached?void 0:this._downloadProgress(`Downloading Model...`,a)));return this._downloadComplete(),this._throwDeferred(),this._appended=!0,this._processAndParent(e.scene),{root:e.scene,animations:e.animations||[]}}catch(e){throw this._isCancellation(e)?this._cancellationError():e}finally{o?.release(),this._disposeGLTFLoader(i)}}appendObject3D(e,t=`object3d`){this._appended=!0;let n=this._adoptExternalObject(e);return n.name=e.name||t,this._processAndParent(n),{root:n}}removeModelRoot(e){e&&(e.userData.__rayzeeExternal?(ie(e),e.parent?.remove(e)):re(e))}async loadGLBFromArrayBuffer(e,t=`model.glb`){let n=await this.createGLTFLoader();try{z({isLoading:!0,status:`Processing GLB Data...`,progress:5}),await new Promise(e=>setTimeout(e,0));let r=await jr(()=>n.parseAsync(e,``));return this._throwDeferred(),this.releaseTargetModel(),this.targetModel=r.scene,this.animations=r.animations||[],this.sceneMetadata=vy(r),z({isLoading:!0,status:`Processing Data...`,progress:10}),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:r.scene,filename:t}),r}catch(e){throw console.error(`Error loading GLB:`,e),this.dispatchEvent({type:`error`,message:e.message,filename:t}),e}finally{this._disposeGLTFLoader(n)}}async loadObject3D(e,t=`object3d`){this.releaseTargetModel();let n=this._adoptExternalObject(e);return n.name=e.name||t,this.targetModel=n,z({isLoading:!0,status:`Processing Data...`,progress:10}),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:n,filename:t}),n}async onModelLoad(e){let t=new tc(`onModelLoad`);t.start(`Camera extraction`);let n=this.extractCamerasFromModel(e);t.end(`Camera extraction`),t.start(`Camera setup`);let i=new r.Box3().setFromObject(e),a=i.getCenter(new r.Vector3),o=i.getSize(new r.Vector3);this.controls?.target.copy(a);let s=Math.max(o.x,o.y,o.z),c=this.camera.fov*(Math.PI/180),l=Math.abs(s/Math.sin(c/2)/2),u=Math.PI/6,d=new r.Vector3(Math.cos(u)*l,l/Math.sqrt(2),Math.sin(u)*l);if(this.camera.position.copy(d.add(a)),this.camera.lookAt(a),this.camera.near=s/100,this.camera.far=s*100,this.camera.updateProjectionMatrix(),this.controls&&(this.controls.maxDistance=l*10,this.controls.saveState(),this.controls.update()),t.end(`Camera setup`),this.floorPlane){let e=i.min.y;this.floorPlane.position.y=e,this.floorPlane.rotation.x=-Math.PI/2,this.floorPlane.scale.setScalar(s*5)}t.start(`Process model objects`),this.processModelObjects(e),t.end(`Process model objects`),t.start(`Scene add`),this.scene.add(e),t.end(`Scene add`);let f=s;return this.sceneSize.copy(o),t.start(`setupPathTracing`),await this.setupPathTracing(e,f),t.end(`setupPathTracing`),t.print(),this.dispatchEvent({type:`modelProcessed`,model:e,cameras:n,sceneData:{center:a,size:o,maxDim:s,sceneScale:f}}),this.dispatchEvent({type:`SceneRebuild`}),{center:a,size:o,maxDim:s,sceneScale:f}}extractCamerasFromModel(e){let t=[];return e.updateWorldMatrix(!0,!0),e.traverse(e=>{if(e.isCamera){let n=e.clone();n.userData.__rayzeeSourceUuid=e.uuid,e.getWorldPosition(n.position),e.getWorldQuaternion(n.quaternion),e.getWorldScale(n.scale),n.scale.set(Math.sign(n.scale.x)||1,Math.sign(n.scale.y)||1,Math.sign(n.scale.z)||1),(!n.name||n.name===``)&&(n.name=`Model Camera ${t.length+1}`),n.isPerspectiveCamera&&(n.aspect=this.camera.aspect,n.updateProjectionMatrix()),t.push(n)}}),t}processModelObjects(e){let t=[],n=[];e.traverse(e=>{let i=e.userData;e.isRectAreaLight&&!i.__radianceConverted&&(e.intensity*=Ay(e,e.width,e.height,i),i.__radianceConverted=!0),(e.isPointLight||e.isSpotLight)&&!i.__candelaConverted&&(e.intensity*=4*Math.PI/ky,i.__candelaConverted=!0),e.isDirectionalLight&&!i.__luxConverted&&(e.intensity/=ky,i.__luxConverted=!0);let a=e.name.startsWith(`RectAreaLightPlaceholder`);if(a&&!(i.name&&i.type===`RectAreaLight`)&&!e.parent?.name?.startsWith(`RectAreaLightPlaceholder`)&&n.push(e.name),a&&i.name&&i.type===`RectAreaLight`){let t=i.normalize??!0,n=i.shape??`rectangle`,a=i.intensity*Ay(e,i.width,i.height,i),o=new r.RectAreaLight(new r.Color(...i.color),a*this._areaLightIntensityScale(),i.width,i.height);o.userData.normalize=t,o.userData.spread=Number.isFinite(i.spread)?i.spread:Math.PI,o.userData.shape=n,o.userData.__radianceConverted=!0,o.name=i.name,e.add(o)}e.isMesh&&Array.isArray(e.material)&&t.push(e)}),n.length&&this._issues?.record(X.LIGHT_PLACEHOLDER_SKIPPED,`${n.length} area-light placeholder(s) lack userData.name or userData.type 'RectAreaLight' — no light was made for them`,{count:n.length,names:n.slice(0,10)});let i=e.userData.__rayzeeExternal===!0;for(let e of t){if(!e.parent)continue;console.log(`Found multi-material mesh:`,e.name),i&&(e.geometry=Dy(e.geometry));let t=(0,c.createMeshesFromMultiMaterialMesh)(e);for(let e of t.children)e.geometry.userData.__rayzeeOwned=!0;e.parent.add(t),e.parent.remove(e)}}async setupPathTracing(e,t){this.sceneScale=t}createFloorPlane(){this.floorPlane=new r.Mesh(new r.CircleGeometry,new r.MeshPhysicalMaterial({transparent:!1,color:3158064,roughness:1,metalness:0,opacity:0,transmission:0})),this.floorPlane.name=`Ground`,this.floorPlane.visible=!1,this.scene.add(this.floorPlane)}setFloorPlane(e){this.floorPlane=e}getSceneScale(){return this.sceneScale}getSceneSize(){return this.sceneSize.clone()}getTargetModel(){return this.targetModel}getSupportedFormats(e=null){let t={...Cy,...this._archiveFormats};for(let[e,{type:n,name:r}]of this._formats)t[e]={type:n,name:r};if(e){let n={};for(let[r,i]of Object.entries(t))i.type===e&&(n[r]=i);return n}return t}dispose(){for(let e in this.loaderCache){let t=this.loaderCache[e];t&&typeof t.dispose==`function`&&t.dispose()}this.loaderCache={},this._listeners=void 0,this._loadingManager.onError=void 0,this._issues=null,this._urlAbort?.abort(),this._urlAbort=null,this.storage=null,this._downloads=null,this.archives?.release(),this.archives=null,this._archiveLoader=null,this.releaseTargetModel()}removeAllEventListeners(){this._listeners=void 0}};function My(e,t){let{data:n,width:r,height:i}=e.image??{};if(!(n instanceof Float32Array)||r<=t||n.length!==r*i*4)return;let a=Math.ceil(r/t),o=Math.ceil(r/a),s=Math.ceil(i/a);for(let e=0;e<s;e++){let t=Math.min(i,(e+1)*a);for(let i=0;i<o;i++){let s=Math.min(r,(i+1)*a),c=0,l=0,u=0,d=0,f=0;for(let o=e*a;o<t;o++)for(let e=i*a;e<s;e++){let t=(o*r+e)*4;c+=n[t],l+=n[t+1],u+=n[t+2],d+=n[t+3],f++}let p=(e*o+i)*4;n[p]=c/f,n[p+1]=l/f,n[p+2]=u/f,n[p+3]=d/f}}let c=o*s*16;e.image={data:n.byteOffset===0&&n.byteLength===n.buffer.byteLength&&n.buffer.transfer?new Float32Array(n.buffer.transfer(c)):n.slice(0,o*s*4),width:o,height:s},e.needsUpdate=!0,Sy.info(`environment ${r}×${i} shrunk to ${o}×${s} (memory spill)`)}var Ny={addEventListener(){},removeEventListener(){},dispatchEvent(){return!0}},Py=class{constructor(e){this.canvas=e,this._configuration=null,this._texture=null}configure(e){this.unconfigure(),this._configuration=e}unconfigure(){this._texture?.destroy(),this._texture=null,this._configuration=null}getConfiguration(){return this._configuration}getCurrentTexture(){if(!this._configuration)throw Error(`HeadlessGPUContext: getCurrentTexture() before configure()`);let e=Math.max(1,this.canvas.width),t=Math.max(1,this.canvas.height);if(this._texture?.width!==e||this._texture?.height!==t){let{device:n,format:r,usage:i}=this._configuration;this._texture?.destroy(),this._texture=n.createTexture({label:`headless-canvas`,size:[e,t],format:r,usage:i})}return this._texture}};function Fy(e=1,t=1){let n={...Ny,defaultView:null},r={...Ny,isHeadlessCanvas:!0,width:e,height:t,clientWidth:0,clientHeight:0,style:{},parentNode:null,ownerDocument:n,getRootNode:()=>n,getBoundingClientRect(){return{x:0,y:0,left:0,top:0,right:this.width,bottom:this.height,width:this.width,height:this.height}},setPointerCapture(){},releasePointerCapture(){},hasPointerCapture:()=>!1,focus(){},getContext:e=>e===`webgpu`?i:null},i=new Py(r);return r}var Iy=class extends r.PerspectiveCamera{constructor(e,t,n,r){super(e,t,n,r),this.orthographic=!1,this.orthoHalfHeight=1}get isPerspectiveCamera(){return!this.orthographic}set isPerspectiveCamera(e){}get isOrthographicCamera(){return this.orthographic}get top(){return this.orthoHalfHeight}get bottom(){return-this.orthoHalfHeight}get right(){return this.orthoHalfHeight*this.aspect}get left(){return-this.orthoHalfHeight*this.aspect}updateProjectionMatrix(){this.orthographic?r.OrthographicCamera.prototype.updateProjectionMatrix.call(this):super.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.orthographic=e.orthographic===!0,this.orthoHalfHeight=e.orthoHalfHeight??this.orthoHalfHeight,this}},Ly=`__rayzeeUserLight`,Ry={DirectionalLight:r.DirectionalLight,PointLight:r.PointLight,SpotLight:r.SpotLight,RectAreaLight:r.RectAreaLight},zy=class extends r.EventDispatcher{constructor(e,t,n,r={}){super(),this.scene=e,this.sceneHelpers=t,this.pathTracer=n,this._onReset=r.onReset||null,this._onLightRemoved=r.onLightRemoved||null}addLight(e){let t={DirectionalLight:{position:[1,1,1],intensity:1,color:`#ffffff`},PointLight:{position:[0,2,0],intensity:1e3,color:`#ffffff`},SpotLight:{position:[0,1,0],intensity:1e3,color:`#ffffff`,angle:15},RectAreaLight:{position:[0,2,0],intensity:100,color:`#ffffff`,width:2,height:2}}[e];if(!t)return null;let n;if(e===`DirectionalLight`)n=new r.DirectionalLight(t.color,t.intensity),n.position.fromArray(t.position);else if(e===`PointLight`)n=new r.PointLight(t.color,t.intensity),n.position.fromArray(t.position);else if(e===`SpotLight`){n=new r.SpotLight(t.color,t.intensity),n.position.fromArray(t.position),n.angle=r.MathUtils.degToRad(t.angle);let e=new r.Object3D;this.scene.add(e),n.target=e}else e===`RectAreaLight`&&(n=new r.RectAreaLight(t.color,t.intensity,t.width,t.height),n.position.fromArray(t.position),n.lookAt(0,0,0),n.userData.normalize=!0,n.userData.spread=Math.PI,n.userData.shape=`rectangle`);n.userData[Ly]=!0,n.userData.temperature=6500,n.userData.useTemperature=!1,n.userData.exposure=0;let i=this.scene.getObjectsByProperty(`isLight`,!0).length;return n.name=`${e.replace(`Light`,``)} ${i+1}`,this.scene.add(n),this.updateLights(),this._syncHelpers(),this._onReset?.(),this._buildDescriptor(n)}getLight(e){let t=this.scene.getObjectByProperty(`uuid`,e);return t?.isLight?t:null}setIntensity(e,t){let n=this.getLight(e);return n?(n.intensity=t,this.updateLights(),this._onReset?.(),!0):!1}removeLight(e){let t=this.scene.getObjectByProperty(`uuid`,e);return!t||!t.isLight?!1:(this._onLightRemoved?.(t),this.sceneHelpers.remove(t),t.target&&t.target.removeFromParent(),t.removeFromParent(),this.updateLights(),this._onReset?.(),!0)}clearLights(){this.sceneHelpers.clear(),this._removeAllLights(),this.updateLights(),this._onReset?.()}getLights(){return this.scene.getObjectsByProperty(`isLight`,!0).map(e=>this._buildDescriptor(e))}updateLights(){this.pathTracer?.updateLights(),this.sceneHelpers?.visible&&this.sceneHelpers.update()}transferSceneLights(e,{keepUserLights:t=!1}={}){this._removeAllLights(t?e=>!e.userData?.[Ly]:void 0);let n=e.getObjectsByProperty(`isLight`,!0);if(!n||n.length===0){this.updateLights();return}for(let e of n){let t=e.clone();if(e.updateWorldMatrix(!0,!1),e.getWorldPosition(t.position),e.getWorldQuaternion(t.quaternion),e.getWorldScale(t.scale),t.isRectAreaLight&&(t.width*=t.scale.x,t.height*=t.scale.y,t.scale.set(1,1,1)),(e.isSpotLight||e.isDirectionalLight)&&e.target){let n=new r.Object3D;e.target.updateWorldMatrix(!0,!1),e.target.getWorldPosition(n.position),this.scene.add(n),t.target=n}this.scene.add(t)}this.updateLights(),this._syncHelpers()}setShowLightHelper(e){this.sceneHelpers.visible=e,e?this._syncHelpers():this.sceneHelpers.clear()}serialize(){return this.scene.getObjectsByProperty(`isLight`,!0).map(e=>{let t={type:e.type,name:e.name,visible:e.visible,color:[e.color.r,e.color.g,e.color.b],intensity:e.intensity,position:e.position.toArray(),quaternion:e.quaternion.toArray(),scale:e.scale.toArray(),userData:nr(e.userData)??{}};return e.isSpotLight&&Object.assign(t,{angle:e.angle,penumbra:e.penumbra,distance:e.distance,decay:e.decay}),e.isPointLight&&Object.assign(t,{distance:e.distance,decay:e.decay}),e.isRectAreaLight&&Object.assign(t,{width:e.width,height:e.height}),e.target&&(e.isSpotLight||e.isDirectionalLight)&&(t.target=e.target.position.toArray()),t})}restore(e){this.sceneHelpers?.clear(),this._removeAllLights();let t=[];for(let n of e??[]){let e=Ry[n.type];if(!e)continue;let i=new e;i.name=n.name??``,i.visible=n.visible!==!1,i.color.setRGB(...n.color),i.intensity=n.intensity,i.position.fromArray(n.position),i.quaternion.fromArray(n.quaternion),i.scale.fromArray(n.scale??[1,1,1]),i.userData=rr(n.userData)??{};for(let e of[`angle`,`penumbra`,`distance`,`decay`,`width`,`height`])typeof n[e]==`number`&&(i[e]=n[e]);if(n.target){let e=new r.Object3D;e.position.fromArray(n.target),this.scene.add(e),i.target=e}this.scene.add(i),t.push(i)}return this.updateLights(),this._syncHelpers(),this._onReset?.(),t}add(e){return this.addLight(e)}remove(e){return this.removeLight(e)}clear(){this.clearLights()}getAll(){return this.getLights()}sync(){this.updateLights()}showHelpers(e){this.setShowLightHelper(e)}dispose(){this._disposed||(this._disposed=!0,this._onLightRemoved=null,this.sceneHelpers?.clear(),this._removeAllLights(),this._onReset=null,this.pathTracer=null,this.sceneHelpers=null,this.scene=null)}_removeAllLights(e){this.scene.getObjectsByProperty(`isLight`,!0).filter(t=>!e||e(t)).forEach(e=>{this._onLightRemoved?.(e),e.target&&this.scene.remove(e.target),this.scene.remove(e)})}_syncHelpers(){if(!this.sceneHelpers.visible)return;let e=this.scene.getObjectsByProperty(`isLight`,!0);this.sceneHelpers.sync(e)}_buildDescriptor(e){let t=0;e.type===`SpotLight`&&e.angle!==void 0?t=r.MathUtils.radToDeg(e.angle):e.type===`DirectionalLight`&&(t=r.MathUtils.radToDeg(e.userData?.angle??0));let n={uuid:e.uuid,name:e.name,type:e.type,visible:e.visible,intensity:e.intensity,color:`#${e.color.getHexString()}`,position:[e.position.x,e.position.y,e.position.z],angle:t,temperature:e.userData?.temperature??6500,useTemperature:e.userData?.useTemperature??!1,exposure:e.userData?.exposure??0};if(e.type===`RectAreaLight`){n.width=e.width,n.height=e.height,n.normalize=e.userData?.normalize??!0,n.spread=r.MathUtils.radToDeg(e.userData?.spread??Math.PI);let t=e.userData?.shape;n.shape=t===`square`||t===`rectangle`||t===`disk`||t===`ellipse`?t:t===1?`ellipse`:`rectangle`;let i=e.getWorldDirection(e.position.clone());n.target=[e.position.x+i.x,e.position.y+i.y,e.position.z+i.z]}else e.type===`SpotLight`&&e.target?(n.target=[e.target.position.x,e.target.position.y,e.target.position.z],n.distance=e.distance??0,n.penumbra=e.penumbra??0,n.decay=e.decay??2):e.type===`PointLight`&&(n.distance=e.distance??0,n.decay=e.decay??2);return(e.type===`SpotLight`||e.type===`DirectionalLight`)&&e.userData?.gobo&&(n.gobo=e.userData.gobo.name,n.goboIntensity=e.userData.gobo.intensity,n.goboInverted=!!e.userData.gobo.inverted,e.type===`DirectionalLight`&&(n.goboScale=e.userData.gobo.scale??5)),e.type===`SpotLight`&&e.userData?.ies&&(n.ies=e.userData.ies.name,n.iesIntensity=e.userData.ies.intensity??1,n.fixtureLumens=e.userData.ies.fixtureLumens??null),n}};lt(),Ft(),qn(),de(),Ae(),F(),an(),ui(),Sv(),vs(),Do(),wc();var By=({element:e,pbrtEntry:t}={})=>({...e===void 0?{}:{element:e},...t===void 0?{}:{pbrtEntry:t}}),Vy=new WeakMap,Hy=3e4,Uy=new Set([...Object.values(N),...Object.values(P)]),Wy=new Set;async function Gy(e,t){if(!t||typeof self<`u`)return e.init();globalThis.self={requestAnimationFrame:()=>0,cancelAnimationFrame:()=>{}};try{return await e.init()}finally{delete globalThis.self}}var Ky=ve(`engine`);function qy(){let e=new Float32Array(16);return new Uint32Array(e.buffer)[3]=Tt.TRIANGLE_LEAF,e}function Jy(e,t){e.lost.then(e=>{t.app&&t.app._handleDeviceLost(e)})}var Yy=[`core-features-and-limits`,`depth-clip-control`,`depth32float-stencil8`,`texture-compression-bc`,`texture-compression-bc-sliced-3d`,`texture-compression-etc2`,`texture-compression-astc`,`texture-compression-astc-sliced-3d`,`timestamp-query`,`indirect-first-instance`,`shader-f16`,`rg11b10ufloat-renderable`,`bgra8unorm-storage`,`float32-filterable`,`float32-blendable`,`clip-distances`,`dual-source-blending`,`subgroups`,`texture-formats-tier1`,`texture-formats-tier2`],Xy=/swiftshader|llvmpipe|lavapipe|basic render|microsoft basic|warp/i;function Zy(e){let t=e.info??{},n=`${t.vendor??``} ${t.architecture??``} ${t.device??``} ${t.description??``}`;return{vendor:t.vendor??``,architecture:t.architecture??``,device:t.device??``,description:t.description??``,isSoftware:t.isFallbackAdapter===!0||e.isFallbackAdapter===!0||Xy.test(n)}}var Qy=class extends r.EventDispatcher{constructor(e,t={}){super(),this._headless=t.headless===!0||!e,e??=Fy();try{Vy.get(e)?.dispose()}catch(e){Ky.warn(`prior canvas owner dispose failed`,e)}if(Vy.set(e,this),this.canvas=e,this._autoResize=!this._headless&&t.autoResize!==!1,this._maxSceneBytes=t.maxSceneBytes,this._hostMemoryGB=t.hostMemoryGB,this._storageOption=t.storage,this._storageOpener=null,this._memorySpill=t.memorySpill===!0||t.memorySpill===!1?t.memorySpill:`auto`,this._spillPlan=null,this.storage=null,this._storageRelease=null,this._applySceneMetadataEnabled=t.applySceneMetadata!==!1,this._unlitRestore=null,this._applyingSceneMetadata=!1,t.profile!==void 0)throw Error("the `profile` option was removed: the engine has one set of defaults. For the old 'physical' profile set `areaLightIntensityScale: 1` and `dofMode: 'physical'` through `settings`.");this._issues=new rn({strict:t.strict===!0,onIssue:e=>this.dispatchEvent({type:N.ISSUE,issue:e})}),this.color=new Hv({issues:this._issues}),ei(this.color),this.settings=new jv(H,{issues:this._issues}),this.renderer=null,this.scene=null,this.meshScene=null,this._sceneHelpers=null,this.assetLoader=null,this._sdf=null,this.pipeline=null,this._pendingReservedRenderSize=null,this.stages={},this.camera=null,this.lightManager=null,this.environmentManager=null,this.isInitialized=!1,this.pauseRendering=!1,this._pathTracerEnabled=!0,this._rasterPrecompile=null,this.animationManagerId=null,this.needsReset=!1,this._loadingInProgress=!1,this._needsDisplayRefresh=!1,this._paused=!1,this._emissiveSamplingUserSet=!1,this.completion=new Y_,this._resizeDebounceTimer=null,this._displayWidth=0,this._displayHeight=0,this._renderScale=1,this._renderWidth=0,this._renderHeight=0,this._trackedListeners=[],this._disposed=!1,this._deviceLost=!1,this._gpuDevice=null,this._deviceLostHolder=null,this._deterministic=!1,this._dispatchPinned=!1,this._deterministicRestore=null,this.adapterInfo=null}_addTrackedListener(e,t,n){e&&(e.addEventListener(t,n),this._trackedListeners.push({target:e,type:t,handler:n}))}_removeTrackedListeners(){for(let{target:e,type:t,handler:n}of this._trackedListeners)try{e.removeEventListener(t,n)}catch(e){Ky.warn(`failed to remove listener`,t,e)}this._trackedListeners.length=0}async init(){let e=this._initStorage();return await this._initRenderer(),this._applyPendingReservedRenderSize(),this.camera=this._createCamera(),this._initScenes(),this._initAssetPipeline(),this._initPipeline(),await this._initManagers(),this._wireEvents(),await e,this._attachStorage(),this.stages.pathTracer.setTriangleData(new Uint32Array(K.FLOATS_PER_TRIANGLE),0),this.stages.pathTracer.setBVHData(qy()),this.stages.pathTracer.materialData.setMaterialData(new Float32Array(16)),this.stages.pathTracer.setupMaterial(),this.isInitialized=!0,Ky.debug(`WebGPU path tracer app initialized`),this}async setStorageOpener(e){this._storageOpener=e,!(!this.isInitialized||this.storage||this._disposed)&&(await this._initStorage(),this._attachStorage())}async _initStorage(){let e=this._storageOption??(this._issues.strict&&!oi(`storage`)?!1:si().storage);if(e!==!1){if(e&&typeof e==`object`)this.storage=e;else{if(!this._storageOpener){(this._storageOption!==void 0||oi(`storage`))&&this._issues.warn(X.CAPABILITY_MISSING,`on-disk storage needs rayzee/addons/storage: setStorageOpener( acquireSharedStorage )`);return}let{storage:e,reason:t,release:n}=await this._storageOpener(si().cacheNamespace);if(this._disposed){n();return}if(!e){this._issues.warn(X.STORAGE_UNAVAILABLE,`on-disk storage is off: ${t}`,{reason:t});return}this.storage=e,this._storageRelease=n}this._addTrackedListener(this.storage,`change`,e=>this.dispatchEvent({type:N.STORAGE_CHANGED,area:e.area})),this._addTrackedListener(this.storage,`issue`,e=>this._issues.warn(e.code,e.message,e.detail))}}_attachStorage(){this.assetLoader&&(this.assetLoader.storage=this.storage)}dispatchEvent(e){super.dispatchEvent(e);let t=P[e.type];t&&super.dispatchEvent({...e,type:t})}addEventListener(e,t){!Uy.has(e)&&!Wy.has(e)&&(Wy.add(e),Ky.warn(`no engine event is named "${e}", so this listener will never fire — see EngineEvents`)),super.addEventListener(e,t)}animate(){if(this._headless)throw Error(`a headless app has no render loop — drive it with renderFrames() or renderUntilComplete()`);if(this._deviceLost)return;if(this.animationManagerId=requestAnimationFrame(()=>this.animate()),this._loadingInProgress||this._sdf?.isProcessing){this.dispatchEvent({type:N.FRAME});return}this._beginFrame();let e=this.needsReset;if(this.needsReset&&=(this.stages.pathTracer?.noteViewChanged(),this.reset(!0),!1),this.camera.updateMatrixWorld(),!this.pathTracerEnabled){this.renderer.render(this.meshScene,this.camera),this._renderHelperOverlay();return}if(!this.pauseRendering){if(this._beforeTrace(),this.stages.pathTracer?.isReady){if(this.stages.pathTracer.isComplete&&this.completion.renderCompleteDispatched){if(this._needsDisplayRefresh&&(this._needsDisplayRefresh=!1,this.stages.compositor.render(this.pipeline.context),this._renderHelperOverlay()),this._settling()){this.dispatchEvent({type:N.FRAME});return}this.stopAnimation();return}if(this._holdTrace(e)){this._renderHelperOverlay(),this.dispatchEvent({type:N.FRAME});return}if(this.stages.pathTracer.readbackWait()){this.dispatchEvent({type:N.FRAME});return}this._traceFrame({liveDenoise:!0}),this.stages.pathTracer.isComplete&&this.completion.markComplete()&&this._announceComplete()}this._renderHelperOverlay(),this.dispatchEvent({type:N.FRAME})}}_announceComplete(){let e=this._completionInfo(),t=this.stages.pathTracer.resetCount,n=()=>{!this.completion.renderCompleteDispatched||this.stages.pathTracer?.resetCount!==t||(this._renderCompleted(),this.dispatchEvent({type:N.RENDER_COMPLETE,...e}))},r=this._finishImage();r?r.then(n,n):n()}_traceFrame({liveDenoise:e=!1}={}){let t=this.stages.pathTracer;this.pipeline.render(),this._afterTrace(t,e),t.isComplete||this.completion.updateTime(),this._ensureVRAMWiring();let n=t.vramTracker,r=t.frameCount??0;n&&(r<=1||r%30==0)&&n.measure(),ue({timeElapsed:this.completion.timeElapsed,samples:L(t),memoryUsed:n?.current??0,memoryPeak:n?.peak??0}),this.completion.isTimeLimitReached(t,this.settings.get(`renderLimitMode`),this.settings.get(`renderTimeLimit`))&&(t.isComplete=!0)}_completionInfo(){return{samples:this.stages.pathTracer.frameCount,timeElapsed:this.completion.timeElapsed,budgetOverrun:this.completion.budgetOverrun,reason:this.completion.stopCondition(this.stages.pathTracer)??`samples`}}stopAnimation(){this.animationManagerId&&=(cancelAnimationFrame(this.animationManagerId),null)}_handleDeviceLost(e){this._deviceLost||(this._deviceLost=!0,Ky.error(`WebGPU device lost (${e?.reason||`unknown`}): ${e?.message||``}`),this.stopAnimation(),this.dispatchEvent({type:N.DEVICE_LOST,reason:e?.reason,message:e?.message}))}wake(){this._deviceLost||this._headless||!this.animationManagerId&&this.isInitialized&&!this._paused&&this.animate()}pause(){this._paused=!0,this.stopAnimation()}resume(){this._paused=!1,!this.animationManagerId&&!this._headless&&this.animate()}reset(e=!1,{motion:t=!1}={}){t&&this.stages.pathTracer?.noteViewChanged(),this._beforeReset(e||t),this.pipeline&&(this.pipeline.reset(),e||this.pipeline.eventBus.emit(`pipeline:historyReset`)),this._afterReset(),this.completion.reset(),this.wake(),this.dispatchEvent({type:N.RENDER_RESET})}dispose(){if(this._disposed)return;if(this._disposed=!0,this.dispatchEvent({type:N.DISPOSE}),this.stopAnimation(),clearTimeout(this._resizeDebounceTimer),this._resizeDebounceTimer=null,clearTimeout(this._respillTimer),this._respillTimer=null,this._removeTrackedListeners(),I(null),this._storageRelease?.(),this._storageRelease=null,this.storage=null,this._sceneSource=this._sceneSourceInput=null,this._issues.detach(),this.color?.dispose(),this.color=null,this._textureReadback?.dispose(),this._textureReadback=null,this._readbackToneMapper?.dispose(),this._readbackToneMapper=null,this._disposeExtensions(),this.lightManager?.dispose(),this.pipeline?.dispose(),this._sdf?.dispose(),this._sdf=null,this.assetLoader?.dispose(),this.assetLoader=null,this.meshScene){this.meshScene.environment?.dispose(),this.meshScene.environment=null;for(let e of[...this.meshScene.children])re(e);this.meshScene.clear(),this.meshScene=null}this._sceneHelpers?.clear(),this._sceneHelpers=null,this.scene?.clear(),this.scene=null;try{let e=(0,n.texture)().value,t=(0,n.cubeTexture)().value;e?._listeners?.dispose&&(e._listeners.dispose.length=0),t?._listeners?.dispose&&(t._listeners.dispose.length=0)}catch(e){Ky.warn(`failed to clear TSL texture singleton listeners`,e)}this.canvas&&Vy.get(this.canvas)===this&&Vy.delete(this.canvas);let e=this._gpuDevice;e&&(e.onuncapturederror=null,this._gpuDevice=null),this._deviceLostHolder&&=(this._deviceLostHolder.app=null,null),Promise.resolve(ne(this.renderer)).finally(()=>e?.destroy()),this.renderer=null,this.stages={},this.isInitialized=!1}unloadScene(){if(this.isInitialized){if(this._loadingInProgress)throw Error(`PathTracerApp.unloadScene: cannot unload while a load is in progress`);this._disposed||(this._releaseSceneState(),this.assetLoader?.releaseTargetModel(),this._sceneSource=this._sceneSourceInput=null,this.lightManager?.clearLights?.(),this.stages.pathTracer&&(this.stages.pathTracer.setTriangleData(new Uint32Array(K.FLOATS_PER_TRIANGLE),0),this.stages.pathTracer.setBVHData(qy()),this.stages.pathTracer.materialData.setMaterialData(new Float32Array(16)),this.stages.pathTracer.setEmissiveTriangleData?.(new Float32Array,0,0),this.stages.pathTracer.setupMaterial()),this._dropDisplay(),this.reset(),this.dispatchEvent({type:N.SCENE_UNLOADED}))}}async loadModel(e,t={}){await this._loadWithSceneRebuild(()=>this.assetLoader.loadModel(e,t),{type:N.MODEL_LOADED,url:e},{kind:`url`,url:e,cacheKey:t.cacheKey??null})}async loadObject3D(e,t=`object3d`){await this._loadWithSceneRebuild(()=>this.assetLoader.loadObject3D(e,t),{type:N.OBJECT3D_LOADED,name:t},{kind:`object3d`,name:t})}_busyError(e){let t=Error(`${e}: another load is already in progress`);return t.code=`LOAD_IN_PROGRESS`,t}async loadEnvironment(e){if(this._loadingInProgress)throw this._busyError(`PathTracerApp.loadEnvironment`);this._loadingInProgress=!0;try{await this.assetLoader.loadEnvironment(e);let t=this.meshScene.environment;t&&this.stages.pathTracer&&await this.stages.pathTracer.environment.setEnvironmentMap(t),this.pipeline?.eventBus.emit(`pipeline:lightingChanged`),this.reset(),this.dispatchEvent({type:N.ENVIRONMENT_LOADED,url:e})}finally{this._loadingInProgress=!1}}async inspectArchive(e){return await this.assetLoader.inspectArchive(e)}async loadFile(e,t={}){if(t=this._sceneBudgets(t),typeof e==`string`){let n=t.filename??tv(e),r=this.assetLoader?.getFileFormat(n);if(!r)throw this.assetLoader.formatError(n);if(r.type===`environment`||r.type===`image`)return this.loadEnvironment(e);await this._loadWithSceneRebuild(()=>this.assetLoader.loadAssetFromUrl(e,{...t,filename:n}),{type:N.MODEL_LOADED,filename:n},{kind:`url`,url:e,filename:n,cacheKey:t.cacheKey??null,...By(t)});return}if(Ev(e)){let n=Cv(e,{isModel:e=>this.assetLoader?.getFileFormat(e)?.type===`model`});if(n.files.length===0)throw Error(`${n.name} holds no files to load`);await this._loadWithSceneRebuild(()=>this.assetLoader.loadFolder(n,t),{type:N.MODEL_LOADED,filename:n.name},async()=>{let e=await mv(n);return{kind:`local-folder`,folder:e,key:hv(e),...n.flat?{flat:!0}:{},...By(t)}}),this._sceneSourceInput=n;return}let n=this.assetLoader?.getFileFormat(e?.name||``);if(!n)throw this.assetLoader.formatError(e?.name||``);if(n.type!==`environment`&&n.type!==`image`){let n=pv(e).catch(()=>({name:e.name,size:e.size,lastModified:e.lastModified??0,sample:null}));await this._loadWithSceneRebuild(()=>this.assetLoader.loadAssetFromFile(e,t),{type:N.MODEL_LOADED,filename:e.name},async()=>{let e=await n;return{kind:`local-file`,file:e,key:e.sample?hv(e):null,...By(t)}}),this._sceneSourceInput=e;return}if(this._loadingInProgress)throw this._busyError(`PathTracerApp.loadFile`);this._loadingInProgress=!0;try{await this.assetLoader.loadAssetFromFile(e);let t=this.meshScene.environment;t&&this.stages.pathTracer&&await this.stages.pathTracer.environment.applyHDRI(t),this.pipeline?.eventBus.emit(`pipeline:lightingChanged`),this.reset(),this.dispatchEvent({type:N.ENVIRONMENT_LOADED,filename:e.name})}finally{this._loadingInProgress=!1}}async loadExampleModels(e,t){await this._loadWithSceneRebuild(()=>this.assetLoader.loadExampleModels(e,t),{type:N.MODEL_LOADED,index:e},{kind:`url`,url:t[e]?.url??null,cacheKey:null})}cancelLoad(){this._loadingInProgress&&this.assetLoader?.cancelActiveLoad()}async setMaxTextureSize(e,{reprocess:t=!0}={}){let n=this.settings.get(`maxTextureSize`),r=this._sdf?.setMaxTextureSize(e)??e;if(this.settings.set(`maxTextureSize`,r,{reset:!1}),typeof this.stages?.pathTracer?.sdfs?.setMaxTextureSize==`function`&&this.stages.pathTracer.sdfs.setMaxTextureSize(r),t&&r!==n&&this._sdf?.triangles&&!this._loadingInProgress){this._loadingInProgress=!0;try{await this.loadSceneData(),this.reset(),this.dispatchEvent({type:N.TEXTURES_REPROCESSED,maxTextureSize:r})}finally{this._loadingInProgress=!1}}}get sceneSource(){return this._sceneSource??null}get sceneSourceFile(){return this._sceneSourceInput&&!Ev(this._sceneSourceInput)?this._sceneSourceInput:null}get sceneSourceFolder(){return Ev(this._sceneSourceInput)?this._sceneSourceInput:null}async _loadWithSceneRebuild(e,t,n=null){if(this._loadingInProgress)throw this._busyError(`PathTracerApp`);this._loadingInProgress=!0,this.assetLoader&&(this.assetLoader.maxEnvironmentWidth=this._memorySpill===!0?Co:0);try{await e(),this._sceneSource=typeof n==`function`?await n():n,this._sceneSourceInput=null,this._emissiveSamplingUserSet=!1,this._clearAppendedModels(),this._modelReplaced(),this._planSpill();let r=await this.loadSceneData({pendingEnvironment:this._beginSceneMetadataEnvironment()});this._maybeSpill(),this.pipeline?.eventBus.emit(`pipeline:lightingChanged`),this._dropDisplay(),this.reset(),this.dispatchEvent(t),this._modelAnnounced(),r&&this.assetLoader?.commitPendingGraph(this.sceneModel)}catch(e){throw(!e||e.code!==`LOAD_IN_PROGRESS`)&&this._discardFailedLoad(),e?.code===`ARCHIVE_NEEDS_ELEMENT`?le():e?.code!==`LOAD_IN_PROGRESS`&&z({status:`Error: ${e?.message??e}`,failed:!0,progress:100}),e}finally{this._loadingInProgress=!1,this._spillPlan=null}}_discardFailedLoad(){this._sceneSource=this._sceneSourceInput=null;try{this._clearAppendedModels(),this.assetLoader?.releaseTargetModel(),this._dropDisplay(),this.reset()}catch(e){console.warn(`PathTracerApp: could not clear the scene after a failed load`,e)}}get sceneMetadata(){return this.assetLoader?.sceneMetadata??null}_beginSceneMetadataEnvironment(){this._restoreUnlitSettings();let e=this.sceneMetadata?.environment;return this._applySceneMetadataEnabled&&e?.enabled===!1?(this._applyUnlitSettings(),null):!this._applySceneMetadataEnabled||!e?.sourceFile||!this.stages.pathTracer?null:(this.stages.pathTracer.environment.beginHDRI(),this._applyingSceneMetadata=!0,this.assetLoader.loadEnvironment(e.sourceFile).catch(t=>(this._issues.record(X.ENVIRONMENT_LOAD_FAILED,`authored environment "${e.sourceFile}" failed to load — lighting falls back to the previous environment`,{sourceFile:e.sourceFile,cause:String(t?.message??t)}),null)).finally(()=>{this._applyingSceneMetadata=!1}))}_applySceneMetadataSettings(e){let t=this.sceneMetadata,n=t?.environment;if(!n||n.enabled===!1)return;let r={enableEnvironment:!0,showBackground:!0,transparentBackground:!1};n.intensity!==void 0&&(r.environmentIntensity=n.intensity,r.backgroundIntensity=n.intensity),n.rotation!==void 0&&(r.environmentRotation=n.rotation),this.settings.setMany(r,{reset:!1,source:Av.SCENE_METADATA}),this.scene&&(this.scene.background=e),this.dispatchEvent({type:N.SCENE_METADATA_APPLIED,metadata:t,environment:{...n}})}_applyUnlitSettings(){let e=this.settings.getEffective(),t={enableEnvironment:!1,showBackground:!1};this._unlitRestore=Object.fromEntries(Object.keys(t).map(t=>[t,{value:e[t].value,source:e[t].source}])),this.settings.setMany(t,{reset:!1,source:Av.SCENE_METADATA}),this.dispatchEvent({type:N.SCENE_METADATA_APPLIED,metadata:this.sceneMetadata,environment:{enabled:!1}})}_restoreUnlitSettings(){let e=this._unlitRestore;if(!e)return;this._unlitRestore=null;let t=this.settings.getEffective();for(let[n,{value:r,source:i}]of Object.entries(e))t[n]?.source===Av.SCENE_METADATA&&this.settings.set(n,r,{reset:!1,source:i});this.dispatchEvent({type:N.SCENE_METADATA_APPLIED,metadata:this.sceneMetadata,environment:{enabled:this.settings.get(`enableEnvironment`)}})}async loadSceneData({pendingEnvironment:e=null,keepUserLights:t=!1}={}){this._releaseSceneState({keepSelection:!!this._preserveSelectionOnRebuild}),this._tagPrimarySceneObject();let n=new tc(``,{namespace:`scene`,level:`info`}),r=()=>this.stages.pathTracer.environment.envParams.mode===`hdri`?this.meshScene.environment:null,i=r(),a=null;if(e?(n.start(`Environment fetch + CDF (concurrent)`),a=e.then(async e=>{e&&(await this.stages.pathTracer.environment.applyHDRI(e),this._applySceneMetadataSettings(e))}).catch(e=>this._issues.record(X.ENVIRONMENT_LOAD_FAILED,`authored environment failed to install — the scene is lit by whatever was already loaded`,{cause:String(e?.message??e)})).finally(()=>n.end(`Environment fetch + CDF (concurrent)`))):i?.image?.data&&(n.start(`Environment CDF build (worker)`),this.stages.pathTracer.scene.environment=i,a=this.stages.pathTracer.environment.buildEnvironmentCDF().then(()=>{n.end(`Environment CDF build (worker)`),this._applySceneMetadataEnabled&&this._applySceneMetadataSettings(i)})),n.start(`BVH build (SceneProcessor)`),this._sdf.setMaxTextureSize(this.settings.get(`maxTextureSize`)),await this._sdf.buildBVH(this.meshScene,{sceneKey:this.assetLoader?.sceneSourceKey??null,progressive:this._progressiveSpill()}),this.assetLoader?.flushPendingGraph(this._sdf.performanceMetrics.totalProcessingTime),n.end(`BVH build (SceneProcessor)`),z({status:`Transferring data to GPU...`,progress:86}),await new Promise(e=>setTimeout(e,0)),n.start(`GPU data transfer`),await this._sdf.uploadChunks(this._chunkUploader()),!this._sdf.uploadToPathTracer(this.stages.pathTracer,this.lightManager,this.meshScene,r(),{keepUserLights:t}))return!1;for(let e of[...this._sdf.srgbBucketTextures??[],...this._sdf.linearBucketTextures??[]])e&&(this.renderer.initTexture(e),await this.stages.pathTracer.drainUploads());this.stages.pathTracer._meshRefs=this.stages.pathTracer._collectMeshRefs(this.meshScene),this.stages.pathTracer.setMeshVisibilityData(this.stages.pathTracer._meshRefs),this._refreshEmissiveForVisibility(),n.end(`GPU data transfer`),z({status:`Compiling shaders...`,progress:90}),await new Promise(e=>setTimeout(e,0)),n.start(`Material setup (TSL compile)`),this.stages.pathTracer.setupMaterial(),n.end(`Material setup (TSL compile)`),this._rasterPrecompile=null,this._pathTracerEnabled||(n.start(`Pipeline precompile`),await this.precompileRaster(),n.end(`Pipeline precompile`)),a&&(z({status:`Finalizing environment map...`,progress:95}),await a,this.stages.pathTracer.environment.applyCDFResults());let o=this.getSceneMinY();if(this.settings.set(`groundProjectionLevel`,o,{reset:!1}),this.settings.set(`groundCatcherHeight`,o,{reset:!1}),!this._emissiveSamplingUserSet){let e=(this._sdf?.emissiveTriangleBuilder?.emissiveTriangles?.length??this._sdf?.emissiveTriangleCount??0)>0;this.settings.set(`enableEmissiveTriangleSampling`,e,{reset:!1})}return n.start(`Apply settings`),this.settings.applyAll(),this.stages.compositor.setTransparentBackground(this.settings.get(`transparentBackground`)),n.end(`Apply settings`),n.print(this._sceneSummaryParts()),le(),this._sceneRebuilt(),this.dispatchEvent({type:N.SCENE_REBUILD}),!0}_sceneSummaryParts(){let e=this.stages.pathTracer,t=this._sdf?.instanceTable?.setCount??0,n=this._sdf?.geometryExtractor?.maps?.length??0;return[V.count(e.triangleCount,`tri`),t?V.count(t,`mesh`,`meshes`):null,V.count(e.materialData.materialCount,`material`),n?V.count(n,`map`):null,V.count(e.bvhNodeCount,`BVH node`)]}_tagPrimarySceneObject(){let e=this.sceneModel;e&&(e.userData.__rayzeeSceneObject=!0)}_clearAppendedModels(){let e=this.meshScene;if(!e)return;let t=this.assetLoader?.floorPlane,n=this.sceneModel;for(let r of[...e.children])r===t||r===n||r.userData?.__rayzeeSceneObject&&this.assetLoader.removeModelRoot(r)}async _finishRebuildNoReframe(e){await this.loadSceneData({keepUserLights:!0}),this._maybeSpill(),this._sceneBoundsChanged(),this.pipeline?.eventBus.emit(`pipeline:lightingChanged`),this.reset(),e&&this.dispatchEvent(e)}async addModel(e,{name:t,cacheKey:n}={}){if(this._loadingInProgress)throw Error(`PathTracerApp.addModel: another load is already in progress`);this._loadingInProgress=!0,this._preserveSelectionOnRebuild=!0;try{let{root:r}=await this.assetLoader.appendModel(e,{cacheKey:n});return r.userData.__rayzeeSceneObject=!0,r.userData.__rayzeeSourceUrl=e,n&&(r.userData.__rayzeeCacheKey=n),t&&(r.userData.__rayzeeName=t),await this._finishRebuildNoReframe({type:N.MODEL_ADDED,url:e,id:r.uuid}),r.uuid}finally{this._preserveSelectionOnRebuild=!1,this._loadingInProgress=!1}}async addModelFromObject3D(e,{name:t}={}){if(this._loadingInProgress)throw Error(`PathTracerApp.addModelFromObject3D: another load is already in progress`);this._loadingInProgress=!0,this._preserveSelectionOnRebuild=!0;try{let{root:n}=this.assetLoader.appendObject3D(e,t||`object3d`);return n.userData.__rayzeeSceneObject=!0,t&&(n.userData.__rayzeeName=t),await this._finishRebuildNoReframe({type:N.MODEL_ADDED,id:n.uuid}),n.uuid}finally{this._preserveSelectionOnRebuild=!1,this._loadingInProgress=!1}}async removeSceneObject(e){if(!this.meshScene)return!1;let t=this.assetLoader?.floorPlane;if(t&&t.uuid===e)return!1;let n=this.getSceneObject(e);if(!n)return!1;if(this._loadingInProgress)throw Error(`PathTracerApp.removeSceneObject: another load is already in progress`);this._loadingInProgress=!0;try{return this._releaseSceneState(),n===this.sceneModel?this.assetLoader.releaseTargetModel():this.assetLoader.removeModelRoot(n),await this._finishRebuildNoReframe({type:N.SCENE_OBJECT_REMOVED,id:e}),!0}finally{this._loadingInProgress=!1}}setSceneObjectVisibility(e,t){return this.setMeshVisibilityByUuid(e,t)}get memorySpill(){return this._memorySpill}setMemorySpill(e){this._memorySpill=e===!0||e===!1?e:`auto`}get sceneSpilled(){return!!this._sdf?.spilling}get geometryOnDisk(){return this._sdf?.geometryOnDisk===!0}_sceneBudgets(e){return this._memorySpill===!1||!this.storage?e:{maxTriangles:xo,maxPlacements:So,...e}}_planSpill(){let e=this._memorySpill!==!1&&!!this.storage&&(this.assetLoader?.animations?.length??0)===0&&(this._memorySpill===!0||this._sdf.needsSpill(this.meshScene));this.assetLoader&&(this.assetLoader.maxEnvironmentWidth=e?Co:0);let t=e?this.meshScene?.environment:null,n=t?.image;return n&&My(t,Co),t&&t.image!==n&&(t.dispose(),t.needsUpdate=!0),e&&this._memorySpill===`auto`&&Ky.info(`scene is past the in-memory line: building it through disk`),this._spillPlan=e,e}_progressiveSpill(){let e=this._spillPlan??this._planSpill();return this._spillPlan=null,e?{storage:this.storage,uploader:this._chunkUploader()}:null}_chunkUploader(){let e=this.stages.pathTracer;return(t,n,r)=>n===`triangles`?e.createTriangleChunkUploader(t,r):e.createChunkUploader(t)}_maybeSpill(){!this._sdf?.spilling||!this.storage||(this._sdf.spillAfterLoad().catch(e=>this._issues.warn(X.STORAGE_WRITE_FAILED,`memory spill failed: ${e.message}`)),this._sdf.spillToDisk(this.storage).then(e=>e&&this.dispatchEvent({type:N.SCENE_SPILLED,...e})).catch(e=>this._issues.warn(X.STORAGE_WRITE_FAILED,`memory spill failed: ${e.message}`)))}_scheduleRespill(){this._sdf?.spilling&&(clearTimeout(this._respillTimer),this._respillTimer=setTimeout(()=>{this._respillTimer=null,this._sdf?.respill().catch(e=>this._issues.warn(X.STORAGE_WRITE_FAILED,`memory spill failed: ${e.message}`))},Hy),this._respillTimer.unref?.())}async ensureSceneResident(){this._sdf?.spilled&&await this._sdf.ensureResident(),await this._sdf?.ensureGeometryResident()}get sceneMeshes(){return this._sdf?.meshes??[]}get sceneModel(){return this.assetLoader?.targetModel??null}getSceneObject(e){let t=this.meshScene?.children.find(t=>t.uuid===e);return t?.userData?.__rayzeeSceneObject?t:null}async refitBVH(e,t){await this.ensureSceneResident();let{triRanges:n,bvhRanges:r,...i}=await this._sdf.refitBVH(e,t);return this.stages.pathTracer.updateTriangleData(this._sdf.triangles,n),this.stages.pathTracer.updateBVHData(this._sdf.bvh,r),this.reset(!1,{motion:!0}),i}refitBLASes(e,t,n){if(this._sdf?.spilled)throw Error(`refitBLASes: the scene is spilled to disk — await app.ensureSceneResident() first`);let r=this._sdf.refitBLASes(e,t,n),{triRanges:i,bvhRanges:a}=this._sdf.computeBLASDirtyRanges(e);return this.stages.pathTracer.updateBufferRanges(i,a),this.reset(!1,{motion:!0}),this._sdf.scheduleBackgroundRebuild(e,e=>{let t=this._sdf.computeBLASDirtyRanges([e]);this.stages.pathTracer.updateBufferRanges(t.triRanges,t.bvhRanges),this.reset(!1,{motion:!0})}),r}updateMeshTransforms(e){if(this._sdf?.needsPageInForMove(e))return this._sdf.ensureMovable(e).then(()=>this.updateMeshTransforms(e)).catch(e=>this._issues.warn(X.STORAGE_READ_FAILED,`reading instance matrices back failed: ${e.message}`)),null;this._notePlacementsMoving(e);let t=this._sdf.updateMeshTransforms(e);return this.stages.pathTracer.updateBufferRanges([],this._sdf.takeMoveRanges()),this.reset(!1,{motion:!0}),this._scheduleRespill(),t}setReservedRenderResolution(e,{allowLower:t=!1}={}){let n=t?e:Math.max(e,Me);if(!this.renderer)return this._pendingReservedRenderSize={requestedPx:e,allowLower:t},Math.max(256,Math.min(je,Math.floor(n)||256));let r=this.renderer.backend?.device?.limits?.maxStorageBufferBindingSize||128*1024*1024,i=co(this._hostMemoryGB),a=i.gb>=8&&r>=1024*1024*1024?je:2048,o=Ne(Math.min(n,a));if(o<Math.floor(e)&&this._issues.warn(X.RENDER_RESERVE_CAPPED,`reserved render size ${V.n(e)}px was capped to ${V.n(o)}px by this device's limits — renders above ${V.n(o)}px will be declined`+(i.assumed&&i.gb<8?` (host memory unknown, 4 GB assumed: pass hostMemoryGB)`:``),{requested:e,applied:o,deviceMemoryGB:i.gb,assumed:i.assumed,maxStorageBufferBindingSize:r}),(this.stages?.pathTracer?.storageTextures?.writeColor?.image?.width??o)!==o){let e=this.pauseRendering;this.pauseRendering=!0;try{let e=this.renderer.domElement;(e.width>o||e.height>o)&&this.renderer.setSize(Math.min(e.width,o),Math.min(e.height,o),!1);for(let e of Object.values(this.stages))e?.reallocateReservedStorage?.()}finally{this.pauseRendering=e}this.reset(),this.dispatchEvent({type:N.RESERVED_RENDER_SIZE_CHANGED,size:o})}return o}_applyPendingReservedRenderSize(){let e=this._pendingReservedRenderSize;if(!e)return;this._pendingReservedRenderSize=null;let t=this.setReservedRenderResolution(e.requestedPx,{allowLower:e.allowLower});this.dispatchEvent({type:N.RESERVED_RENDER_SIZE_CHANGED,size:t})}getReservedRenderResolution(){return Me}_isRenderSizeSupported(e,t){return e>Me||t>Me?(this._issues.record(X.RENDER_SIZE_DECLINED,`render resolution ${e}×${t} exceeds the ${Me}px storage reserve — resize ignored, so output stays at the previous size. Raise it with setReservedRenderResolution( ${Math.max(e,t)} ) before init().`,{width:e,height:t,reserve:Me}),!1):!0}onResize(){let e=this.canvas.clientWidth,t=this.canvas.clientHeight;e===0||t===0||this._isRenderSizeSupported(e,t)&&(this.renderer.setPixelRatio(1),this._setDisplaySize(e,t),!(e===this._renderWidth&&t===this._renderHeight)&&(clearTimeout(this._resizeDebounceTimer),this._resizeDebounceTimer=setTimeout(()=>{this._applyRenderResize(e,t)},300)))}_applyRenderResize(e,t){this._isRenderSizeSupported(e,t)&&(this.pipeline?.setSize(this._scaled(e),this._scaled(t)),this._renderWidth=e,this._renderHeight=t,this._renderSizeChanged(e,t),this.needsReset=!0,this.dispatchEvent({type:N.RESOLUTION_CHANGED,width:e,height:t}))}setCanvasSize(e,t){return e===0||t===0||!this._isRenderSizeSupported(e,t)?null:(this.renderer.setPixelRatio(1),this._setDisplaySize(e,t),clearTimeout(this._resizeDebounceTimer),this._applyRenderResize(e,t),{width:e,height:t})}_scaled(e){return Math.max(1,Math.round(e*this._renderScale))}_setDisplaySize(e,t){this._displayWidth=e,this._displayHeight=t,this.renderer.setSize(this._scaled(e),this._scaled(t),!1),this.camera.aspect=e/t,this.camera.updateProjectionMatrix()}refreshFrame(){this._needsDisplayRefresh=!0,this.wake()}setDeterministicMode(e=!0,{pinDispatch:t=!0}={}){let n=this.stages.pathTracer;if(!n)return!1;if(e)this._deterministicRestore||={settings:{useAdaptiveSampling:this.settings.get(`useAdaptiveSampling`),usePixelFreeze:this.settings.get(`usePixelFreeze`),interactionModeEnabled:this.settings.get(`interactionModeEnabled`),renderLimitMode:this.settings.get(`renderLimitMode`),renderTimeLimit:this.settings.get(`renderTimeLimit`)},bounceEarlyExit:n._bounceEarlyExitThreshold,dynamicDispatch:n._useDynamicDispatch,extras:this._deterministicSnapshot()},this.settings.setMany({useAdaptiveSampling:!1,usePixelFreeze:!1,interactionModeEnabled:!1,renderLimitMode:`frames`,renderTimeLimit:0},{silent:!0}),t?(n._bounceEarlyExitThreshold=-1,n._useDynamicDispatch=!1):(n._bounceEarlyExitThreshold=this._deterministicRestore.bounceEarlyExit,n._useDynamicDispatch=this._deterministicRestore.dynamicDispatch),this._setDeterministicExtras(!0,this._deterministicRestore.extras),n._pinSeedToFrame=!0,this._deterministic=!0,this._dispatchPinned=t;else if(this._deterministicRestore){let e=this._deterministicRestore;this.settings.setMany(e.settings,{silent:!0}),n._bounceEarlyExitThreshold=e.bounceEarlyExit,n._useDynamicDispatch=e.dynamicDispatch,this._setDeterministicExtras(!1,e.extras),n._pinSeedToFrame=!1,this._deterministicRestore=null,this._deterministic=!1,this._dispatchPinned=!1}return this.reset(),this.stopAnimation(),this._deterministic}get issues(){return this._issues.list}get issueErrors(){return this._issues.errors}clearIssues(){this._issues.clear()}get isDeterministic(){return this._deterministic&&this._dispatchPinned}async renderFrames(e,{reset:t=!0,yieldEvery:n=8,onProgress:r,allowEarlyRetire:i=!1}={}){let a=this.stages.pathTracer;if(!a)throw Error(`renderFrames: app is not initialized`);if(!(e>0))throw Error(`renderFrames: count must be positive, got ${e}`);let o=(t?0:a.frameCount)+e;this.settings.get(`maxSamples`)<o&&this.settings.set(`maxSamples`,o,{silent:!0,reset:!1}),t&&this.reset(),this.stopAnimation();let s=e+64,c=0,l=!1;for(;a.frameCount<o&&c<s;){if(this._deviceLost)throw Error(`renderFrames: WebGPU device lost`);if(!a.isReady)throw Error(`renderFrames: path tracer stage is not ready`);let e=a.readbackWait();if(e){await this._awaitReadback(e);continue}if(this.camera.updateMatrixWorld(),this.pipeline.render(),c++,a.isComplete&&a.frameCount<o){l=!0;break}r?.(a.frameCount),n>0&&c%n===0&&await new Promise(e=>setTimeout(e,0))}if(a.frameCount<o&&!(l&&i)){let e=l?"adaptive sampling retired the frame at the convergence threshold — pass `allowEarlyRetire: true`, or disable it with setDeterministicMode()":`something retired the render (maxSamples, a stray reset, or a canvas resize)`;throw Error(`renderFrames: stopped at ${a.frameCount}/${o} samples after ${c} passes — ${e}`)}return await this._finishImage(),a.frameCount}async renderUntilComplete({reset:e=!0,denoise:t=!0,signal:n,drainEvery:r=4,onProgress:i}={}){let a=this.stages.pathTracer;if(!a)throw Error(`renderUntilComplete: app is not initialized`);if(this._loadingInProgress||this._sdf?.isProcessing)throw Error(`renderUntilComplete: a scene is still loading`);let o=a.lockstepReadbacks;a.setLockstepReadbacks(!0);let s=this.settings.getEffective().interactionModeEnabled;this.settings.set(`interactionModeEnabled`,!1,{silent:!0,reset:!1});try{e&&this.reset(),this.stopAnimation();let o=this.renderer.backend.device?.queue,s=0,c=null;for(;!a.isComplete;){if(n?.throwIfAborted(),this._deviceLost)throw Error(`renderUntilComplete: WebGPU device lost`);if(!a.isReady)throw Error(`renderUntilComplete: path tracer stage is not ready`);let e=a.readbackWait();if(e){await this._awaitReadback(e);continue}this.camera.updateMatrixWorld();let t=a.frameCount;if(this._traceFrame(),i?.(a.frameCount),a.frameCount===t&&!a.isComplete&&await new Promise(e=>setTimeout(e,0)),o&&r>0&&++s%r===0){let e=o.onSubmittedWorkDone();c&&await c,c=e}}let l=this._completionInfo();await this._finishImage(),this.completion.markComplete()&&this.dispatchEvent({type:N.RENDER_COMPLETE,...l});let u=t?await this._finalDenoise():!1,{reason:d,...f}=l;return{...f,retiredBy:d,denoised:u}}finally{a.setLockstepReadbacks(o),s&&this.settings.set(`interactionModeEnabled`,s.value,{silent:!0,reset:!1,source:s.source})}}getProvenance(){let e=this.stages.pathTracer,t=this.color?.status();return nr({engine:Cc,three:r.REVISION,adapter:this.adapterInfo??null,mode:{headless:this._headless,strict:this._issues.strict,deterministic:this.isDeterministic,lockstep:!!e?.accumulationLockstep},render:e?{width:e.width,height:e.height,samples:e.frameCount,complete:e.isComplete,retiredBy:e.isComplete?this.completion.stopCondition(e)??`samples`:null}:null,color:t?{config:t.config?.id??null,workingSpace:t.workingSpace,view:t.activeView??t.activeTransform?.id??null,context:t.context}:null,scene:this.sceneSource,settings:this.settings.getEffective(),issues:this.issues.map(({code:e,severity:t})=>({code:e,severity:t}))})}setLockstepReadbacks(e=!0){this.stages.pathTracer?.setLockstepReadbacks(e)}async _awaitReadback(e){let t=this.renderer.backend.device?.lost,n=await(t?Promise.race([e.then(()=>null),t]):e);if(n)throw Error(`WebGPU device lost while awaiting a readback: ${n.message??n.reason}`)}async captureRenderCheckpoint(){let e=this.stages.pathTracer;if(!e)return null;let t=await e.captureAccumulation();return{v:1,engine:Cc,savedAt:Date.now(),samples:t.state.frameCount,...t}}restoreRenderCheckpoint(e){if(e?.v!==1)throw Error(`render checkpoint version ${e?.v} is not 1`);let t=this.stages.pathTracer;if(!t)throw Error(`restoreRenderCheckpoint: app is not initialized`);t.restoreAccumulation(e),this.needsReset=!1,this.dispatchEvent({type:N.RENDER_RESET,restored:e.samples})}async renderToBuffer({colorSpace:e=`srgb`,preserveAlpha:t=!1,source:n=`accumulation`}={}){if(e!==`linear`&&e!==`srgb`&&!this.color?.hasConfig)throw Error(`renderToBuffer: colorSpace must be 'linear' or 'srgb' without a colour config loaded, got "${e}"`);let r=this.stages?.pathTracer,i=r?.storageTextures?.readTarget;if(!i)throw Error(`renderToBuffer: no render target — call init() and render at least one sample`);let{width:a,height:o}=r,s=!!this.settings.get(`transparentBackground`);if(e===`srgb`){let r=n===`display`?this._displaySource(i):null,c={exposure:this.renderer.toneMappingExposure,toneMapping:this.renderer.toneMapping,saturation:this.settings.get(`saturation`)??1,preserveAlpha:t&&s,gain:this._displayGain()},l=await this._toneMapOnGPU(r?.texture??null,i,a,o,c),u=!l&&c.gain?.cpu?await c.gain.cpu():null,d=c.gain?.backdrop??0;return{data:l??js(r?await this._readTexture(r.texture,a,o):await D_(this.renderer,i,a,o),{...c,pixelGain:u||d?{fn:u,width:a,height:o,backdrop:d}:null}),width:a,height:o,colorSpace:e,source:r?.source??`accumulation`,toneMappedOn:l?`gpu`:`cpu`}}let{data:c,source:l}=n===`display`?await this._readDisplaySource(i,a,o):{data:await D_(this.renderer,i,a,o),source:`accumulation`};if(!s){let e=c instanceof Uint16Array?15360:1;for(let t=3;t<c.length;t+=4)c[t]=e}if(e===`linear`)return{data:c,width:a,height:o,colorSpace:e,workingSpace:this.color?.workingSpace??null,source:l};let{rgba:u,colorSpace:d}=this.color.exportPixels(c,e);return{data:u,width:a,height:o,colorSpace:d,source:l}}async _toneMapOnGPU(e,t,n,r,i){let a=this.renderer?.backend;if(!a?.device)return this._toneMapFallback(`the renderer has no WebGPU device`);try{let o=e?this._readbackPass().draw(e,n,r).texture:t.textures[0],s=a.get(o).texture;return s?(this._readbackToneMapper??=new Bv(a.device,`rayzee:readback-tonemap`,{input:`texture`}),this._readbackToneMapper.ensureSize(n,r),await this._readbackToneMapper.toRGBA8(s,i)):this._toneMapFallback(`the picture has no GPU texture yet`)}catch(e){if(e instanceof nn)throw e;return this._toneMapFallback(`the GPU pass threw`,e)}finally{this._readbackToneMapper?.release(),e&&this._textureReadback?.release()}}_toneMapFallback(e,t=null){let n=t?String(t?.message??t):null,r=`renderToBuffer: tone mapped on the CPU — ${e}${n?`: ${n}`:``}`;return Ky.warn(r),this._issues.warn(X.OUTPUT_TONEMAP_FALLBACK,r,{reason:e,cause:n}),null}enableGPUTiming(e=!0){let t=this.renderer?.backend;return!t||e&&t.hasFeature?.(`timestamp-query`)!==!0?!1:(t.trackTimestamp=e,t.trackTimestamp===e)}async getGPUTimings(){let e=this.renderer;if(!e?.backend?.trackTimestamp)return null;await e.resolveTimestampsAsync(`compute`),await e.resolveTimestampsAsync(`render`);let t=e.info.compute.timestamp||0,n=e.info.render.timestamp||0;return{compute:t,render:n,total:t+n}}async getKernelGPUTimings(){let e=this.renderer;if(!e?.backend?.trackTimestamp)return null;await e.resolveTimestampsAsync(`compute`);let t=e.backend.timestampQueryPool?.compute?.timestamps;if(!t||t.size===0)return null;let n=new Map,r=this.stages?.pathTracer?._kernelManager?.kernels;if(r)for(let[e,t]of r)n.set(t.id,e);let i=[],a=-1;for(let[e,n]of t){let t=e.split(`:`);if(t.length!==4)continue;let r=Number(t[3].slice(1));Number.isFinite(r)&&(i.push({nodeId:Number(t[2]),f:r,ms:n}),r>a&&(a=r))}let o={},s=0,c=0;for(let e of i){if(e.f!==a)continue;s+=e.ms;let t=n.get(e.nodeId);t===void 0?c+=e.ms:o[t]=(o[t]??0)+e.ms}return{kernels:o,total:s,unattributed:c,frame:a}}getCanvas(){return this.renderer?.domElement?this._displayCanvas()||(this.stages.compositor&&this.pipeline?.context&&this.stages.compositor.render(this.pipeline.context),this.renderer.domElement):null}screenshot({type:e=`image/png`,quality:t}={}){let n=this.getCanvas();return n?new Promise(r=>n.toBlob(r,e,t)):Promise.resolve(null)}getStatistics(){try{return this._sdf?.getStatistics?.()??null}catch{return null}}get pathTracerEnabled(){return this._pathTracerEnabled}set pathTracerEnabled(e){this._pathTracerEnabled=e,e||this.precompileRaster()}precompileRaster(){return!this.renderer||!this.meshScene?Promise.resolve():(this._rasterPrecompile??=this.renderer.compileAsync(this.meshScene,this.camera).catch(e=>Ky.warn(`raster fallback precompile failed`,e)),this._rasterPrecompile)}get isLoading(){return this._loadingInProgress}isComplete(){return this.stages.pathTracer?.isComplete??!1}getFrameCount(){return this.stages.pathTracer?.frameCount||0}getConvergenceStats(){return this.stages.pathTracer?.getConvergenceStats?.()??null}get vram(){return this.stages.pathTracer?.vramTracker??null}getMemoryInfo(){return this._ensureVRAMWiring(),this.stages.pathTracer?.vramTracker?.measure()??{current:0,peak:0,byCategory:{}}}getHostMemoryInfo(){let e=this._sdf;return e?.memory?{preflight:e.memoryPreflight,...e.memory.report}:null}_ensureVRAMWiring(){if(this._vramWired)return;let e=this.stages.pathTracer?.vramTracker;if(!e)return;e.register(`stages`,()=>this._collectStageTextures()),this._registerVRAM(e),e.register(`canvas`,()=>[{bytes:this.canvas.width*this.canvas.height*4},...this.renderer?._frameBufferTargets?.values()??[],...this._canvasResources()]);let t=()=>e.measure();this._addTrackedListener(this,N.SCENE_REBUILD,t),this._addTrackedListener(this,N.ENVIRONMENT_LOADED,t),this._addTrackedListener(this,N.RESOLUTION_CHANGED,t),this._vramWired=!0}_collectStageTextures(){let e=[],t=this.stages||{},n=t.pathTracer;for(let r in t){let i=t[r];if(!(!i||i===n||typeof i!=`object`))for(let t in i){let n=i[t];n&&(n.isTexture||n.isRenderTarget)&&e.push(n)}}return e}getSceneMinY(){if(!this.meshScene)return 0;let e=new r.Box3().setFromObject(this.meshScene);return Number.isFinite(e.min.y)?e.min.y:0}getMaterialProperty(e,t){return this.stages.pathTracer?.materialData.getMaterialProperty(e,t)}getMaterialPropertySource(e,t){return this.stages.pathTracer?.materialData.getMaterialPropertySource(e,t)}setMaterialProperty(e,t,n){if(this._sdf?.spilled&&yr.has(t)){this.ensureSceneResident().then(()=>this.setMaterialProperty(e,t,n));return}this.stages.pathTracer?.materialData.updateMaterialProperty(e,t,n),[`emissive`,`emissiveIntensity`].includes(t)&&this._sdf&&this._uploadEmissivePayload(this._sdf.updateMaterialEmissive(e,t,n)),this.reset()}_uploadEmissivePayload(e){!e||!this.stages.pathTracer||(this.stages.pathTracer.setEmissiveTriangleData(e.rawData,e.emissiveCount,e.totalPower,e.bitTrailMap),e.lightBVHNodeData&&this.stages.pathTracer.setLightBVHData(e.lightBVHNodeData,e.lightBVHNodeCount))}_refreshEmissiveForVisibility(){let e=this._sdf?.instanceTable;if(!e)return;let t=new Set;for(let n=0;n<e.count;n++)e.isSet[n]&&!e.visible[n]&&t.add(e.sourceMesh[n]);this._uploadEmissivePayload(this._sdf.rebuildEmissiveForVisibility(t))}setEmissiveTriangleSampling(e){this._emissiveSamplingUserSet=!0,this.settings.set(`enableEmissiveTriangleSampling`,e)}hasEmissiveGeometry(){return(this._sdf?.emissiveTriangleBuilder?.emissiveTriangles?.length??this._sdf?.emissiveTriangleCount??0)>0}setMeshVisibility(e,t){this._whenTLASEditable(()=>this.stages.pathTracer?.updateMeshVisibility(e,t))}updateAllMeshVisibility(){this._whenTLASEditable(()=>this.stages.pathTracer?.updateAllMeshVisibility())}_whenTLASEditable(e){let t=()=>{e(),this._refreshEmissiveForVisibility(),this.reset(),this._scheduleRespill()},n=this._sdf?.whenTLASEditable();if(!n)return t();n.then(t).catch(e=>this._issues.warn(X.STORAGE_READ_FAILED,`reading the TLAS back failed: ${e.message}`))}getScene(){return this.meshScene||this.scene}setMeshVisibilityByUuid(e,t){let n=this.getScene()?.getObjectByProperty(`uuid`,e);if(!n)return null;let r=typeof t==`function`?!!t(n.visible):!!t;return n.visible=r,this.updateAllMeshVisibility(),r}setTextureTransform(e,t,n){this.stages.pathTracer?.materialData.updateTextureTransform(e,t,n),this.reset()}_displaySource(e){let t=this.pipeline?.context,n=t&&this.stages.compositor?.resolveLightSource(t);return n&&n.key!==`pathtracer:color`&&n.texture!==e.texture?{texture:n.texture,source:n.key.split(`:`)[0]}:(this._denoiserInUse()&&this._issues.record(X.OUTPUT_SOURCE_FALLBACK,`renderToBuffer: 'display' was asked for, but no denoiser has published a picture — returned the raw accumulation`,{requested:`display`,read:`accumulation`}),null)}async _readDisplaySource(e,t,n){let r=this._displaySource(e);return r?{data:await this._readTexture(r.texture,t,n),source:r.source}:{data:await D_(this.renderer,e,t,n),source:`accumulation`}}_readbackPass(){return this._textureReadback??=new O_(this.renderer)}_readTexture(e,t,n){return this._readbackPass().read(e,t,n)}async setTextureColorSpace(e,n){if(!e?.isTexture)throw Error(`setTextureColorSpace wants a three.js texture`);let r=e.userData??={};r.__rayzeeOriginalColorSpace===void 0&&(r.__rayzeeOriginalColorSpace=e.colorSpace);let i=r.__rayzeeOriginalColorSpace;if(delete r.ocioColorSpace,delete r.__rayzeeColorSpaceChoice,n==null)e.colorSpace=i,delete r.__rayzeeOriginalColorSpace;else if(n===`srgb`||n===`linear`)e.colorSpace=n===`srgb`?t.SRGBColorSpace:t.LinearSRGBColorSpace,r.__rayzeeColorSpaceChoice=n;else{if(!this.color?.hasConfig)throw Error(`"${n}" needs a colour config loaded`);r.ocioColorSpace=n,e.colorSpace=t.SRGBColorSpace}e.needsUpdate=!0,this.stages.pathTracer?.sdfs&&await this.rebuildMaterials()}setColorManagement(e){this.color?.dispose(),this.color=new e({issues:this._issues}),ei(this.color),this.renderer&&this.color.attachRenderer(this.renderer)}async loadColorConfig(e={}){await this._leaveColorWorkingSpace();let t=$o(this.renderer?.toneMapping),n=await this.color.loadConfig(e);return this.color.workingSpaceAdopted&&await this.applyColorWorkingSpace(),(!(t?.source===`ocio`&&$o(this.renderer?.toneMapping)===t)||this.color.workingSpaceAdopted)&&this.reset(),n}async unloadColorConfig(){await this._leaveColorWorkingSpace(),this.color.unloadConfig(),this.reset()}async _leaveColorWorkingSpace(){this.color?.workingSpaceAdopted&&(this.color.setWorkingSpace(null),await this.applyColorWorkingSpace())}async applyColorWorkingSpace(){let e=this.environmentManager?.getEnvironmentTexture?.(),t=!1;if(e&&this.color?.hasConfig)try{t=this.color.convertTexturePixels(e)}catch(e){Ky.warn(`environment colour conversion failed: ${e.message}`)}this.stages.pathTracer?.sdfs&&(await this.rebuildMaterials(),this._uploadEmissivePayload(this._sdf?.rebuildEmissiveColors?.()??null)),t&&await this.environmentManager?.buildEnvironmentCDF?.(),e?._isPhysicalSky&&await this.environmentManager.generateProceduralSkyTexture(),this.environmentManager?.refreshSun?.(),this.reset()}async rebuildMaterials(e){await this.ensureSceneResident();let t=this.stages.pathTracer;await t?.rebuildMaterials(e||this.meshScene),t?.triangleStorageNode?.withoutUV&&this._sdf?.triangles&&Rn(e||this.meshScene)&&(this._sdf.textureCoordinates=!0,t.setTriangleData(this._sdf.triangles,this._sdf.triangleCount,{textureCoordinates:!0}),t.setupMaterial()),this.reset()}async _initRenderer(){I(e=>this.dispatchEvent(e)),(typeof navigator>`u`||!navigator.gpu)&&this._issues.fail(X.WEBGPU_UNAVAILABLE,"WebGPU is not available — outside a browser, install one as navigator.gpu (for Node, the `webgpu` package)");let e=null,n;try{e=await navigator.gpu.requestAdapter({powerPreference:`high-performance`})}catch(e){n=e}e||this._issues.fail(X.ADAPTER_UNAVAILABLE,`no WebGPU adapter${n?`: `+n.message:``}`,{},n),this.adapterInfo=Zy(e),this.adapterInfo.isSoftware&&(this._issues.warn(X.ADAPTER_SOFTWARE,`software GPU adapter "${this.adapterInfo.description||this.adapterInfo.vendor}" — renders are correct but orders of magnitude slower than hardware`,{...this.adapterInfo}),Ky.warn(`software GPU adapter — check app.adapterInfo.isSoftware. ${this.adapterInfo.description}`));let r=e.limits,a={maxColorAttachmentBytesPerSample:128};for(let e of[`maxBufferSize`,`maxStorageBufferBindingSize`,`maxSampledTexturesPerShaderStage`,`maxStorageTexturesPerShaderStage`,`maxTextureArrayLayers`,`maxTextureDimension2D`,`maxComputeInvocationsPerWorkgroup`,`maxComputeWorkgroupStorageSize`,`maxComputeWorkgroupSizeX`,`maxComputeWorkgroupSizeY`,`maxComputeWorkgroupSizeZ`]){let t=r[e];t!==void 0&&(a[e]=t)}a.maxStorageBuffersPerShaderStage=Math.min(r.maxStorageBuffersPerShaderStage,10);let o;try{o=await e.requestDevice({requiredFeatures:Yy.filter(t=>e.features.has(t)),requiredLimits:a})}catch(e){this._issues.fail(X.DEVICE_UNAVAILABLE,`WebGPU device request failed: ${e.message}`,{adapter:{...this.adapterInfo}},e)}this.renderer=new t.WebGPURenderer({canvas:this.canvas,alpha:!0,device:o});try{await Gy(this.renderer,this._headless)}catch(e){throw o.destroy(),e}this.renderer.backend?.isWebGPUBackend||(o.destroy(),this._issues.fail(X.WEBGPU_UNAVAILABLE,`three.js fell back to WebGL2, which cannot run the path tracer's compute kernels. Check GPU process flags and driver support.`)),this._gpuDevice=o,o.lost&&(this._deviceLostHolder={app:this},Jy(o,this._deviceLostHolder),o.onuncapturederror=e=>Ky.error(`WebGPU uncaptured error:`,e.error)),t.RectAreaLightNode.setLTC(i.RectAreaLightTexturesLib.init()),this.renderer.outputColorSpace=t.SRGBColorSpace,this.renderer.toneMapping=_s,this.renderer.toneMappingExposure=1,this.renderer.setPixelRatio(1),this.color.attachRenderer(this.renderer)}_initScenes(){this.scene=new r.Scene,this.meshScene=new r.Scene,this._sceneHelpers=new k}_initAssetPipeline(){this._sdf=new nl({issues:this._issues,...this._maxSceneBytes===void 0?{}:{maxSceneBytes:this._maxSceneBytes}}),this.assetLoader=new jy(this.meshScene,this.camera,null,{issues:this._issues,areaLightIntensityScale:()=>this.settings.get(`areaLightIntensityScale`)}),this.assetLoader.setRenderer(this.renderer),this.assetLoader.createFloorPlane()}_initPipeline(){this._createStages();let{clientWidth:e,clientHeight:t}=this.canvas;this.pipeline=new q_(this.renderer,e||1,t||1,{issues:this._issues}),this.pipeline.addStage(this.stages.pathTracer);for(let e of this._extraStages)this.pipeline.addStage(e);this.pipeline.addStage(this.stages.compositor);let n=this.canvas.clientWidth||1,r=this.canvas.clientHeight||1;this._displayWidth=n,this._displayHeight=r,this._renderWidth=n,this._renderHeight=r,this.pipeline.setSize(n,r)}async _initManagers(){this.lightManager=new zy(this.scene,this._sceneHelpers,this.stages.pathTracer,{onReset:()=>this.reset(),onLightRemoved:e=>this._lightRemoved(e)}),this.environmentManager=this.stages.pathTracer.environment,this.environmentManager.issues=this._issues,this.stages.pathTracer.issues=this._issues,this.environmentManager.callbacks.onLightingChanged=()=>this.pipeline.eventBus.emit(`pipeline:lightingChanged`),this.environmentManager.callbacks.onReset=()=>this.reset()}_wireEvents(){this.settings.bind(this._settingsBindings()),this.renderer.toneMappingExposure=this.settings.get(`exposure`)??1,this.onResize(),this.resizeHandler=()=>this.onResize(),this._autoResize&&this._addTrackedListener(window,`resize`,this.resizeHandler),this._onAssetLoaded=async e=>{if(!this._loadingInProgress&&!(this._applyingSceneMetadata&&e.texture)){if(e.model)this._clearAppendedModels(),await this.loadSceneData({pendingEnvironment:this._beginSceneMetadataEnvironment()})&&this.assetLoader?.commitPendingGraph(e.model);else if(e.texture){let e=this.meshScene.environment;e&&this.stages.pathTracer&&await this.stages.pathTracer.environment.setEnvironmentMap(e),le()}this.pauseRendering=!1,this.reset()}},this._addTrackedListener(this.assetLoader,`load`,this._onAssetLoaded),this.pipeline.eventBus.on(`pathtracer:compiling`,({compiling:e})=>this.dispatchEvent({type:N.SHADERS_COMPILING,compiling:e}))}_createStages(){this.stages.pathTracer=new N_(this.renderer,this.scene,this.camera,{hostMemoryGB:this._hostMemoryGB,sortMaterials:this.settings.get(`wavefrontSortMaterials`)}),this._extraStages=this._createExtraStages(),this.stages.compositor=new P_(this.renderer,{saturation:this.settings.get(`saturation`)??H.saturation,pathTracer:this.stages.pathTracer,displaySources:this._displaySources()})}_reconcileCompletion(){let e=this.stages.pathTracer;if(!e)return;let t=this.completion.isLimitReached(e,this.settings.get(`renderLimitMode`),this.settings.get(`renderTimeLimit`));t&&!e.isComplete?e.isComplete=!0:!t&&e.isComplete&&(e.isComplete=!1,this.completion.resumeFromPause(),this._completionReopened(),this.dispatchEvent({type:N.RENDER_RESET}),this.wake())}_forwardEvents(e,t){if(e)for(let n of t)this._addTrackedListener(e,n,e=>this.dispatchEvent(e))}_createCamera(){let e=new Iy(60,this.canvas.clientWidth/this.canvas.clientHeight||1,.01,1e3);return e.position.set(0,0,5),e}_createExtraStages(){return[]}_displaySources(){return[]}_settingsBindings(){return{stages:this.stages,resetCallback:()=>this.reset(),reconcileCompletion:()=>this._reconcileCompletion(),applyExposure:e=>{this.renderer.toneMappingExposure=e}}}_beginFrame(){}_beforeTrace(){}_holdTrace(){return!1}_afterTrace(){}_renderCompleted(){}_settling(){return!1}_finishImage(){return null}_renderHelperOverlay(){this.scene.updateMatrixWorld()}_beforeReset(){}_afterReset(){}_dropDisplay(){}_releaseSceneState(){}_modelReplaced(){}_modelAnnounced(){}_sceneRebuilt(){}_sceneBoundsChanged(){}_notePlacementsMoving(){}_lightRemoved(){}_renderSizeChanged(){}_completionReopened(){}async _finalDenoise(){return!1}_displayGain(){return null}_denoiserInUse(){return!1}_displayCanvas(){return null}_registerVRAM(){}_canvasResources(){return[]}_deterministicSnapshot(){return null}_setDeterministicExtras(){}_disposeExtensions(){}},$y=65504,eb=6e4,tb=Object.freeze([`none`,`nrd`,`oidn`]),nb=3,rb=.1,ib={maxAccumulatedFrameNum:30,maxFastAccumulatedFrameNum:6,maxStabilizedFrameNum:63,historyFixFrameNum:3,historyFixBasePixelStride:14,prepassBlurRadius:30,minBlurRadius:1,maxBlurRadius:30,lobeAngleFraction:.15,roughnessFraction:.15,planeDistanceSensitivity:.02,minHitDistanceWeight:.1,fastHistoryClampingSigmaScale:2,fireflySuppressorMinRelativeScale:2,enableAntiFirefly:!0,antilagLuminanceSigmaScale:2,antilagLuminanceSensitivity:3,disocclusionThreshold:.01,convergenceS:1,convergenceB:.2,convergenceP:.8,lobeVolumePercent:.1,handoverFrames:0},ab=[`maxAccumulatedFrameNum`,`maxFastAccumulatedFrameNum`,`maxStabilizedFrameNum`,`historyFixFrameNum`,`prepassBlurRadius`,`maxBlurRadius`,`enableAntiFirefly`],ob={low:{maxAccumulatedFrameNum:16,maxFastAccumulatedFrameNum:4,maxStabilizedFrameNum:16,historyFixFrameNum:2,prepassBlurRadius:0,maxBlurRadius:20,enableAntiFirefly:!1},medium:{},high:{maxAccumulatedFrameNum:45,maxFastAccumulatedFrameNum:8,historyFixFrameNum:4,prepassBlurRadius:40,maxBlurRadius:40}},sb={denoiserStrategy:`none`,enableOIDN:!1,oidnQuality:`fast`,continuousDenoise:!1,continuousDenoiseInterval:8,oidnTemporalHistory:!0,enableUpscaler:!1,upscalerScale:2,upscalerQuality:`fast`,upscalerHdr:!0,nrdQualityPreset:`medium`,nrdDebugMode:0};Dl(),xu(),pr();var cb=class extends j{constructor(e,i={}){super(`NormalDepth`,{...i,executionMode:A.ALWAYS}),this.renderer=e,this.pathTracer=i.pathTracer,this._dirty=!0,this.cameraWorldMatrix=(0,n.uniform)(new r.Matrix4,`mat4`),this.cameraProjectionMatrixInverse=(0,n.uniform)(new r.Matrix4,`mat4`),this.cameraRay=sf(),this.resolutionWidth=(0,n.uniform)(i.width||1),this.resolutionHeight=(0,n.uniform)(i.height||1);let a=i.width||1,o=i.height||1;this._outputStorageTex=new t.StorageTexture(Me,Me),this._outputStorageTex.type=r.HalfFloatType,this._outputStorageTex.format=r.RGBAFormat,this._outputStorageTex.minFilter=r.NearestFilter,this._outputStorageTex.magFilter=r.NearestFilter,this._shadingStorageTex=new t.StorageTexture(Me,Me),this._shadingStorageTex.type=r.HalfFloatType,this._shadingStorageTex.format=r.RGBAFormat,this._shadingStorageTex.minFilter=r.NearestFilter,this._shadingStorageTex.magFilter=r.NearestFilter,this._shadingRT=new t.RenderTarget(a,o,{type:r.HalfFloatType,format:r.RGBAFormat,minFilter:r.NearestFilter,magFilter:r.NearestFilter,depthBuffer:!1,stencilBuffer:!1}),this._leafStorageTex=null,this._leafRT=null,this._srcRegion=new r.Box2(new r.Vector2(0,0),new r.Vector2(0,0));let s={type:r.HalfFloatType,format:r.RGBAFormat,minFilter:r.NearestFilter,magFilter:r.NearestFilter,depthBuffer:!1,stencilBuffer:!1};this._rtA=new t.RenderTarget(a,o,s),this._rtB=new t.RenderTarget(a,o,s),this._currentIdx=0,this._hasHistory=!1,this._dispatchX=Math.ceil(a/8),this._dispatchY=Math.ceil(o/8),this._triStorageNode=null,this._bvhStorageNode=null,this._matStorageNode=null,this._lastTriAttr=null,this._lastBvhAttr=null,this._lastMatAttr=null,this._computeNode=null,this._computeBuilt=!1,this._linearBuckets=null}setupEventListeners(){this.on(`camera:moved`,()=>{this._dirty=!0}),this.on(`pipeline:reset`,()=>{this._dirty=!0})}_syncStorageBuffers(){let e=this.pathTracer;if(!e)return!1;let t=e.materialData?.materialStorageAttr,r=e.triangleGeoAttr&&e.triangleGeoAttr!==this._lastTriAttr,i=e.bvhStorageAttr&&e.bvhStorageAttr!==this._lastBvhAttr,a=t&&t!==this._lastMatAttr;if((r||i||a)&&(this._computeNode?.dispose?.(),this._computeNode=null,this._computeBuilt=!1,this._triStorageNode=null,this._bvhStorageNode=null,this._matStorageNode=null,this._dirty=!0,this._hasHistory=!1),!this._triStorageNode||!this._bvhStorageNode){let t=e.sceneStorageNodes?.();t&&(this._triStorageNode=t.triangles,this._bvhStorageNode=t.bvh)}return t&&!this._matStorageNode&&(this._matStorageNode=(0,n.storage)(t,`vec4`,t.count).toReadOnly()),this._linearBuckets&&_p(this._linearBuckets,e.materialData?.linearBuckets),this._lastTriAttr=e.triangleGeoAttr||this._lastTriAttr,this._lastBvhAttr=e.bvhStorageAttr||this._lastBvhAttr,this._lastMatAttr=t||this._lastMatAttr,!!(this._triStorageNode&&this._bvhStorageNode&&this._matStorageNode)}_buildCompute(){let e=this._triStorageNode,t=this._bvhStorageNode,r=this._matStorageNode;this._linearBuckets=gp(this.pathTracer?.materialData?.linearBuckets);let i={srgbBuckets:gp(null),linearBuckets:this._linearBuckets,shadowAlbedoMaps:null,goboMaps:null,iesProfiles:null,alphaShadows:null},a=this.cameraWorldMatrix,o=this.cameraProjectionMatrixInverse,s=this.resolutionWidth,c=this.resolutionHeight,l=this._outputStorageTex,u=this._shadingStorageTex,d=this._leafStorageTex;this._computeNode=ur((0,n.Fn)(([i,a])=>{let o=(0,n.int)(n.workgroupId.x).mul(8).add((0,n.int)(n.localId.x)),f=(0,n.int)(n.workgroupId.y).mul(8).add((0,n.int)(n.localId.y));(0,n.If)(o.lessThan((0,n.int)(s)).and(f.lessThan((0,n.int)(c))),()=>{let p=cf((0,n.vec2)((0,n.float)(o).add(.5).div(s),(0,n.float)(f).add(.5).div(c)),i,a,this.cameraRay),m=p.direction.toVar(),h=uf(m,this.cameraRay.clipStart,i,this.cameraRay.cameraProjection).toVar(),g=dl({origin:p.origin.add(m.mul(h)),direction:m}),_=gl.wrap(Lf(g,t,e)),v=_.normal.mul(.5).add(.5),y=(0,n.min)(_.dst.add(h),(0,n.float)(65504)),b=_.didHit.select((0,n.vec4)(v,y),(0,n.vec4)(0,0,0,(0,n.float)($y)));(0,n.textureStore)(l,(0,n.uvec2)((0,n.uint)(o),(0,n.uint)(f)),b).toWriteOnly(),d&&(0,n.textureStore)(d,(0,n.uvec2)((0,n.uint)(o),(0,n.uint)(f)),(0,n.uvec4)((0,n.uint)(_.instanceLeaf.add(1)),0,0,0)).toWriteOnly();let x=_.normal.toVar(),S=(0,n.float)(1).toVar();(0,n.If)(_.didHit,()=>{let i=fl.wrap(fu(_.materialIndex,r)).toVar(),a=Tl.wrap(Sp(_.uv,i)).toVar(),o=(0,n.vec4)(0).toVar();(0,n.If)(i.normalMapIndex.greaterThanEqual((0,n.int)(0)),()=>{o.assign(Ep(e,_.triangleIndex,_.normal,i.normalTransform,t,_.instanceLeaf))});let s=Op(_.normal,i,a,o).toVar();x.assign(kp(s,i,a)),S.assign(wp(i,a).y.clamp(.05,1));let c=(0,n.max)(i.emissive.x,(0,n.max)(i.emissive.y,i.emissive.z)).mul(i.emissiveIntensity).greaterThan(0);S.assign((0,n.select)(c,S.negate(),S))});let C=_.didHit.select((0,n.vec4)(x.mul(.5).add(.5),S),(0,n.vec4)(0,0,0,1));(0,n.textureStore)(u,(0,n.uvec2)((0,n.uint)(o),(0,n.uint)(f)),C).toWriteOnly()})})(a,o),i).compute([this._dispatchX,this._dispatchY,1],[8,8,1]),this._computeBuilt=!0}render(e){if(!this.enabled||!this._syncStorageBuffers())return;this._computeBuilt||this._buildCompute();let t=this.pathTracer;if(t&&(this.cameraWorldMatrix.value.copy(t.uniforms.get(`cameraWorldMatrix`).value),this.cameraProjectionMatrixInverse.value.copy(t.uniforms.get(`cameraProjectionMatrixInverse`).value),this.cameraRay.sync(t.uniforms)),!this._dirty&&this._hasHistory){let t=this._currentIdx===0?this._rtA:this._rtB;e.setTexture(`pathtracer:normalDepth`,t.texture),e.setTexture(`pathtracer:prevNormalDepth`,t.texture),e.setTexture(`pathtracer:shadingNormal`,this._shadingRT.texture),this._publishLeaf(e);return}let n=e.getTexture(`pathtracer:color`);if(n&&n.image){let e=n.image;e.width>0&&e.height>0&&(e.width!==this._rtA.width||e.height!==this._rtA.height)&&this.setSize(e.width,e.height)}this._hasHistory&&(this._currentIdx=1-this._currentIdx);let r=this._currentIdx===0?this._rtA:this._rtB,i=this._currentIdx===0?this._rtB:this._rtA;this.renderer.compute(this._computeNode),this._srcRegion.max.set(r.width,r.height),this.renderer.copyTextureToTexture(this._outputStorageTex,r.texture,this._srcRegion),this.renderer.copyTextureToTexture(this._shadingStorageTex,this._shadingRT.texture,this._srcRegion),this._leafRT&&this.renderer.copyTextureToTexture(this._leafStorageTex,this._leafRT.texture,this._srcRegion),this._hasHistory||=(this.renderer.copyTextureToTexture(this._outputStorageTex,i.texture,this._srcRegion),!0),e.setTexture(`pathtracer:normalDepth`,r.texture),e.setTexture(`pathtracer:prevNormalDepth`,i.texture),e.setTexture(`pathtracer:shadingNormal`,this._shadingRT.texture),this._publishLeaf(e),this._dirty=!1}releaseGPUMemory(){this._outputStorageTex?.dispose(),this._shadingStorageTex?.dispose(),this._leafStorageTex?.dispose(),this.reset(),this._hasHistory=!1}reset(){this._dirty=!0}setSize(e,t){this._rtA.setSize(e,t),this._rtA.texture.needsUpdate=!0,this._rtB.setSize(e,t),this._rtB.texture.needsUpdate=!0,this._shadingRT.setSize(e,t),this._shadingRT.texture.needsUpdate=!0,this._leafRT&&(this._leafRT.setSize(e,t),this._leafRT.texture.needsUpdate=!0),this._hasHistory=!1,this.resolutionWidth.value=e,this.resolutionHeight.value=t,this._dispatchX=Math.ceil(e/8),this._dispatchY=Math.ceil(t/8),this._computeNode&&(this._computeNode.dispatchSize=[this._dispatchX,this._dispatchY,1]),this._dirty=!0}reallocateReservedStorage(){this._computeNode?.dispose(),this._computeNode=null,this._outputStorageTex?.dispose(),this._shadingStorageTex?.dispose();let e=()=>{let e=new t.StorageTexture(Me,Me);return e.type=r.HalfFloatType,e.format=r.RGBAFormat,e.minFilter=r.NearestFilter,e.magFilter=r.NearestFilter,e};this._outputStorageTex=e(),this._shadingStorageTex=e(),this._leafStorageTex&&=(this._leafStorageTex.dispose(),this._makeLeafStorage()),this._computeBuilt=!1}setInstanceLeafOutput(e){e=!!e,e!==!!this._leafStorageTex&&(this._computeNode?.dispose(),this._computeNode=null,this._computeBuilt=!1,this._dirty=!0,e?(this._leafStorageTex=this._makeLeafStorage(),this._leafRT=new t.RenderTarget(this._rtA.width,this._rtA.height,{type:r.UnsignedIntType,format:r.RedIntegerFormat,minFilter:r.NearestFilter,magFilter:r.NearestFilter,depthBuffer:!1,stencilBuffer:!1})):(this._leafStorageTex.dispose(),this._leafRT.dispose(),this._leafStorageTex=null,this._leafRT=null))}_publishLeaf(e){this._leafRT?e.setTexture(`pathtracer:instanceLeaf`,this._leafRT.texture):e.getTexture(`pathtracer:instanceLeaf`)&&e.removeTexture(`pathtracer:instanceLeaf`)}_makeLeafStorage(){let e=new t.StorageTexture(Me,Me);return e.type=r.UnsignedIntType,e.format=r.RedIntegerFormat,e.minFilter=r.NearestFilter,e.magFilter=r.NearestFilter,e}dispose(){this._computeNode?.dispose(),this._outputStorageTex?.dispose(),this._shadingStorageTex?.dispose(),this._shadingRT?.dispose(),this._leafStorageTex?.dispose(),this._leafRT?.dispose(),this._rtA?.dispose(),this._rtB?.dispose()}},lb=class extends j{constructor(e,i,a={}){super(`MotionVector`,{...a,executionMode:A.ALWAYS}),this.renderer=e,this.camera=i,this.pathTracer=a.pathTracer||null;let o=a.width||1,s=a.height||1;this.prevViewProjectionMatrix=new r.Matrix4,this.currentViewProjectionMatrix=new r.Matrix4,this.matricesInitialized=!1,this.cameraWorldMatrix=(0,n.uniform)(new r.Matrix4,`mat4`),this.cameraProjectionMatrixInverse=(0,n.uniform)(new r.Matrix4,`mat4`),this.cameraRay=sf(),this.prevVP=(0,n.uniform)(new r.Matrix4,`mat4`),this.resolutionWidth=(0,n.uniform)(o),this.resolutionHeight=(0,n.uniform)(s),this._normalDepthTexNode=new t.TextureNode,this._screenSpaceStorageTex=new t.StorageTexture(Me,Me),this._screenSpaceStorageTex.type=r.HalfFloatType,this._screenSpaceStorageTex.format=r.RGBAFormat,this._screenSpaceStorageTex.minFilter=r.NearestFilter,this._screenSpaceStorageTex.magFilter=r.NearestFilter,this._srcRegion=new r.Box2(new r.Vector2(0,0),new r.Vector2(0,0)),this.screenSpaceTarget=new t.RenderTarget(o,s,{type:r.HalfFloatType,format:r.RGBAFormat,minFilter:r.NearestFilter,magFilter:r.NearestFilter,depthBuffer:!1,stencilBuffer:!1}),this._dispatchX=Math.ceil(o/16),this._dispatchY=Math.ceil(s/16),this._buildScreenSpaceCompute()}_buildScreenSpaceCompute(){let e=this._normalDepthTexNode,t=this.cameraWorldMatrix,r=this.cameraProjectionMatrixInverse,i=this.prevVP,a=this.resolutionWidth,o=this.resolutionHeight,s=this._screenSpaceStorageTex;this._screenSpaceComputeNode=(0,n.Fn)(([t,r])=>{let c=(0,n.int)(n.workgroupId.x).mul(16).add((0,n.int)(n.localId.x)),l=(0,n.int)(n.workgroupId.y).mul(16).add((0,n.int)(n.localId.y));(0,n.If)(c.lessThan((0,n.int)(a)).and(l.lessThan((0,n.int)(o))),()=>{let u=(0,n.textureLoad)(e,(0,n.ivec2)(c,l)).w,d=(0,n.vec2)((0,n.float)(c).add(.5).div(a),(0,n.float)(l).add(.5).div(o)),f=(0,n.vec4)(0,0,u,1).toVar();(0,n.If)(u.lessThan((0,n.float)(6e4)),()=>{let e=lf(d,u,t,r,this.cameraRay),a=i.mul((0,n.vec4)(e,1)),o=a.xy.div(a.w),s=(0,n.vec2)(o.x.mul(.5).add(.5),o.y.mul(-.5).add(.5)),c=d.sub(s),l=s.x.greaterThanEqual(0).and(s.x.lessThanEqual(1)).and(s.y.greaterThanEqual(0)).and(s.y.lessThanEqual(1));f.assign(l.select((0,n.vec4)(c,u,1),(0,n.vec4)((0,n.float)(1e3),(0,n.float)(1e3),u,0)))}),(0,n.textureStore)(s,(0,n.uvec2)((0,n.uint)(c),(0,n.uint)(l)),f).toWriteOnly()})})(t,r).compute([this._dispatchX,this._dispatchY,1],[16,16,1])}_updateCameraMatrices(){let e=this.pathTracer,t,n,r,i;if(e&&e.uniforms)this.cameraRay.sync(e.uniforms),t=e.uniforms.get(`cameraWorldMatrix`).value,n=e.uniforms.get(`cameraViewMatrix`).value,r=e.uniforms.get(`cameraProjectionMatrix`).value,i=e.uniforms.get(`cameraProjectionMatrixInverse`).value;else{let e=this.camera;if(!e)return;t=e.matrixWorld,n=e.matrixWorldInverse,r=e.projectionMatrix,i=e.projectionMatrixInverse}this.matricesInitialized?this.prevViewProjectionMatrix.copy(this.currentViewProjectionMatrix):(this.currentViewProjectionMatrix.multiplyMatrices(r,n),this.prevViewProjectionMatrix.copy(this.currentViewProjectionMatrix),this.matricesInitialized=!0),this.currentViewProjectionMatrix.multiplyMatrices(r,n),this.cameraWorldMatrix.value.copy(t),this.cameraProjectionMatrixInverse.value.copy(i),this.prevVP.value.copy(this.prevViewProjectionMatrix)}render(e){if(!this.enabled)return;let t=e.getTexture(`pathtracer:normalDepth`);if(!t)return;this._updateCameraMatrices();let n=t.image;n&&n.width>0&&n.height>0&&(n.width!==this.screenSpaceTarget.width||n.height!==this.screenSpaceTarget.height)&&this.setSize(n.width,n.height),this._normalDepthTexNode.value=t,this.renderer.compute(this._screenSpaceComputeNode),this._srcRegion.max.set(this.screenSpaceTarget.width,this.screenSpaceTarget.height),this.renderer.copyTextureToTexture(this._screenSpaceStorageTex,this.screenSpaceTarget.texture,this._srcRegion),e.setTexture(`motionVector:screenSpace`,this.screenSpaceTarget.texture)}releaseGPUMemory(){this._screenSpaceStorageTex?.dispose()}setSize(e,t){this.screenSpaceTarget.setSize(e,t),this.screenSpaceTarget.texture.needsUpdate=!0,this.resolutionWidth.value=e,this.resolutionHeight.value=t,this._dispatchX=Math.ceil(e/16),this._dispatchY=Math.ceil(t/16),this._screenSpaceComputeNode&&(this._screenSpaceComputeNode.dispatchSize=[this._dispatchX,this._dispatchY,1])}reallocateReservedStorage(){this._screenSpaceComputeNode?.dispose(),this._screenSpaceStorageTex?.dispose();let e=new t.StorageTexture(Me,Me);e.type=r.HalfFloatType,e.format=r.RGBAFormat,e.minFilter=r.NearestFilter,e.magFilter=r.NearestFilter,this._screenSpaceStorageTex=e,this._buildScreenSpaceCompute()}dispose(){this._screenSpaceComputeNode?.dispose(),this._screenSpaceStorageTex?.dispose(),this.screenSpaceTarget?.dispose(),this._normalDepthTexNode?.dispose()}};xu();var ub=1e-6,db=1.5/255,fb=.01,pb=3,mb=2,hb=2,gb=3,_b=2,vb=38,yb=.1,bb=4,xb=Math.cos(89*Math.PI/180),Sb=.5,Cb=.04,wb=.1*Cb,Tb=16,Eb=16,Db={pre:{radiusScale:1,fractionScale:2},blur:{radiusScale:1,fractionScale:1},post:{radiusScale:2,fractionScale:.5}},Ob=.25*Math.SQRT2,kb=[[-1,0,1],[0,1,1],[1,0,1],[0,-1,1],[-Ob,Ob,.5],[Ob,Ob,.5],[Ob,-Ob,.5],[-Ob,-Ob,.5]],Ab=(e,t,r)=>(0,n.smoothstep)(0,1,(0,n.float)(1).sub(e.mul(t).add(r).abs())),jb=(e,t,r)=>{let i=e.mul(t).add(r).abs().mul(-pb);return(0,n.float)(1).div(i.mul(i).sub(i).add(1))},Mb=e=>(0,n.mix)((0,n.float)(1.570796),(0,n.float)(1.395402),(0,n.saturate)(e)).mul((0,n.sqrt)((0,n.saturate)((0,n.float)(1).sub(e)))),Nb=(e,t)=>(0,n.float)(1).sub((0,n.exp2)(e.mul(e).mul(-200))).mul((0,n.pow)((0,n.saturate)(e),t)),Pb=(e,t)=>(0,n.saturate)(e).mul((0,n.sqrt)(t.div((0,n.float)(1).sub(t).add(ub)))),Fb=(e,t,r,i)=>{let a=(0,n.max)((0,n.atan)(Pb(r,i.mul((0,n.mix)((0,n.saturate)(t),(0,n.float)(1),e)))),(0,n.float)(db));return(0,n.float)(1).div(a)},Ib=(e,t)=>{let r=(0,n.float)(1).div((0,n.mix)((0,n.float)(fb),(0,n.float)(1),(0,n.saturate)(e.mul(t))));return(0,n.vec2)(r,e.mul(r).negate())},Lb=(e,t,r)=>{let i=(0,n.float)(1).div((0,n.mix)((0,n.float)(r),(0,n.float)(1),(0,n.mix)(e.mul(e),e,(0,n.saturate)(t))));return(0,n.vec2)(i,e.mul(i).negate())},Rb=(e,t)=>{let r=(0,n.float)(1).div(t);return(0,n.vec2)(r,e.mul(r).negate())},zb=(e,t,r,i)=>{let a=(0,n.float)(1).div(e.mul(t));return(0,n.vec2)(a,(0,n.dot)(i,r).mul(a).negate())},Bb=e=>(0,n.vec2)(1).sub((0,n.vec2)(1).sub((0,n.fract)(e.mul(.5)).mul(2)).abs()).min(.99999),Vb=e=>(0,n.vec3)((0,n.dot)(e,(0,n.vec3)(.25,.5,.25)),(0,n.dot)(e,(0,n.vec3)(.5,0,-.5)),(0,n.dot)(e,(0,n.vec3)(-.25,.5,-.25))),Hb=e=>{let t=e.x.sub(e.z);return(0,n.max)((0,n.vec3)(t.add(e.y),e.x.add(e.z),t.sub(e.y)),(0,n.vec3)(0))},Ub=(e,t)=>t.add(ub).div(e.add(ub)),Wb=(e,t)=>(0,n.vec4)(e.xyz.mul(Ub(e.x,t)),e.w),Gb=e=>(0,n.vec4)(Vb(Hb(e.xyz)),(0,n.saturate)(e.w)),Kb=(e,t)=>(0,n.sqrt)(t.sub(e.mul(e)).abs()),qb=(e,t)=>(0,n.vec2)(e.x.mul(t.x).add(e.y.mul(t.y)),e.z.mul(t.x).add(e.w.mul(t.y))),Jb=e=>e.mul(1-Cb).add(Cb),Yb=e=>(0,n.max)(e.x,(0,n.max)(e.y,e.z)).lessThan(wb),Xb=e=>e.z.greaterThan(Tb-.5),Zb=e=>e.lessThan(0),Qb=e=>e.abs().clamp(.05,1),$b=(e,t)=>(0,n.select)(e.equal(0),(0,n.vec4)(0),t);function ex(e){let t=Math.imul(e|0,2654435761)>>>0;return t^=t>>>15,t=Math.imul(t,2246822507)>>>0,t^=t>>>13,t=Math.imul(t,3266489909)>>>0,t^=t>>>16,t/4294967296}var tx=class extends j{constructor(e,i={}){super(`NRD`,{...i,executionMode:A.PER_CYCLE}),this.renderer=e,this.pathTracer=i.pathTracer||null,this.settings={...ib,...i.settings||{}},this._releaseHitDistance=this.pathTracer?.requestOutput?.(`hitDistance`,{encode:(e,t)=>e.div((0,n.max)(t.mul(.1).add(3),(0,n.float)(1e-4))).clamp(0,1)})??null;let a=i.width||1,o=i.height||1;this.resW=(0,n.uniform)(a),this.resH=(0,n.uniform)(o),this.minRectDimMulUnproject=(0,n.uniform)(1),this.inputFrames=(0,n.uniform)(0),this.resetU=(0,n.uniform)(0),this.debugMode=(0,n.uniform)(0,`int`),this.rotPre=(0,n.uniform)(new r.Vector4(1,0,0,1),`vec4`),this.rotBlur=(0,n.uniform)(new r.Vector4(1,0,0,1),`vec4`),this.rotPost=(0,n.uniform)(new r.Vector4(1,0,0,1),`vec4`),this.camWorld=(0,n.uniform)(new r.Matrix4,`mat4`),this.camProjInv=(0,n.uniform)(new r.Matrix4,`mat4`),this.camView=(0,n.uniform)(new r.Matrix4,`mat4`),this.prevCamView=(0,n.uniform)(new r.Matrix4,`mat4`),this.camPos=(0,n.uniform)(new r.Vector3,`vec3`),this.prevCamPos=(0,n.uniform)(new r.Vector3,`vec3`),this.viewVector=(0,n.uniform)(new r.Vector3,`vec3`),this.prevViewVector=(0,n.uniform)(new r.Vector3,`vec3`),this.cameraRay=sf(),this.u={};for(let e of[`maxAccum`,`maxFast`,`stabilizationStrength`,`historyFixFrameNum`,`historyFixStride`,`prepassBlurRadius`,`minBlurRadius`,`maxBlurRadius`,`lobeAngleFraction`,`roughnessFraction`,`planeDistSensitivity`,`minHitDistanceWeight`,`fastClampSigmaScale`,`fireflyMinRelativeScale`,`antiFirefly`,`disocclusionThreshold`,`lobeVolumePercent`,`handoverFrames`])this.u[e]=(0,n.uniform)(0);this.u.antilag=(0,n.uniform)(new r.Vector2,`vec2`),this.u.convergence=(0,n.uniform)(new r.Vector3,`vec3`),this._syncUniforms(),this._colorTexNode=new t.TextureNode,this._albedoTexNode=new t.TextureNode,this._ndTexNode=new t.TextureNode,this._snTexNode=new t.TextureNode,this._motionTexNode=new t.TextureNode,this._placeholders=new Map;let s=()=>{let e=new r.DataTexture(new Float32Array(4),1,1,r.RGBAFormat,r.FloatType);e.needsUpdate=!0;let n=new t.TextureNode(e);return this._placeholders.set(n,e),n};this._nTmpA=s(),this._nTmpB=s(),this._nHist=s(),this._nFast=s(),this._nInternal=s(),this._nGeom=s(),this._nData=s(),this._nStabRead=s(),this._allocStorage(),this._srcRegion=new r.Box2(new r.Vector2(0,0),new r.Vector2(0,0)),this.outputTarget=new t.RenderTarget(a,o,{type:r.HalfFloatType,format:r.RGBAFormat,minFilter:r.LinearFilter,magFilter:r.LinearFilter,depthBuffer:!1,stencilBuffer:!1}),this._compiled=!1,this._needsReset=!0,this._stabPing=0,this._camInitialized=!1,this._dispatchX=Math.ceil(a/Eb),this._dispatchY=Math.ceil(o/Eb),this._buildKernels()}_allocStorage(){let e=()=>Fe(r.HalfFloatType);this._tmpA=e(),this._tmpB=e(),this._hist=e(),this._fastHist=e(),this._internal=e(),this._geomPrev=e(),this._stabA=e(),this._stabB=e(),this._dataT=e()}_disposeStorage(){for(let e of[this._tmpA,this._tmpB,this._hist,this._fastHist,this._internal,this._geomPrev,this._stabA,this._stabB,this._dataT])e?.dispose()}_disposeKernels(){for(let e of this._kernels??[])e?.dispose()}updateParameters(e){if(e){for(let t of Object.keys(e))t===`debugMode`?this.debugMode.value=e.debugMode|0:t in ib&&(this.settings[t]=e[t]);this._syncUniforms()}}_syncUniforms(){let e=this.settings,t=this.u,n=Math.min(e.maxAccumulatedFrameNum,63),r=Math.min(e.maxStabilizedFrameNum,n),i=Math.max(e.maxBlurRadius,e.minBlurRadius);t.maxAccum.value=n,t.maxFast.value=e.maxFastAccumulatedFrameNum,t.stabilizationStrength.value=r/(1+r),t.historyFixFrameNum.value=e.historyFixFrameNum,t.historyFixStride.value=e.historyFixBasePixelStride,t.prepassBlurRadius.value=e.prepassBlurRadius,t.minBlurRadius.value=e.minBlurRadius,t.maxBlurRadius.value=i,t.lobeAngleFraction.value=e.lobeAngleFraction*e.lobeAngleFraction,t.roughnessFraction.value=e.roughnessFraction,t.planeDistSensitivity.value=e.planeDistanceSensitivity,t.minHitDistanceWeight.value=e.minHitDistanceWeight;let a=Math.min(1,Math.max(0,i/2));t.fastClampSigmaScale.value=3+(e.fastHistoryClampingSigmaScale-3)*a,t.fireflyMinRelativeScale.value=e.fireflySuppressorMinRelativeScale,t.antiFirefly.value=+!!e.enableAntiFirefly,t.antilag.value.set(e.antilagLuminanceSigmaScale,e.antilagLuminanceSensitivity),t.disocclusionThreshold.value=e.disocclusionThreshold,t.convergence.value.set(e.convergenceS,e.convergenceB,e.convergenceP),t.lobeVolumePercent.value=e.lobeVolumePercent,t.handoverFrames.value=e.handoverFrames>0?e.handoverFrames:2*n}_worldPosAt(e,t,n,r){return lf(e,t,n,r,this.cameraRay)}_viewVector(e,t,r){return(0,n.select)(of(this.cameraRay.cameraProjection),r,(0,n.normalize)(t.sub(e)))}_frustumSize(e){return this.minRectDimMulUnproject.mul((0,n.select)(of(this.cameraRay.cameraProjection),(0,n.float)(1),e))}_pixelUv(e,t){return(0,n.vec2)((0,n.float)(e).add(.5).div(this.resW),(0,n.float)(t).add(.5).div(this.resH))}_clampCoord(e,t){return(0,n.ivec2)(e.clamp((0,n.int)(0),(0,n.int)(this.resW).sub(1)),t.clamp((0,n.int)(0),(0,n.int)(this.resH).sub(1)))}_uvToCoord(e){return this._clampCoord((0,n.int)(e.x.mul(this.resW)),(0,n.int)(e.y.mul(this.resH)))}_advancedNonLinear(e){let t=this.u.convergence,r=(0,n.saturate)(e.div((0,n.float)(1).add(this.u.maxAccum.mul(t.z)))),i=t.x.mul((0,n.mix)(t.y,(0,n.float)(1),r));return(0,n.float)(1).div((0,n.float)(1).add(i.mul(e)))}_handover(e){return(0,n.saturate)(e.div((0,n.max)(this.u.handoverFrames,1)))}_excluded(e,t,n,r){return e.greaterThanEqual(eb).or(Zb(t)).or(n.and(r.not()))}_bilinear(e){let t=e.mul((0,n.vec2)(this.resW,this.resH)).sub(.5),r=(0,n.floor)(t),i=(0,n.saturate)(t.sub(r)),a=(0,n.int)(r.x),o=(0,n.int)(r.y),s=(e,t)=>(0,n.select)(e.greaterThanEqual((0,n.int)(0)).and(t.greaterThanEqual((0,n.int)(0))).and(e.lessThan((0,n.int)(this.resW))).and(t.lessThan((0,n.int)(this.resH))),(0,n.float)(1),(0,n.float)(0));return{f:i,taps:[this._clampCoord(a,o),this._clampCoord(a.add(1),o),this._clampCoord(a,o.add(1)),this._clampCoord(a.add(1),o.add(1))],inScreen:[s(a,o),s(a.add(1),o),s(a,o.add(1)),s(a.add(1),o.add(1))],customWeights:e=>[e[0].mul((0,n.float)(1).sub(i.x)).mul((0,n.float)(1).sub(i.y)),e[1].mul(i.x).mul((0,n.float)(1).sub(i.y)),e[2].mul((0,n.float)(1).sub(i.x)).mul(i.y),e[3].mul(i.x).mul(i.y)],filter:e=>(0,n.mix)((0,n.mix)(e[0],e[1],i.x),(0,n.mix)(e[2],e[3],i.x),i.y)}}_applyCustomWeights(e,t,r){let i=e[0].mul(t[0]).add(e[1].mul(t[1])).add(e[2].mul(t[2])).add(e[3].mul(t[3])),a=t[0].add(t[1]).add(t[2]).add(t[3]);return(0,n.select)(a.lessThan(1e-4),r,i.div((0,n.max)(a,1e-4)))}_sampleHistory(e,t,r,i,a){let o=(0,n.vec4)(0).toVar();return(0,n.If)(a,()=>{let r=(0,n.saturate)(t).mul((0,n.vec2)(this.resW,this.resH)),i=(0,n.floor)(r.sub(.5)).add(.5),a=(0,n.saturate)(r.sub(i)),s=Sb,c=a.mul(a.mul(a.mul(-s).add(2*s)).sub(s)),l=a.mul(a.mul(a.mul(2-s).sub(3-s))).add(1),u=a.mul(a.mul(a.mul(-(2-s)).add(3-2*s)).add(s)),d=a.mul(a.mul(a.mul(s).sub(s))),f=[c.x,l.x,u.x,d.x],p=[c.y,l.y,u.y,d.y],m=(0,n.int)(i.x).sub(1),h=(0,n.int)(i.y).sub(1),g=(0,n.vec4)(0).toVar(),_=(0,n.float)(0).toVar();for(let t=0;t<4;t++)for(let n=0;n<4;n++){if((n===0||n===3)&&(t===0||t===3))continue;let r=f[n].mul(p[t]);g.addAssign(e(this._clampCoord(m.add(n),h.add(t))).mul(r)),_.addAssign(r)}o.assign((0,n.select)(_.lessThan(1e-4),(0,n.vec4)(0),g.div((0,n.max)(_,1e-4))))}).Else(()=>{o.assign(this._applyCustomWeights(r.taps.map(t=>e(t)),i,(0,n.vec4)(0)))}),o}_buildKernels(){this._kPre=this._buildSpatial(`pre`),this._kTa=this._buildTemporalAccumulation(),this._kHf=this._buildHistoryFix(),this._kBlur=this._buildSpatial(`blur`),this._kPost=this._buildSpatial(`post`),this._kTsA=this._buildTemporalStabilization(this._stabA),this._kTsB=this._buildTemporalStabilization(this._stabB),this._kernels=[this._kPre,this._kTa,this._kHf,this._kBlur,this._kPost,this._kTsA,this._kTsB]}_dispatchOf(e){return e(this.camWorld,this.camProjInv).compute([this._dispatchX,this._dispatchY,1],[Eb,Eb,1])}_buildSpatial(e){let t=e===`pre`,{radiusScale:r,fractionScale:i}=Db[e],a=this.u,o=this._colorTexNode,s=this._albedoTexNode,c=this._ndTexNode,l=this._snTexNode,u=this._nData,d=e===`blur`?this._nTmpA:this._nTmpB,f=e===`blur`?this._tmpB:t?this._tmpA:this._hist,p=this._geomPrev,m=t?this.rotPre:e===`blur`?this.rotBlur:this.rotPost,h=t?a.prepassBlurRadius:a.maxBlurRadius,g=this.camView,_=this.camPos,v=this.resW,y=this.resH,b=this.inputFrames,x=t?(e,t)=>(0,n.vec4)(Vb(Ul((0,n.textureLoad)(o,e).xyz.div(Jb(t.xyz)))),Hl(t.w,Vl).min(1)):e=>(0,n.textureLoad)(d,e),S=(0,n.Fn)(([o,d])=>{let S=(0,n.int)(n.workgroupId.x).mul(Eb).add((0,n.int)(n.localId.x)),C=(0,n.int)(n.workgroupId.y).mul(Eb).add((0,n.int)(n.localId.y));(0,n.If)(S.lessThan((0,n.int)(v)).and(C.lessThan((0,n.int)(y))),()=>{let w=(0,n.ivec2)(S,C),T=(0,n.uvec2)((0,n.uint)(S),(0,n.uint)(C)),E=(0,n.textureLoad)(c,w).w.toVar(),D=E.greaterThanEqual(eb),O=(0,n.textureLoad)(l,w).toVar(),k=(0,n.normalize)(O.xyz.mul(2).sub(1)).toVar(),A=Qb(O.w).toVar(),j=(0,n.float)(eb).toVar(),M=t?(0,n.textureLoad)(s,w):null,N=(t?Yb(M):Xb((0,n.textureLoad)(u,w))).toVar(),P=x(w,M).toVar();(0,n.If)(D.not(),()=>{let e=this._pixelUv(S,C),f=this._worldPosAt(e,E,o,d).toVar();j.assign(g.mul((0,n.vec4)(f,1)).z.abs()),(0,n.If)(h.greaterThan(0).and(Zb(O.w).not()),()=>{let p=(0,n.dot)(k,this._viewVector(f,_,this.viewVector)).abs().toVar(),S=this._frustumSize(j).toVar(),C=b.add(1),T=t?(0,n.max)(b,(0,n.float)(10)):(0,n.textureLoad)(u,w).y.add(b),E=(t?(0,n.float)(1).div(T.add(1)):this._advancedNonLinear(T)).toVar(),D=Nb(A,.5).toVar(),O=j.mul(rb).add(3),M=P.w.toVar(),F=(0,n.saturate)(M.mul(O).div(S)),I=(0,n.float)(1).sub(this._handover(C)),L=(t?F.div(C):F.mul(E)).mul(I),ee=a.minBlurRadius.mul((0,n.saturate)((0,n.float)(2).sub(T.div((0,n.max)(a.maxAccum,1))))),te=(0,n.max)((0,n.saturate)((0,n.sqrt)((0,n.saturate)(L)).mul(r)).mul(h).mul(D),ee.mul(D)).toVar(),R=zb(a.planeDistSensitivity,S,f,k).toVar(),ne=Fb(E,a.lobeAngleFraction,A,a.lobeVolumePercent).div(i).toVar(),re=Ib(A,a.roughnessFraction.mul(i)).toVar(),ie=Rb(M,E).toVar(),ae=a.minHitDistanceWeight.mul(i).mul(D);t||(ae=ae.mul(E)),ae=ae.toVar();let oe=(0,n.vec2)(1);if(!t){let e=g.mul((0,n.vec4)(k,0)).xy;oe=(0,n.mix)((0,n.vec2)(1).sub(e.abs()),(0,n.vec2)(1),p),oe=oe.div((0,n.max)(oe.x,oe.y))}let se=oe.mul((0,n.vec2)((0,n.float)(1).div(v),(0,n.float)(1).div(y))).mul(te).toVar(),ce=(0,n.float)(1).toVar();for(let r=0;r<kb.length;r++){let i=kb[r],a=e.add(qb(m,(0,n.vec2)(i[0],i[1])).mul(se)),f=Bb(a),p=(0,n.select)(f.x.notEqual(a.x).or(f.y.notEqual(a.y)),(0,n.float)(1),(0,n.float)(Math.exp(-.66*i[2]*i[2]))).toVar(),h=this._uvToCoord(f),g=(0,n.textureLoad)(c,h).w,_=this._worldPosAt(f,g,o,d),v=(0,n.textureLoad)(l,h),y=Mb((0,n.dot)(k,(0,n.normalize)(v.xyz.mul(2).sub(1))));p.mulAssign(Ab(y,ne,(0,n.float)(0))),p.mulAssign(Ab(Qb(v.w),re.x,re.y)),p.mulAssign(Ab((0,n.dot)(k,_),R.x,R.y));let b=t?(0,n.textureLoad)(s,h):null,S=t?Yb(b):Xb((0,n.textureLoad)(u,h));p.assign((0,n.select)(this._excluded(g,v.w,S,N),(0,n.float)(0),p));let C=$b(p,x(h,b));p.mulAssign(ae.add(jb(C.w,ie.x,ie.y))),ce.addAssign(p),P.addAssign(C.mul(p))}P.divAssign((0,n.max)(ce,1e-6)),t||P.assign((0,n.vec4)(P.xyz,M))})}),(0,n.textureStore)(f,T,P).toWriteOnly(),e===`post`&&(0,n.textureStore)(p,T,(0,n.vec4)(k,j)).toWriteOnly()})});return this._dispatchOf(S)}_buildTemporalAccumulation(){let e=this.u,t=this._ndTexNode,r=this._snTexNode,i=this._motionTexNode,a=this._nTmpA,o=this._nHist,s=this._nFast,c=this._nInternal,l=this._nGeom,u=this._tmpB,d=this._dataT,f=this._albedoTexNode,p=this.camView,m=this.prevCamView,h=this.camPos,g=this.prevCamPos,_=this.resW,v=this.resH,y=this.inputFrames,b=this.resetU,x=(0,n.Fn)(([x,S])=>{let C=(0,n.int)(n.workgroupId.x).mul(Eb).add((0,n.int)(n.localId.x)),w=(0,n.int)(n.workgroupId.y).mul(Eb).add((0,n.int)(n.localId.y));(0,n.If)(C.lessThan((0,n.int)(_)).and(w.lessThan((0,n.int)(v))),()=>{let _=(0,n.ivec2)(C,w),v=(0,n.uvec2)((0,n.uint)(C),(0,n.uint)(w)),T=(0,n.textureLoad)(t,_).w,E=(0,n.textureLoad)(a,_).toVar();(0,n.If)(T.greaterThanEqual(eb),()=>{(0,n.textureStore)(u,v,E).toWriteOnly(),(0,n.textureStore)(d,v,(0,n.vec4)(0)).toWriteOnly(),(0,n.Return)()});let D=e.maxAccum.mul((0,n.float)(1).sub(b)).toVar(),O=e.maxFast.mul((0,n.float)(1).sub(b)).toVar(),k=(0,n.textureLoad)(r,_),A=(0,n.normalize)(k.xyz.mul(2).sub(1)).toVar(),j=Qb(k.w).toVar(),M=this._pixelUv(C,w),N=this._worldPosAt(M,T,x,S).toVar(),P=p.mul((0,n.vec4)(N,1)).z.abs().toVar(),F=(0,n.dot)(A,this._viewVector(N,h,this.viewVector)).abs().toVar(),I=this._frustumSize(P).toVar(),L=(0,n.vec3)(0).toVar();L.addAssign(A.mul(.25));for(let e=-1;e<=0;e++)for(let i=-1;i<=0;i++){if(i===0&&e===0)continue;let a=this._clampCoord(C.add(i),w.add(e)),o=(0,n.normalize)((0,n.textureLoad)(r,a).xyz.mul(2).sub(1)),s=(0,n.textureLoad)(t,a).w.lessThan(eb);L.addAssign((0,n.select)(s,o,A).mul(.25))}let ee=(0,n.textureLoad)(i,_),te=M.sub(ee.xy).toVar(),R=m.mul((0,n.vec4)(N,1)).z.abs().toVar(),ne=this._bilinear(te),re=I.mul((0,n.saturate)(e.disocclusionThreshold.div((0,n.max)(F,.05)))).sub(ub).toVar(),ie=(0,n.float)(1).sub(b),ae=[],oe=[];for(let e=0;e<4;e++){let t=(0,n.textureLoad)(l,ne.taps[e]),r=(0,n.select)((0,n.dot)(t.xyz,L).greaterThan(xb),(0,n.float)(1),(0,n.float)(0)),i=(0,n.select)(t.w.sub(R).abs().lessThanEqual(re),(0,n.float)(1),(0,n.float)(0)),a=(0,n.select)(t.w.lessThan(eb),(0,n.float)(1),(0,n.float)(0));ae.push(r.mul(i).mul(a).mul(ne.inScreen[e]).mul(ie).toVar()),oe.push((0,n.textureLoad)(c,ne.taps[e]).x)}let se=ne.customWeights(ae).map(e=>e.toVar()),ce=ae[0].add(ae[1]).add(ae[2]).add(ae[3]).greaterThan(3.5).toVar(),le=ae[0].add(ae[1].mul(2)).add(ae[2].mul(4)).add(ae[3].mul(8)),z=this._applyCustomWeights(oe,se,(0,n.float)(0)).toVar(),ue=(0,n.dot)(A,this._viewVector(N,g,this.prevViewVector)).abs().add(.001).div(F.add(.001)).toVar();ue.assign((0,n.mix)((0,n.float)(.1),(0,n.float)(1),(0,n.saturate)(ue.mul(ue))));let de=(0,n.sqrt)((0,n.saturate)(ne.filter(ae))).mul(ue).toVar();z.assign(z.mul((0,n.mix)(de,(0,n.float)(1),(0,n.float)(1).div(z.add(1))))),z.assign((0,n.min)(z,D));let fe=Gb(this._sampleHistory(e=>(0,n.textureLoad)(o,e),te,ne,se,ce)).toVar(),pe=(0,n.max)(this._applyCustomWeights(ne.taps.map(e=>(0,n.textureLoad)(s,e).x),se,(0,n.float)(0)),0).toVar(),me=y.add(1),he=this._handover(me).toVar(),ge=z.mul((0,n.float)(1).sub(he)),_e=me.div(me.add(ge)).toVar(),ve=(0,n.float)(1).div((0,n.float)(1).add(Nb(j,.25).mul(.5).mul(D))),ye=(0,n.vec4)((0,n.mix)(fe.xyz,E.xyz,_e),(0,n.mix)(fe.w,E.w,(0,n.max)(_e,ve))).toVar(),be=e.fireflyMinRelativeScale.add((0,n.float)(vb).div(z.add(1))).toVar(),xe=z.mul(e.maxBlurRadius).mul(yb).toVar();xe.assign(xe.div(xe.add(1)).mul((0,n.float)(1).sub(he)));let Se=(0,n.mix)(ye.x,(0,n.min)(ye.x,fe.x.mul(be)),xe);ye.assign(Wb(ye,Se));let Ce=(0,n.float)(1.2).add((0,n.float)(1).div(z.add(1)));ye.assign((0,n.vec4)(ye.xyz,(0,n.mix)(ye.w,(0,n.min)(ye.w,fe.w.mul(Ce)),xe))),(0,n.textureStore)(u,v,ye).toWriteOnly();let we=(0,n.min)(z,O).mul((0,n.float)(1).sub(he)),B=me.div(me.add(we)),Te=(0,n.mix)(pe,E.x,B).toVar(),Ee=(0,n.min)(Te,fe.x.mul(be).mul(bb));Te.assign((0,n.mix)(Te,Ee,xe));let De=(0,n.select)(Yb((0,n.textureLoad)(f,_)),(0,n.float)(Tb),(0,n.float)(0));(0,n.textureStore)(d,v,(0,n.vec4)(Te,z,le.add(De),(0,n.select)(ce,(0,n.float)(1),(0,n.float)(0)))).toWriteOnly()})});return this._dispatchOf(x)}_buildHistoryFix(){let e=this.u,t=this._ndTexNode,r=this._snTexNode,i=this._nTmpB,a=this._nData,o=this._tmpA,s=this._fastHist,c=this.camView,l=this.resW,u=this.resH,d=this.inputFrames,f=(0,n.Fn)(([f,p])=>{let m=(0,n.int)(n.workgroupId.x).mul(Eb).add((0,n.int)(n.localId.x)),h=(0,n.int)(n.workgroupId.y).mul(Eb).add((0,n.int)(n.localId.y));(0,n.If)(m.lessThan((0,n.int)(l)).and(h.lessThan((0,n.int)(u))),()=>{let g=(0,n.ivec2)(m,h),_=(0,n.uvec2)((0,n.uint)(m),(0,n.uint)(h)),v=(0,n.textureLoad)(t,g).w;(0,n.If)(v.greaterThanEqual(eb),()=>{let e=(0,n.textureLoad)(i,g);(0,n.textureStore)(o,_,e).toWriteOnly(),(0,n.textureStore)(s,_,(0,n.vec4)(e.x,0,0,0)).toWriteOnly(),(0,n.Return)()});let y=(0,n.textureLoad)(a,g).toVar(),b=y.y.toVar(),x=b.add(d),S=this._handover(d.add(1)).toVar(),C=(0,n.textureLoad)(r,g),w=(0,n.normalize)(C.xyz.mul(2).sub(1)).toVar(),T=Qb(C.w).toVar(),E=this._pixelUv(m,h),D=this._worldPosAt(E,v,f,p).toVar(),O=c.mul((0,n.vec4)(D,1)).z.abs(),k=this._frustumSize(O).toVar(),A=(0,n.textureLoad)(i,g).toVar(),j=(0,n.float)(1).div(x.add(1)).toVar(),M=O.mul(rb).add(3),N=(0,n.saturate)(A.w.mul(M).div(k)),P=A.w.toVar(),F=(0,n.round)((0,n.select)(x.lessThan(e.historyFixFrameNum),(0,n.float)(1),(0,n.float)(0)).mul(.5).mul(2/mb).mul(e.historyFixStride).mul((0,n.mix)((0,n.float)(.25).add((0,n.sqrt)(N).mul(.75)),(0,n.float)(1),j))).toVar(),I=Zb(C.w).toVar();(0,n.If)(F.notEqual(0).and(I.not()),()=>{let o=Fb(j,e.lobeAngleFraction,T,e.lobeVolumePercent).toVar(),s=zb(e.planeDistSensitivity,k,D,w).toVar(),c=Rb(P,j).toVar(),d=Lb(T.mul(T),(0,n.sqrt)(e.roughnessFraction),fb).toVar(),m=Xb(y).toVar(),h=(0,n.float)(1).add(b).toVar();A.mulAssign(h);for(let e=-mb;e<=mb;e++)for(let g=-mb;g<=mb;g++){if(g===0&&e===0||Math.abs(g)+Math.abs(e)===mb*2)continue;let _=Bb(E.add((0,n.vec2)(g,e).mul(F).mul((0,n.vec2)((0,n.float)(1).div(l),(0,n.float)(1).div(u))))),v=this._uvToCoord(_),y=(0,n.textureLoad)(t,v).w,b=this._worldPosAt(_,y,f,p),x=(0,n.textureLoad)(r,v),S=jb(Mb((0,n.dot)((0,n.normalize)(x.xyz.mul(2).sub(1)),w)),o,(0,n.float)(0)).toVar(),C=Qb(x.w);S.mulAssign(jb(C.mul(C),d.x,d.y));let T=(0,n.textureLoad)(a,v);S.mulAssign((0,n.float)(1).add(T.y)),S.mulAssign(Ab((0,n.dot)(w,b),s.x,s.y)),S.assign((0,n.select)(this._excluded(y,x.w,Xb(T),m),(0,n.float)(0),S));let D=$b(S,(0,n.textureLoad)(i,v));S.mulAssign(jb(D.w,c.x,c.y)),h.addAssign(S),A.addAssign(D.mul(S))}A.divAssign((0,n.max)(h,1e-6))});let L=A.x.toVar(),ee=(0,n.saturate)(b.div((0,n.max)(e.historyFixFrameNum,ub))),te=(0,n.mix)(L,y.x,ee).toVar();(0,n.textureStore)(s,_,(0,n.vec4)(te,0,0,0)).toWriteOnly();let R=te.toVar(),ne=te.mul(te).toVar(),re=(0,n.float)(0).toVar(),ie=(0,n.float)(0).toVar(),ae=(e,r,i)=>{let o=this._clampCoord(m.add(e),h.add(r)),s=(0,n.textureLoad)(t,o).w,c=(0,n.select)(s.greaterThanEqual(eb),te,(0,n.textureLoad)(a,o).x);Math.abs(e)<=hb&&Math.abs(r)<=hb&&(R.addAssign(c),ne.addAssign(c.mul(c))),i&&(re.addAssign(c),ie.addAssign(c.mul(c)))},oe=e.antiFirefly.greaterThan(.5);for(let e=-hb;e<=hb;e++)for(let t=-hb;t<=hb;t++)t===0&&e===0||ae(t,e,Math.abs(t)>1||Math.abs(e)>1);(0,n.If)(oe,()=>{for(let e=-gb;e<=gb;e++)for(let t=-gb;t<=gb;t++)Math.abs(t)<=hb&&Math.abs(e)<=hb||ae(t,e,!0)}),(0,n.If)(oe,()=>{let e=1/((gb*2+1)**2-9),t=re.mul(e),r=Kb(t,ie.mul(e)).mul(_b);L.assign((0,n.mix)(L.clamp(t.sub(r),t.add(r)),L,S))});{let t=1/(hb*2+1)**2,r=R.mul(t),i=Kb(r,ne.mul(t)).mul(e.fastClampSigmaScale),a=L.clamp(r.sub(i),r.add(i)),o=(0,n.select)(e.maxFast.lessThan(e.maxAccum),(0,n.float)(1),(0,n.float)(0)),s=(0,n.mix)((0,n.float)(1).div((0,n.float)(1).add(o.mul(b).mul(2))),(0,n.float)(1),S);L.assign((0,n.mix)(a,L,s))}(0,n.textureStore)(o,_,(0,n.select)(I,A,Wb(A,L))).toWriteOnly()})});return this._dispatchOf(f)}_buildTemporalStabilization(e){let t=this.u,r=this._colorTexNode,i=this._albedoTexNode,a=this._ndTexNode,o=this._snTexNode,s=this._motionTexNode,c=this._nHist,l=this._nData,u=this._nStabRead,d=this._internal,f=this._tmpA,p=this.resW,m=this.resH,h=this.inputFrames,g=this.resetU,_=this.debugMode;return(0,n.Fn)(()=>{let v=(0,n.int)(n.workgroupId.x).mul(Eb).add((0,n.int)(n.localId.x)),y=(0,n.int)(n.workgroupId.y).mul(Eb).add((0,n.int)(n.localId.y));(0,n.If)(v.lessThan((0,n.int)(p)).and(y.lessThan((0,n.int)(m))),()=>{let p=(0,n.ivec2)(v,y),m=(0,n.uvec2)((0,n.uint)(v),(0,n.uint)(y)),b=(0,n.textureLoad)(a,p).w,x=(0,n.textureLoad)(r,p).toVar();(0,n.If)(b.greaterThanEqual(eb),()=>{(0,n.textureStore)(f,m,x).toWriteOnly(),(0,n.textureStore)(e,m,(0,n.vec4)((0,n.textureLoad)(c,p).x,0,0,0)).toWriteOnly(),(0,n.textureStore)(d,m,(0,n.vec4)(0,1,0,0)).toWriteOnly(),(0,n.Return)()});let S=(0,n.textureLoad)(o,p).w,C=Qb(S),w=this._pixelUv(v,y),T=(0,n.textureLoad)(s,p),E=w.sub(T.xy).toVar(),D=(0,n.textureLoad)(l,p).toVar(),O=D.y.toVar(),k=(0,n.uint)(D.z.add(.5)).toVar(),A=D.w.greaterThan(.5),j=this._bilinear(E),M=[1,2,4,8].map(e=>(0,n.select)(k.bitAnd((0,n.uint)(e)).notEqual((0,n.uint)(0)),(0,n.float)(1),(0,n.float)(0))),N=j.customWeights(M).map(e=>e.toVar()),P=(0,n.sqrt)((0,n.saturate)(j.filter(M))).toVar(),F=(0,n.textureLoad)(c,p).toVar(),I=F.x.toVar(),L=I.toVar(),ee=I.mul(I).toVar();for(let e=-1;e<=1;e++)for(let t=-1;t<=1;t++){if(t===0&&e===0)continue;let r=this._clampCoord(v.add(t),y.add(e)),i=(0,n.textureLoad)(a,r).w,o=(0,n.select)(i.greaterThanEqual(eb),I,(0,n.textureLoad)(c,r).x);L.addAssign(o),ee.addAssign(o.mul(o))}L.divAssign(9),ee.divAssign(9);let te=Kb(L,ee).toVar();(0,n.If)(O.lessThan(t.historyFixFrameNum).and(Zb(S).not()),()=>{I.assign((0,n.min)(I,L.mul((0,n.float)(1.2).add((0,n.float)(1).div(O.add(1))))))});let R=(0,n.max)(this._sampleHistory(e=>(0,n.textureLoad)(u,e),E,j,N,A).x,0).toVar(),ne=te.mul(t.antilag.x),re=t.antilag.y.mul(4),ie=R.clamp(L.sub(ne),L.add(ne)),ae=R.sub(ie).abs().div((0,n.max)(R,ie).add(ub)),oe=(0,n.float)(1).div((0,n.float)(1).add(ae.mul(O.mul(P)).div(re))).toVar(),se=(0,n.min)(O,t.historyFixFrameNum);O.assign((0,n.mix)(se,O,oe));let ce=h.add(1),le=this._handover(ce),z=P.mul((0,n.float)(1).sub(this._advancedNonLinear(O.mul((0,n.float)(1).sub(le)).div(ce)))).mul(oe).toVar(),ue=(0,n.float)(1).add(z.mul(6)),de=t.stabilizationStrength.mul((0,n.float)(1).sub(g)),fe=(0,n.mix)(I,R.clamp(L.sub(te.mul(ue)),L.add(te.mul(ue))),(0,n.min)(z,de)).toVar();F.assign(Wb(F,fe)),(0,n.textureStore)(e,m,(0,n.vec4)(fe,0,0,0)).toWriteOnly();let pe=t.maxAccum.mul((0,n.float)(1).sub(g));(0,n.textureStore)(d,m,(0,n.vec4)((0,n.min)(O.add(1),pe),C,0,0)).toWriteOnly();let me=(0,n.textureLoad)(i,p),he=(0,n.vec4)(Hb(F.xyz).mul(Jb(me.xyz)),x.w).toVar();(0,n.If)(_.equal((0,n.int)(1)),()=>{let e=(0,n.saturate)(O.div((0,n.max)(t.maxAccum,1)));he.assign((0,n.vec4)((0,n.float)(1).sub(e),e,.2,1))}).ElseIf(_.equal((0,n.int)(2)),()=>{he.assign((0,n.vec4)((0,n.vec3)(F.w),1))}).ElseIf(_.equal((0,n.int)(3)),()=>{he.assign((0,n.vec4)((0,n.vec3)(C),1))}).ElseIf(_.equal((0,n.int)(4)),()=>{let e=D.x.div(D.x.add(1));he.assign((0,n.vec4)((0,n.vec3)(e),1))}).ElseIf(_.equal((0,n.int)(5)),()=>{he.assign((0,n.vec4)((0,n.vec3)((0,n.float)(k.bitAnd((0,n.uint)(15))).div(15)),1))}),(0,n.textureStore)(f,m,he).toWriteOnly()})})().compute([this._dispatchX,this._dispatchY,1],[Eb,Eb,1])}setupEventListeners(){this.on(`pipeline:historyReset`,()=>this.resetHistory())}resetHistory(){this._needsReset=!0}_updateCamera(){let e=this.pathTracer;if(!e?.uniforms)return;let t=e.uniforms.get(`cameraWorldMatrix`).value,n=e.uniforms.get(`cameraViewMatrix`).value,r=e.uniforms.get(`cameraProjectionMatrixInverse`).value,i=e.uniforms.get(`cameraProjectionMatrix`).value;this._camInitialized&&(this.prevCamView.value.copy(this.camView.value),this.prevCamPos.value.copy(this.camPos.value),this.prevViewVector.value.copy(this.viewVector.value)),this.camWorld.value.copy(t),this.camProjInv.value.copy(r),this.camView.value.copy(n),this.camPos.value.setFromMatrixPosition(t),this.viewVector.value.setFromMatrixColumn(t,2).normalize(),this.cameraRay.sync(e.uniforms),this._camInitialized||=(this.prevCamView.value.copy(n),this.prevCamPos.value.copy(this.camPos.value),this.prevViewVector.value.copy(this.viewVector.value),!0);let a=i.elements[5]||1,o=1/(.5*this.resH.value*a);this.minRectDimMulUnproject.value=Math.min(this.resW.value,this.resH.value)*o}_updateRotators(e){let t=(t,n)=>{let r=ex(e*3+n)*Math.PI*2;t.value.set(Math.cos(r),Math.sin(r),-Math.sin(r),Math.cos(r))};t(this.rotPre,0),t(this.rotBlur,1),t(this.rotPost,2)}render(e){if(!this.enabled)return;let t=e.getTexture(`pathtracer:color`),n=e.getTexture(`pathtracer:albedo`),r=e.getTexture(`pathtracer:normalDepth`),i=e.getTexture(`pathtracer:shadingNormal`),a=e.getTexture(`motionVector:screenSpace`);if(!t)return;if(!n||!r||!i||!a){e.setTexture(`nrd:output`,t);return}let o=t.image;o&&o.width>0&&o.height>0&&(o.width!==this.outputTarget.width||o.height!==this.outputTarget.height)&&this.setSize(o.width,o.height);let s=e.getState(`pathtracer:samples`)??this.pathTracer?.frameCount??0;if(s+1>=this.u.handoverFrames.value){e.setTexture(`nrd:output`,t),this._needsReset=!0;return}if(this._colorTexNode.value=t,this._albedoTexNode.value=n,this._ndTexNode.value=r,this._snTexNode.value=i,this._motionTexNode.value=a,this._updateCamera(),this.inputFrames.value=s,this._updateRotators(this.pathTracer?.uniforms?.get(`seedFrame`)?.value??e.getState(`frame`)??0),this.resetU.value=+!!this._needsReset,!this._compiled){for(let e of this._kernels)this.renderer.compute(e);this._compiled=!0}this._nTmpA.value=this._tmpA,this._nTmpB.value=this._tmpB,this._nHist.value=this._hist,this._nFast.value=this._fastHist,this._nInternal.value=this._internal,this._nGeom.value=this._geomPrev,this._nData.value=this._dataT,this._nStabRead.value=this._stabPing===0?this._stabB:this._stabA,this.renderer.compute(this._kPre),this.renderer.compute(this._kTa),this.renderer.compute(this._kHf),this.renderer.compute(this._kBlur),this.renderer.compute(this._kPost),this.renderer.compute(this._stabPing===0?this._kTsA:this._kTsB),this._srcRegion.max.set(this.outputTarget.width,this.outputTarget.height),this.renderer.copyTextureToTexture(this._tmpA,this.outputTarget.texture,this._srcRegion),e.setTexture(`nrd:output`,this.outputTarget.texture),this._stabPing=1-this._stabPing,this._needsReset=!1,this._needsReset=!1}setSize(e,t){this.outputTarget.setSize(e,t),this.outputTarget.texture.needsUpdate=!0,this.resW.value=e,this.resH.value=t,this._dispatchX=Math.ceil(e/Eb),this._dispatchY=Math.ceil(t/Eb);let n=[this._dispatchX,this._dispatchY,1];for(let e of this._kernels)e&&(e.dispatchSize=n);this._needsReset=!0}releaseGPUMemory(){this._disposeStorage(),this.context?.removeTexture(`nrd:output`),this.outputTarget?.texture?.dispose(),this._needsReset=!0}reallocateReservedStorage(){this._disposeKernels(),this._disposeStorage();for(let[e,t]of this._placeholders)e.value=t;this._allocStorage(),this._buildKernels(),this._compiled=!1,this._needsReset=!0,this._stabPing=0}dispose(){this._releaseHitDistance?.(),this._releaseHitDistance=null,this._disposeKernels(),this._disposeStorage(),this.outputTarget?.dispose();for(let e of[this._colorTexNode,this._albedoTexNode,this._ndTexNode,this._snTexNode,this._motionTexNode])e?.dispose();for(let[e,t]of this._placeholders)e.dispose(),t.dispose();this._placeholders.clear()}};tr();var nx={autoExposure:!1,autoExposureMetering:`center`,autoExposureStrength:.3,autoExposureKeyValue:.18,autoExposureMinExposure:2**-8,autoExposureMaxExposure:2**8,autoExposureAdaptSpeedBright:3,autoExposureAdaptSpeedDark:1},rx=[`average`,`center`,`spot`],ix=64,ax=8,ox=8,sx=256,cx=-16,lx=(12-cx)/sx,ux=2**-24,dx=65536,fx=256,px=128,mx=1.5,hx=.01,gx=.06,_x=.25,vx=4,yx=.3,bx=1.5,xx=3,Sx=[.2126,.7152,.0722],Cx=.999,wx={transparent:0,environment:1,color:2};function Tx(e,t,n,r,i){let a=t-e;if(a===0||!(n>0))return e;let o=Math.max(a<0?r:i,.001);if(n===1/0)return t;let s=Math.min(o*n,Math.abs(a)*(1-Math.exp(-o*n/mx)));return e+Math.sign(a)*s}function Ex(e,t,n){let r=Math.abs(e);return e*(r<=bx?n:r>=xx?1:n+(1-n)*(r-bx)/(xx-bx))+n*(t-e)}function Dx(e,t){if(!e)return t.fromArray(Sx);let n=new r.Matrix3().set(...e).invert().elements;return t.set(Sx[0]*n[0]+Sx[1]*n[1]+Sx[2]*n[2],Sx[0]*n[3]+Sx[1]*n[4]+Sx[2]*n[5],Sx[0]*n[6]+Sx[1]*n[7]+Sx[2]*n[8])}var Ox=e=>e<16?1:e<64?4:16,kx=class extends j{constructor(e,i={}){super(`AutoExposure`,{...i,executionMode:A.ALWAYS}),this.renderer=e,this.metering=i.metering??nx.autoExposureMetering,this.meteringPoint=new r.Vector2(.5,.5),this.keyValue=i.keyValue??nx.autoExposureKeyValue,this.minExposure=i.minExposure??nx.autoExposureMinExposure,this.maxExposure=i.maxExposure??nx.autoExposureMaxExposure,this.adaptSpeedBright=i.adaptSpeedBright??nx.autoExposureAdaptSpeedBright,this.adaptSpeedDark=i.adaptSpeedDark??nx.autoExposureAdaptSpeedDark,this.centerWeight=i.centerWeight??8,this.strength=i.strength??nx.autoExposureStrength,this.instant=!1,this.holdSamples=0,this.onChange=null,this._lowU=(0,n.uniform)(i.lowPercentile??.1),this._highU=(0,n.uniform)(i.highPercentile??.9),this._falloffU=(0,n.uniform)(new r.Vector2),this._pointU=(0,n.uniform)(new r.Vector2(.5,.5)),this._lumWeightsU=(0,n.uniform)(new r.Vector3().fromArray(Sx)),this._backdropModeU=(0,n.uniform)(wx.transparent,`int`),this._widthU=(0,n.uniform)(1,`int`),this._heightU=(0,n.uniform)(1,`int`),this._strideU=(0,n.uniform)(1,`int`),this._gridXU=(0,n.uniform)(ix,`int`),this._gridYU=(0,n.uniform)(ix,`int`),this._inputNode=new t.TextureNode,this._workingMatrix=void 0,this._histogram=(0,n.attributeArray)(sx,`uint`).toAtomic(),this._result=(0,n.attributeArray)(1,`vec4`),this._readback=new t.ReadbackBuffer(16),this._readback.name=`AutoExposure`,this._kernels=[this._buildTileKernel(),this._buildResolveKernel()],this._compensation=1,this._exposureEV=0,this._targetEV=null,this._viewEV=null,this._roomEV=null,this._clock=0,this._movingUntil=-1,this._viewMoves=0,this._landed=null,this._meteredLog2=null,this._snap=!0,this._lastUpdate=null,this._accumulating=!1,this._emittedEV=null,this._pending=null,this._generation=0,this._restarts=0,this._meteredAt={restarts:-1,samples:-1},this._stale=!1,this._disposed=!1}_buildTileKernel(){let e=this._inputNode,t=this._histogram,r=this._widthU,i=this._heightU,a=this._strideU,o=this._gridXU,s=this._gridYU,c=this._lumWeightsU,l=this._falloffU,u=this._pointU,d=this._backdropModeU;return(0,n.Fn)(()=>{let f=n.localId.y.mul((0,n.uint)(ox)).add(n.localId.x),p=(0,n.int)(n.workgroupId.x),m=(0,n.int)(n.workgroupId.y),h=p.mul(r).div(o).toVar(),g=p.add((0,n.int)(1)).mul(r).div(o).toVar(),_=m.mul(i).div(s).toVar(),v=m.add((0,n.int)(1)).mul(i).div(s).toVar(),y=a.mul((0,n.int)(ox)),b=(0,n.float)(0).toVar(),x=(0,n.float)(0).toVar();(0,n.Loop)({start:_.add((0,n.int)(n.localId.y)),end:v,type:`int`,condition:`<`,update:y,name:`py`},({py:t})=>{(0,n.Loop)({start:h.add((0,n.int)(n.localId.x)),end:g,type:`int`,condition:`<`,update:y,name:`px`},({px:r})=>{let i=(0,n.textureLoad)(e,(0,n.ivec2)(r,t)),a=(0,n.dot)(i.xyz,c).toVar(),o=(0,n.floatBitsToUint)(a).bitAnd((0,n.uint)(2139095040)).notEqual((0,n.uint)(2139095040)),s=i.w.clamp(0,1),l=(0,n.select)(d.equal((0,n.int)(wx.environment)),(0,n.float)(1),(0,n.select)(d.equal((0,n.int)(wx.color)),(0,n.select)(s.greaterThanEqual(Cx),(0,n.float)(1),(0,n.float)(0)),s));b.addAssign((0,n.select)(o,a.clamp(0,1e6),(0,n.float)(0)).mul(l)),x.addAssign(l)})});let S=(0,n.workgroupArray)(`float`,ox*ox),C=(0,n.workgroupArray)(`float`,ox*ox);S.element(f).assign(b),C.element(f).assign(x),(0,n.workgroupBarrier)();for(let e=ox*ox>>1;e>0;e>>=1)(0,n.If)(f.lessThan((0,n.uint)(e)),()=>{S.element(f).addAssign(S.element(f.add((0,n.uint)(e)))),C.element(f).addAssign(C.element(f.add((0,n.uint)(e))))}),(0,n.workgroupBarrier)();(0,n.If)(f.equal((0,n.uint)(0)),()=>{let e=S.element((0,n.uint)(0)).toVar(),a=C.element((0,n.uint)(0)).toVar(),o=e=>e.div(y).mul((0,n.int)(ox)).add((0,n.min)(e.mod(y),(0,n.int)(ox))),s=(0,n.float)(o(g.sub(h)).mul(o(v.sub(_))));(0,n.If)(a.greaterThan(0).and(e.greaterThan(a.mul(ux))),()=>{let o=(0,n.uint)((0,n.log2)(e.div(a)).sub(cx).div(lx).floor().clamp(0,sx-1)),c=(0,n.vec2)((0,n.float)(h.add(g)).div((0,n.float)(r)),(0,n.float)(_.add(v)).div((0,n.float)(i))).mul(.5).sub(u),d=(0,n.uint)((0,n.exp)((0,n.dot)(c.mul(c),l).negate()).mul(a.div((0,n.max)(s,1))).mul(dx).add(.5));(0,n.If)(d.greaterThan((0,n.uint)(0)),()=>{(0,n.atomicAdd)(t.element(o),d)})})})})().compute([ix,ix,1],[ox,ox,1])}_buildResolveKernel(){let e=this._histogram,t=this._result,r=this._lowU,i=this._highU;return(0,n.Fn)(()=>{let a=n.localId.x,o=(0,n.float)((0,n.atomicLoad)(e.element(a))).toVar();(0,n.atomicStore)(e.element(a),(0,n.uint)(0));let s=(0,n.workgroupArray)(`float`,sx),c=(0,n.workgroupArray)(`float`,sx);s.element(a).assign(o),(0,n.workgroupBarrier)();for(let e=1;e<sx;e<<=1){let t=s.element(a).toVar();(0,n.If)(a.greaterThanEqual((0,n.uint)(e)),()=>{t.addAssign(s.element(a.sub((0,n.uint)(e))))}),(0,n.workgroupBarrier)(),s.element(a).assign(t),(0,n.workgroupBarrier)()}let l=s.element((0,n.uint)(sx-1)).toVar(),u=s.element(a).toVar();(0,n.workgroupBarrier)();let d=(0,n.max)((0,n.min)(u,l.mul(i)).sub((0,n.max)(u.sub(o),l.mul(r))),0);s.element(a).assign(d),c.element(a).assign(d.mul((0,n.float)(a).add(.5).mul(lx).add(cx))),(0,n.workgroupBarrier)();for(let e=sx>>1;e>0;e>>=1)(0,n.If)(a.lessThan((0,n.uint)(e)),()=>{s.element(a).addAssign(s.element(a.add((0,n.uint)(e)))),c.element(a).addAssign(c.element(a.add((0,n.uint)(e))))}),(0,n.workgroupBarrier)();(0,n.If)(a.equal((0,n.uint)(0)),()=>{let e=s.element((0,n.uint)(0));t.element((0,n.uint)(0)).assign((0,n.vec4)(c.element((0,n.uint)(0)).div((0,n.max)(e,1e-6)),l.div(dx),e.div(dx),1))})})().compute([1,1,1],[sx,1,1])}setupEventListeners(){this.on(`pipeline:reset`,()=>this._restarts++),this.on(`pipeline:lightingChanged`,()=>this.resetHistory())}render(e){if(!this.enabled)return;let t=e.getState(`pathtracer:samples`)??0;if(this._accumulating=t>=2,!this._pending){let n=this._meteredAt,r=this._stale||this._targetEV===null||n.restarts!==this._restarts||t-n.samples>=Ox(t),i=t<this.holdSamples&&this._targetEV!==null&&!this._stale;r&&!i&&this._meter(e,t)}e.setState(`autoexposure:value`,this.renderer.toneMappingExposure),e.setState(`autoexposure:avgLuminance`,this.luminance)}async meter(e=this.context){for(;this._pending;)await this._pending;let t=this._meter(e,e?.getState(`pathtracer:samples`)??0);return t?await t:null}_meter(e,t){let n=e?.getTexture(`pathtracer:color`),r=n?.image?.width|0,i=n?.image?.height|0;if(!n||r<1||i<1||this._disposed)return null;this._meteredAt.restarts=this._restarts,this._meteredAt.samples=t,this._stale=!1;let a=Yn();a!==this._workingMatrix&&(this._workingMatrix=a,Dx(a,this._lumWeightsU.value));let o=Math.min(ix,Math.max(1,Math.floor(r/ax))),s=Math.min(ix,Math.max(1,Math.floor(i/ax))),c=r/o*(i/s);this._gridXU.value=o,this._gridYU.value=s,this._kernels[0].dispatchSize=[o,s,1],this._strideU.value=Math.max(1,Math.round(Math.sqrt(c/fx))),this._widthU.value=r,this._heightU.value=i,this._backdropModeU.value=wx[e.getState(`pathtracer:backdrop`)]??wx.transparent,this._updateMeteringPattern(r/i),this._inputNode.value=n,this.renderer.compute(this._kernels);let l=this._generation,u={restarts:this._restarts,moves:this._viewMoves},d=this.renderer.getArrayBufferAsync(this._result.value,this._readback).then(e=>{let t=e?.buffer?new Float32Array(e.buffer.slice(0,16)):null;return this._readback.release(),t&&l===this._generation&&!this._disposed?this._applyMetering(t,u):null},()=>(!this._disposed&&this._readback._mapped&&this._readback.release(),null)).finally(()=>{this._pending===d&&(this._pending=null)});return this._pending=d,d}_updateMeteringPattern(e){let t=this._falloffU.value,n=this._pointU.value;if(this.metering===`average`)t.set(0,0);else if(this.metering===`spot`){t.set(px*e*e,px),n.copy(this.meteringPoint);return}else t.set(this.centerWeight,this.centerWeight);n.set(.5,.5)}_applyMetering(e,t=this._landed){let[n,r,i]=e;if(!this.enabled||!(r>0&&i>0)||!Number.isFinite(n))return null;let a=this._viewEV;this._meteredLog2=n,this._viewEV=Math.log2(this.keyValue)-n,this._roomEV===null?this._roomEV=this._viewEV:t?.moves===this._landed?.moves?this._roomEV+=this._viewEV-a:this._movingUntil=this._clock+yx,this._landed=t;let o=this._aim(),s=this._targetEV===null||Math.abs(o-this._targetEV)>hx;return this._targetEV=o,(s||this.settling)&&this.onChange?.(),n}update(e=performance.now()){let t=this._lastUpdate===null?0:Math.min((e-this._lastUpdate)/1e3,_x),n=this.advance(t,this._accumulating);return this._lastUpdate=this.settling||this._clock<=this._movingUntil?e:null,n}advance(e,t=!1){if(!this.enabled||this._targetEV===null)return!1;e>0&&e!==1/0&&(this._clock+=e,this._clock<=this._movingUntil&&(this._roomEV+=(this._viewEV-this._roomEV)*(1-Math.exp(-Math.min(e,_x)/vx)),this._targetEV=this._aim()));let n=this._exposureEV;return this._snap||this.instant?(this._exposureEV=this._targetEV,this._snap=!1):(this._exposureEV=t?n+(this._targetEV-n)*(1-Math.exp(-e/gx)):Tx(n,this._targetEV,e,this.adaptSpeedBright,this.adaptSpeedDark),Math.abs(this._targetEV-this._exposureEV)<=hx&&(this._exposureEV=this._targetEV)),this._exposureEV===n?!1:(this._apply(),!0)}_inRange(e){return Math.min(Math.max(e,Math.log2(this.minExposure)),Math.log2(this.maxExposure))}_aim(){return this._inRange(Ex(this._roomEV,this._viewEV,this.strength))}noteViewChanged(){this._viewMoves++}get settling(){return this.enabled&&this._targetEV!==null&&(this._snap||Math.abs(this._targetEV-this._exposureEV)>0)}get wantsMetering(){return this.enabled&&!this._pending&&(this._stale||this._targetEV===null)}_apply(){this.renderer.toneMappingExposure=this.enabled?2**this._exposureEV*this._compensation:this._compensation,!(!this.enabled||this._emittedEV!==null&&Math.abs(this._exposureEV-this._emittedEV)<.005)&&(this._emittedEV=this._exposureEV,this.emit(`autoexposure:updated`,{exposure:this.renderer.toneMappingExposure,autoExposure:this.getExposure(),targetExposure:this._targetEV===null?null:2**this._targetEV,luminance:this.luminance}))}setEnabled(e,t=this._compensation){if(this._compensation=t,e===this.enabled){this._apply();return}this.enabled=e,this._emittedEV=null,e&&(this.resetHistory(),this._exposureEV=0),this._apply(),this.onChange?.()}setCompensation(e){this._compensation=e,this._apply()}resetHistory(){this._generation++,this._targetEV=null,this._viewEV=null,this._roomEV=null,this._landed=null,this._meteredLog2=null,this._snap=!0}getExposure(){return 2**this._exposureEV}get luminance(){return this._meteredLog2===null?null:2**this._meteredLog2}getLuminance(){return this.luminance}updateParameters(e){let t=e.metering;t!==void 0&&rx.includes(t)&&(this.metering=t),e.meteringPoint&&this.meteringPoint.set(e.meteringPoint.x,e.meteringPoint.y);for(let t of[`keyValue`,`minExposure`,`maxExposure`,`adaptSpeedBright`,`adaptSpeedDark`,`centerWeight`,`strength`])e[t]!==void 0&&(this[t]=e[t]);e.lowPercentile!==void 0&&(this._lowU.value=e.lowPercentile),e.highPercentile!==void 0&&(this._highU.value=e.highPercentile),this._stale=!0,this._meteredLog2!==null&&this._applyMetering([this._meteredLog2,1,1]),this.onChange?.()}reset(){}setSize(){}dispose(){this._disposed=!0,this.onChange=null;for(let e of this._kernels)e.dispose();this._readback.dispose(),this._inputNode.dispose()}},Ax={localExposure:!1,localExposureHighlightContrast:.6,localExposureShadowContrast:1,localExposureDetailStrength:1},jx=128,Mx=(jx/2)**2,Nx=32,Px=-16,Fx=16,Ix=-40,Lx=40,Rx=256,zx=32,Bx=.6,Vx=50,Hx=Math.log2(.18),Ux=.999,Wx=2**-24,Gx=Math.ceil(je/jx),Kx=Math.ceil(je/zx),qx=[.2126,.7152,.0722],Jx=e=>e<16?1:e<64?4:16,Yx=(e,t,n)=>Math.min(Math.max(e,t),n);function Xx(e,t,n,r,i,a,o){let s=Math.min(Math.log2(Math.max(a,Wx)),Lx),c=e[6],l=e[7],u=Yx(r*e[2]-.5,0,c-1),d=Yx(i*e[3]-.5,0,l-1),f=Math.floor(u),p=Math.floor(d),m=Math.min(f+1,c-1),h=Math.min(p+1,l-1),g=u-f,_=d-p,v=e=>n[e*c+f]+(n[e*c+m]-n[e*c+f])*g,y=v(p)+(v(h)-v(p))*_,b=e[4],x=e[5],S=Yx(r*e[0]-.5,0,b-1),C=Yx(i*e[1]-.5,0,x-1),w=Yx((s+e[8]-Px)/(Fx-Px),0,1)*(Nx-1),T=Math.floor(S),E=Math.floor(C),D=Math.floor(w),O=S-T,k=C-E,A=w-D,j=0,M=0;for(let e=0;e<8;e++){let n=e&1,r=e>>1&1,i=e>>2,a=(n?O:1-O)*(r?k:1-k)*(i?A:1-A),o=((Math.min(E+r,x-1)*b+Math.min(T+n,b-1))*Nx+Math.min(D+i,Nx-1))*2;j+=t[o]*a,M+=t[o+1]*a}let N=M*Mx<.001?y:j/M,P=N+(y-N)*e[12]+o,F=s+o,I=P>e[13]?e[9]:e[10];return 2**(e[13]+(P-e[13])*I+(F-P)*e[11]-F)}var Zx=`
|
|
926
|
+
`,zv=32,Bv=class{constructor(e,t=`rayzee:tonemap`,{input:n=`packed`,output:r=`rgba8`}={}){this.device=e,this.label=t,this.input=n,this.output=r,this.width=0,this.height=0,this._pipelines=new Map,this._storage=null,this._map=null,this._params=null,this._paramData=new ArrayBuffer(zv),this._paramU32=new Uint32Array(this._paramData),this._paramF32=new Float32Array(this._paramData),this._shaderVersion=-1,this._bindings=[],this._tables=new Map,this.disposed=!1}_ensurePipeline(e=null){let{wgsl:t,bindings:n,version:r}=Mv();this._shaderVersion!==r&&(this._pipelines.clear(),this._bindings=n,this._shaderVersion=r);let i=e?.wgsl?e.key:``,a=this._pipelines.get(i);return a||(a=this.device.createComputePipeline({label:this.label,layout:`auto`,compute:{module:this.device.createShaderModule({label:this.label,code:Rv(t,this.input,this.output,e?.wgsl)}),entryPoint:`main`}}),this._pipelines.set(i,a),a)}_ensureTables(){let e=new Set;for(let{index:t,transform:n}of this._bindings){let{data:r,size:i}=n.table;e.add(t);let a=this._tables.get(t);if(a&&a.data===r)continue;a?.texture.destroy();let o=this.device.createTexture({label:`${this.label}-${n.wgslConst}`,size:[i,i,i],dimension:`3d`,format:`rgba16float`,usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST});this.device.queue.writeTexture({texture:o},r,{bytesPerRow:i*8,rowsPerImage:i},[i,i,i]),this._tables.set(t,{texture:o,data:r,view:o.createView()})}for(let[t,n]of this._tables)e.has(t)||(n.texture.destroy(),this._tables.delete(t))}ensureSize(e,t){if(this._ensurePipeline(),this._ensureTables(),this.width===e&&this.height===t&&this._storage)return;this._releaseBuffers();let n=e*t*Lv[this.output];this._storage=this.device.createBuffer({label:`${this.label}-out`,size:n,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC}),this._map=this.device.createBuffer({label:`${this.label}-map`,size:n,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),this._params=this.device.createBuffer({label:`${this.label}-params`,size:zv,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this.width=e,this.height=t}async toRGBA8(e,t){return new Uint8ClampedArray(await this._run(e,t))}async toPlanar(e,t){return new Float32Array(await this._run(e,t))}async _run(e,t={}){let n=t.gain;if(!n?.wgsl||!n.device||n.device===this.device)return this._dispatch(e,t);let r=await n.copyTo(this.device);try{return await this._dispatch(e,{...t,gain:{...r,backdrop:n.backdrop}})}finally{r.destroy()}}async _dispatch(e,{exposure:t=1,toneMapping:n=0,saturation:r=1,flipY:i=!1,preserveAlpha:a=!1,gain:o=null}={}){if(this.disposed)throw Error(`PackedToneMapper: disposed`);if(!this._storage)throw Error(`PackedToneMapper: call ensureSize() first`);let s=this._ensurePipeline(o);this._ensureTables();let{width:c,height:l}=this,u=c*l*Lv[this.output];this._paramU32[0]=c,this._paramU32[1]=l,this._paramU32[2]=n>>>0,this._paramU32[3]=+!!i,this._paramF32[4]=t,this._paramF32[5]=r,this._paramU32[6]=+!!a,this._paramF32[7]=o?.backdrop>0?o.backdrop:0,this.device.queue.writeBuffer(this._params,0,this._paramData);let d=[...this._tables.entries()].map(([e,t])=>({binding:e,resource:t.view})),f=this.device.createBindGroup({layout:s.getBindGroupLayout(0),entries:[...d,{binding:0,resource:this.input===`texture`?e.createView():{buffer:e,size:c*l*8}},{binding:1,resource:{buffer:this._storage}},{binding:2,resource:{buffer:this._params}}]}),p=this.device.createCommandEncoder({label:this.label}),m=p.beginComputePass();m.setPipeline(s),m.setBindGroup(0,f),o?.wgsl&&m.setBindGroup(1,this.device.createBindGroup({layout:s.getBindGroupLayout(1),entries:o.entries})),m.dispatchWorkgroups(Math.ceil(c/8),Math.ceil(l/8)),m.end(),p.copyBufferToBuffer(this._storage,0,this._map,0,u),this.device.queue.submit([p.finish()]),await this._map.mapAsync(GPUMapMode.READ);let h=this._map.getMappedRange().slice(0);return this._map.unmap(),h}release(){this._releaseBuffers(),this.width=this.height=0}_releaseBuffers(){this._storage?.destroy(),this._map?.destroy(),this._params?.destroy(),this._storage=null,this._map=null,this._params=null}dispose(){if(!this.disposed){this.disposed=!0,this._releaseBuffers();for(let e of this._tables.values())e.texture.destroy();this._tables.clear(),this._pipelines.clear()}}}}));Vv(),vs(),tr(),an();var Hv=class{constructor({issues:e=null}={}){this._issues=e,this._renderer=null,this._offRegistry=Qo(()=>{this._renderer&&os(this._renderer)})}get hasConfig(){return!1}get workingSpace(){return Zr}get workingSpaceAdopted(){return!1}get inputKey(){return`-`}attachRenderer(e){this._renderer=e;let t=os(e);return e.outputColorSpace=r.SRGBColorSpace,t}listViews(){return es()}get activeView(){return null}setActiveView(e){let t=$o(e);if(!t)throw Error(`no view transform with id ${e}`);if(t.outputEncoded)throw Error(`"${t.name}" returns display-encoded colour: it needs rayzee/addons/color`);return this._renderer&&(this._renderer.toneMapping=e),t}_publishWorkingMatrix(){Jn(null,Zr)}loadConfig(){let e=`colour configs need the OCIO pipeline: renderer.setColorManagement( ColorManagement ), from rayzee/addons/color`;return this._issues?.record(X.CAPABILITY_MISSING,e,{capability:`color`}),Promise.reject(Error(e))}unloadConfig(){}setWorkingSpace(){}setHdrOutput(e){e&&this._issues?.warn(X.CAPABILITY_MISSING,`HDR on screen needs rayzee/addons/color`,{capability:`color`})}get hdrOutput(){return!1}get canvasTransform(){return null}get canvasColorSpace(){return`srgb`}exportPixels(e){return{rgba:e,colorSpace:Zr}}status(){let e=this._renderer?$o(this._renderer.toneMapping):null;return{config:null,workingSpace:Zr,workingSpaceAdopted:!1,activeTransform:e?{id:e.id,name:e.name,source:e.source}:null,activeView:null,context:null,exportSpace:null,views:es(),registryVersion:Zo(),bakeError:e?.error??null,canvasColorSpace:`srgb`,hdr:{on:!1,showing:!1,view:null,reason:null}}}dispose(){this._offRegistry?.(),this._renderer=null,this._issues=null,$r()===this&&(Jn(null),ei(null))}};function Uv(e){return e.mimeType?e.mimeType:e.uri?.startsWith(`data:`)?e.uri.slice(5,e.uri.indexOf(`;`)):ey.find(([t])=>t.test(e.uri??``))?.[1]??`image/png`}function Wv(e){for(let t=8;t+12<=e.length;){let n=(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0,r=t+12+n;if(e[t+4]===73&&e[t+5]===69&&e[t+6]===78&&e[t+7]===68)return e.subarray(0,r);t=r}return e}function Gv({data:e,width:t,height:n},{shared:i=!1}={}){let a=new Uint8Array(e.buffer,e.byteOffset,t*n*4),o=a;i&&typeof SharedArrayBuffer<`u`&&!(a.buffer instanceof SharedArrayBuffer)&&(o=new Uint8Array(new SharedArrayBuffer(a.byteLength)),o.set(a));let s=new r.DataTexture(o,t,n,r.RGBAFormat,r.UnsignedByteType);return s.needsUpdate=!0,s}function Kv(e,t){return Dr().decodeImage(t===`image/png`?Wv(e):e,t)}async function qv(e){let t=await fetch(e);if(!t.ok)throw Error(`HTTP ${t.status}`);return new Uint8Array(await t.arrayBuffer())}function Jv(e,t){return t.bufferView===void 0?qv(e.options.manager.resolveURL(r.LoaderUtils.resolveURL(t.uri,e.options.path))):e.getDependency(`bufferView`,t.bufferView).then(e=>new Uint8Array(e))}function Yv(e,t,n){if(e.sourceCache[t]!==void 0)return e.sourceCache[t].then(e=>e.clone());let r=Jv(e,e.json.images[t]).then(e=>new Promise((t,r)=>{n.parse(e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength),t,r)}));return e.sourceCache[t]=r,r}async function Xv(e,t=Uv({uri:e})){let n=Gv(await Kv(await qv(e),t));return n.flipY=!0,n}async function Zv(e,t){let n=Gv(await Kv(e,Uv({uri:t})),{shared:!0});return n.flipY=!0,n}function Qv(e,t=null){return e.loadImageSource=function(e,n){if(ty(this,n))return Yv(this,e,n);let r=this.json.images[e],i=Error(`no image decoder in this runtime: configurePlatform( nodePlatform( { decodeImage } ) ) — see "Running in Node"`);return t?.(r.uri??`bufferView ${r.bufferView}`,i),Promise.reject(i)},{name:`RAYZEE_missing_image_decoder`}}function $v(e,t=null){return e.loadImageSource=function(e,n){if(ty(this,n))return Yv(this,e,n);if(this.sourceCache[e]!==void 0)return this.sourceCache[e].then(e=>e.clone());let r=this.json.images[e],i=Uv(r),a=r.uri??`bufferView ${r.bufferView}`,o=Jv(this,r).then(e=>Kv(e,i)).then(e=>{let t=Gv(e,{shared:!0});return r.extras&&typeof r.extras==`object`&&Object.assign(t.userData,r.extras),t.userData.mimeType=i,t}).catch(e=>{throw t?.(a,e),e});return this.sourceCache[e]=o,o},{name:`RAYZEE_platform_images`}}var ey,ty,ny=g((()=>{Fr(),ey=[[/\.jpe?g(\?|#|$)/i,`image/jpeg`],[/\.webp(\?|#|$)/i,`image/webp`],[/\.avif(\?|#|$)/i,`image/avif`]],ty=(e,t)=>!!t&&t!==e.textureLoader&&typeof t.parse==`function`}));ny();var ry=`KHR_materials_diffuse_transmission`;function iy(e){let t=(t,n,r,i)=>{let a={};return e.assignTexture(a,n,r,i).then(()=>{a[n]&&(t[n]=a[n])})};return{name:ry,afterRoot(n){let i=e.json.materials??[],a=new Set,o=[];for(let s of n.scenes??[])s.traverse(n=>{let s=Array.isArray(n.material)?n.material:n.material?[n.material]:[];for(let n of s){if(a.has(n))continue;a.add(n);let s=e.associations.get(n)?.materials,c=s===void 0?null:i[s]?.extensions?.[ry];if(!c)continue;n.diffuseTransmission=c.diffuseTransmissionFactor??0;let[l,u,d]=c.diffuseTransmissionColorFactor??[1,1,1];n.diffuseTransmissionColor=new r.Color().setRGB(l,u,d,r.LinearSRGBColorSpace),c.diffuseTransmissionTexture&&o.push(t(n,`diffuseTransmissionMap`,c.diffuseTransmissionTexture)),c.diffuseTransmissionColorTexture&&o.push(t(n,`diffuseTransmissionColorMap`,c.diffuseTransmissionColorTexture,r.SRGBColorSpace))}});return Promise.all(o)}}}ui();var ay=`KHR_draco_mesh_compression`,oy=`KHR_texture_basisu`,sy=[`EXT_meshopt_compression`,`KHR_meshopt_compression`],cy=new TextDecoder;function ly(e){if(typeof e==`string`)return e;if(!(e instanceof ArrayBuffer))return JSON.stringify(e?.extensionsUsed??[]);let t=new DataView(e);if(!(e.byteLength>=20&&t.getUint32(0,!0)===1179937895))return cy.decode(e);let n=Math.min(t.getUint32(12,!0),e.byteLength-20);return cy.decode(new Uint8Array(e,20,n))}async function uy(e,t,n){let{dracoDecoderPath:r,ktx2TranscoderPath:i}=si(),[a,o,s]=await Promise.all([t.includes(ay)&&!e.dracoLoader?import(`three/addons/loaders/DRACOLoader.js`):null,t.includes(oy)&&!e.ktx2Loader?import(`three/addons/loaders/KTX2Loader.js`):null,sy.some(e=>t.includes(e))&&!e.meshoptDecoder?import(`three/addons/libs/meshopt_decoder.module.js`):null]);if(a){let t=new a.DRACOLoader;t.setDecoderConfig({type:`js`}),t.setDecoderPath(r),e.setDRACOLoader(t)}if(o){let t=new o.KTX2Loader;t.setTranscoderPath(i),n&&(t.detectSupport(n),t.workerConfig={astcSupported:!1,etc1Supported:!1,etc2Supported:!1,dxtSupported:!1,bptcSupported:!1,pvrtcSupported:!1}),e.setKTX2Loader(t)}s&&e.setMeshoptDecoder(s.MeshoptDecoder)}function dy(e,t){let n=e.parse.bind(e);return e.parse=(r,i,a,o)=>{uy(e,ly(r),t).then(()=>n(r,i,a,o),e=>o?.(e))},e}function fy(e){if(typeof e==`string`)try{let t=JSON.parse(e);return t&&typeof t==`object`?t:null}catch{return null}return e&&typeof e==`object`?e:null}function py(e){let t=typeof e==`string`?parseFloat(e):e;return Number.isFinite(t)?t:void 0}function my(e){let t=fy(e);if(!t)return null;let n=e=>e&&(e.environment!==void 0||e.render!==void 0),r=fy(t.rayzee);return n(r)?r:n(t)?t:null}function hy(e){let t=fy(e);if(!t)return null;let n=yy.map(e=>t[e]).find(e=>typeof e==`string`&&e.trim());if(!n)return null;let r=py(t.rotation),i=py(t.intensity),a={sourceFile:n.trim()};return r!==void 0&&(a.rotation=r),i!==void 0&&(a.intensity=Math.max(0,i)),a}function gy(e){let t=fy(e);if(!t)return null;let n={};for(let e of by){let r=py(t[e]);r!==void 0&&r>0&&(n[e]=Math.round(r))}return Object.keys(n).length?n:null}function _y(e){let t=my(e);if(!t)return null;let n=hy(t.environment),r=gy(t.render);return!n&&!r?null:{...n?{environment:n}:{},...r?{render:r}:{}}}function vy(e){if(!e)return null;let t=[e.userData,e.asset?.extras,e.scene?.userData];Array.isArray(e.scenes)&&t.push(...e.scenes.map(e=>e?.userData));for(let e of t){let t=_y(e);if(t)return t}return null}var yy,by,xy=g((()=>{yy=[`sourceFile`,`url`,`file`],by=[`maxBounces`,`samples`,`width`,`height`]}));yi(),de(),Fr(),xy(),an(),lt(),Ae();var Sy=ve(`assets`),Cy={glb:{type:`model`,name:`GLB (GLTF Binary)`},gltf:{type:`model`,name:`GLTF`},hdr:{type:`environment`,name:`HDR (High Dynamic Range)`},png:{type:`image`,name:`PNG`},jpg:{type:`image`,name:`JPEG`},jpeg:{type:`image`,name:`JPEG`},webp:{type:`image`,name:`WebP`}},wy={addOn:`rayzee/addons/archives`,install:`assetLoader.setArchiveImporter()`},Ty={addOn:`rayzee/addons/formats`,install:`assetLoader.registerFormat()`},Ey={zip:wy,gz:wy,tgz:wy,tar:wy,fbx:Ty,obj:Ty,stl:Ty,ply:Ty,dae:Ty,"3mf":Ty,usd:Ty,usda:Ty,usdc:Ty,usdz:Ty,exr:Ty};function Dy(e){let t=new r.BufferGeometry;for(let n in e.attributes)t.setAttribute(n,e.attributes[n]);e.index&&t.setIndex(e.index);for(let n of e.groups)t.addGroup(n.start,n.count,n.materialIndex);return t}var Oy={name:`RAYZEE_camera_clip`,afterRoot(e){for(let t of e.scenes)t.traverse(e=>{e.isCamera&&e.near>0&&(e.userData.clipStart=e.near)})}},ky=683;function Ay(e,t,n,i){if(!(i.normalize??!0))return Math.PI;let a=i.shape===`ellipse`||i.shape===`disk`?Math.PI/4:1,o=e.getWorldScale(new r.Vector3),s=Math.PI*a*Math.abs(t*o.x*n*o.y);return Number.isFinite(s)?s:Math.PI}var jy=class e extends r.EventDispatcher{constructor(e,t,n,{issues:i=null,areaLightIntensityScale:a=null}={}){super(),this.scene=e,this.camera=t,this.controls=n,this.targetModel=null,this.floorPlane=null,this.sceneScale=1,this.sceneSize=new r.Vector3(1,1,1),this.loaderCache={},this.uploadedFileInfo=null,this.animations=[],this.renderer=null,this.sceneMetadata=null,this._loadingManager=new r.LoadingManager,this._loadCancelled=!1,this._urlAbort=null,this.storage=null,this._downloads=null,this._sourceKey=null,this._appended=!1,this.archives=null,this._archiveLoader=null,this._formats=new Map,this._issues=i,this._areaLightIntensityScale=a??(()=>H.areaLightIntensityScale),this._loadingManager.onError=e=>{this._loadCancelled||this._issues?.record(X.ASSET_UNREACHABLE,`asset "${e}" could not be fetched — anything depending on it renders without it`,{url:e})}}cancelActiveLoad(){this._loadCancelled=!0,this._loadingManager.abort(),this._urlAbort?.abort()}async _viaCache(t,n,r,{cacheKey:i=t,cachePolicy:a}={}){if(!this.storage||!e._isNetworkUrl(t)||/\.gltf$/i.test(t.split(/[?#]/)[0]))return{url:t,release:()=>{},cached:!1};let o=new AbortController;this._urlAbort=o;try{return await cv(t,{downloads:this.downloads,key:i,policy:a,name:tv(t),signal:o.signal,onProgress:this._downloadProgress(n,r)})}catch(e){throw this._isCancellation(e)?this._cancellationError():e}finally{this._urlAbort=null}}get sceneSourceKey(){return this._appended?null:this._sourceKey}_keyed(e,t){return t?`${e}::${t}`:null}get downloads(){return this._downloads?._storage!==this.storage&&(this._downloads=new av(this.storage)),this._downloads}_isCancellation(e){return this._loadCancelled||e?.name===`AbortError`||e?.code===`LOAD_CANCELLED`}_cancellationError(){let e=Error(`Load cancelled`);return e.code=`LOAD_CANCELLED`,e}_downloadProgress(e,t){return n=>{let r=n?.loaded||0,i=n?.lengthComputable&&n.total||0;z({isLoading:!0,status:e,loadedBytes:r,totalBytes:i,canCancel:!!t,progress:i?Math.min(60,2+Math.round(r/i*58)):2})}}_downloadComplete(e=`Processing Data...`,t=62){z({status:e,progress:t,canCancel:!1,loadedBytes:null,totalBytes:null})}static _isNetworkUrl(e){return typeof e==`string`&&/^https?:/i.test(e)}_adoptExternalObject(e){let t;try{t=(0,l.clone)(e)}catch(t){throw Error(`Cannot render "${e.name||e.type}": its userData must be JSON-serializable.`,{cause:t})}return t.userData.__rayzeeExternal=!0,this.scene?.children.some(t=>t.uuid===e.uuid)||(t.uuid=e.uuid),e.parent&&(e.parent.updateWorldMatrix(!0,!1),t.applyMatrix4(e.parent.matrixWorld)),t}releaseTargetModel(){this.sceneMetadata=null,this._sourceKey=null,this._appended=!1,this.archives?.release(),this.targetModel&&(this.removeModelRoot(this.targetModel),this.targetModel=null,this.animations=[])}setRenderer(e){this.renderer=e}setArchiveImporter(e){this.archives=e}setArchiveImporterLoader(e,t){this._archiveLoader={load:e,formats:t,pending:null}}async _archiveImporter(){return!this.archives&&this._archiveLoader&&(this.archives=await(this._archiveLoader.pending??=this._archiveLoader.load())),this.archives}get _archiveFormats(){return this.archives?.constructor.FORMATS??this._archiveLoader?.formats??null}registerFormat(...e){for(let t of e)for(let e of t.extensions)this._formats.set(e,t);return this}getFileFormat(e){let t=e.split(`.`).pop().toLowerCase();return Cy[t]||this._formats.get(t)||this._archiveFormats?.[t]||null}formatError(e){let t=Ey[e.split(`.`).pop().toLowerCase()];return Error(t?`${e}: this format is read by ${t.addOn} — install it with ${t.install}`:`Unsupported file format: ${e}`)}async inspectArchive(e){let t=await this._archiveImporter();if(!t)throw this.formatError(e.name??`archive.zip`);return await t.inspectArchive(e)}flushPendingGraph(e){this.archives?.flushPendingGraph(e)}commitPendingGraph(e){this.archives?.commitPendingGraph(e)}readFileAsArrayBuffer(e){return e.arrayBuffer()}readFileAsText(e){return e.text()}async loadAssetFromFile(e,t={}){let n=e.name,r=this.getFileFormat(n);if(!r)throw this.formatError(n);z({isLoading:!0,status:`Loading ${r.name}...`,progress:2});try{let i;switch(r.type){case`model`:i=await this.loadModelFromFile(e,n);break;case`environment`:case`image`:i=await this.loadEnvironmentFromFile(e,n);break;case`archive`:i=await(await this._archiveImporter()).loadArchiveFromFile(e,n,t);break;default:throw Error(`Unknown asset type: ${r.type}`)}return i}catch(e){throw e?.code!==`ARCHIVE_NEEDS_ELEMENT`&&this.dispatchEvent({type:`error`,message:e.message,filename:n}),e}}async loadFolder(e,t={}){let n=await this._archiveImporter();if(!n)throw Error(`${e.name}: folders are read by ${wy.addOn} — install it with ${wy.install}`);z({isLoading:!0,status:`Loading ${e.name}...`,progress:2});try{return await n.loadFolder(e,t)}catch(t){throw t?.code===`ARCHIVE_NEEDS_ELEMENT`?t.file=e:this.dispatchEvent({type:`error`,message:t.message,filename:e.name}),t}}async loadAssetFromUrl(t,n={}){let{filename:r=tv(t),cacheKey:i=t,cachePolicy:a,...o}=n;if(!this.getFileFormat(r))throw this.formatError(r);this._loadCancelled=!1;let s=e._isNetworkUrl(t),c=`Downloading ${r}...`,l=new AbortController;this._urlAbort=l,z({isLoading:!0,status:c,progress:2,canCancel:s,loadedBytes:0,totalBytes:0});let u;try{u=await this.downloads.fetch(t,{key:i,name:r,policy:a,signal:l.signal,onProgress:this._downloadProgress(c,s)})}catch(e){throw this._isCancellation(e)?this._cancellationError():e}finally{this._urlAbort=null}this._downloadComplete();try{return await this.loadAssetFromFile(u.file,o)}catch(e){throw e?.code===`ARCHIVE_NEEDS_ELEMENT`&&(e.file=u.file),e}finally{u.release()}}async loadModelFromFile(e,t){let n=this.storage?this._keyed(`file`,hv(await pv(e))):null,r=/\.(usd|usda|usdc)$/i.test(t)?await this._archiveImporter():null,i=r?await r.loadUSDScene({[t]:e},t):await this._loadModelFileByExtension(e,t);return this._sourceKey=n,i}async _loadModelFileByExtension(e,t){let n=t.split(`.`).pop().toLowerCase();if(n===`glb`||n===`gltf`)return await this.loadGLBFromArrayBuffer(await this.readFileAsArrayBuffer(e),t);let r=this._formats.get(n);if(r?.type!==`model`)throw this.formatError(t);return await this._loadModelWithFormat(r,e,t)}async _loadModelWithFormat(e,t,n){try{z({isLoading:!0,status:`Processing ${e.label} Data...`,progress:5}),await new Promise(e=>setTimeout(e,0));let{model:r,result:i=r}=await e.parse(t,{filename:n,cache:this.loaderCache});return this.releaseTargetModel(),this.targetModel=r,z({isLoading:!0,status:`Processing Data...`,progress:10}),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:r,filename:n}),i}catch(t){throw console.error(`Error loading ${e.label}:`,t),this.dispatchEvent({type:`error`,message:t.message,filename:n}),t}}async loadEnvironmentFromFile(e,t){let n=URL.createObjectURL(e);this.uploadedFileInfo={name:t,type:e.type,size:e.size};try{let r=await this.loadEnvironment(n);return di(r,hv(await pv(e))),this.dispatchEvent({type:`load`,texture:r,filename:t}),r}finally{URL.revokeObjectURL(n)}}async loadEnvironment(t){this._loadCancelled=!1;try{this.dispatchEvent({type:`beforeEnvironmentLoad`,url:t});let n;if(t.startsWith(`blob:`))n=await this.loadEnvironmentFromBlob(t);else{let e=t.split(/[?#]/)[0].split(`.`).pop().toLowerCase();n=await this.loadEnvironmentByExtension(t,e)}return n.generateMipmaps=!0,e._isNetworkUrl(t)&&di(n,t),this.applyEnvironmentToScene(n),this.dispatchEvent({type:`load`,texture:n,url:t,filename:t.split(/[?#]/)[0].split(`/`).pop()}),n}catch(e){throw this._isCancellation(e)?this._cancellationError():(console.error(`Error loading environment:`,e),this.dispatchEvent({type:`error`,message:e.message,filename:t}),e)}}async loadEnvironmentFromBlob(e){let t=await(await fetch(e)).blob(),n=this.determineEnvironmentExtension(t,e),r=URL.createObjectURL(t);try{return await this.loadEnvironmentByExtension(r,n)}finally{URL.revokeObjectURL(r)}}determineEnvironmentExtension(e,t){let n;if(e.type===`image/x-exr`||e.type.includes(`exr`))n=`exr`;else if(e.type===`image/vnd.radiance`||e.type.includes(`hdr`))n=`hdr`;else{let e=t.split(`/`).pop();if(e){let t=e.match(/\.([^.]+)$/);t&&(n=t[1].toLowerCase())}}return!n&&this.uploadedFileInfo&&(n=this.uploadedFileInfo.name.split(`.`).pop().toLowerCase()),n}async loadEnvironmentByExtension(t,n,{loader:i=null}={}){let a=this._formats.get(n);if(!i&&a?.type===`environment`&&(i=this.loaderCache[n]??=await a.createLoader(this._loadingManager)),!i&&n===`hdr`&&(i=this.loaderCache.hdr??=new s.HDRLoader(this._loadingManager).setDataType(r.FloatType)),!i&&Ey[n])throw this.formatError(`environment.${n}`);let o=e._isNetworkUrl(t),c=`Downloading Environment...`,l=await this._viaCache(t,c,o),u=l.cached?void 0:this._downloadProgress(c,o),d;try{i?d=await i.loadAsync(l.url,u):Dr().decodeImage?(d=await Xv(l.url,`image/${n===`jpg`?`jpeg`:n}`),d.colorSpace=r.SRGBColorSpace):(this.loaderCache.texture||(this.loaderCache.texture=new r.TextureLoader(this._loadingManager)),d=await this.loaderCache.texture.loadAsync(l.url,u),d.colorSpace=r.SRGBColorSpace)}finally{l.release()}return this._downloadComplete(`Processing Environment...`,62),this.maxEnvironmentWidth&&My(d,this.maxEnvironmentWidth),d.mapping=r.EquirectangularReflectionMapping,d.minFilter=r.LinearFilter,d.magFilter=r.LinearFilter,d}applyEnvironmentToScene(e){this.scene.background=e,this.scene.environment=e}async createGLTFLoader(){let e=dy(new o.GLTFLoader(this._loadingManager),this.renderer),t=(e,t)=>this._reportImageFailure(e,t);return Dr().decodeImage?e.register(e=>$v(e,t)):kr()||e.register(e=>Qv(e,t)),e.register(e=>iy(e)),e.register(()=>Oy),e}_reportImageFailure(e,t){try{this._issues?.record(X.TEXTURE_BUILD_FAILED,`image ${e} could not be decoded (${t?.message??t}) — the surfaces using it render untextured`,{image:e,cause:String(t?.message??t)})}catch(e){this._deferredError??=e}}_throwDeferred(){let e=this._deferredError;if(this._deferredError=null,e)throw e}_disposeGLTFLoader(e){e&&(e.dracoLoader?.dispose(),e.ktx2Loader?.dispose())}async loadExampleModels(e,t){if(!t||!t[e])throw Error(`No model file at index ${e}`);let n=`${t[e].url}`;return await this.loadModel(n)}async loadModel(t,n={}){this._loadCancelled=!1;let i=await this.createGLTFLoader(),a=e._isNetworkUrl(t),o=null;try{z({isLoading:!0,status:`Downloading Model...`,progress:2,canCancel:a,loadedBytes:0,totalBytes:0}),o=await this._viaCache(t,`Downloading Model...`,a,n),o.cached&&i.setResourcePath(r.LoaderUtils.extractUrlBase(t));let e=await jr(()=>i.loadAsync(o.url,o.cached?void 0:this._downloadProgress(`Downloading Model...`,a)));return this._downloadComplete(),this._throwDeferred(),this.releaseTargetModel(),this._sourceKey=a?this._keyed(`url`,n.cacheKey??t):null,this.targetModel=e.scene,this.animations=e.animations||[],this.sceneMetadata=vy(e),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:e.scene,filename:t.split(`/`).pop()}),e}catch(e){throw this._isCancellation(e)?this._cancellationError():(console.error(`Error loading model:`,e),this.dispatchEvent({type:`error`,message:e.message,filename:t}),e)}finally{o?.release(),this._disposeGLTFLoader(i)}}_processAndParent(e){this.processModelObjects(e),this.scene.add(e),e.updateMatrixWorld(!0)}async appendModel(t,n={}){this._loadCancelled=!1;let i=await this.createGLTFLoader(),a=e._isNetworkUrl(t),o=null;try{z({isLoading:!0,status:`Downloading Model...`,progress:2,canCancel:a,loadedBytes:0,totalBytes:0}),o=await this._viaCache(t,`Downloading Model...`,a,n),o.cached&&i.setResourcePath(r.LoaderUtils.extractUrlBase(t));let e=await jr(()=>i.loadAsync(o.url,o.cached?void 0:this._downloadProgress(`Downloading Model...`,a)));return this._downloadComplete(),this._throwDeferred(),this._appended=!0,this._processAndParent(e.scene),{root:e.scene,animations:e.animations||[]}}catch(e){throw this._isCancellation(e)?this._cancellationError():e}finally{o?.release(),this._disposeGLTFLoader(i)}}appendObject3D(e,t=`object3d`){this._appended=!0;let n=this._adoptExternalObject(e);return n.name=e.name||t,this._processAndParent(n),{root:n}}removeModelRoot(e){e&&(e.userData.__rayzeeExternal?(ie(e),e.parent?.remove(e)):re(e))}async loadGLBFromArrayBuffer(e,t=`model.glb`){let n=await this.createGLTFLoader();try{z({isLoading:!0,status:`Processing GLB Data...`,progress:5}),await new Promise(e=>setTimeout(e,0));let r=await jr(()=>n.parseAsync(e,``));return this._throwDeferred(),this.releaseTargetModel(),this.targetModel=r.scene,this.animations=r.animations||[],this.sceneMetadata=vy(r),z({isLoading:!0,status:`Processing Data...`,progress:10}),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:r.scene,filename:t}),r}catch(e){throw console.error(`Error loading GLB:`,e),this.dispatchEvent({type:`error`,message:e.message,filename:t}),e}finally{this._disposeGLTFLoader(n)}}async loadObject3D(e,t=`object3d`){this.releaseTargetModel();let n=this._adoptExternalObject(e);return n.name=e.name||t,this.targetModel=n,z({isLoading:!0,status:`Processing Data...`,progress:10}),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:n,filename:t}),n}async onModelLoad(e){let t=new tc(`onModelLoad`);t.start(`Camera extraction`);let n=this.extractCamerasFromModel(e);t.end(`Camera extraction`),t.start(`Camera setup`);let i=new r.Box3().setFromObject(e),a=i.getCenter(new r.Vector3),o=i.getSize(new r.Vector3);this.controls?.target.copy(a);let s=Math.max(o.x,o.y,o.z),c=this.camera.fov*(Math.PI/180),l=Math.abs(s/Math.sin(c/2)/2),u=Math.PI/6,d=new r.Vector3(Math.cos(u)*l,l/Math.sqrt(2),Math.sin(u)*l);if(this.camera.position.copy(d.add(a)),this.camera.lookAt(a),this.camera.near=s/100,this.camera.far=s*100,this.camera.updateProjectionMatrix(),this.controls&&(this.controls.maxDistance=l*10,this.controls.saveState(),this.controls.update()),t.end(`Camera setup`),this.floorPlane){let e=i.min.y;this.floorPlane.position.y=e,this.floorPlane.rotation.x=-Math.PI/2,this.floorPlane.scale.setScalar(s*5)}t.start(`Process model objects`),this.processModelObjects(e),t.end(`Process model objects`),t.start(`Scene add`),this.scene.add(e),t.end(`Scene add`);let f=s;return this.sceneSize.copy(o),t.start(`setupPathTracing`),await this.setupPathTracing(e,f),t.end(`setupPathTracing`),t.print(),this.dispatchEvent({type:`modelProcessed`,model:e,cameras:n,sceneData:{center:a,size:o,maxDim:s,sceneScale:f}}),this.dispatchEvent({type:`SceneRebuild`}),{center:a,size:o,maxDim:s,sceneScale:f}}extractCamerasFromModel(e){let t=[];return e.updateWorldMatrix(!0,!0),e.traverse(e=>{if(e.isCamera){let n=e.clone();n.userData.__rayzeeSourceUuid=e.uuid,e.getWorldPosition(n.position),e.getWorldQuaternion(n.quaternion),e.getWorldScale(n.scale),n.scale.set(Math.sign(n.scale.x)||1,Math.sign(n.scale.y)||1,Math.sign(n.scale.z)||1),(!n.name||n.name===``)&&(n.name=`Model Camera ${t.length+1}`),n.isPerspectiveCamera&&(n.aspect=this.camera.aspect,n.updateProjectionMatrix()),t.push(n)}}),t}processModelObjects(e){let t=[],n=[];e.traverse(e=>{let i=e.userData;e.isRectAreaLight&&!i.__radianceConverted&&(e.intensity*=Ay(e,e.width,e.height,i),i.__radianceConverted=!0),(e.isPointLight||e.isSpotLight)&&!i.__candelaConverted&&(e.intensity*=4*Math.PI/ky,i.__candelaConverted=!0),e.isDirectionalLight&&!i.__luxConverted&&(e.intensity/=ky,i.__luxConverted=!0);let a=e.name.startsWith(`RectAreaLightPlaceholder`);if(a&&!(i.name&&i.type===`RectAreaLight`)&&!e.parent?.name?.startsWith(`RectAreaLightPlaceholder`)&&n.push(e.name),a&&i.name&&i.type===`RectAreaLight`){let t=i.normalize??!0,n=i.shape??`rectangle`,a=i.intensity*Ay(e,i.width,i.height,i),o=new r.RectAreaLight(new r.Color(...i.color),a*this._areaLightIntensityScale(),i.width,i.height);o.userData.normalize=t,o.userData.spread=Number.isFinite(i.spread)?i.spread:Math.PI,o.userData.shape=n,o.userData.__radianceConverted=!0,o.name=i.name,e.add(o)}e.isMesh&&Array.isArray(e.material)&&t.push(e)}),n.length&&this._issues?.record(X.LIGHT_PLACEHOLDER_SKIPPED,`${n.length} area-light placeholder(s) lack userData.name or userData.type 'RectAreaLight' — no light was made for them`,{count:n.length,names:n.slice(0,10)});let i=e.userData.__rayzeeExternal===!0;for(let e of t){if(!e.parent)continue;console.log(`Found multi-material mesh:`,e.name),i&&(e.geometry=Dy(e.geometry));let t=(0,c.createMeshesFromMultiMaterialMesh)(e);for(let e of t.children)e.geometry.userData.__rayzeeOwned=!0;e.parent.add(t),e.parent.remove(e)}}async setupPathTracing(e,t){this.sceneScale=t}createFloorPlane(){this.floorPlane=new r.Mesh(new r.CircleGeometry,new r.MeshPhysicalMaterial({transparent:!1,color:3158064,roughness:1,metalness:0,opacity:0,transmission:0})),this.floorPlane.name=`Ground`,this.floorPlane.visible=!1,this.scene.add(this.floorPlane)}setFloorPlane(e){this.floorPlane=e}getSceneScale(){return this.sceneScale}getSceneSize(){return this.sceneSize.clone()}getTargetModel(){return this.targetModel}getSupportedFormats(e=null){let t={...Cy,...this._archiveFormats};for(let[e,{type:n,name:r}]of this._formats)t[e]={type:n,name:r};if(e){let n={};for(let[r,i]of Object.entries(t))i.type===e&&(n[r]=i);return n}return t}dispose(){for(let e in this.loaderCache){let t=this.loaderCache[e];t&&typeof t.dispose==`function`&&t.dispose()}this.loaderCache={},this._listeners=void 0,this._loadingManager.onError=void 0,this._issues=null,this._urlAbort?.abort(),this._urlAbort=null,this.storage=null,this._downloads=null,this.archives?.release(),this.archives=null,this._archiveLoader=null,this.releaseTargetModel()}removeAllEventListeners(){this._listeners=void 0}};function My(e,t){let{data:n,width:r,height:i}=e.image??{};if(!(n instanceof Float32Array)||r<=t||n.length!==r*i*4)return;let a=Math.ceil(r/t),o=Math.ceil(r/a),s=Math.ceil(i/a);for(let e=0;e<s;e++){let t=Math.min(i,(e+1)*a);for(let i=0;i<o;i++){let s=Math.min(r,(i+1)*a),c=0,l=0,u=0,d=0,f=0;for(let o=e*a;o<t;o++)for(let e=i*a;e<s;e++){let t=(o*r+e)*4;c+=n[t],l+=n[t+1],u+=n[t+2],d+=n[t+3],f++}let p=(e*o+i)*4;n[p]=c/f,n[p+1]=l/f,n[p+2]=u/f,n[p+3]=d/f}}let c=o*s*16;e.image={data:n.byteOffset===0&&n.byteLength===n.buffer.byteLength&&n.buffer.transfer?new Float32Array(n.buffer.transfer(c)):n.slice(0,o*s*4),width:o,height:s},e.needsUpdate=!0,Sy.info(`environment ${r}×${i} shrunk to ${o}×${s} (memory spill)`)}var Ny={addEventListener(){},removeEventListener(){},dispatchEvent(){return!0}},Py=class{constructor(e){this.canvas=e,this._configuration=null,this._texture=null}configure(e){this.unconfigure(),this._configuration=e}unconfigure(){this._texture?.destroy(),this._texture=null,this._configuration=null}getConfiguration(){return this._configuration}getCurrentTexture(){if(!this._configuration)throw Error(`HeadlessGPUContext: getCurrentTexture() before configure()`);let e=Math.max(1,this.canvas.width),t=Math.max(1,this.canvas.height);if(this._texture?.width!==e||this._texture?.height!==t){let{device:n,format:r,usage:i}=this._configuration;this._texture?.destroy(),this._texture=n.createTexture({label:`headless-canvas`,size:[e,t],format:r,usage:i})}return this._texture}};function Fy(e=1,t=1){let n={...Ny,defaultView:null},r={...Ny,isHeadlessCanvas:!0,width:e,height:t,clientWidth:0,clientHeight:0,style:{},parentNode:null,ownerDocument:n,getRootNode:()=>n,getBoundingClientRect(){return{x:0,y:0,left:0,top:0,right:this.width,bottom:this.height,width:this.width,height:this.height}},setPointerCapture(){},releasePointerCapture(){},hasPointerCapture:()=>!1,focus(){},getContext:e=>e===`webgpu`?i:null},i=new Py(r);return r}var Iy=class extends r.PerspectiveCamera{constructor(e,t,n,r){super(e,t,n,r),this.orthographic=!1,this.orthoHalfHeight=1}get isPerspectiveCamera(){return!this.orthographic}set isPerspectiveCamera(e){}get isOrthographicCamera(){return this.orthographic}get top(){return this.orthoHalfHeight}get bottom(){return-this.orthoHalfHeight}get right(){return this.orthoHalfHeight*this.aspect}get left(){return-this.orthoHalfHeight*this.aspect}updateProjectionMatrix(){this.orthographic?r.OrthographicCamera.prototype.updateProjectionMatrix.call(this):super.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.orthographic=e.orthographic===!0,this.orthoHalfHeight=e.orthoHalfHeight??this.orthoHalfHeight,this}},Ly=`__rayzeeUserLight`,Ry={DirectionalLight:r.DirectionalLight,PointLight:r.PointLight,SpotLight:r.SpotLight,RectAreaLight:r.RectAreaLight},zy=class extends r.EventDispatcher{constructor(e,t,n,r={}){super(),this.scene=e,this.sceneHelpers=t,this.pathTracer=n,this._onReset=r.onReset||null,this._onLightRemoved=r.onLightRemoved||null}addLight(e){let t={DirectionalLight:{position:[1,1,1],intensity:1,color:`#ffffff`},PointLight:{position:[0,2,0],intensity:1e3,color:`#ffffff`},SpotLight:{position:[0,1,0],intensity:1e3,color:`#ffffff`,angle:15},RectAreaLight:{position:[0,2,0],intensity:100,color:`#ffffff`,width:2,height:2}}[e];if(!t)return null;let n;if(e===`DirectionalLight`)n=new r.DirectionalLight(t.color,t.intensity),n.position.fromArray(t.position);else if(e===`PointLight`)n=new r.PointLight(t.color,t.intensity),n.position.fromArray(t.position);else if(e===`SpotLight`){n=new r.SpotLight(t.color,t.intensity),n.position.fromArray(t.position),n.angle=r.MathUtils.degToRad(t.angle);let e=new r.Object3D;this.scene.add(e),n.target=e}else e===`RectAreaLight`&&(n=new r.RectAreaLight(t.color,t.intensity,t.width,t.height),n.position.fromArray(t.position),n.lookAt(0,0,0),n.userData.normalize=!0,n.userData.spread=Math.PI,n.userData.shape=`rectangle`);n.userData[Ly]=!0,n.userData.temperature=6500,n.userData.useTemperature=!1,n.userData.exposure=0;let i=this.scene.getObjectsByProperty(`isLight`,!0).length;return n.name=`${e.replace(`Light`,``)} ${i+1}`,this.scene.add(n),this.updateLights(),this._syncHelpers(),this._onReset?.(),this._buildDescriptor(n)}getLight(e){let t=this.scene.getObjectByProperty(`uuid`,e);return t?.isLight?t:null}setIntensity(e,t){let n=this.getLight(e);return n?(n.intensity=t,this.updateLights(),this._onReset?.(),!0):!1}removeLight(e){let t=this.scene.getObjectByProperty(`uuid`,e);return!t||!t.isLight?!1:(this._onLightRemoved?.(t),this.sceneHelpers.remove(t),t.target&&t.target.removeFromParent(),t.removeFromParent(),this.updateLights(),this._onReset?.(),!0)}clearLights(){this.sceneHelpers.clear(),this._removeAllLights(),this.updateLights(),this._onReset?.()}getLights(){return this.scene.getObjectsByProperty(`isLight`,!0).map(e=>this._buildDescriptor(e))}updateLights(){this.pathTracer?.updateLights(),this.sceneHelpers?.visible&&this.sceneHelpers.update()}transferSceneLights(e,{keepUserLights:t=!1}={}){this._removeAllLights(t?e=>!e.userData?.[Ly]:void 0);let n=e.getObjectsByProperty(`isLight`,!0);if(!n||n.length===0){this.updateLights();return}for(let e of n){let t=e.clone();if(e.updateWorldMatrix(!0,!1),e.getWorldPosition(t.position),e.getWorldQuaternion(t.quaternion),e.getWorldScale(t.scale),t.isRectAreaLight&&(t.width*=t.scale.x,t.height*=t.scale.y,t.scale.set(1,1,1)),(e.isSpotLight||e.isDirectionalLight)&&e.target){let n=new r.Object3D;e.target.updateWorldMatrix(!0,!1),e.target.getWorldPosition(n.position),this.scene.add(n),t.target=n}this.scene.add(t)}this.updateLights(),this._syncHelpers()}setShowLightHelper(e){this.sceneHelpers.visible=e,e?this._syncHelpers():this.sceneHelpers.clear()}serialize(){return this.scene.getObjectsByProperty(`isLight`,!0).map(e=>{let t={type:e.type,name:e.name,visible:e.visible,color:[e.color.r,e.color.g,e.color.b],intensity:e.intensity,position:e.position.toArray(),quaternion:e.quaternion.toArray(),scale:e.scale.toArray(),userData:nr(e.userData)??{}};return e.isSpotLight&&Object.assign(t,{angle:e.angle,penumbra:e.penumbra,distance:e.distance,decay:e.decay}),e.isPointLight&&Object.assign(t,{distance:e.distance,decay:e.decay}),e.isRectAreaLight&&Object.assign(t,{width:e.width,height:e.height}),e.target&&(e.isSpotLight||e.isDirectionalLight)&&(t.target=e.target.position.toArray()),t})}restore(e){this.sceneHelpers?.clear(),this._removeAllLights();let t=[];for(let n of e??[]){let e=Ry[n.type];if(!e)continue;let i=new e;i.name=n.name??``,i.visible=n.visible!==!1,i.color.setRGB(...n.color),i.intensity=n.intensity,i.position.fromArray(n.position),i.quaternion.fromArray(n.quaternion),i.scale.fromArray(n.scale??[1,1,1]),i.userData=rr(n.userData)??{};for(let e of[`angle`,`penumbra`,`distance`,`decay`,`width`,`height`])typeof n[e]==`number`&&(i[e]=n[e]);if(n.target){let e=new r.Object3D;e.position.fromArray(n.target),this.scene.add(e),i.target=e}this.scene.add(i),t.push(i)}return this.updateLights(),this._syncHelpers(),this._onReset?.(),t}add(e){return this.addLight(e)}remove(e){return this.removeLight(e)}clear(){this.clearLights()}getAll(){return this.getLights()}sync(){this.updateLights()}showHelpers(e){this.setShowLightHelper(e)}dispose(){this._disposed||(this._disposed=!0,this._onLightRemoved=null,this.sceneHelpers?.clear(),this._removeAllLights(),this._onReset=null,this.pathTracer=null,this.sceneHelpers=null,this.scene=null)}_removeAllLights(e){this.scene.getObjectsByProperty(`isLight`,!0).filter(t=>!e||e(t)).forEach(e=>{this._onLightRemoved?.(e),e.target&&this.scene.remove(e.target),this.scene.remove(e)})}_syncHelpers(){if(!this.sceneHelpers.visible)return;let e=this.scene.getObjectsByProperty(`isLight`,!0);this.sceneHelpers.sync(e)}_buildDescriptor(e){let t=0;e.type===`SpotLight`&&e.angle!==void 0?t=r.MathUtils.radToDeg(e.angle):e.type===`DirectionalLight`&&(t=r.MathUtils.radToDeg(e.userData?.angle??0));let n={uuid:e.uuid,name:e.name,type:e.type,visible:e.visible,intensity:e.intensity,color:`#${e.color.getHexString()}`,position:[e.position.x,e.position.y,e.position.z],angle:t,temperature:e.userData?.temperature??6500,useTemperature:e.userData?.useTemperature??!1,exposure:e.userData?.exposure??0};if(e.type===`RectAreaLight`){n.width=e.width,n.height=e.height,n.normalize=e.userData?.normalize??!0,n.spread=r.MathUtils.radToDeg(e.userData?.spread??Math.PI);let t=e.userData?.shape;n.shape=t===`square`||t===`rectangle`||t===`disk`||t===`ellipse`?t:t===1?`ellipse`:`rectangle`;let i=e.getWorldDirection(e.position.clone());n.target=[e.position.x+i.x,e.position.y+i.y,e.position.z+i.z]}else e.type===`SpotLight`&&e.target?(n.target=[e.target.position.x,e.target.position.y,e.target.position.z],n.distance=e.distance??0,n.penumbra=e.penumbra??0,n.decay=e.decay??2):e.type===`PointLight`&&(n.distance=e.distance??0,n.decay=e.decay??2);return(e.type===`SpotLight`||e.type===`DirectionalLight`)&&e.userData?.gobo&&(n.gobo=e.userData.gobo.name,n.goboIntensity=e.userData.gobo.intensity,n.goboInverted=!!e.userData.gobo.inverted,e.type===`DirectionalLight`&&(n.goboScale=e.userData.gobo.scale??5)),e.type===`SpotLight`&&e.userData?.ies&&(n.ies=e.userData.ies.name,n.iesIntensity=e.userData.ies.intensity??1,n.fixtureLumens=e.userData.ies.fixtureLumens??null),n}};lt(),Ft(),qn(),de(),Ae(),F(),an(),ui(),Sv(),vs(),Do(),wc();var By=({element:e,pbrtEntry:t}={})=>({...e===void 0?{}:{element:e},...t===void 0?{}:{pbrtEntry:t}}),Vy=new WeakMap,Hy=3e4,Uy=new Set([...Object.values(N),...Object.values(P)]),Wy=new Set;async function Gy(e,t){if(!t||typeof self<`u`)return e.init();globalThis.self={requestAnimationFrame:()=>0,cancelAnimationFrame:()=>{}};try{return await e.init()}finally{delete globalThis.self}}var Ky=ve(`engine`);function qy(){let e=new Float32Array(16);return new Uint32Array(e.buffer)[3]=Tt.TRIANGLE_LEAF,e}function Jy(e,t){e.lost.then(e=>{t.app&&t.app._handleDeviceLost(e)})}var Yy=[`core-features-and-limits`,`depth-clip-control`,`depth32float-stencil8`,`texture-compression-bc`,`texture-compression-bc-sliced-3d`,`texture-compression-etc2`,`texture-compression-astc`,`texture-compression-astc-sliced-3d`,`timestamp-query`,`indirect-first-instance`,`shader-f16`,`rg11b10ufloat-renderable`,`bgra8unorm-storage`,`float32-filterable`,`float32-blendable`,`clip-distances`,`dual-source-blending`,`subgroups`,`texture-formats-tier1`,`texture-formats-tier2`],Xy=/swiftshader|llvmpipe|lavapipe|basic render|microsoft basic|warp/i;function Zy(e){let t=e.info??{},n=`${t.vendor??``} ${t.architecture??``} ${t.device??``} ${t.description??``}`;return{vendor:t.vendor??``,architecture:t.architecture??``,device:t.device??``,description:t.description??``,isSoftware:t.isFallbackAdapter===!0||e.isFallbackAdapter===!0||Xy.test(n)}}var Qy=class extends r.EventDispatcher{constructor(e,t={}){super(),this._headless=t.headless===!0||!e,e??=Fy();try{Vy.get(e)?.dispose()}catch(e){Ky.warn(`prior canvas owner dispose failed`,e)}if(Vy.set(e,this),this.canvas=e,this._autoResize=!this._headless&&t.autoResize!==!1,this._maxSceneBytes=t.maxSceneBytes,this._hostMemoryGB=t.hostMemoryGB,this._storageOption=t.storage,this._storageOpener=null,this._memorySpill=t.memorySpill===!0||t.memorySpill===!1?t.memorySpill:`auto`,this._spillPlan=null,this.storage=null,this._storageRelease=null,this._applySceneMetadataEnabled=t.applySceneMetadata!==!1,this._unlitRestore=null,this._applyingSceneMetadata=!1,t.profile!==void 0)throw Error("the `profile` option was removed: the engine has one set of defaults. For the old 'physical' profile set `areaLightIntensityScale: 1` and `dofMode: 'physical'` through `settings`.");this._issues=new rn({strict:t.strict===!0,onIssue:e=>this.dispatchEvent({type:N.ISSUE,issue:e})}),this.color=new Hv({issues:this._issues}),ei(this.color),this.settings=new jv(H,{issues:this._issues}),this.renderer=null,this.scene=null,this.meshScene=null,this._sceneHelpers=null,this.assetLoader=null,this._sdf=null,this.pipeline=null,this._pendingReservedRenderSize=null,this.stages={},this.camera=null,this.lightManager=null,this.environmentManager=null,this.isInitialized=!1,this.pauseRendering=!1,this._pathTracerEnabled=!0,this._rasterPrecompile=null,this.animationManagerId=null,this.needsReset=!1,this._loadingInProgress=!1,this._needsDisplayRefresh=!1,this._paused=!1,this._emissiveSamplingUserSet=!1,this.completion=new Y_,this._resizeDebounceTimer=null,this._displayWidth=0,this._displayHeight=0,this._renderScale=1,this._renderWidth=0,this._renderHeight=0,this._trackedListeners=[],this._disposed=!1,this._deviceLost=!1,this._gpuDevice=null,this._deviceLostHolder=null,this._deterministic=!1,this._dispatchPinned=!1,this._deterministicRestore=null,this.adapterInfo=null}_addTrackedListener(e,t,n){e&&(e.addEventListener(t,n),this._trackedListeners.push({target:e,type:t,handler:n}))}_removeTrackedListeners(){for(let{target:e,type:t,handler:n}of this._trackedListeners)try{e.removeEventListener(t,n)}catch(e){Ky.warn(`failed to remove listener`,t,e)}this._trackedListeners.length=0}async init(){let e=this._initStorage();return await this._initRenderer(),this._applyPendingReservedRenderSize(),this.camera=this._createCamera(),this._initScenes(),this._initAssetPipeline(),this._initPipeline(),await this._initManagers(),this._wireEvents(),await e,this._attachStorage(),this.stages.pathTracer.setTriangleData(new Uint32Array(K.FLOATS_PER_TRIANGLE),0),this.stages.pathTracer.setBVHData(qy()),this.stages.pathTracer.materialData.setMaterialData(new Float32Array(16)),this.stages.pathTracer.setupMaterial(),this.isInitialized=!0,Ky.debug(`WebGPU path tracer app initialized`),this}async setStorageOpener(e){this._storageOpener=e,!(!this.isInitialized||this.storage||this._disposed)&&(await this._initStorage(),this._attachStorage())}async _initStorage(){let e=this._storageOption??(this._issues.strict&&!oi(`storage`)?!1:si().storage);if(e!==!1){if(e&&typeof e==`object`)this.storage=e;else{if(!this._storageOpener){(this._storageOption!==void 0||oi(`storage`))&&this._issues.warn(X.CAPABILITY_MISSING,`on-disk storage needs rayzee/addons/storage: setStorageOpener( acquireSharedStorage )`);return}let{storage:e,reason:t,release:n}=await this._storageOpener(si().cacheNamespace);if(this._disposed){n();return}if(!e){this._issues.warn(X.STORAGE_UNAVAILABLE,`on-disk storage is off: ${t}`,{reason:t});return}this.storage=e,this._storageRelease=n}this._addTrackedListener(this.storage,`change`,e=>this.dispatchEvent({type:N.STORAGE_CHANGED,area:e.area})),this._addTrackedListener(this.storage,`issue`,e=>this._issues.warn(e.code,e.message,e.detail))}}_attachStorage(){this.assetLoader&&(this.assetLoader.storage=this.storage)}dispatchEvent(e){super.dispatchEvent(e);let t=P[e.type];t&&super.dispatchEvent({...e,type:t})}addEventListener(e,t){!Uy.has(e)&&!Wy.has(e)&&(Wy.add(e),Ky.warn(`no engine event is named "${e}", so this listener will never fire — see EngineEvents`)),super.addEventListener(e,t)}animate(){if(this._headless)throw Error(`a headless app has no render loop — drive it with renderFrames() or renderUntilComplete()`);if(this._deviceLost)return;if(this.animationManagerId=requestAnimationFrame(()=>this.animate()),this._loadingInProgress||this._sdf?.isProcessing){this.dispatchEvent({type:N.FRAME});return}this._beginFrame();let e=this.needsReset;if(this.needsReset&&=(this.stages.pathTracer?.noteViewChanged(),this.reset(!0),!1),this.camera.updateMatrixWorld(),!this.pathTracerEnabled){this.renderer.render(this.meshScene,this.camera),this._renderHelperOverlay();return}if(!this.pauseRendering){if(this._beforeTrace(),this.stages.pathTracer?.isReady){if(this.stages.pathTracer.isComplete&&this.completion.renderCompleteDispatched){if(this._needsDisplayRefresh&&(this._needsDisplayRefresh=!1,this.stages.compositor.render(this.pipeline.context),this._renderHelperOverlay()),this._settling()){this.dispatchEvent({type:N.FRAME});return}this.stopAnimation();return}if(this._holdTrace(e)){this._renderHelperOverlay(),this.dispatchEvent({type:N.FRAME});return}if(this.stages.pathTracer.readbackWait()){this.dispatchEvent({type:N.FRAME});return}this._traceFrame({liveDenoise:!0}),this.stages.pathTracer.isComplete&&this.completion.markComplete()&&this._announceComplete()}this._renderHelperOverlay(),this.dispatchEvent({type:N.FRAME})}}_announceComplete(){let e=this._completionInfo(),t=this.stages.pathTracer.resetCount,n=()=>{!this.completion.renderCompleteDispatched||this.stages.pathTracer?.resetCount!==t||(this._renderCompleted(),this.dispatchEvent({type:N.RENDER_COMPLETE,...e}))},r=this._finishImage();r?r.then(n,n):n()}_traceFrame({liveDenoise:e=!1}={}){let t=this.stages.pathTracer;this.pipeline.render(),this._afterTrace(t,e),t.isComplete||this.completion.updateTime(),this._ensureVRAMWiring();let n=t.vramTracker,r=t.frameCount??0;n&&(r<=1||r%30==0)&&n.measure(),ue({timeElapsed:this.completion.timeElapsed,samples:L(t),memoryUsed:n?.current??0,memoryPeak:n?.peak??0}),this.completion.isTimeLimitReached(t,this.settings.get(`renderLimitMode`),this.settings.get(`renderTimeLimit`))&&(t.isComplete=!0)}_completionInfo(){return{samples:this.stages.pathTracer.frameCount,timeElapsed:this.completion.timeElapsed,budgetOverrun:this.completion.budgetOverrun,reason:this.completion.stopCondition(this.stages.pathTracer)??`samples`}}stopAnimation(){this.animationManagerId&&=(cancelAnimationFrame(this.animationManagerId),null)}_handleDeviceLost(e){this._deviceLost||(this._deviceLost=!0,Ky.error(`WebGPU device lost (${e?.reason||`unknown`}): ${e?.message||``}`),this.stopAnimation(),this.dispatchEvent({type:N.DEVICE_LOST,reason:e?.reason,message:e?.message}))}wake(){this._deviceLost||this._headless||!this.animationManagerId&&this.isInitialized&&!this._paused&&this.animate()}pause(){this._paused=!0,this.stopAnimation()}resume(){this._paused=!1,!this.animationManagerId&&!this._headless&&this.animate()}reset(e=!1,{motion:t=!1}={}){t&&this.stages.pathTracer?.noteViewChanged(),this._beforeReset(e||t),this.pipeline&&(this.pipeline.reset(),e||this.pipeline.eventBus.emit(`pipeline:historyReset`)),this._afterReset(),this.completion.reset(),this.wake(),this.dispatchEvent({type:N.RENDER_RESET})}dispose(){if(this._disposed)return;if(this._disposed=!0,this.dispatchEvent({type:N.DISPOSE}),this.stopAnimation(),clearTimeout(this._resizeDebounceTimer),this._resizeDebounceTimer=null,clearTimeout(this._respillTimer),this._respillTimer=null,this._removeTrackedListeners(),I(null),this._storageRelease?.(),this._storageRelease=null,this.storage=null,this._sceneSource=this._sceneSourceInput=null,this._issues.detach(),this.color?.dispose(),this.color=null,this._pictureCopy=null,this._textureReadback?.dispose(),this._textureReadback=null,this._readbackToneMapper?.dispose(),this._readbackToneMapper=null,this._disposeExtensions(),this.lightManager?.dispose(),this.pipeline?.dispose(),this._sdf?.dispose(),this._sdf=null,this.assetLoader?.dispose(),this.assetLoader=null,this.meshScene){this.meshScene.environment?.dispose(),this.meshScene.environment=null;for(let e of[...this.meshScene.children])re(e);this.meshScene.clear(),this.meshScene=null}this._sceneHelpers?.clear(),this._sceneHelpers=null,this.scene?.clear(),this.scene=null;try{let e=(0,n.texture)().value,t=(0,n.cubeTexture)().value;e?._listeners?.dispose&&(e._listeners.dispose.length=0),t?._listeners?.dispose&&(t._listeners.dispose.length=0)}catch(e){Ky.warn(`failed to clear TSL texture singleton listeners`,e)}this.canvas&&Vy.get(this.canvas)===this&&Vy.delete(this.canvas);let e=this._gpuDevice;e&&(e.onuncapturederror=null,this._gpuDevice=null),this._deviceLostHolder&&=(this._deviceLostHolder.app=null,null),Promise.resolve(ne(this.renderer)).finally(()=>e?.destroy()),this.renderer=null,this.stages={},this.isInitialized=!1}unloadScene(){if(this.isInitialized){if(this._loadingInProgress)throw Error(`PathTracerApp.unloadScene: cannot unload while a load is in progress`);this._disposed||(this._releaseSceneState(),this.assetLoader?.releaseTargetModel(),this._sceneSource=this._sceneSourceInput=null,this.lightManager?.clearLights?.(),this.stages.pathTracer&&(this.stages.pathTracer.setTriangleData(new Uint32Array(K.FLOATS_PER_TRIANGLE),0),this.stages.pathTracer.setBVHData(qy()),this.stages.pathTracer.materialData.setMaterialData(new Float32Array(16)),this.stages.pathTracer.setEmissiveTriangleData?.(new Float32Array,0,0),this.stages.pathTracer.setupMaterial()),this._dropDisplay(),this.reset(),this.dispatchEvent({type:N.SCENE_UNLOADED}))}}async loadModel(e,t={}){await this._loadWithSceneRebuild(()=>this.assetLoader.loadModel(e,t),{type:N.MODEL_LOADED,url:e},{kind:`url`,url:e,cacheKey:t.cacheKey??null})}async loadObject3D(e,t=`object3d`){await this._loadWithSceneRebuild(()=>this.assetLoader.loadObject3D(e,t),{type:N.OBJECT3D_LOADED,name:t},{kind:`object3d`,name:t})}_busyError(e){let t=Error(`${e}: another load is already in progress`);return t.code=`LOAD_IN_PROGRESS`,t}async loadEnvironment(e){if(this._loadingInProgress)throw this._busyError(`PathTracerApp.loadEnvironment`);this._loadingInProgress=!0;try{await this.assetLoader.loadEnvironment(e);let t=this.meshScene.environment;t&&this.stages.pathTracer&&await this.stages.pathTracer.environment.setEnvironmentMap(t),this.pipeline?.eventBus.emit(`pipeline:lightingChanged`),this.reset(),this.dispatchEvent({type:N.ENVIRONMENT_LOADED,url:e})}finally{this._loadingInProgress=!1}}async inspectArchive(e){return await this.assetLoader.inspectArchive(e)}async loadFile(e,t={}){if(t=this._sceneBudgets(t),typeof e==`string`){let n=t.filename??tv(e),r=this.assetLoader?.getFileFormat(n);if(!r)throw this.assetLoader.formatError(n);if(r.type===`environment`||r.type===`image`)return this.loadEnvironment(e);await this._loadWithSceneRebuild(()=>this.assetLoader.loadAssetFromUrl(e,{...t,filename:n}),{type:N.MODEL_LOADED,filename:n},{kind:`url`,url:e,filename:n,cacheKey:t.cacheKey??null,...By(t)});return}if(Ev(e)){let n=Cv(e,{isModel:e=>this.assetLoader?.getFileFormat(e)?.type===`model`});if(n.files.length===0)throw Error(`${n.name} holds no files to load`);await this._loadWithSceneRebuild(()=>this.assetLoader.loadFolder(n,t),{type:N.MODEL_LOADED,filename:n.name},async()=>{let e=await mv(n);return{kind:`local-folder`,folder:e,key:hv(e),...n.flat?{flat:!0}:{},...By(t)}}),this._sceneSourceInput=n;return}let n=this.assetLoader?.getFileFormat(e?.name||``);if(!n)throw this.assetLoader.formatError(e?.name||``);if(n.type!==`environment`&&n.type!==`image`){let n=pv(e).catch(()=>({name:e.name,size:e.size,lastModified:e.lastModified??0,sample:null}));await this._loadWithSceneRebuild(()=>this.assetLoader.loadAssetFromFile(e,t),{type:N.MODEL_LOADED,filename:e.name},async()=>{let e=await n;return{kind:`local-file`,file:e,key:e.sample?hv(e):null,...By(t)}}),this._sceneSourceInput=e;return}if(this._loadingInProgress)throw this._busyError(`PathTracerApp.loadFile`);this._loadingInProgress=!0;try{await this.assetLoader.loadAssetFromFile(e);let t=this.meshScene.environment;t&&this.stages.pathTracer&&await this.stages.pathTracer.environment.applyHDRI(t),this.pipeline?.eventBus.emit(`pipeline:lightingChanged`),this.reset(),this.dispatchEvent({type:N.ENVIRONMENT_LOADED,filename:e.name})}finally{this._loadingInProgress=!1}}async loadExampleModels(e,t){await this._loadWithSceneRebuild(()=>this.assetLoader.loadExampleModels(e,t),{type:N.MODEL_LOADED,index:e},{kind:`url`,url:t[e]?.url??null,cacheKey:null})}cancelLoad(){this._loadingInProgress&&this.assetLoader?.cancelActiveLoad()}async setMaxTextureSize(e,{reprocess:t=!0}={}){let n=this.settings.get(`maxTextureSize`),r=this._sdf?.setMaxTextureSize(e)??e;if(this.settings.set(`maxTextureSize`,r,{reset:!1}),typeof this.stages?.pathTracer?.sdfs?.setMaxTextureSize==`function`&&this.stages.pathTracer.sdfs.setMaxTextureSize(r),t&&r!==n&&this._sdf?.triangles&&!this._loadingInProgress){this._loadingInProgress=!0;try{await this.loadSceneData(),this.reset(),this.dispatchEvent({type:N.TEXTURES_REPROCESSED,maxTextureSize:r})}finally{this._loadingInProgress=!1}}}get sceneSource(){return this._sceneSource??null}get sceneSourceFile(){return this._sceneSourceInput&&!Ev(this._sceneSourceInput)?this._sceneSourceInput:null}get sceneSourceFolder(){return Ev(this._sceneSourceInput)?this._sceneSourceInput:null}async _loadWithSceneRebuild(e,t,n=null){if(this._loadingInProgress)throw this._busyError(`PathTracerApp`);this._loadingInProgress=!0,this.assetLoader&&(this.assetLoader.maxEnvironmentWidth=this._memorySpill===!0?Co:0);try{await e(),this._sceneSource=typeof n==`function`?await n():n,this._sceneSourceInput=null,this._emissiveSamplingUserSet=!1,this._clearAppendedModels(),this._modelReplaced(),this._planSpill();let r=await this.loadSceneData({pendingEnvironment:this._beginSceneMetadataEnvironment()});this._maybeSpill(),this.pipeline?.eventBus.emit(`pipeline:lightingChanged`),this._dropDisplay(),this.reset(),this.dispatchEvent(t),this._modelAnnounced(),r&&this.assetLoader?.commitPendingGraph(this.sceneModel)}catch(e){throw(!e||e.code!==`LOAD_IN_PROGRESS`)&&this._discardFailedLoad(),e?.code===`ARCHIVE_NEEDS_ELEMENT`?le():e?.code!==`LOAD_IN_PROGRESS`&&z({status:`Error: ${e?.message??e}`,failed:!0,progress:100}),e}finally{this._loadingInProgress=!1,this._spillPlan=null}}_discardFailedLoad(){this._sceneSource=this._sceneSourceInput=null;try{this._clearAppendedModels(),this.assetLoader?.releaseTargetModel(),this._dropDisplay(),this.reset()}catch(e){console.warn(`PathTracerApp: could not clear the scene after a failed load`,e)}}get sceneMetadata(){return this.assetLoader?.sceneMetadata??null}_beginSceneMetadataEnvironment(){this._restoreUnlitSettings();let e=this.sceneMetadata?.environment;return this._applySceneMetadataEnabled&&e?.enabled===!1?(this._applyUnlitSettings(),null):!this._applySceneMetadataEnabled||!e?.sourceFile||!this.stages.pathTracer?null:(this.stages.pathTracer.environment.beginHDRI(),this._applyingSceneMetadata=!0,this.assetLoader.loadEnvironment(e.sourceFile).catch(t=>(this._issues.record(X.ENVIRONMENT_LOAD_FAILED,`authored environment "${e.sourceFile}" failed to load — lighting falls back to the previous environment`,{sourceFile:e.sourceFile,cause:String(t?.message??t)}),null)).finally(()=>{this._applyingSceneMetadata=!1}))}_applySceneMetadataSettings(e){let t=this.sceneMetadata,n=t?.environment;if(!n||n.enabled===!1)return;let r={enableEnvironment:!0,showBackground:!0,transparentBackground:!1};n.intensity!==void 0&&(r.environmentIntensity=n.intensity,r.backgroundIntensity=n.intensity),n.rotation!==void 0&&(r.environmentRotation=n.rotation),this.settings.setMany(r,{reset:!1,source:Av.SCENE_METADATA}),this.scene&&(this.scene.background=e),this.dispatchEvent({type:N.SCENE_METADATA_APPLIED,metadata:t,environment:{...n}})}_applyUnlitSettings(){let e=this.settings.getEffective(),t={enableEnvironment:!1,showBackground:!1};this._unlitRestore=Object.fromEntries(Object.keys(t).map(t=>[t,{value:e[t].value,source:e[t].source}])),this.settings.setMany(t,{reset:!1,source:Av.SCENE_METADATA}),this.dispatchEvent({type:N.SCENE_METADATA_APPLIED,metadata:this.sceneMetadata,environment:{enabled:!1}})}_restoreUnlitSettings(){let e=this._unlitRestore;if(!e)return;this._unlitRestore=null;let t=this.settings.getEffective();for(let[n,{value:r,source:i}]of Object.entries(e))t[n]?.source===Av.SCENE_METADATA&&this.settings.set(n,r,{reset:!1,source:i});this.dispatchEvent({type:N.SCENE_METADATA_APPLIED,metadata:this.sceneMetadata,environment:{enabled:this.settings.get(`enableEnvironment`)}})}async loadSceneData({pendingEnvironment:e=null,keepUserLights:t=!1}={}){this._releaseSceneState({keepSelection:!!this._preserveSelectionOnRebuild}),this._tagPrimarySceneObject();let n=new tc(``,{namespace:`scene`,level:`info`}),r=()=>this.stages.pathTracer.environment.envParams.mode===`hdri`?this.meshScene.environment:null,i=r(),a=null;if(e?(n.start(`Environment fetch + CDF (concurrent)`),a=e.then(async e=>{e&&(await this.stages.pathTracer.environment.applyHDRI(e),this._applySceneMetadataSettings(e))}).catch(e=>this._issues.record(X.ENVIRONMENT_LOAD_FAILED,`authored environment failed to install — the scene is lit by whatever was already loaded`,{cause:String(e?.message??e)})).finally(()=>n.end(`Environment fetch + CDF (concurrent)`))):i?.image?.data&&(n.start(`Environment CDF build (worker)`),this.stages.pathTracer.scene.environment=i,a=this.stages.pathTracer.environment.buildEnvironmentCDF().then(()=>{n.end(`Environment CDF build (worker)`),this._applySceneMetadataEnabled&&this._applySceneMetadataSettings(i)})),n.start(`BVH build (SceneProcessor)`),this._sdf.setMaxTextureSize(this.settings.get(`maxTextureSize`)),await this._sdf.buildBVH(this.meshScene,{sceneKey:this.assetLoader?.sceneSourceKey??null,progressive:this._progressiveSpill()}),this.assetLoader?.flushPendingGraph(this._sdf.performanceMetrics.totalProcessingTime),n.end(`BVH build (SceneProcessor)`),z({status:`Transferring data to GPU...`,progress:86}),await new Promise(e=>setTimeout(e,0)),n.start(`GPU data transfer`),await this._sdf.uploadChunks(this._chunkUploader()),!this._sdf.uploadToPathTracer(this.stages.pathTracer,this.lightManager,this.meshScene,r(),{keepUserLights:t}))return!1;for(let e of[...this._sdf.srgbBucketTextures??[],...this._sdf.linearBucketTextures??[]])e&&(this.renderer.initTexture(e),await this.stages.pathTracer.drainUploads());this.stages.pathTracer._meshRefs=this.stages.pathTracer._collectMeshRefs(this.meshScene),this.stages.pathTracer.setMeshVisibilityData(this.stages.pathTracer._meshRefs),this._refreshEmissiveForVisibility(),n.end(`GPU data transfer`),z({status:`Compiling shaders...`,progress:90}),await new Promise(e=>setTimeout(e,0)),n.start(`Material setup (TSL compile)`),this.stages.pathTracer.setupMaterial(),n.end(`Material setup (TSL compile)`),this._rasterPrecompile=null,this._pathTracerEnabled||(n.start(`Pipeline precompile`),await this.precompileRaster(),n.end(`Pipeline precompile`)),a&&(z({status:`Finalizing environment map...`,progress:95}),await a,this.stages.pathTracer.environment.applyCDFResults());let o=this.getSceneMinY();if(this.settings.set(`groundProjectionLevel`,o,{reset:!1}),this.settings.set(`groundCatcherHeight`,o,{reset:!1}),!this._emissiveSamplingUserSet){let e=(this._sdf?.emissiveTriangleBuilder?.emissiveTriangles?.length??this._sdf?.emissiveTriangleCount??0)>0;this.settings.set(`enableEmissiveTriangleSampling`,e,{reset:!1})}return n.start(`Apply settings`),this.settings.applyAll(),this.stages.compositor.setTransparentBackground(this.settings.get(`transparentBackground`)),n.end(`Apply settings`),n.print(this._sceneSummaryParts()),le(),this._sceneRebuilt(),this.dispatchEvent({type:N.SCENE_REBUILD}),!0}_sceneSummaryParts(){let e=this.stages.pathTracer,t=this._sdf?.instanceTable?.setCount??0,n=this._sdf?.geometryExtractor?.maps?.length??0;return[V.count(e.triangleCount,`tri`),t?V.count(t,`mesh`,`meshes`):null,V.count(e.materialData.materialCount,`material`),n?V.count(n,`map`):null,V.count(e.bvhNodeCount,`BVH node`)]}_tagPrimarySceneObject(){let e=this.sceneModel;e&&(e.userData.__rayzeeSceneObject=!0)}_clearAppendedModels(){let e=this.meshScene;if(!e)return;let t=this.assetLoader?.floorPlane,n=this.sceneModel;for(let r of[...e.children])r===t||r===n||r.userData?.__rayzeeSceneObject&&this.assetLoader.removeModelRoot(r)}async _finishRebuildNoReframe(e){await this.loadSceneData({keepUserLights:!0}),this._maybeSpill(),this._sceneBoundsChanged(),this.pipeline?.eventBus.emit(`pipeline:lightingChanged`),this.reset(),e&&this.dispatchEvent(e)}async addModel(e,{name:t,cacheKey:n}={}){if(this._loadingInProgress)throw Error(`PathTracerApp.addModel: another load is already in progress`);this._loadingInProgress=!0,this._preserveSelectionOnRebuild=!0;try{let{root:r}=await this.assetLoader.appendModel(e,{cacheKey:n});return r.userData.__rayzeeSceneObject=!0,r.userData.__rayzeeSourceUrl=e,n&&(r.userData.__rayzeeCacheKey=n),t&&(r.userData.__rayzeeName=t),await this._finishRebuildNoReframe({type:N.MODEL_ADDED,url:e,id:r.uuid}),r.uuid}finally{this._preserveSelectionOnRebuild=!1,this._loadingInProgress=!1}}async addModelFromObject3D(e,{name:t}={}){if(this._loadingInProgress)throw Error(`PathTracerApp.addModelFromObject3D: another load is already in progress`);this._loadingInProgress=!0,this._preserveSelectionOnRebuild=!0;try{let{root:n}=this.assetLoader.appendObject3D(e,t||`object3d`);return n.userData.__rayzeeSceneObject=!0,t&&(n.userData.__rayzeeName=t),await this._finishRebuildNoReframe({type:N.MODEL_ADDED,id:n.uuid}),n.uuid}finally{this._preserveSelectionOnRebuild=!1,this._loadingInProgress=!1}}async removeSceneObject(e){if(!this.meshScene)return!1;let t=this.assetLoader?.floorPlane;if(t&&t.uuid===e)return!1;let n=this.getSceneObject(e);if(!n)return!1;if(this._loadingInProgress)throw Error(`PathTracerApp.removeSceneObject: another load is already in progress`);this._loadingInProgress=!0;try{return this._releaseSceneState(),n===this.sceneModel?this.assetLoader.releaseTargetModel():this.assetLoader.removeModelRoot(n),await this._finishRebuildNoReframe({type:N.SCENE_OBJECT_REMOVED,id:e}),!0}finally{this._loadingInProgress=!1}}setSceneObjectVisibility(e,t){return this.setMeshVisibilityByUuid(e,t)}get memorySpill(){return this._memorySpill}setMemorySpill(e){this._memorySpill=e===!0||e===!1?e:`auto`}get sceneSpilled(){return!!this._sdf?.spilling}get geometryOnDisk(){return this._sdf?.geometryOnDisk===!0}_sceneBudgets(e){return this._memorySpill===!1||!this.storage?e:{maxTriangles:xo,maxPlacements:So,...e}}_planSpill(){let e=this._memorySpill!==!1&&!!this.storage&&(this.assetLoader?.animations?.length??0)===0&&(this._memorySpill===!0||this._sdf.needsSpill(this.meshScene));this.assetLoader&&(this.assetLoader.maxEnvironmentWidth=e?Co:0);let t=e?this.meshScene?.environment:null,n=t?.image;return n&&My(t,Co),t&&t.image!==n&&(t.dispose(),t.needsUpdate=!0),e&&this._memorySpill===`auto`&&Ky.info(`scene is past the in-memory line: building it through disk`),this._spillPlan=e,e}_progressiveSpill(){let e=this._spillPlan??this._planSpill();return this._spillPlan=null,e?{storage:this.storage,uploader:this._chunkUploader()}:null}_chunkUploader(){let e=this.stages.pathTracer;return(t,n,r)=>n===`triangles`?e.createTriangleChunkUploader(t,r):e.createChunkUploader(t)}_maybeSpill(){!this._sdf?.spilling||!this.storage||(this._sdf.spillAfterLoad().catch(e=>this._issues.warn(X.STORAGE_WRITE_FAILED,`memory spill failed: ${e.message}`)),this._sdf.spillToDisk(this.storage).then(e=>e&&this.dispatchEvent({type:N.SCENE_SPILLED,...e})).catch(e=>this._issues.warn(X.STORAGE_WRITE_FAILED,`memory spill failed: ${e.message}`)))}_scheduleRespill(){this._sdf?.spilling&&(clearTimeout(this._respillTimer),this._respillTimer=setTimeout(()=>{this._respillTimer=null,this._sdf?.respill().catch(e=>this._issues.warn(X.STORAGE_WRITE_FAILED,`memory spill failed: ${e.message}`))},Hy),this._respillTimer.unref?.())}async ensureSceneResident(){this._sdf?.spilled&&await this._sdf.ensureResident(),await this._sdf?.ensureGeometryResident()}get sceneMeshes(){return this._sdf?.meshes??[]}get sceneModel(){return this.assetLoader?.targetModel??null}getSceneObject(e){let t=this.meshScene?.children.find(t=>t.uuid===e);return t?.userData?.__rayzeeSceneObject?t:null}async refitBVH(e,t){await this.ensureSceneResident();let{triRanges:n,bvhRanges:r,...i}=await this._sdf.refitBVH(e,t);return this.stages.pathTracer.updateTriangleData(this._sdf.triangles,n),this.stages.pathTracer.updateBVHData(this._sdf.bvh,r),this.reset(!1,{motion:!0}),i}refitBLASes(e,t,n){if(this._sdf?.spilled)throw Error(`refitBLASes: the scene is spilled to disk — await app.ensureSceneResident() first`);let r=this._sdf.refitBLASes(e,t,n),{triRanges:i,bvhRanges:a}=this._sdf.computeBLASDirtyRanges(e);return this.stages.pathTracer.updateBufferRanges(i,a),this.reset(!1,{motion:!0}),this._sdf.scheduleBackgroundRebuild(e,e=>{let t=this._sdf.computeBLASDirtyRanges([e]);this.stages.pathTracer.updateBufferRanges(t.triRanges,t.bvhRanges),this.reset(!1,{motion:!0})}),r}updateMeshTransforms(e){if(this._sdf?.needsPageInForMove(e))return this._sdf.ensureMovable(e).then(()=>this.updateMeshTransforms(e)).catch(e=>this._issues.warn(X.STORAGE_READ_FAILED,`reading instance matrices back failed: ${e.message}`)),null;this._notePlacementsMoving(e);let t=this._sdf.updateMeshTransforms(e);return this.stages.pathTracer.updateBufferRanges([],this._sdf.takeMoveRanges()),this.reset(!1,{motion:!0}),this._scheduleRespill(),t}setReservedRenderResolution(e,{allowLower:t=!1}={}){let n=t?e:Math.max(e,Me);if(!this.renderer)return this._pendingReservedRenderSize={requestedPx:e,allowLower:t},Math.max(256,Math.min(je,Math.floor(n)||256));let r=this.renderer.backend?.device?.limits?.maxStorageBufferBindingSize||128*1024*1024,i=co(this._hostMemoryGB),a=i.gb>=8&&r>=1024*1024*1024?je:2048,o=Ne(Math.min(n,a));if(o<Math.floor(e)&&this._issues.warn(X.RENDER_RESERVE_CAPPED,`reserved render size ${V.n(e)}px was capped to ${V.n(o)}px by this device's limits — renders above ${V.n(o)}px will be declined`+(i.assumed&&i.gb<8?` (host memory unknown, 4 GB assumed: pass hostMemoryGB)`:``),{requested:e,applied:o,deviceMemoryGB:i.gb,assumed:i.assumed,maxStorageBufferBindingSize:r}),(this.stages?.pathTracer?.storageTextures?.writeColor?.image?.width??o)!==o){let e=this.pauseRendering;this.pauseRendering=!0;try{let e=this.renderer.domElement;(e.width>o||e.height>o)&&this.renderer.setSize(Math.min(e.width,o),Math.min(e.height,o),!1);for(let e of Object.values(this.stages))e?.reallocateReservedStorage?.()}finally{this.pauseRendering=e}this.reset(),this.dispatchEvent({type:N.RESERVED_RENDER_SIZE_CHANGED,size:o})}return o}_applyPendingReservedRenderSize(){let e=this._pendingReservedRenderSize;if(!e)return;this._pendingReservedRenderSize=null;let t=this.setReservedRenderResolution(e.requestedPx,{allowLower:e.allowLower});this.dispatchEvent({type:N.RESERVED_RENDER_SIZE_CHANGED,size:t})}getReservedRenderResolution(){return Me}_isRenderSizeSupported(e,t){return e>Me||t>Me?(this._issues.record(X.RENDER_SIZE_DECLINED,`render resolution ${e}×${t} exceeds the ${Me}px storage reserve — resize ignored, so output stays at the previous size. Raise it with setReservedRenderResolution( ${Math.max(e,t)} ) before init().`,{width:e,height:t,reserve:Me}),!1):!0}onResize(){let e=this.canvas.clientWidth,t=this.canvas.clientHeight;e===0||t===0||this._isRenderSizeSupported(e,t)&&(this.renderer.setPixelRatio(1),this._setDisplaySize(e,t),!(e===this._renderWidth&&t===this._renderHeight)&&(clearTimeout(this._resizeDebounceTimer),this._resizeDebounceTimer=setTimeout(()=>{this._applyRenderResize(e,t)},300)))}_applyRenderResize(e,t){this._isRenderSizeSupported(e,t)&&(this.pipeline?.setSize(this._scaled(e),this._scaled(t)),this._renderWidth=e,this._renderHeight=t,this._renderSizeChanged(e,t),this.needsReset=!0,this.dispatchEvent({type:N.RESOLUTION_CHANGED,width:e,height:t}))}setCanvasSize(e,t){return e===0||t===0||!this._isRenderSizeSupported(e,t)?null:(this.renderer.setPixelRatio(1),this._setDisplaySize(e,t),clearTimeout(this._resizeDebounceTimer),this._applyRenderResize(e,t),{width:e,height:t})}_scaled(e){return Math.max(1,Math.round(e*this._renderScale))}_setDisplaySize(e,t){this._displayWidth=e,this._displayHeight=t,this.renderer.setSize(this._scaled(e),this._scaled(t),!1),this.camera.aspect=e/t,this.camera.updateProjectionMatrix()}refreshFrame(){this._needsDisplayRefresh=!0,this.wake()}setDeterministicMode(e=!0,{pinDispatch:t=!0}={}){let n=this.stages.pathTracer;if(!n)return!1;if(e)this._deterministicRestore||={settings:{useAdaptiveSampling:this.settings.get(`useAdaptiveSampling`),usePixelFreeze:this.settings.get(`usePixelFreeze`),interactionModeEnabled:this.settings.get(`interactionModeEnabled`),renderLimitMode:this.settings.get(`renderLimitMode`),renderTimeLimit:this.settings.get(`renderTimeLimit`)},bounceEarlyExit:n._bounceEarlyExitThreshold,dynamicDispatch:n._useDynamicDispatch,extras:this._deterministicSnapshot()},this.settings.setMany({useAdaptiveSampling:!1,usePixelFreeze:!1,interactionModeEnabled:!1,renderLimitMode:`frames`,renderTimeLimit:0},{silent:!0}),t?(n._bounceEarlyExitThreshold=-1,n._useDynamicDispatch=!1):(n._bounceEarlyExitThreshold=this._deterministicRestore.bounceEarlyExit,n._useDynamicDispatch=this._deterministicRestore.dynamicDispatch),this._setDeterministicExtras(!0,this._deterministicRestore.extras),n._pinSeedToFrame=!0,this._deterministic=!0,this._dispatchPinned=t;else if(this._deterministicRestore){let e=this._deterministicRestore;this.settings.setMany(e.settings,{silent:!0}),n._bounceEarlyExitThreshold=e.bounceEarlyExit,n._useDynamicDispatch=e.dynamicDispatch,this._setDeterministicExtras(!1,e.extras),n._pinSeedToFrame=!1,this._deterministicRestore=null,this._deterministic=!1,this._dispatchPinned=!1}return this.reset(),this.stopAnimation(),this._deterministic}get issues(){return this._issues.list}get issueErrors(){return this._issues.errors}clearIssues(){this._issues.clear()}get isDeterministic(){return this._deterministic&&this._dispatchPinned}async renderFrames(e,{reset:t=!0,yieldEvery:n=8,onProgress:r,allowEarlyRetire:i=!1}={}){let a=this.stages.pathTracer;if(!a)throw Error(`renderFrames: app is not initialized`);if(!(e>0))throw Error(`renderFrames: count must be positive, got ${e}`);let o=(t?0:a.frameCount)+e;this.settings.get(`maxSamples`)<o&&this.settings.set(`maxSamples`,o,{silent:!0,reset:!1}),t&&this.reset(),this.stopAnimation();let s=e+64,c=0,l=!1;for(;a.frameCount<o&&c<s;){if(this._deviceLost)throw Error(`renderFrames: WebGPU device lost`);if(!a.isReady)throw Error(`renderFrames: path tracer stage is not ready`);let e=a.readbackWait();if(e){await this._awaitReadback(e);continue}if(this.camera.updateMatrixWorld(),this.pipeline.render(),c++,a.isComplete&&a.frameCount<o){l=!0;break}r?.(a.frameCount),n>0&&c%n===0&&await new Promise(e=>setTimeout(e,0))}if(a.frameCount<o&&!(l&&i)){let e=l?"adaptive sampling retired the frame at the convergence threshold — pass `allowEarlyRetire: true`, or disable it with setDeterministicMode()":`something retired the render (maxSamples, a stray reset, or a canvas resize)`;throw Error(`renderFrames: stopped at ${a.frameCount}/${o} samples after ${c} passes — ${e}`)}return await this._finishImage(),a.frameCount}async renderUntilComplete({reset:e=!0,denoise:t=!0,signal:n,drainEvery:r=4,onProgress:i}={}){let a=this.stages.pathTracer;if(!a)throw Error(`renderUntilComplete: app is not initialized`);if(this._loadingInProgress||this._sdf?.isProcessing)throw Error(`renderUntilComplete: a scene is still loading`);let o=a.lockstepReadbacks;a.setLockstepReadbacks(!0);let s=this.settings.getEffective().interactionModeEnabled;this.settings.set(`interactionModeEnabled`,!1,{silent:!0,reset:!1});try{e&&this.reset(),this.stopAnimation();let o=this.renderer.backend.device?.queue,s=0,c=null;for(;!a.isComplete;){if(n?.throwIfAborted(),this._deviceLost)throw Error(`renderUntilComplete: WebGPU device lost`);if(!a.isReady)throw Error(`renderUntilComplete: path tracer stage is not ready`);let e=a.readbackWait();if(e){await this._awaitReadback(e);continue}this.camera.updateMatrixWorld();let t=a.frameCount;if(this._traceFrame(),i?.(a.frameCount),a.frameCount===t&&!a.isComplete&&await new Promise(e=>setTimeout(e,0)),o&&r>0&&++s%r===0){let e=o.onSubmittedWorkDone();c&&await c,c=e}}let l=this._completionInfo();await this._finishImage(),this.completion.markComplete()&&this.dispatchEvent({type:N.RENDER_COMPLETE,...l});let u=t?await this._finalDenoise():!1,{reason:d,...f}=l;return{...f,retiredBy:d,denoised:u}}finally{a.setLockstepReadbacks(o),s&&this.settings.set(`interactionModeEnabled`,s.value,{silent:!0,reset:!1,source:s.source})}}getProvenance(){let e=this.stages.pathTracer,t=this.color?.status();return nr({engine:Cc,three:r.REVISION,adapter:this.adapterInfo??null,mode:{headless:this._headless,strict:this._issues.strict,deterministic:this.isDeterministic,lockstep:!!e?.accumulationLockstep},render:e?{width:e.width,height:e.height,samples:e.frameCount,complete:e.isComplete,retiredBy:e.isComplete?this.completion.stopCondition(e)??`samples`:null}:null,color:t?{config:t.config?.id??null,workingSpace:t.workingSpace,view:t.activeView??t.activeTransform?.id??null,context:t.context}:null,scene:this.sceneSource,settings:this.settings.getEffective(),issues:this.issues.map(({code:e,severity:t})=>({code:e,severity:t}))})}setLockstepReadbacks(e=!0){this.stages.pathTracer?.setLockstepReadbacks(e)}async _awaitReadback(e){let t=this.renderer.backend.device?.lost,n=await(t?Promise.race([e.then(()=>null),t]):e);if(n)throw Error(`WebGPU device lost while awaiting a readback: ${n.message??n.reason}`)}async captureRenderCheckpoint(){let e=this.stages.pathTracer;if(!e)return null;let t=await e.captureAccumulation();return{v:1,engine:Cc,savedAt:Date.now(),samples:t.state.frameCount,...t}}restoreRenderCheckpoint(e){if(e?.v!==1)throw Error(`render checkpoint version ${e?.v} is not 1`);let t=this.stages.pathTracer;if(!t)throw Error(`restoreRenderCheckpoint: app is not initialized`);t.restoreAccumulation(e),this.needsReset=!1,this.dispatchEvent({type:N.RENDER_RESET,restored:e.samples})}async renderToBuffer({colorSpace:e=`srgb`,preserveAlpha:t=!1,source:n=`accumulation`}={}){if(e!==`linear`&&e!==`srgb`&&!this.color?.hasConfig)throw Error(`renderToBuffer: colorSpace must be 'linear' or 'srgb' without a colour config loaded, got "${e}"`);let r=this.stages?.pathTracer,i=r?.storageTextures?.readTarget;if(!i)throw Error(`renderToBuffer: no render target — call init() and render at least one sample`);let{width:a,height:o}=r,s=!!this.settings.get(`transparentBackground`);if(e===`srgb`){let r=n===`display`?this._displaySource(i):null,c={exposure:this.renderer.toneMappingExposure,toneMapping:this.renderer.toneMapping,saturation:this.settings.get(`saturation`)??1,preserveAlpha:t&&s,gain:this._displayGain()},l=await this._toneMapOnGPU(r?.texture??null,i,a,o,c),u=!l&&c.gain?.cpu?await c.gain.cpu():null,d=c.gain?.backdrop??0;return{data:l??js(r?await this._readTexture(r.texture,a,o):await D_(this.renderer,i,a,o),{...c,pixelGain:u||d?{fn:u,width:a,height:o,backdrop:d}:null}),width:a,height:o,colorSpace:e,displayColorSpace:this.color?.canvasColorSpace??`srgb`,source:r?.source??`accumulation`,toneMappedOn:l?`gpu`:`cpu`}}let{data:c,source:l}=n===`display`?await this._readDisplaySource(i,a,o):{data:await D_(this.renderer,i,a,o),source:`accumulation`};if(!s){let e=c instanceof Uint16Array?15360:1;for(let t=3;t<c.length;t+=4)c[t]=e}if(e===`linear`)return{data:c,width:a,height:o,colorSpace:e,workingSpace:this.color?.workingSpace??null,source:l};let{rgba:u,colorSpace:d}=this.color.exportPixels(c,e);return{data:u,width:a,height:o,colorSpace:d,source:l}}async _toneMapOnGPU(e,t,n,r,i){let a=this.renderer?.backend;if(!a?.device)return this._toneMapFallback(`the renderer has no WebGPU device`);try{let o=e?this._readbackPass().draw(e,n,r).texture:t.textures[0],s=a.get(o).texture;return s?(this._readbackToneMapper??=new Bv(a.device,`rayzee:readback-tonemap`,{input:`texture`}),this._readbackToneMapper.ensureSize(n,r),await this._readbackToneMapper.toRGBA8(s,i)):this._toneMapFallback(`the picture has no GPU texture yet`)}catch(e){if(e instanceof nn)throw e;return this._toneMapFallback(`the GPU pass threw`,e)}finally{this._readbackToneMapper?.release(),e&&this._textureReadback?.release()}}_toneMapFallback(e,t=null){let n=t?String(t?.message??t):null,r=`renderToBuffer: tone mapped on the CPU — ${e}${n?`: ${n}`:``}`;return Ky.warn(r),this._issues.warn(X.OUTPUT_TONEMAP_FALLBACK,r,{reason:e,cause:n}),null}enableGPUTiming(e=!0){let t=this.renderer?.backend;return!t||e&&t.hasFeature?.(`timestamp-query`)!==!0?!1:(t.trackTimestamp=e,t.trackTimestamp===e)}async getGPUTimings(){let e=this.renderer;if(!e?.backend?.trackTimestamp)return null;await e.resolveTimestampsAsync(`compute`),await e.resolveTimestampsAsync(`render`);let t=e.info.compute.timestamp||0,n=e.info.render.timestamp||0;return{compute:t,render:n,total:t+n}}async getKernelGPUTimings(){let e=this.renderer;if(!e?.backend?.trackTimestamp)return null;await e.resolveTimestampsAsync(`compute`);let t=e.backend.timestampQueryPool?.compute?.timestamps;if(!t||t.size===0)return null;let n=new Map,r=this.stages?.pathTracer?._kernelManager?.kernels;if(r)for(let[e,t]of r)n.set(t.id,e);let i=[],a=-1;for(let[e,n]of t){let t=e.split(`:`);if(t.length!==4)continue;let r=Number(t[3].slice(1));Number.isFinite(r)&&(i.push({nodeId:Number(t[2]),f:r,ms:n}),r>a&&(a=r))}let o={},s=0,c=0;for(let e of i){if(e.f!==a)continue;s+=e.ms;let t=n.get(e.nodeId);t===void 0?c+=e.ms:o[t]=(o[t]??0)+e.ms}return{kernels:o,total:s,unattributed:c,frame:a}}getCanvas(){return this.renderer?.domElement?this._displayCanvas()??this._pictureCanvas():null}_pictureCanvas(){let e=this.renderer.domElement,t=this.stages.compositor,n=this.pipeline?.context;if(!t||!n||(t.renderPicture(n),!(this.renderer.backend?.parameters?.outputType===r.HalfFloatType||t.showsCanvasTransform)||this._headless||typeof document>`u`))return e;let i=e.getContext(`webgpu`)?.getConfiguration?.()?.colorSpace??`srgb`,a=this._pictureCopy;(!a||a.colorSpace!==i)&&(a=this._pictureCopy={canvas:document.createElement(`canvas`),colorSpace:i}),(a.canvas.width!==e.width||a.canvas.height!==e.height)&&(a.canvas.width=e.width,a.canvas.height=e.height);let o=a.canvas.getContext(`2d`,{colorSpace:i});return o.clearRect(0,0,e.width,e.height),o.drawImage(e,0,0),t.render(n),a.canvas}screenshot({type:e=`image/png`,quality:t}={}){let n=this.getCanvas();return n?new Promise(r=>n.toBlob(r,e,t)):Promise.resolve(null)}getStatistics(){try{return this._sdf?.getStatistics?.()??null}catch{return null}}get pathTracerEnabled(){return this._pathTracerEnabled}set pathTracerEnabled(e){this._pathTracerEnabled=e,e||this.precompileRaster()}precompileRaster(){return!this.renderer||!this.meshScene?Promise.resolve():(this._rasterPrecompile??=this.renderer.compileAsync(this.meshScene,this.camera).catch(e=>Ky.warn(`raster fallback precompile failed`,e)),this._rasterPrecompile)}get isLoading(){return this._loadingInProgress}isComplete(){return this.stages.pathTracer?.isComplete??!1}getFrameCount(){return this.stages.pathTracer?.frameCount||0}getConvergenceStats(){return this.stages.pathTracer?.getConvergenceStats?.()??null}get vram(){return this.stages.pathTracer?.vramTracker??null}getMemoryInfo(){return this._ensureVRAMWiring(),this.stages.pathTracer?.vramTracker?.measure()??{current:0,peak:0,byCategory:{}}}getHostMemoryInfo(){let e=this._sdf;return e?.memory?{preflight:e.memoryPreflight,...e.memory.report}:null}_ensureVRAMWiring(){if(this._vramWired)return;let e=this.stages.pathTracer?.vramTracker;if(!e)return;e.register(`stages`,()=>this._collectStageTextures()),this._registerVRAM(e),e.register(`canvas`,()=>[{bytes:this.canvas.width*this.canvas.height*4},...this.renderer?._frameBufferTargets?.values()??[],...this._canvasResources()]);let t=()=>e.measure();this._addTrackedListener(this,N.SCENE_REBUILD,t),this._addTrackedListener(this,N.ENVIRONMENT_LOADED,t),this._addTrackedListener(this,N.RESOLUTION_CHANGED,t),this._vramWired=!0}_collectStageTextures(){let e=[],t=this.stages||{},n=t.pathTracer;for(let r in t){let i=t[r];if(!(!i||i===n||typeof i!=`object`))for(let t in i){let n=i[t];n&&(n.isTexture||n.isRenderTarget)&&e.push(n)}}return e}getSceneMinY(){if(!this.meshScene)return 0;let e=new r.Box3().setFromObject(this.meshScene);return Number.isFinite(e.min.y)?e.min.y:0}getMaterialProperty(e,t){return this.stages.pathTracer?.materialData.getMaterialProperty(e,t)}getMaterialPropertySource(e,t){return this.stages.pathTracer?.materialData.getMaterialPropertySource(e,t)}setMaterialProperty(e,t,n){if(this._sdf?.spilled&&yr.has(t)){this.ensureSceneResident().then(()=>this.setMaterialProperty(e,t,n));return}this.stages.pathTracer?.materialData.updateMaterialProperty(e,t,n),[`emissive`,`emissiveIntensity`].includes(t)&&this._sdf&&this._uploadEmissivePayload(this._sdf.updateMaterialEmissive(e,t,n)),this.reset()}_uploadEmissivePayload(e){!e||!this.stages.pathTracer||(this.stages.pathTracer.setEmissiveTriangleData(e.rawData,e.emissiveCount,e.totalPower,e.bitTrailMap),e.lightBVHNodeData&&this.stages.pathTracer.setLightBVHData(e.lightBVHNodeData,e.lightBVHNodeCount))}_refreshEmissiveForVisibility(){let e=this._sdf?.instanceTable;if(!e)return;let t=new Set;for(let n=0;n<e.count;n++)e.isSet[n]&&!e.visible[n]&&t.add(e.sourceMesh[n]);this._uploadEmissivePayload(this._sdf.rebuildEmissiveForVisibility(t))}setEmissiveTriangleSampling(e){this._emissiveSamplingUserSet=!0,this.settings.set(`enableEmissiveTriangleSampling`,e)}hasEmissiveGeometry(){return(this._sdf?.emissiveTriangleBuilder?.emissiveTriangles?.length??this._sdf?.emissiveTriangleCount??0)>0}setMeshVisibility(e,t){this._whenTLASEditable(()=>this.stages.pathTracer?.updateMeshVisibility(e,t))}updateAllMeshVisibility(){this._whenTLASEditable(()=>this.stages.pathTracer?.updateAllMeshVisibility())}_whenTLASEditable(e){let t=()=>{e(),this._refreshEmissiveForVisibility(),this.reset(),this._scheduleRespill()},n=this._sdf?.whenTLASEditable();if(!n)return t();n.then(t).catch(e=>this._issues.warn(X.STORAGE_READ_FAILED,`reading the TLAS back failed: ${e.message}`))}getScene(){return this.meshScene||this.scene}setMeshVisibilityByUuid(e,t){let n=this.getScene()?.getObjectByProperty(`uuid`,e);if(!n)return null;let r=typeof t==`function`?!!t(n.visible):!!t;return n.visible=r,this.updateAllMeshVisibility(),r}setTextureTransform(e,t,n){this.stages.pathTracer?.materialData.updateTextureTransform(e,t,n),this.reset()}_displaySource(e){let t=this.pipeline?.context,n=t&&this.stages.compositor?.resolveLightSource(t);return n&&n.key!==`pathtracer:color`&&n.texture!==e.texture?{texture:n.texture,source:n.key.split(`:`)[0]}:(this._denoiserInUse()&&this._issues.record(X.OUTPUT_SOURCE_FALLBACK,`renderToBuffer: 'display' was asked for, but no denoiser has published a picture — returned the raw accumulation`,{requested:`display`,read:`accumulation`}),null)}async _readDisplaySource(e,t,n){let r=this._displaySource(e);return r?{data:await this._readTexture(r.texture,t,n),source:r.source}:{data:await D_(this.renderer,e,t,n),source:`accumulation`}}_readbackPass(){return this._textureReadback??=new O_(this.renderer)}_readTexture(e,t,n){return this._readbackPass().read(e,t,n)}async setTextureColorSpace(e,n){if(!e?.isTexture)throw Error(`setTextureColorSpace wants a three.js texture`);let r=e.userData??={};r.__rayzeeOriginalColorSpace===void 0&&(r.__rayzeeOriginalColorSpace=e.colorSpace);let i=r.__rayzeeOriginalColorSpace;if(delete r.ocioColorSpace,delete r.__rayzeeColorSpaceChoice,n==null)e.colorSpace=i,delete r.__rayzeeOriginalColorSpace;else if(n===`srgb`||n===`linear`)e.colorSpace=n===`srgb`?t.SRGBColorSpace:t.LinearSRGBColorSpace,r.__rayzeeColorSpaceChoice=n;else{if(!this.color?.hasConfig)throw Error(`"${n}" needs a colour config loaded`);r.ocioColorSpace=n,e.colorSpace=t.SRGBColorSpace}e.needsUpdate=!0,this.stages.pathTracer?.sdfs&&await this.rebuildMaterials()}setColorManagement(e){this.color?.dispose(),this.color=new e({issues:this._issues}),ei(this.color),this.color.on?.(`canvas`,()=>this._applyCanvasTransform()),this.renderer&&this.color.attachRenderer(this.renderer)}_applyCanvasTransform(){let e=this.stages?.compositor;e&&(e.setCanvasTransform(this.color?.canvasTransform??null),e.showsCanvasTransform||(this._pictureCopy=null),this.animationManagerId?this._needsDisplayRefresh=!0:this.pipeline?.context&&!this._deviceLost&&e.render(this.pipeline.context))}async loadColorConfig(e={}){await this._leaveColorWorkingSpace();let t=$o(this.renderer?.toneMapping),n=await this.color.loadConfig(e);return this.color.workingSpaceAdopted&&await this.applyColorWorkingSpace(),(!(t?.source===`ocio`&&$o(this.renderer?.toneMapping)===t)||this.color.workingSpaceAdopted)&&this.reset(),n}async unloadColorConfig(){await this._leaveColorWorkingSpace(),this.color.unloadConfig(),this.reset()}async _leaveColorWorkingSpace(){this.color?.workingSpaceAdopted&&(this.color.setWorkingSpace(null),await this.applyColorWorkingSpace())}async applyColorWorkingSpace(){let e=this.environmentManager?.getEnvironmentTexture?.(),t=!1;if(e&&this.color?.hasConfig)try{t=this.color.convertTexturePixels(e)}catch(e){Ky.warn(`environment colour conversion failed: ${e.message}`)}this.stages.pathTracer?.sdfs&&(await this.rebuildMaterials(),this._uploadEmissivePayload(this._sdf?.rebuildEmissiveColors?.()??null)),t&&await this.environmentManager?.buildEnvironmentCDF?.(),e?._isPhysicalSky&&await this.environmentManager.generateProceduralSkyTexture(),this.environmentManager?.refreshSun?.(),this.reset()}async rebuildMaterials(e){await this.ensureSceneResident();let t=this.stages.pathTracer;await t?.rebuildMaterials(e||this.meshScene),t?.triangleStorageNode?.withoutUV&&this._sdf?.triangles&&Rn(e||this.meshScene)&&(this._sdf.textureCoordinates=!0,t.setTriangleData(this._sdf.triangles,this._sdf.triangleCount,{textureCoordinates:!0}),t.setupMaterial()),this.reset()}async _initRenderer(){I(e=>this.dispatchEvent(e)),(typeof navigator>`u`||!navigator.gpu)&&this._issues.fail(X.WEBGPU_UNAVAILABLE,"WebGPU is not available — outside a browser, install one as navigator.gpu (for Node, the `webgpu` package)");let e=null,n;try{e=await navigator.gpu.requestAdapter({powerPreference:`high-performance`})}catch(e){n=e}e||this._issues.fail(X.ADAPTER_UNAVAILABLE,`no WebGPU adapter${n?`: `+n.message:``}`,{},n),this.adapterInfo=Zy(e),this.adapterInfo.isSoftware&&(this._issues.warn(X.ADAPTER_SOFTWARE,`software GPU adapter "${this.adapterInfo.description||this.adapterInfo.vendor}" — renders are correct but orders of magnitude slower than hardware`,{...this.adapterInfo}),Ky.warn(`software GPU adapter — check app.adapterInfo.isSoftware. ${this.adapterInfo.description}`));let r=e.limits,a={maxColorAttachmentBytesPerSample:128};for(let e of[`maxBufferSize`,`maxStorageBufferBindingSize`,`maxSampledTexturesPerShaderStage`,`maxStorageTexturesPerShaderStage`,`maxTextureArrayLayers`,`maxTextureDimension2D`,`maxComputeInvocationsPerWorkgroup`,`maxComputeWorkgroupStorageSize`,`maxComputeWorkgroupSizeX`,`maxComputeWorkgroupSizeY`,`maxComputeWorkgroupSizeZ`]){let t=r[e];t!==void 0&&(a[e]=t)}a.maxStorageBuffersPerShaderStage=Math.min(r.maxStorageBuffersPerShaderStage,10);let o;try{o=await e.requestDevice({requiredFeatures:Yy.filter(t=>e.features.has(t)),requiredLimits:a})}catch(e){this._issues.fail(X.DEVICE_UNAVAILABLE,`WebGPU device request failed: ${e.message}`,{adapter:{...this.adapterInfo}},e)}this.renderer=new t.WebGPURenderer({canvas:this.canvas,alpha:!0,device:o});try{await Gy(this.renderer,this._headless)}catch(e){throw o.destroy(),e}this.renderer.backend?.isWebGPUBackend||(o.destroy(),this._issues.fail(X.WEBGPU_UNAVAILABLE,`three.js fell back to WebGL2, which cannot run the path tracer's compute kernels. Check GPU process flags and driver support.`)),this._gpuDevice=o,o.lost&&(this._deviceLostHolder={app:this},Jy(o,this._deviceLostHolder),o.onuncapturederror=e=>Ky.error(`WebGPU uncaptured error:`,e.error)),t.RectAreaLightNode.setLTC(i.RectAreaLightTexturesLib.init()),this.renderer.outputColorSpace=t.SRGBColorSpace,this.renderer.toneMapping=_s,this.renderer.toneMappingExposure=1,this.renderer.setPixelRatio(1),this.color.attachRenderer(this.renderer)}_initScenes(){this.scene=new r.Scene,this.meshScene=new r.Scene,this._sceneHelpers=new k}_initAssetPipeline(){this._sdf=new nl({issues:this._issues,...this._maxSceneBytes===void 0?{}:{maxSceneBytes:this._maxSceneBytes}}),this.assetLoader=new jy(this.meshScene,this.camera,null,{issues:this._issues,areaLightIntensityScale:()=>this.settings.get(`areaLightIntensityScale`)}),this.assetLoader.setRenderer(this.renderer),this.assetLoader.createFloorPlane()}_initPipeline(){this._createStages();let{clientWidth:e,clientHeight:t}=this.canvas;this.pipeline=new q_(this.renderer,e||1,t||1,{issues:this._issues}),this.pipeline.addStage(this.stages.pathTracer);for(let e of this._extraStages)this.pipeline.addStage(e);this.pipeline.addStage(this.stages.compositor);let n=this.canvas.clientWidth||1,r=this.canvas.clientHeight||1;this._displayWidth=n,this._displayHeight=r,this._renderWidth=n,this._renderHeight=r,this.pipeline.setSize(n,r)}async _initManagers(){this.lightManager=new zy(this.scene,this._sceneHelpers,this.stages.pathTracer,{onReset:()=>this.reset(),onLightRemoved:e=>this._lightRemoved(e)}),this.environmentManager=this.stages.pathTracer.environment,this.environmentManager.issues=this._issues,this.stages.pathTracer.issues=this._issues,this.environmentManager.callbacks.onLightingChanged=()=>this.pipeline.eventBus.emit(`pipeline:lightingChanged`),this.environmentManager.callbacks.onReset=()=>this.reset()}_wireEvents(){this.settings.bind(this._settingsBindings()),this.renderer.toneMappingExposure=this.settings.get(`exposure`)??1,this.onResize(),this.resizeHandler=()=>this.onResize(),this._autoResize&&this._addTrackedListener(window,`resize`,this.resizeHandler),this._onAssetLoaded=async e=>{if(!this._loadingInProgress&&!(this._applyingSceneMetadata&&e.texture)){if(e.model)this._clearAppendedModels(),await this.loadSceneData({pendingEnvironment:this._beginSceneMetadataEnvironment()})&&this.assetLoader?.commitPendingGraph(e.model);else if(e.texture){let e=this.meshScene.environment;e&&this.stages.pathTracer&&await this.stages.pathTracer.environment.setEnvironmentMap(e),le()}this.pauseRendering=!1,this.reset()}},this._addTrackedListener(this.assetLoader,`load`,this._onAssetLoaded),this.pipeline.eventBus.on(`pathtracer:compiling`,({compiling:e})=>this.dispatchEvent({type:N.SHADERS_COMPILING,compiling:e}))}_createStages(){this.stages.pathTracer=new N_(this.renderer,this.scene,this.camera,{hostMemoryGB:this._hostMemoryGB,sortMaterials:this.settings.get(`wavefrontSortMaterials`)}),this._extraStages=this._createExtraStages(),this.stages.compositor=new P_(this.renderer,{saturation:this.settings.get(`saturation`)??H.saturation,pathTracer:this.stages.pathTracer,displaySources:this._displaySources(),canvasTransform:this.color?.canvasTransform??null})}_reconcileCompletion(){let e=this.stages.pathTracer;if(!e)return;let t=this.completion.isLimitReached(e,this.settings.get(`renderLimitMode`),this.settings.get(`renderTimeLimit`));t&&!e.isComplete?e.isComplete=!0:!t&&e.isComplete&&(e.isComplete=!1,this.completion.resumeFromPause(),this._completionReopened(),this.dispatchEvent({type:N.RENDER_RESET}),this.wake())}_forwardEvents(e,t){if(e)for(let n of t)this._addTrackedListener(e,n,e=>this.dispatchEvent(e))}_createCamera(){let e=new Iy(60,this.canvas.clientWidth/this.canvas.clientHeight||1,.01,1e3);return e.position.set(0,0,5),e}_createExtraStages(){return[]}_displaySources(){return[]}_settingsBindings(){return{stages:this.stages,resetCallback:()=>this.reset(),reconcileCompletion:()=>this._reconcileCompletion(),applyExposure:e=>{this.renderer.toneMappingExposure=e}}}_beginFrame(){}_beforeTrace(){}_holdTrace(){return!1}_afterTrace(){}_renderCompleted(){}_settling(){return!1}_finishImage(){return null}_renderHelperOverlay(){this.scene.updateMatrixWorld()}_beforeReset(){}_afterReset(){}_dropDisplay(){}_releaseSceneState(){}_modelReplaced(){}_modelAnnounced(){}_sceneRebuilt(){}_sceneBoundsChanged(){}_notePlacementsMoving(){}_lightRemoved(){}_renderSizeChanged(){}_completionReopened(){}async _finalDenoise(){return!1}_displayGain(){return null}_denoiserInUse(){return!1}_displayCanvas(){return null}_registerVRAM(){}_canvasResources(){return[]}_deterministicSnapshot(){return null}_setDeterministicExtras(){}_disposeExtensions(){}},$y=65504,eb=6e4,tb=Object.freeze([`none`,`nrd`,`oidn`]),nb=3,rb=.1,ib={maxAccumulatedFrameNum:30,maxFastAccumulatedFrameNum:6,maxStabilizedFrameNum:63,historyFixFrameNum:3,historyFixBasePixelStride:14,prepassBlurRadius:30,minBlurRadius:1,maxBlurRadius:30,lobeAngleFraction:.15,roughnessFraction:.15,planeDistanceSensitivity:.02,minHitDistanceWeight:.1,fastHistoryClampingSigmaScale:2,fireflySuppressorMinRelativeScale:2,enableAntiFirefly:!0,antilagLuminanceSigmaScale:2,antilagLuminanceSensitivity:3,disocclusionThreshold:.01,convergenceS:1,convergenceB:.2,convergenceP:.8,lobeVolumePercent:.1,handoverFrames:0},ab=[`maxAccumulatedFrameNum`,`maxFastAccumulatedFrameNum`,`maxStabilizedFrameNum`,`historyFixFrameNum`,`prepassBlurRadius`,`maxBlurRadius`,`enableAntiFirefly`],ob={low:{maxAccumulatedFrameNum:16,maxFastAccumulatedFrameNum:4,maxStabilizedFrameNum:16,historyFixFrameNum:2,prepassBlurRadius:0,maxBlurRadius:20,enableAntiFirefly:!1},medium:{},high:{maxAccumulatedFrameNum:45,maxFastAccumulatedFrameNum:8,historyFixFrameNum:4,prepassBlurRadius:40,maxBlurRadius:40}},sb={denoiserStrategy:`none`,enableOIDN:!1,oidnQuality:`fast`,continuousDenoise:!1,continuousDenoiseInterval:8,oidnTemporalHistory:!0,enableUpscaler:!1,upscalerScale:2,upscalerQuality:`fast`,upscalerHdr:!0,nrdQualityPreset:`medium`,nrdDebugMode:0};Dl(),xu(),pr();var cb=class extends j{constructor(e,i={}){super(`NormalDepth`,{...i,executionMode:A.ALWAYS}),this.renderer=e,this.pathTracer=i.pathTracer,this._dirty=!0,this.cameraWorldMatrix=(0,n.uniform)(new r.Matrix4,`mat4`),this.cameraProjectionMatrixInverse=(0,n.uniform)(new r.Matrix4,`mat4`),this.cameraRay=sf(),this.resolutionWidth=(0,n.uniform)(i.width||1),this.resolutionHeight=(0,n.uniform)(i.height||1);let a=i.width||1,o=i.height||1;this._outputStorageTex=new t.StorageTexture(Me,Me),this._outputStorageTex.type=r.HalfFloatType,this._outputStorageTex.format=r.RGBAFormat,this._outputStorageTex.minFilter=r.NearestFilter,this._outputStorageTex.magFilter=r.NearestFilter,this._shadingStorageTex=new t.StorageTexture(Me,Me),this._shadingStorageTex.type=r.HalfFloatType,this._shadingStorageTex.format=r.RGBAFormat,this._shadingStorageTex.minFilter=r.NearestFilter,this._shadingStorageTex.magFilter=r.NearestFilter,this._shadingRT=new t.RenderTarget(a,o,{type:r.HalfFloatType,format:r.RGBAFormat,minFilter:r.NearestFilter,magFilter:r.NearestFilter,depthBuffer:!1,stencilBuffer:!1}),this._leafStorageTex=null,this._leafRT=null,this._srcRegion=new r.Box2(new r.Vector2(0,0),new r.Vector2(0,0));let s={type:r.HalfFloatType,format:r.RGBAFormat,minFilter:r.NearestFilter,magFilter:r.NearestFilter,depthBuffer:!1,stencilBuffer:!1};this._rtA=new t.RenderTarget(a,o,s),this._rtB=new t.RenderTarget(a,o,s),this._currentIdx=0,this._hasHistory=!1,this._dispatchX=Math.ceil(a/8),this._dispatchY=Math.ceil(o/8),this._triStorageNode=null,this._bvhStorageNode=null,this._matStorageNode=null,this._lastTriAttr=null,this._lastBvhAttr=null,this._lastMatAttr=null,this._computeNode=null,this._computeBuilt=!1,this._linearBuckets=null}setupEventListeners(){this.on(`camera:moved`,()=>{this._dirty=!0}),this.on(`pipeline:reset`,()=>{this._dirty=!0})}_syncStorageBuffers(){let e=this.pathTracer;if(!e)return!1;let t=e.materialData?.materialStorageAttr,r=e.triangleGeoAttr&&e.triangleGeoAttr!==this._lastTriAttr,i=e.bvhStorageAttr&&e.bvhStorageAttr!==this._lastBvhAttr,a=t&&t!==this._lastMatAttr;if((r||i||a)&&(this._computeNode?.dispose?.(),this._computeNode=null,this._computeBuilt=!1,this._triStorageNode=null,this._bvhStorageNode=null,this._matStorageNode=null,this._dirty=!0,this._hasHistory=!1),!this._triStorageNode||!this._bvhStorageNode){let t=e.sceneStorageNodes?.();t&&(this._triStorageNode=t.triangles,this._bvhStorageNode=t.bvh)}return t&&!this._matStorageNode&&(this._matStorageNode=(0,n.storage)(t,`vec4`,t.count).toReadOnly()),this._linearBuckets&&_p(this._linearBuckets,e.materialData?.linearBuckets),this._lastTriAttr=e.triangleGeoAttr||this._lastTriAttr,this._lastBvhAttr=e.bvhStorageAttr||this._lastBvhAttr,this._lastMatAttr=t||this._lastMatAttr,!!(this._triStorageNode&&this._bvhStorageNode&&this._matStorageNode)}_buildCompute(){let e=this._triStorageNode,t=this._bvhStorageNode,r=this._matStorageNode;this._linearBuckets=gp(this.pathTracer?.materialData?.linearBuckets);let i={srgbBuckets:gp(null),linearBuckets:this._linearBuckets,shadowAlbedoMaps:null,goboMaps:null,iesProfiles:null,alphaShadows:null},a=this.cameraWorldMatrix,o=this.cameraProjectionMatrixInverse,s=this.resolutionWidth,c=this.resolutionHeight,l=this._outputStorageTex,u=this._shadingStorageTex,d=this._leafStorageTex;this._computeNode=ur((0,n.Fn)(([i,a])=>{let o=(0,n.int)(n.workgroupId.x).mul(8).add((0,n.int)(n.localId.x)),f=(0,n.int)(n.workgroupId.y).mul(8).add((0,n.int)(n.localId.y));(0,n.If)(o.lessThan((0,n.int)(s)).and(f.lessThan((0,n.int)(c))),()=>{let p=cf((0,n.vec2)((0,n.float)(o).add(.5).div(s),(0,n.float)(f).add(.5).div(c)),i,a,this.cameraRay),m=p.direction.toVar(),h=uf(m,this.cameraRay.clipStart,i,this.cameraRay.cameraProjection).toVar(),g=dl({origin:p.origin.add(m.mul(h)),direction:m}),_=gl.wrap(Lf(g,t,e)),v=_.normal.mul(.5).add(.5),y=(0,n.min)(_.dst.add(h),(0,n.float)(65504)),b=_.didHit.select((0,n.vec4)(v,y),(0,n.vec4)(0,0,0,(0,n.float)($y)));(0,n.textureStore)(l,(0,n.uvec2)((0,n.uint)(o),(0,n.uint)(f)),b).toWriteOnly(),d&&(0,n.textureStore)(d,(0,n.uvec2)((0,n.uint)(o),(0,n.uint)(f)),(0,n.uvec4)((0,n.uint)(_.instanceLeaf.add(1)),0,0,0)).toWriteOnly();let x=_.normal.toVar(),S=(0,n.float)(1).toVar();(0,n.If)(_.didHit,()=>{let i=fl.wrap(fu(_.materialIndex,r)).toVar(),a=Tl.wrap(Sp(_.uv,i)).toVar(),o=(0,n.vec4)(0).toVar();(0,n.If)(i.normalMapIndex.greaterThanEqual((0,n.int)(0)),()=>{o.assign(Ep(e,_.triangleIndex,_.normal,i.normalTransform,t,_.instanceLeaf))});let s=Op(_.normal,i,a,o).toVar();x.assign(kp(s,i,a)),S.assign(wp(i,a).y.clamp(.05,1));let c=(0,n.max)(i.emissive.x,(0,n.max)(i.emissive.y,i.emissive.z)).mul(i.emissiveIntensity).greaterThan(0);S.assign((0,n.select)(c,S.negate(),S))});let C=_.didHit.select((0,n.vec4)(x.mul(.5).add(.5),S),(0,n.vec4)(0,0,0,1));(0,n.textureStore)(u,(0,n.uvec2)((0,n.uint)(o),(0,n.uint)(f)),C).toWriteOnly()})})(a,o),i).compute([this._dispatchX,this._dispatchY,1],[8,8,1]),this._computeBuilt=!0}render(e){if(!this.enabled||!this._syncStorageBuffers())return;this._computeBuilt||this._buildCompute();let t=this.pathTracer;if(t&&(this.cameraWorldMatrix.value.copy(t.uniforms.get(`cameraWorldMatrix`).value),this.cameraProjectionMatrixInverse.value.copy(t.uniforms.get(`cameraProjectionMatrixInverse`).value),this.cameraRay.sync(t.uniforms)),!this._dirty&&this._hasHistory){let t=this._currentIdx===0?this._rtA:this._rtB;e.setTexture(`pathtracer:normalDepth`,t.texture),e.setTexture(`pathtracer:prevNormalDepth`,t.texture),e.setTexture(`pathtracer:shadingNormal`,this._shadingRT.texture),this._publishLeaf(e);return}let n=e.getTexture(`pathtracer:color`);if(n&&n.image){let e=n.image;e.width>0&&e.height>0&&(e.width!==this._rtA.width||e.height!==this._rtA.height)&&this.setSize(e.width,e.height)}this._hasHistory&&(this._currentIdx=1-this._currentIdx);let r=this._currentIdx===0?this._rtA:this._rtB,i=this._currentIdx===0?this._rtB:this._rtA;this.renderer.compute(this._computeNode),this._srcRegion.max.set(r.width,r.height),this.renderer.copyTextureToTexture(this._outputStorageTex,r.texture,this._srcRegion),this.renderer.copyTextureToTexture(this._shadingStorageTex,this._shadingRT.texture,this._srcRegion),this._leafRT&&this.renderer.copyTextureToTexture(this._leafStorageTex,this._leafRT.texture,this._srcRegion),this._hasHistory||=(this.renderer.copyTextureToTexture(this._outputStorageTex,i.texture,this._srcRegion),!0),e.setTexture(`pathtracer:normalDepth`,r.texture),e.setTexture(`pathtracer:prevNormalDepth`,i.texture),e.setTexture(`pathtracer:shadingNormal`,this._shadingRT.texture),this._publishLeaf(e),this._dirty=!1}releaseGPUMemory(){this._outputStorageTex?.dispose(),this._shadingStorageTex?.dispose(),this._leafStorageTex?.dispose(),this.reset(),this._hasHistory=!1}reset(){this._dirty=!0}setSize(e,t){this._rtA.setSize(e,t),this._rtA.texture.needsUpdate=!0,this._rtB.setSize(e,t),this._rtB.texture.needsUpdate=!0,this._shadingRT.setSize(e,t),this._shadingRT.texture.needsUpdate=!0,this._leafRT&&(this._leafRT.setSize(e,t),this._leafRT.texture.needsUpdate=!0),this._hasHistory=!1,this.resolutionWidth.value=e,this.resolutionHeight.value=t,this._dispatchX=Math.ceil(e/8),this._dispatchY=Math.ceil(t/8),this._computeNode&&(this._computeNode.dispatchSize=[this._dispatchX,this._dispatchY,1]),this._dirty=!0}reallocateReservedStorage(){this._computeNode?.dispose(),this._computeNode=null,this._outputStorageTex?.dispose(),this._shadingStorageTex?.dispose();let e=()=>{let e=new t.StorageTexture(Me,Me);return e.type=r.HalfFloatType,e.format=r.RGBAFormat,e.minFilter=r.NearestFilter,e.magFilter=r.NearestFilter,e};this._outputStorageTex=e(),this._shadingStorageTex=e(),this._leafStorageTex&&=(this._leafStorageTex.dispose(),this._makeLeafStorage()),this._computeBuilt=!1}setInstanceLeafOutput(e){e=!!e,e!==!!this._leafStorageTex&&(this._computeNode?.dispose(),this._computeNode=null,this._computeBuilt=!1,this._dirty=!0,e?(this._leafStorageTex=this._makeLeafStorage(),this._leafRT=new t.RenderTarget(this._rtA.width,this._rtA.height,{type:r.UnsignedIntType,format:r.RedIntegerFormat,minFilter:r.NearestFilter,magFilter:r.NearestFilter,depthBuffer:!1,stencilBuffer:!1})):(this._leafStorageTex.dispose(),this._leafRT.dispose(),this._leafStorageTex=null,this._leafRT=null))}_publishLeaf(e){this._leafRT?e.setTexture(`pathtracer:instanceLeaf`,this._leafRT.texture):e.getTexture(`pathtracer:instanceLeaf`)&&e.removeTexture(`pathtracer:instanceLeaf`)}_makeLeafStorage(){let e=new t.StorageTexture(Me,Me);return e.type=r.UnsignedIntType,e.format=r.RedIntegerFormat,e.minFilter=r.NearestFilter,e.magFilter=r.NearestFilter,e}dispose(){this._computeNode?.dispose(),this._outputStorageTex?.dispose(),this._shadingStorageTex?.dispose(),this._shadingRT?.dispose(),this._leafStorageTex?.dispose(),this._leafRT?.dispose(),this._rtA?.dispose(),this._rtB?.dispose()}},lb=class extends j{constructor(e,i,a={}){super(`MotionVector`,{...a,executionMode:A.ALWAYS}),this.renderer=e,this.camera=i,this.pathTracer=a.pathTracer||null;let o=a.width||1,s=a.height||1;this.prevViewProjectionMatrix=new r.Matrix4,this.currentViewProjectionMatrix=new r.Matrix4,this.matricesInitialized=!1,this.cameraWorldMatrix=(0,n.uniform)(new r.Matrix4,`mat4`),this.cameraProjectionMatrixInverse=(0,n.uniform)(new r.Matrix4,`mat4`),this.cameraRay=sf(),this.prevVP=(0,n.uniform)(new r.Matrix4,`mat4`),this.resolutionWidth=(0,n.uniform)(o),this.resolutionHeight=(0,n.uniform)(s),this._normalDepthTexNode=new t.TextureNode,this._screenSpaceStorageTex=new t.StorageTexture(Me,Me),this._screenSpaceStorageTex.type=r.HalfFloatType,this._screenSpaceStorageTex.format=r.RGBAFormat,this._screenSpaceStorageTex.minFilter=r.NearestFilter,this._screenSpaceStorageTex.magFilter=r.NearestFilter,this._srcRegion=new r.Box2(new r.Vector2(0,0),new r.Vector2(0,0)),this.screenSpaceTarget=new t.RenderTarget(o,s,{type:r.HalfFloatType,format:r.RGBAFormat,minFilter:r.NearestFilter,magFilter:r.NearestFilter,depthBuffer:!1,stencilBuffer:!1}),this._dispatchX=Math.ceil(o/16),this._dispatchY=Math.ceil(s/16),this._buildScreenSpaceCompute()}_buildScreenSpaceCompute(){let e=this._normalDepthTexNode,t=this.cameraWorldMatrix,r=this.cameraProjectionMatrixInverse,i=this.prevVP,a=this.resolutionWidth,o=this.resolutionHeight,s=this._screenSpaceStorageTex;this._screenSpaceComputeNode=(0,n.Fn)(([t,r])=>{let c=(0,n.int)(n.workgroupId.x).mul(16).add((0,n.int)(n.localId.x)),l=(0,n.int)(n.workgroupId.y).mul(16).add((0,n.int)(n.localId.y));(0,n.If)(c.lessThan((0,n.int)(a)).and(l.lessThan((0,n.int)(o))),()=>{let u=(0,n.textureLoad)(e,(0,n.ivec2)(c,l)).w,d=(0,n.vec2)((0,n.float)(c).add(.5).div(a),(0,n.float)(l).add(.5).div(o)),f=(0,n.vec4)(0,0,u,1).toVar();(0,n.If)(u.lessThan((0,n.float)(6e4)),()=>{let e=lf(d,u,t,r,this.cameraRay),a=i.mul((0,n.vec4)(e,1)),o=a.xy.div(a.w),s=(0,n.vec2)(o.x.mul(.5).add(.5),o.y.mul(-.5).add(.5)),c=d.sub(s),l=s.x.greaterThanEqual(0).and(s.x.lessThanEqual(1)).and(s.y.greaterThanEqual(0)).and(s.y.lessThanEqual(1));f.assign(l.select((0,n.vec4)(c,u,1),(0,n.vec4)((0,n.float)(1e3),(0,n.float)(1e3),u,0)))}),(0,n.textureStore)(s,(0,n.uvec2)((0,n.uint)(c),(0,n.uint)(l)),f).toWriteOnly()})})(t,r).compute([this._dispatchX,this._dispatchY,1],[16,16,1])}_updateCameraMatrices(){let e=this.pathTracer,t,n,r,i;if(e&&e.uniforms)this.cameraRay.sync(e.uniforms),t=e.uniforms.get(`cameraWorldMatrix`).value,n=e.uniforms.get(`cameraViewMatrix`).value,r=e.uniforms.get(`cameraProjectionMatrix`).value,i=e.uniforms.get(`cameraProjectionMatrixInverse`).value;else{let e=this.camera;if(!e)return;t=e.matrixWorld,n=e.matrixWorldInverse,r=e.projectionMatrix,i=e.projectionMatrixInverse}this.matricesInitialized?this.prevViewProjectionMatrix.copy(this.currentViewProjectionMatrix):(this.currentViewProjectionMatrix.multiplyMatrices(r,n),this.prevViewProjectionMatrix.copy(this.currentViewProjectionMatrix),this.matricesInitialized=!0),this.currentViewProjectionMatrix.multiplyMatrices(r,n),this.cameraWorldMatrix.value.copy(t),this.cameraProjectionMatrixInverse.value.copy(i),this.prevVP.value.copy(this.prevViewProjectionMatrix)}render(e){if(!this.enabled)return;let t=e.getTexture(`pathtracer:normalDepth`);if(!t)return;this._updateCameraMatrices();let n=t.image;n&&n.width>0&&n.height>0&&(n.width!==this.screenSpaceTarget.width||n.height!==this.screenSpaceTarget.height)&&this.setSize(n.width,n.height),this._normalDepthTexNode.value=t,this.renderer.compute(this._screenSpaceComputeNode),this._srcRegion.max.set(this.screenSpaceTarget.width,this.screenSpaceTarget.height),this.renderer.copyTextureToTexture(this._screenSpaceStorageTex,this.screenSpaceTarget.texture,this._srcRegion),e.setTexture(`motionVector:screenSpace`,this.screenSpaceTarget.texture)}releaseGPUMemory(){this._screenSpaceStorageTex?.dispose()}setSize(e,t){this.screenSpaceTarget.setSize(e,t),this.screenSpaceTarget.texture.needsUpdate=!0,this.resolutionWidth.value=e,this.resolutionHeight.value=t,this._dispatchX=Math.ceil(e/16),this._dispatchY=Math.ceil(t/16),this._screenSpaceComputeNode&&(this._screenSpaceComputeNode.dispatchSize=[this._dispatchX,this._dispatchY,1])}reallocateReservedStorage(){this._screenSpaceComputeNode?.dispose(),this._screenSpaceStorageTex?.dispose();let e=new t.StorageTexture(Me,Me);e.type=r.HalfFloatType,e.format=r.RGBAFormat,e.minFilter=r.NearestFilter,e.magFilter=r.NearestFilter,this._screenSpaceStorageTex=e,this._buildScreenSpaceCompute()}dispose(){this._screenSpaceComputeNode?.dispose(),this._screenSpaceStorageTex?.dispose(),this.screenSpaceTarget?.dispose(),this._normalDepthTexNode?.dispose()}};xu();var ub=1e-6,db=1.5/255,fb=.01,pb=3,mb=2,hb=2,gb=3,_b=2,vb=38,yb=.1,bb=4,xb=Math.cos(89*Math.PI/180),Sb=.5,Cb=.04,wb=.1*Cb,Tb=16,Eb=16,Db={pre:{radiusScale:1,fractionScale:2},blur:{radiusScale:1,fractionScale:1},post:{radiusScale:2,fractionScale:.5}},Ob=.25*Math.SQRT2,kb=[[-1,0,1],[0,1,1],[1,0,1],[0,-1,1],[-Ob,Ob,.5],[Ob,Ob,.5],[Ob,-Ob,.5],[-Ob,-Ob,.5]],Ab=(e,t,r)=>(0,n.smoothstep)(0,1,(0,n.float)(1).sub(e.mul(t).add(r).abs())),jb=(e,t,r)=>{let i=e.mul(t).add(r).abs().mul(-pb);return(0,n.float)(1).div(i.mul(i).sub(i).add(1))},Mb=e=>(0,n.mix)((0,n.float)(1.570796),(0,n.float)(1.395402),(0,n.saturate)(e)).mul((0,n.sqrt)((0,n.saturate)((0,n.float)(1).sub(e)))),Nb=(e,t)=>(0,n.float)(1).sub((0,n.exp2)(e.mul(e).mul(-200))).mul((0,n.pow)((0,n.saturate)(e),t)),Pb=(e,t)=>(0,n.saturate)(e).mul((0,n.sqrt)(t.div((0,n.float)(1).sub(t).add(ub)))),Fb=(e,t,r,i)=>{let a=(0,n.max)((0,n.atan)(Pb(r,i.mul((0,n.mix)((0,n.saturate)(t),(0,n.float)(1),e)))),(0,n.float)(db));return(0,n.float)(1).div(a)},Ib=(e,t)=>{let r=(0,n.float)(1).div((0,n.mix)((0,n.float)(fb),(0,n.float)(1),(0,n.saturate)(e.mul(t))));return(0,n.vec2)(r,e.mul(r).negate())},Lb=(e,t,r)=>{let i=(0,n.float)(1).div((0,n.mix)((0,n.float)(r),(0,n.float)(1),(0,n.mix)(e.mul(e),e,(0,n.saturate)(t))));return(0,n.vec2)(i,e.mul(i).negate())},Rb=(e,t)=>{let r=(0,n.float)(1).div(t);return(0,n.vec2)(r,e.mul(r).negate())},zb=(e,t,r,i)=>{let a=(0,n.float)(1).div(e.mul(t));return(0,n.vec2)(a,(0,n.dot)(i,r).mul(a).negate())},Bb=e=>(0,n.vec2)(1).sub((0,n.vec2)(1).sub((0,n.fract)(e.mul(.5)).mul(2)).abs()).min(.99999),Vb=e=>(0,n.vec3)((0,n.dot)(e,(0,n.vec3)(.25,.5,.25)),(0,n.dot)(e,(0,n.vec3)(.5,0,-.5)),(0,n.dot)(e,(0,n.vec3)(-.25,.5,-.25))),Hb=e=>{let t=e.x.sub(e.z);return(0,n.max)((0,n.vec3)(t.add(e.y),e.x.add(e.z),t.sub(e.y)),(0,n.vec3)(0))},Ub=(e,t)=>t.add(ub).div(e.add(ub)),Wb=(e,t)=>(0,n.vec4)(e.xyz.mul(Ub(e.x,t)),e.w),Gb=e=>(0,n.vec4)(Vb(Hb(e.xyz)),(0,n.saturate)(e.w)),Kb=(e,t)=>(0,n.sqrt)(t.sub(e.mul(e)).abs()),qb=(e,t)=>(0,n.vec2)(e.x.mul(t.x).add(e.y.mul(t.y)),e.z.mul(t.x).add(e.w.mul(t.y))),Jb=e=>e.mul(1-Cb).add(Cb),Yb=e=>(0,n.max)(e.x,(0,n.max)(e.y,e.z)).lessThan(wb),Xb=e=>e.z.greaterThan(Tb-.5),Zb=e=>e.lessThan(0),Qb=e=>e.abs().clamp(.05,1),$b=(e,t)=>(0,n.select)(e.equal(0),(0,n.vec4)(0),t);function ex(e){let t=Math.imul(e|0,2654435761)>>>0;return t^=t>>>15,t=Math.imul(t,2246822507)>>>0,t^=t>>>13,t=Math.imul(t,3266489909)>>>0,t^=t>>>16,t/4294967296}var tx=class extends j{constructor(e,i={}){super(`NRD`,{...i,executionMode:A.PER_CYCLE}),this.renderer=e,this.pathTracer=i.pathTracer||null,this.settings={...ib,...i.settings||{}},this._releaseHitDistance=this.pathTracer?.requestOutput?.(`hitDistance`,{encode:(e,t)=>e.div((0,n.max)(t.mul(.1).add(3),(0,n.float)(1e-4))).clamp(0,1)})??null;let a=i.width||1,o=i.height||1;this.resW=(0,n.uniform)(a),this.resH=(0,n.uniform)(o),this.minRectDimMulUnproject=(0,n.uniform)(1),this.inputFrames=(0,n.uniform)(0),this.resetU=(0,n.uniform)(0),this.debugMode=(0,n.uniform)(0,`int`),this.rotPre=(0,n.uniform)(new r.Vector4(1,0,0,1),`vec4`),this.rotBlur=(0,n.uniform)(new r.Vector4(1,0,0,1),`vec4`),this.rotPost=(0,n.uniform)(new r.Vector4(1,0,0,1),`vec4`),this.camWorld=(0,n.uniform)(new r.Matrix4,`mat4`),this.camProjInv=(0,n.uniform)(new r.Matrix4,`mat4`),this.camView=(0,n.uniform)(new r.Matrix4,`mat4`),this.prevCamView=(0,n.uniform)(new r.Matrix4,`mat4`),this.camPos=(0,n.uniform)(new r.Vector3,`vec3`),this.prevCamPos=(0,n.uniform)(new r.Vector3,`vec3`),this.viewVector=(0,n.uniform)(new r.Vector3,`vec3`),this.prevViewVector=(0,n.uniform)(new r.Vector3,`vec3`),this.cameraRay=sf(),this.u={};for(let e of[`maxAccum`,`maxFast`,`stabilizationStrength`,`historyFixFrameNum`,`historyFixStride`,`prepassBlurRadius`,`minBlurRadius`,`maxBlurRadius`,`lobeAngleFraction`,`roughnessFraction`,`planeDistSensitivity`,`minHitDistanceWeight`,`fastClampSigmaScale`,`fireflyMinRelativeScale`,`antiFirefly`,`disocclusionThreshold`,`lobeVolumePercent`,`handoverFrames`])this.u[e]=(0,n.uniform)(0);this.u.antilag=(0,n.uniform)(new r.Vector2,`vec2`),this.u.convergence=(0,n.uniform)(new r.Vector3,`vec3`),this._syncUniforms(),this._colorTexNode=new t.TextureNode,this._albedoTexNode=new t.TextureNode,this._ndTexNode=new t.TextureNode,this._snTexNode=new t.TextureNode,this._motionTexNode=new t.TextureNode,this._placeholders=new Map;let s=()=>{let e=new r.DataTexture(new Float32Array(4),1,1,r.RGBAFormat,r.FloatType);e.needsUpdate=!0;let n=new t.TextureNode(e);return this._placeholders.set(n,e),n};this._nTmpA=s(),this._nTmpB=s(),this._nHist=s(),this._nFast=s(),this._nInternal=s(),this._nGeom=s(),this._nData=s(),this._nStabRead=s(),this._allocStorage(),this._srcRegion=new r.Box2(new r.Vector2(0,0),new r.Vector2(0,0)),this.outputTarget=new t.RenderTarget(a,o,{type:r.HalfFloatType,format:r.RGBAFormat,minFilter:r.LinearFilter,magFilter:r.LinearFilter,depthBuffer:!1,stencilBuffer:!1}),this._compiled=!1,this._needsReset=!0,this._stabPing=0,this._camInitialized=!1,this._dispatchX=Math.ceil(a/Eb),this._dispatchY=Math.ceil(o/Eb),this._buildKernels()}_allocStorage(){let e=()=>Fe(r.HalfFloatType);this._tmpA=e(),this._tmpB=e(),this._hist=e(),this._fastHist=e(),this._internal=e(),this._geomPrev=e(),this._stabA=e(),this._stabB=e(),this._dataT=e()}_disposeStorage(){for(let e of[this._tmpA,this._tmpB,this._hist,this._fastHist,this._internal,this._geomPrev,this._stabA,this._stabB,this._dataT])e?.dispose()}_disposeKernels(){for(let e of this._kernels??[])e?.dispose()}updateParameters(e){if(e){for(let t of Object.keys(e))t===`debugMode`?this.debugMode.value=e.debugMode|0:t in ib&&(this.settings[t]=e[t]);this._syncUniforms()}}_syncUniforms(){let e=this.settings,t=this.u,n=Math.min(e.maxAccumulatedFrameNum,63),r=Math.min(e.maxStabilizedFrameNum,n),i=Math.max(e.maxBlurRadius,e.minBlurRadius);t.maxAccum.value=n,t.maxFast.value=e.maxFastAccumulatedFrameNum,t.stabilizationStrength.value=r/(1+r),t.historyFixFrameNum.value=e.historyFixFrameNum,t.historyFixStride.value=e.historyFixBasePixelStride,t.prepassBlurRadius.value=e.prepassBlurRadius,t.minBlurRadius.value=e.minBlurRadius,t.maxBlurRadius.value=i,t.lobeAngleFraction.value=e.lobeAngleFraction*e.lobeAngleFraction,t.roughnessFraction.value=e.roughnessFraction,t.planeDistSensitivity.value=e.planeDistanceSensitivity,t.minHitDistanceWeight.value=e.minHitDistanceWeight;let a=Math.min(1,Math.max(0,i/2));t.fastClampSigmaScale.value=3+(e.fastHistoryClampingSigmaScale-3)*a,t.fireflyMinRelativeScale.value=e.fireflySuppressorMinRelativeScale,t.antiFirefly.value=+!!e.enableAntiFirefly,t.antilag.value.set(e.antilagLuminanceSigmaScale,e.antilagLuminanceSensitivity),t.disocclusionThreshold.value=e.disocclusionThreshold,t.convergence.value.set(e.convergenceS,e.convergenceB,e.convergenceP),t.lobeVolumePercent.value=e.lobeVolumePercent,t.handoverFrames.value=e.handoverFrames>0?e.handoverFrames:2*n}_worldPosAt(e,t,n,r){return lf(e,t,n,r,this.cameraRay)}_viewVector(e,t,r){return(0,n.select)(of(this.cameraRay.cameraProjection),r,(0,n.normalize)(t.sub(e)))}_frustumSize(e){return this.minRectDimMulUnproject.mul((0,n.select)(of(this.cameraRay.cameraProjection),(0,n.float)(1),e))}_pixelUv(e,t){return(0,n.vec2)((0,n.float)(e).add(.5).div(this.resW),(0,n.float)(t).add(.5).div(this.resH))}_clampCoord(e,t){return(0,n.ivec2)(e.clamp((0,n.int)(0),(0,n.int)(this.resW).sub(1)),t.clamp((0,n.int)(0),(0,n.int)(this.resH).sub(1)))}_uvToCoord(e){return this._clampCoord((0,n.int)(e.x.mul(this.resW)),(0,n.int)(e.y.mul(this.resH)))}_advancedNonLinear(e){let t=this.u.convergence,r=(0,n.saturate)(e.div((0,n.float)(1).add(this.u.maxAccum.mul(t.z)))),i=t.x.mul((0,n.mix)(t.y,(0,n.float)(1),r));return(0,n.float)(1).div((0,n.float)(1).add(i.mul(e)))}_handover(e){return(0,n.saturate)(e.div((0,n.max)(this.u.handoverFrames,1)))}_excluded(e,t,n,r){return e.greaterThanEqual(eb).or(Zb(t)).or(n.and(r.not()))}_bilinear(e){let t=e.mul((0,n.vec2)(this.resW,this.resH)).sub(.5),r=(0,n.floor)(t),i=(0,n.saturate)(t.sub(r)),a=(0,n.int)(r.x),o=(0,n.int)(r.y),s=(e,t)=>(0,n.select)(e.greaterThanEqual((0,n.int)(0)).and(t.greaterThanEqual((0,n.int)(0))).and(e.lessThan((0,n.int)(this.resW))).and(t.lessThan((0,n.int)(this.resH))),(0,n.float)(1),(0,n.float)(0));return{f:i,taps:[this._clampCoord(a,o),this._clampCoord(a.add(1),o),this._clampCoord(a,o.add(1)),this._clampCoord(a.add(1),o.add(1))],inScreen:[s(a,o),s(a.add(1),o),s(a,o.add(1)),s(a.add(1),o.add(1))],customWeights:e=>[e[0].mul((0,n.float)(1).sub(i.x)).mul((0,n.float)(1).sub(i.y)),e[1].mul(i.x).mul((0,n.float)(1).sub(i.y)),e[2].mul((0,n.float)(1).sub(i.x)).mul(i.y),e[3].mul(i.x).mul(i.y)],filter:e=>(0,n.mix)((0,n.mix)(e[0],e[1],i.x),(0,n.mix)(e[2],e[3],i.x),i.y)}}_applyCustomWeights(e,t,r){let i=e[0].mul(t[0]).add(e[1].mul(t[1])).add(e[2].mul(t[2])).add(e[3].mul(t[3])),a=t[0].add(t[1]).add(t[2]).add(t[3]);return(0,n.select)(a.lessThan(1e-4),r,i.div((0,n.max)(a,1e-4)))}_sampleHistory(e,t,r,i,a){let o=(0,n.vec4)(0).toVar();return(0,n.If)(a,()=>{let r=(0,n.saturate)(t).mul((0,n.vec2)(this.resW,this.resH)),i=(0,n.floor)(r.sub(.5)).add(.5),a=(0,n.saturate)(r.sub(i)),s=Sb,c=a.mul(a.mul(a.mul(-s).add(2*s)).sub(s)),l=a.mul(a.mul(a.mul(2-s).sub(3-s))).add(1),u=a.mul(a.mul(a.mul(-(2-s)).add(3-2*s)).add(s)),d=a.mul(a.mul(a.mul(s).sub(s))),f=[c.x,l.x,u.x,d.x],p=[c.y,l.y,u.y,d.y],m=(0,n.int)(i.x).sub(1),h=(0,n.int)(i.y).sub(1),g=(0,n.vec4)(0).toVar(),_=(0,n.float)(0).toVar();for(let t=0;t<4;t++)for(let n=0;n<4;n++){if((n===0||n===3)&&(t===0||t===3))continue;let r=f[n].mul(p[t]);g.addAssign(e(this._clampCoord(m.add(n),h.add(t))).mul(r)),_.addAssign(r)}o.assign((0,n.select)(_.lessThan(1e-4),(0,n.vec4)(0),g.div((0,n.max)(_,1e-4))))}).Else(()=>{o.assign(this._applyCustomWeights(r.taps.map(t=>e(t)),i,(0,n.vec4)(0)))}),o}_buildKernels(){this._kPre=this._buildSpatial(`pre`),this._kTa=this._buildTemporalAccumulation(),this._kHf=this._buildHistoryFix(),this._kBlur=this._buildSpatial(`blur`),this._kPost=this._buildSpatial(`post`),this._kTsA=this._buildTemporalStabilization(this._stabA),this._kTsB=this._buildTemporalStabilization(this._stabB),this._kernels=[this._kPre,this._kTa,this._kHf,this._kBlur,this._kPost,this._kTsA,this._kTsB]}_dispatchOf(e){return e(this.camWorld,this.camProjInv).compute([this._dispatchX,this._dispatchY,1],[Eb,Eb,1])}_buildSpatial(e){let t=e===`pre`,{radiusScale:r,fractionScale:i}=Db[e],a=this.u,o=this._colorTexNode,s=this._albedoTexNode,c=this._ndTexNode,l=this._snTexNode,u=this._nData,d=e===`blur`?this._nTmpA:this._nTmpB,f=e===`blur`?this._tmpB:t?this._tmpA:this._hist,p=this._geomPrev,m=t?this.rotPre:e===`blur`?this.rotBlur:this.rotPost,h=t?a.prepassBlurRadius:a.maxBlurRadius,g=this.camView,_=this.camPos,v=this.resW,y=this.resH,b=this.inputFrames,x=t?(e,t)=>(0,n.vec4)(Vb(Ul((0,n.textureLoad)(o,e).xyz.div(Jb(t.xyz)))),Hl(t.w,Vl).min(1)):e=>(0,n.textureLoad)(d,e),S=(0,n.Fn)(([o,d])=>{let S=(0,n.int)(n.workgroupId.x).mul(Eb).add((0,n.int)(n.localId.x)),C=(0,n.int)(n.workgroupId.y).mul(Eb).add((0,n.int)(n.localId.y));(0,n.If)(S.lessThan((0,n.int)(v)).and(C.lessThan((0,n.int)(y))),()=>{let w=(0,n.ivec2)(S,C),T=(0,n.uvec2)((0,n.uint)(S),(0,n.uint)(C)),E=(0,n.textureLoad)(c,w).w.toVar(),D=E.greaterThanEqual(eb),O=(0,n.textureLoad)(l,w).toVar(),k=(0,n.normalize)(O.xyz.mul(2).sub(1)).toVar(),A=Qb(O.w).toVar(),j=(0,n.float)(eb).toVar(),M=t?(0,n.textureLoad)(s,w):null,N=(t?Yb(M):Xb((0,n.textureLoad)(u,w))).toVar(),P=x(w,M).toVar();(0,n.If)(D.not(),()=>{let e=this._pixelUv(S,C),f=this._worldPosAt(e,E,o,d).toVar();j.assign(g.mul((0,n.vec4)(f,1)).z.abs()),(0,n.If)(h.greaterThan(0).and(Zb(O.w).not()),()=>{let p=(0,n.dot)(k,this._viewVector(f,_,this.viewVector)).abs().toVar(),S=this._frustumSize(j).toVar(),C=b.add(1),T=t?(0,n.max)(b,(0,n.float)(10)):(0,n.textureLoad)(u,w).y.add(b),E=(t?(0,n.float)(1).div(T.add(1)):this._advancedNonLinear(T)).toVar(),D=Nb(A,.5).toVar(),O=j.mul(rb).add(3),M=P.w.toVar(),F=(0,n.saturate)(M.mul(O).div(S)),I=(0,n.float)(1).sub(this._handover(C)),L=(t?F.div(C):F.mul(E)).mul(I),ee=a.minBlurRadius.mul((0,n.saturate)((0,n.float)(2).sub(T.div((0,n.max)(a.maxAccum,1))))),te=(0,n.max)((0,n.saturate)((0,n.sqrt)((0,n.saturate)(L)).mul(r)).mul(h).mul(D),ee.mul(D)).toVar(),R=zb(a.planeDistSensitivity,S,f,k).toVar(),ne=Fb(E,a.lobeAngleFraction,A,a.lobeVolumePercent).div(i).toVar(),re=Ib(A,a.roughnessFraction.mul(i)).toVar(),ie=Rb(M,E).toVar(),ae=a.minHitDistanceWeight.mul(i).mul(D);t||(ae=ae.mul(E)),ae=ae.toVar();let oe=(0,n.vec2)(1);if(!t){let e=g.mul((0,n.vec4)(k,0)).xy;oe=(0,n.mix)((0,n.vec2)(1).sub(e.abs()),(0,n.vec2)(1),p),oe=oe.div((0,n.max)(oe.x,oe.y))}let se=oe.mul((0,n.vec2)((0,n.float)(1).div(v),(0,n.float)(1).div(y))).mul(te).toVar(),ce=(0,n.float)(1).toVar();for(let r=0;r<kb.length;r++){let i=kb[r],a=e.add(qb(m,(0,n.vec2)(i[0],i[1])).mul(se)),f=Bb(a),p=(0,n.select)(f.x.notEqual(a.x).or(f.y.notEqual(a.y)),(0,n.float)(1),(0,n.float)(Math.exp(-.66*i[2]*i[2]))).toVar(),h=this._uvToCoord(f),g=(0,n.textureLoad)(c,h).w,_=this._worldPosAt(f,g,o,d),v=(0,n.textureLoad)(l,h),y=Mb((0,n.dot)(k,(0,n.normalize)(v.xyz.mul(2).sub(1))));p.mulAssign(Ab(y,ne,(0,n.float)(0))),p.mulAssign(Ab(Qb(v.w),re.x,re.y)),p.mulAssign(Ab((0,n.dot)(k,_),R.x,R.y));let b=t?(0,n.textureLoad)(s,h):null,S=t?Yb(b):Xb((0,n.textureLoad)(u,h));p.assign((0,n.select)(this._excluded(g,v.w,S,N),(0,n.float)(0),p));let C=$b(p,x(h,b));p.mulAssign(ae.add(jb(C.w,ie.x,ie.y))),ce.addAssign(p),P.addAssign(C.mul(p))}P.divAssign((0,n.max)(ce,1e-6)),t||P.assign((0,n.vec4)(P.xyz,M))})}),(0,n.textureStore)(f,T,P).toWriteOnly(),e===`post`&&(0,n.textureStore)(p,T,(0,n.vec4)(k,j)).toWriteOnly()})});return this._dispatchOf(S)}_buildTemporalAccumulation(){let e=this.u,t=this._ndTexNode,r=this._snTexNode,i=this._motionTexNode,a=this._nTmpA,o=this._nHist,s=this._nFast,c=this._nInternal,l=this._nGeom,u=this._tmpB,d=this._dataT,f=this._albedoTexNode,p=this.camView,m=this.prevCamView,h=this.camPos,g=this.prevCamPos,_=this.resW,v=this.resH,y=this.inputFrames,b=this.resetU,x=(0,n.Fn)(([x,S])=>{let C=(0,n.int)(n.workgroupId.x).mul(Eb).add((0,n.int)(n.localId.x)),w=(0,n.int)(n.workgroupId.y).mul(Eb).add((0,n.int)(n.localId.y));(0,n.If)(C.lessThan((0,n.int)(_)).and(w.lessThan((0,n.int)(v))),()=>{let _=(0,n.ivec2)(C,w),v=(0,n.uvec2)((0,n.uint)(C),(0,n.uint)(w)),T=(0,n.textureLoad)(t,_).w,E=(0,n.textureLoad)(a,_).toVar();(0,n.If)(T.greaterThanEqual(eb),()=>{(0,n.textureStore)(u,v,E).toWriteOnly(),(0,n.textureStore)(d,v,(0,n.vec4)(0)).toWriteOnly(),(0,n.Return)()});let D=e.maxAccum.mul((0,n.float)(1).sub(b)).toVar(),O=e.maxFast.mul((0,n.float)(1).sub(b)).toVar(),k=(0,n.textureLoad)(r,_),A=(0,n.normalize)(k.xyz.mul(2).sub(1)).toVar(),j=Qb(k.w).toVar(),M=this._pixelUv(C,w),N=this._worldPosAt(M,T,x,S).toVar(),P=p.mul((0,n.vec4)(N,1)).z.abs().toVar(),F=(0,n.dot)(A,this._viewVector(N,h,this.viewVector)).abs().toVar(),I=this._frustumSize(P).toVar(),L=(0,n.vec3)(0).toVar();L.addAssign(A.mul(.25));for(let e=-1;e<=0;e++)for(let i=-1;i<=0;i++){if(i===0&&e===0)continue;let a=this._clampCoord(C.add(i),w.add(e)),o=(0,n.normalize)((0,n.textureLoad)(r,a).xyz.mul(2).sub(1)),s=(0,n.textureLoad)(t,a).w.lessThan(eb);L.addAssign((0,n.select)(s,o,A).mul(.25))}let ee=(0,n.textureLoad)(i,_),te=M.sub(ee.xy).toVar(),R=m.mul((0,n.vec4)(N,1)).z.abs().toVar(),ne=this._bilinear(te),re=I.mul((0,n.saturate)(e.disocclusionThreshold.div((0,n.max)(F,.05)))).sub(ub).toVar(),ie=(0,n.float)(1).sub(b),ae=[],oe=[];for(let e=0;e<4;e++){let t=(0,n.textureLoad)(l,ne.taps[e]),r=(0,n.select)((0,n.dot)(t.xyz,L).greaterThan(xb),(0,n.float)(1),(0,n.float)(0)),i=(0,n.select)(t.w.sub(R).abs().lessThanEqual(re),(0,n.float)(1),(0,n.float)(0)),a=(0,n.select)(t.w.lessThan(eb),(0,n.float)(1),(0,n.float)(0));ae.push(r.mul(i).mul(a).mul(ne.inScreen[e]).mul(ie).toVar()),oe.push((0,n.textureLoad)(c,ne.taps[e]).x)}let se=ne.customWeights(ae).map(e=>e.toVar()),ce=ae[0].add(ae[1]).add(ae[2]).add(ae[3]).greaterThan(3.5).toVar(),le=ae[0].add(ae[1].mul(2)).add(ae[2].mul(4)).add(ae[3].mul(8)),z=this._applyCustomWeights(oe,se,(0,n.float)(0)).toVar(),ue=(0,n.dot)(A,this._viewVector(N,g,this.prevViewVector)).abs().add(.001).div(F.add(.001)).toVar();ue.assign((0,n.mix)((0,n.float)(.1),(0,n.float)(1),(0,n.saturate)(ue.mul(ue))));let de=(0,n.sqrt)((0,n.saturate)(ne.filter(ae))).mul(ue).toVar();z.assign(z.mul((0,n.mix)(de,(0,n.float)(1),(0,n.float)(1).div(z.add(1))))),z.assign((0,n.min)(z,D));let fe=Gb(this._sampleHistory(e=>(0,n.textureLoad)(o,e),te,ne,se,ce)).toVar(),pe=(0,n.max)(this._applyCustomWeights(ne.taps.map(e=>(0,n.textureLoad)(s,e).x),se,(0,n.float)(0)),0).toVar(),me=y.add(1),he=this._handover(me).toVar(),ge=z.mul((0,n.float)(1).sub(he)),_e=me.div(me.add(ge)).toVar(),ve=(0,n.float)(1).div((0,n.float)(1).add(Nb(j,.25).mul(.5).mul(D))),ye=(0,n.vec4)((0,n.mix)(fe.xyz,E.xyz,_e),(0,n.mix)(fe.w,E.w,(0,n.max)(_e,ve))).toVar(),be=e.fireflyMinRelativeScale.add((0,n.float)(vb).div(z.add(1))).toVar(),xe=z.mul(e.maxBlurRadius).mul(yb).toVar();xe.assign(xe.div(xe.add(1)).mul((0,n.float)(1).sub(he)));let Se=(0,n.mix)(ye.x,(0,n.min)(ye.x,fe.x.mul(be)),xe);ye.assign(Wb(ye,Se));let Ce=(0,n.float)(1.2).add((0,n.float)(1).div(z.add(1)));ye.assign((0,n.vec4)(ye.xyz,(0,n.mix)(ye.w,(0,n.min)(ye.w,fe.w.mul(Ce)),xe))),(0,n.textureStore)(u,v,ye).toWriteOnly();let we=(0,n.min)(z,O).mul((0,n.float)(1).sub(he)),B=me.div(me.add(we)),Te=(0,n.mix)(pe,E.x,B).toVar(),Ee=(0,n.min)(Te,fe.x.mul(be).mul(bb));Te.assign((0,n.mix)(Te,Ee,xe));let De=(0,n.select)(Yb((0,n.textureLoad)(f,_)),(0,n.float)(Tb),(0,n.float)(0));(0,n.textureStore)(d,v,(0,n.vec4)(Te,z,le.add(De),(0,n.select)(ce,(0,n.float)(1),(0,n.float)(0)))).toWriteOnly()})});return this._dispatchOf(x)}_buildHistoryFix(){let e=this.u,t=this._ndTexNode,r=this._snTexNode,i=this._nTmpB,a=this._nData,o=this._tmpA,s=this._fastHist,c=this.camView,l=this.resW,u=this.resH,d=this.inputFrames,f=(0,n.Fn)(([f,p])=>{let m=(0,n.int)(n.workgroupId.x).mul(Eb).add((0,n.int)(n.localId.x)),h=(0,n.int)(n.workgroupId.y).mul(Eb).add((0,n.int)(n.localId.y));(0,n.If)(m.lessThan((0,n.int)(l)).and(h.lessThan((0,n.int)(u))),()=>{let g=(0,n.ivec2)(m,h),_=(0,n.uvec2)((0,n.uint)(m),(0,n.uint)(h)),v=(0,n.textureLoad)(t,g).w;(0,n.If)(v.greaterThanEqual(eb),()=>{let e=(0,n.textureLoad)(i,g);(0,n.textureStore)(o,_,e).toWriteOnly(),(0,n.textureStore)(s,_,(0,n.vec4)(e.x,0,0,0)).toWriteOnly(),(0,n.Return)()});let y=(0,n.textureLoad)(a,g).toVar(),b=y.y.toVar(),x=b.add(d),S=this._handover(d.add(1)).toVar(),C=(0,n.textureLoad)(r,g),w=(0,n.normalize)(C.xyz.mul(2).sub(1)).toVar(),T=Qb(C.w).toVar(),E=this._pixelUv(m,h),D=this._worldPosAt(E,v,f,p).toVar(),O=c.mul((0,n.vec4)(D,1)).z.abs(),k=this._frustumSize(O).toVar(),A=(0,n.textureLoad)(i,g).toVar(),j=(0,n.float)(1).div(x.add(1)).toVar(),M=O.mul(rb).add(3),N=(0,n.saturate)(A.w.mul(M).div(k)),P=A.w.toVar(),F=(0,n.round)((0,n.select)(x.lessThan(e.historyFixFrameNum),(0,n.float)(1),(0,n.float)(0)).mul(.5).mul(2/mb).mul(e.historyFixStride).mul((0,n.mix)((0,n.float)(.25).add((0,n.sqrt)(N).mul(.75)),(0,n.float)(1),j))).toVar(),I=Zb(C.w).toVar();(0,n.If)(F.notEqual(0).and(I.not()),()=>{let o=Fb(j,e.lobeAngleFraction,T,e.lobeVolumePercent).toVar(),s=zb(e.planeDistSensitivity,k,D,w).toVar(),c=Rb(P,j).toVar(),d=Lb(T.mul(T),(0,n.sqrt)(e.roughnessFraction),fb).toVar(),m=Xb(y).toVar(),h=(0,n.float)(1).add(b).toVar();A.mulAssign(h);for(let e=-mb;e<=mb;e++)for(let g=-mb;g<=mb;g++){if(g===0&&e===0||Math.abs(g)+Math.abs(e)===mb*2)continue;let _=Bb(E.add((0,n.vec2)(g,e).mul(F).mul((0,n.vec2)((0,n.float)(1).div(l),(0,n.float)(1).div(u))))),v=this._uvToCoord(_),y=(0,n.textureLoad)(t,v).w,b=this._worldPosAt(_,y,f,p),x=(0,n.textureLoad)(r,v),S=jb(Mb((0,n.dot)((0,n.normalize)(x.xyz.mul(2).sub(1)),w)),o,(0,n.float)(0)).toVar(),C=Qb(x.w);S.mulAssign(jb(C.mul(C),d.x,d.y));let T=(0,n.textureLoad)(a,v);S.mulAssign((0,n.float)(1).add(T.y)),S.mulAssign(Ab((0,n.dot)(w,b),s.x,s.y)),S.assign((0,n.select)(this._excluded(y,x.w,Xb(T),m),(0,n.float)(0),S));let D=$b(S,(0,n.textureLoad)(i,v));S.mulAssign(jb(D.w,c.x,c.y)),h.addAssign(S),A.addAssign(D.mul(S))}A.divAssign((0,n.max)(h,1e-6))});let L=A.x.toVar(),ee=(0,n.saturate)(b.div((0,n.max)(e.historyFixFrameNum,ub))),te=(0,n.mix)(L,y.x,ee).toVar();(0,n.textureStore)(s,_,(0,n.vec4)(te,0,0,0)).toWriteOnly();let R=te.toVar(),ne=te.mul(te).toVar(),re=(0,n.float)(0).toVar(),ie=(0,n.float)(0).toVar(),ae=(e,r,i)=>{let o=this._clampCoord(m.add(e),h.add(r)),s=(0,n.textureLoad)(t,o).w,c=(0,n.select)(s.greaterThanEqual(eb),te,(0,n.textureLoad)(a,o).x);Math.abs(e)<=hb&&Math.abs(r)<=hb&&(R.addAssign(c),ne.addAssign(c.mul(c))),i&&(re.addAssign(c),ie.addAssign(c.mul(c)))},oe=e.antiFirefly.greaterThan(.5);for(let e=-hb;e<=hb;e++)for(let t=-hb;t<=hb;t++)t===0&&e===0||ae(t,e,Math.abs(t)>1||Math.abs(e)>1);(0,n.If)(oe,()=>{for(let e=-gb;e<=gb;e++)for(let t=-gb;t<=gb;t++)Math.abs(t)<=hb&&Math.abs(e)<=hb||ae(t,e,!0)}),(0,n.If)(oe,()=>{let e=1/((gb*2+1)**2-9),t=re.mul(e),r=Kb(t,ie.mul(e)).mul(_b);L.assign((0,n.mix)(L.clamp(t.sub(r),t.add(r)),L,S))});{let t=1/(hb*2+1)**2,r=R.mul(t),i=Kb(r,ne.mul(t)).mul(e.fastClampSigmaScale),a=L.clamp(r.sub(i),r.add(i)),o=(0,n.select)(e.maxFast.lessThan(e.maxAccum),(0,n.float)(1),(0,n.float)(0)),s=(0,n.mix)((0,n.float)(1).div((0,n.float)(1).add(o.mul(b).mul(2))),(0,n.float)(1),S);L.assign((0,n.mix)(a,L,s))}(0,n.textureStore)(o,_,(0,n.select)(I,A,Wb(A,L))).toWriteOnly()})});return this._dispatchOf(f)}_buildTemporalStabilization(e){let t=this.u,r=this._colorTexNode,i=this._albedoTexNode,a=this._ndTexNode,o=this._snTexNode,s=this._motionTexNode,c=this._nHist,l=this._nData,u=this._nStabRead,d=this._internal,f=this._tmpA,p=this.resW,m=this.resH,h=this.inputFrames,g=this.resetU,_=this.debugMode;return(0,n.Fn)(()=>{let v=(0,n.int)(n.workgroupId.x).mul(Eb).add((0,n.int)(n.localId.x)),y=(0,n.int)(n.workgroupId.y).mul(Eb).add((0,n.int)(n.localId.y));(0,n.If)(v.lessThan((0,n.int)(p)).and(y.lessThan((0,n.int)(m))),()=>{let p=(0,n.ivec2)(v,y),m=(0,n.uvec2)((0,n.uint)(v),(0,n.uint)(y)),b=(0,n.textureLoad)(a,p).w,x=(0,n.textureLoad)(r,p).toVar();(0,n.If)(b.greaterThanEqual(eb),()=>{(0,n.textureStore)(f,m,x).toWriteOnly(),(0,n.textureStore)(e,m,(0,n.vec4)((0,n.textureLoad)(c,p).x,0,0,0)).toWriteOnly(),(0,n.textureStore)(d,m,(0,n.vec4)(0,1,0,0)).toWriteOnly(),(0,n.Return)()});let S=(0,n.textureLoad)(o,p).w,C=Qb(S),w=this._pixelUv(v,y),T=(0,n.textureLoad)(s,p),E=w.sub(T.xy).toVar(),D=(0,n.textureLoad)(l,p).toVar(),O=D.y.toVar(),k=(0,n.uint)(D.z.add(.5)).toVar(),A=D.w.greaterThan(.5),j=this._bilinear(E),M=[1,2,4,8].map(e=>(0,n.select)(k.bitAnd((0,n.uint)(e)).notEqual((0,n.uint)(0)),(0,n.float)(1),(0,n.float)(0))),N=j.customWeights(M).map(e=>e.toVar()),P=(0,n.sqrt)((0,n.saturate)(j.filter(M))).toVar(),F=(0,n.textureLoad)(c,p).toVar(),I=F.x.toVar(),L=I.toVar(),ee=I.mul(I).toVar();for(let e=-1;e<=1;e++)for(let t=-1;t<=1;t++){if(t===0&&e===0)continue;let r=this._clampCoord(v.add(t),y.add(e)),i=(0,n.textureLoad)(a,r).w,o=(0,n.select)(i.greaterThanEqual(eb),I,(0,n.textureLoad)(c,r).x);L.addAssign(o),ee.addAssign(o.mul(o))}L.divAssign(9),ee.divAssign(9);let te=Kb(L,ee).toVar();(0,n.If)(O.lessThan(t.historyFixFrameNum).and(Zb(S).not()),()=>{I.assign((0,n.min)(I,L.mul((0,n.float)(1.2).add((0,n.float)(1).div(O.add(1))))))});let R=(0,n.max)(this._sampleHistory(e=>(0,n.textureLoad)(u,e),E,j,N,A).x,0).toVar(),ne=te.mul(t.antilag.x),re=t.antilag.y.mul(4),ie=R.clamp(L.sub(ne),L.add(ne)),ae=R.sub(ie).abs().div((0,n.max)(R,ie).add(ub)),oe=(0,n.float)(1).div((0,n.float)(1).add(ae.mul(O.mul(P)).div(re))).toVar(),se=(0,n.min)(O,t.historyFixFrameNum);O.assign((0,n.mix)(se,O,oe));let ce=h.add(1),le=this._handover(ce),z=P.mul((0,n.float)(1).sub(this._advancedNonLinear(O.mul((0,n.float)(1).sub(le)).div(ce)))).mul(oe).toVar(),ue=(0,n.float)(1).add(z.mul(6)),de=t.stabilizationStrength.mul((0,n.float)(1).sub(g)),fe=(0,n.mix)(I,R.clamp(L.sub(te.mul(ue)),L.add(te.mul(ue))),(0,n.min)(z,de)).toVar();F.assign(Wb(F,fe)),(0,n.textureStore)(e,m,(0,n.vec4)(fe,0,0,0)).toWriteOnly();let pe=t.maxAccum.mul((0,n.float)(1).sub(g));(0,n.textureStore)(d,m,(0,n.vec4)((0,n.min)(O.add(1),pe),C,0,0)).toWriteOnly();let me=(0,n.textureLoad)(i,p),he=(0,n.vec4)(Hb(F.xyz).mul(Jb(me.xyz)),x.w).toVar();(0,n.If)(_.equal((0,n.int)(1)),()=>{let e=(0,n.saturate)(O.div((0,n.max)(t.maxAccum,1)));he.assign((0,n.vec4)((0,n.float)(1).sub(e),e,.2,1))}).ElseIf(_.equal((0,n.int)(2)),()=>{he.assign((0,n.vec4)((0,n.vec3)(F.w),1))}).ElseIf(_.equal((0,n.int)(3)),()=>{he.assign((0,n.vec4)((0,n.vec3)(C),1))}).ElseIf(_.equal((0,n.int)(4)),()=>{let e=D.x.div(D.x.add(1));he.assign((0,n.vec4)((0,n.vec3)(e),1))}).ElseIf(_.equal((0,n.int)(5)),()=>{he.assign((0,n.vec4)((0,n.vec3)((0,n.float)(k.bitAnd((0,n.uint)(15))).div(15)),1))}),(0,n.textureStore)(f,m,he).toWriteOnly()})})().compute([this._dispatchX,this._dispatchY,1],[Eb,Eb,1])}setupEventListeners(){this.on(`pipeline:historyReset`,()=>this.resetHistory())}resetHistory(){this._needsReset=!0}_updateCamera(){let e=this.pathTracer;if(!e?.uniforms)return;let t=e.uniforms.get(`cameraWorldMatrix`).value,n=e.uniforms.get(`cameraViewMatrix`).value,r=e.uniforms.get(`cameraProjectionMatrixInverse`).value,i=e.uniforms.get(`cameraProjectionMatrix`).value;this._camInitialized&&(this.prevCamView.value.copy(this.camView.value),this.prevCamPos.value.copy(this.camPos.value),this.prevViewVector.value.copy(this.viewVector.value)),this.camWorld.value.copy(t),this.camProjInv.value.copy(r),this.camView.value.copy(n),this.camPos.value.setFromMatrixPosition(t),this.viewVector.value.setFromMatrixColumn(t,2).normalize(),this.cameraRay.sync(e.uniforms),this._camInitialized||=(this.prevCamView.value.copy(n),this.prevCamPos.value.copy(this.camPos.value),this.prevViewVector.value.copy(this.viewVector.value),!0);let a=i.elements[5]||1,o=1/(.5*this.resH.value*a);this.minRectDimMulUnproject.value=Math.min(this.resW.value,this.resH.value)*o}_updateRotators(e){let t=(t,n)=>{let r=ex(e*3+n)*Math.PI*2;t.value.set(Math.cos(r),Math.sin(r),-Math.sin(r),Math.cos(r))};t(this.rotPre,0),t(this.rotBlur,1),t(this.rotPost,2)}render(e){if(!this.enabled)return;let t=e.getTexture(`pathtracer:color`),n=e.getTexture(`pathtracer:albedo`),r=e.getTexture(`pathtracer:normalDepth`),i=e.getTexture(`pathtracer:shadingNormal`),a=e.getTexture(`motionVector:screenSpace`);if(!t)return;if(!n||!r||!i||!a){e.setTexture(`nrd:output`,t);return}let o=t.image;o&&o.width>0&&o.height>0&&(o.width!==this.outputTarget.width||o.height!==this.outputTarget.height)&&this.setSize(o.width,o.height);let s=e.getState(`pathtracer:samples`)??this.pathTracer?.frameCount??0;if(s+1>=this.u.handoverFrames.value){e.setTexture(`nrd:output`,t),this._needsReset=!0;return}if(this._colorTexNode.value=t,this._albedoTexNode.value=n,this._ndTexNode.value=r,this._snTexNode.value=i,this._motionTexNode.value=a,this._updateCamera(),this.inputFrames.value=s,this._updateRotators(this.pathTracer?.uniforms?.get(`seedFrame`)?.value??e.getState(`frame`)??0),this.resetU.value=+!!this._needsReset,!this._compiled){for(let e of this._kernels)this.renderer.compute(e);this._compiled=!0}this._nTmpA.value=this._tmpA,this._nTmpB.value=this._tmpB,this._nHist.value=this._hist,this._nFast.value=this._fastHist,this._nInternal.value=this._internal,this._nGeom.value=this._geomPrev,this._nData.value=this._dataT,this._nStabRead.value=this._stabPing===0?this._stabB:this._stabA,this.renderer.compute(this._kPre),this.renderer.compute(this._kTa),this.renderer.compute(this._kHf),this.renderer.compute(this._kBlur),this.renderer.compute(this._kPost),this.renderer.compute(this._stabPing===0?this._kTsA:this._kTsB),this._srcRegion.max.set(this.outputTarget.width,this.outputTarget.height),this.renderer.copyTextureToTexture(this._tmpA,this.outputTarget.texture,this._srcRegion),e.setTexture(`nrd:output`,this.outputTarget.texture),this._stabPing=1-this._stabPing,this._needsReset=!1,this._needsReset=!1}setSize(e,t){this.outputTarget.setSize(e,t),this.outputTarget.texture.needsUpdate=!0,this.resW.value=e,this.resH.value=t,this._dispatchX=Math.ceil(e/Eb),this._dispatchY=Math.ceil(t/Eb);let n=[this._dispatchX,this._dispatchY,1];for(let e of this._kernels)e&&(e.dispatchSize=n);this._needsReset=!0}releaseGPUMemory(){this._disposeStorage(),this.context?.removeTexture(`nrd:output`),this.outputTarget?.texture?.dispose(),this._needsReset=!0}reallocateReservedStorage(){this._disposeKernels(),this._disposeStorage();for(let[e,t]of this._placeholders)e.value=t;this._allocStorage(),this._buildKernels(),this._compiled=!1,this._needsReset=!0,this._stabPing=0}dispose(){this._releaseHitDistance?.(),this._releaseHitDistance=null,this._disposeKernels(),this._disposeStorage(),this.outputTarget?.dispose();for(let e of[this._colorTexNode,this._albedoTexNode,this._ndTexNode,this._snTexNode,this._motionTexNode])e?.dispose();for(let[e,t]of this._placeholders)e.dispose(),t.dispose();this._placeholders.clear()}};tr();var nx={autoExposure:!1,autoExposureMetering:`center`,autoExposureStrength:.3,autoExposureKeyValue:.18,autoExposureMinExposure:2**-8,autoExposureMaxExposure:2**8,autoExposureAdaptSpeedBright:3,autoExposureAdaptSpeedDark:1},rx=[`average`,`center`,`spot`],ix=64,ax=8,ox=8,sx=256,cx=-16,lx=(12-cx)/sx,ux=2**-24,dx=65536,fx=256,px=128,mx=1.5,hx=.01,gx=.06,_x=.25,vx=4,yx=.3,bx=1.5,xx=3,Sx=[.2126,.7152,.0722],Cx=.999,wx={transparent:0,environment:1,color:2};function Tx(e,t,n,r,i){let a=t-e;if(a===0||!(n>0))return e;let o=Math.max(a<0?r:i,.001);if(n===1/0)return t;let s=Math.min(o*n,Math.abs(a)*(1-Math.exp(-o*n/mx)));return e+Math.sign(a)*s}function Ex(e,t,n){let r=Math.abs(e);return e*(r<=bx?n:r>=xx?1:n+(1-n)*(r-bx)/(xx-bx))+n*(t-e)}function Dx(e,t){if(!e)return t.fromArray(Sx);let n=new r.Matrix3().set(...e).invert().elements;return t.set(Sx[0]*n[0]+Sx[1]*n[1]+Sx[2]*n[2],Sx[0]*n[3]+Sx[1]*n[4]+Sx[2]*n[5],Sx[0]*n[6]+Sx[1]*n[7]+Sx[2]*n[8])}var Ox=e=>e<16?1:e<64?4:16,kx=class extends j{constructor(e,i={}){super(`AutoExposure`,{...i,executionMode:A.ALWAYS}),this.renderer=e,this.metering=i.metering??nx.autoExposureMetering,this.meteringPoint=new r.Vector2(.5,.5),this.keyValue=i.keyValue??nx.autoExposureKeyValue,this.minExposure=i.minExposure??nx.autoExposureMinExposure,this.maxExposure=i.maxExposure??nx.autoExposureMaxExposure,this.adaptSpeedBright=i.adaptSpeedBright??nx.autoExposureAdaptSpeedBright,this.adaptSpeedDark=i.adaptSpeedDark??nx.autoExposureAdaptSpeedDark,this.centerWeight=i.centerWeight??8,this.strength=i.strength??nx.autoExposureStrength,this.instant=!1,this.holdSamples=0,this.onChange=null,this._lowU=(0,n.uniform)(i.lowPercentile??.1),this._highU=(0,n.uniform)(i.highPercentile??.9),this._falloffU=(0,n.uniform)(new r.Vector2),this._pointU=(0,n.uniform)(new r.Vector2(.5,.5)),this._lumWeightsU=(0,n.uniform)(new r.Vector3().fromArray(Sx)),this._backdropModeU=(0,n.uniform)(wx.transparent,`int`),this._widthU=(0,n.uniform)(1,`int`),this._heightU=(0,n.uniform)(1,`int`),this._strideU=(0,n.uniform)(1,`int`),this._gridXU=(0,n.uniform)(ix,`int`),this._gridYU=(0,n.uniform)(ix,`int`),this._inputNode=new t.TextureNode,this._workingMatrix=void 0,this._histogram=(0,n.attributeArray)(sx,`uint`).toAtomic(),this._result=(0,n.attributeArray)(1,`vec4`),this._readback=new t.ReadbackBuffer(16),this._readback.name=`AutoExposure`,this._kernels=[this._buildTileKernel(),this._buildResolveKernel()],this._compensation=1,this._exposureEV=0,this._targetEV=null,this._viewEV=null,this._roomEV=null,this._clock=0,this._movingUntil=-1,this._viewMoves=0,this._landed=null,this._meteredLog2=null,this._snap=!0,this._lastUpdate=null,this._accumulating=!1,this._emittedEV=null,this._pending=null,this._generation=0,this._restarts=0,this._meteredAt={restarts:-1,samples:-1},this._stale=!1,this._disposed=!1}_buildTileKernel(){let e=this._inputNode,t=this._histogram,r=this._widthU,i=this._heightU,a=this._strideU,o=this._gridXU,s=this._gridYU,c=this._lumWeightsU,l=this._falloffU,u=this._pointU,d=this._backdropModeU;return(0,n.Fn)(()=>{let f=n.localId.y.mul((0,n.uint)(ox)).add(n.localId.x),p=(0,n.int)(n.workgroupId.x),m=(0,n.int)(n.workgroupId.y),h=p.mul(r).div(o).toVar(),g=p.add((0,n.int)(1)).mul(r).div(o).toVar(),_=m.mul(i).div(s).toVar(),v=m.add((0,n.int)(1)).mul(i).div(s).toVar(),y=a.mul((0,n.int)(ox)),b=(0,n.float)(0).toVar(),x=(0,n.float)(0).toVar();(0,n.Loop)({start:_.add((0,n.int)(n.localId.y)),end:v,type:`int`,condition:`<`,update:y,name:`py`},({py:t})=>{(0,n.Loop)({start:h.add((0,n.int)(n.localId.x)),end:g,type:`int`,condition:`<`,update:y,name:`px`},({px:r})=>{let i=(0,n.textureLoad)(e,(0,n.ivec2)(r,t)),a=(0,n.dot)(i.xyz,c).toVar(),o=(0,n.floatBitsToUint)(a).bitAnd((0,n.uint)(2139095040)).notEqual((0,n.uint)(2139095040)),s=i.w.clamp(0,1),l=(0,n.select)(d.equal((0,n.int)(wx.environment)),(0,n.float)(1),(0,n.select)(d.equal((0,n.int)(wx.color)),(0,n.select)(s.greaterThanEqual(Cx),(0,n.float)(1),(0,n.float)(0)),s));b.addAssign((0,n.select)(o,a.clamp(0,1e6),(0,n.float)(0)).mul(l)),x.addAssign(l)})});let S=(0,n.workgroupArray)(`float`,ox*ox),C=(0,n.workgroupArray)(`float`,ox*ox);S.element(f).assign(b),C.element(f).assign(x),(0,n.workgroupBarrier)();for(let e=ox*ox>>1;e>0;e>>=1)(0,n.If)(f.lessThan((0,n.uint)(e)),()=>{S.element(f).addAssign(S.element(f.add((0,n.uint)(e)))),C.element(f).addAssign(C.element(f.add((0,n.uint)(e))))}),(0,n.workgroupBarrier)();(0,n.If)(f.equal((0,n.uint)(0)),()=>{let e=S.element((0,n.uint)(0)).toVar(),a=C.element((0,n.uint)(0)).toVar(),o=e=>e.div(y).mul((0,n.int)(ox)).add((0,n.min)(e.mod(y),(0,n.int)(ox))),s=(0,n.float)(o(g.sub(h)).mul(o(v.sub(_))));(0,n.If)(a.greaterThan(0).and(e.greaterThan(a.mul(ux))),()=>{let o=(0,n.uint)((0,n.log2)(e.div(a)).sub(cx).div(lx).floor().clamp(0,sx-1)),c=(0,n.vec2)((0,n.float)(h.add(g)).div((0,n.float)(r)),(0,n.float)(_.add(v)).div((0,n.float)(i))).mul(.5).sub(u),d=(0,n.uint)((0,n.exp)((0,n.dot)(c.mul(c),l).negate()).mul(a.div((0,n.max)(s,1))).mul(dx).add(.5));(0,n.If)(d.greaterThan((0,n.uint)(0)),()=>{(0,n.atomicAdd)(t.element(o),d)})})})})().compute([ix,ix,1],[ox,ox,1])}_buildResolveKernel(){let e=this._histogram,t=this._result,r=this._lowU,i=this._highU;return(0,n.Fn)(()=>{let a=n.localId.x,o=(0,n.float)((0,n.atomicLoad)(e.element(a))).toVar();(0,n.atomicStore)(e.element(a),(0,n.uint)(0));let s=(0,n.workgroupArray)(`float`,sx),c=(0,n.workgroupArray)(`float`,sx);s.element(a).assign(o),(0,n.workgroupBarrier)();for(let e=1;e<sx;e<<=1){let t=s.element(a).toVar();(0,n.If)(a.greaterThanEqual((0,n.uint)(e)),()=>{t.addAssign(s.element(a.sub((0,n.uint)(e))))}),(0,n.workgroupBarrier)(),s.element(a).assign(t),(0,n.workgroupBarrier)()}let l=s.element((0,n.uint)(sx-1)).toVar(),u=s.element(a).toVar();(0,n.workgroupBarrier)();let d=(0,n.max)((0,n.min)(u,l.mul(i)).sub((0,n.max)(u.sub(o),l.mul(r))),0);s.element(a).assign(d),c.element(a).assign(d.mul((0,n.float)(a).add(.5).mul(lx).add(cx))),(0,n.workgroupBarrier)();for(let e=sx>>1;e>0;e>>=1)(0,n.If)(a.lessThan((0,n.uint)(e)),()=>{s.element(a).addAssign(s.element(a.add((0,n.uint)(e)))),c.element(a).addAssign(c.element(a.add((0,n.uint)(e))))}),(0,n.workgroupBarrier)();(0,n.If)(a.equal((0,n.uint)(0)),()=>{let e=s.element((0,n.uint)(0));t.element((0,n.uint)(0)).assign((0,n.vec4)(c.element((0,n.uint)(0)).div((0,n.max)(e,1e-6)),l.div(dx),e.div(dx),1))})})().compute([1,1,1],[sx,1,1])}setupEventListeners(){this.on(`pipeline:reset`,()=>this._restarts++),this.on(`pipeline:lightingChanged`,()=>this.resetHistory())}render(e){if(!this.enabled)return;let t=e.getState(`pathtracer:samples`)??0;if(this._accumulating=t>=2,!this._pending){let n=this._meteredAt,r=this._stale||this._targetEV===null||n.restarts!==this._restarts||t-n.samples>=Ox(t),i=t<this.holdSamples&&this._targetEV!==null&&!this._stale;r&&!i&&this._meter(e,t)}e.setState(`autoexposure:value`,this.renderer.toneMappingExposure),e.setState(`autoexposure:avgLuminance`,this.luminance)}async meter(e=this.context){for(;this._pending;)await this._pending;let t=this._meter(e,e?.getState(`pathtracer:samples`)??0);return t?await t:null}_meter(e,t){let n=e?.getTexture(`pathtracer:color`),r=n?.image?.width|0,i=n?.image?.height|0;if(!n||r<1||i<1||this._disposed)return null;this._meteredAt.restarts=this._restarts,this._meteredAt.samples=t,this._stale=!1;let a=Yn();a!==this._workingMatrix&&(this._workingMatrix=a,Dx(a,this._lumWeightsU.value));let o=Math.min(ix,Math.max(1,Math.floor(r/ax))),s=Math.min(ix,Math.max(1,Math.floor(i/ax))),c=r/o*(i/s);this._gridXU.value=o,this._gridYU.value=s,this._kernels[0].dispatchSize=[o,s,1],this._strideU.value=Math.max(1,Math.round(Math.sqrt(c/fx))),this._widthU.value=r,this._heightU.value=i,this._backdropModeU.value=wx[e.getState(`pathtracer:backdrop`)]??wx.transparent,this._updateMeteringPattern(r/i),this._inputNode.value=n,this.renderer.compute(this._kernels);let l=this._generation,u={restarts:this._restarts,moves:this._viewMoves},d=this.renderer.getArrayBufferAsync(this._result.value,this._readback).then(e=>{let t=e?.buffer?new Float32Array(e.buffer.slice(0,16)):null;return this._readback.release(),t&&l===this._generation&&!this._disposed?this._applyMetering(t,u):null},()=>(!this._disposed&&this._readback._mapped&&this._readback.release(),null)).finally(()=>{this._pending===d&&(this._pending=null)});return this._pending=d,d}_updateMeteringPattern(e){let t=this._falloffU.value,n=this._pointU.value;if(this.metering===`average`)t.set(0,0);else if(this.metering===`spot`){t.set(px*e*e,px),n.copy(this.meteringPoint);return}else t.set(this.centerWeight,this.centerWeight);n.set(.5,.5)}_applyMetering(e,t=this._landed){let[n,r,i]=e;if(!this.enabled||!(r>0&&i>0)||!Number.isFinite(n))return null;let a=this._viewEV;this._meteredLog2=n,this._viewEV=Math.log2(this.keyValue)-n,this._roomEV===null?this._roomEV=this._viewEV:t?.moves===this._landed?.moves?this._roomEV+=this._viewEV-a:this._movingUntil=this._clock+yx,this._landed=t;let o=this._aim(),s=this._targetEV===null||Math.abs(o-this._targetEV)>hx;return this._targetEV=o,(s||this.settling)&&this.onChange?.(),n}update(e=performance.now()){let t=this._lastUpdate===null?0:Math.min((e-this._lastUpdate)/1e3,_x),n=this.advance(t,this._accumulating);return this._lastUpdate=this.settling||this._clock<=this._movingUntil?e:null,n}advance(e,t=!1){if(!this.enabled||this._targetEV===null)return!1;e>0&&e!==1/0&&(this._clock+=e,this._clock<=this._movingUntil&&(this._roomEV+=(this._viewEV-this._roomEV)*(1-Math.exp(-Math.min(e,_x)/vx)),this._targetEV=this._aim()));let n=this._exposureEV;return this._snap||this.instant?(this._exposureEV=this._targetEV,this._snap=!1):(this._exposureEV=t?n+(this._targetEV-n)*(1-Math.exp(-e/gx)):Tx(n,this._targetEV,e,this.adaptSpeedBright,this.adaptSpeedDark),Math.abs(this._targetEV-this._exposureEV)<=hx&&(this._exposureEV=this._targetEV)),this._exposureEV===n?!1:(this._apply(),!0)}_inRange(e){return Math.min(Math.max(e,Math.log2(this.minExposure)),Math.log2(this.maxExposure))}_aim(){return this._inRange(Ex(this._roomEV,this._viewEV,this.strength))}noteViewChanged(){this._viewMoves++}get settling(){return this.enabled&&this._targetEV!==null&&(this._snap||Math.abs(this._targetEV-this._exposureEV)>0)}get wantsMetering(){return this.enabled&&!this._pending&&(this._stale||this._targetEV===null)}_apply(){this.renderer.toneMappingExposure=this.enabled?2**this._exposureEV*this._compensation:this._compensation,!(!this.enabled||this._emittedEV!==null&&Math.abs(this._exposureEV-this._emittedEV)<.005)&&(this._emittedEV=this._exposureEV,this.emit(`autoexposure:updated`,{exposure:this.renderer.toneMappingExposure,autoExposure:this.getExposure(),targetExposure:this._targetEV===null?null:2**this._targetEV,luminance:this.luminance}))}setEnabled(e,t=this._compensation){if(this._compensation=t,e===this.enabled){this._apply();return}this.enabled=e,this._emittedEV=null,e&&(this.resetHistory(),this._exposureEV=0),this._apply(),this.onChange?.()}setCompensation(e){this._compensation=e,this._apply()}resetHistory(){this._generation++,this._targetEV=null,this._viewEV=null,this._roomEV=null,this._landed=null,this._meteredLog2=null,this._snap=!0}getExposure(){return 2**this._exposureEV}get luminance(){return this._meteredLog2===null?null:2**this._meteredLog2}getLuminance(){return this.luminance}updateParameters(e){let t=e.metering;t!==void 0&&rx.includes(t)&&(this.metering=t),e.meteringPoint&&this.meteringPoint.set(e.meteringPoint.x,e.meteringPoint.y);for(let t of[`keyValue`,`minExposure`,`maxExposure`,`adaptSpeedBright`,`adaptSpeedDark`,`centerWeight`,`strength`])e[t]!==void 0&&(this[t]=e[t]);e.lowPercentile!==void 0&&(this._lowU.value=e.lowPercentile),e.highPercentile!==void 0&&(this._highU.value=e.highPercentile),this._stale=!0,this._meteredLog2!==null&&this._applyMetering([this._meteredLog2,1,1]),this.onChange?.()}reset(){}setSize(){}dispose(){this._disposed=!0,this.onChange=null;for(let e of this._kernels)e.dispose();this._readback.dispose(),this._inputNode.dispose()}},Ax={localExposure:!1,localExposureHighlightContrast:.6,localExposureShadowContrast:1,localExposureDetailStrength:1},jx=128,Mx=(jx/2)**2,Nx=32,Px=-16,Fx=16,Ix=-40,Lx=40,Rx=256,zx=32,Bx=.6,Vx=50,Hx=Math.log2(.18),Ux=.999,Wx=2**-24,Gx=Math.ceil(je/jx),Kx=Math.ceil(je/zx),qx=[.2126,.7152,.0722],Jx=e=>e<16?1:e<64?4:16,Yx=(e,t,n)=>Math.min(Math.max(e,t),n);function Xx(e,t,n,r,i,a,o){let s=Math.min(Math.log2(Math.max(a,Wx)),Lx),c=e[6],l=e[7],u=Yx(r*e[2]-.5,0,c-1),d=Yx(i*e[3]-.5,0,l-1),f=Math.floor(u),p=Math.floor(d),m=Math.min(f+1,c-1),h=Math.min(p+1,l-1),g=u-f,_=d-p,v=e=>n[e*c+f]+(n[e*c+m]-n[e*c+f])*g,y=v(p)+(v(h)-v(p))*_,b=e[4],x=e[5],S=Yx(r*e[0]-.5,0,b-1),C=Yx(i*e[1]-.5,0,x-1),w=Yx((s+e[8]-Px)/(Fx-Px),0,1)*(Nx-1),T=Math.floor(S),E=Math.floor(C),D=Math.floor(w),O=S-T,k=C-E,A=w-D,j=0,M=0;for(let e=0;e<8;e++){let n=e&1,r=e>>1&1,i=e>>2,a=(n?O:1-O)*(r?k:1-k)*(i?A:1-A),o=((Math.min(E+r,x-1)*b+Math.min(T+n,b-1))*Nx+Math.min(D+i,Nx-1))*2;j+=t[o]*a,M+=t[o+1]*a}let N=M*Mx<.001?y:j/M,P=N+(y-N)*e[12]+o,F=s+o,I=P>e[13]?e[9]:e[10];return 2**(e[13]+(P-e[13])*I+(F-P)*e[11]-F)}var Zx=`
|
|
927
927
|
@group(1) @binding(0) var<storage, read> leGrid: array<vec2<f32>>;
|
|
928
928
|
@group(1) @binding(1) var<storage, read> leBlur: array<f32>;
|
|
929
929
|
@group(1) @binding(2) var<uniform> le: array<vec4<f32>, 4>;
|
|
@@ -1332,7 +1332,7 @@ fn main( @builtin(global_invocation_id) gid: vec3<u32> ) {
|
|
|
1332
1332
|
textureStore( outNormal, p, vec4<f32>( n, an.w ) );
|
|
1333
1333
|
|
|
1334
1334
|
}
|
|
1335
|
-
`,TC=e=>({binding:e,visibility:GPUShaderStage.COMPUTE,texture:{sampleType:`unfilterable-float`}}),EC=e=>({binding:e,visibility:GPUShaderStage.COMPUTE,storageTexture:{access:`write-only`,format:`rgba32float`}}),DC=(e,t)=>({binding:e,visibility:GPUShaderStage.COMPUTE,buffer:{type:t}}),OC=class{constructor(e){this.device=e,this.settings={...pC,cleanAux:!1,splitCopies:!0},this.valid=!1,this.width=0,this.height=0,this._sets=null,this._current=0,this._picked=null,this._copies=null,this._paramsBuffer=null,this._pipelines=null,this._movedLeaves=null,this._movedToPrev=null,this._movedCapacity=0,this._movedCount=0,this._paramData=new ArrayBuffer(hC),this._paramU32=new Uint32Array(this._paramData),this._paramF32=new Float32Array(this._paramData),this._prevViewProj=new Float32Array(16),this._prevCamPos=new Float32Array(4),this._prevCamDir=new Float32Array(4)}get textures(){return this.valid?this._sets[this._current]:null}invalidate(){this.valid=!1}accumulate(e,t,n=null){if(!this._ensure(e.width,e.height))return;this._uploadMoved(n),this._writeParams(t,!this.valid,0,1);let r=this._sets[this._current],i=this._sets[1-this._current],{select:a,blend:o}=this._pipelines,s=this.device.createCommandEncoder({label:`oidn-history`});s.clearBuffer(this._copies),this._dispatch(s,a,[{buffer:this._paramsBuffer},e.geo,e.geoPrev,{buffer:this._picked},{buffer:this._copies},e.leaf,{buffer:this._movedLeaves},{buffer:this._movedToPrev}]),this._dispatch(s,o,[{buffer:this._paramsBuffer},e.color,e.albedo,e.normal,e.shading,r.color,r.albedo,r.normal,{buffer:this._picked},{buffer:this._copies},i.color,i.albedo,i.normal]),this.device.queue.submit([s.finish()]),this._current=1-this._current,this.valid=!0,this._rememberCamera(t)}merge(e,t,n,{commit:r=!1,keepHistory:i=!0,historyScale:a=1}={}){if(!this._ensure(e.width,e.height))return null;this._writeParams(n,!this.valid||!i,t,a);let o=this._sets[this._current],s=this._sets[1-this._current],c=this.device.createCommandEncoder({label:`oidn-history-merge`});return this._dispatch(c,this._pipelines.merge,[{buffer:this._paramsBuffer},e.color,e.albedo,e.normal,o.color,o.albedo,o.normal,s.color,s.albedo,s.normal]),this.device.queue.submit([c.finish()]),r&&(this._current=1-this._current,this.valid=!0,this._rememberCamera(n)),s}dispose(){this._releaseTextures(),this._paramsBuffer?.destroy(),this._movedLeaves?.destroy(),this._movedToPrev?.destroy(),this._paramsBuffer=null,this._movedLeaves=null,this._movedToPrev=null,this._movedCapacity=0,this._pipelines=null}gpuBytes(){return this._sets?this._sets.length*3*this.width*this.height*16+this._picked.size+this._copies.size:0}_ensure(e,t){if(!e||!t)return!1;if(this._ensurePipelines(),this._sets&&this.width===e&&this.height===t)return!0;this._releaseTextures();let n=this.device,r=GPUTextureUsage.STORAGE_BINDING|GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_SRC,i=i=>n.createTexture({label:i,size:{width:e,height:t},format:`rgba32float`,usage:r});return this._sets=[0,1].map(e=>({color:i(`oidn-history-color-${e}`),albedo:i(`oidn-history-albedo-${e}`),normal:i(`oidn-history-normal-${e}`)})),this._picked=n.createBuffer({label:`oidn-history-picked`,size:e*t*4,usage:GPUBufferUsage.STORAGE}),this._copies=n.createBuffer({label:`oidn-history-copies`,size:e*t*4,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST}),this.width=e,this.height=t,this._current=0,this.valid=!1,!0}_ensurePipelines(){if(this._pipelines)return;let e=this.device,t=(t,n,r)=>{let i=e.createBindGroupLayout({label:t,entries:r});return{pipeline:e.createComputePipeline({label:t,layout:e.createPipelineLayout({bindGroupLayouts:[i]}),compute:{module:e.createShaderModule({label:t,code:n}),entryPoint:`main`}}),layout:i}},n=DC(0,`uniform`);this._pipelines={select:t(`oidn-history-select`,SC,[n,TC(1),TC(2),DC(3,`storage`),DC(4,`storage`),{binding:5,visibility:GPUShaderStage.COMPUTE,texture:{sampleType:`uint`}},DC(6,`read-only-storage`),DC(7,`read-only-storage`)]),blend:t(`oidn-history-blend`,CC,[n,...[1,2,3,4,5,6,7].map(TC),DC(8,`read-only-storage`),DC(9,`read-only-storage`),EC(10),EC(11),EC(12)]),merge:t(`oidn-history-merge`,wC,[n,...[1,2,3,4,5,6].map(TC),EC(7),EC(8),EC(9)])},this._paramsBuffer=e.createBuffer({label:`oidn-history-params`,size:hC,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this._growMoved(gC)}_growMoved(e){this._movedLeaves?.destroy(),this._movedToPrev?.destroy();let t=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST;this._movedLeaves=this.device.createBuffer({label:`oidn-history-moved-leaves`,size:e*4,usage:t}),this._movedToPrev=this.device.createBuffer({label:`oidn-history-moved-matrices`,size:e*64,usage:t}),this._movedCapacity=e}_uploadMoved(e){this._movedCount=e?.count??0,this._movedCount&&(this._movedCount>this._movedCapacity&&this._growMoved(Math.max(this._movedCount,this._movedCapacity*2)),this.device.queue.writeBuffer(this._movedLeaves,0,e.leaves,0,this._movedCount),this.device.queue.writeBuffer(this._movedToPrev,0,e.toPrev,0,this._movedCount*16))}_dispatch(e,{pipeline:t,layout:n},r){let i=r.map((e,t)=>({binding:t,resource:e.buffer?e:e.createView()})),a=e.beginComputePass();a.setPipeline(t),a.setBindGroup(0,this.device.createBindGroup({layout:n,entries:i})),a.dispatchWorkgroups(Math.ceil(this.width/mC),Math.ceil(this.height/mC)),a.end()}_writeParams(e,t,n,r){let i=this.settings,a=this._paramU32,o=this._paramF32;a[0]=this.width,a[1]=this.height,a[2]=+!!t,a[3]=(i.cleanAux?_C:0)|(i.splitCopies?vC:0)|(e.orthographic?yC:0),o[4]=i.maxLength,o[5]=i.smoothLength,o[6]=i.depthTolerance,o[7]=i.normalTolerance,o[8]=i.roughStart,o[9]=i.roughEnd,o[10]=n,o[11]=r,o.set(e.world,12),o.set(e.projInv,28),o.set(this._prevViewProj,44),o.set(this._prevCamPos,60),a[64]=this._movedCount,o[68]=i.movedLength,o.set(this._prevCamDir,72),this.device.queue.writeBuffer(this._paramsBuffer,0,this._paramData)}_rememberCamera(e){this._prevViewProj.set(e.viewProj),this._prevCamPos[0]=e.world[12],this._prevCamPos[1]=e.world[13],this._prevCamPos[2]=e.world[14];let t=Math.hypot(e.world[8],e.world[9],e.world[10]);this._prevCamDir[0]=-e.world[8]/t,this._prevCamDir[1]=-e.world[9]/t,this._prevCamDir[2]=-e.world[10]/t}_releaseTextures(){this._sets?.forEach(e=>Object.values(e).forEach(e=>e.destroy())),this._picked?.destroy(),this._copies?.destroy(),this._sets=null,this._picked=null,this._copies=null,this.width=0,this.height=0,this.valid=!1}},kC='const e=Object.freeze({ADAPTER_SOFTWARE:`adapter.software`,ADAPTER_UNAVAILABLE:`adapter.unavailable`,DEVICE_UNAVAILABLE:`device.unavailable`,WEBGPU_UNAVAILABLE:`webgpu.unavailable`,ASSET_UNREACHABLE:`asset.unreachable`,ASSET_AMBIGUOUS_ENTRY:`asset.ambiguous_entry`,ASSET_ARCHIVE_TOO_LARGE:`asset.archive_too_large`,ASSET_ENTRY_TOO_LARGE:`asset.entry_too_large`,ASSET_PARAMETERS_IGNORED:`asset.parameters_ignored`,TEXTURE_BUILD_FAILED:`texture.build_failed`,TEXTURE_PROCESSING_FALLBACK:`texture.processing_fallback`,TEXTURE_LIMIT_EXCEEDED:`texture.limit_exceeded`,ENVIRONMENT_LOAD_FAILED:`environment.load_failed`,SETTING_UNKNOWN_KEY:`setting.unknown_key`,RENDER_SIZE_DECLINED:`render.size_declined`,STAGE_RENDER_FAILED:`stage.render_failed`,RENDER_RESERVE_CAPPED:`render.reserve_capped`,SCENE_MEMORY_BUDGET:`scene.memory_budget`,EMISSIVE_INSTANCES_COLLAPSED:`emissive.instances_collapsed`,REFIT_SHARED_GEOMETRY:`refit.shared_geometry`,VIEW_TRANSFORM_DISPLAY_MISMATCH:`viewTransform.display_mismatch`,VIEW_TRANSFORM_BAKE_FAILED:`viewTransform.bake_failed`,COLOR_CONFIG_LOAD_FAILED:`color.config_load_failed`,STORAGE_UNAVAILABLE:`storage.unavailable`,STORAGE_QUOTA_EXCEEDED:`storage.quota_exceeded`,STORAGE_WRITE_FAILED:`storage.write_failed`,STORAGE_READ_FAILED:`storage.read_failed`,STORAGE_ENTRY_CORRUPT:`storage.entry_corrupt`,STORAGE_CACHE_MISMATCH:`storage.cache_mismatch`,DENOISER_UNAVAILABLE:`denoiser.unavailable`,OUTPUT_SOURCE_FALLBACK:`output.source_fallback`,OUTPUT_TONEMAP_FALLBACK:`output.tonemap_fallback`,LIGHT_PLACEHOLDER_SKIPPED:`light.placeholder_skipped`,CAPABILITY_MISSING:`capability.missing`});Object.freeze({ERROR:`error`,WARNING:`warning`});const t=new Map;function n(e,t){return e.exclusive||t===`exclusive`&&e.shared>0?!1:(t===`exclusive`?e.exclusive=!0:e.shared++,!0)}function r(e,r,a){let o=t.get(e);o||(o={shared:0,exclusive:!1,queue:[]},t.set(e,o));let s=i(()=>{for(r===`exclusive`?o.exclusive=!1:o.shared--;o.queue.length&&n(o,o.queue[0].mode);)o.queue.shift().grant();!o.exclusive&&o.shared===0&&o.queue.length===0&&t.delete(e)});return o.queue.length===0&&n(o,r)?Promise.resolve(s):a?(!o.exclusive&&o.shared===0&&o.queue.length===0&&t.delete(e),Promise.resolve(null)):new Promise(e=>o.queue.push({mode:r,grant:()=>e(s)}))}function i(e){let t=!1;return()=>{t||(t=!0,e())}}const a=()=>typeof navigator<`u`&&navigator.locks?.request?navigator.locks:null;function o(e,{mode:t=`exclusive`,ifAvailable:n=!1}={}){let o=a();return o?new Promise((r,a)=>{o.request(e,{mode:t,ifAvailable:n},e=>{if(!e){r(null);return}return new Promise(e=>r(i(e)))}).catch(a)}):r(e,t,n)}async function s(){let e=a();if(!e)return new Set(t.keys());let{held:n=[]}=await e.query();return new Set(n.map(e=>e.name))}const c=new TextEncoder;function l(e){let t=``;for(let n of e)t+=n.toString(16).padStart(2,`0`);return t}async function u(e){let t=typeof e==`string`?c.encode(e):e;return l(new Uint8Array(await crypto.subtle.digest(`SHA-256`,t)))}async function d(e){return(await u(e)).slice(0,32)}var f=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)}},p=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})}},m=class{constructor(e){this._ops=new p(e)}async call(e,t){return this._ops[e](t)}dispose(){this._ops.dispose()}};const h=Object.freeze({CACHE:`cache`,USER:`user`,SCRATCH:`scratch`}),g=Object.freeze({DOWNLOADS:`downloads`,ARCHIVES:`archives`,SCENES:`scenes`,CDF:`cdf`,SPILL:`spill`}),_=`meta.json`,v=100*1024**3,y=64*1024**2,b=8*1024**2,x=new TextEncoder;function S(e,{copy:t,transfer:n}){if(typeof e==`string`&&(e=x.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 C(e,t){try{let n=await(await e.getFileHandle(t)).getFile();return JSON.parse(await n.text())}catch{return null}}async function*w(e){for await(let[t,n]of e.entries())n.kind===`directory`&&(yield[t,n])}var T=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(t){try{return await(await this._dir.getFileHandle(t)).getFile()}catch(n){return this.area.manager._issue(e.STORAGE_READ_FAILED,`could not read ${this.area.name}/${this.id}/${t}`,{error:n.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}},E=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:S(t,{copy:!0,transfer:r}))??S(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}=S(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=b}={}){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>=4&&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:1,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}=S(JSON.stringify(n),{copy:!1});return await this._transport.call(`writeFile`,{path:this._path,name:_,...i},a),this.area.kind===h.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`)}},D=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 C(e,_);if(!n||n.v!==1||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(t,{wait:n=!1}={}){let r=await d(t),i=await o(this._lockName(r),{mode:`shared`,ifAvailable:!n});if(!i)return null;try{let e=await this._entryDir(r),n=e?await this._validMeta(e,t):null;return n?(Date.now()-n.lastUsed>36e5&&this._touch(r,n),new T(this,r,n,e,i)):(i(),null)}catch(t){return i(),this.manager._issue(e.STORAGE_READ_FAILED,`could not open ${this.name} entry`,{error:t.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}=S(JSON.stringify(n),{copy:!1});this.manager._transport.call(`writeFile`,{path:[this.name,e],name:_,...r},i).catch(()=>{}),t.lastUsed=n.lastUsed}async create(t,{label:n=``,pinned:r=!1,expectedBytes:i=0,extra:a={},growable:s=[]}={}){let c=await d(t),l=await o(this._lockName(c),{mode:`exclusive`});try{return i>0&&!await this.manager.ensureSpace(i,this.kind)?(l(),this.manager._issue(e.STORAGE_QUOTA_EXCEEDED,`no room for ${(i/1048576).toFixed(0)} MB in ${this.name}`,{area:this.name,expectedBytes:i}),null):(await this._removeDir(c),await this._entryDir(c,!0),new E(this,c,t,{label:n,pinned:r,extra:a,growable:s},l))}catch(e){return l(),this.manager._writeFailed(this.name,e),null}}async patchMeta(e,t){let n=await d(e),r=await o(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}=S(JSON.stringify({...i,...t,v:1,key:e}),{copy:!1});return await this.manager._transport.call(`writeFile`,{path:[this.name,n],name:_,...a},o),!0}finally{r()}}async edit(e){let t=await d(e),n=await o(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 E(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 d(e))}async removeById(e){let t=await o(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 w(e)){let e=await C(r,_);e?.v===1&&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 s(),n=0;for await(let[r,i]of w(e))t.has(this._lockName(r))||await this._validMeta(i)||await this.removeById(r)&&n++;return n}},O=class extends f{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(g))this.defineArea(e,{kind:e===g.SPILL?h.SCRATCH:h.CACHE})}defineArea(e,{kind:t=h.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 D(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*.3,v)}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>3e4)&&(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===h.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===h.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 s(),o=t.filter(({area:e,meta:t})=>!t.pinned&&!a.has(e._lockName(t.id))).sort((e,t)=>e.meta.lastUsed-t.meta.lastUsed),c=0;for(let{area:e,meta:t}of o){if(c>=i)break;await e.removeById(t.id)&&(c+=t.bytes??0,r.bytes-=t.bytes??0)}return c}async ensureSpace(e,t=h.CACHE){let n=async()=>{let{quota:n,usage:r}=await this.estimate(),i=e+y-(n-r);return t===h.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===h.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(t,n){let r=n?.name===`QuotaExceededError`;this._issue(r?e.STORAGE_QUOTA_EXCEEDED:e.STORAGE_WRITE_FAILED,`${t}: ${n?.message??n}`,{area:t,error:n?.name})}dispose(){this._transport?.dispose(),this._transport=null,this._areas.clear()}};function k({namespace:e,root:t}){let n=new m(t);n.inline=!0;let r=new O({root:t,transport:n,namespace:e});return r.sweep().catch(()=>{}),r}const A=Object.freeze({IMMUTABLE:`immutable`,REVALIDATE:`revalidate`,NETWORK:`network`}),j=(e,t)=>({loaded:e,total:t,lengthComputable:t>0&&e<=t}),M=(e,t)=>e.headers?.get?.(t)??null,N=e=>e.reason??new DOMException(`aborted`,`AbortError`);function P(e){try{let t=new URL(e,globalThis.location?.href??`http://localhost/`).pathname;return decodeURIComponent(t.split(`/`).pop())||`download`}catch{return`download`}}async function F(e,{onProgress:t,signal:n}){let r=Number(M(e,`content-length`))||0,i=M(e,`content-type`)??``;if(!e.body)return new Blob([await e.arrayBuffer()],{type:i});let a=e.body.getReader(),o=[],s=0;for(;;){if(n?.aborted)throw a.cancel().catch(()=>{}),N(n);let{done:e,value:i}=await a.read();if(e)break;o.push(i),s+=i.length,t?.(j(s,r))}return new Blob(o,{type:i})}const I=(e,t,n)=>new File([e],t,{type:n||e.type,lastModified:e.lastModified??Date.now()}),L=()=>{};var R=class{constructor(e){this._storage=e,this._revalidating=new Set}get _area(){return this._storage?.area(g.DOWNLOADS)??null}async fetch(e,{key:t=e,name:n=P(e),policy:r=A.REVALIDATE,maxAgeMs:i=864e5,onProgress:a=null,signal:o=null,fetchOptions:s={}}={}){let c=this._area;if(c&&r!==A.NETWORK){let o=await c.open(t);if(o){let c=await o.file(`data`);if(c)return r===A.REVALIDATE&&Date.now()-(o.extra.checkedAt??0)>=i&&this._revalidate(e,t,n,o.extra,s),a?.(j(c.size,c.size)),{file:I(c,n,o.extra.contentType),release:()=>o.release(),fromCache:!0};o.release()}}return this._download(e,t,n,{onProgress:a,signal:o,fetchOptions:s,cache:!!c})}async has(e){return await this._area?.has(e)===!0}async _download(e,t,n,{onProgress:r,signal:i,fetchOptions:a,cache:o}){if(i?.aborted)throw N(i);let s=await fetch(e,{...a,signal:i});if(!s.ok)throw Error(`HTTP ${s.status} fetching ${e}`);let c=Number(M(s,`content-length`))||0,l={url:e,contentType:M(s,`content-type`)??``,lastModified:M(s,`last-modified`),contentLength:c||null,checkedAt:Date.now()},u=o&&s.body?await this._area.create(t,{label:n,expectedBytes:c}):null;if(!u)return{file:I(await F(s,{onProgress:r,signal:i}),n,l.contentType),release:L,fromCache:!1};try{await u.writeStream(`data`,s.body,{signal:i,onProgress:e=>r?.(j(e,c))}),await u.commit(l)}catch(o){if(await u.abort(),o?.name!==`QuotaExceededError`)throw o;return this._download(e,t,n,{onProgress:r,signal:i,fetchOptions:a,cache:!1})}let d=await this._area.open(t,{wait:!0}),f=d&&await d.file(`data`);if(!f)throw d?.release(),Error(`storage: ${n} vanished right after it was saved`);return{file:I(f,n,l.contentType),release:()=>d.release(),fromCache:!1}}async _revalidate(e,t,n,r,i){if(this._revalidating.has(t))return;this._revalidating.add(t);let a=!1;try{let t=new Headers(i?.headers);t.set(`Range`,`bytes=0-0`);let n=await fetch(e,{...i,headers:t});if(n.body?.cancel().catch(()=>{}),n.ok){let e=M(n,`last-modified`),t=n.status===206?Number(M(n,`content-range`)?.match(/\\/(\\d+)$/)?.[1])||null:Number(M(n,`content-length`))||null;a=!!(e&&r.lastModified&&e!==r.lastModified||t&&r.contentLength&&t!==r.contentLength)}}catch{}try{if(a){let{release:r}=await this._download(e,t,n,{fetchOptions:i,cache:!0});r()}else await this._area.patchMeta(t,{extra:{...r,checkedAt:Date.now()}})}catch{}finally{this._revalidating.delete(t)}}};let z={ortRuntimeUrl:`https://cdn.jsdelivr.net/npm/onnxruntime-web@1.24.3/dist/ort.webgpu.bundle.min.mjs`,ortWasmPaths:`https://cdn.jsdelivr.net/npm/onnxruntime-web@1.24.3/dist/`,cacheNamespace:`rayzee`,storage:`auto`},B=null;async function V(){return B||(B=await import(z.ortRuntimeUrl),B.env.wasm.wasmPaths=z.ortWasmPaths,B.env.logLevel=`error`,B)}let H=null,U=null,W=null;function G(){return W??=(async()=>{if(z.storage===!1||!navigator.storage?.getDirectory)return new R(null);try{let e=await(await navigator.storage.getDirectory()).getDirectoryHandle(z.cacheNamespace,{create:!0}),t=k({namespace:z.cacheNamespace,root:e});return await K(t).catch(()=>{}),new R(t)}catch{return new R(null)}})(),W}async function K(e){let t=`${z.cacheNamespace}:ai-upscaler-models`;if(typeof indexedDB>`u`||!indexedDB.databases||!(await indexedDB.databases()).some(e=>e.name===t))return;let n=await new Promise((e,n)=>{let r=indexedDB.open(t);r.onerror=()=>n(r.error),r.onsuccess=()=>{let t=r.result;if(!t.objectStoreNames.contains(`models`)){t.close(),e([]);return}let i=[],a=t.transaction(`models`,`readonly`).objectStore(`models`).openCursor();a.onerror=()=>n(a.error),a.onsuccess=()=>{let n=a.result;if(!n){t.close(),e(i);return}i.push([n.key,n.value]),n.continue()}}}),r=e.area(`downloads`);for(let[e,t]of n){if(typeof e!=`string`||!(t instanceof ArrayBuffer)||await r.has(e))continue;let n=await r.create(e,{label:e.split(`/`).pop(),expectedBytes:t.byteLength});n&&(await n.write(`data`,t,{transfer:!0}),await n.commit({url:e,contentType:`application/octet-stream`,checkedAt:Date.now()}))}await new Promise(e=>{let n=indexedDB.deleteDatabase(t);n.onsuccess=n.onerror=n.onblocked=()=>e()})}async function q(e){let{file:t,release:n,fromCache:r}=await(await G()).fetch(e);try{let e=await t.arrayBuffer();return r&&console.log(`AI Upscaler Worker: model loaded from cache (${(e.byteLength/1024/1024).toFixed(1)}MB)`),e}finally{n()}}async function J(e,t){if(H&&U===e){self.postMessage({type:`loaded`,backend:`webgpu`});return}H&&=(await H.release(),null);let[n,r]=await Promise.all([q(e),V()]);H=await r.InferenceSession.create(n,t),U=e;let i=512;try{let e=await navigator.gpu?.requestAdapter(),t=await e?.requestAdapterInfo?.()||e?.info,n=/apple|swiftshader|llvmpipe/i.test(t?.vendor||``)||/apple|swiftshader/i.test(t?.architecture||``),r=t?.device?.toLowerCase?.()?.includes(`integrated`)||/intel.*iris|intel.*uhd|intel.*hd|amd.*vega|radeon.*graphics/i.test(t?.description||``);i=n?128:r?256:512,console.log(`AI Upscaler Worker: GPU="${t?.description||t?.device||`unknown`}", tileSize=${i}`)}catch{}let a=(n.byteLength/1024/1024).toFixed(1);console.log(`AI Upscaler Worker: model loaded (${a}MB), backend: webgpu`),self.postMessage({type:`loaded`,backend:`webgpu`,tileSize:i})}async function Y(e,t,n,r){let i=await V(),a=H.inputNames[0],o=H.outputNames[0],s=new i.Tensor(`float32`,e,[1,3,n,t]),c=(await H.run({[a]:s}))[o].data;self.postMessage({type:`inferred`,outputData:c,id:r},[c.buffer])}self.onmessage=async e=>{let{type:t}=e.data;try{t===`load`?(e.data.ortRuntimeUrl&&(z.ortRuntimeUrl=e.data.ortRuntimeUrl),e.data.ortWasmPaths&&(z.ortWasmPaths=e.data.ortWasmPaths),e.data.cacheNamespace&&(z.cacheNamespace=e.data.cacheNamespace),e.data.storage!==void 0&&(z.storage=e.data.storage),await J(e.data.url,e.data.sessionOptions)):t===`infer`?await Y(e.data.tileData,e.data.width,e.data.height,e.data.id):t===`dispose`&&H&&(await H.release(),H=null,U=null)}catch(t){self.postMessage({type:`error`,message:t.message,id:e.data?.id})}};',AC=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,kC],{type:`text/javascript;charset=utf-8`});function jC(e){let t;try{if(t=AC&&(self.URL||self.webkitURL).createObjectURL(AC),!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(kC),{type:`module`,name:e?.name})}}Vv(),ui();var MC={fast:{2:`2x-spanx2-ch48.onnx`,4:`4xNomos8k_span_otf_strong_fp32_opset17.onnx`},balanced:{2:`2xNomosUni_compact_otf_medium.onnx`,4:`RealESRGAN_x4plus.onnx`},quality:{2:`2x-realesrgan-x2plus.onnx`,4:`4xNomos2_hq_mosr_fp32.onnx`}};function NC(){let{upscalerModelBaseUrl:e}=si(),t={};for(let n in MC){t[n]={};for(let r in MC[n])t[n][r]=e+MC[n][r]}return t}var PC={get QUALITY_PRESETS(){return NC()},TILE_SIZE:512,TILE_OVERLAP:16,SESSION_OPTIONS:{executionProviders:[{name:`webgpu`,preferredLayout:`NCHW`}],graphOptimizationLevel:`all`}},FC=class extends r.EventDispatcher{constructor(e,t,n={}){if(super(),!e||!t)throw Error(`AIUpscaler requires output canvas and renderer`);this.renderer=t,this.input=t.domElement,this.output=e,this.getSourceCanvas=n.getSourceCanvas||null,this.getGPUTextures=n.getGPUTextures||null,this.getExposure=n.getExposure||(()=>1),this.getToneMapping=n.getToneMapping||(()=>r.ACESFilmicToneMapping),this.getSaturation=n.getSaturation||(()=>1),this.getDisplayGain=n.getDisplayGain||(()=>null),this.getTransparentBackground=n.getTransparentBackground||(()=>!1),this.enabled=!1,this.hdr=!1,this.scaleFactor=n.scaleFactor||2,this.quality=n.quality||`fast`,this.refreshInput=n.refreshInput||null,this.tileSize=n.tileSize||PC.TILE_SIZE,this._tileSizeOverride=!!n.tileSize,this.state={isUpscaling:!1,isLoading:!1,abortController:null},this._worker=null,this._currentModelUrl=null,this._tileId=0,this._pendingWorkerHandlers=new Map,this._upscaledAlpha=null,this._upscaledAlphaWidth=0,this._backupCanvas=null,this._baseWidth=e.width,this._baseHeight=e.height,this._toneMapper=null}async _ensureSession(){let e=PC.QUALITY_PRESETS[this.quality];if(!e)throw Error(`Unknown quality preset: ${this.quality}`);let t=e[this.scaleFactor];if(!t)throw Error(`No model for ${this.quality}/${this.scaleFactor}x`);if(!(this._worker&&this._currentModelUrl===t)){this.state.isLoading=!0,this.dispatchEvent({type:`loading`,message:`Loading ${this.scaleFactor}x upscale model...`});try{this._worker||=new jC,await new Promise((e,n)=>{let r=t=>{t.data.type===`loaded`?(this._worker.removeEventListener(`message`,r),t.data.tileSize&&!this._tileSizeOverride&&(this.tileSize=t.data.tileSize),console.log(`AI Upscaler: ${this.scaleFactor}x model loaded, backend: ${t.data.backend}, tileSize: ${this.tileSize}`),e()):t.data.type===`error`&&(this._worker.removeEventListener(`message`,r),n(Error(t.data.message)))},{ortRuntimeUrl:i,ortWasmPaths:a,cacheNamespace:o,storage:s}=si();this._worker.addEventListener(`message`,r),this._worker.postMessage({type:`load`,url:t,sessionOptions:PC.SESSION_OPTIONS,ortRuntimeUrl:i,ortWasmPaths:a,cacheNamespace:o,storage:s})}),this._currentModelUrl=t,this.dispatchEvent({type:`loaded`})}catch(e){throw console.error(`AI Upscaler: Failed to load model:`,e),this.dispatchEvent({type:`error`,error:e}),e}finally{this.state.isLoading=!1}}}async start(e=null){if(!this.enabled||this.state.isUpscaling||this.state.isLoading)return!1;this.dispatchEvent({type:`start`});let t=performance.now(),n=await this.execute(e);if(n){this.renderer?.resetState?.();let e=performance.now()-t;console.log(`AI Upscaler: ${this.scaleFactor}x upscale completed in ${e.toFixed(1)}ms`)}return n}_revealOutput(){this.output.style.display=`block`,this.input.style.opacity=`0`}async execute(e=null){if(!this.enabled)return!1;this.state.abortController=new AbortController,this.state.isUpscaling=!0,e?this._capturedSource=e:this.hdr&&this.getGPUTextures?this._capturedSource=await this._captureSourceHDR():this._capturedSource=this._captureSource(),this._createBackup(this._capturedSource);let t=this._capturedSource.width*this.scaleFactor,n=this._capturedSource.height*this.scaleFactor;this.output.width=t,this.output.height=n;let r=this.output.getContext(`2d`,{willReadFrequently:!0,alpha:!0});r.imageSmoothingEnabled=!0,r.imageSmoothingQuality=`high`,r.drawImage(this._backupCanvas,0,0,t,n),this._revealOutput();try{return await this._ensureSession(),await this._runUpscale(),this.dispatchEvent({type:`resolution_changed`,width:this.output.width,height:this.output.height}),!0}catch(e){return e.name===`AbortError`?console.log(`AI Upscaler: Upscaling was aborted`):(console.error(`AI Upscaler: Upscaling error:`,e),this.dispatchEvent({type:`error`,error:e}),this._restoreBackup(),this.input.style.opacity=`1`,this.dispatchEvent({type:`resolution_changed`,width:this._baseWidth,height:this._baseHeight})),!1}finally{this._capturedSource=null,this._upscaledAlpha=null,this._backupCanvas=null,this.state.isUpscaling&&(this.state.isUpscaling=!1,this.state.abortController=null,this.dispatchEvent({type:`end`}))}}abort(){this.state.isUpscaling&&(this.state.abortController?.abort(),this._cleanupPendingWorkerHandlers(),this.input.style.opacity=`1`,this._restoreBackup(),this.dispatchEvent({type:`resolution_changed`,width:this._baseWidth,height:this._baseHeight}),this.state.isUpscaling=!1,this.dispatchEvent({type:`end`}),console.log(`AI Upscaler: Aborted`))}async _runUpscale(){let e=this.state.abortController.signal,t=this._capturedSource;this._capturedSource=null;let{width:n,height:r}=t,i=this.scaleFactor,a=this.output.getContext(`2d`,{willReadFrequently:!0,alpha:!0});this._cacheUpscaledAlpha(t,n*i,r*i);let o=PC.TILE_OVERLAP,s=this.tileSize,c=s-o*2,l=Math.ceil(n/c),u=Math.ceil(r/c),d=l*u,f=0;for(let o=0;o<u;o++)for(let u=0;u<l;u++){if(e.aborted)throw new DOMException(`Aborted`,`AbortError`);let l=Math.min(u*c,Math.max(0,n-s)),p=Math.min(o*c,Math.max(0,r-s)),m=Math.min(s,n-l),h=Math.min(s,r-p),g=this._extractTile(t,l,p,m,h),_=await this._inferTile(g,m,h),v=l*i,y=p*i,b=m*i,x=h*i,S=this._tensorToImageData(_,b,x,v,y);a.putImageData(S,v,y),f++,this.dispatchEvent({type:`progress`,progress:f/d,tile:{x:u,y:o,total:d,completed:f}}),this.dispatchEvent({type:`tileProgress`,tile:{x:v,y,width:b,height:x},imageWidth:n*i,imageHeight:r*i})}}_captureSource(){let e=this.getSourceCanvas?this.getSourceCanvas():null;if(e&&e!==this.output){this.refreshInput?.();let t=document.createElement(`canvas`);t.width=e.width,t.height=e.height;let n=t.getContext(`2d`);return n.drawImage(e,0,0),n.getImageData(0,0,t.width,t.height)}return this.output.getContext(`2d`,{willReadFrequently:!0}).getImageData(0,0,this.output.width,this.output.height)}async _captureSourceHDR(){let e=this.getGPUTextures();if(!e?.color)throw Error(`No GPU color texture available for HDR capture`);let t=e.color,{width:n,height:i}=t;this._toneMapper??=new Bv(this.renderer.backend.device,`aiupscaler-tonemap`,{input:`texture`,output:`planar`}),this._toneMapper.ensureSize(n,i);let a=await this._toneMapper.toPlanar(t,{exposure:this.getExposure(),toneMapping:this.getToneMapping()??r.ACESFilmicToneMapping,saturation:this.getSaturation(),gain:this.getDisplayGain()});return this._toneMapper.release(),this.getTransparentBackground()||a.fill(1,3*n*i),{planes:a,width:n,height:i,isHDR:!0}}_extractTile(e,t,n,r,i){let{width:a}=e,o=r*i,s=new Float32Array(3*o);if(e.isHDR){let{planes:c}=e,l=a*e.height;for(let e=0;e<3;e++)for(let u=0;u<i;u++){let i=e*l+(n+u)*a+t;s.set(c.subarray(i,i+r),e*o+u*r)}return s}let{data:c}=e;for(let e=0;e<i;e++)for(let i=0;i<r;i++){let l=((n+e)*a+(t+i))*4,u=e*r+i;s[u]=c[l]/255,s[o+u]=c[l+1]/255,s[2*o+u]=c[l+2]/255}return s}async _inferTile(e,t,n){let r=++this._tileId;return new Promise((i,a)=>{let o=e=>{e.data.id===r&&(this._worker.removeEventListener(`message`,o),this._pendingWorkerHandlers.delete(o),e.data.type===`inferred`?i(e.data.outputData):e.data.type===`error`&&a(Error(e.data.message)))};this._pendingWorkerHandlers.set(o,a),this._worker.addEventListener(`message`,o),this._worker.postMessage({type:`infer`,tileData:e,width:t,height:n,id:r},[e.buffer])})}_tensorToImageData(e,t,n,r,i){let a=new ImageData(t,n),o=a.data,s=t*n,c=this._upscaledAlpha,l=this._upscaledAlphaWidth;for(let n=0;n<s;n++)if(o[n*4]=Math.min(255,Math.max(0,e[n]*255+.5))|0,o[n*4+1]=Math.min(255,Math.max(0,e[s+n]*255+.5))|0,o[n*4+2]=Math.min(255,Math.max(0,e[2*s+n]*255+.5))|0,c){let e=n/t|0,a=n%t;o[n*4+3]=c[(i+e)*l+(r+a)]}else o[n*4+3]=255;return a}_cacheUpscaledAlpha(e,t,n){let{width:r,height:i}=e,a=r*i,o=e.isHDR,s=o?e.planes.subarray(3*a):e.data,c=o?1:4,l=o?0:3,u=o?1:255,d=!1;for(let e=l;e<s.length;e+=c)if(s[e]<u){d=!0;break}if(!d){this._upscaledAlpha=null,this._upscaledAlphaWidth=0;return}let f=document.createElement(`canvas`);f.width=r,f.height=i;let p=f.getContext(`2d`),m=p.createImageData(r,i);for(let e=0;e<a;e++){let t=o?Math.min(Math.max(s[e]*255,0),255)|0:s[e*4+3];m.data[e*4]=t,m.data[e*4+1]=t,m.data[e*4+2]=t,m.data[e*4+3]=255}p.putImageData(m,0,0);let h=document.createElement(`canvas`);h.width=t,h.height=n;let g=h.getContext(`2d`);g.imageSmoothingEnabled=!0,g.imageSmoothingQuality=`high`,g.drawImage(f,0,0,t,n);let _=g.getImageData(0,0,t,n).data,v=new Uint8Array(t*n);for(let e=0,r=t*n;e<r;e++)v[e]=_[e*4];this._upscaledAlpha=v,this._upscaledAlphaWidth=t}_createBackup(e){this._backupCanvas=document.createElement(`canvas`),this._backupCanvas.width=e.width,this._backupCanvas.height=e.height;let t=this._backupCanvas.getContext(`2d`);if(e.isHDR){let{planes:n,width:r,height:i}=e,a=r*i,o=t.createImageData(r,i),s=o.data;for(let e=0;e<a;e++){let t=e*4;s[t]=n[e]*255+.5|0,s[t+1]=n[a+e]*255+.5|0,s[t+2]=n[2*a+e]*255+.5|0,s[t+3]=255}t.putImageData(o,0,0)}else t.putImageData(e,0,0)}_restoreBackup(){this._backupCanvas&&=(this.output.width=this._backupCanvas.width,this.output.height=this._backupCanvas.height,this.output.getContext(`2d`).drawImage(this._backupCanvas,0,0),null)}toggleHDR(e){this.hdr=!!e}setQuality(e){if(!PC.QUALITY_PRESETS[e]){console.warn(`AIUpscaler: Invalid quality "${e}", must be fast/balanced/quality`);return}this.quality=e}setScaleFactor(e){if(e=Number(e),e!==2&&e!==4){console.warn(`AIUpscaler: Invalid scale factor ${e}, must be 2 or 4`);return}this.scaleFactor=e}setBaseSize(e,t){this._baseWidth=e,this._baseHeight=t}_cleanupPendingWorkerHandlers(){for(let[e,t]of this._pendingWorkerHandlers)this._worker?.removeEventListener(`message`,e),t(new DOMException(`Aborted`,`AbortError`));this._pendingWorkerHandlers.clear()}async dispose(){this.abort(),this._cleanupPendingWorkerHandlers(),this._worker&&=(this._worker.postMessage({type:`dispose`}),this._worker.terminate(),null),this._currentModelUrl=null,this._backupCanvas=null,this._upscaledAlpha=null,this.state.abortController=null,this._toneMapper?.dispose(),this._toneMapper=null,console.log(`AIUpscaler disposed`)}},IC=_({NeuralSuperRes:()=>ZC,SR_MAX_INPUT:()=>qC,SR_SCALE:()=>2,presentRGBA8:()=>WC,readDenoisedHalf:()=>BC,releaseDenoisedReader:()=>zC,renderUpscaled:()=>HC});function LC(){if(JC)return JC;let{neuralRuntimeUrl:e,neuralAssetBaseUrl:t}=si();return t?(globalThis.__NEURAL_ASSET_BASE__=t,JC=new Promise((t,n)=>{if(globalThis.NeuralRuntime?.getNativeSR)return t(globalThis.NeuralRuntime.getNativeSR());let r=document.createElement(`script`);r.src=e,r.onload=()=>{let e=globalThis.NeuralRuntime?.getNativeSR;if(!e)return n(Error(`Neural runtime loaded but exposed no super-resolution entry`));t(e())},r.onerror=()=>n(Error(`Failed to load the neural runtime from ${e}`)),document.head.appendChild(r)}),JC):Promise.reject(Error(`No neural model location: set neuralAssetBaseUrl with configureAssets()`))}function RC(e,t,n){if(XC&&(XC.device!==e||XC.width!==t||XC.height!==n)&&zC(),XC)return XC;let r=t*n*8;return XC={device:e,width:t,height:n,storage:e.createBuffer({label:`rayzee:neural-sr-pack`,size:r,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC}),map:e.createBuffer({label:`rayzee:neural-sr-pack-map`,size:r,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),pipeline:e.createComputePipeline({label:`rayzee:neural-sr-pack`,layout:`auto`,compute:{module:e.createShaderModule({label:`rayzee:neural-sr-pack`,code:YC}),entryPoint:`main`}})},XC}function zC(){XC?.storage.destroy(),XC?.map.destroy(),XC=null}async function BC(e){let t=e?._outGPUTexture;if(!t)throw Error(`NeuralSuperRes: no denoised frame — enable OIDN and finish a render first`);let n=e.gpuDevice,{width:r,height:i}=e._outTexSize,a=RC(n,r,i),o=n.createBindGroup({layout:a.pipeline.getBindGroupLayout(0),entries:[{binding:0,resource:t.createView()},{binding:1,resource:{buffer:a.storage}}]}),s=n.createCommandEncoder({label:`rayzee:neural-sr-pack`}),c=s.beginComputePass();c.setPipeline(a.pipeline),c.setBindGroup(0,o),c.dispatchWorkgroups(Math.ceil(r/8),Math.ceil(i/8)),c.end(),s.copyBufferToBuffer(a.storage,0,a.map,0,r*i*8),n.queue.submit([s.finish()]),await a.map.mapAsync(GPUMapMode.READ);let l=new Uint16Array(a.map.getMappedRange().slice(0));return a.map.unmap(),{half:l,width:r,height:i}}function VC(e,t,n){return new Promise((r,i)=>{let a=!1,o=(t,n)=>{a||(a=!0,e.removeEventListener(N.DENOISING_END,c),clearInterval(l),clearTimeout(u),t?r():i(n))},s=!1,c=()=>{(e.stages?.pathTracer?.frameCount??0)>=t&&(s=!0)};e.addEventListener(N.DENOISING_END,c);let l=setInterval(()=>{s&&o(!0)},200),u=setTimeout(()=>o(!1,Error(`NeuralSuperRes: timed out waiting for the render to finish`)),n)})}async function HC(e,{outputWidth:t,outputHeight:n,samples:r=64,upscaler:i=null,timeoutMs:a=6e5,present:o=!0,onProgress:s=()=>{}}={}){if(t%2||n%2)throw Error(`renderUpscaled: output must be divisible by 2, got ${t}x${n}`);let c=t/2,l=n/2,u=e.stages?.pathTracer,d={width:u?.width,height:u?.height,maxSamples:e.settings?.get?.(`maxSamples`),renderLimitMode:e.settings?.get?.(`renderLimitMode`),finalDenoise:e.denoisingManager?.finalDenoise,paused:e.pauseRendering},f=!i,p=i,m={};try{if(!p){let e=performance.now();s(`Loading the super-resolution model`),p=await ZC.create({width:c,height:l,onProgress:s}),m.load=performance.now()-e}else if(p.inputWidth!==c||p.inputHeight!==l)throw Error(`renderUpscaled: upscaler is ${p.inputWidth}x${p.inputHeight}, need ${c}x${l}`);let i=performance.now();s(`Tracing ${c}x${l} at ${r} spp`),e.pauseRendering=!1,e.setCanvasSize(c,l),await new Promise(e=>setTimeout(e,300)),e.denoisingManager.applyOIDNEnabled(!0),e.settings.setMany({maxSamples:r,renderLimitMode:`frames`},{reset:!1});let u=VC(e,r,a);e.reset(),await u,e.pauseRendering=!0,m.render=performance.now()-i,s(`Reading the denoised frame`);let d=performance.now(),f=await BC(e.denoisingManager?.denoiser);m.read=performance.now()-d,s(`Upscaling to ${t}x${n}`);let h={exposure:e.renderer.toneMappingExposure,toneMapping:e.renderer.toneMapping,saturation:e.settings.get(`saturation`)??1,gain:e._displayGain?.()??null},{rgba8:g,width:_,height:v,ms:y,toneMs:b}=await p.upscaleToRGBA8(f,h);return m.upscale=y,m.tonemap=b,o&&UC(e.denoisingManager?.upscalerCanvas,g,_,v),{rgba8:g,width:_,height:v,timings:m,upscaler:p}}catch(e){throw f&&p?.dispose(),e}finally{d.width&&d.height&&e.setCanvasSize(d.width,d.height),d.maxSamples!==void 0&&e.settings?.set?.(`maxSamples`,d.maxSamples),d.renderLimitMode!==void 0&&e.settings?.set?.(`renderLimitMode`,d.renderLimitMode,{reset:!1}),d.finalDenoise!==void 0&&e.denoisingManager?.applyOIDNEnabled(d.finalDenoise),e.pauseRendering=d.paused}}function UC(e,t,n,r){return e?(e.width=n,e.height=r,e.getContext(`2d`).putImageData(new ImageData(new Uint8ClampedArray(t.buffer??t),n,r),0,0),e.style.display=`block`,!0):!1}function WC(e,t,n,r){return UC(e,t,n,r)}var GC,KC,qC,JC,YC,XC,ZC,QC=g((()=>{F(),Ae(),Vv(),ui(),GC=2,KC=ve(`neural`),qC=2048,JC=null,YC=`
|
|
1335
|
+
`,TC=e=>({binding:e,visibility:GPUShaderStage.COMPUTE,texture:{sampleType:`unfilterable-float`}}),EC=e=>({binding:e,visibility:GPUShaderStage.COMPUTE,storageTexture:{access:`write-only`,format:`rgba32float`}}),DC=(e,t)=>({binding:e,visibility:GPUShaderStage.COMPUTE,buffer:{type:t}}),OC=class{constructor(e){this.device=e,this.settings={...pC,cleanAux:!1,splitCopies:!0},this.valid=!1,this.width=0,this.height=0,this._sets=null,this._current=0,this._picked=null,this._copies=null,this._paramsBuffer=null,this._pipelines=null,this._movedLeaves=null,this._movedToPrev=null,this._movedCapacity=0,this._movedCount=0,this._paramData=new ArrayBuffer(hC),this._paramU32=new Uint32Array(this._paramData),this._paramF32=new Float32Array(this._paramData),this._prevViewProj=new Float32Array(16),this._prevCamPos=new Float32Array(4),this._prevCamDir=new Float32Array(4)}get textures(){return this.valid?this._sets[this._current]:null}invalidate(){this.valid=!1}accumulate(e,t,n=null){if(!this._ensure(e.width,e.height))return;this._uploadMoved(n),this._writeParams(t,!this.valid,0,1);let r=this._sets[this._current],i=this._sets[1-this._current],{select:a,blend:o}=this._pipelines,s=this.device.createCommandEncoder({label:`oidn-history`});s.clearBuffer(this._copies),this._dispatch(s,a,[{buffer:this._paramsBuffer},e.geo,e.geoPrev,{buffer:this._picked},{buffer:this._copies},e.leaf,{buffer:this._movedLeaves},{buffer:this._movedToPrev}]),this._dispatch(s,o,[{buffer:this._paramsBuffer},e.color,e.albedo,e.normal,e.shading,r.color,r.albedo,r.normal,{buffer:this._picked},{buffer:this._copies},i.color,i.albedo,i.normal]),this.device.queue.submit([s.finish()]),this._current=1-this._current,this.valid=!0,this._rememberCamera(t)}merge(e,t,n,{commit:r=!1,keepHistory:i=!0,historyScale:a=1}={}){if(!this._ensure(e.width,e.height))return null;this._writeParams(n,!this.valid||!i,t,a);let o=this._sets[this._current],s=this._sets[1-this._current],c=this.device.createCommandEncoder({label:`oidn-history-merge`});return this._dispatch(c,this._pipelines.merge,[{buffer:this._paramsBuffer},e.color,e.albedo,e.normal,o.color,o.albedo,o.normal,s.color,s.albedo,s.normal]),this.device.queue.submit([c.finish()]),r&&(this._current=1-this._current,this.valid=!0,this._rememberCamera(n)),s}dispose(){this._releaseTextures(),this._paramsBuffer?.destroy(),this._movedLeaves?.destroy(),this._movedToPrev?.destroy(),this._paramsBuffer=null,this._movedLeaves=null,this._movedToPrev=null,this._movedCapacity=0,this._pipelines=null}gpuBytes(){return this._sets?this._sets.length*3*this.width*this.height*16+this._picked.size+this._copies.size:0}_ensure(e,t){if(!e||!t)return!1;if(this._ensurePipelines(),this._sets&&this.width===e&&this.height===t)return!0;this._releaseTextures();let n=this.device,r=GPUTextureUsage.STORAGE_BINDING|GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_SRC,i=i=>n.createTexture({label:i,size:{width:e,height:t},format:`rgba32float`,usage:r});return this._sets=[0,1].map(e=>({color:i(`oidn-history-color-${e}`),albedo:i(`oidn-history-albedo-${e}`),normal:i(`oidn-history-normal-${e}`)})),this._picked=n.createBuffer({label:`oidn-history-picked`,size:e*t*4,usage:GPUBufferUsage.STORAGE}),this._copies=n.createBuffer({label:`oidn-history-copies`,size:e*t*4,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST}),this.width=e,this.height=t,this._current=0,this.valid=!1,!0}_ensurePipelines(){if(this._pipelines)return;let e=this.device,t=(t,n,r)=>{let i=e.createBindGroupLayout({label:t,entries:r});return{pipeline:e.createComputePipeline({label:t,layout:e.createPipelineLayout({bindGroupLayouts:[i]}),compute:{module:e.createShaderModule({label:t,code:n}),entryPoint:`main`}}),layout:i}},n=DC(0,`uniform`);this._pipelines={select:t(`oidn-history-select`,SC,[n,TC(1),TC(2),DC(3,`storage`),DC(4,`storage`),{binding:5,visibility:GPUShaderStage.COMPUTE,texture:{sampleType:`uint`}},DC(6,`read-only-storage`),DC(7,`read-only-storage`)]),blend:t(`oidn-history-blend`,CC,[n,...[1,2,3,4,5,6,7].map(TC),DC(8,`read-only-storage`),DC(9,`read-only-storage`),EC(10),EC(11),EC(12)]),merge:t(`oidn-history-merge`,wC,[n,...[1,2,3,4,5,6].map(TC),EC(7),EC(8),EC(9)])},this._paramsBuffer=e.createBuffer({label:`oidn-history-params`,size:hC,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this._growMoved(gC)}_growMoved(e){this._movedLeaves?.destroy(),this._movedToPrev?.destroy();let t=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST;this._movedLeaves=this.device.createBuffer({label:`oidn-history-moved-leaves`,size:e*4,usage:t}),this._movedToPrev=this.device.createBuffer({label:`oidn-history-moved-matrices`,size:e*64,usage:t}),this._movedCapacity=e}_uploadMoved(e){this._movedCount=e?.count??0,this._movedCount&&(this._movedCount>this._movedCapacity&&this._growMoved(Math.max(this._movedCount,this._movedCapacity*2)),this.device.queue.writeBuffer(this._movedLeaves,0,e.leaves,0,this._movedCount),this.device.queue.writeBuffer(this._movedToPrev,0,e.toPrev,0,this._movedCount*16))}_dispatch(e,{pipeline:t,layout:n},r){let i=r.map((e,t)=>({binding:t,resource:e.buffer?e:e.createView()})),a=e.beginComputePass();a.setPipeline(t),a.setBindGroup(0,this.device.createBindGroup({layout:n,entries:i})),a.dispatchWorkgroups(Math.ceil(this.width/mC),Math.ceil(this.height/mC)),a.end()}_writeParams(e,t,n,r){let i=this.settings,a=this._paramU32,o=this._paramF32;a[0]=this.width,a[1]=this.height,a[2]=+!!t,a[3]=(i.cleanAux?_C:0)|(i.splitCopies?vC:0)|(e.orthographic?yC:0),o[4]=i.maxLength,o[5]=i.smoothLength,o[6]=i.depthTolerance,o[7]=i.normalTolerance,o[8]=i.roughStart,o[9]=i.roughEnd,o[10]=n,o[11]=r,o.set(e.world,12),o.set(e.projInv,28),o.set(this._prevViewProj,44),o.set(this._prevCamPos,60),a[64]=this._movedCount,o[68]=i.movedLength,o.set(this._prevCamDir,72),this.device.queue.writeBuffer(this._paramsBuffer,0,this._paramData)}_rememberCamera(e){this._prevViewProj.set(e.viewProj),this._prevCamPos[0]=e.world[12],this._prevCamPos[1]=e.world[13],this._prevCamPos[2]=e.world[14];let t=Math.hypot(e.world[8],e.world[9],e.world[10]);this._prevCamDir[0]=-e.world[8]/t,this._prevCamDir[1]=-e.world[9]/t,this._prevCamDir[2]=-e.world[10]/t}_releaseTextures(){this._sets?.forEach(e=>Object.values(e).forEach(e=>e.destroy())),this._picked?.destroy(),this._copies?.destroy(),this._sets=null,this._picked=null,this._copies=null,this.width=0,this.height=0,this.valid=!1}},kC='const e=Object.freeze({ADAPTER_SOFTWARE:`adapter.software`,ADAPTER_UNAVAILABLE:`adapter.unavailable`,DEVICE_UNAVAILABLE:`device.unavailable`,WEBGPU_UNAVAILABLE:`webgpu.unavailable`,ASSET_UNREACHABLE:`asset.unreachable`,ASSET_AMBIGUOUS_ENTRY:`asset.ambiguous_entry`,ASSET_ARCHIVE_TOO_LARGE:`asset.archive_too_large`,ASSET_ENTRY_TOO_LARGE:`asset.entry_too_large`,ASSET_PARAMETERS_IGNORED:`asset.parameters_ignored`,TEXTURE_BUILD_FAILED:`texture.build_failed`,TEXTURE_PROCESSING_FALLBACK:`texture.processing_fallback`,TEXTURE_LIMIT_EXCEEDED:`texture.limit_exceeded`,ENVIRONMENT_LOAD_FAILED:`environment.load_failed`,SETTING_UNKNOWN_KEY:`setting.unknown_key`,RENDER_SIZE_DECLINED:`render.size_declined`,STAGE_RENDER_FAILED:`stage.render_failed`,RENDER_RESERVE_CAPPED:`render.reserve_capped`,SCENE_MEMORY_BUDGET:`scene.memory_budget`,EMISSIVE_INSTANCES_COLLAPSED:`emissive.instances_collapsed`,REFIT_SHARED_GEOMETRY:`refit.shared_geometry`,VIEW_TRANSFORM_DISPLAY_MISMATCH:`viewTransform.display_mismatch`,VIEW_TRANSFORM_BAKE_FAILED:`viewTransform.bake_failed`,COLOR_CONFIG_LOAD_FAILED:`color.config_load_failed`,STORAGE_UNAVAILABLE:`storage.unavailable`,STORAGE_QUOTA_EXCEEDED:`storage.quota_exceeded`,STORAGE_WRITE_FAILED:`storage.write_failed`,STORAGE_READ_FAILED:`storage.read_failed`,STORAGE_ENTRY_CORRUPT:`storage.entry_corrupt`,STORAGE_CACHE_MISMATCH:`storage.cache_mismatch`,DENOISER_UNAVAILABLE:`denoiser.unavailable`,OUTPUT_SOURCE_FALLBACK:`output.source_fallback`,OUTPUT_TONEMAP_FALLBACK:`output.tonemap_fallback`,LIGHT_PLACEHOLDER_SKIPPED:`light.placeholder_skipped`,CAPABILITY_MISSING:`capability.missing`});Object.freeze({ERROR:`error`,WARNING:`warning`});const t=new Map;function n(e,t){return e.exclusive||t===`exclusive`&&e.shared>0?!1:(t===`exclusive`?e.exclusive=!0:e.shared++,!0)}function r(e,r,a){let o=t.get(e);o||(o={shared:0,exclusive:!1,queue:[]},t.set(e,o));let s=i(()=>{for(r===`exclusive`?o.exclusive=!1:o.shared--;o.queue.length&&n(o,o.queue[0].mode);)o.queue.shift().grant();!o.exclusive&&o.shared===0&&o.queue.length===0&&t.delete(e)});return o.queue.length===0&&n(o,r)?Promise.resolve(s):a?(!o.exclusive&&o.shared===0&&o.queue.length===0&&t.delete(e),Promise.resolve(null)):new Promise(e=>o.queue.push({mode:r,grant:()=>e(s)}))}function i(e){let t=!1;return()=>{t||(t=!0,e())}}const a=()=>typeof navigator<`u`&&navigator.locks?.request?navigator.locks:null;function o(e,{mode:t=`exclusive`,ifAvailable:n=!1}={}){let o=a();return o?new Promise((r,a)=>{o.request(e,{mode:t,ifAvailable:n},e=>{if(!e){r(null);return}return new Promise(e=>r(i(e)))}).catch(a)}):r(e,t,n)}async function s(){let e=a();if(!e)return new Set(t.keys());let{held:n=[]}=await e.query();return new Set(n.map(e=>e.name))}const c=new TextEncoder;function l(e){let t=``;for(let n of e)t+=n.toString(16).padStart(2,`0`);return t}async function u(e){let t=typeof e==`string`?c.encode(e):e;return l(new Uint8Array(await crypto.subtle.digest(`SHA-256`,t)))}async function d(e){return(await u(e)).slice(0,32)}var f=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)}},p=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})}},m=class{constructor(e){this._ops=new p(e)}async call(e,t){return this._ops[e](t)}dispose(){this._ops.dispose()}};const h=Object.freeze({CACHE:`cache`,USER:`user`,SCRATCH:`scratch`}),g=Object.freeze({DOWNLOADS:`downloads`,ARCHIVES:`archives`,SCENES:`scenes`,CDF:`cdf`,SPILL:`spill`}),_=`meta.json`,v=100*1024**3,y=64*1024**2,b=8*1024**2,x=new TextEncoder;function S(e,{copy:t,transfer:n}){if(typeof e==`string`&&(e=x.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 C(e,t){try{let n=await(await e.getFileHandle(t)).getFile();return JSON.parse(await n.text())}catch{return null}}async function*w(e){for await(let[t,n]of e.entries())n.kind===`directory`&&(yield[t,n])}var T=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(t){try{return await(await this._dir.getFileHandle(t)).getFile()}catch(n){return this.area.manager._issue(e.STORAGE_READ_FAILED,`could not read ${this.area.name}/${this.id}/${t}`,{error:n.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}},E=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:S(t,{copy:!0,transfer:r}))??S(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}=S(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=b}={}){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>=4&&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:1,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}=S(JSON.stringify(n),{copy:!1});return await this._transport.call(`writeFile`,{path:this._path,name:_,...i},a),this.area.kind===h.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`)}},D=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 C(e,_);if(!n||n.v!==1||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(t,{wait:n=!1}={}){let r=await d(t),i=await o(this._lockName(r),{mode:`shared`,ifAvailable:!n});if(!i)return null;try{let e=await this._entryDir(r),n=e?await this._validMeta(e,t):null;return n?(Date.now()-n.lastUsed>36e5&&this._touch(r,n),new T(this,r,n,e,i)):(i(),null)}catch(t){return i(),this.manager._issue(e.STORAGE_READ_FAILED,`could not open ${this.name} entry`,{error:t.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}=S(JSON.stringify(n),{copy:!1});this.manager._transport.call(`writeFile`,{path:[this.name,e],name:_,...r},i).catch(()=>{}),t.lastUsed=n.lastUsed}async create(t,{label:n=``,pinned:r=!1,expectedBytes:i=0,extra:a={},growable:s=[]}={}){let c=await d(t),l=await o(this._lockName(c),{mode:`exclusive`});try{return i>0&&!await this.manager.ensureSpace(i,this.kind)?(l(),this.manager._issue(e.STORAGE_QUOTA_EXCEEDED,`no room for ${(i/1048576).toFixed(0)} MB in ${this.name}`,{area:this.name,expectedBytes:i}),null):(await this._removeDir(c),await this._entryDir(c,!0),new E(this,c,t,{label:n,pinned:r,extra:a,growable:s},l))}catch(e){return l(),this.manager._writeFailed(this.name,e),null}}async patchMeta(e,t){let n=await d(e),r=await o(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}=S(JSON.stringify({...i,...t,v:1,key:e}),{copy:!1});return await this.manager._transport.call(`writeFile`,{path:[this.name,n],name:_,...a},o),!0}finally{r()}}async edit(e){let t=await d(e),n=await o(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 E(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 d(e))}async removeById(e){let t=await o(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 w(e)){let e=await C(r,_);e?.v===1&&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 s(),n=0;for await(let[r,i]of w(e))t.has(this._lockName(r))||await this._validMeta(i)||await this.removeById(r)&&n++;return n}},O=class extends f{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(g))this.defineArea(e,{kind:e===g.SPILL?h.SCRATCH:h.CACHE})}defineArea(e,{kind:t=h.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 D(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*.3,v)}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>3e4)&&(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===h.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===h.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 s(),o=t.filter(({area:e,meta:t})=>!t.pinned&&!a.has(e._lockName(t.id))).sort((e,t)=>e.meta.lastUsed-t.meta.lastUsed),c=0;for(let{area:e,meta:t}of o){if(c>=i)break;await e.removeById(t.id)&&(c+=t.bytes??0,r.bytes-=t.bytes??0)}return c}async ensureSpace(e,t=h.CACHE){let n=async()=>{let{quota:n,usage:r}=await this.estimate(),i=e+y-(n-r);return t===h.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===h.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(t,n){let r=n?.name===`QuotaExceededError`;this._issue(r?e.STORAGE_QUOTA_EXCEEDED:e.STORAGE_WRITE_FAILED,`${t}: ${n?.message??n}`,{area:t,error:n?.name})}dispose(){this._transport?.dispose(),this._transport=null,this._areas.clear()}};function k({namespace:e,root:t}){let n=new m(t);n.inline=!0;let r=new O({root:t,transport:n,namespace:e});return r.sweep().catch(()=>{}),r}const A=Object.freeze({IMMUTABLE:`immutable`,REVALIDATE:`revalidate`,NETWORK:`network`}),j=(e,t)=>({loaded:e,total:t,lengthComputable:t>0&&e<=t}),M=(e,t)=>e.headers?.get?.(t)??null,N=e=>e.reason??new DOMException(`aborted`,`AbortError`);function P(e){try{let t=new URL(e,globalThis.location?.href??`http://localhost/`).pathname;return decodeURIComponent(t.split(`/`).pop())||`download`}catch{return`download`}}async function F(e,{onProgress:t,signal:n}){let r=Number(M(e,`content-length`))||0,i=M(e,`content-type`)??``;if(!e.body)return new Blob([await e.arrayBuffer()],{type:i});let a=e.body.getReader(),o=[],s=0;for(;;){if(n?.aborted)throw a.cancel().catch(()=>{}),N(n);let{done:e,value:i}=await a.read();if(e)break;o.push(i),s+=i.length,t?.(j(s,r))}return new Blob(o,{type:i})}const I=(e,t,n)=>new File([e],t,{type:n||e.type,lastModified:e.lastModified??Date.now()}),L=()=>{};var R=class{constructor(e){this._storage=e,this._revalidating=new Set}get _area(){return this._storage?.area(g.DOWNLOADS)??null}async fetch(e,{key:t=e,name:n=P(e),policy:r=A.REVALIDATE,maxAgeMs:i=864e5,onProgress:a=null,signal:o=null,fetchOptions:s={}}={}){let c=this._area;if(c&&r!==A.NETWORK){let o=await c.open(t);if(o){let c=await o.file(`data`);if(c)return r===A.REVALIDATE&&Date.now()-(o.extra.checkedAt??0)>=i&&this._revalidate(e,t,n,o.extra,s),a?.(j(c.size,c.size)),{file:I(c,n,o.extra.contentType),release:()=>o.release(),fromCache:!0};o.release()}}return this._download(e,t,n,{onProgress:a,signal:o,fetchOptions:s,cache:!!c})}async has(e){return await this._area?.has(e)===!0}async _download(e,t,n,{onProgress:r,signal:i,fetchOptions:a,cache:o}){if(i?.aborted)throw N(i);let s=await fetch(e,{...a,signal:i});if(!s.ok)throw Error(`HTTP ${s.status} fetching ${e}`);let c=Number(M(s,`content-length`))||0,l={url:e,contentType:M(s,`content-type`)??``,lastModified:M(s,`last-modified`),contentLength:c||null,checkedAt:Date.now()},u=o&&s.body?await this._area.create(t,{label:n,expectedBytes:c}):null;if(!u)return{file:I(await F(s,{onProgress:r,signal:i}),n,l.contentType),release:L,fromCache:!1};try{await u.writeStream(`data`,s.body,{signal:i,onProgress:e=>r?.(j(e,c))}),await u.commit(l)}catch(o){if(await u.abort(),o?.name!==`QuotaExceededError`)throw o;return this._download(e,t,n,{onProgress:r,signal:i,fetchOptions:a,cache:!1})}let d=await this._area.open(t,{wait:!0}),f=d&&await d.file(`data`);if(!f)throw d?.release(),Error(`storage: ${n} vanished right after it was saved`);return{file:I(f,n,l.contentType),release:()=>d.release(),fromCache:!1}}async _revalidate(e,t,n,r,i){if(this._revalidating.has(t))return;this._revalidating.add(t);let a=!1;try{let t=new Headers(i?.headers);t.set(`Range`,`bytes=0-0`);let n=await fetch(e,{...i,headers:t});if(n.body?.cancel().catch(()=>{}),n.ok){let e=M(n,`last-modified`),t=n.status===206?Number(M(n,`content-range`)?.match(/\\/(\\d+)$/)?.[1])||null:Number(M(n,`content-length`))||null;a=!!(e&&r.lastModified&&e!==r.lastModified||t&&r.contentLength&&t!==r.contentLength)}}catch{}try{if(a){let{release:r}=await this._download(e,t,n,{fetchOptions:i,cache:!0});r()}else await this._area.patchMeta(t,{extra:{...r,checkedAt:Date.now()}})}catch{}finally{this._revalidating.delete(t)}}};let z={ortRuntimeUrl:`https://cdn.jsdelivr.net/npm/onnxruntime-web@1.24.3/dist/ort.webgpu.bundle.min.mjs`,ortWasmPaths:`https://cdn.jsdelivr.net/npm/onnxruntime-web@1.24.3/dist/`,cacheNamespace:`rayzee`,storage:`auto`},B=null;async function V(){return B||(B=await import(z.ortRuntimeUrl),B.env.wasm.wasmPaths=z.ortWasmPaths,B.env.logLevel=`error`,B)}let H=null,U=null,W=null;function G(){return W??=(async()=>{if(z.storage===!1||!navigator.storage?.getDirectory)return new R(null);try{let e=await(await navigator.storage.getDirectory()).getDirectoryHandle(z.cacheNamespace,{create:!0}),t=k({namespace:z.cacheNamespace,root:e});return await K(t).catch(()=>{}),new R(t)}catch{return new R(null)}})(),W}async function K(e){let t=`${z.cacheNamespace}:ai-upscaler-models`;if(typeof indexedDB>`u`||!indexedDB.databases||!(await indexedDB.databases()).some(e=>e.name===t))return;let n=await new Promise((e,n)=>{let r=indexedDB.open(t);r.onerror=()=>n(r.error),r.onsuccess=()=>{let t=r.result;if(!t.objectStoreNames.contains(`models`)){t.close(),e([]);return}let i=[],a=t.transaction(`models`,`readonly`).objectStore(`models`).openCursor();a.onerror=()=>n(a.error),a.onsuccess=()=>{let n=a.result;if(!n){t.close(),e(i);return}i.push([n.key,n.value]),n.continue()}}}),r=e.area(`downloads`);for(let[e,t]of n){if(typeof e!=`string`||!(t instanceof ArrayBuffer)||await r.has(e))continue;let n=await r.create(e,{label:e.split(`/`).pop(),expectedBytes:t.byteLength});n&&(await n.write(`data`,t,{transfer:!0}),await n.commit({url:e,contentType:`application/octet-stream`,checkedAt:Date.now()}))}await new Promise(e=>{let n=indexedDB.deleteDatabase(t);n.onsuccess=n.onerror=n.onblocked=()=>e()})}async function q(e){let{file:t,release:n,fromCache:r}=await(await G()).fetch(e);try{let e=await t.arrayBuffer();return r&&console.log(`AI Upscaler Worker: model loaded from cache (${(e.byteLength/1024/1024).toFixed(1)}MB)`),e}finally{n()}}async function J(e,t){if(H&&U===e){self.postMessage({type:`loaded`,backend:`webgpu`});return}H&&=(await H.release(),null);let[n,r]=await Promise.all([q(e),V()]);H=await r.InferenceSession.create(n,t),U=e;let i=512;try{let e=await navigator.gpu?.requestAdapter(),t=await e?.requestAdapterInfo?.()||e?.info,n=/apple|swiftshader|llvmpipe/i.test(t?.vendor||``)||/apple|swiftshader/i.test(t?.architecture||``),r=t?.device?.toLowerCase?.()?.includes(`integrated`)||/intel.*iris|intel.*uhd|intel.*hd|amd.*vega|radeon.*graphics/i.test(t?.description||``);i=n?128:r?256:512,console.log(`AI Upscaler Worker: GPU="${t?.description||t?.device||`unknown`}", tileSize=${i}`)}catch{}let a=(n.byteLength/1024/1024).toFixed(1);console.log(`AI Upscaler Worker: model loaded (${a}MB), backend: webgpu`),self.postMessage({type:`loaded`,backend:`webgpu`,tileSize:i})}async function Y(e,t,n,r){let i=await V(),a=H.inputNames[0],o=H.outputNames[0],s=new i.Tensor(`float32`,e,[1,3,n,t]),c=(await H.run({[a]:s}))[o].data;self.postMessage({type:`inferred`,outputData:c,id:r},[c.buffer])}self.onmessage=async e=>{let{type:t}=e.data;try{t===`load`?(e.data.ortRuntimeUrl&&(z.ortRuntimeUrl=e.data.ortRuntimeUrl),e.data.ortWasmPaths&&(z.ortWasmPaths=e.data.ortWasmPaths),e.data.cacheNamespace&&(z.cacheNamespace=e.data.cacheNamespace),e.data.storage!==void 0&&(z.storage=e.data.storage),await J(e.data.url,e.data.sessionOptions)):t===`infer`?await Y(e.data.tileData,e.data.width,e.data.height,e.data.id):t===`dispose`&&H&&(await H.release(),H=null,U=null)}catch(t){self.postMessage({type:`error`,message:t.message,id:e.data?.id})}};',AC=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,kC],{type:`text/javascript;charset=utf-8`});function jC(e){let t;try{if(t=AC&&(self.URL||self.webkitURL).createObjectURL(AC),!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(kC),{type:`module`,name:e?.name})}}Vv(),ui();var MC={fast:{2:`2x-spanx2-ch48.onnx`,4:`4xNomos8k_span_otf_strong_fp32_opset17.onnx`},balanced:{2:`2xNomosUni_compact_otf_medium.onnx`,4:`RealESRGAN_x4plus.onnx`},quality:{2:`2x-realesrgan-x2plus.onnx`,4:`4xNomos2_hq_mosr_fp32.onnx`}};function NC(){let{upscalerModelBaseUrl:e}=si(),t={};for(let n in MC){t[n]={};for(let r in MC[n])t[n][r]=e+MC[n][r]}return t}var PC={get QUALITY_PRESETS(){return NC()},TILE_SIZE:512,TILE_OVERLAP:16,SESSION_OPTIONS:{executionProviders:[{name:`webgpu`,preferredLayout:`NCHW`}],graphOptimizationLevel:`all`}},FC=class extends r.EventDispatcher{constructor(e,t,n={}){if(super(),!e||!t)throw Error(`AIUpscaler requires output canvas and renderer`);this.renderer=t,this.input=t.domElement,this.output=e,this.getSourceCanvas=n.getSourceCanvas||null,this.getGPUTextures=n.getGPUTextures||null,this.getExposure=n.getExposure||(()=>1),this.getToneMapping=n.getToneMapping||(()=>r.ACESFilmicToneMapping),this.getColorSpace=n.getColorSpace||(()=>`srgb`),this.getSaturation=n.getSaturation||(()=>1),this.getDisplayGain=n.getDisplayGain||(()=>null),this.getTransparentBackground=n.getTransparentBackground||(()=>!1),this.enabled=!1,this.hdr=!1,this.scaleFactor=n.scaleFactor||2,this.quality=n.quality||`fast`,this.refreshInput=n.refreshInput||null,this.tileSize=n.tileSize||PC.TILE_SIZE,this._tileSizeOverride=!!n.tileSize,this.state={isUpscaling:!1,isLoading:!1,abortController:null},this._worker=null,this._currentModelUrl=null,this._tileId=0,this._pendingWorkerHandlers=new Map,this._upscaledAlpha=null,this._upscaledAlphaWidth=0,this._backupCanvas=null,this._baseWidth=e.width,this._baseHeight=e.height,this._toneMapper=null}async _ensureSession(){let e=PC.QUALITY_PRESETS[this.quality];if(!e)throw Error(`Unknown quality preset: ${this.quality}`);let t=e[this.scaleFactor];if(!t)throw Error(`No model for ${this.quality}/${this.scaleFactor}x`);if(!(this._worker&&this._currentModelUrl===t)){this.state.isLoading=!0,this.dispatchEvent({type:`loading`,message:`Loading ${this.scaleFactor}x upscale model...`});try{this._worker||=new jC,await new Promise((e,n)=>{let r=t=>{t.data.type===`loaded`?(this._worker.removeEventListener(`message`,r),t.data.tileSize&&!this._tileSizeOverride&&(this.tileSize=t.data.tileSize),console.log(`AI Upscaler: ${this.scaleFactor}x model loaded, backend: ${t.data.backend}, tileSize: ${this.tileSize}`),e()):t.data.type===`error`&&(this._worker.removeEventListener(`message`,r),n(Error(t.data.message)))},{ortRuntimeUrl:i,ortWasmPaths:a,cacheNamespace:o,storage:s}=si();this._worker.addEventListener(`message`,r),this._worker.postMessage({type:`load`,url:t,sessionOptions:PC.SESSION_OPTIONS,ortRuntimeUrl:i,ortWasmPaths:a,cacheNamespace:o,storage:s})}),this._currentModelUrl=t,this.dispatchEvent({type:`loaded`})}catch(e){throw console.error(`AI Upscaler: Failed to load model:`,e),this.dispatchEvent({type:`error`,error:e}),e}finally{this.state.isLoading=!1}}}async start(e=null){if(!this.enabled||this.state.isUpscaling||this.state.isLoading)return!1;this.dispatchEvent({type:`start`});let t=performance.now(),n=await this.execute(e);if(n){this.renderer?.resetState?.();let e=performance.now()-t;console.log(`AI Upscaler: ${this.scaleFactor}x upscale completed in ${e.toFixed(1)}ms`)}return n}_revealOutput(){this.output.style.display=`block`,this.input.style.opacity=`0`}async execute(e=null){if(!this.enabled)return!1;this.state.abortController=new AbortController,this.state.isUpscaling=!0,this._sourceColorSpace=e?.colorSpace??(this.hdr&&this.getGPUTextures?this.getColorSpace():`srgb`),e?this._capturedSource=e:this.hdr&&this.getGPUTextures?this._capturedSource=await this._captureSourceHDR():this._capturedSource=this._captureSource(),this._createBackup(this._capturedSource);let t=this._capturedSource.width*this.scaleFactor,n=this._capturedSource.height*this.scaleFactor;this.output.width=t,this.output.height=n;let r=this.output.getContext(`2d`,{willReadFrequently:!0,alpha:!0});r.imageSmoothingEnabled=!0,r.imageSmoothingQuality=`high`,r.drawImage(this._backupCanvas,0,0,t,n),this._revealOutput();try{return await this._ensureSession(),await this._runUpscale(),this.dispatchEvent({type:`resolution_changed`,width:this.output.width,height:this.output.height}),!0}catch(e){return e.name===`AbortError`?console.log(`AI Upscaler: Upscaling was aborted`):(console.error(`AI Upscaler: Upscaling error:`,e),this.dispatchEvent({type:`error`,error:e}),this._restoreBackup(),this.input.style.opacity=`1`,this.dispatchEvent({type:`resolution_changed`,width:this._baseWidth,height:this._baseHeight})),!1}finally{this._capturedSource=null,this._upscaledAlpha=null,this._backupCanvas=null,this.state.isUpscaling&&(this.state.isUpscaling=!1,this.state.abortController=null,this.dispatchEvent({type:`end`}))}}abort(){this.state.isUpscaling&&(this.state.abortController?.abort(),this._cleanupPendingWorkerHandlers(),this.input.style.opacity=`1`,this._restoreBackup(),this.dispatchEvent({type:`resolution_changed`,width:this._baseWidth,height:this._baseHeight}),this.state.isUpscaling=!1,this.dispatchEvent({type:`end`}),console.log(`AI Upscaler: Aborted`))}async _runUpscale(){let e=this.state.abortController.signal,t=this._capturedSource;this._capturedSource=null;let{width:n,height:r}=t,i=this.scaleFactor,a=this.output.getContext(`2d`,{willReadFrequently:!0,alpha:!0});this._cacheUpscaledAlpha(t,n*i,r*i);let o=PC.TILE_OVERLAP,s=this.tileSize,c=s-o*2,l=Math.ceil(n/c),u=Math.ceil(r/c),d=l*u,f=0;for(let o=0;o<u;o++)for(let u=0;u<l;u++){if(e.aborted)throw new DOMException(`Aborted`,`AbortError`);let l=Math.min(u*c,Math.max(0,n-s)),p=Math.min(o*c,Math.max(0,r-s)),m=Math.min(s,n-l),h=Math.min(s,r-p),g=this._extractTile(t,l,p,m,h),_=await this._inferTile(g,m,h),v=l*i,y=p*i,b=m*i,x=h*i,S=this._tensorToImageData(_,b,x,v,y);a.putImageData(S,v,y),f++,this.dispatchEvent({type:`progress`,progress:f/d,tile:{x:u,y:o,total:d,completed:f}}),this.dispatchEvent({type:`tileProgress`,tile:{x:v,y,width:b,height:x},imageWidth:n*i,imageHeight:r*i})}}_captureSource(){let e=this.getSourceCanvas?this.getSourceCanvas():null;if(e&&e!==this.output){this.refreshInput?.();let t=document.createElement(`canvas`);t.width=e.width,t.height=e.height;let n=t.getContext(`2d`);return n.drawImage(e,0,0),n.getImageData(0,0,t.width,t.height)}return this.output.getContext(`2d`,{willReadFrequently:!0}).getImageData(0,0,this.output.width,this.output.height)}async _captureSourceHDR(){let e=this.getGPUTextures();if(!e?.color)throw Error(`No GPU color texture available for HDR capture`);let t=e.color,{width:n,height:i}=t;this._toneMapper??=new Bv(this.renderer.backend.device,`aiupscaler-tonemap`,{input:`texture`,output:`planar`}),this._toneMapper.ensureSize(n,i);let a=await this._toneMapper.toPlanar(t,{exposure:this.getExposure(),toneMapping:this.getToneMapping()??r.ACESFilmicToneMapping,saturation:this.getSaturation(),gain:this.getDisplayGain()});return this._toneMapper.release(),this.getTransparentBackground()||a.fill(1,3*n*i),{planes:a,width:n,height:i,isHDR:!0}}_extractTile(e,t,n,r,i){let{width:a}=e,o=r*i,s=new Float32Array(3*o);if(e.isHDR){let{planes:c}=e,l=a*e.height;for(let e=0;e<3;e++)for(let u=0;u<i;u++){let i=e*l+(n+u)*a+t;s.set(c.subarray(i,i+r),e*o+u*r)}return s}let{data:c}=e;for(let e=0;e<i;e++)for(let i=0;i<r;i++){let l=((n+e)*a+(t+i))*4,u=e*r+i;s[u]=c[l]/255,s[o+u]=c[l+1]/255,s[2*o+u]=c[l+2]/255}return s}async _inferTile(e,t,n){let r=++this._tileId;return new Promise((i,a)=>{let o=e=>{e.data.id===r&&(this._worker.removeEventListener(`message`,o),this._pendingWorkerHandlers.delete(o),e.data.type===`inferred`?i(e.data.outputData):e.data.type===`error`&&a(Error(e.data.message)))};this._pendingWorkerHandlers.set(o,a),this._worker.addEventListener(`message`,o),this._worker.postMessage({type:`infer`,tileData:e,width:t,height:n,id:r},[e.buffer])})}_tensorToImageData(e,t,n,r,i){let a=new ImageData(t,n,{colorSpace:this._sourceColorSpace??`srgb`}),o=a.data,s=t*n,c=this._upscaledAlpha,l=this._upscaledAlphaWidth;for(let n=0;n<s;n++)if(o[n*4]=Math.min(255,Math.max(0,e[n]*255+.5))|0,o[n*4+1]=Math.min(255,Math.max(0,e[s+n]*255+.5))|0,o[n*4+2]=Math.min(255,Math.max(0,e[2*s+n]*255+.5))|0,c){let e=n/t|0,a=n%t;o[n*4+3]=c[(i+e)*l+(r+a)]}else o[n*4+3]=255;return a}_cacheUpscaledAlpha(e,t,n){let{width:r,height:i}=e,a=r*i,o=e.isHDR,s=o?e.planes.subarray(3*a):e.data,c=o?1:4,l=o?0:3,u=o?1:255,d=!1;for(let e=l;e<s.length;e+=c)if(s[e]<u){d=!0;break}if(!d){this._upscaledAlpha=null,this._upscaledAlphaWidth=0;return}let f=document.createElement(`canvas`);f.width=r,f.height=i;let p=f.getContext(`2d`),m=p.createImageData(r,i);for(let e=0;e<a;e++){let t=o?Math.min(Math.max(s[e]*255,0),255)|0:s[e*4+3];m.data[e*4]=t,m.data[e*4+1]=t,m.data[e*4+2]=t,m.data[e*4+3]=255}p.putImageData(m,0,0);let h=document.createElement(`canvas`);h.width=t,h.height=n;let g=h.getContext(`2d`);g.imageSmoothingEnabled=!0,g.imageSmoothingQuality=`high`,g.drawImage(f,0,0,t,n);let _=g.getImageData(0,0,t,n).data,v=new Uint8Array(t*n);for(let e=0,r=t*n;e<r;e++)v[e]=_[e*4];this._upscaledAlpha=v,this._upscaledAlphaWidth=t}_createBackup(e){this._backupCanvas=document.createElement(`canvas`),this._backupCanvas.width=e.width,this._backupCanvas.height=e.height;let t=this._backupCanvas.getContext(`2d`);if(e.isHDR){let{planes:n,width:r,height:i}=e,a=r*i,o=t.createImageData(r,i,{colorSpace:this._sourceColorSpace??`srgb`}),s=o.data;for(let e=0;e<a;e++){let t=e*4;s[t]=n[e]*255+.5|0,s[t+1]=n[a+e]*255+.5|0,s[t+2]=n[2*a+e]*255+.5|0,s[t+3]=255}t.putImageData(o,0,0)}else t.putImageData(e,0,0)}_restoreBackup(){this._backupCanvas&&=(this.output.width=this._backupCanvas.width,this.output.height=this._backupCanvas.height,this.output.getContext(`2d`).drawImage(this._backupCanvas,0,0),null)}toggleHDR(e){this.hdr=!!e}setQuality(e){if(!PC.QUALITY_PRESETS[e]){console.warn(`AIUpscaler: Invalid quality "${e}", must be fast/balanced/quality`);return}this.quality=e}setScaleFactor(e){if(e=Number(e),e!==2&&e!==4){console.warn(`AIUpscaler: Invalid scale factor ${e}, must be 2 or 4`);return}this.scaleFactor=e}setBaseSize(e,t){this._baseWidth=e,this._baseHeight=t}_cleanupPendingWorkerHandlers(){for(let[e,t]of this._pendingWorkerHandlers)this._worker?.removeEventListener(`message`,e),t(new DOMException(`Aborted`,`AbortError`));this._pendingWorkerHandlers.clear()}async dispose(){this.abort(),this._cleanupPendingWorkerHandlers(),this._worker&&=(this._worker.postMessage({type:`dispose`}),this._worker.terminate(),null),this._currentModelUrl=null,this._backupCanvas=null,this._upscaledAlpha=null,this.state.abortController=null,this._toneMapper?.dispose(),this._toneMapper=null,console.log(`AIUpscaler disposed`)}},IC=_({NeuralSuperRes:()=>ZC,SR_MAX_INPUT:()=>qC,SR_SCALE:()=>2,presentRGBA8:()=>WC,readDenoisedHalf:()=>BC,releaseDenoisedReader:()=>zC,renderUpscaled:()=>HC});function LC(){if(JC)return JC;let{neuralRuntimeUrl:e,neuralAssetBaseUrl:t}=si();return t?(globalThis.__NEURAL_ASSET_BASE__=t,JC=new Promise((t,n)=>{if(globalThis.NeuralRuntime?.getNativeSR)return t(globalThis.NeuralRuntime.getNativeSR());let r=document.createElement(`script`);r.src=e,r.onload=()=>{let e=globalThis.NeuralRuntime?.getNativeSR;if(!e)return n(Error(`Neural runtime loaded but exposed no super-resolution entry`));t(e())},r.onerror=()=>n(Error(`Failed to load the neural runtime from ${e}`)),document.head.appendChild(r)}),JC):Promise.reject(Error(`No neural model location: set neuralAssetBaseUrl with configureAssets()`))}function RC(e,t,n){if(XC&&(XC.device!==e||XC.width!==t||XC.height!==n)&&zC(),XC)return XC;let r=t*n*8;return XC={device:e,width:t,height:n,storage:e.createBuffer({label:`rayzee:neural-sr-pack`,size:r,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC}),map:e.createBuffer({label:`rayzee:neural-sr-pack-map`,size:r,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),pipeline:e.createComputePipeline({label:`rayzee:neural-sr-pack`,layout:`auto`,compute:{module:e.createShaderModule({label:`rayzee:neural-sr-pack`,code:YC}),entryPoint:`main`}})},XC}function zC(){XC?.storage.destroy(),XC?.map.destroy(),XC=null}async function BC(e){let t=e?._outGPUTexture;if(!t)throw Error(`NeuralSuperRes: no denoised frame — enable OIDN and finish a render first`);let n=e.gpuDevice,{width:r,height:i}=e._outTexSize,a=RC(n,r,i),o=n.createBindGroup({layout:a.pipeline.getBindGroupLayout(0),entries:[{binding:0,resource:t.createView()},{binding:1,resource:{buffer:a.storage}}]}),s=n.createCommandEncoder({label:`rayzee:neural-sr-pack`}),c=s.beginComputePass();c.setPipeline(a.pipeline),c.setBindGroup(0,o),c.dispatchWorkgroups(Math.ceil(r/8),Math.ceil(i/8)),c.end(),s.copyBufferToBuffer(a.storage,0,a.map,0,r*i*8),n.queue.submit([s.finish()]),await a.map.mapAsync(GPUMapMode.READ);let l=new Uint16Array(a.map.getMappedRange().slice(0));return a.map.unmap(),{half:l,width:r,height:i}}function VC(e,t,n){return new Promise((r,i)=>{let a=!1,o=(t,n)=>{a||(a=!0,e.removeEventListener(N.DENOISING_END,c),clearInterval(l),clearTimeout(u),t?r():i(n))},s=!1,c=()=>{(e.stages?.pathTracer?.frameCount??0)>=t&&(s=!0)};e.addEventListener(N.DENOISING_END,c);let l=setInterval(()=>{s&&o(!0)},200),u=setTimeout(()=>o(!1,Error(`NeuralSuperRes: timed out waiting for the render to finish`)),n)})}async function HC(e,{outputWidth:t,outputHeight:n,samples:r=64,upscaler:i=null,timeoutMs:a=6e5,present:o=!0,onProgress:s=()=>{}}={}){if(t%2||n%2)throw Error(`renderUpscaled: output must be divisible by 2, got ${t}x${n}`);let c=t/2,l=n/2,u=e.stages?.pathTracer,d={width:u?.width,height:u?.height,maxSamples:e.settings?.get?.(`maxSamples`),renderLimitMode:e.settings?.get?.(`renderLimitMode`),finalDenoise:e.denoisingManager?.finalDenoise,paused:e.pauseRendering},f=!i,p=i,m={};try{if(!p){let e=performance.now();s(`Loading the super-resolution model`),p=await ZC.create({width:c,height:l,onProgress:s}),m.load=performance.now()-e}else if(p.inputWidth!==c||p.inputHeight!==l)throw Error(`renderUpscaled: upscaler is ${p.inputWidth}x${p.inputHeight}, need ${c}x${l}`);let i=performance.now();s(`Tracing ${c}x${l} at ${r} spp`),e.pauseRendering=!1,e.setCanvasSize(c,l),await new Promise(e=>setTimeout(e,300)),e.denoisingManager.applyOIDNEnabled(!0),e.settings.setMany({maxSamples:r,renderLimitMode:`frames`},{reset:!1});let u=VC(e,r,a);e.reset(),await u,e.pauseRendering=!0,m.render=performance.now()-i,s(`Reading the denoised frame`);let d=performance.now(),f=await BC(e.denoisingManager?.denoiser);m.read=performance.now()-d,s(`Upscaling to ${t}x${n}`);let h={exposure:e.renderer.toneMappingExposure,toneMapping:e.renderer.toneMapping,saturation:e.settings.get(`saturation`)??1,gain:e._displayGain?.()??null},{rgba8:g,width:_,height:v,ms:y,toneMs:b}=await p.upscaleToRGBA8(f,h);return m.upscale=y,m.tonemap=b,o&&UC(e.denoisingManager?.upscalerCanvas,g,_,v,e.color?.canvasColorSpace),{rgba8:g,width:_,height:v,timings:m,upscaler:p}}catch(e){throw f&&p?.dispose(),e}finally{d.width&&d.height&&e.setCanvasSize(d.width,d.height),d.maxSamples!==void 0&&e.settings?.set?.(`maxSamples`,d.maxSamples),d.renderLimitMode!==void 0&&e.settings?.set?.(`renderLimitMode`,d.renderLimitMode,{reset:!1}),d.finalDenoise!==void 0&&e.denoisingManager?.applyOIDNEnabled(d.finalDenoise),e.pauseRendering=d.paused}}function UC(e,t,n,r,i=`srgb`){return e?(e.width=n,e.height=r,e.getContext(`2d`).putImageData(new ImageData(new Uint8ClampedArray(t.buffer??t),n,r,{colorSpace:i}),0,0),e.style.display=`block`,!0):!1}function WC(e,t,n,r,i){return UC(e,t,n,r,i)}var GC,KC,qC,JC,YC,XC,ZC,QC=g((()=>{F(),Ae(),Vv(),ui(),GC=2,KC=ve(`neural`),qC=2048,JC=null,YC=`
|
|
1336
1336
|
@group(0) @binding(0) var src: texture_2d<f32>;
|
|
1337
1337
|
@group(0) @binding(1) var<storage, read_write> dst: array<u32>;
|
|
1338
1338
|
|
|
@@ -1372,7 +1372,7 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
|
|
|
1372
1372
|
dst[a] = pack2x16float(c.rg);
|
|
1373
1373
|
dst[a + 1u] = pack2x16float(vec2<f32>(c.b, 1.0));
|
|
1374
1374
|
}
|
|
1375
|
-
`,uw=class e{constructor(e,t){this.chain=e,this.canvas=t,this.slot=0,this.source=null,this.staging=null,this._readbackPipeline=null,this._readbackStorage=null,this._readbackMap=null,this._hdrPipeline=null,this._hdrStorage=null,this._hdrMap=null,this._toneMapper=null,this.disposed=!1}get device(){return this.chain.device}get width(){return this.chain.pipeline.geometry.validWidth}get height(){return this.chain.pipeline.geometry.validHeight}static async create({width:t,height:n,canvas:r=null,settings:i={},onProgress:a=()=>{}}){if(!Number.isInteger(t)||!Number.isInteger(n)||t<1||n<1)throw Error(`NeuralRetouch.create: width and height must be positive integers`);if(t*n>4194304)throw Error(`NeuralRetouch.create: ${t}x${n} is ${(t*n/1e6).toFixed(1)} MP, above the ${(aw/1e6).toFixed(1)} MP this pass survives. Past it the run takes minutes and then loses every GPU device in the page.`);let o=r??document.createElement(`canvas`);r||(o.style.cssText=`position:fixed;left:-10000px;top:0;pointer-events:none`);let s=new e(await(await tw()).create(o,t,n,a,ew(i).runtime),o);return s._allocate(),s}_allocate(){let{validWidth:e,validHeight:t}=this.chain.pipeline.geometry;this.source=this.device.createBuffer({label:`rayzee:retouch-source`,size:e*t*8,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST}),this.staging=new Uint16Array(e*t*4);let n=e*t*4;this._readbackStorage=this.device.createBuffer({label:`rayzee:retouch-readback`,size:n,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC}),this._readbackMap=this.device.createBuffer({label:`rayzee:retouch-readback-map`,size:n,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),this._readbackPipeline=this.device.createComputePipeline({label:`rayzee:retouch-readback`,layout:`auto`,compute:{module:this.device.createShaderModule({code:cw}),entryPoint:`main`}});let r=e*t*8;this._hdrStorage=this.device.createBuffer({label:`rayzee:retouch-hdr`,size:r,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC}),this._hdrMap=this.device.createBuffer({label:`rayzee:retouch-hdr-map`,size:r,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),this._hdrPipeline=this.device.createComputePipeline({label:`rayzee:retouch-hdr`,layout:`auto`,compute:{module:this.device.createShaderModule({code:lw}),entryPoint:`main`}})}async _packHDR(e,t,n=!1){let r=this.chain.pipeline.slots[this.slot]?.hdrOutput;if(!r)throw Error("NeuralRetouch: the runtime has no scene-referred output. Either no frame has been produced yet, or neural-runtime.js was re-vendored without its `rayzee-patch` edits.");let i=this.device.createBindGroup({layout:this._hdrPipeline.getBindGroupLayout(0),entries:[{binding:0,resource:r.createView()},{binding:1,resource:{buffer:this._hdrStorage}}]}),a=this.device.createCommandEncoder({label:`rayzee:retouch-hdr`}),o=a.beginComputePass();o.setPipeline(this._hdrPipeline),o.setBindGroup(0,i),o.dispatchWorkgroups(Math.ceil(e/8),Math.ceil(t/8)),o.end(),n&&a.copyBufferToBuffer(this._hdrStorage,0,this._hdrMap,0,e*t*8),this.device.queue.submit([a.finish()])}async readOutputHDR(){let{validWidth:e,validHeight:t}=this.chain.pipeline.geometry;await this._packHDR(e,t,!0),await this._hdrMap.mapAsync(GPUMapMode.READ);let n=new Uint16Array(this._hdrMap.getMappedRange().slice(0));return this._hdrMap.unmap(),{half:n,width:e,height:t}}async readOutputToned(e){let{validWidth:t,validHeight:n}=this.chain.pipeline.geometry;return await this._packHDR(t,n),this._toneMapper??=new Bv(this.device,`rayzee:retouch-tonemap`),this._toneMapper.ensureSize(t,n),{rgba8:await this._toneMapper.toRGBA8(this._hdrStorage,{exposure:e.exposure??1,toneMapping:e.toneMapping??0,saturation:e.saturation??1,gain:e.gain}),width:t,height:n}}async readOutput(){let{validWidth:e,validHeight:t}=this.chain.pipeline.geometry,n=this.chain.pipeline.slots[this.slot]?.output;if(!n)throw Error(`NeuralRetouch.readOutput: the pass has not produced a frame yet`);let r=this.device.createBindGroup({layout:this._readbackPipeline.getBindGroupLayout(0),entries:[{binding:0,resource:n.createView()},{binding:1,resource:{buffer:this._readbackStorage}}]}),i=this.device.createCommandEncoder({label:`rayzee:retouch-readback`}),a=i.beginComputePass();a.setPipeline(this._readbackPipeline),a.setBindGroup(0,r),a.dispatchWorkgroups(Math.ceil(e/8),Math.ceil(t/8)),a.end(),i.copyBufferToBuffer(this._readbackStorage,0,this._readbackMap,0,e*t*4),this.device.queue.submit([i.finish()]),await this._readbackMap.mapAsync(GPUMapMode.READ);let o=new Uint8ClampedArray(this._readbackMap.getMappedRange().slice(0));return this._readbackMap.unmap(),o}dispose(){if(!this.disposed){this.disposed=!0,this.source?.destroy(),this._readbackStorage?.destroy(),this._readbackMap?.destroy(),this._hdrStorage?.destroy(),this._hdrMap?.destroy(),this._toneMapper?.dispose();try{this.chain.destroy()}catch(e){iw.warn(`retouch teardown:`,e)}}}},dw=20}));F(),an(),Ae(),lt();var pw=ve(`neural`),mw=120,hw=2,gw=1,_w=0,vw=300,yw=5,bw=3,xw=3,Sw=16,Cw=e=>Math.max(0,1-e/Sw),ww=class extends r.EventDispatcher{constructor({renderer:e,mainCanvas:t,stages:n,pipeline:i,getExposure:a,getSaturation:o,getDisplayGain:s=null,issues:c=null}){super(),this.renderer=e,this._issues=c,this.mainCanvas=t,this.upscalerCanvas=this._createUpscalerCanvas(t),this.pipeline=i,this._stages=n,this._getExposure=a,this._getSaturation=o,this._getDisplayGain=s,this.denoiser=null,this.upscaler=null,this.upscalerBackend=`esrgan`,this._neuralUpscaler=null,this.neuralRendering=!1,this.neuralRenderingSettings={},this._retouch=null,this._superResModule=null,this._neuralPostBusy=!1,this._postIsStillComplete=null,this._postRun=null,this._postRedo=null,this._postCancelled=!1,this._finalQuality=sb.oidnQuality,this.finalDenoise=sb.enableOIDN,this.continuousDenoise=sb.continuousDenoise,this.continuousDenoiseInterval=sb.continuousDenoiseInterval,this._lastCadenceAt=-1/0,this._lastCadenceSamples=0,this._failedRefreshes=0,this._cadenceSuspended=!1,this._movingDenoiseMs=[],this._movingHopeless=!1,this._holdWhileMoving=null,this._onReset=null,this._onPostProcessRefresh=null,this._onDisplayRefresh=null,this.temporalHistory=sb.oidnTemporalHistory,this._history=null,this._historyDirty=!0,this._knownResetCount=0,this._seenTracedFrames=0,this._viewProj=new r.Matrix4,this._historyCamera={world:null,projInv:null,viewProj:null,orthographic:!1},this._movedPlacements=new Map,this._movedUpload={count:0,leaves:new Uint32Array,toPrev:new Float32Array},this._matA=new r.Matrix4,this._matB=new r.Matrix4,this._lastRenderWidth=0,this._lastRenderHeight=0,this._pendingStartUpscaler=null,this._pendingCloseDenoise=null,this._denoiserStartHandler=null,this._denoiserEndHandler=null,this._denoiserTileHandler=null,this._denoiserErrorHandler=null,this._denoiserLoadHandler=null,this._upscalerResChangedHandler=null,this._upscalerStartHandler=null,this._upscalerProgressHandler=null,this._upscalerEndHandler=null}_createUpscalerCanvas(e){let t=e.parentNode;if(!t)return null;let n=document.createElement(`canvas`);return n.width=e.width,n.height=e.height,n.style.position=`absolute`,n.style.inset=`0`,n.style.width=`100%`,n.style.height=`100%`,n.style.display=`none`,t.insertBefore(n,e),n}gpuBytes(){return(this.denoiser?.gpuBytes?.()??0)+(this._history?.gpuBytes?.()??0)}_recordNoOverlayCanvas(e){this._issues?.record(X.DENOISER_UNAVAILABLE,`the ${e} pass needs the render canvas to be in a document, and it is not — skipped`,{pass:e})}setRenderSize(e,t){this._lastRenderWidth=e,this._lastRenderHeight=t,this._cadenceDowngraded=!1,this._holdWhileMoving=null,this._movingDenoiseMs.length=0,this._movingHopeless=!1,this._historyDirty=!0,this.denoiser?.abort(),this._unpublishOutput(),this.denoiser?.setSize(e,t),this.upscalerCanvas&&(this.upscalerCanvas.width!==e||this.upscalerCanvas.height!==t)&&(this.upscalerCanvas.width=e,this.upscalerCanvas.height=t),this.upscaler?.setBaseSize(e,t),this._syncGBufferStages()}restoreBaseResolution(){return!this.upscalerCanvas||!this._lastRenderWidth||!this._lastRenderHeight||!(this.upscalerCanvas.width!==this._lastRenderWidth||this.upscalerCanvas.height!==this._lastRenderHeight)?!1:(this.upscalerCanvas.width=this._lastRenderWidth,this.upscalerCanvas.height=this._lastRenderHeight,!0)}setupDenoiser(){let e=this._stages.pathTracer;this.denoiser=new fC(this.renderer,{enableOIDN:sb.enableOIDN,oidnQuality:sb.oidnQuality,backendParams:()=>({device:this.renderer.backend.device,adapterInfo:null}),getGPUTextures:({continuous:t=!1}={})=>{if(!e?.storageTextures?.readTarget)return null;let n=t?this._historyTextures():null;if(n)return n;let r=e.storageTextures.getReadTextures(),{backend:i}=this.renderer;return{color:i.get(r.color).texture,normal:i.get(r.normalDepth).texture,albedo:i.get(r.albedo).texture}}}),this._syncOIDNInUse(),this._denoiserStartHandler=e=>this.dispatchEvent({type:N.DENOISING_START,continuous:!!e.continuous}),this._denoiserEndHandler=e=>{let t=!e.continuous||this.continuousDenoise&&!this._cadenceSuspended;this.denoiser?.hasOutput&&t&&this._publishOutput(),this.dispatchEvent({type:N.DENOISING_END,continuous:!!e.continuous})},this._denoiserTileHandler=e=>{if(e.continuous)return;this._publishOutput();let t=this.pipeline?.context;this._stages.compositor&&t&&this._stages.compositor.render(t)},this._denoiserErrorHandler=e=>e.url&&this._issues?.record(X.ASSET_UNREACHABLE,`denoiser weights "${e.url}" could not be loaded — the render is not denoised`,{url:e.url,asset:`oidn-weights`,cause:String(e.error?.message??e.error)}),this.denoiser.addEventListener(`start`,this._denoiserStartHandler),this.denoiser.addEventListener(`end`,this._denoiserEndHandler),this.denoiser.addEventListener(`tileProgress`,this._denoiserTileHandler),this.denoiser.addEventListener(`error`,this._denoiserErrorHandler),this._denoiserLoadHandler=e=>this.dispatchEvent({type:N.DENOISER_LOADING,loading:e.type===`loading`});for(let e of[`loading`,`loaded`,`error`])this.denoiser.addEventListener(e,this._denoiserLoadHandler);this.denoiser.state?.isLoading&&this.dispatchEvent({type:N.DENOISER_LOADING,loading:!0})}setupUpscaler(){if(!this.upscalerCanvas)return;let e=this._stages.pathTracer;this.upscaler=new FC(this.upscalerCanvas,this.renderer,{scaleFactor:sb.upscalerScale||2,quality:sb.upscalerQuality||`fast`,getSourceCanvas:()=>this.renderer.domElement,refreshInput:()=>{let e=this.pipeline?.context;this._stages.compositor&&e&&this._stages.compositor.render(e)},getGPUTextures:()=>{if(!e?.storageTextures?.readTarget)return null;let t=e.storageTextures.getReadTextures();return{color:this.renderer.backend.get(t.color).texture}},getExposure:()=>this._getEffectiveExposure(),getToneMapping:()=>this._getToneMapping(),getSaturation:()=>this._getSaturation(),getDisplayGain:()=>this._getDisplayGain?.()??null,getTransparentBackground:()=>!!this._settings?.get(`transparentBackground`)}),this.upscaler.enabled=sb.enableUpscaler||!1,this._upscalerResChangedHandler=e=>this.dispatchEvent({type:N.RESOLUTION_CHANGED,width:e.width,height:e.height}),this._upscalerStartHandler=()=>this.dispatchEvent({type:N.UPSCALING_START}),this._upscalerProgressHandler=e=>this.dispatchEvent({type:N.UPSCALING_PROGRESS,progress:e.progress}),this._upscalerEndHandler=()=>this.dispatchEvent({type:N.UPSCALING_END}),this.upscaler.addEventListener(`resolution_changed`,this._upscalerResChangedHandler),this.upscaler.addEventListener(`start`,this._upscalerStartHandler),this.upscaler.addEventListener(`progress`,this._upscalerProgressHandler),this.upscaler.addEventListener(`end`,this._upscalerEndHandler)}get denoiserStrategy(){return this.continuousDenoise?`oidn`:this._stages.nrd?.enabled?`nrd`:`none`}setDenoiserStrategy(e,t){let n=this._stages;tb.includes(e)||(this._issues?.record(X.DENOISER_UNAVAILABLE,`'${e}' is not a live denoiser (${tb.join(`, `)}) — none is used`,{strategy:e}),e=`none`),e===`nrd`&&this._isPanorama()&&(this._issues?.record(X.DENOISER_UNAVAILABLE,`NRD cannot run in a panorama — oidn is used`,{strategy:e}),e=`oidn`),this._clearDenoiserTextures(),n.nrd&&(n.nrd.enabled=e===`nrd`),n.nrd?.enabled&&(n.nrd.resetHistory?.(),this._applyNRDPreset(t||`medium`)),this.setContinuousDenoise(e===`oidn`)}setAutoExposureEnabled(e,t){this._stages.autoExposure?.setEnabled(e,t)}get requiresMotionVectors(){return!!this._stages.nrd?.enabled}_syncGBufferStages(){let e=this._stages,t=e.normalDepth,n=e.motionVector,r=this.requiresMotionVectors,i=r||this.historyWanted;this.historyWanted||this._releaseHistory(),t&&(i&&!t.enabled&&t.reset(),t.enabled=i,t.setInstanceLeafOutput?.(this.historyWanted)),n&&(r&&!n.enabled&&(n.matricesInitialized=!1),n.enabled=r),e.pathTracer?.setAuxGBufferEnabled?.(i||!!this.denoiser?.enabled),e.pathTracer?.setCleanAuxNormal?.(!!this.denoiser?.enabled&&!!this.denoiser?.expectsCleanAux(this._finalQuality));for(let r of[e.nrd,t,n])r&&!r.enabled&&r.releaseGPUMemory?.()}_cleanupCompletionListener(){this.denoiser&&(this._pendingStartUpscaler&&this.denoiser.removeEventListener(`end`,this._pendingStartUpscaler),this._pendingCloseDenoise&&this.denoiser.removeEventListener(`end`,this._pendingCloseDenoise)),this._pendingStartUpscaler=null,this._pendingCloseDenoise=null}get holdsWhileMoving(){if(!this._stages.pathTracer?.viewIsChanging||!this.continuousDenoise||this._cadenceSuspended||!this.denoiser?.enabled||this._movingHopeless)return!1;let e=this.movingCostMs,t=this._movingDenoiseMs.length;e>vw*bw&&(this._movingHopeless=!0,this._syncGBufferStages());let n=!this._movingHopeless&&(t<2||e<=vw);return this._holdWhileMoving=(this._holdWhileMoving===null||this._holdWhileMoving)&&n,this._holdWhileMoving}skipsTrace(){return this.holdsWhileMoving&&!!this.denoiser?.state.isDenoising}get movingCostMs(){return this._movingDenoiseMs.length?Math.min(...this._movingDenoiseMs):0}_publishOutput(){let e=this.pipeline?.context,t=this.denoiser?.outputTexture;e&&t&&e.setTexture(`oidn:output`,t)}_unpublishOutput(){this.pipeline?.context?.removeTexture(`oidn:output`),this.denoiser?.invalidateOutput()}_checkHeldFrameHealthy(){!this.denoiser?.hasOutput||this._failedRefreshes<xw||this._unpublishOutput()}tickContinuousDenoise(e){let t=this.denoiser;if(!this.continuousDenoise||this._cadenceSuspended||!t)return!1;this._checkHeldFrameHealthy();let n=!!this._stages.pathTracer?.viewIsChanging;if(!n)this._holdWhileMoving=null,this._movingDenoiseMs.length=0;else if(!this.holdsWhileMoving)return!1;if(t.state.isDenoising||t.state.isLoading||!n&&e<=this._lastCadenceSamples)return!1;let r=performance.now(),i=n?_w:this._lastCadenceSamples===0?gw:hw,a=Math.max(this.continuousDenoiseInterval,t.lastDenoiseMs*i);if(r-this._lastCadenceAt<a)return!1;this._lastCadenceAt=r,this._lastCadenceSamples=e,t.lastDenoiseMs>mw&&(this._cadenceDowngraded=!0);let o=this._cadenceDowngraded?this.previewQuality():this._finalQuality;return t.quality!==o&&t.updateQuality(o),t.start({continuous:!0}).then(e=>{this._failedRefreshes=e?0:this._failedRefreshes+1,!(!e||!n)&&(this._movingDenoiseMs.push(t.lastDenoiseMs),this._movingDenoiseMs.length>yw&&this._movingDenoiseMs.shift())}),!0}previewQuality(){return this.denoiser?.expectsCleanAux(this._finalQuality)?`fast-clean`:`fast`}setCadenceSuspended(e){this._cadenceSuspended=!!e,this._historyDirty=!0,this._cadenceSuspended&&(this.denoiser?.abort(),this._unpublishOutput()),this._syncGBufferStages()}setContinuousDenoise(e){!e&&!this.finalDenoise&&this.denoiser?.abort(),this.continuousDenoise=!!e,this._syncOIDNInUse(),this._lastCadenceAt=-1/0,this._resetCadence(),this._syncGBufferStages()}_useFinalQuality(){let e=this.denoiser;e&&e.quality!==this._finalQuality&&e.updateQuality(this._finalQuality)}_resetCadence(){this._lastCadenceSamples=0}setTemporalHistory(e){this.temporalHistory=!!e,this._syncGBufferStages()}get historyWanted(){return this.temporalHistory&&this.continuousDenoise&&!!this.denoiser?.enabled&&!this._movingHopeless&&!this._cadenceSuspended&&!this._isPanorama()}get historyActive(){return this.historyWanted&&!!this._stages.normalDepth?.enabled&&!(this._stages.pathTracer?.visMode?.value>0)}_isPanorama(){return this._stages.pathTracer?.uniforms?.get(`cameraProjection`)?.value===at.equirectangular}beforeReset({keepHistory:e=!1}={}){let t=this._stages.pathTracer;if(!t||!this.historyActive)return;let n=t.resetCount!==this._knownResetCount;if(!e||n&&t.frameCount<2){this._historyDirty=!0;return}if(t.frameCount<2)return;let r=this._historyInputs();r&&(this._ensureHistory().merge(r,t.frameCount,this._historyCameraNow(),{commit:!0,keepHistory:!this._historyDirty&&!n,historyScale:Cw(t.frameCount)}),this._historyDirty=!1)}afterReset(){this._knownResetCount=this._stages.pathTracer?.resetCount??0}afterTrace(){let e=this._stages.pathTracer;if(!e||e.tracedFrames===this._seenTracedFrames)return;if(this._seenTracedFrames=e.tracedFrames,e.resetCount!==this._knownResetCount&&(this._historyDirty=!0,this._knownResetCount=e.resetCount),!this.historyActive||e.frame.value!==0){this._movedPlacements.clear();return}let t=this._historyInputs();if(!t){this._movedPlacements.clear(),this._historyDirty=!0;return}let n=this._ensureHistory();this._historyDirty&&n.invalidate(),n.accumulate(t,this._historyCameraNow(),this._takeMovedPlacements()),this._historyDirty=!1}notePlacementMoving(e,t){e<0||!this.historyActive||this._movedPlacements.has(e)||this._movedPlacements.set(e,{matrixOf:t,prev:t().slice()})}_takeMovedPlacements(){let e=this._movedPlacements,t=this._movedUpload;if(t.count=e.size,!e.size)return t;t.leaves.length<e.size&&(t.leaves=new Uint32Array(e.size*2),t.toPrev=new Float32Array(e.size*32));let n=[...e.keys()].sort((e,t)=>e-t);for(let r=0;r<n.length;r++){let{matrixOf:i,prev:a}=e.get(n[r]);this._matB.fromArray(i()).invert(),this._matA.fromArray(a).multiply(this._matB).toArray(t.toPrev,r*16),t.leaves[r]=n[r]}return e.clear(),t}_historyTextures(){let e=this._stages.pathTracer,t=this._history;if(!t?.valid||this._historyDirty||!this.historyActive||e.isComplete||e.resetCount!==this._knownResetCount||t.width!==this._lastRenderWidth||t.height!==this._lastRenderHeight)return null;if(e.frameCount<=1)return t.textures;if(e.frameCount>=Sw)return null;let n=this._historyInputs();return n?t.merge(n,e.frameCount,this._historyCameraNow(),{historyScale:Cw(e.frameCount)}):null}_historyInputs(){let e=this._stages.pathTracer,t=this.pipeline?.context,n=this.renderer?.backend;if(!e?.storageTextures?.readTarget||!t||!n)return null;let r=e.storageTextures.getReadTextures(),i=e=>e?n.get(e)?.texture:null,a={color:i(r.color),albedo:i(r.albedo),normal:i(r.normalDepth),geo:i(t.getTexture(`pathtracer:normalDepth`)),geoPrev:i(t.getTexture(`pathtracer:prevNormalDepth`)),shading:i(t.getTexture(`pathtracer:shadingNormal`)),leaf:i(t.getTexture(`pathtracer:instanceLeaf`)),width:e.width,height:e.height};return a.color&&a.albedo&&a.normal&&a.geo&&a.geoPrev&&a.shading&&a.leaf?a:null}_historyCameraNow(){let e=this._stages.pathTracer;this._viewProj.multiplyMatrices(e.cameraProjectionMatrix.value,e.cameraViewMatrix.value);let t=this._historyCamera;return t.world=e.cameraWorldMatrix.value.elements,t.projInv=e.cameraProjectionMatrixInverse.value.elements,t.viewProj=this._viewProj.elements,t.orthographic=e.uniforms?.get(`cameraProjection`)?.value===at.orthographic,t}_ensureHistory(){return this._history??=new OC(this.renderer.backend.device),this._history.settings.cleanAux=!!this.denoiser?.expectsCleanAux(this._finalQuality),this._history}_releaseHistory(){this._history?.dispose(),this._history=null,this._historyDirty=!0,this._movedPlacements.clear()}setUpscalerBackend(e){let t=e===`neural`?`neural`:`esrgan`;t!==this.upscalerBackend&&(this.upscalerBackend=t,this._restoreRenderDisplay(),t!==`neural`&&this._releaseNeuralUpscaler())}_restoreRenderDisplay(){let e=this.upscalerCanvas&&this.upscalerCanvas.style.display!==`none`;return this.upscalerCanvas&&(this.upscalerCanvas.style.display=`none`),this.mainCanvas&&(this.mainCanvas.style.opacity=`1`),e&&this._lastRenderWidth&&this._lastRenderHeight&&this.dispatchEvent({type:N.RESOLUTION_CHANGED,width:this._lastRenderWidth,height:this._lastRenderHeight}),!!e}_releaseNeuralUpscaler(){this._neuralUpscaler?.dispose(),this._neuralUpscaler=null,this._superResModule?.releaseDenoisedReader()}setNeuralRendering(e,t=null){let n=this.neuralRendering!==!!e;this.neuralRendering=!!e,t&&(this.neuralRenderingSettings={...this.neuralRenderingSettings,...t}),this.neuralRendering||(this._releaseNeuralRetouch(),this._restoreRenderDisplay()),n&&this._redoPostPasses()}_releaseNeuralRetouch(){this._retouch?.dispose(),this._retouch=null}async _runNeuralPost(e){let t=this.upscaler?.enabled&&this.upscalerBackend===`neural`,n=this.neuralRendering,r=this.upscaler?.enabled&&!t;if(!(!t&&!n)&&!this._neuralPostBusy){if(!this.upscalerCanvas){this._recordNoOverlayCanvas(`neural`);return}if(!this.pipeline?.context?.getTexture(`oidn:output`)){pw.warn(`neural pass skipped: no denoised picture — it needs OIDN`);return}this._neuralPostBusy=!0,this.dispatchEvent({type:N.UPSCALING_START});try{let i=await Promise.resolve().then(()=>(QC(),IC));this._superResModule=i;let a=n?await Promise.resolve().then(()=>(fw(),$C)):null,o=this.denoiser?._outTexSize,s=(o?.width??0)*(o?.height??0),c=n&&s<=a.RETOUCH_MAX_PIXELS;if(n&&!c&&(pw.warn(`Neural rendering skipped: the render is ${(s/1e6).toFixed(1)} MP, above the ${(a.RETOUCH_MAX_PIXELS/1e6).toFixed(1)} MP the pass survives.`+(t?` The upscale still ran.`:``)),this._releaseNeuralRetouch()),!t&&!c){r&&!this._postCancelled&&await this.upscaler.start();return}let l={exposure:this._getEffectiveExposure(),toneMapping:this._getToneMapping(),saturation:this._getSaturation?.()??1,gain:this._getDisplayGain?.()??null},u=await i.readDenoisedHalf(this.denoiser);t&&(this._neuralUpscaler&&(this._neuralUpscaler.inputWidth!==u.width||this._neuralUpscaler.inputHeight!==u.height)&&this._releaseNeuralUpscaler(),this._neuralUpscaler||=await i.NeuralSuperRes.create({width:u.width,height:u.height}));let d=u;if(c){let e=await a.enhanceFrame({source:d,settings:this.neuralRenderingSettings,instance:this._retouch,exposure:l.exposure,tone:t?null:l});this._retouch=e.instance,d=e}if(t&&(d=await this._neuralUpscaler.upscaleToRGBA8(d,l)),!e()){this.dropDisplay();return}if(this._postRedo||this._postCancelled)return;if(r){await this.upscaler.start(new ImageData(d.rgba8,d.width,d.height));return}if(i.presentRGBA8(this.upscalerCanvas,d.rgba8,d.width,d.height),!e()){this.dropDisplay();return}this.mainCanvas&&(this.mainCanvas.style.opacity=`0`),this.dispatchEvent({type:N.RESOLUTION_CHANGED,width:d.width,height:d.height})}catch(e){pw.warn(`neural pass failed`,e)}finally{this._neuralPostBusy=!1,this.dispatchEvent({type:N.UPSCALING_END})}}}async denoiseOnce(){let e=this.denoiser;if(!e?.enabled)return!1;for(this._cleanupCompletionListener(),this._resetCadence(),this._useFinalQuality();e.state.isLoading||e.state.isDenoising;)await(e.state.isLoading?e.whenLoaded():new Promise(t=>{let n=()=>{e.removeEventListener(`end`,n),t()};e.addEventListener(`end`,n)}));let t=await e.start();return t&&this._onDisplayRefresh?.(),t&&e.hasOutput}_runPostPasses(e){this._postIsStillComplete=e,this._postCancelled=!1,this.neuralRendering||this.upscaler?.enabled&&this.upscalerBackend===`neural`?this._postRun=this._runNeuralPost(e):this._postRun=this.upscaler?.enabled?this.upscaler.start():null}_redoPostPasses(){let e=this._postIsStillComplete;!e?.()||this._postRedo||(this.upscaler?.abort(),this._postCancelled=!1,this._postRedo=Promise.resolve(this._postRun).catch(()=>{}).then(()=>{this._postRedo=null,!(this._postCancelled||this._postIsStillComplete!==e||!e())&&(this._restoreRenderDisplay(),this._runPostPasses(e))}))}cancelPostPasses(){this._postCancelled=!0,this.upscaler?.abort(),this._restoreRenderDisplay(),this.dispatchEvent({type:N.UPSCALING_END})}onRenderComplete({isStillComplete:e}){this._cleanupCompletionListener(),this._postIsStillComplete=null;let t=this.continuousDenoise&&!this._cadenceSuspended,n=this.finalDenoise?`final`:t?`refresh`:null,r=()=>{this.denoiser?.removeEventListener(`end`,r),this._pendingStartUpscaler=null,e()&&(n&&this._onDisplayRefresh?.(),this._runPostPasses(e))};if(!n){r();return}let i=()=>{e()&&(this._pendingStartUpscaler=r,this.denoiser.addEventListener(`end`,r),n===`final`?(this._useFinalQuality(),this.denoiser.start()):this.denoiser.start({continuous:!0}))};if(this._resetCadence(),this.denoiser.state.isDenoising){let e=()=>{this.denoiser?.removeEventListener(`end`,e),this._pendingCloseDenoise===e&&(this._pendingCloseDenoise=null),i()};this._pendingCloseDenoise=e,this.denoiser.addEventListener(`end`,e)}else i()}abort(e,{keepDisplay:t=!1}={}){this._cleanupCompletionListener(),this._postIsStillComplete=null,this._restoreRenderDisplay(),e&&e!==this.mainCanvas&&(e.style.opacity=`1`),this.upscaler&&this.upscaler.abort();let n=!!this._stages.pathTracer?.viewIsChanging,r=t&&this.continuousDenoise&&!this._cadenceSuspended&&!!this.denoiser?.hasOutput&&(!n||this.holdsWhileMoving);this.denoiser&&!r&&(this.denoiser.enabled&&this.denoiser.abort(),this._unpublishOutput()),this._resetCadence()}dropDisplay(){this._unpublishOutput(),this._restoreRenderDisplay(),this._historyDirty=!0}dispose(){if(this._cleanupCompletionListener(),this._postIsStillComplete=null,this._releaseNeuralUpscaler(),this._releaseNeuralRetouch(),this._unpublishOutput(),this._releaseHistory(),this.denoiser){if(this._denoiserStartHandler&&this.denoiser.removeEventListener(`start`,this._denoiserStartHandler),this._denoiserEndHandler&&this.denoiser.removeEventListener(`end`,this._denoiserEndHandler),this._denoiserTileHandler&&this.denoiser.removeEventListener(`tileProgress`,this._denoiserTileHandler),this._denoiserErrorHandler&&this.denoiser.removeEventListener(`error`,this._denoiserErrorHandler),this._denoiserLoadHandler){for(let e of[`loading`,`loaded`,`error`])this.denoiser.removeEventListener(e,this._denoiserLoadHandler);this.denoiser.state?.isLoading&&this.dispatchEvent({type:N.DENOISER_LOADING,loading:!1})}this.denoiser.dispose(),this.denoiser=null}this.upscaler&&(this._upscalerResChangedHandler&&this.upscaler.removeEventListener(`resolution_changed`,this._upscalerResChangedHandler),this._upscalerStartHandler&&this.upscaler.removeEventListener(`start`,this._upscalerStartHandler),this._upscalerProgressHandler&&this.upscaler.removeEventListener(`progress`,this._upscalerProgressHandler),this._upscalerEndHandler&&this.upscaler.removeEventListener(`end`,this._upscalerEndHandler),this.upscaler.dispose(),this.upscaler=null,this.upscalerBackend=`esrgan`,this._neuralUpscaler=null),this._denoiserStartHandler=null,this._denoiserEndHandler=null,this._denoiserTileHandler=null,this._denoiserErrorHandler=null,this._denoiserLoadHandler=null,this._upscalerResChangedHandler=null,this._upscalerStartHandler=null,this._upscalerProgressHandler=null,this._upscalerEndHandler=null,this._onReset=null,this._onPostProcessRefresh=null,this._onDisplayRefresh=null,this._getExposure=null,this._getSaturation=null,this._getDisplayGain=null,this._issues=null,this.upscalerCanvas?.parentNode&&(this.upscalerCanvas.parentNode.removeChild(this.upscalerCanvas),this.upscalerCanvas=null)}setOverlayManager(e){this._overlayManager=e}setResetCallback(e){this._onReset=e}setPostProcessRefreshCallback(e){this._onPostProcessRefresh=e}setDisplayRefreshCallback(e){this._onDisplayRefresh=e}setSettings(e){this._settings=e}setAutoExposureParams(e){this._stages.autoExposure?.updateParameters(e)}applyOIDNEnabled(e){this.finalDenoise=!!e,this._syncOIDNInUse()}get oidnQuality(){return this._finalQuality}setOIDNEnabled(e){this.applyOIDNEnabled(e),this._syncGBufferStages(),this._onPostProcessRefresh?.()}_syncOIDNInUse(){this.denoiser&&(this.denoiser.enabled=this.finalDenoise||this.continuousDenoise)}applyOIDNQuality(e){this._finalQuality=e,this._cadenceDowngraded=!1,this.denoiser?.updateQuality(e)}setOIDNQuality(e){this.applyOIDNQuality(e),this._syncGBufferStages(),this._onPostProcessRefresh?.()}setTileHelperEnabled(e){this._setTileHelper(e)}setUpscalerEnabled(e){let t=!!this.upscaler&&this.upscaler.enabled!==!!e;this.upscaler?this.upscaler.enabled=e:e&&this._recordNoOverlayCanvas(`upscaler`),e||this._restoreRenderDisplay(),t&&this._redoPostPasses()}setUpscalerScaleFactor(e){this.upscaler?.setScaleFactor(e)}setUpscalerQuality(e){this.upscaler?.setQuality(e)}setAutoExposure(e){this.setAutoExposureEnabled(e,this._getExposure())}setStrategy(e,t){this.setDenoiserStrategy(e,t),this._onReset?.()}setNRDParams(e){this._stages.nrd?.updateParameters(e)}applyNRDPreset(e){this._applyNRDPreset(e)}setNRDDebugMode(e){this._stages.nrd?.updateParameters({debugMode:e})}_setTileHelper(e){let t=this._overlayManager?.getHelper(`tiles`);t&&(t.enabled=e,e||t.hide())}_getEffectiveExposure(){return this._stages.autoExposure?.enabled?this.renderer.toneMappingExposure:this._getExposure()}_getToneMapping(){return this.renderer.toneMapping}_clearDenoiserTextures(){let e=this.pipeline?.context;e&&(e.removeTexture(`nrd:output`),e.removeTexture(`oidn:output`))}_applyNRDPreset(e){let t=ob[e];if(!t)return;let n={};for(let e of ab)n[e]=ib[e];this._stages.nrd?.updateParameters({...n,...t})}},Tw=class{constructor(){this.layer=`hud`,this.visible=!1,this._tileBounds=null,this._imageWidth=1,this._imageHeight=1,this.enabled=!0,this._borderColor=`rgba(255, 0, 0, 0.6)`,this._borderWidthRatio=1/540,this._borderWidthMin=1.5,this._borderWidthMax=4}setActiveTile(e){this._tileBounds=e}setRenderSize(e,t){this._imageWidth=e,this._imageHeight=t}render(e,t,n){if(!this._tileBounds)return;let r=this._tileBounds,i=t/this._imageWidth,a=n/this._imageHeight,o=r.x*i,s=r.y*a,c=r.width*i,l=r.height*a,u=Math.min(this._borderWidthMax,Math.max(this._borderWidthMin,Math.min(t,n)*this._borderWidthRatio));e.strokeStyle=this._borderColor,e.lineWidth=u,e.strokeRect(o,s,c,l)}show(){this.enabled&&(this.visible=!0)}hide(){this.visible=!1,this._tileBounds=null}dispose(){this.visible=!1}},Ew=class{constructor(e,t){this.layer=`scene`,this._enabled=!0,this._scene=e,this._camera=t,this._build([])}_build(e){this._orthographic=this._camera.isOrthographicCamera===!0,this._outlineNode=(0,d.outline)(this._scene,this._camera,{selectedObjects:e,edgeThickness:(0,n.uniform)(1),edgeGlow:(0,n.uniform)(0)});let i=(0,n.uniform)(3),a=(0,n.uniform)(new r.Color(16777215)),o=(0,n.uniform)(new r.Color(1640965)),{visibleEdge:s,hiddenEdge:c}=this._outlineNode,l=s.mul(a).add(c.mul(o)).mul(i),u=l.r.max(l.g).max(l.b).clamp(0,1);this._material=new t.MeshBasicNodeMaterial,this._material.colorNode=(0,n.vec4)(l,u),this._material.transparent=!0,this._material.blending=r.CustomBlending,this._material.blendEquation=r.AddEquation,this._material.blendSrc=r.OneFactor,this._material.blendDst=r.OneFactor,this._material.blendEquationAlpha=r.AddEquation,this._material.blendSrcAlpha=r.OneFactor,this._material.blendDstAlpha=r.OneFactor,this._material.toneMapped=!1,this._material.depthTest=!1,this._material.depthWrite=!1,this._quad=new t.QuadMesh(this._material)}setSelectedObjects(e){this._outlineNode.selectedObjects=e}get visible(){return this._enabled&&this._outlineNode.selectedObjects.length>0}render(e){if(!this.visible)return;if(this._camera.isOrthographicCamera!==this._orthographic){let e=[...this._outlineNode.selectedObjects];this._outlineNode.dispose(),this._material.dispose(),this._build(e)}let t=e.autoClear;e.autoClear=!1,e.setRenderTarget(null),this._quad.render(e),e.autoClear=t}show(){this._enabled=!0}hide(){this._enabled=!1}dispose(){this._enabled=!1,this._outlineNode?.dispose(),this._material?.dispose(),this._quad=null}};function Dw(e=!1){let t=document.createElement(`canvas`);return t.style.cssText=`position:absolute;top:0;left:0;width:100%;height:100%;pointer-events:none;`+(e?`display:none;`:``),t}function Ow(e,t=1/0){let n=e?.getBoundingClientRect();if(!n||n.width===0||n.height===0)return null;let r=Math.min(window.devicePixelRatio||1,2),i=Math.round(n.width*r),a=Math.round(n.height*r),o=t/Math.max(i,a);return o<1&&(i=Math.max(1,Math.round(i*o)),a=Math.max(1,Math.round(a*o))),{width:i,height:a}}de();var kw=4096,Aw=class{constructor(){this.canvas=Dw(!0),this._visible=!1,this.renderer=null,this._sizeSource=null}async init({device:e,sizeSource:n}){this._sizeSource=n;let i=e.onuncapturederror,a=new t.WebGPURenderer({canvas:this.canvas,device:e,alpha:!0,antialias:(window.devicePixelRatio||1)<2});return await a.init(),e.onuncapturederror=i,a.outputColorSpace=r.SRGBColorSpace,a.setPixelRatio(1),a.setClearColor(0,0),a.autoClear=!1,this.renderer=a,this.syncSize(),this}get isVisible(){return this._visible}syncSize(){if(!this.renderer)return;let e=Ow(this._sizeSource,kw);!e||e.width===this.canvas.width&&e.height===this.canvas.height||this.renderer.setSize(e.width,e.height,!1)}begin(){this.renderer&&(this.renderer.setRenderTarget(null),this.renderer.clear())}setVisible(e){this._visible!==e&&(this._visible=e,this.canvas.style.display=e?``:`none`)}dispose(){ne(this.renderer),this.renderer=null,this.canvas.parentElement?.removeChild(this.canvas)}};Ae(),F();var jw=ve(`overlay`),Mw=(e,t)=>e.visible&&e.layer===t&&e.render,Nw=class{constructor(e){this.camera=e,this._helpers=new Map,this._hudCanvas=Dw(),this._hudCtx=this._hudCanvas.getContext(`2d`),this._helperScene=null,this._viewOverlay=null}async initViewRenderer({device:e,sizeSource:t}){if(!(!e||!t))try{this._viewOverlay=await new Aw().init({device:e,sizeSource:t})}catch(e){jw.error(`overlay surface unavailable — light gizmos, transform gizmo and outlines are disabled`,e),this._viewOverlay=null}}gpuResources(){let e=this._viewOverlay;return e?.isVisible?[{bytes:e.canvas.width*e.canvas.height*4},...e.renderer?._frameBufferTargets?.values()??[]]:[]}setHelperScene(e){this._helperScene=e}getHUDCanvas(){return this._hudCanvas}mount(e){if(!e)return;let t=this._viewOverlay?.canvas;t&&t.parentElement!==e&&e.appendChild(t),this._hudCanvas.parentElement!==e&&e.appendChild(this._hudCanvas)}setupDefaultHelpers({helperScene:e,meshScene:t,pipeline:n,denoisingManager:r,app:i,renderWidth:a,renderHeight:o}){this.setHelperScene(e);let s=new Tw;this.register(`tiles`,s),s.setRenderSize(a||1,o||1),i.addEventListener(N.RESOLUTION_CHANGED,e=>{s.setRenderSize(e.width,e.height)}),n.eventBus.on(`pipeline:reset`,()=>s.hide()),this._wireDenoiserTileEvents(s,r);let c=new Ew(t,this.camera);this.register(`outline`,c)}_wireDenoiserTileEvents(e,t){let n=[t?.denoiser,t?.upscaler];for(let t of n)t&&(t.addEventListener(`tileProgress`,t=>{t.continuous||t.tile&&(e.setRenderSize(t.imageWidth,t.imageHeight),e.setActiveTile(t.tile),e.show(),this.refreshHUD())}),t.addEventListener(`end`,()=>{e.hide(),this.refreshHUD()}))}register(e,t){this._helpers.has(e)&&(jw.warn(`helper "${e}" already registered — replacing.`),this._helpers.get(e).dispose?.()),this._helpers.set(e,t)}unregister(e){let t=this._helpers.get(e);t&&(t.dispose?.(),this._helpers.delete(e))}show(e){this._helpers.get(e)?.show()}hide(e){this._helpers.get(e)?.hide()}toggle(e){let t=this._helpers.get(e);t&&(t.visible?t.hide():t.show())}getHelper(e){return this._helpers.get(e)??null}isVisible(e){return this._helpers.get(e)?.visible??!1}showAll(){for(let e of this._helpers.values())e.show()}hideAll(){for(let e of this._helpers.values())e.hide()}render(){let e=this._viewOverlay;if(e){let t=this._hasVisibleSceneOverlay();(t||e.isVisible)&&(e.syncSize(),e.begin(),t&&this._renderSceneLayer(e.renderer),e.setVisible(t))}this.refreshHUD()}_renderSceneLayer(e){this._helperScene?.render(e,this.camera);for(let t of this._helpers.values())Mw(t,`scene`)&&t.render(e,this.camera)}_hasVisibleSceneOverlay(){if(this._helperScene?.isDrawing)return!0;for(let e of this._helpers.values())if(Mw(e,`scene`))return!0;return!1}refreshHUD(){let e=this._hudCanvas,t=this._hudCtx,n=!1;for(let e of this._helpers.values())if(Mw(e,`hud`)){n=!0;break}if(!n){e.style.display!==`none`&&(e.style.display=`none`);return}e.style.display!==``&&(e.style.display=``);let r=e.clientWidth,i=e.clientHeight,a=r>0&&i>0?Ow(e):null;if(a){(e.width!==a.width||e.height!==a.height)&&(e.width=a.width,e.height=a.height),t.clearRect(0,0,a.width,a.height),t.save(),t.scale(a.width/r,a.height/i);for(let e of this._helpers.values())Mw(e,`hud`)&&e.render(t,r,i);t.restore(),e.style.display!==``&&(e.style.display=``)}}dispose(){for(let e of this._helpers.values())e.dispose?.();this._helpers.clear(),this._viewOverlay?.dispose(),this._viewOverlay=null,this._hudCanvas.parentElement&&this._hudCanvas.parentElement.removeChild(this._hudCanvas)}};F();function Pw(e,t){let n=[...e].filter(t=>{for(let n=t.parent;n;n=n.parent)if(e.has(n))return!1;return!0}),r=0,i=0;t.traverse?.(()=>r++);for(let e of n)e.traverse?.(()=>i++);return i+n.length/2<r?n:null}var Fw=class extends r.EventDispatcher{constructor(){super(),this.mixer=null,this.timer=new r.Timer,this.actions=[],this.isPlaying=!1,this._scene=null,this._mixerRoot=null,this._meshes=null,this._meshTriRanges=null,this._meshPositions=null,this._tempVec=new r.Vector3,this._skinnedCache=null,this._clipsCache=null,this._savedTimeScale=1,this.onFinished=null,this._rigid=!1,this._plans=null,this._allPlan=null,this._activeClip=0,this._slotOf=null,this._lastWorld=null,this._lastVisible=null,this._lastMeshWorld=null,this._lastMorphWeights=null,this.wakeCallback=null,this.applyPoseCallback=null}init(e,t,n,i){if(this.dispose(),!i||i.length===0)return;this._scene=e,this._mixerRoot=t,this._meshes=n,this.mixer=new r.AnimationMixer(t);let a=i.map(e=>this.mixer.clipAction(e)),o=(e,t)=>e.name===t||e.getObjectByName(t)!==void 0;!a.some(e=>e.getClip().tracks.some(e=>{let n=e.name.split(`.`)[0];return o(t,n)}))&&t!==e&&(console.log(`[AnimationManager] Tracks did not resolve from model root, retrying with scene root`),this.mixer=new r.AnimationMixer(e),this._mixerRoot=e,a=i.map(e=>this.mixer.clipAction(e))),this.actions=a,this._rigid=!n.some(e=>e?.isSkinnedMesh)&&!i.some(e=>e.tracks.some(e=>e.name.includes(`morphTargetInfluences`))),this._planClips(i),this.mixer.addEventListener(`finished`,()=>{this.isPlaying=!1,this.timer.reset(),this.onFinished&&this.onFinished()}),this._meshTriRanges=[],this._skinnedCache=[];let s=0;for(let e of n){let t=e.geometry,n=t.attributes.position,r=t.index?t.index.array:null,i=r?r.length/3:n.count/3,a=n.count;this._meshTriRanges.push({start:s,count:i,uniqueVerts:a,indices:r}),s+=i}this._skinnedCache=[],this._meshPositions=[],this._lastMeshWorld=this._rigid?null:new Float64Array(n.length*16).fill(NaN),this._lastMorphWeights=[];let c=n.filter(e=>e.isSkinnedMesh).length;console.debug(`[AnimationManager] Init: ${i.length} clips, ${n.length} meshes (${c} skinned), ${s} triangles, ${this._rigid?`rigid`:`deforming`}`)}_planClips(e){let t=this._mixerRoot,n=new Map;if(t.traverse?.(e=>{n.has(e.name)||n.set(e.name,e),n.set(e.uuid,e)}),this._plans=e.map(e=>{let i=new Set,a=!1,o=!1;for(let s of e.tracks){let{nodeName:e,propertyName:c}=r.PropertyBinding.parseTrackName(s.name),l=e===``||e===`.`?t:n.get(e);if(!l){o=!0;continue}i.add(l),c===`visible`&&(a=!0)}let s=[];for(let e=0;e<this._meshes.length;e++)for(let t=this._meshes[e];t;t=t.parent)if(i.has(t)){s.push(e);break}let c=new Set;for(let e of i)e.traverse(e=>e.isCamera&&c.add(e));return{meshes:Int32Array.from(s),visibility:a,cameras:[...c],nodes:o?null:i,roots:o?null:Pw(i,t)}}),this._allPlan=null,!this._rigid)return;this._slotOf=new Int32Array(this._meshes.length).fill(-1);let i=0;for(let e of this._plans)for(let t of e.meshes)this._slotOf[t]<0&&(this._slotOf[t]=i++);this._lastWorld=new Float64Array(i*16).fill(NaN),this._lastVisible=new Uint8Array(i).fill(2)}_planFor(e){if(!this._plans)return null;if(e>=0)return this._plans[e]??null;if(!this._allPlan){let e=new Set,t=new Set,n=!1,r=new Set;for(let i of this._plans)i.meshes.forEach(t=>e.add(t)),i.cameras.forEach(e=>t.add(e)),n||=i.visibility,r&&i.nodes?i.nodes.forEach(e=>r.add(e)):r=null;this._allPlan={meshes:Int32Array.from(e),visibility:n,cameras:[...t],nodes:r,roots:r?Pw(r,this._mixerRoot):null}}return this._allPlan}_applyRigidPose(e){let t=this._planFor(e);if(!t)return;let n=[],r=!1,i=this._lastWorld,a=this._lastVisible;for(let e of t.meshes){let o=this._meshes[e],s=this._slotOf[e],c=o.matrixWorld.elements,l=s*16;for(let t=0;t<16;t++)if(i[l+t]!==c[t]){for(let e=0;e<16;e++)i[l+e]=c[e];n.push(e);break}if(t.visibility||a[s]===2){let e=1;for(let t=o;t;t=t.parent)if(!t.visible){e=0;break}a[s]!==e&&(a[s]=e,r=!0)}}(n.length||r||t.cameras.length)&&this.applyPoseCallback?.({meshIndices:n,visibilityChanged:r,cameras:t.cameras})}play(e=0){if(!(!this.mixer||this.actions.length===0)){if(this.mixer.stopAllAction(),e===-1)for(let e of this.actions)e.play();else e>=0&&e<this.actions.length&&this.actions[e].play();this._activeClip=e,this.timer.reset(),this.isPlaying=!0,this.wakeCallback?.(),this.dispatchEvent({type:N.ANIMATION_STARTED})}}pause(){this.mixer&&(this.mixer.timeScale=0,this.timer.reset(),this.isPlaying=!1,this.dispatchEvent({type:N.ANIMATION_PAUSED}))}resume(){this.mixer&&(this.mixer.timeScale=this._savedTimeScale||1,this.timer.reset(),this.isPlaying=!0,this.wakeCallback?.(),this.dispatchEvent({type:N.ANIMATION_STARTED}))}stop(){this.mixer&&(this.mixer.stopAllAction(),this.mixer.timeScale=this._savedTimeScale||1,this.timer.reset(),this.isPlaying=!1,this._rigid&&(this._mixerRoot.updateMatrixWorld(!0),this._applyRigidPose(-1)),this.dispatchEvent({type:N.ANIMATION_STOPPED}))}setSpeed(e){this._savedTimeScale=e,this.mixer&&this.isPlaying&&(this.mixer.timeScale=e)}setLoop(e){let t=e?r.LoopRepeat:r.LoopOnce;for(let n of this.actions)n.setLoop(t),n.clampWhenFinished=!e}seekTo(e,t=0){if(!this.mixer||this.actions.length===0)return null;if(this._activeClip=t,this.mixer.stopAllAction(),t===-1)for(let e of this.actions)e.play();else t>=0&&t<this.actions.length&&this.actions[t].play();this.mixer.setTime(e);for(let e of this.actions)e.isRunning()&&(e.paused=!0);return this._poseReader()}get currentTime(){return this.mixer?.time||0}update(){if(!this.isPlaying||!this.mixer)return null;this.timer.update();let e=this.timer.getDelta();return this.mixer.update(e),this._poseReader()}_scratch(e,t,n){let r=e[t];return r&&r.length===n?r:e[t]=new Float32Array(n)}_poseReader(){let e=this._rigid?this._planFor(this._activeClip)?.roots:null;if(e)for(let t of e)t.updateMatrixWorld(!0);else this._mixerRoot.updateMatrixWorld(!0);if(this._rigid)return this._applyRigidPose(this._activeClip),null;let t=this._planFor(this._activeClip)?.cameras;t?.length&&this.applyPoseCallback?.({meshIndices:[],visibilityChanged:!1,cameras:t});let n=new Int8Array(this._meshes.length);return e=>(n[e]===0&&(n[e]=this._meshes[e].isSkinnedMesh||this._poseChanged(e)?1:-1),n[e]>0?this._computeMeshPositions(e):null)}_poseChanged(e){let t=this._meshes[e],n=this._lastMeshWorld,r=t.matrixWorld.elements,i=e*16,a=!1;for(let e=0;e<16;e++)if(n[i+e]!==r[e]){for(let e=0;e<16;e++)n[i+e]=r[e];a=!0;break}let o=t.morphTargetInfluences;if(o?.length){let t=this._lastMorphWeights[e];(!t||t.length!==o.length||t.some((e,t)=>e!==o[t]))&&(this._lastMorphWeights[e]=Float64Array.from(o),a=!0)}return a}_computeMeshPositions(e){let t=this._tempVec,n=this._meshes[e],{count:r,uniqueVerts:i,indices:a}=this._meshTriRanges[e],o=this._scratch(this._skinnedCache,e,i*3),s=this._scratch(this._meshPositions,e,r*9),c=n.matrixWorld;for(let e=0;e<i;e++)n.getVertexPosition(e,t),t.applyMatrix4(c),o[e*3]=t.x,o[e*3+1]=t.y,o[e*3+2]=t.z;if(a)for(let e=0;e<r;e++){let t=e*3,n=a[t]*3,r=a[t+1]*3,i=a[t+2]*3,c=e*9;s[c]=o[n],s[c+1]=o[n+1],s[c+2]=o[n+2],s[c+3]=o[r],s[c+4]=o[r+1],s[c+5]=o[r+2],s[c+6]=o[i],s[c+7]=o[i+1],s[c+8]=o[i+2]}else for(let e=0;e<r;e++){let t=e*3*3,n=(e*3+1)*3,r=(e*3+2)*3,i=e*9;s[i]=o[t],s[i+1]=o[t+1],s[i+2]=o[t+2],s[i+3]=o[n],s[i+4]=o[n+1],s[i+5]=o[n+2],s[i+6]=o[r],s[i+7]=o[r+1],s[i+8]=o[r+2]}return s}get hasAnimations(){return this.actions.length>0}get clips(){return this._clipsCache||=this.actions.map((e,t)=>{let n=e.getClip();return{index:t,name:n.name||`Clip ${t}`,duration:n.duration}}),this._clipsCache}dispose(){this.mixer&&=(this.mixer.stopAllAction(),this.mixer.uncacheRoot(this._mixerRoot),null),this.actions=[],this.isPlaying=!1,this.timer.reset(),this._scene=null,this._mixerRoot=null,this._meshes=null,this._meshTriRanges=null,this._meshPositions=null,this._skinnedCache=null,this._clipsCache=null,this._rigid=!1,this._plans=null,this._allPlan=null,this._activeClip=0,this._slotOf=null,this._lastWorld=null,this._lastVisible=null,this._lastMeshWorld=null,this._lastMorphWeights=null}};F();var Iw=new r.Vector3(0,0,-1),Lw=e=>{for(;e.parent;)e=e.parent;return e.isScene?e:null},Rw=class{constructor({camera:e,canvas:t,orbitControls:n,app:i}){this._app=i,this._orbitControls=n,this._camera=e,this._controls=new f.TransformControls(e,t),this._gizmoScene=new r.Scene,this._gizmoScene.add(this._controls.getHelper()),this._attached=null,this._isDragging=!1,this._meshes=null,this._refitInFlight=!1,this._baselineComputed=!1,this._moved=new Set,this._tempForward=new r.Vector3,this._lightTargetDistance=null,this._lastLightPosition=null,this._onDraggingChanged=this._onDraggingChanged.bind(this),this._onObjectChange=this._onObjectChange.bind(this),this._controls.addEventListener(`dragging-changed`,this._onDraggingChanged),this._controls.addEventListener(`objectChange`,this._onObjectChange)}setMeshData(e){this._meshes=e;for(let e of this._moved)Lw(e)||this._moved.delete(e)}get movedObjects(){return[...this._moved].filter(e=>Lw(e))}noteMoved(e){e&&!e.isLight&&this._moved.add(e)}attach(e){this._attached!==e&&(this._controls.attach(e),this._attached=e,this._lightTargetDistance=null,this._lastLightPosition=null,e.isLight&&e.target&&(this._syncLightAim(e),this._lastLightPosition=e.position.clone()))}detach(){this._attached&&(this._controls.detach(),this._attached=null,this._lightTargetDistance=null,this._lastLightPosition=null)}setMode(e){this._controls.setMode(e),this._app?.dispatchEvent({type:N.TRANSFORM_MODE_CHANGED,mode:e}),this._app?.refreshFrame()}setSpace(e){this._controls.setSpace(e),this._app?.refreshFrame()}get isDragging(){return this._isDragging}get attachedObject(){return this._attached}get controls(){return this._controls}render(e){if(!this._attached)return;let t=e.autoClear;e.autoClear=!1,e.clearDepth(),e.setRenderTarget(null),e.render(this._gizmoScene,this._camera),e.autoClear=t}_onDraggingChanged(e){this._isDragging=e.value,this._orbitControls&&(this._orbitControls.enabled=!e.value),e.value?this._app.dispatchEvent({type:N.OBJECT_TRANSFORM_START}):(this._attached?.isLight?this._finalizeLightTransform():this._recomputeAndRefit(),this._app.dispatchEvent({type:N.OBJECT_TRANSFORM_END}))}_onObjectChange(){this._app.needsReset=!0,this._app.wake(),this._attached?.isLight&&this._syncLightDuringDrag()}_syncLightDuringDrag(){let e=this._attached;if(e.target){let t=this._controls.mode;if(t===`translate`&&this._lastLightPosition&&!e.isDirectionalLight){let t=this._tempForward.copy(e.position).sub(this._lastLightPosition);e.target.position.add(t),e.target.updateMatrixWorld(!0)}else if(t===`rotate`&&this._lightTargetDistance!=null){let t=this._tempForward.set(0,0,-1).applyQuaternion(e.quaternion);e.target.position.copy(e.position).addScaledVector(t,this._lightTargetDistance),e.target.updateMatrixWorld(!0)}this._lastLightPosition.copy(e.position)}this._app.lightManager?.updateLights()}_finalizeLightTransform(){let e=this._attached;e.isDirectionalLight&&e.target&&this._controls.mode===`translate`&&this._syncLightAim(e),e.isRectAreaLight&&(e.scale.x!==1||e.scale.y!==1)&&(e.width*=e.scale.x,e.height*=e.scale.y,e.scale.set(1,1,1)),this._app.lightManager?.updateLights()}_syncLightAim(e){let t=this._tempForward.copy(e.target.position).sub(e.position),n=t.length();n>1e-4?(e.quaternion.setFromUnitVectors(Iw,t.normalize()),this._lightTargetDistance=n):this._lightTargetDistance=1}_recomputeAndRefit(){if(!this._meshes||this._refitInFlight||!this._attached)return;this._attached.updateMatrixWorld(!0);let e=this._findAffectedMeshIndices(this._attached);if(e.length!==0){this._refitInFlight=!0;try{this._app.updateMeshTransforms(e),this._moved.add(this._attached)}catch(e){console.error(`Transform refit error:`,e)}finally{this._refitInFlight=!1}}}_findAffectedMeshIndices(e){let t=[];for(let n=0;n<this._meshes.length;n++){let r=this._meshes[n];(r===e||this._isDescendantOf(r,e))&&t.push(n)}return t}_isDescendantOf(e,t){let n=e.parent;for(;n;){if(n===t)return!0;n=n.parent}return!1}dispose(){this._controls.removeEventListener(`dragging-changed`,this._onDraggingChanged),this._controls.removeEventListener(`objectChange`,this._onObjectChange),this.detach(),this._gizmoScene.remove(this._controls.getHelper()),this._controls.dispose(),this._meshes=null,this._moved.clear(),this._baselineComputed=!1,this._tempForward=null,this._lightTargetDistance=null,this._lastLightPosition=null,this._app=null,this._orbitControls=null,this._camera=null,this._controls=null,this._gizmoScene=null}},zw=class{constructor(e){this.layer=`scene`,this._transformManager=e,this._enabled=!0}get visible(){return this._enabled&&this._transformManager.attachedObject!==null}render(e){this._transformManager.render(e)}show(){this._enabled=!0}hide(){this._enabled=!1}dispose(){this._enabled=!1}};wc();var Bw=1,Vw=e=>typeof e==`string`&&/^https?:\/\//.test(e);function Hw(e,t){let n=[];for(;e&&e!==t;){let t=e.parent;if(!t)return null;n.unshift(t.children.indexOf(e)),e=t}return e===t?n:null}function Uw(e,t){let n=e;for(let e of t)if(n=n?.children[e],!n)return null;return n}function Ww(e){return{key:e.assetLoader?.sceneSourceKey??null,name:e.sceneModel?.name??null,meshes:e.sceneMeshes.length,materials:e.stages.pathTracer?.materialData.materialCount??0}}function Gw(e){let t=new Map;for(let n of e.sceneMeshes){let e=n.userData?.materialIndex;e!==void 0&&!t.has(e)&&t.set(e,Array.isArray(n.material)?n.material[0]:n.material)}return t}function Kw(e){if(!e)return null;let t=e.status(),n=t.activeView,r=t.config?.id??n?.configId??null;return{config:r?{id:r}:null,view:n?{display:n.display,view:n.view,look:n.look??null}:null,transform:n?null:t.activeTransform?.id??null,workingSpace:t.workingSpaceAdopted?t.workingSpace:null,context:t.context??null}}function qw(e){let t=e.meshScene,n=Gw(e),r=[];return t.traverse(e=>{e!==t&&e.visible===!1&&r.push(Hw(e,t))}),{v:1,engine:Cc,savedAt:Date.now(),scene:Ww(e),appended:t.children.filter(t=>t!==e.sceneModel&&t.userData?.__rayzeeSceneObject).map(e=>({name:e.userData.__rayzeeName??e.name,url:e.userData.__rayzeeSourceUrl??null,cacheKey:e.userData.__rayzeeCacheKey??null})),settings:e.settings.serialize(),environment:e.environmentManager?.serialize()??null,color:Kw(e.color),lights:e.lightManager.serialize(),cameras:e.cameraManager.serialize(),timeline:e.timeline?.serialize()??null,materials:(e.stages.pathTracer?.materialData.serializeHostEdits()??[]).map(e=>({...e,name:n.get(e.index)?.name??``})),hidden:r,moved:(e.transformManager?.movedObjects??[]).map(e=>({path:Hw(e,t),name:e.name,position:e.position.toArray(),quaternion:e.quaternion.toArray(),scale:e.scale.toArray()})).filter(e=>e.path)}}function Jw(e,t,n){let r=e[t];r?.copy&&(n?.isColor||n?.isVector2||n?.isVector3)?r.copy(n):e[t]=n,e.needsUpdate=!0}async function Yw(e,t,n,r){if(!t)return;let i=e.environmentManager;if(t.hdri&&t.hdri!==i.hdriSource){let i=Vw(t.hdri)?t.hdri:await n({kind:`environment`,source:t.hdri});try{typeof i==`string`?await e.loadEnvironment(i):i?await e.loadFile(i):r(`environment`,`source unavailable`,{source:t.hdri})}catch(e){r(`environment`,e.message,{source:t.hdri})}}await i.restore(t)}async function Xw(e,t,n,r){let i=e.color;if(!t||!i)return;let a=i.status(),o=a.activeView,s=!!t.view&&!!o&&o.display===t.view.display&&o.view===t.view.view&&(o.look??null)===t.view.look,c=a.config?.id??null,l=c??o?.configId??null;if(!((t.config?.id??null)===l&&!t.workingSpace&&!t.context&&(t.view?s:!o&&(!t.transform||t.transform===a.activeTransform?.id))))try{if(t.config&&t.config.id!==c){if(!await n({kind:`colorConfig`,config:t.config})){if(!(await i.constructor.listBuiltinConfigs().catch(()=>[])).some(e=>(e.name??e)===t.config.id||`ocio://${e.name??e}`===t.config.id)){r(`color`,`config unavailable`,{config:t.config.id});return}await e.loadColorConfig({builtin:t.config.id,registerViews:!1})}}else !t.config&&c&&await e.unloadColorConfig();t.context&&i.setContext(t.context),t.view?i.setView(t.view):t.transform&&i.setActiveView(t.transform),(t.workingSpace??null)!==(i.workingSpaceAdopted?i.workingSpace:null)&&(i.setWorkingSpace(t.workingSpace),await e.applyColorWorkingSpace())}catch(e){r(`color`,e.message,{config:t.config?.id??null})}}async function Zw(e,t,{resolve:n=async()=>null}={}){if(t?.v!==1)throw Error(`scene state version ${t?.v} is not 1`);let r=[],i=(e,t,n={})=>r.push({section:e,reason:t,...n});for(let n of t.appended??[]){if(!n.url){i(`appended`,`added from memory, not a file`,{name:n.name});continue}try{await e.addModel(n.url,{name:n.name,cacheKey:n.cacheKey??void 0})}catch(e){i(`appended`,e.message,{name:n.name})}}let a=Ww(e),o=t.scene??{},s=o.meshes===a.meshes&&o.materials===a.materials;s||i(`scene`,`the loaded scene is not the one saved: objects and materials left as loaded`,{saved:o,now:a}),await Yw(e,t.environment,n,i),await Xw(e,t.color,n,i);let c=e.settings.restore(t.settings);c.length&&i(`settings`,`not settings in this engine`,{keys:c});let l=e.lightManager.restore(t.lights);for(let t of l){let{gobo:n,ies:r}=t.userData;n&&e.goboManager?.entries?.length&&e.goboManager.setLightGobo(t.uuid,n.name,n),r&&e.iesManager?.entries?.length&&e.iesManager.setSpotLightProfile(t.uuid,r.name,r.intensity,{applyAutoCone:!1})}if(s){let n=Gw(e);for(let r of t.materials??[]){let t=n.get(r.index);if(!t||(t.name??``)!==r.name){i(`materials`,`no such material`,{index:r.index,name:r.name});continue}for(let[n,i]of Object.entries(r.props)){let a=rr(i);Jw(t,n,a),e.setMaterialProperty(r.index,n,a)}}let r=e.meshScene,a=new Set((t.hidden??[]).map(e=>Uw(r,e)).filter(Boolean));r.traverse(e=>{e!==r&&!e.isLight&&(e.visible=!a.has(e))}),e.updateAllMeshVisibility();let o=[];for(let n of t.moved??[]){let t=Uw(r,n.path);if(!t||t.name!==n.name){i(`moved`,`no such object`,{name:n.name});continue}t.position.fromArray(n.position),t.quaternion.fromArray(n.quaternion),t.scale.fromArray(n.scale),t.updateMatrixWorld(!0),e.transformManager?.noteMoved(t),o.push(t)}if(o.length){let t=[];e.sceneMeshes.forEach((e,n)=>{for(let r=e;r;r=r.parent)if(o.includes(r)){t.push(n);break}}),t.length&&e.updateMeshTransforms(t)}}let{mismatched:u}=e.cameraManager.restore(t.cameras);return u.length&&i(`cameras`,`model cameras changed`,{names:u}),e._dispatchCamerasUpdated(),e.timeline?.restore(t.timeline),e.reset(),{skipped:r}}var Qw=[{name:`FBX`,label:`FBX`,type:`model`,extensions:[`fbx`],async parse(e,{cache:t}){return t.fbx??=new(await(import(`three/addons/loaders/FBXLoader.js`))).FBXLoader,{model:t.fbx.parse(await e.arrayBuffer())}}},{name:`OBJ`,label:`OBJ`,type:`model`,extensions:[`obj`],async parse(e,{filename:t,cache:n}){n.obj??=new(await(import(`three/addons/loaders/OBJLoader.js`))).OBJLoader;let r=n.obj.parse(await e.text());return r.name=t,{model:r}}},{name:`STL`,label:`STL`,type:`model`,extensions:[`stl`],async parse(e,{filename:t,cache:n}){n.stl??=new(await(import(`three/addons/loaders/STLLoader.js`))).STLLoader;let i=new r.Mesh(n.stl.parse(await e.arrayBuffer()),new r.MeshStandardMaterial);return i.name=t,{model:i}}},{name:`PLY (Polygon File Format)`,label:`PLY`,type:`model`,extensions:[`ply`],async parse(e,{filename:t,cache:n}){n.ply??=new(await(import(`three/addons/loaders/PLYLoader.js`))).PLYLoader;let i=n.ply.parse(await e.arrayBuffer()),a;if(i.index!==null)a=new r.Mesh(i,new r.MeshStandardMaterial);else{let e=new r.PointsMaterial({size:.01});e.vertexColors=i.hasAttribute(`color`),a=new r.Points(i,e)}return a.name=t,{model:a}}},{name:`Collada`,label:`Collada`,type:`model`,extensions:[`dae`],async parse(e,{filename:t,cache:n}){n.collada??=new(await(import(`three/addons/loaders/ColladaLoader.js`))).ColladaLoader;let r=n.collada.parse(await e.text());return r.scene.name=t,{model:r.scene,result:r}}},{name:`3D Manufacturing Format`,label:`3MF`,type:`model`,extensions:[`3mf`],async parse(e,{cache:t}){return t.threemf??=new(await(import(`three/addons/loaders/3MFLoader.js`))).ThreeMFLoader,{model:t.threemf.parse(await e.arrayBuffer())}}},{name:`USD (Universal Scene Description)`,label:`USD`,type:`model`,extensions:[`usd`,`usda`,`usdc`,`usdz`],async parse(e,{filename:t,cache:n}){n.usd??=new(await(import(`three/addons/loaders/USDLoader.js`))).USDLoader;let r=await e.arrayBuffer(),i=await new Promise((e,t)=>n.usd.parse(r,``,e,t));return i.name=t,{model:i}}},{name:`EXR (OpenEXR)`,label:`EXR`,type:`environment`,extensions:[`exr`],async createLoader(e){let{EXRLoader:t}=await import(`three/addons/loaders/EXRLoader.js`);return new t(e).setDataType(r.FloatType)}}],$w=_({LampPick:()=>eT,areaLightDirectPdfW:()=>lT,directionalConeSolidAngle:()=>cT,lampCount:()=>tT,lampPickPdf:()=>oT,lampTypeAt:()=>nT,pickLamp:()=>aT,spotConeSolidAngle:()=>sT});O(),xu();var eT=x({kind:`int`,index:`int`,pdf:`float`,total:`float`}),tT=e=>e.numDirectional.add(e.numArea).add(e.numPoint).add(e.numSpot),nT=(e,t)=>(0,n.select)(t.lessThan(e.numDirectional),(0,n.int)(0),(0,n.select)(t.lessThan(e.numDirectional.add(e.numArea)),(0,n.int)(1),(0,n.select)(t.lessThan(e.numDirectional.add(e.numArea).add(e.numPoint)),(0,n.int)(2),(0,n.int)(3)))),rT=(e,t)=>(0,n.select)(t.equal((0,n.int)(0)),(0,n.int)(0),(0,n.select)(t.equal((0,n.int)(1)),e.numDirectional,(0,n.select)(t.equal((0,n.int)(2)),e.numDirectional.add(e.numArea),e.numDirectional.add(e.numArea).add(e.numPoint)))),iT=(e,t,r,i,a)=>{let o=(e,t,r)=>(0,n.If)(t.greaterThan((0,n.int)(0)),()=>{(0,n.Loop)({start:(0,n.int)(0),end:t,type:`int`,condition:`<`},({i:t})=>{a((0,n.int)(e),t,r(t).toVar())})});o(0,e.numDirectional,t=>Sh(Nm.wrap(zm(e.directional,t)),r,i,(0,n.int)(0))),o(1,e.numArea,a=>{let o=Pm.wrap(Bm(e.area,a));return(0,n.select)(o.intensity.greaterThan(0),Ch(o,t,r,i),(0,n.float)(0))}),o(2,e.numPoint,n=>wh(Fm.wrap(Vm(e.point,n)),t,r,i)),o(3,e.numSpot,n=>Th(Im.wrap(Hm(e.spot,n)),t,r,i))};function aT(e,t,r,i,a,o){let s=(0,n.int)(-1).toVar(),c=(0,n.int)(-1).toVar(),l=(0,n.float)(0).toVar(),u=(0,n.float)(0).toVar();iT(e,t,r,i,(t,r,i)=>{u.addAssign(i),(0,n.If)(i.greaterThan(0).and(o((0,n.int)(Ge+64).add(rT(e,t)).add(r)).mul(u).lessThan(i)),()=>{s.assign(t),c.assign(r),l.assign(i)})});let d=tT(e).toVar(),f=l.div((0,n.max)(u,1e-10)).toVar();return(0,n.If)(u.lessThanEqual(0),()=>{let t=(0,n.min)((0,n.int)(a.mul((0,n.float)(d))),d.sub((0,n.int)(1))).toVar();s.assign(nT(e,t)),c.assign(t.sub(rT(e,s))),f.assign((0,n.float)(1).div((0,n.max)((0,n.float)(d),1)))}),eT({kind:s,index:c,pdf:f,total:u})}function oT(e,t,r,i,a,o){let s=(0,n.float)(0).toVar(),c=(0,n.float)(0).toVar();return iT(e,i,a,o,(e,i,a)=>{s.addAssign(a),(0,n.If)(e.equal(t).and(i.equal(r)),()=>{c.assign(a)})}),(0,n.select)(s.greaterThan(0),c.div(s),(0,n.float)(1).div((0,n.max)((0,n.float)(tT(e)),1)))}var sT=e=>(0,n.float)(2*Nl).mul((0,n.max)((0,n.float)(1).sub((0,n.cos)(e.angle)),1e-10)),cT=e=>(0,n.float)(2*Nl).mul((0,n.max)((0,n.float)(1).sub((0,n.cos)(e.angle.mul(.5))),1e-10)),lT=(e,t,r,i)=>{let a=Zm(t,e.position.sub(e.u).sub(e.v),e.u.mul(2),e.v.mul(2)).toVar();return(0,n.select)(e.shape.lessThan(.5).and(a.greaterThan(1e-5)),(0,n.float)(1).div(a),r.mul(r).div((0,n.max)(e.area.mul((0,n.max)(i,.001)),1e-10)))},uT=_({DIM_CONNECT_PATH:()=>16,DIM_CONNECT_VERTEX:()=>17,DIM_EMIT:()=>dT,LIGHT_PIXEL_ROW_OFFSET:()=>fT,PASS_TAG_BIT:()=>hT,SOURCE:()=>PT,SPLAT_MAX:()=>mT,SPLAT_SCALE:()=>pT,STRATEGY:()=>kT,STRATEGY_ALONE:()=>8,emitterAreaPdf:()=>MT,emitterSideProbability:()=>jT,facingSide:()=>BT,lampSource:()=>IT,lightEndCosine:()=>VT,lightPathPixel:()=>vT,mergeEta:()=>TT,mergeRadiusAt:()=>wT,mergeVmAt:()=>ET,mis:()=>yT,misMergePartial:()=>DT,misOnHit:()=>bT,misOnScatter:()=>ST,misOnSpecular:()=>xT,misPartial:()=>CT,misWeight:()=>OT,resolveSurfaceMaterial:()=>zT,sourceLampIndex:()=>RT,sourceLampType:()=>LT,sourcePick:()=>FT,strategyWeight:()=>AT,sunEmissionPdf:()=>NT});xu(),Dl();var dT=Ge+2048,fT=65536,pT=16384,mT=4096,hT=2147483648,gT=1e30,_T=e=>(0,n.select)(e.equal(e),e,(0,n.float)(0)).clamp(0,gT),vT=(e,t)=>{let r=(0,n.uint)(t.x);return(0,n.vec2)((0,n.float)((0,n.uint)(e).mod(r)).add(.5),(0,n.float)((0,n.uint)(e).div(r).add((0,n.uint)(fT))).add(.5))},yT=e=>e.mul(e),bT=(e,t,r)=>{let i=(0,n.max)(r,1e-6);e.dVCM.assign(_T(e.dVCM.mul(yT(t.mul(t).div(i))))),e.dVC.assign(_T(e.dVC.div(yT(i))))},xT=(e,t)=>{e.dVC.assign(_T(e.dVC.mul(yT(t)))),e.dVCM.assign(0)},ST=(e,t,r,i)=>{let a=(0,n.max)(r,1e-12),o=e.dVC.mul(yT(i)).add(e.dVCM);e.dVC.assign(_T(yT(t.div(a)).mul(_T(e.vm?o.add(e.vm):o)))),e.dVCM.assign(_T(yT((0,n.float)(1).div(a))))},CT=(e,t,n)=>{let r=t.dVCM.add(t.dVC.mul(yT(n)));return _T(_T(yT(e)).mul(_T(t.vm?r.add(t.vm):r)))},wT=(e,t)=>(0,n.max)(e.mergeConst.add(e.mergeSlope.mul((0,n.length)(t.sub(e.cameraPosition)))),e.mergeMin),TT=(e,t)=>t.mul(t).mul(Math.PI).mul((0,n.float)(e.lightPaths)),ET=(e,t)=>{let n=TT(e,wT(e,t)).mul(e.mergeTrust);return n.mul(n)},DT=(e,t,n)=>_T(_T(e.dVCM.add(e.dVC.mul(yT(t)))).mul(n)),OT=(e,t)=>(0,n.float)(1).div((0,n.float)(1).add(_T(e)).add(_T(t))),kT={ALL:0,HIT:1,NEE:2,CONNECT:3,LIGHT_TRACE:4,MERGE:5},AT=(e,t,r,i=(0,n.float)(1))=>(0,n.select)(e.equal((0,n.uint)(kT.ALL)).or(e.equal((0,n.uint)(t))),r,(0,n.select)(e.equal((0,n.uint)(t+8)),i,(0,n.float)(0))),jT=(e,t)=>(0,n.select)(e.equal((0,n.int)(2)),(0,n.float)(.5),(0,n.select)(e.equal((0,n.int)(1)),(0,n.select)(t.lessThan(0),(0,n.float)(1),(0,n.float)(0)),(0,n.select)(t.greaterThan(0),(0,n.float)(1),(0,n.float)(0)))),MT=(e,t,r=1)=>(0,n.max)((0,n.dot)(e,Bl),0).div((0,n.max)(t,1e-10)).mul(r),NT=(e,t,r)=>e.sunPick.mul(r).div((0,n.max)(t.y,1e-30)),PT={SUN:0,EMITTERS:1,ENVIRONMENT:2,LAMPS:3},FT=(e,t)=>{let r=(0,n.int)(t);return e.sourceCdf.element(r).sub((0,n.select)(r.greaterThan((0,n.int)(0)),e.sourceCdf.element((0,n.max)(r.sub((0,n.int)(1)),(0,n.int)(0))),(0,n.float)(0)))},IT=(e,t,r)=>(0,n.select)(t.equal((0,n.int)(0)),(0,n.int)(e.sourceOffsets[0]),(0,n.select)(t.equal((0,n.int)(1)),(0,n.int)(e.sourceOffsets[1]),(0,n.select)(t.equal((0,n.int)(2)),(0,n.int)(e.sourceOffsets[2]),(0,n.int)(e.sourceOffsets[3])))).add(r),LT=(e,t)=>(0,n.select)(t.lessThan((0,n.int)(e.sourceOffsets[1])),(0,n.int)(0),(0,n.select)(t.lessThan((0,n.int)(e.sourceOffsets[2])),(0,n.int)(1),(0,n.select)(t.lessThan((0,n.int)(e.sourceOffsets[3])),(0,n.int)(2),(0,n.int)(3)))),RT=(e,t,r)=>t.sub((0,n.select)(r.equal((0,n.int)(0)),(0,n.int)(e.sourceOffsets[0]),(0,n.select)(r.equal((0,n.int)(1)),(0,n.int)(e.sourceOffsets[1]),(0,n.select)(r.equal((0,n.int)(2)),(0,n.int)(e.sourceOffsets[2]),(0,n.int)(e.sourceOffsets[3])))));function zT(e,t,r,i){let a=fl.wrap(fu((0,n.int)(e),i)).toVar();a.normalMapIndex.assign((0,n.int)(-1)),a.bumpMapIndex.assign((0,n.int)(-1)),a.displacementMapIndex.assign((0,n.int)(-1));let o=Cl.wrap(Np(a,t,r,(0,n.vec4)(0))).toVar(),s=o.roughness.toVar();a.color.assign(o.albedo),a.metalness.assign(o.metalness.clamp(0,1)),a.roughness.assign(o.roughness.clamp(Ll,1)),a.sheenRoughness.assign(a.sheenRoughness.clamp(.05,1));let c=yp({uv:t,transform:a.albedoTransform}).toVar();(0,n.If)(a.anisotropyMapIndex.greaterThanEqual((0,n.int)(0)),()=>{let e=Ap(a,c).toVar();a.anisotropy.assign(e.x),a.anisotropyRotation.assign(e.y)});let l=pl.wrap(jp(a,c)).toVar();return a.transmission.assign(l.transmission),a.clearcoat.assign(l.clearcoat),a.clearcoatRoughness.assign(l.clearcoatRoughness),a.sheenColor.assign(l.sheenColor),a.sheenRoughness.assign(l.sheenRoughness),a.iridescence.assign(l.iridescence),a.iridescenceThicknessRange.assign((0,n.vec2)(a.iridescenceThicknessRange.x,l.iridescenceThickness)),a.specularIntensity.assign(l.specularIntensity),a.specularColor.assign(l.specularColor),a.diffuseTransmission.assign(l.diffuseTransmission),a.diffuseTransmissionColor.assign(l.diffuseTransmissionColor),(0,n.If)(s.lessThan(Ll).and(a.anisotropy.equal(0)).and(a.clearcoat.equal(0)).and(a.transmission.equal(0)).and(a.subsurface.equal(0)),()=>{a.roughness.assign(0)}),a}var BT=(e,t,r)=>(0,n.select)(r.diffuseTransmission.greaterThan(0).and((0,n.dot)(e,t).lessThan(0)),e.negate(),e),VT=(e,t,r,i)=>(0,n.abs)((0,n.dot)(e,t)).mul((0,n.abs)((0,n.dot)(i,r))).div((0,n.max)((0,n.abs)((0,n.dot)(e,r)),1e-4)),HT=4096,UT=HT+1,WT=Math.ceil(UT*4/256)*64,GT=.2,KT=e=>{let t=(0,n.normalize)((0,n.cross)((0,n.select)((0,n.abs)(e.x).greaterThan(.9),(0,n.vec3)(0,1,0),(0,n.vec3)(1,0,0)),e)).toVar();return{u:t,v:(0,n.cross)(e,t).toVar()}},qT=e=>{let t=e.div((0,n.max)((0,n.abs)(e.x).add((0,n.abs)(e.y)).add((0,n.abs)(e.z)),1e-20)).toVar(),r=(0,n.vec2)(t.x,t.z).toVar();(0,n.If)(t.y.lessThan(0),()=>{r.assign((0,n.vec2)((0,n.float)(1).sub((0,n.abs)(t.z)).mul((0,n.select)(t.x.greaterThanEqual(0),1,-1)),(0,n.float)(1).sub((0,n.abs)(t.x)).mul((0,n.select)(t.z.greaterThanEqual(0),1,-1))))});let i=(0,n.floor)(r.mul(.5).add(.5).mul(4)).clamp(0,3);return(0,n.int)(i.y).mul(4).add((0,n.int)(i.x))},JT=(e,t,r)=>{let{u:i,v:a}=KT(t),o=r.sub(e.sceneCenter);return(0,n.vec2)((0,n.dot)(o,i),(0,n.dot)(o,a)).div(e.sceneRadius)},YT=e=>{let t=e.mul(.5).add(.5).mul(64).toVar();return(0,n.select)(t.x.greaterThanEqual(0).and(t.y.greaterThanEqual(0)).and(t.x.lessThan(64)).and(t.y.lessThan(64)),(0,n.int)(t.y).mul(64).add((0,n.int)(t.x)),(0,n.int)(-1))},XT=(e,t,r)=>e.guide.greaterThan((0,n.uint)(0)).and(t.load((0,n.ivec2)((0,n.int)(HT),r)).x.greaterThan(0)),ZT=(e,t,r,i)=>{let a=JT(e,r,i).toVar(),o=e.sceneRadius.mul(e.sceneRadius).toVar(),s=(0,n.select)((0,n.dot)(a,a).lessThanEqual(1),(0,n.float)(1).div((0,n.max)(o.mul(Math.PI),1e-30)),(0,n.float)(0)).toVar(),c=qT(r).toVar(),l=YT(a).toVar(),u=e=>t.load((0,n.ivec2)((0,n.max)(e,(0,n.int)(0)),c)).x,d=(0,n.select)(l.greaterThanEqual((0,n.int)(0)),u(l).sub((0,n.select)(l.greaterThan((0,n.int)(0)),u(l.sub((0,n.int)(1))),(0,n.float)(0))),(0,n.float)(0)).mul(HT/4).div((0,n.max)(o,1e-30));return(0,n.select)(XT(e,t,c),(0,n.mix)(d,s,GT),s)},QT=(e,t,r,i,a)=>{let{u:o,v:s}=KT(r),c=(0,n.vec2)(0).toVar(),l=qT(r).toVar();return(0,n.If)(XT(e,t,l).and(i.lessThan(1-GT)),()=>{let e=i.div(1-GT).toVar(),r=(0,n.int)(0).toVar(),o=(0,n.int)(HT-1).toVar();(0,n.Loop)(r.lessThan(o),()=>{let i=r.add(o).div(2).toVar();(0,n.If)(t.load((0,n.ivec2)(i,l)).x.lessThanEqual(e),()=>{r.assign(i.add(1))}).Else(()=>{o.assign(i)})});let s=(0,n.vec2)((0,n.float)(r.mod((0,n.int)(64))),(0,n.float)(r.div((0,n.int)(64))));c.assign(s.add(a).div(64).mul(2).sub(1))}).Else(()=>{let e=(0,n.sqrt)(a.x),t=a.y.mul(2*Math.PI);c.assign((0,n.vec2)(e.mul((0,n.cos)(t)),e.mul((0,n.sin)(t))))}),e.sceneCenter.add(r.mul(e.sceneRadius)).add(o.mul(c.x).add(s.mul(c.y)).mul(e.sceneRadius))},$T=(e,t,r,i)=>{let a=YT(JT(t,r,i)).toVar();(0,n.If)(t.guideLearning.greaterThan((0,n.uint)(0)).and(a.greaterThanEqual((0,n.int)(0))),()=>{(0,n.atomicAdd)(e.element((0,n.uint)(Z.GUIDE).add((0,n.uint)(qT(r).mul((0,n.int)(HT)).add(a)))),(0,n.uint)(1))})};function eE({counters:e,out:t}){return(0,n.Fn)(()=>{let r=n.instanceIndex;(0,n.If)(r.greaterThanEqual((0,n.uint)(16)),()=>{(0,n.Return)()});let i=(0,n.uint)(Z.GUIDE).add(r.mul((0,n.uint)(HT))).toVar(),a=(0,n.float)(0).toVar();(0,n.Loop)({start:(0,n.int)(0),end:(0,n.int)(HT),type:`int`,condition:`<`},({i:t})=>{a.addAssign((0,n.float)((0,n.atomicLoad)(e.element(i.add((0,n.uint)(t))))))});let o=r.mul((0,n.uint)(WT)).toVar(),s=(0,n.float)(0).toVar();(0,n.Loop)({start:(0,n.int)(0),end:(0,n.int)(HT),type:`int`,condition:`<`},({i:r})=>{s.addAssign((0,n.float)((0,n.atomicLoad)(e.element(i.add((0,n.uint)(r)))))),t.element(o.add((0,n.uint)(r))).assign((0,n.select)(a.greaterThan(0),(0,n.select)(r.equal((0,n.int)(HT-1)),(0,n.float)(1),s.div(a)),(0,n.float)(0)))}),t.element(o.add((0,n.uint)(HT))).assign(a)})().compute(16,[16])}function tE({counters:e}){return(0,n.Fn)(()=>{(0,n.If)(n.instanceIndex.lessThan((0,n.uint)(Ud)),()=>{(0,n.atomicStore)(e.element((0,n.uint)(Z.GUIDE).add(n.instanceIndex)),(0,n.uint)(0))})})().compute(Ud,[256])}xu(),Vd();function nE(e){let{rayBufferRW:t,hitBufferRW:r,activeIndicesRW:i,counters:a,lightBuffer:o,triangleBuffer:s,bvhBuffer:c,emissiveTriangleCount:l,emissiveVec4Offset:u,emissiveTotalPower:d,emissiveBoost:f,sunDirection:p,sunRadiance:m,sunParams:h,environmentIntensity:g,envTexture:_,envCDFTexture:v,envMatrix:y,envResolution:b,directionalLightsBuffer:x,areaLightsBuffer:S,pointLightsBuffer:C,spotLightsBuffer:w,bidirectional:T,resolution:E,frame:D,transmissiveBounces:O}=e,{lightPaths:k}=T;return(0,n.Fn)(()=>{let e=n.instanceIndex;(0,n.If)(e.equal((0,n.uint)(0)),()=>{(0,n.atomicStore)(a.element((0,n.uint)(Z.ACTIVE_RAY_COUNT)),k),(0,n.atomicStore)(a.element((0,n.uint)(Z.ENTERING_COUNT)),k)}),(0,n.If)(e.greaterThanEqual(k),()=>{(0,n.Return)()}),i.element(e).assign(e);let A=vT(e,E).toVar(),j=Be({state:nt({pixelCoord:A,rayIndex:(0,n.int)(3),frame:D})}).toVar(),M=(0,n.vec3)(0).toVar(),N=(0,n.vec3)(0,1,0).toVar(),P=(0,n.vec3)(0).toVar(),F=(0,n.float)(0).toVar(),I=(0,n.float)(0).toVar(),L=(0,n.int)(-1).toVar(),ee=(0,n.int)(0).toVar(),te=(0,n.float)(1).toVar(),R=(0,n.bool)(!1).toVar(),ne=et(A,(0,n.int)(0),(0,n.int)(dT+4),j,E,D).toVar(),re=(0,n.int)(0).toVar(),ie=(0,n.int)(T.sourceCount-1).toVar();(0,n.Loop)(re.lessThan(ie),()=>{let e=re.add(ie).div(2).toVar();(0,n.If)(T.sourceCdf.element(e).lessThanEqual(ne),()=>{re.assign(e.add(1))}).Else(()=>{ie.assign(e)})});let ae=T.guideTexture,oe=e=>{let t=QT(T,ae,e,et(A,(0,n.int)(0),(0,n.int)(dT+7),j,E,D),$e(A,(0,n.int)(0),(0,n.int)(dT+6),j,E,D)).toVar();return{start:t,pdf:ZT(T,ae,e,t)}};(0,n.If)(re.equal((0,n.int)(PT.SUN)),()=>{let e=jh(p,h,$e(A,(0,n.int)(0),(0,n.int)(dT+5),j,E,D)).toVar(),t=Ah(e,p,m,h).mul(g).toVar(),r=oe(e),i=NT(T,h,r.pdf).toVar();(0,n.If)(t.x.add(t.y).add(t.z).greaterThan(0).and(i.greaterThan(0)),()=>{M.assign(r.start),N.assign(e.negate()),P.assign(t.div(i)),F.assign(yT((0,n.float)(1).div(h.y.mul(i)))),I.assign(yT((0,n.float)(1).div(i))),R.assign(!0)})}).ElseIf(re.equal((0,n.int)(PT.EMITTERS)),()=>{let e=Kg(o,u,l,et(A,(0,n.int)(0),(0,n.int)(dT),j,E,D)).toVar(),t=u.add(e.mul((0,n.int)(2))),r=o.element(t).toVar(),i=o.element(t.add((0,n.int)(1))).toVar();L.assign((0,n.int)(r.x)),ee.assign((0,n.int)(r.w));let a=Ug.wrap(Wg(L,s,c,ee)).toVar(),p=Ng(a.v0,a.v1,a.v2,$e(A,(0,n.int)(0),(0,n.int)(dT+1),j,E,D)).toVar(),m=(0,n.normalize)((0,n.cross)(a.v1.sub(a.v0),a.v2.sub(a.v0))).toVar(),h=Pf(cu(s,L,4).z).toVar(),g=(0,n.select)(h.equal((0,n.int)(1)).or(h.equal((0,n.int)(2)).and(et(A,(0,n.int)(0),(0,n.int)(dT+3),j,E,D).lessThan(.5))).toVar(),m.negate(),m).toVar();N.assign(cp(g,$e(A,(0,n.int)(0),(0,n.int)(dT+2),j,E,D)));let _=(0,n.dot)(N,g).toVar(),v=(0,n.max)(r.y,0).div((0,n.max)(d,1e-10)).div((0,n.max)(i.w,1e-20)).mul((0,n.select)(h.equal((0,n.int)(2)),(0,n.float)(.5),(0,n.float)(1))).mul(T.emitterPick).toVar(),y=v.mul(_).div(Math.PI).toVar();(0,n.If)(_.greaterThan(1e-6).and(y.greaterThan(0)),()=>{M.assign(jl(p,g)),P.assign(i.xyz.mul(f).mul(Math.PI).div(v)),F.assign(yT((0,n.float)(1).div(y))),I.assign(yT(_.div(y))),te.assign(_),R.assign(!0)})}).ElseIf(re.equal((0,n.int)(PT.ENVIRONMENT)),()=>{let e=tp(v,y,b,$e(A,(0,n.int)(0),(0,n.int)(dT+5),j,E,D)),t=e.direction.toVar(),r=e.pdf.toVar(),i=rp({tex:_,samp:(0,n.sampler)(_),direction:t,environmentMatrix:y,environmentIntensity:g,enableEnvironmentLight:(0,n.float)(1)}).xyz.toVar(),a=oe(t),o=T.envPick.mul(r).mul(a.pdf).toVar();(0,n.If)(i.x.add(i.y).add(i.z).greaterThan(0).and(o.greaterThan(0)),()=>{M.assign(a.start),N.assign(t.negate()),P.assign(i.div(o)),F.assign(yT(r.div(o))),I.assign(yT((0,n.float)(1).div(o))),L.assign((0,n.int)(-1-PT.ENVIRONMENT)),R.assign(!0)})}).ElseIf(re.greaterThanEqual((0,n.int)(PT.LAMPS)),()=>{let e=FT(T,re).toVar(),t=LT(T,re).toVar(),r=RT(T,re,t).toVar();L.assign((0,n.int)(-1).sub(re));let i=(0,n.float)(0).toVar(),a=(0,n.vec3)(0).toVar(),o=$e(A,(0,n.int)(0),(0,n.int)(dT+2),j,E,D).toVar();(0,n.If)(t.equal((0,n.int)(0)),()=>{let t=Nm.wrap(zm(x,r)),o=(0,n.normalize)(t.direction).toVar();a.assign(t.color.mul(t.intensity)),i.assign(e),(0,n.If)(t.angle.greaterThan(0),()=>{let e=cT(t).toVar();o.assign(Ym(o,t.angle.mul(.5),$e(A,(0,n.int)(0),(0,n.int)(dT+5),j,E,D))),a.divAssign(e),i.divAssign(e)});let s=oe(o);i.mulAssign(s.pdf),M.assign(s.start),N.assign(o.negate())}).ElseIf(t.equal((0,n.int)(1)),()=>{let t=Pm.wrap(Bm(S,r)),s=t.shape.greaterThan(.5),c=$e(A,(0,n.int)(0),(0,n.int)(dT+1),j,E,D).toVar(),l=(0,n.sqrt)(c.x),u=c.y.mul(2*Math.PI);M.assign(t.position.add(t.u.mul((0,n.select)(s,l.mul((0,n.cos)(u)),c.x.mul(2).sub(1)))).add(t.v.mul((0,n.select)(s,l.mul((0,n.sin)(u)),c.y.mul(2).sub(1))))),N.assign(cp(t.normal,o));let d=(0,n.dot)(N,t.normal).toVar();a.assign((0,n.select)(t.area.greaterThan(0).and(d.greaterThan(1e-6)),Jh(t).mul(qh(d,t.spread)).mul(d),(0,n.vec3)(0))),i.assign(e.div((0,n.max)(t.area,1e-20)).mul(d).div(Math.PI)),I.assign(yT(d.div((0,n.max)(i,1e-30))))}).ElseIf(t.equal((0,n.int)(2)),()=>{let t=Fm.wrap(Vm(C,r));M.assign(t.position),N.assign(Ym((0,n.vec3)(0,1,0),(0,n.float)(Math.PI),o)),a.assign(t.color.mul(t.intensity)),i.assign(e.div(4*Math.PI))}).Else(()=>{let t=Im.wrap(Hm(w,r));M.assign(t.position),N.assign(Ym(t.direction,t.angle,o));let s=N.negate();a.assign(t.color.mul(t.intensity).mul(Gm({coneCosine:(0,n.cos)(t.angle),blend:t.penumbra,angleCosine:(0,n.dot)(N,t.direction)})).mul(Km(t,s)).mul(Jm(t,s))),i.assign(e.div(sT(t)))}),(0,n.If)(a.x.add(a.y).add(a.z).greaterThan(0).and(i.greaterThan(0)),()=>{P.assign(a.div(i)),F.assign(yT((0,n.float)(1).div(i))),R.assign(!0)})}),(0,n.If)(R.not(),()=>{td(t,e,N,(0,n.uint)(0)),(0,n.Return)()});let se=(0,n.max)((0,n.max)((0,n.max)(P.x,P.y),P.z),1e-20).toVar();ed(t,e,M,(0,n.int)(0),(0,n.int)(0)),td(t,e,N,(0,n.uint)(Q.ACTIVE|Q.REDIRECTED|Q.LIGHT_PATH|Q.LIGHT_EMITTED)),nd(t,e,P.div(se),(0,n.float)(0)),rd(t,e,(0,n.vec4)((0,n.vec3)(0),(0,n.float)(1))),kd(t,e,(0,n.uint)(0),(0,n.uint)(O),(0,n.float)(1),(0,n.float)(1),(0,n.float)(1)),md(r,e,j,F,I),Td(r,e,L,ee,te,se)})}xu(),Vd();function rE(e){let{rayBufferRW:t,hitBufferRO:r,activeIndicesRO:i,counters:a,bvhBuffer:o,triangleBuffer:s,materialBuffer:c,resolution:l,frame:u,accumFrame:d,currentBounce:f,chunkRowBase:p,lightPaths:m,slotsPerPath:h,lightTag:g,passTag:_,strategyView:v,maxBounceCount:y,globalIlluminationIntensity:b,fireflyThreshold:x,mergeVm:S=null,diffuseTransmission:C=!0}=e;return(0,n.Fn)(()=>{let e=n.instanceIndex;(0,n.If)(e.greaterThanEqual((0,n.atomicLoad)(a.element((0,n.uint)(Z.ENTERING_COUNT)))),()=>{(0,n.Return)()});let w=i.element(e).toVar(),T=hd(w);(0,n.If)(vd(r,T).notEqual(_),()=>{(0,n.Return)()});let E=Sd(r,T),D={...E,vm:S?.(E.position)??null},O=(0,n.int)(D.extra).add((0,n.int)(1)).toVar(),k=(0,n.int)(l.x),A=(0,n.int)(w).add(p.mul(k)),j=(0,n.vec2)((0,n.float)(A.mod(k)).add(.5),(0,n.float)(A.div(k)).add(.5)).toVar(),M=(0,n.int)(f).mul((0,n.int)(32)),N=Be({state:dd(r,w).bitXor((0,n.uint)(2654435769))}).toVar(),P=et(j,(0,n.int)(0),M.add((0,n.int)(16)),N,l,u).toVar(),F=et(j,(0,n.int)(0),M.add((0,n.int)(17)),N,l,u).toVar(),I=(0,n.min)((0,n.uint)((0,n.float)(m).mul(P)),m.sub((0,n.uint)(1))).toVar().mul(h).toVar(),L=(0,n.min)((0,n.int)(Cd(r,gd(I),g)),(0,n.int)(y).add((0,n.int)(1)).sub(O)).toVar();(0,n.If)(L.lessThan((0,n.int)(1)),()=>{(0,n.Return)()});let ee=(0,n.min)((0,n.int)((0,n.float)(L).mul(F)),L.sub((0,n.int)(1))).toVar(),te=Sd(r,gd(I.add((0,n.uint)(ee)))),R={...te,vm:S?.(te.position)??null},ne=R.position.sub(D.position).toVar(),re=(0,n.max)((0,n.dot)(ne,ne),1e-12).toVar(),ie=ne.div((0,n.sqrt)(re)).toVar(),ae=(0,n.dot)(ie,D.N).toVar(),oe=(0,n.dot)(ie,D.facetN).toVar(),se=(0,n.dot)(ie,R.facetN).negate().toVar(),ce=ae.greaterThan(0).and(oe.greaterThan(0)).and(se.greaterThan(0)),le=ae.lessThan(0).and(oe.lessThan(0)),z=se.lessThan(0);(0,n.If)((C?le.or(ae.greaterThan(0).and(oe.greaterThan(0))).and(z.or(se.greaterThan(0))):ce).not(),()=>{(0,n.Return)()});let ue=zT(D.materialIndex,D.uv,D.N,c),de=zT(R.materialIndex,R.uv,R.N,c),fe=ie.negate();C&&(0,n.If)(le.and(ue.diffuseTransmission.lessThanEqual(0)).or(z.and(de.diffuseTransmission.lessThanEqual(0))),()=>{(0,n.Return)()});let pe=e=>C?BT(D.N,e,ue):D.N,me=e=>C?BT(R.N,e,de):R.N,he=Mm(D.V,ie,D.N,ue).toVar(),ge=Mm(fe,R.V,me(fe),de).toVar(),_e=(C?(0,n.abs)(ae):ae).mul(VT(R.V,R.N,R.facetN,fe)).div(re),ve=ng(D.V,ie,D.N,ue),ye=ng(ie,D.V,pe(ie),ue),be=ng(R.V,fe,R.N,de),xe=ng(fe,R.V,me(fe),de),Se=CT(ve.mul(C?(0,n.abs)(se):se).div(re),R,xe),Ce=CT(be.mul(C?(0,n.abs)(oe):oe).div(re),D,ye),we=O.add(ee).add((0,n.int)(1)),B=AT(v,kT.CONNECT,OT(Se,Ce),(0,n.float)(1).div((0,n.float)(we.sub((0,n.int)(1))))),Te=gg(D.throughput.mul(he).mul(ge).mul(R.throughput).mul(_e.mul(B).mul((0,n.float)(L)).mul(b)),(0,n.float)(we.sub((0,n.int)(1))),x,(0,n.int)(d)).toVar();(0,n.If)(Yl(Te).greaterThan(0),()=>{let e=jl(D.position,C?(0,n.select)(le,D.facetN.negate(),D.facetN):D.facetN).toVar(),r=jl(R.position,C?(0,n.select)(z,R.facetN.negate(),R.facetN):R.facetN).sub(e).toVar(),i=(0,n.length)(r).toVar(),a=bh(e,r.div(i),i.mul(Ml),Bf,o,s,c);(0,n.If)(a.greaterThan(0),()=>{let e=Wu(t,w).toVar();rd(t,w,(0,n.vec4)(e.xyz.add(Te.mul(a)),e.w))})})})}xu(),Vd();var iE=4294967295,aE=1024,oE=Math.log2(1.25),sE=(e,t)=>(0,n.int)((0,n.max)((0,n.floor)((0,n.log2)(t.div(e.mergeMin)).div(oE)),0)),cE=(e,t)=>e.mergeMin.mul((0,n.exp2)((0,n.float)(t.add((0,n.int)(1))).mul(oE))).mul(2).div((0,n.max)((0,n.float)(1).sub(e.mergeSlope),.5)),lE=(e,t,r)=>(0,n.uint)(t.x).mul((0,n.uint)(73856093)).bitXor((0,n.uint)(t.y).mul((0,n.uint)(19349663))).bitXor((0,n.uint)(t.z).mul((0,n.uint)(83492791))).bitXor((0,n.uint)(e).mul((0,n.uint)(2654435761))).bitAnd(r),uE=(e,t)=>{let r=sE(e,wT(e,t)).toVar();return{shell:r,cell:(0,n.ivec3)((0,n.floor)(t.div(cE(e,r)))).toVar()}};function dE({head:e,hashSize:t}){return(0,n.Fn)(()=>{(0,n.If)(n.instanceIndex.lessThan((0,n.uint)(t)),()=>{(0,n.atomicStore)(e.element(n.instanceIndex),(0,n.uint)(iE))})})().compute(Math.ceil(t/256)*256,[256])}function fE({hitBufferRW:e,head:t,bidirectional:r}){let{lightPaths:i,slotsPerPath:a,lightTag:o,hashMask:s}=r;return(0,n.Fn)(()=>{let c=n.instanceIndex.toVar();(0,n.If)(c.greaterThanEqual(i.mul(a)),()=>{(0,n.Return)()});let l=c.mod(a).toVar();(0,n.If)(l.greaterThanEqual(Cd(e,gd(c.sub(l)),o)),()=>{(0,n.Return)()});let u=gd(c),{shell:d,cell:f}=uE(r,yd(e,u)),p=lE(d,f,s);xd(e,u,(0,n.atomicFunc)(`atomicExchange`,t.element(p),c))})}function pE(e){let{rayBufferRW:t,hitBufferRO:r,activeIndicesRO:i,counters:a,head:o,materialBuffer:s,bidirectional:c,maxBounceCount:l,globalIlluminationIntensity:u,fireflyThreshold:d,accumFrame:f,diffuseTransmission:p=!0}=e,{passTag:m,slotsPerPath:h,strategyView:g,hashMask:_}=c;return(0,n.Fn)(()=>{let e=n.instanceIndex;(0,n.If)(e.greaterThanEqual((0,n.atomicLoad)(a.element((0,n.uint)(Z.ENTERING_COUNT)))),()=>{(0,n.Return)()});let v=i.element(e).toVar(),y=hd(v);(0,n.If)(vd(r,y).notEqual(m),()=>{(0,n.Return)()});let b=Sd(r,y),x=(0,n.int)(b.extra).toVar(),S=(0,n.int)(l).add((0,n.int)(1)).sub(x).toVar(),C=zT(b.materialIndex,b.uv,b.N,s),w=(0,n.vec3)(0).toVar(),T=wT(c,b.position).toVar(),E=T.mul(T).toVar(),D=TT(c,T).toVar(),O=D.mul(c.mergeTrust),k=(0,n.float)(1).div((0,n.max)(O.mul(O),1e-30)).toVar(),A=(0,n.length)(b.position.sub(c.cameraPosition)).toVar(),j=sE(c,(0,n.max)(c.mergeConst.add(c.mergeSlope.mul((0,n.max)(A.sub(T),0))),c.mergeMin)).toVar(),M=(0,n.min)(sE(c,c.mergeConst.add(c.mergeSlope.mul(A.add(T)))),j.add((0,n.int)(1))).toVar();(0,n.Loop)({start:(0,n.int)(0),end:(0,n.int)(16),type:`int`,condition:`<`},({i:e})=>{let t=j.add(e.shiftRight((0,n.int)(3))).toVar();(0,n.If)(t.greaterThan(M),()=>{(0,n.Break)()});let i=cE(c,t).toVar(),a=e.bitAnd((0,n.int)(7)),s=(0,n.ivec3)((0,n.floor)(b.position.div(i).sub(.5))).add((0,n.ivec3)(a.bitAnd((0,n.int)(1)),a.shiftRight((0,n.int)(1)).bitAnd((0,n.int)(1)),a.shiftRight((0,n.int)(2)))).toVar(),l=(0,n.atomicLoad)(o.element(lE(t,s,_))).toVar(),m=(0,n.int)(0).toVar();(0,n.Loop)(l.notEqual((0,n.uint)(iE)).and(m.lessThan((0,n.int)(aE))),()=>{let e=gd(l),i=yd(r,e).toVar(),a=i.sub(b.position),o=(0,n.int)(l.mod(h)).add((0,n.int)(1)).toVar();(0,n.If)((0,n.dot)(a,a).lessThan(E).and(o.lessThanEqual(S)),()=>{let a=uE(c,i);(0,n.If)(a.shell.equal(t).and(a.cell.x.equal(s.x)).and(a.cell.y.equal(s.y)).and(a.cell.z.equal(s.z)),()=>{let t=Sd(r,e),i=(0,n.dot)(t.V,b.N).toVar(),a=(0,n.dot)(t.V,b.facetN).toVar(),s=i.greaterThan(0).and(a.greaterThan(0)),c=C.diffuseTransmission.greaterThan(0).and(i.lessThan(0)).and(a.lessThan(0));(0,n.If)(p?s.or(c):s,()=>{let e=Mm(b.V,t.V,b.N,C),r=DT(t,ng(b.V,t.V,b.N,C),k),s=p?BT(b.N,t.V,C):b.N,c=DT(b,ng(t.V,b.V,s,C),k),l=x.add(o),m=AT(g,kT.MERGE,OT(r,c),(0,n.float)(1).div((0,n.float)(l))),h=(0,n.select)(l.greaterThan((0,n.int)(1)),u,(0,n.float)(1)),_=p?(0,n.abs)(i).div((0,n.max)((0,n.abs)(a),1e-4)):i.div((0,n.max)(a,1e-4));w.addAssign(gg(b.throughput.mul(e).mul(t.throughput).mul(m.mul(_).div(D).mul(h)),(0,n.float)(l.sub((0,n.int)(1))),d,(0,n.int)(f)))})})}),l.assign(bd(r,e)),m.addAssign((0,n.int)(1))})}),(0,n.If)(Yl(w).greaterThan(0),()=>{let e=Wu(t,v).toVar();rd(t,v,(0,n.vec4)(e.xyz.add(w),e.w))})})}xu(),Vd();function mE(e){let{hitBufferRO:t,splatBuffer:r,bvhBuffer:i,triangleBuffer:a,materialBuffer:o,lightPaths:s,slotsPerPath:c,lightTag:l,strategyView:u,cameraPosition:d,cameraForward:f,cameraClipStart:p,cameraViewMatrix:m,cameraProjectionMatrix:h,pixelArea:g,renderWidth:_,renderHeight:v,globalIlluminationIntensity:y,fireflyThreshold:b,accumFrame:x,frame:S,mergeVm:C=null,diffuseTransmission:w=!0}=e;return(0,n.Fn)(()=>{let e=n.instanceIndex.toVar();(0,n.If)(e.greaterThanEqual(s.mul(c)),()=>{(0,n.Return)()});let T=e.mod(c).toVar(),E=Cd(t,gd(e.sub(T)),l);(0,n.If)(T.greaterThanEqual(E),()=>{(0,n.Return)()});let D=Sd(t,gd(e)),O={...D,vm:C?.(D.position)??null},k=d.sub(O.position).toVar(),A=(0,n.max)((0,n.dot)(k,k),1e-12).toVar(),j=k.div((0,n.sqrt)(A)).toVar(),M=(0,n.dot)(j,O.facetN).toVar(),N=(0,n.dot)(j,f).negate().toVar(),P=M.lessThan(0),F=w?(0,n.select)(P,O.extra.bitAnd((0,n.uint)(2)),O.extra.bitAnd((0,n.uint)(1))).notEqual((0,n.uint)(0)):O.extra.notEqual((0,n.uint)(0)),I=p.div((0,n.max)(N,1e-6)).toVar();(0,n.If)((w?M.equal(0):M.lessThanEqual(0)).or(N.lessThanEqual(1e-6)).or(F).or(A.lessThanEqual(I.mul(I))),()=>{(0,n.Return)()});let L=h.mul(m.mul((0,n.vec4)(O.position,1))).toVar();(0,n.If)(L.w.lessThanEqual(0),()=>{(0,n.Return)()});let ee=(0,n.floor)(L.x.div(L.w).mul(.5).add(.5).mul((0,n.float)(_))).toVar(),te=(0,n.floor)((0,n.float)(.5).sub(L.y.div(L.w).mul(.5)).mul((0,n.float)(v))).toVar();(0,n.If)(ee.lessThan(0).or(te.lessThan(0)).or(ee.greaterThanEqual((0,n.float)(_))).or(te.greaterThanEqual((0,n.float)(v))),()=>{(0,n.Return)()});let R=zT(O.materialIndex,O.uv,O.N,o);w&&(0,n.If)(P.and(R.diffuseTransmission.lessThanEqual(0)),()=>{(0,n.Return)()});let ne=w?BT(O.N,j,R):O.N,re=Mm(j,O.V,ne,R).toVar(),ie=(0,n.float)(1).div(g.mul(N).mul(N).mul(N)).div(A).toVar(),ae=CT(ie.mul(w?(0,n.abs)(M):M).div((0,n.float)(s)),O,ng(j,O.V,ne,R)),oe=T.add((0,n.uint)(1)),se=(0,n.float)(1).toVar();(0,n.If)(oe.greaterThan((0,n.uint)(1)),()=>{se.assign(y)});let ce=gg(O.throughput.mul(re).mul(VT(O.V,O.N,O.facetN,j)).mul(ie.div((0,n.float)(s)).mul(AT(u,kT.LIGHT_TRACE,OT(ae,(0,n.float)(0)))).mul(se)),(0,n.float)(T),b,(0,n.int)(x)).toVar(),le=jl(O.position,w?(0,n.select)(P,O.facetN.negate(),O.facetN):O.facetN).toVar(),z=d.sub(le).toVar(),ue=(0,n.length)(z).toVar(),de=bh(le,z.div(ue),ue.sub(I).mul(Ml),Vf,i,a,o);(0,n.If)(de.greaterThan(0),()=>{let t=(0,n.min)(Ul(ce.mul(de)),(0,n.vec3)(mT)).mul(pT).toVar(),i=(0,n.float)(Be({state:e.bitXor((0,n.uint)(S).mul((0,n.uint)(2654435769)))}).shiftRight((0,n.uint)(8))).mul(1/16777216).toVar(),a=(0,n.uint)(te).mul((0,n.uint)(_)).add((0,n.uint)(ee)).mul((0,n.uint)(3)).toVar();(0,n.atomicAdd)(r.element(a),(0,n.uint)((0,n.floor)(t.x.add(i)))),(0,n.atomicAdd)(r.element(a.add((0,n.uint)(1))),(0,n.uint)((0,n.floor)(t.y.add(i)))),(0,n.atomicAdd)(r.element(a.add((0,n.uint)(2))),(0,n.uint)((0,n.floor)(t.z.add(i))))})})}function hE(e){let{rayBufferRW:t,splatBuffer:r,renderWidth:i,chunkRowBase:a,chunkRows:o}=e;return(0,n.Fn)(()=>{let e=(0,n.int)(n.workgroupId.x).mul(16).add((0,n.int)(n.localId.x)),s=(0,n.int)(n.workgroupId.y).mul(16).add((0,n.int)(n.localId.y));(0,n.If)(e.lessThan(i).and(s.lessThan(o)),()=>{let o=(0,n.uint)(s.mul(i).add(e)),c=(0,n.uint)(s.add(a).mul(i).add(e)).mul((0,n.uint)(3)).toVar(),l=(0,n.atomicLoad)(r.element(c)).toVar(),u=(0,n.atomicLoad)(r.element(c.add((0,n.uint)(1)))).toVar(),d=(0,n.atomicLoad)(r.element(c.add((0,n.uint)(2)))).toVar();(0,n.If)(l.bitOr(u).bitOr(d).notEqual((0,n.uint)(0)),()=>{(0,n.atomicStore)(r.element(c),(0,n.uint)(0)),(0,n.atomicStore)(r.element(c.add((0,n.uint)(1))),(0,n.uint)(0)),(0,n.atomicStore)(r.element(c.add((0,n.uint)(2))),(0,n.uint)(0));let e=Wu(t,o).toVar();rd(t,o,(0,n.vec4)(e.xyz.add((0,n.vec3)((0,n.float)(l),(0,n.float)(u),(0,n.float)(d)).div(pT)),e.w))})})})}O(),Vd(),lt(),Ft();var{PASS_TAG_BIT:gE,STRATEGY:_E,STRATEGY_ALONE:vE,SOURCE:yE,mergeVmAt:bE}=uT,xE={...uT,...$w,guidedDiscPdf:ZT,recordEscape:$T},SE=256*1024*1024,CE=.05,wE=.5,TE=(1<<24)-1,EE=1,DE=.75,OE=.25,kE=class{constructor(e){this.pt=e,this.merging=!1,this._mergeRadiusPixels=EE,this._mergeHeadAttr=null,this._lightCacheSlots=0,this._splatAttr=null,this._lightTag=0,this._passTag=0,this._lightTraced=!1,this._lastLightBounceCounts=null,this._lastLightBounceEnergy=null,this._lastLightCurveKey=null,this._lightCurveKey=null,this.uniforms={lib:xE,lightPaths:(0,n.uniform)(0,`uint`),slotsPerPath:(0,n.uniform)(1,`uint`),lightTag:(0,n.uniform)(1,`uint`),passTag:(0,n.uniform)(0,`uint`),lightTrace:(0,n.uniform)(0,`uint`),strategyView:(0,n.uniform)(0,`uint`),pixelArea:(0,n.uniform)(1,`float`),cameraPosition:(0,n.uniform)(new r.Vector3,`vec3`),cameraForward:(0,n.uniform)(new r.Vector3(0,0,-1),`vec3`),sunPick:(0,n.uniform)(0,`float`),emitterPick:(0,n.uniform)(0,`float`),envPick:(0,n.uniform)(0,`float`),envTable:(0,n.uniform)(0,`uint`),sourceCdf:(0,n.uniformArray)(new Float32Array(yE.LAMPS),`float`),sourceCount:yE.LAMPS,sourceOffsets:[yE.LAMPS,yE.LAMPS,yE.LAMPS,yE.LAMPS],sceneCenter:(0,n.uniform)(new r.Vector3,`vec3`),sceneRadius:(0,n.uniform)(1,`float`),guide:(0,n.uniform)(0,`uint`),guideLearning:(0,n.uniform)(1,`uint`),guideTexture:null,merging:!1,mergeConst:(0,n.uniform)(0,`float`),mergeSlope:(0,n.uniform)(0,`float`),mergeMin:(0,n.uniform)(1,`float`),mergeTrust:(0,n.uniform)(OE,`float`),hashMask:(0,n.uniform)(0,`uint`)},this._lightGuiding=!0,this._guideTexture=null,this._guideBuildAttr=null,this._u32Views=new WeakMap}get name(){return this.merging?`vcm`:`bidirectional`}select(e){this.merging=e===`vcm`,this.uniforms.merging=this.merging,this._lastLightCurveKey=null}get hitStride(){return 7}cacheBytes(e,t){let n=Math.floor(Math.min(SE,e*.45,t*.05)/64)*64;return this._lightCacheSlots=n/64,n}get lightVertices(){return this._lightCacheSlots}beforeKernelBuild(){this._sizeSourceTable()}allocate(e){(!this._splatAttr||this._splatAttr.count<e*3)&&(Au(this.pt.renderer,this._splatAttr),this._splatAttr=v(e*3,1,Uint32Array));let t=this.merging?2**Math.ceil(Math.log2(Math.max(this._lightCacheSlots,1024))):0;this._mergeHeadAttr?.count!==t&&(Au(this.pt.renderer,this._mergeHeadAttr),this._mergeHeadAttr=t>0?v(t,1,Uint32Array):null),this.uniforms.hashMask.value=Math.max(t-1,0),this._guideTexture||(this._guideTexture=new r.DataTexture(null,UT,16,r.RedFormat,r.FloatType),this._guideTexture.source.dataReady=!1,this._guideTexture.needsUpdate=!0,this._guideBuildAttr=v(WT*16,1,Float32Array)),this.uniforms.guideTexture=(0,n.texture)(this._guideTexture),this.uniforms.guide.value=0}registerKernels(e){let{km:t,qm:r,pb:i,counters:a,bounceCountsBuf:o,wfCurrentBounce:s,copyReadB:c,copyWriteA:l,maxRays:u,w:d,own:f,freshLight:p,freshTri:m,freshBvh:h,freshMat:g,freshEnvTex:_,freshEnvCDF:v,materialLayers:y}=e,b=y?.diffuseTransmission??!0,x=this.uniforms,S=r.MAX_BOUNCE_SNAPSHOTS,C=e=>{let t=(0,n.uint)(s).clamp((0,n.uint)(0),(0,n.uint)(S-1));o.element(t.add((0,n.uint)(2*S))).assign(e),o.element(t.add((0,n.uint)(3*S))).assign((0,n.atomicLoad)(a.element((0,n.uint)(Z.ACTIVE_ENERGY)))),(0,n.atomicStore)(a.element((0,n.uint)(Z.ENTERING_COUNT)),e)};if(t.register(`lightSnapshot`,(0,n.Fn)(()=>{C((0,n.atomicLoad)(a.element((0,n.uint)(Z.ACTIVE_RAY_COUNT))))})().compute([1,1,1],[1,1,1])),t.register(`lightCopyback`,(0,n.Fn)(()=>{let e=n.instanceIndex,t=(0,n.atomicLoad)(a.element((0,n.uint)(Z.ACTIVE_RAY_COUNT)));(0,n.If)(e.equal((0,n.uint)(0)),()=>{C(t)}),(0,n.If)(e.greaterThanEqual(t),()=>{(0,n.Return)()}),l.element(e).assign(c.element(e))})().compute([Math.ceil(u/256),1,1],[256,1,1])),t.register(`guideClear`,tE({counters:a})),t.register(`guideBuild`,eE({counters:a,out:(0,n.storage)(this._guideBuildAttr,`float`)})),t.register(`lightGenerate`,f(nE({rayBufferRW:i.rayBuffer.rw,hitBufferRW:i.hitBuffer.rw,activeIndicesRW:r.activeIndices.a,counters:a,lightBuffer:p,triangleBuffer:m,bvhBuffer:h,emissiveTriangleCount:this.pt.emissiveTriangleCount,emissiveVec4Offset:this.pt.emissiveVec4Offset,emissiveTotalPower:this.pt.emissiveTotalPower,emissiveBoost:this.pt.emissiveBoost,sunDirection:this.pt.sunDirection,sunRadiance:this.pt.sunRadiance,sunParams:this.pt.sunParams,environmentIntensity:this.pt.environmentIntensity,envTexture:_,envCDFTexture:v,envMatrix:this.pt.environmentMatrix,envResolution:this.pt.envResolution,directionalLightsBuffer:this.pt.directionalLightsBufferNode,areaLightsBuffer:this.pt.areaLightsBufferNode,pointLightsBuffer:this.pt.pointLightsBufferNode,spotLightsBuffer:this.pt.spotLightsBufferNode,bidirectional:x,resolution:this.pt.resolution,frame:this.pt.seedFrame,transmissiveBounces:this.pt.transmissiveBounces})()).compute([Math.ceil(u/256),1,1],[256,1,1])),t.register(`connect`,f(rE({rayBufferRW:i.rayBuffer.rw,hitBufferRO:i.hitBuffer.ro,activeIndicesRO:r.getActiveReadRO(),counters:a,bvhBuffer:h,triangleBuffer:m,materialBuffer:g,resolution:this.pt.resolution,frame:this.pt.seedFrame,accumFrame:this.pt.frame,currentBounce:this.pt._wfCurrentBounce,chunkRowBase:this.pt._wfChunkRowBase,lightPaths:x.lightPaths,slotsPerPath:x.slotsPerPath,lightTag:x.lightTag,passTag:x.passTag,strategyView:x.strategyView,maxBounceCount:this.pt.maxBounces,globalIlluminationIntensity:this.pt.globalIlluminationIntensity,fireflyThreshold:this.pt.fireflyThreshold,mergeVm:x.merging?e=>bE(x,e):null,diffuseTransmission:b})()).compute([Math.ceil(u/256),1,1],[256,1,1])),x.merging){let e=(0,n.storage)(this._mergeHeadAttr,`uint`).toAtomic();t.register(`mergeClear`,dE({head:e,hashSize:this._mergeHeadAttr.count})),t.register(`mergeInsert`,fE({hitBufferRW:i.hitBuffer.rw,head:e,bidirectional:x})().compute([Math.ceil(this._lightCacheSlots/256),1,1],[256,1,1])),t.register(`merge`,f(pE({rayBufferRW:i.rayBuffer.rw,hitBufferRO:i.hitBuffer.ro,activeIndicesRO:r.getActiveReadRO(),counters:a,head:e,materialBuffer:g,bidirectional:x,maxBounceCount:this.pt.maxBounces,globalIlluminationIntensity:this.pt.globalIlluminationIntensity,fireflyThreshold:this.pt.fireflyThreshold,accumFrame:this.pt.frame,diffuseTransmission:b})()).compute([Math.ceil(u/256),1,1],[256,1,1]))}let w=(0,n.storage)(this._splatAttr,`uint`).toAtomic();t.register(`lightSplat`,f(mE({hitBufferRO:i.hitBuffer.ro,splatBuffer:w,bvhBuffer:h,triangleBuffer:m,materialBuffer:g,lightPaths:x.lightPaths,slotsPerPath:x.slotsPerPath,lightTag:x.lightTag,strategyView:x.strategyView,cameraPosition:x.cameraPosition,cameraForward:x.cameraForward,cameraClipStart:this.pt.cameraClipStart,cameraViewMatrix:this.pt.cameraViewMatrix,cameraProjectionMatrix:this.pt.cameraProjectionMatrix,pixelArea:x.pixelArea,renderWidth:this.pt._wfRenderWidth,renderHeight:this.pt._wfRenderHeight,globalIlluminationIntensity:this.pt.globalIlluminationIntensity,fireflyThreshold:this.pt.fireflyThreshold,accumFrame:this.pt.frame,frame:this.pt.seedFrame,mergeVm:x.merging?e=>bE(x,e):null,diffuseTransmission:b})()).compute([Math.ceil(this._lightCacheSlots/256),1,1],[256,1,1])),t.register(`splatResolve`,hE({rayBufferRW:i.rayBuffer.rw,splatBuffer:w,renderWidth:this.pt._wfRenderWidth,chunkRowBase:this.pt._wfChunkRowBase,chunkRows:this.pt._wfChunkRows})().compute([Math.ceil(d/16),Math.ceil(this.pt._chunkRows/16),1],[16,16,1]))}beginFrame(e){let t=this._updateBidirectionalUniforms();return this._lightTraced=t&&this.uniforms.lightTrace.value>0,t&&(this._updateLightGuide(),this._traceLightPaths(e)),t}beforeShade(){this.uniforms.passTag.value=this._nextPassTag()}afterShade(e){e.dispatch(`connect`),this.merging&&e.dispatch(`merge`)}resolve(e){this._lightTraced&&e.dispatch(`splatResolve`)}get curveKey(){return this._lightCurveKey}applyLightCurve(e,t,n){this._lastLightBounceCounts=e,this._lastLightBounceEnergy=t,this._lastLightCurveKey=n}describe(){return`${this.name}: ${this._lightCacheSlots.toLocaleString(`en-US`)} light vertex slots`}gpuResources(){return this._splatAttr?[this._splatAttr,this._mergeHeadAttr].filter(Boolean):null}dispose(){Au(this.pt.renderer,this._splatAttr),this._splatAttr=null,Au(this.pt.renderer,this._mergeHeadAttr),this._mergeHeadAttr=null,this._disposeLightGuide()}setBidirectionalStrategy(e=`all`,{alone:t=!1}={}){let n={all:_E.ALL,hit:_E.HIT,nee:_E.NEE,connect:_E.CONNECT,lightTrace:_E.LIGHT_TRACE,merge:_E.MERGE}[e]??_E.ALL;this.uniforms.strategyView.value=n===_E.ALL?n:n+(t?vE:0)}setMergeRadius(e=EE){this._mergeRadiusPixels=Math.max(e,.001)}setMergeTrust(e=OE){this.uniforms.mergeTrust.value=Math.max(e,1e-4)}_updateBidirectionalUniforms(){let e=this.uniforms,t=this.pt._wfRenderWidth.value,n=this.pt._wfRenderHeight.value,r=this.pt.maxBounces.value+1,i=this._updateSourceTable()>0?Math.min(Math.ceil(t*n*wE),this.pt._packedBuffers.capacity,Math.floor(this._lightCacheSlots/r)):0;if(e.lightPaths.value=i,e.slotsPerPath.value=r,this._lightCurveKey=`${i}:${r}:${this.pt._bounceLoopBound()}`,i===0)return e.lightTrace.value=0,!1;this._lightTag=this._lightTag%TE+1,e.lightTag.value=this._lightTag;let a=this.pt.cameraWorldMatrix.value.elements;e.cameraPosition.value.set(a[12],a[13],a[14]),e.cameraForward.value.set(-a[8],-a[9],-a[10]).normalize();let o=this.pt.cameraProjectionMatrix.value.elements;e.pixelArea.value=4/(o[0]*o[5]*t*n);let s=this.pt.cameraProjection.value===at.perspective&&!this.pt.enableDOF.value;return e.lightTrace.value=+!!s,this.merging&&this._updateMergeRadius(t,n),!0}_updateMergeRadius(e,t){let n=this.uniforms,r=this._mergeRadiusPixels*(this.pt.frameCount+1)**((DE-1)/2),i=this.pt.cameraProjection.value,a=this.pt.cameraProjectionMatrix.value.elements,o=0,s=0;i===at.orthographic?s=r*2/(a[5]*t):o=i===at.equirectangular?r*2*Math.PI/e:r*Math.sqrt(n.pixelArea.value),n.mergeSlope.value=Math.min(o,.1),n.mergeConst.value=s,n.mergeMin.value=Math.max(s,o*.001*n.sceneRadius.value,1e-9)}_sizeSourceTable(){let e=this.uniforms,t=yE.LAMPS;[`directional`,`area`,`point`,`spot`].forEach((n,r)=>{e.sourceOffsets[r]=t,t+=this.pt[`${n}LightsBufferNode`].array.length/dt[n]}),e.sourceCount=t,e.sourceCdf.array.length!==t&&(e.sourceCdf.array=new Float32Array(t))}_updateSourceTable(){let e=this.uniforms,t=e.sourceCdf.array,n=new Float64Array(t.length),r=(e,t)=>Math.max(.2126*e[t]+.7152*e[t+1]+.0722*e[t+2],0),i=e=>({a:this.pt[`${e}LightsBufferNode`].array,n:this.pt[`num${e[0].toUpperCase()}${e.slice(1)}Lights`].value,f:dt[e]}),a=i(`directional`),o=this.pt.enableEnvironment.value>0,s=this.pt.environment.exactTable;e.envTable.value=+!!s;let c=o&&(this.pt.hasSun.value>0||s)||a.n>0,l=c||this.merging?this._sceneDisc():0,u=c?l*CE:0;if(o&&s&&(n[yE.ENVIRONMENT]=Math.max(s.radianceIntegral,0)*this.pt.environmentIntensity.value*u),this.pt.emissiveTriangleCount.value>0&&(n[yE.EMITTERS]=Math.PI*this.pt.emissiveBoost.value*this.pt.emissiveTotalPower.value),o&&this.pt.hasSun.value>0){let{x:e,y:t,z:r}=this.pt.sunRadiance.value;n[yE.SUN]=Math.max(.2126*e+.7152*t+.0722*r,0)*this.pt.environmentIntensity.value*this.pt.sunParams.value.y*u}for(let t=0;t<a.n;t++)n[e.sourceOffsets[0]+t]=r(a.a,t*a.f+3)*a.a[t*a.f+6]*u;let d=i(`area`);for(let t=0;t<d.n;t++){let i=d.a,a=t*d.f,o=i[a+4]*i[a+8]-i[a+5]*i[a+7],s=i[a+5]*i[a+6]-i[a+3]*i[a+8],c=i[a+3]*i[a+7]-i[a+4]*i[a+6],l=4*Math.hypot(o,s,c)*(i[a+15]>.5?Math.PI/4:1);n[e.sourceOffsets[1]+t]=l>0?r(i,a+9)*Math.max(i[a+12],0)*(i[a+13]>.5?1:l):0}let f=i(`point`);for(let t=0;t<f.n;t++)n[e.sourceOffsets[2]+t]=4*Math.PI*r(f.a,t*f.f+3)*Math.max(f.a[t*f.f+6],0);let p=i(`spot`);for(let t=0;t<p.n;t++){let i=t*p.f;n[e.sourceOffsets[3]+t]=2*Math.PI*(1-Math.cos(p.a[i+10]))*r(p.a,i+6)*Math.max(p.a[i+9],0)}let m=0;for(let e=0;e<n.length;e++)m+=Number.isFinite(n[e])?n[e]:0;let h=0;for(let e=0;e<n.length;e++)h+=Number.isFinite(n[e])?n[e]:0,t[e]=m>0?h/m:0;m>0&&(t[t.length-1]=1);let g=e=>Math.fround(t[e]-(e>0?t[e-1]:0));return e.sunPick.value=g(yE.SUN),e.emitterPick.value=g(yE.EMITTERS),e.envPick.value=g(yE.ENVIRONMENT),m}_sceneDisc(){let e=this.uniforms,t=this._visibleSceneBounds();if(!t)return 0;let[n,r,i]=t.min,[a,o,s]=t.max,c=.5*Math.hypot(a-n,o-r,s-i);return c>0&&Number.isFinite(c)?(e.sceneCenter.value.set((n+a)/2,(r+o)/2,(i+s)/2),e.sceneRadius.value=c,Math.PI*c*c):0}_visibleSceneBounds(){let e=this.pt._bvhRecords,t=e?null:this.pt.bvhStorageAttr?.array;if(!e&&!(t?.length>=16))return null;let n=this.pt._instanceTable?.blasBase??1;if(e&&!e.isResident(0,n))return this.pt._whenTLASResident(()=>{}),null;let r=e=>{let t=this._u32Views.get(e);return t||this._u32Views.set(e,t=new Uint32Array(e.buffer,e.byteOffset,e.length)),t},i=n=>{let i=e?e.chunkFor(n):t;return{f:i,u:r(i),o:e?e.baseOf(n):n*16}},a=e=>{if(e.u[e.o+3]!==Tt.CLUSTER_LEAF)return e.f[e.o+2]!==0;let t=(e.u[e.o]>>>28&3)+1;for(let n=0;n<t;n++)if(!(e.u[e.o+12+n]&2147483648))return!0;return!1},o=i(0);if(o.u[o.o+3]>=1073741824)return null;let s=e?e.recordCount:t.length/16,c=[],l=[];for(let e=0;e<3;e++)for(let t of[1,-1]){let n=(n,r)=>t>0?n.f[n.o+r*8+4+e]:-n.f[n.o+r*8+e],r=(e,t)=>e.u[e.o+3+t*4],u=-1/0,d=[],f=e=>{let t=n(e,0),i=n(e,1),a=t<=i?0:1;d.push(r(e,a),a===0?t:i,r(e,1-a),a===0?i:t)};f(o);let p=0;for(;d.length;){let e=d.pop(),t=d.pop();if(e<=u)continue;if(t>=s||++p>s)return null;let n=i(t);n.u[n.o+3]>=1073741824?a(n)&&(u=e):f(n)}if(u===-1/0)return null;(t>0?l:c)[e]=t>0?u:-u}return{min:c,max:l}}setLightGuiding(e){this._lightGuiding=e!==!1,this.uniforms.guide.value=0,this.pt.reset()}_updateLightGuide(){let e=this.uniforms,t=this.pt._kernelManager;e.guideLearning.value=+!!this._lightGuiding;let n=this.pt.frameCount;if(n===0){t.dispatch(`guideClear`),e.guide.value=0;return}if(!this._lightGuiding||!(n<=32?!(n&n-1):n%32==0))return;t.dispatch(`guideBuild`);let r=this.pt.renderer.backend;this.pt.renderer.initTexture(this._guideTexture);let i=r.device.createCommandEncoder({label:`LightGuide`});i.copyBufferToTexture({buffer:r.get(this._guideBuildAttr).buffer,bytesPerRow:WT*4,rowsPerImage:16},{texture:r.get(this._guideTexture).texture},[UT,16]),r.device.queue.submit([i.finish()]),e.guide.value=1}_disposeLightGuide(){Au(this.pt.renderer,this._guideBuildAttr),this._guideTexture?.dispose(),this._guideTexture=this._guideBuildAttr=null,this.uniforms.guideTexture=null}_nextPassTag(){return this._passTag=this._passTag+1&2147483647,(gE|this._passTag)>>>0}_traceLightPaths(e){let t=this.pt._kernelManager,n=this.uniforms.lightPaths.value;this.pt._wfChunkRowBase.value=0,this.pt._wfMaxRayCount.value=n,t.setDispatchForCount(`lightGenerate`,n),t.dispatch(`lightGenerate`);let r=this.pt._useDynamicDispatch,i=this._lastLightCurveKey===this._lightCurveKey,a=i?this._lastLightBounceCounts:null,o=i?this._lastLightBounceEnergy:null,s=this.pt._bounceEarlyExitThreshold>=0?this.pt._bounceEarlyExitThreshold*n*64:-1;for(let i=0;i<=e;i++){this.pt._wfCurrentBounce.value=i;let c=i>0?a?.[i-1]:void 0,l=r&&c>0?Math.min(n,Math.ceil(c*1.5)+1024):n;for(let e of M_)t.setDispatchForCount(e,l);if(r||t.dispatch(`enterFull`),t.dispatch(`extend`),this.pt._sortMaterials&&(t.dispatch(`resetGlobalHist`),t.dispatch(`globalHist`),t.dispatch(`globalPrefix`),t.dispatch(`globalScatter`)),t.dispatch(`shade`),t.dispatch(`compact`),t.dispatch(r?`lightCopyback`:`lightSnapshot`),s>=0&&i<e&&o?.[i]!==void 0&&o[i]<=s)break}this.uniforms.lightTrace.value>0&&(t.setDispatchForCount(`lightSplat`,n*this.uniforms.slotsPerPath.value),t.dispatch(`lightSplat`)),this.merging&&(t.dispatch(`mergeClear`),t.setDispatchForCount(`mergeInsert`,n*this.uniforms.slotsPerPath.value),t.dispatch(`mergeInsert`))}};function AE(e){let t=String(e??``);return/(hdr|pq|hlg|2100|st2084)/i.test(t)?null:/^display\s*p3\b/i.test(t)?`display-p3`:/^(srgb|rec\.?\s*1886|bt\.?\s*1886|gamma\s*2\.2\s*rec\.?\s*709)\b(?!.*(p3|2020))/i.test(t)?`srgb`:null}ui(),Ae();var jE=ve(`ocio`);function ME(e){let t=String(e);/\[OpenColorIO Error\]/.test(t)?jE.error(t):/\[OpenColorIO Warning\]/.test(t)?jE.warn(t):jE.debug(t)}var NE=null,PE=null,FE=null,IE=null,LE=null;async function RE(){let{ocioRuntimeFactory:e,ocioRuntimeUrl:t}=si();if(typeof e==`function`)return await e();if(typeof t==`string`&&t)return await import(t);throw Error(`OpenColorIO runtime not configured. Call configureAssets({ ocioRuntimeFactory: () => import('@bb-studio/ocio') }) before loading a config.`)}async function zE(){return PE||(NE||=(async()=>{let e=await RE();if(typeof e.createOcioRuntime!=`function`)throw Error(`OCIO module has no createOcioRuntime() — wrong package or version`);let{ocioWasmUrl:t}=si();return PE=await e.createOcioRuntime({...t?{wasmUrl:t}:{},moduleOptions:{print:ME,printErr:ME}}),PE})().catch(e=>{throw NE=null,e}),await NE)}async function BE(){return(await zE()).ocio.listBuiltinConfigs()}async function VE({builtin:e,text:t,files:n=[],configPath:r=`config.ocio`,id:i}={}){let a=await zE();if(e)FE=a.loadBuiltinConfig(e),IE=e,LE=qE(a,e);else{let e=n.map(e=>({relativePath:e.relativePath??e.path??e.name,data:e.data instanceof Uint8Array?e.data:new Uint8Array(e.data)}));if(t!==void 0&&e.unshift({relativePath:r,data:new TextEncoder().encode(t)}),!e.some(e=>e.relativePath===r))throw Error(`config package has no "${r}" — pass configPath to name the .ocio file`);FE=a.loadConfigPackage({configRelativePath:r,files:e},i?{id:i}:void 0),IE=i??FE.id;let o=e.find(e=>e.relativePath===r);LE=o?new TextDecoder().decode(o.data):null}return KE()}function HE(){FE=null,IE=null,LE=null}function UE(){return FE!==null}function WE(){return FE?PE:null}function GE(){return FE}function KE(){if(!FE)return null;let e=Object.fromEntries(FE.roles.map(e=>[e.name,e.colorSpace]));return{id:IE,name:LE?.match(/^name:\s*(\S.*?)\s*$/m)?.[1]??null,ocioVersion:FE.ocioVersion,version:FE.version,roles:e,sceneLinear:e.scene_linear??null,colorPicking:e.color_picking??e.texture_paint??null,texturePaint:e.texture_paint??e.color_picking??null,data:e.data??null,compositingLog:e.compositing_log??e.color_timing??null,colorSpaces:FE.colorSpaces.map(e=>({name:e.name,family:e.family,categories:e.categories??[],encoding:e.encoding,isData:e.isData,aliases:e.aliases,description:e.description})),displays:FE.displays.slice(),defaultDisplay:FE.defaultDisplay,views:Object.fromEntries(Object.entries(FE.viewsByDisplay).map(([e,t])=>[e,t.map(e=>({name:e.name,transform:e.transform,colorSpace:e.colorSpace,looks:e.looks,description:e.description}))])),defaultViews:{...FE.defaultViewsByDisplay},looks:FE.looks.map(e=>({name:e.name,processSpace:e.processSpace,description:e.description,forward:e.hasForwardTransform,inverse:e.hasInverseTransform})),namedTransforms:FE.namedTransforms.map(e=>e.name),fileRules:FE.fileRules.map(e=>({index:e.index,name:e.name,colorSpace:e.colorSpace,pattern:e.pattern,extension:e.extension,regex:e.regex})),contextVariables:JE()}}function qE(e,t){try{return e.ocio.getBuiltinConfigYaml(t)}catch{return null}}function JE(){if(!LE)return[];let e=new Map,t=LE.split(/\r?\n/),n=t.findIndex(e=>/^environment:\s*(\{\s*\})?\s*$/.test(e));if(n>=0&&!/\{\s*\}/.test(t[n]))for(let r=n+1;r<t.length;r++){let n=t[r];if(/^\S/.test(n))break;let i=n.match(/^\s+([A-Za-z_][A-Za-z0-9_]*)\s*:\s*(.*?)\s*$/);i&&e.set(i[1],{name:i[1],default:i[2].replace(/^["']|["']$/g,``)||null,declared:!0})}for(let t of LE.matchAll(/\$\{?([A-Za-z_][A-Za-z0-9_]*)\}?/g))e.has(t[1])||e.set(t[1],{name:t[1],default:null,declared:!1});return[...e.values()].sort((e,t)=>e.name.localeCompare(t.name))}function YE(){HE(),PE?.dispose?.(),PE=null,NE=null}var XE=1<<20,ZE=new Map,QE=new Map,$E=4096,eD=new Map;function tD(e,t,n){return`${e}\u0000${t}\u0000${n?JSON.stringify(n):``}`}function nD(){for(let e of ZE.values())e.dispose?.();ZE.clear(),QE.clear(),eD.clear()}function rD(e,t,{context:n=null}={}){if(!WE()||e===t)return null;let r=tD(e,t,n),i=ZE.get(r);if(i!==void 0)return i;try{i=sD().createColorSpaceProcessor(e,t,n?{context:n}:void 0),i.isNoOp&&(i.dispose(),i=null)}catch(n){throw Error(`no OCIO transform from "${e}" to "${t}": ${n.message}`)}return ZE.set(r,i),i}var iD=null,aD=null,oD=!1;function sD(){let e=WE();if(!e)throw Error(`no OCIO config loaded`);if(e.config)return e.config;let t=GE();if(iD&&aD===t.id)return iD;if(oD&&iD?.dispose?.(),!t.id?.startsWith(`ocio://`))throw Error(`OCIO runtime exposes no Config handle for this config`);return iD=e.ocio.createBuiltinConfig(t.id),oD=!0,aD=t.id,iD}function cD(){oD&&iD?.dispose?.(),iD=null,aD=null,oD=!1,nD()}function lD(e,t,n,{context:r=null}={}){let i=WE();if(!i||t===n)return[e[0],e[1],e[2]];let a=`${tD(t,n,r)}\u0000${e[0]},${e[1]},${e[2]}`,o=QE.get(a);if(o)return o.slice();let s=i.transformRgb(t,n,[e[0],e[1],e[2]],r?{context:r}:void 0);return QE.size>=$E&&QE.clear(),QE.set(a,s),s.slice()}function uD(e,t,n,{context:r=null}={}){if(e.length%4!=0)throw Error(`convertPixelsF32 wants 4 floats per pixel`);let i=rD(t,n,{context:r});if(!i)return e;let a=e.length/4;if(a<=XE)return i.applyRGBAF32(e),e;for(let t=0;t<a;t+=XE){let n=Math.min(XE,a-t);i.applyRGBAF32(e.subarray(t*4,(t+n)*4))}return e}var dD=.055;function fD(e){return e<=.04045?e/12.92:((e+dD)/(1+dD))**2.4}function pD(e){return e<=0?0:e<=.0031308?12.92*e:(1+dD)*e**(1/2.4)-dD}var mD=new Float32Array(256);for(let e=0;e<256;e++)mD[e]=fD(e/255);var hD=new Float32Array(256);for(let e=0;e<256;e++)hD[e]=e/255;function gD(e){return e===`srgb`?mD:hD}function _D(e,t,n,{context:r=null,inputEncoding:i=`raw`,outputEncoding:a=`srgb`}={}){if(e.length%4!=0)throw Error(`convertEncodedRGBA8 wants 4 bytes per pixel`);let o=rD(t,n,{context:r});if(!o)return e;let s=e.length/4,c=gD(i),l=a===`srgb`?bD:xD,u=new Float32Array(Math.min(XE,s)*4);for(let t=0;t<s;t+=XE){let n=Math.min(XE,s-t),r=n*4===u.length?u:u.subarray(0,n*4);for(let i=0;i<n;i++){let n=(t+i)*4,a=i*4;r[a]=c[e[n]],r[a+1]=c[e[n+1]],r[a+2]=c[e[n+2]],r[a+3]=1}o.applyRGBAF32(r);for(let i=0;i<n;i++){let n=(t+i)*4,a=i*4;e[n]=l(r[a]),e[n+1]=l(r[a+1]),e[n+2]=l(r[a+2])}}return e}var vD=65536,yD=new Uint8Array(vD+1);for(let e=0;e<=vD;e++){let t=e/vD;yD[e]=Math.round(pD(t*t)*255)}function bD(e){return e>0?e>=1?255:yD[Math.sqrt(e)*vD+.5|0]:0}function xD(e){return e>0?e>=1?255:e*255+.5|0:0}function SD(e,t,n=`srgb`){if(!t)return e;let r=gD(n),i=n===`srgb`?bD:xD,[a,o,s,c,l,u,d,f,p]=t;for(let t=0;t<e.length;t+=4){let n=r[e[t]],m=r[e[t+1]],h=r[e[t+2]];e[t]=i(a*n+o*m+s*h),e[t+1]=i(c*n+l*m+u*h),e[t+2]=i(d*n+f*m+p*h)}return e}function CD(e,t,{context:n=null,tolerance:r=1e-4}={}){if(!WE())return null;if(e===t)return[1,0,0,0,1,0,0,0,1];let i=tD(e,t,n);if(eD.has(i))return eD.get(i);let a=rD(e,t,{context:n});if(!a)return eD.set(i,[1,0,0,0,1,0,0,0,1]),eD.get(i);let o=e=>{let t=new Float32Array([e[0],e[1],e[2],1]);return a.applyRGBAF32(t),[t[0],t[1],t[2]]},s=[o([1,0,0]),o([0,1,0]),o([0,0,1])],c=[s[0][0],s[1][0],s[2][0],s[0][1],s[1][1],s[2][1],s[0][2],s[1][2],s[2][2]],l=e=>[c[0]*e[0]+c[1]*e[1]+c[2]*e[2],c[3]*e[0]+c[4]*e[1]+c[5]*e[2],c[6]*e[0]+c[7]*e[1]+c[8]*e[2]],u=[[.18,.18,.18],[.5,.25,.75],[2,.1,.4],[.02,.9,.3],[8,4,1],[.001,.002,.004]],d=!0;for(let e of u){let t=o(e),n=l(e),i=Math.max(.001,Math.abs(n[0]),Math.abs(n[1]),Math.abs(n[2]));for(let e=0;e<3;e++)Math.abs(t[e]-n[e])>r*i&&(d=!1);if(!d)break}let f=d?c:null;return eD.set(i,f),f}function wD(e){let t=GE();if(!t)return!1;let n=t.colorSpaces.find(t=>t.name===e||t.aliases?.includes(e));return n?n.isData:!1}function TD(e){let t=GE();return!t||!e?!1:t.colorSpaces.some(t=>t.name===e||t.aliases?.includes(e))}var ED=1e-10;function DD(e,t,n,r){return e<=0?0:2**(n+e/(t-1)*(r-n))}function OD(e,t,n,r){let i=(Math.log2(Math.max(e,ED))-n)/(r-n);return Math.min(Math.max(i,0),1)*(t-1)}function kD({size:e,minEv:t,maxEv:n,apply:r}){let i=e*e*e,a=new Float32Array(i*4),o=new Float64Array(e);for(let r=0;r<e;r++)o[r]=DD(r,e,t,n);let s=0;for(let t=0;t<e;t++)for(let n=0;n<e;n++)for(let r=0;r<e;r++)a[s++]=o[r],a[s++]=o[n],a[s++]=o[t],a[s++]=1;return r(a),a}function AD(e){let t=new Uint16Array(e.length),n=new Float32Array(1),r=new Uint32Array(n.buffer);for(let i=0;i<e.length;i++){n[0]=e[i];let a=r[0],o=a>>>16&32768,s=a>>>23&255,c=a&8388607;if(s===255)t[i]=o|31744|(c?512:0);else if(s>142)t[i]=o|31743;else if(s<113){let e=13+(113-s);c|=8388608,t[i]=e>=32?o:o|c>>>e}else{let e=o|s-112<<10|c>>>13,n=c&8191;(n>4096||n===4096&&e&1)&&e++,t[i]=(e&32767)>=31744?o|31743:e}}return t}function jD(e,t=new Float32Array(e.length)){for(let n=0;n<e.length;n++){let r=e[n],i=r&32768?-1:1,a=(r&31744)>>10,o=r&1023;a===0?t[n]=i*2**-14*(o/1024):a===31?t[n]=o?NaN:i*(1/0):t[n]=i*2**(a-15)*(1+o/1024)}return t}var MD=null;function ND(){if(!MD){let e=new Uint16Array(65536);for(let t=0;t<65536;t++)e[t]=t;MD=jD(e)}return MD}function PD(e,t,n){return e>t?t>n?{w:[e,t,n],c:[[1,0,0],[1,1,0],[1,1,1]]}:e>n?{w:[e,n,t],c:[[1,0,0],[1,0,1],[1,1,1]]}:{w:[n,e,t],c:[[0,0,1],[1,0,1],[1,1,1]]}:n>t?{w:[n,t,e],c:[[0,0,1],[0,1,1],[1,1,1]]}:n>e?{w:[t,n,e],c:[[0,1,0],[0,1,1],[1,1,1]]}:{w:[t,e,n],c:[[0,1,0],[1,1,0],[1,1,1]]}}function FD({data:e,size:t,minEv:n,maxEv:r}){let i=t*t,a=t-1,o=e instanceof Uint16Array,s=o?ND():null,c=o?(n,r,a,o)=>s[e[(n+r*t+a*i)*4+o]]:(n,r,a,o)=>e[(n+r*t+a*i)*4+o];return function(e,i,o,s){let l=OD(e,t,n,r),u=OD(i,t,n,r),d=OD(o,t,n,r),f=Math.min(Math.floor(l),a-1),p=Math.min(Math.floor(u),a-1),m=Math.min(Math.floor(d),a-1),{w:h,c:g}=PD(Math.min(Math.max(l-f,0),1),Math.min(Math.max(u-p,0),1),Math.min(Math.max(d-m,0),1));for(let e=0;e<3;e++){let t=c(f,p,m,e),n=t,r=t;for(let t=0;t<3;t++){let i=c(f+g[t][0],p+g[t][1],m+g[t][2],e);n+=(i-r)*h[t],r=i}s[e]=n}}}function ID({fnName:e,texName:t,size:n,minEv:r,maxEv:i}){let a=e=>Number.isInteger(e)?`${e}.0`:String(e);return`
|
|
1375
|
+
`,uw=class e{constructor(e,t){this.chain=e,this.canvas=t,this.slot=0,this.source=null,this.staging=null,this._readbackPipeline=null,this._readbackStorage=null,this._readbackMap=null,this._hdrPipeline=null,this._hdrStorage=null,this._hdrMap=null,this._toneMapper=null,this.disposed=!1}get device(){return this.chain.device}get width(){return this.chain.pipeline.geometry.validWidth}get height(){return this.chain.pipeline.geometry.validHeight}static async create({width:t,height:n,canvas:r=null,settings:i={},onProgress:a=()=>{}}){if(!Number.isInteger(t)||!Number.isInteger(n)||t<1||n<1)throw Error(`NeuralRetouch.create: width and height must be positive integers`);if(t*n>4194304)throw Error(`NeuralRetouch.create: ${t}x${n} is ${(t*n/1e6).toFixed(1)} MP, above the ${(aw/1e6).toFixed(1)} MP this pass survives. Past it the run takes minutes and then loses every GPU device in the page.`);let o=r??document.createElement(`canvas`);r||(o.style.cssText=`position:fixed;left:-10000px;top:0;pointer-events:none`);let s=new e(await(await tw()).create(o,t,n,a,ew(i).runtime),o);return s._allocate(),s}_allocate(){let{validWidth:e,validHeight:t}=this.chain.pipeline.geometry;this.source=this.device.createBuffer({label:`rayzee:retouch-source`,size:e*t*8,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST}),this.staging=new Uint16Array(e*t*4);let n=e*t*4;this._readbackStorage=this.device.createBuffer({label:`rayzee:retouch-readback`,size:n,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC}),this._readbackMap=this.device.createBuffer({label:`rayzee:retouch-readback-map`,size:n,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),this._readbackPipeline=this.device.createComputePipeline({label:`rayzee:retouch-readback`,layout:`auto`,compute:{module:this.device.createShaderModule({code:cw}),entryPoint:`main`}});let r=e*t*8;this._hdrStorage=this.device.createBuffer({label:`rayzee:retouch-hdr`,size:r,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC}),this._hdrMap=this.device.createBuffer({label:`rayzee:retouch-hdr-map`,size:r,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),this._hdrPipeline=this.device.createComputePipeline({label:`rayzee:retouch-hdr`,layout:`auto`,compute:{module:this.device.createShaderModule({code:lw}),entryPoint:`main`}})}async _packHDR(e,t,n=!1){let r=this.chain.pipeline.slots[this.slot]?.hdrOutput;if(!r)throw Error("NeuralRetouch: the runtime has no scene-referred output. Either no frame has been produced yet, or neural-runtime.js was re-vendored without its `rayzee-patch` edits.");let i=this.device.createBindGroup({layout:this._hdrPipeline.getBindGroupLayout(0),entries:[{binding:0,resource:r.createView()},{binding:1,resource:{buffer:this._hdrStorage}}]}),a=this.device.createCommandEncoder({label:`rayzee:retouch-hdr`}),o=a.beginComputePass();o.setPipeline(this._hdrPipeline),o.setBindGroup(0,i),o.dispatchWorkgroups(Math.ceil(e/8),Math.ceil(t/8)),o.end(),n&&a.copyBufferToBuffer(this._hdrStorage,0,this._hdrMap,0,e*t*8),this.device.queue.submit([a.finish()])}async readOutputHDR(){let{validWidth:e,validHeight:t}=this.chain.pipeline.geometry;await this._packHDR(e,t,!0),await this._hdrMap.mapAsync(GPUMapMode.READ);let n=new Uint16Array(this._hdrMap.getMappedRange().slice(0));return this._hdrMap.unmap(),{half:n,width:e,height:t}}async readOutputToned(e){let{validWidth:t,validHeight:n}=this.chain.pipeline.geometry;return await this._packHDR(t,n),this._toneMapper??=new Bv(this.device,`rayzee:retouch-tonemap`),this._toneMapper.ensureSize(t,n),{rgba8:await this._toneMapper.toRGBA8(this._hdrStorage,{exposure:e.exposure??1,toneMapping:e.toneMapping??0,saturation:e.saturation??1,gain:e.gain}),width:t,height:n}}async readOutput(){let{validWidth:e,validHeight:t}=this.chain.pipeline.geometry,n=this.chain.pipeline.slots[this.slot]?.output;if(!n)throw Error(`NeuralRetouch.readOutput: the pass has not produced a frame yet`);let r=this.device.createBindGroup({layout:this._readbackPipeline.getBindGroupLayout(0),entries:[{binding:0,resource:n.createView()},{binding:1,resource:{buffer:this._readbackStorage}}]}),i=this.device.createCommandEncoder({label:`rayzee:retouch-readback`}),a=i.beginComputePass();a.setPipeline(this._readbackPipeline),a.setBindGroup(0,r),a.dispatchWorkgroups(Math.ceil(e/8),Math.ceil(t/8)),a.end(),i.copyBufferToBuffer(this._readbackStorage,0,this._readbackMap,0,e*t*4),this.device.queue.submit([i.finish()]),await this._readbackMap.mapAsync(GPUMapMode.READ);let o=new Uint8ClampedArray(this._readbackMap.getMappedRange().slice(0));return this._readbackMap.unmap(),o}dispose(){if(!this.disposed){this.disposed=!0,this.source?.destroy(),this._readbackStorage?.destroy(),this._readbackMap?.destroy(),this._hdrStorage?.destroy(),this._hdrMap?.destroy(),this._toneMapper?.dispose();try{this.chain.destroy()}catch(e){iw.warn(`retouch teardown:`,e)}}}},dw=20}));F(),an(),Ae(),lt();var pw=ve(`neural`),mw=120,hw=2,gw=1,_w=0,vw=300,yw=5,bw=3,xw=3,Sw=16,Cw=e=>Math.max(0,1-e/Sw),ww=class extends r.EventDispatcher{constructor({renderer:e,mainCanvas:t,stages:n,pipeline:i,getExposure:a,getSaturation:o,getDisplayGain:s=null,getPictureCanvas:c=null,getColorSpace:l=null,issues:u=null}){super(),this.renderer=e,this._issues=u,this._getPictureCanvas=c,this._getColorSpace=l,this.mainCanvas=t,this.upscalerCanvas=this._createUpscalerCanvas(t),this.pipeline=i,this._stages=n,this._getExposure=a,this._getSaturation=o,this._getDisplayGain=s,this.denoiser=null,this.upscaler=null,this.upscalerBackend=`esrgan`,this._neuralUpscaler=null,this.neuralRendering=!1,this.neuralRenderingSettings={},this._retouch=null,this._superResModule=null,this._neuralPostBusy=!1,this._postIsStillComplete=null,this._postRun=null,this._postRedo=null,this._postCancelled=!1,this._finalQuality=sb.oidnQuality,this.finalDenoise=sb.enableOIDN,this.continuousDenoise=sb.continuousDenoise,this.continuousDenoiseInterval=sb.continuousDenoiseInterval,this._lastCadenceAt=-1/0,this._lastCadenceSamples=0,this._failedRefreshes=0,this._cadenceSuspended=!1,this._movingDenoiseMs=[],this._movingHopeless=!1,this._holdWhileMoving=null,this._onReset=null,this._onPostProcessRefresh=null,this._onDisplayRefresh=null,this.temporalHistory=sb.oidnTemporalHistory,this._history=null,this._historyDirty=!0,this._knownResetCount=0,this._seenTracedFrames=0,this._viewProj=new r.Matrix4,this._historyCamera={world:null,projInv:null,viewProj:null,orthographic:!1},this._movedPlacements=new Map,this._movedUpload={count:0,leaves:new Uint32Array,toPrev:new Float32Array},this._matA=new r.Matrix4,this._matB=new r.Matrix4,this._lastRenderWidth=0,this._lastRenderHeight=0,this._pendingStartUpscaler=null,this._pendingCloseDenoise=null,this._denoiserStartHandler=null,this._denoiserEndHandler=null,this._denoiserTileHandler=null,this._denoiserErrorHandler=null,this._denoiserLoadHandler=null,this._upscalerResChangedHandler=null,this._upscalerStartHandler=null,this._upscalerProgressHandler=null,this._upscalerEndHandler=null}_createUpscalerCanvas(e){let t=e.parentNode;if(!t)return null;let n=document.createElement(`canvas`);return n.width=e.width,n.height=e.height,n.style.position=`absolute`,n.style.inset=`0`,n.style.width=`100%`,n.style.height=`100%`,n.style.display=`none`,t.insertBefore(n,e),n}gpuBytes(){return(this.denoiser?.gpuBytes?.()??0)+(this._history?.gpuBytes?.()??0)}_recordNoOverlayCanvas(e){this._issues?.record(X.DENOISER_UNAVAILABLE,`the ${e} pass needs the render canvas to be in a document, and it is not — skipped`,{pass:e})}setRenderSize(e,t){this._lastRenderWidth=e,this._lastRenderHeight=t,this._cadenceDowngraded=!1,this._holdWhileMoving=null,this._movingDenoiseMs.length=0,this._movingHopeless=!1,this._historyDirty=!0,this.denoiser?.abort(),this._unpublishOutput(),this.denoiser?.setSize(e,t),this.upscalerCanvas&&(this.upscalerCanvas.width!==e||this.upscalerCanvas.height!==t)&&(this.upscalerCanvas.width=e,this.upscalerCanvas.height=t),this.upscaler?.setBaseSize(e,t),this._syncGBufferStages()}restoreBaseResolution(){return!this.upscalerCanvas||!this._lastRenderWidth||!this._lastRenderHeight||!(this.upscalerCanvas.width!==this._lastRenderWidth||this.upscalerCanvas.height!==this._lastRenderHeight)?!1:(this.upscalerCanvas.width=this._lastRenderWidth,this.upscalerCanvas.height=this._lastRenderHeight,!0)}setupDenoiser(){let e=this._stages.pathTracer;this.denoiser=new fC(this.renderer,{enableOIDN:sb.enableOIDN,oidnQuality:sb.oidnQuality,backendParams:()=>({device:this.renderer.backend.device,adapterInfo:null}),getGPUTextures:({continuous:t=!1}={})=>{if(!e?.storageTextures?.readTarget)return null;let n=t?this._historyTextures():null;if(n)return n;let r=e.storageTextures.getReadTextures(),{backend:i}=this.renderer;return{color:i.get(r.color).texture,normal:i.get(r.normalDepth).texture,albedo:i.get(r.albedo).texture}}}),this._syncOIDNInUse(),this._denoiserStartHandler=e=>this.dispatchEvent({type:N.DENOISING_START,continuous:!!e.continuous}),this._denoiserEndHandler=e=>{let t=!e.continuous||this.continuousDenoise&&!this._cadenceSuspended;this.denoiser?.hasOutput&&t&&this._publishOutput(),this.dispatchEvent({type:N.DENOISING_END,continuous:!!e.continuous})},this._denoiserTileHandler=e=>{if(e.continuous)return;this._publishOutput();let t=this.pipeline?.context;this._stages.compositor&&t&&this._stages.compositor.render(t)},this._denoiserErrorHandler=e=>e.url&&this._issues?.record(X.ASSET_UNREACHABLE,`denoiser weights "${e.url}" could not be loaded — the render is not denoised`,{url:e.url,asset:`oidn-weights`,cause:String(e.error?.message??e.error)}),this.denoiser.addEventListener(`start`,this._denoiserStartHandler),this.denoiser.addEventListener(`end`,this._denoiserEndHandler),this.denoiser.addEventListener(`tileProgress`,this._denoiserTileHandler),this.denoiser.addEventListener(`error`,this._denoiserErrorHandler),this._denoiserLoadHandler=e=>this.dispatchEvent({type:N.DENOISER_LOADING,loading:e.type===`loading`});for(let e of[`loading`,`loaded`,`error`])this.denoiser.addEventListener(e,this._denoiserLoadHandler);this.denoiser.state?.isLoading&&this.dispatchEvent({type:N.DENOISER_LOADING,loading:!0})}setupUpscaler(){if(!this.upscalerCanvas)return;let e=this._stages.pathTracer;this.upscaler=new FC(this.upscalerCanvas,this.renderer,{scaleFactor:sb.upscalerScale||2,quality:sb.upscalerQuality||`fast`,getSourceCanvas:()=>this._getPictureCanvas?.()??this.renderer.domElement,refreshInput:()=>{let e=this.pipeline?.context;this._stages.compositor&&e&&this._stages.compositor.render(e)},getGPUTextures:()=>{if(!e?.storageTextures?.readTarget)return null;let t=e.storageTextures.getReadTextures();return{color:this.renderer.backend.get(t.color).texture}},getExposure:()=>this._getEffectiveExposure(),getToneMapping:()=>this._getToneMapping(),getColorSpace:()=>this._colorSpace(),getSaturation:()=>this._getSaturation(),getDisplayGain:()=>this._getDisplayGain?.()??null,getTransparentBackground:()=>!!this._settings?.get(`transparentBackground`)}),this.upscaler.enabled=sb.enableUpscaler||!1,this._upscalerResChangedHandler=e=>this.dispatchEvent({type:N.RESOLUTION_CHANGED,width:e.width,height:e.height}),this._upscalerStartHandler=()=>this.dispatchEvent({type:N.UPSCALING_START}),this._upscalerProgressHandler=e=>this.dispatchEvent({type:N.UPSCALING_PROGRESS,progress:e.progress}),this._upscalerEndHandler=()=>this.dispatchEvent({type:N.UPSCALING_END}),this.upscaler.addEventListener(`resolution_changed`,this._upscalerResChangedHandler),this.upscaler.addEventListener(`start`,this._upscalerStartHandler),this.upscaler.addEventListener(`progress`,this._upscalerProgressHandler),this.upscaler.addEventListener(`end`,this._upscalerEndHandler)}get denoiserStrategy(){return this.continuousDenoise?`oidn`:this._stages.nrd?.enabled?`nrd`:`none`}setDenoiserStrategy(e,t){let n=this._stages;tb.includes(e)||(this._issues?.record(X.DENOISER_UNAVAILABLE,`'${e}' is not a live denoiser (${tb.join(`, `)}) — none is used`,{strategy:e}),e=`none`),e===`nrd`&&this._isPanorama()&&(this._issues?.record(X.DENOISER_UNAVAILABLE,`NRD cannot run in a panorama — oidn is used`,{strategy:e}),e=`oidn`),this._clearDenoiserTextures(),n.nrd&&(n.nrd.enabled=e===`nrd`),n.nrd?.enabled&&(n.nrd.resetHistory?.(),this._applyNRDPreset(t||`medium`)),this.setContinuousDenoise(e===`oidn`)}setAutoExposureEnabled(e,t){this._stages.autoExposure?.setEnabled(e,t)}get requiresMotionVectors(){return!!this._stages.nrd?.enabled}_syncGBufferStages(){let e=this._stages,t=e.normalDepth,n=e.motionVector,r=this.requiresMotionVectors,i=r||this.historyWanted;this.historyWanted||this._releaseHistory(),t&&(i&&!t.enabled&&t.reset(),t.enabled=i,t.setInstanceLeafOutput?.(this.historyWanted)),n&&(r&&!n.enabled&&(n.matricesInitialized=!1),n.enabled=r),e.pathTracer?.setAuxGBufferEnabled?.(i||!!this.denoiser?.enabled),e.pathTracer?.setCleanAuxNormal?.(!!this.denoiser?.enabled&&!!this.denoiser?.expectsCleanAux(this._finalQuality));for(let r of[e.nrd,t,n])r&&!r.enabled&&r.releaseGPUMemory?.()}_cleanupCompletionListener(){this.denoiser&&(this._pendingStartUpscaler&&this.denoiser.removeEventListener(`end`,this._pendingStartUpscaler),this._pendingCloseDenoise&&this.denoiser.removeEventListener(`end`,this._pendingCloseDenoise)),this._pendingStartUpscaler=null,this._pendingCloseDenoise=null}get holdsWhileMoving(){if(!this._stages.pathTracer?.viewIsChanging||!this.continuousDenoise||this._cadenceSuspended||!this.denoiser?.enabled||this._movingHopeless)return!1;let e=this.movingCostMs,t=this._movingDenoiseMs.length;e>vw*bw&&(this._movingHopeless=!0,this._syncGBufferStages());let n=!this._movingHopeless&&(t<2||e<=vw);return this._holdWhileMoving=(this._holdWhileMoving===null||this._holdWhileMoving)&&n,this._holdWhileMoving}skipsTrace(){return this.holdsWhileMoving&&!!this.denoiser?.state.isDenoising}get movingCostMs(){return this._movingDenoiseMs.length?Math.min(...this._movingDenoiseMs):0}_publishOutput(){let e=this.pipeline?.context,t=this.denoiser?.outputTexture;e&&t&&e.setTexture(`oidn:output`,t)}_unpublishOutput(){this.pipeline?.context?.removeTexture(`oidn:output`),this.denoiser?.invalidateOutput()}_checkHeldFrameHealthy(){!this.denoiser?.hasOutput||this._failedRefreshes<xw||this._unpublishOutput()}tickContinuousDenoise(e){let t=this.denoiser;if(!this.continuousDenoise||this._cadenceSuspended||!t)return!1;this._checkHeldFrameHealthy();let n=!!this._stages.pathTracer?.viewIsChanging;if(!n)this._holdWhileMoving=null,this._movingDenoiseMs.length=0;else if(!this.holdsWhileMoving)return!1;if(t.state.isDenoising||t.state.isLoading||!n&&e<=this._lastCadenceSamples)return!1;let r=performance.now(),i=n?_w:this._lastCadenceSamples===0?gw:hw,a=Math.max(this.continuousDenoiseInterval,t.lastDenoiseMs*i);if(r-this._lastCadenceAt<a)return!1;this._lastCadenceAt=r,this._lastCadenceSamples=e,t.lastDenoiseMs>mw&&(this._cadenceDowngraded=!0);let o=this._cadenceDowngraded?this.previewQuality():this._finalQuality;return t.quality!==o&&t.updateQuality(o),t.start({continuous:!0}).then(e=>{this._failedRefreshes=e?0:this._failedRefreshes+1,!(!e||!n)&&(this._movingDenoiseMs.push(t.lastDenoiseMs),this._movingDenoiseMs.length>yw&&this._movingDenoiseMs.shift())}),!0}previewQuality(){return this.denoiser?.expectsCleanAux(this._finalQuality)?`fast-clean`:`fast`}setCadenceSuspended(e){this._cadenceSuspended=!!e,this._historyDirty=!0,this._cadenceSuspended&&(this.denoiser?.abort(),this._unpublishOutput()),this._syncGBufferStages()}setContinuousDenoise(e){!e&&!this.finalDenoise&&this.denoiser?.abort(),this.continuousDenoise=!!e,this._syncOIDNInUse(),this._lastCadenceAt=-1/0,this._resetCadence(),this._syncGBufferStages()}_useFinalQuality(){let e=this.denoiser;e&&e.quality!==this._finalQuality&&e.updateQuality(this._finalQuality)}_resetCadence(){this._lastCadenceSamples=0}setTemporalHistory(e){this.temporalHistory=!!e,this._syncGBufferStages()}get historyWanted(){return this.temporalHistory&&this.continuousDenoise&&!!this.denoiser?.enabled&&!this._movingHopeless&&!this._cadenceSuspended&&!this._isPanorama()}get historyActive(){return this.historyWanted&&!!this._stages.normalDepth?.enabled&&!(this._stages.pathTracer?.visMode?.value>0)}_isPanorama(){return this._stages.pathTracer?.uniforms?.get(`cameraProjection`)?.value===at.equirectangular}beforeReset({keepHistory:e=!1}={}){let t=this._stages.pathTracer;if(!t||!this.historyActive)return;let n=t.resetCount!==this._knownResetCount;if(!e||n&&t.frameCount<2){this._historyDirty=!0;return}if(t.frameCount<2)return;let r=this._historyInputs();r&&(this._ensureHistory().merge(r,t.frameCount,this._historyCameraNow(),{commit:!0,keepHistory:!this._historyDirty&&!n,historyScale:Cw(t.frameCount)}),this._historyDirty=!1)}afterReset(){this._knownResetCount=this._stages.pathTracer?.resetCount??0}afterTrace(){let e=this._stages.pathTracer;if(!e||e.tracedFrames===this._seenTracedFrames)return;if(this._seenTracedFrames=e.tracedFrames,e.resetCount!==this._knownResetCount&&(this._historyDirty=!0,this._knownResetCount=e.resetCount),!this.historyActive||e.frame.value!==0){this._movedPlacements.clear();return}let t=this._historyInputs();if(!t){this._movedPlacements.clear(),this._historyDirty=!0;return}let n=this._ensureHistory();this._historyDirty&&n.invalidate(),n.accumulate(t,this._historyCameraNow(),this._takeMovedPlacements()),this._historyDirty=!1}notePlacementMoving(e,t){e<0||!this.historyActive||this._movedPlacements.has(e)||this._movedPlacements.set(e,{matrixOf:t,prev:t().slice()})}_takeMovedPlacements(){let e=this._movedPlacements,t=this._movedUpload;if(t.count=e.size,!e.size)return t;t.leaves.length<e.size&&(t.leaves=new Uint32Array(e.size*2),t.toPrev=new Float32Array(e.size*32));let n=[...e.keys()].sort((e,t)=>e-t);for(let r=0;r<n.length;r++){let{matrixOf:i,prev:a}=e.get(n[r]);this._matB.fromArray(i()).invert(),this._matA.fromArray(a).multiply(this._matB).toArray(t.toPrev,r*16),t.leaves[r]=n[r]}return e.clear(),t}_historyTextures(){let e=this._stages.pathTracer,t=this._history;if(!t?.valid||this._historyDirty||!this.historyActive||e.isComplete||e.resetCount!==this._knownResetCount||t.width!==this._lastRenderWidth||t.height!==this._lastRenderHeight)return null;if(e.frameCount<=1)return t.textures;if(e.frameCount>=Sw)return null;let n=this._historyInputs();return n?t.merge(n,e.frameCount,this._historyCameraNow(),{historyScale:Cw(e.frameCount)}):null}_historyInputs(){let e=this._stages.pathTracer,t=this.pipeline?.context,n=this.renderer?.backend;if(!e?.storageTextures?.readTarget||!t||!n)return null;let r=e.storageTextures.getReadTextures(),i=e=>e?n.get(e)?.texture:null,a={color:i(r.color),albedo:i(r.albedo),normal:i(r.normalDepth),geo:i(t.getTexture(`pathtracer:normalDepth`)),geoPrev:i(t.getTexture(`pathtracer:prevNormalDepth`)),shading:i(t.getTexture(`pathtracer:shadingNormal`)),leaf:i(t.getTexture(`pathtracer:instanceLeaf`)),width:e.width,height:e.height};return a.color&&a.albedo&&a.normal&&a.geo&&a.geoPrev&&a.shading&&a.leaf?a:null}_historyCameraNow(){let e=this._stages.pathTracer;this._viewProj.multiplyMatrices(e.cameraProjectionMatrix.value,e.cameraViewMatrix.value);let t=this._historyCamera;return t.world=e.cameraWorldMatrix.value.elements,t.projInv=e.cameraProjectionMatrixInverse.value.elements,t.viewProj=this._viewProj.elements,t.orthographic=e.uniforms?.get(`cameraProjection`)?.value===at.orthographic,t}_ensureHistory(){return this._history??=new OC(this.renderer.backend.device),this._history.settings.cleanAux=!!this.denoiser?.expectsCleanAux(this._finalQuality),this._history}_releaseHistory(){this._history?.dispose(),this._history=null,this._historyDirty=!0,this._movedPlacements.clear()}setUpscalerBackend(e){let t=e===`neural`?`neural`:`esrgan`;t!==this.upscalerBackend&&(this.upscalerBackend=t,this._restoreRenderDisplay(),t!==`neural`&&this._releaseNeuralUpscaler())}_restoreRenderDisplay(){let e=this.upscalerCanvas&&this.upscalerCanvas.style.display!==`none`;return this.upscalerCanvas&&(this.upscalerCanvas.style.display=`none`),this.mainCanvas&&(this.mainCanvas.style.opacity=`1`),e&&this._lastRenderWidth&&this._lastRenderHeight&&this.dispatchEvent({type:N.RESOLUTION_CHANGED,width:this._lastRenderWidth,height:this._lastRenderHeight}),!!e}_releaseNeuralUpscaler(){this._neuralUpscaler?.dispose(),this._neuralUpscaler=null,this._superResModule?.releaseDenoisedReader()}setNeuralRendering(e,t=null){let n=this.neuralRendering!==!!e;this.neuralRendering=!!e,t&&(this.neuralRenderingSettings={...this.neuralRenderingSettings,...t}),this.neuralRendering||(this._releaseNeuralRetouch(),this._restoreRenderDisplay()),n&&this._redoPostPasses()}_releaseNeuralRetouch(){this._retouch?.dispose(),this._retouch=null}async _runNeuralPost(e){let t=this.upscaler?.enabled&&this.upscalerBackend===`neural`,n=this.neuralRendering,r=this.upscaler?.enabled&&!t;if(!(!t&&!n)&&!this._neuralPostBusy){if(!this.upscalerCanvas){this._recordNoOverlayCanvas(`neural`);return}if(!this.pipeline?.context?.getTexture(`oidn:output`)){pw.warn(`neural pass skipped: no denoised picture — it needs OIDN`);return}this._neuralPostBusy=!0,this.dispatchEvent({type:N.UPSCALING_START});try{let i=await Promise.resolve().then(()=>(QC(),IC));this._superResModule=i;let a=n?await Promise.resolve().then(()=>(fw(),$C)):null,o=this.denoiser?._outTexSize,s=(o?.width??0)*(o?.height??0),c=n&&s<=a.RETOUCH_MAX_PIXELS;if(n&&!c&&(pw.warn(`Neural rendering skipped: the render is ${(s/1e6).toFixed(1)} MP, above the ${(a.RETOUCH_MAX_PIXELS/1e6).toFixed(1)} MP the pass survives.`+(t?` The upscale still ran.`:``)),this._releaseNeuralRetouch()),!t&&!c){r&&!this._postCancelled&&await this.upscaler.start();return}let l={exposure:this._getEffectiveExposure(),toneMapping:this._getToneMapping(),saturation:this._getSaturation?.()??1,gain:this._getDisplayGain?.()??null},u=await i.readDenoisedHalf(this.denoiser);t&&(this._neuralUpscaler&&(this._neuralUpscaler.inputWidth!==u.width||this._neuralUpscaler.inputHeight!==u.height)&&this._releaseNeuralUpscaler(),this._neuralUpscaler||=await i.NeuralSuperRes.create({width:u.width,height:u.height}));let d=u;if(c){let e=await a.enhanceFrame({source:d,settings:this.neuralRenderingSettings,instance:this._retouch,exposure:l.exposure,tone:t?null:l});this._retouch=e.instance,d=e}if(t&&(d=await this._neuralUpscaler.upscaleToRGBA8(d,l)),!e()){this.dropDisplay();return}if(this._postRedo||this._postCancelled)return;if(r){await this.upscaler.start(new ImageData(d.rgba8,d.width,d.height,{colorSpace:this._colorSpace()}));return}if(i.presentRGBA8(this.upscalerCanvas,d.rgba8,d.width,d.height,this._colorSpace()),!e()){this.dropDisplay();return}this.mainCanvas&&(this.mainCanvas.style.opacity=`0`),this.dispatchEvent({type:N.RESOLUTION_CHANGED,width:d.width,height:d.height})}catch(e){pw.warn(`neural pass failed`,e)}finally{this._neuralPostBusy=!1,this.dispatchEvent({type:N.UPSCALING_END})}}}async denoiseOnce(){let e=this.denoiser;if(!e?.enabled)return!1;for(this._cleanupCompletionListener(),this._resetCadence(),this._useFinalQuality();e.state.isLoading||e.state.isDenoising;)await(e.state.isLoading?e.whenLoaded():new Promise(t=>{let n=()=>{e.removeEventListener(`end`,n),t()};e.addEventListener(`end`,n)}));let t=await e.start();return t&&this._onDisplayRefresh?.(),t&&e.hasOutput}_runPostPasses(e){this._postIsStillComplete=e,this._postCancelled=!1,this.neuralRendering||this.upscaler?.enabled&&this.upscalerBackend===`neural`?this._postRun=this._runNeuralPost(e):this._postRun=this.upscaler?.enabled?this.upscaler.start():null}_redoPostPasses(){let e=this._postIsStillComplete;!e?.()||this._postRedo||(this.upscaler?.abort(),this._postCancelled=!1,this._postRedo=Promise.resolve(this._postRun).catch(()=>{}).then(()=>{this._postRedo=null,!(this._postCancelled||this._postIsStillComplete!==e||!e())&&(this._restoreRenderDisplay(),this._runPostPasses(e))}))}cancelPostPasses(){this._postCancelled=!0,this.upscaler?.abort(),this._restoreRenderDisplay(),this.dispatchEvent({type:N.UPSCALING_END})}onRenderComplete({isStillComplete:e}){this._cleanupCompletionListener(),this._postIsStillComplete=null;let t=this.continuousDenoise&&!this._cadenceSuspended,n=this.finalDenoise?`final`:t?`refresh`:null,r=()=>{this.denoiser?.removeEventListener(`end`,r),this._pendingStartUpscaler=null,e()&&(n&&this._onDisplayRefresh?.(),this._runPostPasses(e))};if(!n){r();return}let i=()=>{e()&&(this._pendingStartUpscaler=r,this.denoiser.addEventListener(`end`,r),n===`final`?(this._useFinalQuality(),this.denoiser.start()):this.denoiser.start({continuous:!0}))};if(this._resetCadence(),this.denoiser.state.isDenoising){let e=()=>{this.denoiser?.removeEventListener(`end`,e),this._pendingCloseDenoise===e&&(this._pendingCloseDenoise=null),i()};this._pendingCloseDenoise=e,this.denoiser.addEventListener(`end`,e)}else i()}abort(e,{keepDisplay:t=!1}={}){this._cleanupCompletionListener(),this._postIsStillComplete=null,this._restoreRenderDisplay(),e&&e!==this.mainCanvas&&(e.style.opacity=`1`),this.upscaler&&this.upscaler.abort();let n=!!this._stages.pathTracer?.viewIsChanging,r=t&&this.continuousDenoise&&!this._cadenceSuspended&&!!this.denoiser?.hasOutput&&(!n||this.holdsWhileMoving);this.denoiser&&!r&&(this.denoiser.enabled&&this.denoiser.abort(),this._unpublishOutput()),this._resetCadence()}dropDisplay(){this._unpublishOutput(),this._restoreRenderDisplay(),this._historyDirty=!0}dispose(){if(this._cleanupCompletionListener(),this._postIsStillComplete=null,this._releaseNeuralUpscaler(),this._releaseNeuralRetouch(),this._unpublishOutput(),this._releaseHistory(),this.denoiser){if(this._denoiserStartHandler&&this.denoiser.removeEventListener(`start`,this._denoiserStartHandler),this._denoiserEndHandler&&this.denoiser.removeEventListener(`end`,this._denoiserEndHandler),this._denoiserTileHandler&&this.denoiser.removeEventListener(`tileProgress`,this._denoiserTileHandler),this._denoiserErrorHandler&&this.denoiser.removeEventListener(`error`,this._denoiserErrorHandler),this._denoiserLoadHandler){for(let e of[`loading`,`loaded`,`error`])this.denoiser.removeEventListener(e,this._denoiserLoadHandler);this.denoiser.state?.isLoading&&this.dispatchEvent({type:N.DENOISER_LOADING,loading:!1})}this.denoiser.dispose(),this.denoiser=null}this.upscaler&&(this._upscalerResChangedHandler&&this.upscaler.removeEventListener(`resolution_changed`,this._upscalerResChangedHandler),this._upscalerStartHandler&&this.upscaler.removeEventListener(`start`,this._upscalerStartHandler),this._upscalerProgressHandler&&this.upscaler.removeEventListener(`progress`,this._upscalerProgressHandler),this._upscalerEndHandler&&this.upscaler.removeEventListener(`end`,this._upscalerEndHandler),this.upscaler.dispose(),this.upscaler=null,this.upscalerBackend=`esrgan`,this._neuralUpscaler=null),this._denoiserStartHandler=null,this._denoiserEndHandler=null,this._denoiserTileHandler=null,this._denoiserErrorHandler=null,this._denoiserLoadHandler=null,this._upscalerResChangedHandler=null,this._upscalerStartHandler=null,this._upscalerProgressHandler=null,this._upscalerEndHandler=null,this._onReset=null,this._onPostProcessRefresh=null,this._onDisplayRefresh=null,this._getExposure=null,this._getSaturation=null,this._getDisplayGain=null,this._getPictureCanvas=null,this._getColorSpace=null,this._issues=null,this.upscalerCanvas?.parentNode&&(this.upscalerCanvas.parentNode.removeChild(this.upscalerCanvas),this.upscalerCanvas=null)}setOverlayManager(e){this._overlayManager=e}setResetCallback(e){this._onReset=e}setPostProcessRefreshCallback(e){this._onPostProcessRefresh=e}setDisplayRefreshCallback(e){this._onDisplayRefresh=e}setSettings(e){this._settings=e}setAutoExposureParams(e){this._stages.autoExposure?.updateParameters(e)}applyOIDNEnabled(e){this.finalDenoise=!!e,this._syncOIDNInUse()}get oidnQuality(){return this._finalQuality}setOIDNEnabled(e){this.applyOIDNEnabled(e),this._syncGBufferStages(),this._onPostProcessRefresh?.()}_syncOIDNInUse(){this.denoiser&&(this.denoiser.enabled=this.finalDenoise||this.continuousDenoise)}applyOIDNQuality(e){this._finalQuality=e,this._cadenceDowngraded=!1,this.denoiser?.updateQuality(e)}setOIDNQuality(e){this.applyOIDNQuality(e),this._syncGBufferStages(),this._onPostProcessRefresh?.()}setTileHelperEnabled(e){this._setTileHelper(e)}setUpscalerEnabled(e){let t=!!this.upscaler&&this.upscaler.enabled!==!!e;this.upscaler?this.upscaler.enabled=e:e&&this._recordNoOverlayCanvas(`upscaler`),e||this._restoreRenderDisplay(),t&&this._redoPostPasses()}setUpscalerScaleFactor(e){this.upscaler?.setScaleFactor(e)}setUpscalerQuality(e){this.upscaler?.setQuality(e)}setAutoExposure(e){this.setAutoExposureEnabled(e,this._getExposure())}setStrategy(e,t){this.setDenoiserStrategy(e,t),this._onReset?.()}setNRDParams(e){this._stages.nrd?.updateParameters(e)}applyNRDPreset(e){this._applyNRDPreset(e)}setNRDDebugMode(e){this._stages.nrd?.updateParameters({debugMode:e})}_setTileHelper(e){let t=this._overlayManager?.getHelper(`tiles`);t&&(t.enabled=e,e||t.hide())}_getEffectiveExposure(){return this._stages.autoExposure?.enabled?this.renderer.toneMappingExposure:this._getExposure()}_getToneMapping(){return this.renderer.toneMapping}_colorSpace(){return this._getColorSpace?.()??`srgb`}_clearDenoiserTextures(){let e=this.pipeline?.context;e&&(e.removeTexture(`nrd:output`),e.removeTexture(`oidn:output`))}_applyNRDPreset(e){let t=ob[e];if(!t)return;let n={};for(let e of ab)n[e]=ib[e];this._stages.nrd?.updateParameters({...n,...t})}},Tw=class{constructor(){this.layer=`hud`,this.visible=!1,this._tileBounds=null,this._imageWidth=1,this._imageHeight=1,this.enabled=!0,this._borderColor=`rgba(255, 0, 0, 0.6)`,this._borderWidthRatio=1/540,this._borderWidthMin=1.5,this._borderWidthMax=4}setActiveTile(e){this._tileBounds=e}setRenderSize(e,t){this._imageWidth=e,this._imageHeight=t}render(e,t,n){if(!this._tileBounds)return;let r=this._tileBounds,i=t/this._imageWidth,a=n/this._imageHeight,o=r.x*i,s=r.y*a,c=r.width*i,l=r.height*a,u=Math.min(this._borderWidthMax,Math.max(this._borderWidthMin,Math.min(t,n)*this._borderWidthRatio));e.strokeStyle=this._borderColor,e.lineWidth=u,e.strokeRect(o,s,c,l)}show(){this.enabled&&(this.visible=!0)}hide(){this.visible=!1,this._tileBounds=null}dispose(){this.visible=!1}},Ew=class{constructor(e,t){this.layer=`scene`,this._enabled=!0,this._scene=e,this._camera=t,this._build([])}_build(e){this._orthographic=this._camera.isOrthographicCamera===!0,this._outlineNode=(0,d.outline)(this._scene,this._camera,{selectedObjects:e,edgeThickness:(0,n.uniform)(1),edgeGlow:(0,n.uniform)(0)});let i=(0,n.uniform)(3),a=(0,n.uniform)(new r.Color(16777215)),o=(0,n.uniform)(new r.Color(1640965)),{visibleEdge:s,hiddenEdge:c}=this._outlineNode,l=s.mul(a).add(c.mul(o)).mul(i),u=l.r.max(l.g).max(l.b).clamp(0,1);this._material=new t.MeshBasicNodeMaterial,this._material.colorNode=(0,n.vec4)(l,u),this._material.transparent=!0,this._material.blending=r.CustomBlending,this._material.blendEquation=r.AddEquation,this._material.blendSrc=r.OneFactor,this._material.blendDst=r.OneFactor,this._material.blendEquationAlpha=r.AddEquation,this._material.blendSrcAlpha=r.OneFactor,this._material.blendDstAlpha=r.OneFactor,this._material.toneMapped=!1,this._material.depthTest=!1,this._material.depthWrite=!1,this._quad=new t.QuadMesh(this._material)}setSelectedObjects(e){this._outlineNode.selectedObjects=e}get visible(){return this._enabled&&this._outlineNode.selectedObjects.length>0}render(e){if(!this.visible)return;if(this._camera.isOrthographicCamera!==this._orthographic){let e=[...this._outlineNode.selectedObjects];this._outlineNode.dispose(),this._material.dispose(),this._build(e)}let t=e.autoClear;e.autoClear=!1,e.setRenderTarget(null),this._quad.render(e),e.autoClear=t}show(){this._enabled=!0}hide(){this._enabled=!1}dispose(){this._enabled=!1,this._outlineNode?.dispose(),this._material?.dispose(),this._quad=null}};function Dw(e=!1){let t=document.createElement(`canvas`);return t.style.cssText=`position:absolute;top:0;left:0;width:100%;height:100%;pointer-events:none;`+(e?`display:none;`:``),t}function Ow(e,t=1/0){let n=e?.getBoundingClientRect();if(!n||n.width===0||n.height===0)return null;let r=Math.min(window.devicePixelRatio||1,2),i=Math.round(n.width*r),a=Math.round(n.height*r),o=t/Math.max(i,a);return o<1&&(i=Math.max(1,Math.round(i*o)),a=Math.max(1,Math.round(a*o))),{width:i,height:a}}de();var kw=4096,Aw=class{constructor(){this.canvas=Dw(!0),this._visible=!1,this.renderer=null,this._sizeSource=null}async init({device:e,sizeSource:n}){this._sizeSource=n;let i=e.onuncapturederror,a=new t.WebGPURenderer({canvas:this.canvas,device:e,alpha:!0,antialias:(window.devicePixelRatio||1)<2});return await a.init(),e.onuncapturederror=i,a.outputColorSpace=r.SRGBColorSpace,a.setPixelRatio(1),a.setClearColor(0,0),a.autoClear=!1,this.renderer=a,this.syncSize(),this}get isVisible(){return this._visible}syncSize(){if(!this.renderer)return;let e=Ow(this._sizeSource,kw);!e||e.width===this.canvas.width&&e.height===this.canvas.height||this.renderer.setSize(e.width,e.height,!1)}begin(){this.renderer&&(this.renderer.setRenderTarget(null),this.renderer.clear())}setVisible(e){this._visible!==e&&(this._visible=e,this.canvas.style.display=e?``:`none`)}dispose(){ne(this.renderer),this.renderer=null,this.canvas.parentElement?.removeChild(this.canvas)}};Ae(),F();var jw=ve(`overlay`),Mw=(e,t)=>e.visible&&e.layer===t&&e.render,Nw=class{constructor(e){this.camera=e,this._helpers=new Map,this._hudCanvas=Dw(),this._hudCtx=this._hudCanvas.getContext(`2d`),this._helperScene=null,this._viewOverlay=null}async initViewRenderer({device:e,sizeSource:t}){if(!(!e||!t))try{this._viewOverlay=await new Aw().init({device:e,sizeSource:t})}catch(e){jw.error(`overlay surface unavailable — light gizmos, transform gizmo and outlines are disabled`,e),this._viewOverlay=null}}gpuResources(){let e=this._viewOverlay;return e?.isVisible?[{bytes:e.canvas.width*e.canvas.height*4},...e.renderer?._frameBufferTargets?.values()??[]]:[]}setHelperScene(e){this._helperScene=e}getHUDCanvas(){return this._hudCanvas}mount(e){if(!e)return;let t=this._viewOverlay?.canvas;t&&t.parentElement!==e&&e.appendChild(t),this._hudCanvas.parentElement!==e&&e.appendChild(this._hudCanvas)}setupDefaultHelpers({helperScene:e,meshScene:t,pipeline:n,denoisingManager:r,app:i,renderWidth:a,renderHeight:o}){this.setHelperScene(e);let s=new Tw;this.register(`tiles`,s),s.setRenderSize(a||1,o||1),i.addEventListener(N.RESOLUTION_CHANGED,e=>{s.setRenderSize(e.width,e.height)}),n.eventBus.on(`pipeline:reset`,()=>s.hide()),this._wireDenoiserTileEvents(s,r);let c=new Ew(t,this.camera);this.register(`outline`,c)}_wireDenoiserTileEvents(e,t){let n=[t?.denoiser,t?.upscaler];for(let t of n)t&&(t.addEventListener(`tileProgress`,t=>{t.continuous||t.tile&&(e.setRenderSize(t.imageWidth,t.imageHeight),e.setActiveTile(t.tile),e.show(),this.refreshHUD())}),t.addEventListener(`end`,()=>{e.hide(),this.refreshHUD()}))}register(e,t){this._helpers.has(e)&&(jw.warn(`helper "${e}" already registered — replacing.`),this._helpers.get(e).dispose?.()),this._helpers.set(e,t)}unregister(e){let t=this._helpers.get(e);t&&(t.dispose?.(),this._helpers.delete(e))}show(e){this._helpers.get(e)?.show()}hide(e){this._helpers.get(e)?.hide()}toggle(e){let t=this._helpers.get(e);t&&(t.visible?t.hide():t.show())}getHelper(e){return this._helpers.get(e)??null}isVisible(e){return this._helpers.get(e)?.visible??!1}showAll(){for(let e of this._helpers.values())e.show()}hideAll(){for(let e of this._helpers.values())e.hide()}render(){let e=this._viewOverlay;if(e){let t=this._hasVisibleSceneOverlay();(t||e.isVisible)&&(e.syncSize(),e.begin(),t&&this._renderSceneLayer(e.renderer),e.setVisible(t))}this.refreshHUD()}_renderSceneLayer(e){this._helperScene?.render(e,this.camera);for(let t of this._helpers.values())Mw(t,`scene`)&&t.render(e,this.camera)}_hasVisibleSceneOverlay(){if(this._helperScene?.isDrawing)return!0;for(let e of this._helpers.values())if(Mw(e,`scene`))return!0;return!1}refreshHUD(){let e=this._hudCanvas,t=this._hudCtx,n=!1;for(let e of this._helpers.values())if(Mw(e,`hud`)){n=!0;break}if(!n){e.style.display!==`none`&&(e.style.display=`none`);return}e.style.display!==``&&(e.style.display=``);let r=e.clientWidth,i=e.clientHeight,a=r>0&&i>0?Ow(e):null;if(a){(e.width!==a.width||e.height!==a.height)&&(e.width=a.width,e.height=a.height),t.clearRect(0,0,a.width,a.height),t.save(),t.scale(a.width/r,a.height/i);for(let e of this._helpers.values())Mw(e,`hud`)&&e.render(t,r,i);t.restore(),e.style.display!==``&&(e.style.display=``)}}dispose(){for(let e of this._helpers.values())e.dispose?.();this._helpers.clear(),this._viewOverlay?.dispose(),this._viewOverlay=null,this._hudCanvas.parentElement&&this._hudCanvas.parentElement.removeChild(this._hudCanvas)}};F();function Pw(e,t){let n=[...e].filter(t=>{for(let n=t.parent;n;n=n.parent)if(e.has(n))return!1;return!0}),r=0,i=0;t.traverse?.(()=>r++);for(let e of n)e.traverse?.(()=>i++);return i+n.length/2<r?n:null}var Fw=class extends r.EventDispatcher{constructor(){super(),this.mixer=null,this.timer=new r.Timer,this.actions=[],this.isPlaying=!1,this._scene=null,this._mixerRoot=null,this._meshes=null,this._meshTriRanges=null,this._meshPositions=null,this._tempVec=new r.Vector3,this._skinnedCache=null,this._clipsCache=null,this._savedTimeScale=1,this.onFinished=null,this._rigid=!1,this._plans=null,this._allPlan=null,this._activeClip=0,this._slotOf=null,this._lastWorld=null,this._lastVisible=null,this._lastMeshWorld=null,this._lastMorphWeights=null,this.wakeCallback=null,this.applyPoseCallback=null}init(e,t,n,i){if(this.dispose(),!i||i.length===0)return;this._scene=e,this._mixerRoot=t,this._meshes=n,this.mixer=new r.AnimationMixer(t);let a=i.map(e=>this.mixer.clipAction(e)),o=(e,t)=>e.name===t||e.getObjectByName(t)!==void 0;!a.some(e=>e.getClip().tracks.some(e=>{let n=e.name.split(`.`)[0];return o(t,n)}))&&t!==e&&(console.log(`[AnimationManager] Tracks did not resolve from model root, retrying with scene root`),this.mixer=new r.AnimationMixer(e),this._mixerRoot=e,a=i.map(e=>this.mixer.clipAction(e))),this.actions=a,this._rigid=!n.some(e=>e?.isSkinnedMesh)&&!i.some(e=>e.tracks.some(e=>e.name.includes(`morphTargetInfluences`))),this._planClips(i),this.mixer.addEventListener(`finished`,()=>{this.isPlaying=!1,this.timer.reset(),this.onFinished&&this.onFinished()}),this._meshTriRanges=[],this._skinnedCache=[];let s=0;for(let e of n){let t=e.geometry,n=t.attributes.position,r=t.index?t.index.array:null,i=r?r.length/3:n.count/3,a=n.count;this._meshTriRanges.push({start:s,count:i,uniqueVerts:a,indices:r}),s+=i}this._skinnedCache=[],this._meshPositions=[],this._lastMeshWorld=this._rigid?null:new Float64Array(n.length*16).fill(NaN),this._lastMorphWeights=[];let c=n.filter(e=>e.isSkinnedMesh).length;console.debug(`[AnimationManager] Init: ${i.length} clips, ${n.length} meshes (${c} skinned), ${s} triangles, ${this._rigid?`rigid`:`deforming`}`)}_planClips(e){let t=this._mixerRoot,n=new Map;if(t.traverse?.(e=>{n.has(e.name)||n.set(e.name,e),n.set(e.uuid,e)}),this._plans=e.map(e=>{let i=new Set,a=!1,o=!1;for(let s of e.tracks){let{nodeName:e,propertyName:c}=r.PropertyBinding.parseTrackName(s.name),l=e===``||e===`.`?t:n.get(e);if(!l){o=!0;continue}i.add(l),c===`visible`&&(a=!0)}let s=[];for(let e=0;e<this._meshes.length;e++)for(let t=this._meshes[e];t;t=t.parent)if(i.has(t)){s.push(e);break}let c=new Set;for(let e of i)e.traverse(e=>e.isCamera&&c.add(e));return{meshes:Int32Array.from(s),visibility:a,cameras:[...c],nodes:o?null:i,roots:o?null:Pw(i,t)}}),this._allPlan=null,!this._rigid)return;this._slotOf=new Int32Array(this._meshes.length).fill(-1);let i=0;for(let e of this._plans)for(let t of e.meshes)this._slotOf[t]<0&&(this._slotOf[t]=i++);this._lastWorld=new Float64Array(i*16).fill(NaN),this._lastVisible=new Uint8Array(i).fill(2)}_planFor(e){if(!this._plans)return null;if(e>=0)return this._plans[e]??null;if(!this._allPlan){let e=new Set,t=new Set,n=!1,r=new Set;for(let i of this._plans)i.meshes.forEach(t=>e.add(t)),i.cameras.forEach(e=>t.add(e)),n||=i.visibility,r&&i.nodes?i.nodes.forEach(e=>r.add(e)):r=null;this._allPlan={meshes:Int32Array.from(e),visibility:n,cameras:[...t],nodes:r,roots:r?Pw(r,this._mixerRoot):null}}return this._allPlan}_applyRigidPose(e){let t=this._planFor(e);if(!t)return;let n=[],r=!1,i=this._lastWorld,a=this._lastVisible;for(let e of t.meshes){let o=this._meshes[e],s=this._slotOf[e],c=o.matrixWorld.elements,l=s*16;for(let t=0;t<16;t++)if(i[l+t]!==c[t]){for(let e=0;e<16;e++)i[l+e]=c[e];n.push(e);break}if(t.visibility||a[s]===2){let e=1;for(let t=o;t;t=t.parent)if(!t.visible){e=0;break}a[s]!==e&&(a[s]=e,r=!0)}}(n.length||r||t.cameras.length)&&this.applyPoseCallback?.({meshIndices:n,visibilityChanged:r,cameras:t.cameras})}play(e=0){if(!(!this.mixer||this.actions.length===0)){if(this.mixer.stopAllAction(),e===-1)for(let e of this.actions)e.play();else e>=0&&e<this.actions.length&&this.actions[e].play();this._activeClip=e,this.timer.reset(),this.isPlaying=!0,this.wakeCallback?.(),this.dispatchEvent({type:N.ANIMATION_STARTED})}}pause(){this.mixer&&(this.mixer.timeScale=0,this.timer.reset(),this.isPlaying=!1,this.dispatchEvent({type:N.ANIMATION_PAUSED}))}resume(){this.mixer&&(this.mixer.timeScale=this._savedTimeScale||1,this.timer.reset(),this.isPlaying=!0,this.wakeCallback?.(),this.dispatchEvent({type:N.ANIMATION_STARTED}))}stop(){this.mixer&&(this.mixer.stopAllAction(),this.mixer.timeScale=this._savedTimeScale||1,this.timer.reset(),this.isPlaying=!1,this._rigid&&(this._mixerRoot.updateMatrixWorld(!0),this._applyRigidPose(-1)),this.dispatchEvent({type:N.ANIMATION_STOPPED}))}setSpeed(e){this._savedTimeScale=e,this.mixer&&this.isPlaying&&(this.mixer.timeScale=e)}setLoop(e){let t=e?r.LoopRepeat:r.LoopOnce;for(let n of this.actions)n.setLoop(t),n.clampWhenFinished=!e}seekTo(e,t=0){if(!this.mixer||this.actions.length===0)return null;if(this._activeClip=t,this.mixer.stopAllAction(),t===-1)for(let e of this.actions)e.play();else t>=0&&t<this.actions.length&&this.actions[t].play();this.mixer.setTime(e);for(let e of this.actions)e.isRunning()&&(e.paused=!0);return this._poseReader()}get currentTime(){return this.mixer?.time||0}update(){if(!this.isPlaying||!this.mixer)return null;this.timer.update();let e=this.timer.getDelta();return this.mixer.update(e),this._poseReader()}_scratch(e,t,n){let r=e[t];return r&&r.length===n?r:e[t]=new Float32Array(n)}_poseReader(){let e=this._rigid?this._planFor(this._activeClip)?.roots:null;if(e)for(let t of e)t.updateMatrixWorld(!0);else this._mixerRoot.updateMatrixWorld(!0);if(this._rigid)return this._applyRigidPose(this._activeClip),null;let t=this._planFor(this._activeClip)?.cameras;t?.length&&this.applyPoseCallback?.({meshIndices:[],visibilityChanged:!1,cameras:t});let n=new Int8Array(this._meshes.length);return e=>(n[e]===0&&(n[e]=this._meshes[e].isSkinnedMesh||this._poseChanged(e)?1:-1),n[e]>0?this._computeMeshPositions(e):null)}_poseChanged(e){let t=this._meshes[e],n=this._lastMeshWorld,r=t.matrixWorld.elements,i=e*16,a=!1;for(let e=0;e<16;e++)if(n[i+e]!==r[e]){for(let e=0;e<16;e++)n[i+e]=r[e];a=!0;break}let o=t.morphTargetInfluences;if(o?.length){let t=this._lastMorphWeights[e];(!t||t.length!==o.length||t.some((e,t)=>e!==o[t]))&&(this._lastMorphWeights[e]=Float64Array.from(o),a=!0)}return a}_computeMeshPositions(e){let t=this._tempVec,n=this._meshes[e],{count:r,uniqueVerts:i,indices:a}=this._meshTriRanges[e],o=this._scratch(this._skinnedCache,e,i*3),s=this._scratch(this._meshPositions,e,r*9),c=n.matrixWorld;for(let e=0;e<i;e++)n.getVertexPosition(e,t),t.applyMatrix4(c),o[e*3]=t.x,o[e*3+1]=t.y,o[e*3+2]=t.z;if(a)for(let e=0;e<r;e++){let t=e*3,n=a[t]*3,r=a[t+1]*3,i=a[t+2]*3,c=e*9;s[c]=o[n],s[c+1]=o[n+1],s[c+2]=o[n+2],s[c+3]=o[r],s[c+4]=o[r+1],s[c+5]=o[r+2],s[c+6]=o[i],s[c+7]=o[i+1],s[c+8]=o[i+2]}else for(let e=0;e<r;e++){let t=e*3*3,n=(e*3+1)*3,r=(e*3+2)*3,i=e*9;s[i]=o[t],s[i+1]=o[t+1],s[i+2]=o[t+2],s[i+3]=o[n],s[i+4]=o[n+1],s[i+5]=o[n+2],s[i+6]=o[r],s[i+7]=o[r+1],s[i+8]=o[r+2]}return s}get hasAnimations(){return this.actions.length>0}get clips(){return this._clipsCache||=this.actions.map((e,t)=>{let n=e.getClip();return{index:t,name:n.name||`Clip ${t}`,duration:n.duration}}),this._clipsCache}dispose(){this.mixer&&=(this.mixer.stopAllAction(),this.mixer.uncacheRoot(this._mixerRoot),null),this.actions=[],this.isPlaying=!1,this.timer.reset(),this._scene=null,this._mixerRoot=null,this._meshes=null,this._meshTriRanges=null,this._meshPositions=null,this._skinnedCache=null,this._clipsCache=null,this._rigid=!1,this._plans=null,this._allPlan=null,this._activeClip=0,this._slotOf=null,this._lastWorld=null,this._lastVisible=null,this._lastMeshWorld=null,this._lastMorphWeights=null}};F();var Iw=new r.Vector3(0,0,-1),Lw=e=>{for(;e.parent;)e=e.parent;return e.isScene?e:null},Rw=class{constructor({camera:e,canvas:t,orbitControls:n,app:i}){this._app=i,this._orbitControls=n,this._camera=e,this._controls=new f.TransformControls(e,t),this._gizmoScene=new r.Scene,this._gizmoScene.add(this._controls.getHelper()),this._attached=null,this._isDragging=!1,this._meshes=null,this._refitInFlight=!1,this._baselineComputed=!1,this._moved=new Set,this._tempForward=new r.Vector3,this._lightTargetDistance=null,this._lastLightPosition=null,this._onDraggingChanged=this._onDraggingChanged.bind(this),this._onObjectChange=this._onObjectChange.bind(this),this._controls.addEventListener(`dragging-changed`,this._onDraggingChanged),this._controls.addEventListener(`objectChange`,this._onObjectChange)}setMeshData(e){this._meshes=e;for(let e of this._moved)Lw(e)||this._moved.delete(e)}get movedObjects(){return[...this._moved].filter(e=>Lw(e))}noteMoved(e){e&&!e.isLight&&this._moved.add(e)}attach(e){this._attached!==e&&(this._controls.attach(e),this._attached=e,this._lightTargetDistance=null,this._lastLightPosition=null,e.isLight&&e.target&&(this._syncLightAim(e),this._lastLightPosition=e.position.clone()))}detach(){this._attached&&(this._controls.detach(),this._attached=null,this._lightTargetDistance=null,this._lastLightPosition=null)}setMode(e){this._controls.setMode(e),this._app?.dispatchEvent({type:N.TRANSFORM_MODE_CHANGED,mode:e}),this._app?.refreshFrame()}setSpace(e){this._controls.setSpace(e),this._app?.refreshFrame()}get isDragging(){return this._isDragging}get attachedObject(){return this._attached}get controls(){return this._controls}render(e){if(!this._attached)return;let t=e.autoClear;e.autoClear=!1,e.clearDepth(),e.setRenderTarget(null),e.render(this._gizmoScene,this._camera),e.autoClear=t}_onDraggingChanged(e){this._isDragging=e.value,this._orbitControls&&(this._orbitControls.enabled=!e.value),e.value?this._app.dispatchEvent({type:N.OBJECT_TRANSFORM_START}):(this._attached?.isLight?this._finalizeLightTransform():this._recomputeAndRefit(),this._app.dispatchEvent({type:N.OBJECT_TRANSFORM_END}))}_onObjectChange(){this._app.needsReset=!0,this._app.wake(),this._attached?.isLight&&this._syncLightDuringDrag()}_syncLightDuringDrag(){let e=this._attached;if(e.target){let t=this._controls.mode;if(t===`translate`&&this._lastLightPosition&&!e.isDirectionalLight){let t=this._tempForward.copy(e.position).sub(this._lastLightPosition);e.target.position.add(t),e.target.updateMatrixWorld(!0)}else if(t===`rotate`&&this._lightTargetDistance!=null){let t=this._tempForward.set(0,0,-1).applyQuaternion(e.quaternion);e.target.position.copy(e.position).addScaledVector(t,this._lightTargetDistance),e.target.updateMatrixWorld(!0)}this._lastLightPosition.copy(e.position)}this._app.lightManager?.updateLights()}_finalizeLightTransform(){let e=this._attached;e.isDirectionalLight&&e.target&&this._controls.mode===`translate`&&this._syncLightAim(e),e.isRectAreaLight&&(e.scale.x!==1||e.scale.y!==1)&&(e.width*=e.scale.x,e.height*=e.scale.y,e.scale.set(1,1,1)),this._app.lightManager?.updateLights()}_syncLightAim(e){let t=this._tempForward.copy(e.target.position).sub(e.position),n=t.length();n>1e-4?(e.quaternion.setFromUnitVectors(Iw,t.normalize()),this._lightTargetDistance=n):this._lightTargetDistance=1}_recomputeAndRefit(){if(!this._meshes||this._refitInFlight||!this._attached)return;this._attached.updateMatrixWorld(!0);let e=this._findAffectedMeshIndices(this._attached);if(e.length!==0){this._refitInFlight=!0;try{this._app.updateMeshTransforms(e),this._moved.add(this._attached)}catch(e){console.error(`Transform refit error:`,e)}finally{this._refitInFlight=!1}}}_findAffectedMeshIndices(e){let t=[];for(let n=0;n<this._meshes.length;n++){let r=this._meshes[n];(r===e||this._isDescendantOf(r,e))&&t.push(n)}return t}_isDescendantOf(e,t){let n=e.parent;for(;n;){if(n===t)return!0;n=n.parent}return!1}dispose(){this._controls.removeEventListener(`dragging-changed`,this._onDraggingChanged),this._controls.removeEventListener(`objectChange`,this._onObjectChange),this.detach(),this._gizmoScene.remove(this._controls.getHelper()),this._controls.dispose(),this._meshes=null,this._moved.clear(),this._baselineComputed=!1,this._tempForward=null,this._lightTargetDistance=null,this._lastLightPosition=null,this._app=null,this._orbitControls=null,this._camera=null,this._controls=null,this._gizmoScene=null}},zw=class{constructor(e){this.layer=`scene`,this._transformManager=e,this._enabled=!0}get visible(){return this._enabled&&this._transformManager.attachedObject!==null}render(e){this._transformManager.render(e)}show(){this._enabled=!0}hide(){this._enabled=!1}dispose(){this._enabled=!1}};wc();var Bw=1,Vw=e=>typeof e==`string`&&/^https?:\/\//.test(e);function Hw(e,t){let n=[];for(;e&&e!==t;){let t=e.parent;if(!t)return null;n.unshift(t.children.indexOf(e)),e=t}return e===t?n:null}function Uw(e,t){let n=e;for(let e of t)if(n=n?.children[e],!n)return null;return n}function Ww(e){return{key:e.assetLoader?.sceneSourceKey??null,name:e.sceneModel?.name??null,meshes:e.sceneMeshes.length,materials:e.stages.pathTracer?.materialData.materialCount??0}}function Gw(e){let t=new Map;for(let n of e.sceneMeshes){let e=n.userData?.materialIndex;e!==void 0&&!t.has(e)&&t.set(e,Array.isArray(n.material)?n.material[0]:n.material)}return t}function Kw(e){if(!e)return null;let t=e.status(),n=t.activeView,r=t.config?.id??n?.configId??null;return{config:r?{id:r}:null,view:n?{display:n.display,view:n.view,look:n.look??null}:null,transform:n?null:t.activeTransform?.id??null,workingSpace:t.workingSpaceAdopted?t.workingSpace:null,context:t.context??null}}function qw(e){let t=e.meshScene,n=Gw(e),r=[];return t.traverse(e=>{e!==t&&e.visible===!1&&r.push(Hw(e,t))}),{v:1,engine:Cc,savedAt:Date.now(),scene:Ww(e),appended:t.children.filter(t=>t!==e.sceneModel&&t.userData?.__rayzeeSceneObject).map(e=>({name:e.userData.__rayzeeName??e.name,url:e.userData.__rayzeeSourceUrl??null,cacheKey:e.userData.__rayzeeCacheKey??null})),settings:e.settings.serialize(),environment:e.environmentManager?.serialize()??null,color:Kw(e.color),lights:e.lightManager.serialize(),cameras:e.cameraManager.serialize(),timeline:e.timeline?.serialize()??null,materials:(e.stages.pathTracer?.materialData.serializeHostEdits()??[]).map(e=>({...e,name:n.get(e.index)?.name??``})),hidden:r,moved:(e.transformManager?.movedObjects??[]).map(e=>({path:Hw(e,t),name:e.name,position:e.position.toArray(),quaternion:e.quaternion.toArray(),scale:e.scale.toArray()})).filter(e=>e.path)}}function Jw(e,t,n){let r=e[t];r?.copy&&(n?.isColor||n?.isVector2||n?.isVector3)?r.copy(n):e[t]=n,e.needsUpdate=!0}async function Yw(e,t,n,r){if(!t)return;let i=e.environmentManager;if(t.hdri&&t.hdri!==i.hdriSource){let i=Vw(t.hdri)?t.hdri:await n({kind:`environment`,source:t.hdri});try{typeof i==`string`?await e.loadEnvironment(i):i?await e.loadFile(i):r(`environment`,`source unavailable`,{source:t.hdri})}catch(e){r(`environment`,e.message,{source:t.hdri})}}await i.restore(t)}async function Xw(e,t,n,r){let i=e.color;if(!t||!i)return;let a=i.status(),o=a.activeView,s=!!t.view&&!!o&&o.display===t.view.display&&o.view===t.view.view&&(o.look??null)===t.view.look,c=a.config?.id??null,l=c??o?.configId??null;if(!((t.config?.id??null)===l&&!t.workingSpace&&!t.context&&(t.view?s:!o&&(!t.transform||t.transform===a.activeTransform?.id))))try{if(t.config&&t.config.id!==c){if(!await n({kind:`colorConfig`,config:t.config})){if(!(await i.constructor.listBuiltinConfigs().catch(()=>[])).some(e=>(e.name??e)===t.config.id||`ocio://${e.name??e}`===t.config.id)){r(`color`,`config unavailable`,{config:t.config.id});return}await e.loadColorConfig({builtin:t.config.id,registerViews:!1})}}else !t.config&&c&&await e.unloadColorConfig();t.context&&i.setContext(t.context),t.view?i.setView(t.view):t.transform&&i.setActiveView(t.transform),(t.workingSpace??null)!==(i.workingSpaceAdopted?i.workingSpace:null)&&(i.setWorkingSpace(t.workingSpace),await e.applyColorWorkingSpace())}catch(e){r(`color`,e.message,{config:t.config?.id??null})}}async function Zw(e,t,{resolve:n=async()=>null}={}){if(t?.v!==1)throw Error(`scene state version ${t?.v} is not 1`);let r=[],i=(e,t,n={})=>r.push({section:e,reason:t,...n});for(let n of t.appended??[]){if(!n.url){i(`appended`,`added from memory, not a file`,{name:n.name});continue}try{await e.addModel(n.url,{name:n.name,cacheKey:n.cacheKey??void 0})}catch(e){i(`appended`,e.message,{name:n.name})}}let a=Ww(e),o=t.scene??{},s=o.meshes===a.meshes&&o.materials===a.materials;s||i(`scene`,`the loaded scene is not the one saved: objects and materials left as loaded`,{saved:o,now:a}),await Yw(e,t.environment,n,i),await Xw(e,t.color,n,i);let c=e.settings.restore(t.settings);c.length&&i(`settings`,`not settings in this engine`,{keys:c});let l=e.lightManager.restore(t.lights);for(let t of l){let{gobo:n,ies:r}=t.userData;n&&e.goboManager?.entries?.length&&e.goboManager.setLightGobo(t.uuid,n.name,n),r&&e.iesManager?.entries?.length&&e.iesManager.setSpotLightProfile(t.uuid,r.name,r.intensity,{applyAutoCone:!1})}if(s){let n=Gw(e);for(let r of t.materials??[]){let t=n.get(r.index);if(!t||(t.name??``)!==r.name){i(`materials`,`no such material`,{index:r.index,name:r.name});continue}for(let[n,i]of Object.entries(r.props)){let a=rr(i);Jw(t,n,a),e.setMaterialProperty(r.index,n,a)}}let r=e.meshScene,a=new Set((t.hidden??[]).map(e=>Uw(r,e)).filter(Boolean));r.traverse(e=>{e!==r&&!e.isLight&&(e.visible=!a.has(e))}),e.updateAllMeshVisibility();let o=[];for(let n of t.moved??[]){let t=Uw(r,n.path);if(!t||t.name!==n.name){i(`moved`,`no such object`,{name:n.name});continue}t.position.fromArray(n.position),t.quaternion.fromArray(n.quaternion),t.scale.fromArray(n.scale),t.updateMatrixWorld(!0),e.transformManager?.noteMoved(t),o.push(t)}if(o.length){let t=[];e.sceneMeshes.forEach((e,n)=>{for(let r=e;r;r=r.parent)if(o.includes(r)){t.push(n);break}}),t.length&&e.updateMeshTransforms(t)}}let{mismatched:u}=e.cameraManager.restore(t.cameras);return u.length&&i(`cameras`,`model cameras changed`,{names:u}),e._dispatchCamerasUpdated(),e.timeline?.restore(t.timeline),e.reset(),{skipped:r}}var Qw=[{name:`FBX`,label:`FBX`,type:`model`,extensions:[`fbx`],async parse(e,{cache:t}){return t.fbx??=new(await(import(`three/addons/loaders/FBXLoader.js`))).FBXLoader,{model:t.fbx.parse(await e.arrayBuffer())}}},{name:`OBJ`,label:`OBJ`,type:`model`,extensions:[`obj`],async parse(e,{filename:t,cache:n}){n.obj??=new(await(import(`three/addons/loaders/OBJLoader.js`))).OBJLoader;let r=n.obj.parse(await e.text());return r.name=t,{model:r}}},{name:`STL`,label:`STL`,type:`model`,extensions:[`stl`],async parse(e,{filename:t,cache:n}){n.stl??=new(await(import(`three/addons/loaders/STLLoader.js`))).STLLoader;let i=new r.Mesh(n.stl.parse(await e.arrayBuffer()),new r.MeshStandardMaterial);return i.name=t,{model:i}}},{name:`PLY (Polygon File Format)`,label:`PLY`,type:`model`,extensions:[`ply`],async parse(e,{filename:t,cache:n}){n.ply??=new(await(import(`three/addons/loaders/PLYLoader.js`))).PLYLoader;let i=n.ply.parse(await e.arrayBuffer()),a;if(i.index!==null)a=new r.Mesh(i,new r.MeshStandardMaterial);else{let e=new r.PointsMaterial({size:.01});e.vertexColors=i.hasAttribute(`color`),a=new r.Points(i,e)}return a.name=t,{model:a}}},{name:`Collada`,label:`Collada`,type:`model`,extensions:[`dae`],async parse(e,{filename:t,cache:n}){n.collada??=new(await(import(`three/addons/loaders/ColladaLoader.js`))).ColladaLoader;let r=n.collada.parse(await e.text());return r.scene.name=t,{model:r.scene,result:r}}},{name:`3D Manufacturing Format`,label:`3MF`,type:`model`,extensions:[`3mf`],async parse(e,{cache:t}){return t.threemf??=new(await(import(`three/addons/loaders/3MFLoader.js`))).ThreeMFLoader,{model:t.threemf.parse(await e.arrayBuffer())}}},{name:`USD (Universal Scene Description)`,label:`USD`,type:`model`,extensions:[`usd`,`usda`,`usdc`,`usdz`],async parse(e,{filename:t,cache:n}){n.usd??=new(await(import(`three/addons/loaders/USDLoader.js`))).USDLoader;let r=await e.arrayBuffer(),i=await new Promise((e,t)=>n.usd.parse(r,``,e,t));return i.name=t,{model:i}}},{name:`EXR (OpenEXR)`,label:`EXR`,type:`environment`,extensions:[`exr`],async createLoader(e){let{EXRLoader:t}=await import(`three/addons/loaders/EXRLoader.js`);return new t(e).setDataType(r.FloatType)}}],$w=_({LampPick:()=>eT,areaLightDirectPdfW:()=>lT,directionalConeSolidAngle:()=>cT,lampCount:()=>tT,lampPickPdf:()=>oT,lampTypeAt:()=>nT,pickLamp:()=>aT,spotConeSolidAngle:()=>sT});O(),xu();var eT=x({kind:`int`,index:`int`,pdf:`float`,total:`float`}),tT=e=>e.numDirectional.add(e.numArea).add(e.numPoint).add(e.numSpot),nT=(e,t)=>(0,n.select)(t.lessThan(e.numDirectional),(0,n.int)(0),(0,n.select)(t.lessThan(e.numDirectional.add(e.numArea)),(0,n.int)(1),(0,n.select)(t.lessThan(e.numDirectional.add(e.numArea).add(e.numPoint)),(0,n.int)(2),(0,n.int)(3)))),rT=(e,t)=>(0,n.select)(t.equal((0,n.int)(0)),(0,n.int)(0),(0,n.select)(t.equal((0,n.int)(1)),e.numDirectional,(0,n.select)(t.equal((0,n.int)(2)),e.numDirectional.add(e.numArea),e.numDirectional.add(e.numArea).add(e.numPoint)))),iT=(e,t,r,i,a)=>{let o=(e,t,r)=>(0,n.If)(t.greaterThan((0,n.int)(0)),()=>{(0,n.Loop)({start:(0,n.int)(0),end:t,type:`int`,condition:`<`},({i:t})=>{a((0,n.int)(e),t,r(t).toVar())})});o(0,e.numDirectional,t=>Sh(Nm.wrap(zm(e.directional,t)),r,i,(0,n.int)(0))),o(1,e.numArea,a=>{let o=Pm.wrap(Bm(e.area,a));return(0,n.select)(o.intensity.greaterThan(0),Ch(o,t,r,i),(0,n.float)(0))}),o(2,e.numPoint,n=>wh(Fm.wrap(Vm(e.point,n)),t,r,i)),o(3,e.numSpot,n=>Th(Im.wrap(Hm(e.spot,n)),t,r,i))};function aT(e,t,r,i,a,o){let s=(0,n.int)(-1).toVar(),c=(0,n.int)(-1).toVar(),l=(0,n.float)(0).toVar(),u=(0,n.float)(0).toVar();iT(e,t,r,i,(t,r,i)=>{u.addAssign(i),(0,n.If)(i.greaterThan(0).and(o((0,n.int)(Ge+64).add(rT(e,t)).add(r)).mul(u).lessThan(i)),()=>{s.assign(t),c.assign(r),l.assign(i)})});let d=tT(e).toVar(),f=l.div((0,n.max)(u,1e-10)).toVar();return(0,n.If)(u.lessThanEqual(0),()=>{let t=(0,n.min)((0,n.int)(a.mul((0,n.float)(d))),d.sub((0,n.int)(1))).toVar();s.assign(nT(e,t)),c.assign(t.sub(rT(e,s))),f.assign((0,n.float)(1).div((0,n.max)((0,n.float)(d),1)))}),eT({kind:s,index:c,pdf:f,total:u})}function oT(e,t,r,i,a,o){let s=(0,n.float)(0).toVar(),c=(0,n.float)(0).toVar();return iT(e,i,a,o,(e,i,a)=>{s.addAssign(a),(0,n.If)(e.equal(t).and(i.equal(r)),()=>{c.assign(a)})}),(0,n.select)(s.greaterThan(0),c.div(s),(0,n.float)(1).div((0,n.max)((0,n.float)(tT(e)),1)))}var sT=e=>(0,n.float)(2*Nl).mul((0,n.max)((0,n.float)(1).sub((0,n.cos)(e.angle)),1e-10)),cT=e=>(0,n.float)(2*Nl).mul((0,n.max)((0,n.float)(1).sub((0,n.cos)(e.angle.mul(.5))),1e-10)),lT=(e,t,r,i)=>{let a=Zm(t,e.position.sub(e.u).sub(e.v),e.u.mul(2),e.v.mul(2)).toVar();return(0,n.select)(e.shape.lessThan(.5).and(a.greaterThan(1e-5)),(0,n.float)(1).div(a),r.mul(r).div((0,n.max)(e.area.mul((0,n.max)(i,.001)),1e-10)))},uT=_({DIM_CONNECT_PATH:()=>16,DIM_CONNECT_VERTEX:()=>17,DIM_EMIT:()=>dT,LIGHT_PIXEL_ROW_OFFSET:()=>fT,PASS_TAG_BIT:()=>hT,SOURCE:()=>PT,SPLAT_MAX:()=>mT,SPLAT_SCALE:()=>pT,STRATEGY:()=>kT,STRATEGY_ALONE:()=>8,emitterAreaPdf:()=>MT,emitterSideProbability:()=>jT,facingSide:()=>BT,lampSource:()=>IT,lightEndCosine:()=>VT,lightPathPixel:()=>vT,mergeEta:()=>TT,mergeRadiusAt:()=>wT,mergeVmAt:()=>ET,mis:()=>yT,misMergePartial:()=>DT,misOnHit:()=>bT,misOnScatter:()=>ST,misOnSpecular:()=>xT,misPartial:()=>CT,misWeight:()=>OT,resolveSurfaceMaterial:()=>zT,sourceLampIndex:()=>RT,sourceLampType:()=>LT,sourcePick:()=>FT,strategyWeight:()=>AT,sunEmissionPdf:()=>NT});xu(),Dl();var dT=Ge+2048,fT=65536,pT=16384,mT=4096,hT=2147483648,gT=1e30,_T=e=>(0,n.select)(e.equal(e),e,(0,n.float)(0)).clamp(0,gT),vT=(e,t)=>{let r=(0,n.uint)(t.x);return(0,n.vec2)((0,n.float)((0,n.uint)(e).mod(r)).add(.5),(0,n.float)((0,n.uint)(e).div(r).add((0,n.uint)(fT))).add(.5))},yT=e=>e.mul(e),bT=(e,t,r)=>{let i=(0,n.max)(r,1e-6);e.dVCM.assign(_T(e.dVCM.mul(yT(t.mul(t).div(i))))),e.dVC.assign(_T(e.dVC.div(yT(i))))},xT=(e,t)=>{e.dVC.assign(_T(e.dVC.mul(yT(t)))),e.dVCM.assign(0)},ST=(e,t,r,i)=>{let a=(0,n.max)(r,1e-12),o=e.dVC.mul(yT(i)).add(e.dVCM);e.dVC.assign(_T(yT(t.div(a)).mul(_T(e.vm?o.add(e.vm):o)))),e.dVCM.assign(_T(yT((0,n.float)(1).div(a))))},CT=(e,t,n)=>{let r=t.dVCM.add(t.dVC.mul(yT(n)));return _T(_T(yT(e)).mul(_T(t.vm?r.add(t.vm):r)))},wT=(e,t)=>(0,n.max)(e.mergeConst.add(e.mergeSlope.mul((0,n.length)(t.sub(e.cameraPosition)))),e.mergeMin),TT=(e,t)=>t.mul(t).mul(Math.PI).mul((0,n.float)(e.lightPaths)),ET=(e,t)=>{let n=TT(e,wT(e,t)).mul(e.mergeTrust);return n.mul(n)},DT=(e,t,n)=>_T(_T(e.dVCM.add(e.dVC.mul(yT(t)))).mul(n)),OT=(e,t)=>(0,n.float)(1).div((0,n.float)(1).add(_T(e)).add(_T(t))),kT={ALL:0,HIT:1,NEE:2,CONNECT:3,LIGHT_TRACE:4,MERGE:5},AT=(e,t,r,i=(0,n.float)(1))=>(0,n.select)(e.equal((0,n.uint)(kT.ALL)).or(e.equal((0,n.uint)(t))),r,(0,n.select)(e.equal((0,n.uint)(t+8)),i,(0,n.float)(0))),jT=(e,t)=>(0,n.select)(e.equal((0,n.int)(2)),(0,n.float)(.5),(0,n.select)(e.equal((0,n.int)(1)),(0,n.select)(t.lessThan(0),(0,n.float)(1),(0,n.float)(0)),(0,n.select)(t.greaterThan(0),(0,n.float)(1),(0,n.float)(0)))),MT=(e,t,r=1)=>(0,n.max)((0,n.dot)(e,Bl),0).div((0,n.max)(t,1e-10)).mul(r),NT=(e,t,r)=>e.sunPick.mul(r).div((0,n.max)(t.y,1e-30)),PT={SUN:0,EMITTERS:1,ENVIRONMENT:2,LAMPS:3},FT=(e,t)=>{let r=(0,n.int)(t);return e.sourceCdf.element(r).sub((0,n.select)(r.greaterThan((0,n.int)(0)),e.sourceCdf.element((0,n.max)(r.sub((0,n.int)(1)),(0,n.int)(0))),(0,n.float)(0)))},IT=(e,t,r)=>(0,n.select)(t.equal((0,n.int)(0)),(0,n.int)(e.sourceOffsets[0]),(0,n.select)(t.equal((0,n.int)(1)),(0,n.int)(e.sourceOffsets[1]),(0,n.select)(t.equal((0,n.int)(2)),(0,n.int)(e.sourceOffsets[2]),(0,n.int)(e.sourceOffsets[3])))).add(r),LT=(e,t)=>(0,n.select)(t.lessThan((0,n.int)(e.sourceOffsets[1])),(0,n.int)(0),(0,n.select)(t.lessThan((0,n.int)(e.sourceOffsets[2])),(0,n.int)(1),(0,n.select)(t.lessThan((0,n.int)(e.sourceOffsets[3])),(0,n.int)(2),(0,n.int)(3)))),RT=(e,t,r)=>t.sub((0,n.select)(r.equal((0,n.int)(0)),(0,n.int)(e.sourceOffsets[0]),(0,n.select)(r.equal((0,n.int)(1)),(0,n.int)(e.sourceOffsets[1]),(0,n.select)(r.equal((0,n.int)(2)),(0,n.int)(e.sourceOffsets[2]),(0,n.int)(e.sourceOffsets[3])))));function zT(e,t,r,i){let a=fl.wrap(fu((0,n.int)(e),i)).toVar();a.normalMapIndex.assign((0,n.int)(-1)),a.bumpMapIndex.assign((0,n.int)(-1)),a.displacementMapIndex.assign((0,n.int)(-1));let o=Cl.wrap(Np(a,t,r,(0,n.vec4)(0))).toVar(),s=o.roughness.toVar();a.color.assign(o.albedo),a.metalness.assign(o.metalness.clamp(0,1)),a.roughness.assign(o.roughness.clamp(Ll,1)),a.sheenRoughness.assign(a.sheenRoughness.clamp(.05,1));let c=yp({uv:t,transform:a.albedoTransform}).toVar();(0,n.If)(a.anisotropyMapIndex.greaterThanEqual((0,n.int)(0)),()=>{let e=Ap(a,c).toVar();a.anisotropy.assign(e.x),a.anisotropyRotation.assign(e.y)});let l=pl.wrap(jp(a,c)).toVar();return a.transmission.assign(l.transmission),a.clearcoat.assign(l.clearcoat),a.clearcoatRoughness.assign(l.clearcoatRoughness),a.sheenColor.assign(l.sheenColor),a.sheenRoughness.assign(l.sheenRoughness),a.iridescence.assign(l.iridescence),a.iridescenceThicknessRange.assign((0,n.vec2)(a.iridescenceThicknessRange.x,l.iridescenceThickness)),a.specularIntensity.assign(l.specularIntensity),a.specularColor.assign(l.specularColor),a.diffuseTransmission.assign(l.diffuseTransmission),a.diffuseTransmissionColor.assign(l.diffuseTransmissionColor),(0,n.If)(s.lessThan(Ll).and(a.anisotropy.equal(0)).and(a.clearcoat.equal(0)).and(a.transmission.equal(0)).and(a.subsurface.equal(0)),()=>{a.roughness.assign(0)}),a}var BT=(e,t,r)=>(0,n.select)(r.diffuseTransmission.greaterThan(0).and((0,n.dot)(e,t).lessThan(0)),e.negate(),e),VT=(e,t,r,i)=>(0,n.abs)((0,n.dot)(e,t)).mul((0,n.abs)((0,n.dot)(i,r))).div((0,n.max)((0,n.abs)((0,n.dot)(e,r)),1e-4)),HT=4096,UT=HT+1,WT=Math.ceil(UT*4/256)*64,GT=.2,KT=e=>{let t=(0,n.normalize)((0,n.cross)((0,n.select)((0,n.abs)(e.x).greaterThan(.9),(0,n.vec3)(0,1,0),(0,n.vec3)(1,0,0)),e)).toVar();return{u:t,v:(0,n.cross)(e,t).toVar()}},qT=e=>{let t=e.div((0,n.max)((0,n.abs)(e.x).add((0,n.abs)(e.y)).add((0,n.abs)(e.z)),1e-20)).toVar(),r=(0,n.vec2)(t.x,t.z).toVar();(0,n.If)(t.y.lessThan(0),()=>{r.assign((0,n.vec2)((0,n.float)(1).sub((0,n.abs)(t.z)).mul((0,n.select)(t.x.greaterThanEqual(0),1,-1)),(0,n.float)(1).sub((0,n.abs)(t.x)).mul((0,n.select)(t.z.greaterThanEqual(0),1,-1))))});let i=(0,n.floor)(r.mul(.5).add(.5).mul(4)).clamp(0,3);return(0,n.int)(i.y).mul(4).add((0,n.int)(i.x))},JT=(e,t,r)=>{let{u:i,v:a}=KT(t),o=r.sub(e.sceneCenter);return(0,n.vec2)((0,n.dot)(o,i),(0,n.dot)(o,a)).div(e.sceneRadius)},YT=e=>{let t=e.mul(.5).add(.5).mul(64).toVar();return(0,n.select)(t.x.greaterThanEqual(0).and(t.y.greaterThanEqual(0)).and(t.x.lessThan(64)).and(t.y.lessThan(64)),(0,n.int)(t.y).mul(64).add((0,n.int)(t.x)),(0,n.int)(-1))},XT=(e,t,r)=>e.guide.greaterThan((0,n.uint)(0)).and(t.load((0,n.ivec2)((0,n.int)(HT),r)).x.greaterThan(0)),ZT=(e,t,r,i)=>{let a=JT(e,r,i).toVar(),o=e.sceneRadius.mul(e.sceneRadius).toVar(),s=(0,n.select)((0,n.dot)(a,a).lessThanEqual(1),(0,n.float)(1).div((0,n.max)(o.mul(Math.PI),1e-30)),(0,n.float)(0)).toVar(),c=qT(r).toVar(),l=YT(a).toVar(),u=e=>t.load((0,n.ivec2)((0,n.max)(e,(0,n.int)(0)),c)).x,d=(0,n.select)(l.greaterThanEqual((0,n.int)(0)),u(l).sub((0,n.select)(l.greaterThan((0,n.int)(0)),u(l.sub((0,n.int)(1))),(0,n.float)(0))),(0,n.float)(0)).mul(HT/4).div((0,n.max)(o,1e-30));return(0,n.select)(XT(e,t,c),(0,n.mix)(d,s,GT),s)},QT=(e,t,r,i,a)=>{let{u:o,v:s}=KT(r),c=(0,n.vec2)(0).toVar(),l=qT(r).toVar();return(0,n.If)(XT(e,t,l).and(i.lessThan(1-GT)),()=>{let e=i.div(1-GT).toVar(),r=(0,n.int)(0).toVar(),o=(0,n.int)(HT-1).toVar();(0,n.Loop)(r.lessThan(o),()=>{let i=r.add(o).div(2).toVar();(0,n.If)(t.load((0,n.ivec2)(i,l)).x.lessThanEqual(e),()=>{r.assign(i.add(1))}).Else(()=>{o.assign(i)})});let s=(0,n.vec2)((0,n.float)(r.mod((0,n.int)(64))),(0,n.float)(r.div((0,n.int)(64))));c.assign(s.add(a).div(64).mul(2).sub(1))}).Else(()=>{let e=(0,n.sqrt)(a.x),t=a.y.mul(2*Math.PI);c.assign((0,n.vec2)(e.mul((0,n.cos)(t)),e.mul((0,n.sin)(t))))}),e.sceneCenter.add(r.mul(e.sceneRadius)).add(o.mul(c.x).add(s.mul(c.y)).mul(e.sceneRadius))},$T=(e,t,r,i)=>{let a=YT(JT(t,r,i)).toVar();(0,n.If)(t.guideLearning.greaterThan((0,n.uint)(0)).and(a.greaterThanEqual((0,n.int)(0))),()=>{(0,n.atomicAdd)(e.element((0,n.uint)(Z.GUIDE).add((0,n.uint)(qT(r).mul((0,n.int)(HT)).add(a)))),(0,n.uint)(1))})};function eE({counters:e,out:t}){return(0,n.Fn)(()=>{let r=n.instanceIndex;(0,n.If)(r.greaterThanEqual((0,n.uint)(16)),()=>{(0,n.Return)()});let i=(0,n.uint)(Z.GUIDE).add(r.mul((0,n.uint)(HT))).toVar(),a=(0,n.float)(0).toVar();(0,n.Loop)({start:(0,n.int)(0),end:(0,n.int)(HT),type:`int`,condition:`<`},({i:t})=>{a.addAssign((0,n.float)((0,n.atomicLoad)(e.element(i.add((0,n.uint)(t))))))});let o=r.mul((0,n.uint)(WT)).toVar(),s=(0,n.float)(0).toVar();(0,n.Loop)({start:(0,n.int)(0),end:(0,n.int)(HT),type:`int`,condition:`<`},({i:r})=>{s.addAssign((0,n.float)((0,n.atomicLoad)(e.element(i.add((0,n.uint)(r)))))),t.element(o.add((0,n.uint)(r))).assign((0,n.select)(a.greaterThan(0),(0,n.select)(r.equal((0,n.int)(HT-1)),(0,n.float)(1),s.div(a)),(0,n.float)(0)))}),t.element(o.add((0,n.uint)(HT))).assign(a)})().compute(16,[16])}function tE({counters:e}){return(0,n.Fn)(()=>{(0,n.If)(n.instanceIndex.lessThan((0,n.uint)(Ud)),()=>{(0,n.atomicStore)(e.element((0,n.uint)(Z.GUIDE).add(n.instanceIndex)),(0,n.uint)(0))})})().compute(Ud,[256])}xu(),Vd();function nE(e){let{rayBufferRW:t,hitBufferRW:r,activeIndicesRW:i,counters:a,lightBuffer:o,triangleBuffer:s,bvhBuffer:c,emissiveTriangleCount:l,emissiveVec4Offset:u,emissiveTotalPower:d,emissiveBoost:f,sunDirection:p,sunRadiance:m,sunParams:h,environmentIntensity:g,envTexture:_,envCDFTexture:v,envMatrix:y,envResolution:b,directionalLightsBuffer:x,areaLightsBuffer:S,pointLightsBuffer:C,spotLightsBuffer:w,bidirectional:T,resolution:E,frame:D,transmissiveBounces:O}=e,{lightPaths:k}=T;return(0,n.Fn)(()=>{let e=n.instanceIndex;(0,n.If)(e.equal((0,n.uint)(0)),()=>{(0,n.atomicStore)(a.element((0,n.uint)(Z.ACTIVE_RAY_COUNT)),k),(0,n.atomicStore)(a.element((0,n.uint)(Z.ENTERING_COUNT)),k)}),(0,n.If)(e.greaterThanEqual(k),()=>{(0,n.Return)()}),i.element(e).assign(e);let A=vT(e,E).toVar(),j=Be({state:nt({pixelCoord:A,rayIndex:(0,n.int)(3),frame:D})}).toVar(),M=(0,n.vec3)(0).toVar(),N=(0,n.vec3)(0,1,0).toVar(),P=(0,n.vec3)(0).toVar(),F=(0,n.float)(0).toVar(),I=(0,n.float)(0).toVar(),L=(0,n.int)(-1).toVar(),ee=(0,n.int)(0).toVar(),te=(0,n.float)(1).toVar(),R=(0,n.bool)(!1).toVar(),ne=et(A,(0,n.int)(0),(0,n.int)(dT+4),j,E,D).toVar(),re=(0,n.int)(0).toVar(),ie=(0,n.int)(T.sourceCount-1).toVar();(0,n.Loop)(re.lessThan(ie),()=>{let e=re.add(ie).div(2).toVar();(0,n.If)(T.sourceCdf.element(e).lessThanEqual(ne),()=>{re.assign(e.add(1))}).Else(()=>{ie.assign(e)})});let ae=T.guideTexture,oe=e=>{let t=QT(T,ae,e,et(A,(0,n.int)(0),(0,n.int)(dT+7),j,E,D),$e(A,(0,n.int)(0),(0,n.int)(dT+6),j,E,D)).toVar();return{start:t,pdf:ZT(T,ae,e,t)}};(0,n.If)(re.equal((0,n.int)(PT.SUN)),()=>{let e=jh(p,h,$e(A,(0,n.int)(0),(0,n.int)(dT+5),j,E,D)).toVar(),t=Ah(e,p,m,h).mul(g).toVar(),r=oe(e),i=NT(T,h,r.pdf).toVar();(0,n.If)(t.x.add(t.y).add(t.z).greaterThan(0).and(i.greaterThan(0)),()=>{M.assign(r.start),N.assign(e.negate()),P.assign(t.div(i)),F.assign(yT((0,n.float)(1).div(h.y.mul(i)))),I.assign(yT((0,n.float)(1).div(i))),R.assign(!0)})}).ElseIf(re.equal((0,n.int)(PT.EMITTERS)),()=>{let e=Kg(o,u,l,et(A,(0,n.int)(0),(0,n.int)(dT),j,E,D)).toVar(),t=u.add(e.mul((0,n.int)(2))),r=o.element(t).toVar(),i=o.element(t.add((0,n.int)(1))).toVar();L.assign((0,n.int)(r.x)),ee.assign((0,n.int)(r.w));let a=Ug.wrap(Wg(L,s,c,ee)).toVar(),p=Ng(a.v0,a.v1,a.v2,$e(A,(0,n.int)(0),(0,n.int)(dT+1),j,E,D)).toVar(),m=(0,n.normalize)((0,n.cross)(a.v1.sub(a.v0),a.v2.sub(a.v0))).toVar(),h=Pf(cu(s,L,4).z).toVar(),g=(0,n.select)(h.equal((0,n.int)(1)).or(h.equal((0,n.int)(2)).and(et(A,(0,n.int)(0),(0,n.int)(dT+3),j,E,D).lessThan(.5))).toVar(),m.negate(),m).toVar();N.assign(cp(g,$e(A,(0,n.int)(0),(0,n.int)(dT+2),j,E,D)));let _=(0,n.dot)(N,g).toVar(),v=(0,n.max)(r.y,0).div((0,n.max)(d,1e-10)).div((0,n.max)(i.w,1e-20)).mul((0,n.select)(h.equal((0,n.int)(2)),(0,n.float)(.5),(0,n.float)(1))).mul(T.emitterPick).toVar(),y=v.mul(_).div(Math.PI).toVar();(0,n.If)(_.greaterThan(1e-6).and(y.greaterThan(0)),()=>{M.assign(jl(p,g)),P.assign(i.xyz.mul(f).mul(Math.PI).div(v)),F.assign(yT((0,n.float)(1).div(y))),I.assign(yT(_.div(y))),te.assign(_),R.assign(!0)})}).ElseIf(re.equal((0,n.int)(PT.ENVIRONMENT)),()=>{let e=tp(v,y,b,$e(A,(0,n.int)(0),(0,n.int)(dT+5),j,E,D)),t=e.direction.toVar(),r=e.pdf.toVar(),i=rp({tex:_,samp:(0,n.sampler)(_),direction:t,environmentMatrix:y,environmentIntensity:g,enableEnvironmentLight:(0,n.float)(1)}).xyz.toVar(),a=oe(t),o=T.envPick.mul(r).mul(a.pdf).toVar();(0,n.If)(i.x.add(i.y).add(i.z).greaterThan(0).and(o.greaterThan(0)),()=>{M.assign(a.start),N.assign(t.negate()),P.assign(i.div(o)),F.assign(yT(r.div(o))),I.assign(yT((0,n.float)(1).div(o))),L.assign((0,n.int)(-1-PT.ENVIRONMENT)),R.assign(!0)})}).ElseIf(re.greaterThanEqual((0,n.int)(PT.LAMPS)),()=>{let e=FT(T,re).toVar(),t=LT(T,re).toVar(),r=RT(T,re,t).toVar();L.assign((0,n.int)(-1).sub(re));let i=(0,n.float)(0).toVar(),a=(0,n.vec3)(0).toVar(),o=$e(A,(0,n.int)(0),(0,n.int)(dT+2),j,E,D).toVar();(0,n.If)(t.equal((0,n.int)(0)),()=>{let t=Nm.wrap(zm(x,r)),o=(0,n.normalize)(t.direction).toVar();a.assign(t.color.mul(t.intensity)),i.assign(e),(0,n.If)(t.angle.greaterThan(0),()=>{let e=cT(t).toVar();o.assign(Ym(o,t.angle.mul(.5),$e(A,(0,n.int)(0),(0,n.int)(dT+5),j,E,D))),a.divAssign(e),i.divAssign(e)});let s=oe(o);i.mulAssign(s.pdf),M.assign(s.start),N.assign(o.negate())}).ElseIf(t.equal((0,n.int)(1)),()=>{let t=Pm.wrap(Bm(S,r)),s=t.shape.greaterThan(.5),c=$e(A,(0,n.int)(0),(0,n.int)(dT+1),j,E,D).toVar(),l=(0,n.sqrt)(c.x),u=c.y.mul(2*Math.PI);M.assign(t.position.add(t.u.mul((0,n.select)(s,l.mul((0,n.cos)(u)),c.x.mul(2).sub(1)))).add(t.v.mul((0,n.select)(s,l.mul((0,n.sin)(u)),c.y.mul(2).sub(1))))),N.assign(cp(t.normal,o));let d=(0,n.dot)(N,t.normal).toVar();a.assign((0,n.select)(t.area.greaterThan(0).and(d.greaterThan(1e-6)),Jh(t).mul(qh(d,t.spread)).mul(d),(0,n.vec3)(0))),i.assign(e.div((0,n.max)(t.area,1e-20)).mul(d).div(Math.PI)),I.assign(yT(d.div((0,n.max)(i,1e-30))))}).ElseIf(t.equal((0,n.int)(2)),()=>{let t=Fm.wrap(Vm(C,r));M.assign(t.position),N.assign(Ym((0,n.vec3)(0,1,0),(0,n.float)(Math.PI),o)),a.assign(t.color.mul(t.intensity)),i.assign(e.div(4*Math.PI))}).Else(()=>{let t=Im.wrap(Hm(w,r));M.assign(t.position),N.assign(Ym(t.direction,t.angle,o));let s=N.negate();a.assign(t.color.mul(t.intensity).mul(Gm({coneCosine:(0,n.cos)(t.angle),blend:t.penumbra,angleCosine:(0,n.dot)(N,t.direction)})).mul(Km(t,s)).mul(Jm(t,s))),i.assign(e.div(sT(t)))}),(0,n.If)(a.x.add(a.y).add(a.z).greaterThan(0).and(i.greaterThan(0)),()=>{P.assign(a.div(i)),F.assign(yT((0,n.float)(1).div(i))),R.assign(!0)})}),(0,n.If)(R.not(),()=>{td(t,e,N,(0,n.uint)(0)),(0,n.Return)()});let se=(0,n.max)((0,n.max)((0,n.max)(P.x,P.y),P.z),1e-20).toVar();ed(t,e,M,(0,n.int)(0),(0,n.int)(0)),td(t,e,N,(0,n.uint)(Q.ACTIVE|Q.REDIRECTED|Q.LIGHT_PATH|Q.LIGHT_EMITTED)),nd(t,e,P.div(se),(0,n.float)(0)),rd(t,e,(0,n.vec4)((0,n.vec3)(0),(0,n.float)(1))),kd(t,e,(0,n.uint)(0),(0,n.uint)(O),(0,n.float)(1),(0,n.float)(1),(0,n.float)(1)),md(r,e,j,F,I),Td(r,e,L,ee,te,se)})}xu(),Vd();function rE(e){let{rayBufferRW:t,hitBufferRO:r,activeIndicesRO:i,counters:a,bvhBuffer:o,triangleBuffer:s,materialBuffer:c,resolution:l,frame:u,accumFrame:d,currentBounce:f,chunkRowBase:p,lightPaths:m,slotsPerPath:h,lightTag:g,passTag:_,strategyView:v,maxBounceCount:y,globalIlluminationIntensity:b,fireflyThreshold:x,mergeVm:S=null,diffuseTransmission:C=!0}=e;return(0,n.Fn)(()=>{let e=n.instanceIndex;(0,n.If)(e.greaterThanEqual((0,n.atomicLoad)(a.element((0,n.uint)(Z.ENTERING_COUNT)))),()=>{(0,n.Return)()});let w=i.element(e).toVar(),T=hd(w);(0,n.If)(vd(r,T).notEqual(_),()=>{(0,n.Return)()});let E=Sd(r,T),D={...E,vm:S?.(E.position)??null},O=(0,n.int)(D.extra).add((0,n.int)(1)).toVar(),k=(0,n.int)(l.x),A=(0,n.int)(w).add(p.mul(k)),j=(0,n.vec2)((0,n.float)(A.mod(k)).add(.5),(0,n.float)(A.div(k)).add(.5)).toVar(),M=(0,n.int)(f).mul((0,n.int)(32)),N=Be({state:dd(r,w).bitXor((0,n.uint)(2654435769))}).toVar(),P=et(j,(0,n.int)(0),M.add((0,n.int)(16)),N,l,u).toVar(),F=et(j,(0,n.int)(0),M.add((0,n.int)(17)),N,l,u).toVar(),I=(0,n.min)((0,n.uint)((0,n.float)(m).mul(P)),m.sub((0,n.uint)(1))).toVar().mul(h).toVar(),L=(0,n.min)((0,n.int)(Cd(r,gd(I),g)),(0,n.int)(y).add((0,n.int)(1)).sub(O)).toVar();(0,n.If)(L.lessThan((0,n.int)(1)),()=>{(0,n.Return)()});let ee=(0,n.min)((0,n.int)((0,n.float)(L).mul(F)),L.sub((0,n.int)(1))).toVar(),te=Sd(r,gd(I.add((0,n.uint)(ee)))),R={...te,vm:S?.(te.position)??null},ne=R.position.sub(D.position).toVar(),re=(0,n.max)((0,n.dot)(ne,ne),1e-12).toVar(),ie=ne.div((0,n.sqrt)(re)).toVar(),ae=(0,n.dot)(ie,D.N).toVar(),oe=(0,n.dot)(ie,D.facetN).toVar(),se=(0,n.dot)(ie,R.facetN).negate().toVar(),ce=ae.greaterThan(0).and(oe.greaterThan(0)).and(se.greaterThan(0)),le=ae.lessThan(0).and(oe.lessThan(0)),z=se.lessThan(0);(0,n.If)((C?le.or(ae.greaterThan(0).and(oe.greaterThan(0))).and(z.or(se.greaterThan(0))):ce).not(),()=>{(0,n.Return)()});let ue=zT(D.materialIndex,D.uv,D.N,c),de=zT(R.materialIndex,R.uv,R.N,c),fe=ie.negate();C&&(0,n.If)(le.and(ue.diffuseTransmission.lessThanEqual(0)).or(z.and(de.diffuseTransmission.lessThanEqual(0))),()=>{(0,n.Return)()});let pe=e=>C?BT(D.N,e,ue):D.N,me=e=>C?BT(R.N,e,de):R.N,he=Mm(D.V,ie,D.N,ue).toVar(),ge=Mm(fe,R.V,me(fe),de).toVar(),_e=(C?(0,n.abs)(ae):ae).mul(VT(R.V,R.N,R.facetN,fe)).div(re),ve=ng(D.V,ie,D.N,ue),ye=ng(ie,D.V,pe(ie),ue),be=ng(R.V,fe,R.N,de),xe=ng(fe,R.V,me(fe),de),Se=CT(ve.mul(C?(0,n.abs)(se):se).div(re),R,xe),Ce=CT(be.mul(C?(0,n.abs)(oe):oe).div(re),D,ye),we=O.add(ee).add((0,n.int)(1)),B=AT(v,kT.CONNECT,OT(Se,Ce),(0,n.float)(1).div((0,n.float)(we.sub((0,n.int)(1))))),Te=gg(D.throughput.mul(he).mul(ge).mul(R.throughput).mul(_e.mul(B).mul((0,n.float)(L)).mul(b)),(0,n.float)(we.sub((0,n.int)(1))),x,(0,n.int)(d)).toVar();(0,n.If)(Yl(Te).greaterThan(0),()=>{let e=jl(D.position,C?(0,n.select)(le,D.facetN.negate(),D.facetN):D.facetN).toVar(),r=jl(R.position,C?(0,n.select)(z,R.facetN.negate(),R.facetN):R.facetN).sub(e).toVar(),i=(0,n.length)(r).toVar(),a=bh(e,r.div(i),i.mul(Ml),Bf,o,s,c);(0,n.If)(a.greaterThan(0),()=>{let e=Wu(t,w).toVar();rd(t,w,(0,n.vec4)(e.xyz.add(Te.mul(a)),e.w))})})})}xu(),Vd();var iE=4294967295,aE=1024,oE=Math.log2(1.25),sE=(e,t)=>(0,n.int)((0,n.max)((0,n.floor)((0,n.log2)(t.div(e.mergeMin)).div(oE)),0)),cE=(e,t)=>e.mergeMin.mul((0,n.exp2)((0,n.float)(t.add((0,n.int)(1))).mul(oE))).mul(2).div((0,n.max)((0,n.float)(1).sub(e.mergeSlope),.5)),lE=(e,t,r)=>(0,n.uint)(t.x).mul((0,n.uint)(73856093)).bitXor((0,n.uint)(t.y).mul((0,n.uint)(19349663))).bitXor((0,n.uint)(t.z).mul((0,n.uint)(83492791))).bitXor((0,n.uint)(e).mul((0,n.uint)(2654435761))).bitAnd(r),uE=(e,t)=>{let r=sE(e,wT(e,t)).toVar();return{shell:r,cell:(0,n.ivec3)((0,n.floor)(t.div(cE(e,r)))).toVar()}};function dE({head:e,hashSize:t}){return(0,n.Fn)(()=>{(0,n.If)(n.instanceIndex.lessThan((0,n.uint)(t)),()=>{(0,n.atomicStore)(e.element(n.instanceIndex),(0,n.uint)(iE))})})().compute(Math.ceil(t/256)*256,[256])}function fE({hitBufferRW:e,head:t,bidirectional:r}){let{lightPaths:i,slotsPerPath:a,lightTag:o,hashMask:s}=r;return(0,n.Fn)(()=>{let c=n.instanceIndex.toVar();(0,n.If)(c.greaterThanEqual(i.mul(a)),()=>{(0,n.Return)()});let l=c.mod(a).toVar();(0,n.If)(l.greaterThanEqual(Cd(e,gd(c.sub(l)),o)),()=>{(0,n.Return)()});let u=gd(c),{shell:d,cell:f}=uE(r,yd(e,u)),p=lE(d,f,s);xd(e,u,(0,n.atomicFunc)(`atomicExchange`,t.element(p),c))})}function pE(e){let{rayBufferRW:t,hitBufferRO:r,activeIndicesRO:i,counters:a,head:o,materialBuffer:s,bidirectional:c,maxBounceCount:l,globalIlluminationIntensity:u,fireflyThreshold:d,accumFrame:f,diffuseTransmission:p=!0}=e,{passTag:m,slotsPerPath:h,strategyView:g,hashMask:_}=c;return(0,n.Fn)(()=>{let e=n.instanceIndex;(0,n.If)(e.greaterThanEqual((0,n.atomicLoad)(a.element((0,n.uint)(Z.ENTERING_COUNT)))),()=>{(0,n.Return)()});let v=i.element(e).toVar(),y=hd(v);(0,n.If)(vd(r,y).notEqual(m),()=>{(0,n.Return)()});let b=Sd(r,y),x=(0,n.int)(b.extra).toVar(),S=(0,n.int)(l).add((0,n.int)(1)).sub(x).toVar(),C=zT(b.materialIndex,b.uv,b.N,s),w=(0,n.vec3)(0).toVar(),T=wT(c,b.position).toVar(),E=T.mul(T).toVar(),D=TT(c,T).toVar(),O=D.mul(c.mergeTrust),k=(0,n.float)(1).div((0,n.max)(O.mul(O),1e-30)).toVar(),A=(0,n.length)(b.position.sub(c.cameraPosition)).toVar(),j=sE(c,(0,n.max)(c.mergeConst.add(c.mergeSlope.mul((0,n.max)(A.sub(T),0))),c.mergeMin)).toVar(),M=(0,n.min)(sE(c,c.mergeConst.add(c.mergeSlope.mul(A.add(T)))),j.add((0,n.int)(1))).toVar();(0,n.Loop)({start:(0,n.int)(0),end:(0,n.int)(16),type:`int`,condition:`<`},({i:e})=>{let t=j.add(e.shiftRight((0,n.int)(3))).toVar();(0,n.If)(t.greaterThan(M),()=>{(0,n.Break)()});let i=cE(c,t).toVar(),a=e.bitAnd((0,n.int)(7)),s=(0,n.ivec3)((0,n.floor)(b.position.div(i).sub(.5))).add((0,n.ivec3)(a.bitAnd((0,n.int)(1)),a.shiftRight((0,n.int)(1)).bitAnd((0,n.int)(1)),a.shiftRight((0,n.int)(2)))).toVar(),l=(0,n.atomicLoad)(o.element(lE(t,s,_))).toVar(),m=(0,n.int)(0).toVar();(0,n.Loop)(l.notEqual((0,n.uint)(iE)).and(m.lessThan((0,n.int)(aE))),()=>{let e=gd(l),i=yd(r,e).toVar(),a=i.sub(b.position),o=(0,n.int)(l.mod(h)).add((0,n.int)(1)).toVar();(0,n.If)((0,n.dot)(a,a).lessThan(E).and(o.lessThanEqual(S)),()=>{let a=uE(c,i);(0,n.If)(a.shell.equal(t).and(a.cell.x.equal(s.x)).and(a.cell.y.equal(s.y)).and(a.cell.z.equal(s.z)),()=>{let t=Sd(r,e),i=(0,n.dot)(t.V,b.N).toVar(),a=(0,n.dot)(t.V,b.facetN).toVar(),s=i.greaterThan(0).and(a.greaterThan(0)),c=C.diffuseTransmission.greaterThan(0).and(i.lessThan(0)).and(a.lessThan(0));(0,n.If)(p?s.or(c):s,()=>{let e=Mm(b.V,t.V,b.N,C),r=DT(t,ng(b.V,t.V,b.N,C),k),s=p?BT(b.N,t.V,C):b.N,c=DT(b,ng(t.V,b.V,s,C),k),l=x.add(o),m=AT(g,kT.MERGE,OT(r,c),(0,n.float)(1).div((0,n.float)(l))),h=(0,n.select)(l.greaterThan((0,n.int)(1)),u,(0,n.float)(1)),_=p?(0,n.abs)(i).div((0,n.max)((0,n.abs)(a),1e-4)):i.div((0,n.max)(a,1e-4));w.addAssign(gg(b.throughput.mul(e).mul(t.throughput).mul(m.mul(_).div(D).mul(h)),(0,n.float)(l.sub((0,n.int)(1))),d,(0,n.int)(f)))})})}),l.assign(bd(r,e)),m.addAssign((0,n.int)(1))})}),(0,n.If)(Yl(w).greaterThan(0),()=>{let e=Wu(t,v).toVar();rd(t,v,(0,n.vec4)(e.xyz.add(w),e.w))})})}xu(),Vd();function mE(e){let{hitBufferRO:t,splatBuffer:r,bvhBuffer:i,triangleBuffer:a,materialBuffer:o,lightPaths:s,slotsPerPath:c,lightTag:l,strategyView:u,cameraPosition:d,cameraForward:f,cameraClipStart:p,cameraViewMatrix:m,cameraProjectionMatrix:h,pixelArea:g,renderWidth:_,renderHeight:v,globalIlluminationIntensity:y,fireflyThreshold:b,accumFrame:x,frame:S,mergeVm:C=null,diffuseTransmission:w=!0}=e;return(0,n.Fn)(()=>{let e=n.instanceIndex.toVar();(0,n.If)(e.greaterThanEqual(s.mul(c)),()=>{(0,n.Return)()});let T=e.mod(c).toVar(),E=Cd(t,gd(e.sub(T)),l);(0,n.If)(T.greaterThanEqual(E),()=>{(0,n.Return)()});let D=Sd(t,gd(e)),O={...D,vm:C?.(D.position)??null},k=d.sub(O.position).toVar(),A=(0,n.max)((0,n.dot)(k,k),1e-12).toVar(),j=k.div((0,n.sqrt)(A)).toVar(),M=(0,n.dot)(j,O.facetN).toVar(),N=(0,n.dot)(j,f).negate().toVar(),P=M.lessThan(0),F=w?(0,n.select)(P,O.extra.bitAnd((0,n.uint)(2)),O.extra.bitAnd((0,n.uint)(1))).notEqual((0,n.uint)(0)):O.extra.notEqual((0,n.uint)(0)),I=p.div((0,n.max)(N,1e-6)).toVar();(0,n.If)((w?M.equal(0):M.lessThanEqual(0)).or(N.lessThanEqual(1e-6)).or(F).or(A.lessThanEqual(I.mul(I))),()=>{(0,n.Return)()});let L=h.mul(m.mul((0,n.vec4)(O.position,1))).toVar();(0,n.If)(L.w.lessThanEqual(0),()=>{(0,n.Return)()});let ee=(0,n.floor)(L.x.div(L.w).mul(.5).add(.5).mul((0,n.float)(_))).toVar(),te=(0,n.floor)((0,n.float)(.5).sub(L.y.div(L.w).mul(.5)).mul((0,n.float)(v))).toVar();(0,n.If)(ee.lessThan(0).or(te.lessThan(0)).or(ee.greaterThanEqual((0,n.float)(_))).or(te.greaterThanEqual((0,n.float)(v))),()=>{(0,n.Return)()});let R=zT(O.materialIndex,O.uv,O.N,o);w&&(0,n.If)(P.and(R.diffuseTransmission.lessThanEqual(0)),()=>{(0,n.Return)()});let ne=w?BT(O.N,j,R):O.N,re=Mm(j,O.V,ne,R).toVar(),ie=(0,n.float)(1).div(g.mul(N).mul(N).mul(N)).div(A).toVar(),ae=CT(ie.mul(w?(0,n.abs)(M):M).div((0,n.float)(s)),O,ng(j,O.V,ne,R)),oe=T.add((0,n.uint)(1)),se=(0,n.float)(1).toVar();(0,n.If)(oe.greaterThan((0,n.uint)(1)),()=>{se.assign(y)});let ce=gg(O.throughput.mul(re).mul(VT(O.V,O.N,O.facetN,j)).mul(ie.div((0,n.float)(s)).mul(AT(u,kT.LIGHT_TRACE,OT(ae,(0,n.float)(0)))).mul(se)),(0,n.float)(T),b,(0,n.int)(x)).toVar(),le=jl(O.position,w?(0,n.select)(P,O.facetN.negate(),O.facetN):O.facetN).toVar(),z=d.sub(le).toVar(),ue=(0,n.length)(z).toVar(),de=bh(le,z.div(ue),ue.sub(I).mul(Ml),Vf,i,a,o);(0,n.If)(de.greaterThan(0),()=>{let t=(0,n.min)(Ul(ce.mul(de)),(0,n.vec3)(mT)).mul(pT).toVar(),i=(0,n.float)(Be({state:e.bitXor((0,n.uint)(S).mul((0,n.uint)(2654435769)))}).shiftRight((0,n.uint)(8))).mul(1/16777216).toVar(),a=(0,n.uint)(te).mul((0,n.uint)(_)).add((0,n.uint)(ee)).mul((0,n.uint)(3)).toVar();(0,n.atomicAdd)(r.element(a),(0,n.uint)((0,n.floor)(t.x.add(i)))),(0,n.atomicAdd)(r.element(a.add((0,n.uint)(1))),(0,n.uint)((0,n.floor)(t.y.add(i)))),(0,n.atomicAdd)(r.element(a.add((0,n.uint)(2))),(0,n.uint)((0,n.floor)(t.z.add(i))))})})}function hE(e){let{rayBufferRW:t,splatBuffer:r,renderWidth:i,chunkRowBase:a,chunkRows:o}=e;return(0,n.Fn)(()=>{let e=(0,n.int)(n.workgroupId.x).mul(16).add((0,n.int)(n.localId.x)),s=(0,n.int)(n.workgroupId.y).mul(16).add((0,n.int)(n.localId.y));(0,n.If)(e.lessThan(i).and(s.lessThan(o)),()=>{let o=(0,n.uint)(s.mul(i).add(e)),c=(0,n.uint)(s.add(a).mul(i).add(e)).mul((0,n.uint)(3)).toVar(),l=(0,n.atomicLoad)(r.element(c)).toVar(),u=(0,n.atomicLoad)(r.element(c.add((0,n.uint)(1)))).toVar(),d=(0,n.atomicLoad)(r.element(c.add((0,n.uint)(2)))).toVar();(0,n.If)(l.bitOr(u).bitOr(d).notEqual((0,n.uint)(0)),()=>{(0,n.atomicStore)(r.element(c),(0,n.uint)(0)),(0,n.atomicStore)(r.element(c.add((0,n.uint)(1))),(0,n.uint)(0)),(0,n.atomicStore)(r.element(c.add((0,n.uint)(2))),(0,n.uint)(0));let e=Wu(t,o).toVar();rd(t,o,(0,n.vec4)(e.xyz.add((0,n.vec3)((0,n.float)(l),(0,n.float)(u),(0,n.float)(d)).div(pT)),e.w))})})})}O(),Vd(),lt(),Ft();var{PASS_TAG_BIT:gE,STRATEGY:_E,STRATEGY_ALONE:vE,SOURCE:yE,mergeVmAt:bE}=uT,xE={...uT,...$w,guidedDiscPdf:ZT,recordEscape:$T},SE=256*1024*1024,CE=.05,wE=.5,TE=(1<<24)-1,EE=1,DE=.75,OE=.25,kE=class{constructor(e){this.pt=e,this.merging=!1,this._mergeRadiusPixels=EE,this._mergeHeadAttr=null,this._lightCacheSlots=0,this._splatAttr=null,this._lightTag=0,this._passTag=0,this._lightTraced=!1,this._lastLightBounceCounts=null,this._lastLightBounceEnergy=null,this._lastLightCurveKey=null,this._lightCurveKey=null,this.uniforms={lib:xE,lightPaths:(0,n.uniform)(0,`uint`),slotsPerPath:(0,n.uniform)(1,`uint`),lightTag:(0,n.uniform)(1,`uint`),passTag:(0,n.uniform)(0,`uint`),lightTrace:(0,n.uniform)(0,`uint`),strategyView:(0,n.uniform)(0,`uint`),pixelArea:(0,n.uniform)(1,`float`),cameraPosition:(0,n.uniform)(new r.Vector3,`vec3`),cameraForward:(0,n.uniform)(new r.Vector3(0,0,-1),`vec3`),sunPick:(0,n.uniform)(0,`float`),emitterPick:(0,n.uniform)(0,`float`),envPick:(0,n.uniform)(0,`float`),envTable:(0,n.uniform)(0,`uint`),sourceCdf:(0,n.uniformArray)(new Float32Array(yE.LAMPS),`float`),sourceCount:yE.LAMPS,sourceOffsets:[yE.LAMPS,yE.LAMPS,yE.LAMPS,yE.LAMPS],sceneCenter:(0,n.uniform)(new r.Vector3,`vec3`),sceneRadius:(0,n.uniform)(1,`float`),guide:(0,n.uniform)(0,`uint`),guideLearning:(0,n.uniform)(1,`uint`),guideTexture:null,merging:!1,mergeConst:(0,n.uniform)(0,`float`),mergeSlope:(0,n.uniform)(0,`float`),mergeMin:(0,n.uniform)(1,`float`),mergeTrust:(0,n.uniform)(OE,`float`),hashMask:(0,n.uniform)(0,`uint`)},this._lightGuiding=!0,this._guideTexture=null,this._guideBuildAttr=null,this._u32Views=new WeakMap}get name(){return this.merging?`vcm`:`bidirectional`}select(e){this.merging=e===`vcm`,this.uniforms.merging=this.merging,this._lastLightCurveKey=null}get hitStride(){return 7}cacheBytes(e,t){let n=Math.floor(Math.min(SE,e*.45,t*.05)/64)*64;return this._lightCacheSlots=n/64,n}get lightVertices(){return this._lightCacheSlots}beforeKernelBuild(){this._sizeSourceTable()}allocate(e){(!this._splatAttr||this._splatAttr.count<e*3)&&(Au(this.pt.renderer,this._splatAttr),this._splatAttr=v(e*3,1,Uint32Array));let t=this.merging?2**Math.ceil(Math.log2(Math.max(this._lightCacheSlots,1024))):0;this._mergeHeadAttr?.count!==t&&(Au(this.pt.renderer,this._mergeHeadAttr),this._mergeHeadAttr=t>0?v(t,1,Uint32Array):null),this.uniforms.hashMask.value=Math.max(t-1,0),this._guideTexture||(this._guideTexture=new r.DataTexture(null,UT,16,r.RedFormat,r.FloatType),this._guideTexture.source.dataReady=!1,this._guideTexture.needsUpdate=!0,this._guideBuildAttr=v(WT*16,1,Float32Array)),this.uniforms.guideTexture=(0,n.texture)(this._guideTexture),this.uniforms.guide.value=0}registerKernels(e){let{km:t,qm:r,pb:i,counters:a,bounceCountsBuf:o,wfCurrentBounce:s,copyReadB:c,copyWriteA:l,maxRays:u,w:d,own:f,freshLight:p,freshTri:m,freshBvh:h,freshMat:g,freshEnvTex:_,freshEnvCDF:v,materialLayers:y}=e,b=y?.diffuseTransmission??!0,x=this.uniforms,S=r.MAX_BOUNCE_SNAPSHOTS,C=e=>{let t=(0,n.uint)(s).clamp((0,n.uint)(0),(0,n.uint)(S-1));o.element(t.add((0,n.uint)(2*S))).assign(e),o.element(t.add((0,n.uint)(3*S))).assign((0,n.atomicLoad)(a.element((0,n.uint)(Z.ACTIVE_ENERGY)))),(0,n.atomicStore)(a.element((0,n.uint)(Z.ENTERING_COUNT)),e)};if(t.register(`lightSnapshot`,(0,n.Fn)(()=>{C((0,n.atomicLoad)(a.element((0,n.uint)(Z.ACTIVE_RAY_COUNT))))})().compute([1,1,1],[1,1,1])),t.register(`lightCopyback`,(0,n.Fn)(()=>{let e=n.instanceIndex,t=(0,n.atomicLoad)(a.element((0,n.uint)(Z.ACTIVE_RAY_COUNT)));(0,n.If)(e.equal((0,n.uint)(0)),()=>{C(t)}),(0,n.If)(e.greaterThanEqual(t),()=>{(0,n.Return)()}),l.element(e).assign(c.element(e))})().compute([Math.ceil(u/256),1,1],[256,1,1])),t.register(`guideClear`,tE({counters:a})),t.register(`guideBuild`,eE({counters:a,out:(0,n.storage)(this._guideBuildAttr,`float`)})),t.register(`lightGenerate`,f(nE({rayBufferRW:i.rayBuffer.rw,hitBufferRW:i.hitBuffer.rw,activeIndicesRW:r.activeIndices.a,counters:a,lightBuffer:p,triangleBuffer:m,bvhBuffer:h,emissiveTriangleCount:this.pt.emissiveTriangleCount,emissiveVec4Offset:this.pt.emissiveVec4Offset,emissiveTotalPower:this.pt.emissiveTotalPower,emissiveBoost:this.pt.emissiveBoost,sunDirection:this.pt.sunDirection,sunRadiance:this.pt.sunRadiance,sunParams:this.pt.sunParams,environmentIntensity:this.pt.environmentIntensity,envTexture:_,envCDFTexture:v,envMatrix:this.pt.environmentMatrix,envResolution:this.pt.envResolution,directionalLightsBuffer:this.pt.directionalLightsBufferNode,areaLightsBuffer:this.pt.areaLightsBufferNode,pointLightsBuffer:this.pt.pointLightsBufferNode,spotLightsBuffer:this.pt.spotLightsBufferNode,bidirectional:x,resolution:this.pt.resolution,frame:this.pt.seedFrame,transmissiveBounces:this.pt.transmissiveBounces})()).compute([Math.ceil(u/256),1,1],[256,1,1])),t.register(`connect`,f(rE({rayBufferRW:i.rayBuffer.rw,hitBufferRO:i.hitBuffer.ro,activeIndicesRO:r.getActiveReadRO(),counters:a,bvhBuffer:h,triangleBuffer:m,materialBuffer:g,resolution:this.pt.resolution,frame:this.pt.seedFrame,accumFrame:this.pt.frame,currentBounce:this.pt._wfCurrentBounce,chunkRowBase:this.pt._wfChunkRowBase,lightPaths:x.lightPaths,slotsPerPath:x.slotsPerPath,lightTag:x.lightTag,passTag:x.passTag,strategyView:x.strategyView,maxBounceCount:this.pt.maxBounces,globalIlluminationIntensity:this.pt.globalIlluminationIntensity,fireflyThreshold:this.pt.fireflyThreshold,mergeVm:x.merging?e=>bE(x,e):null,diffuseTransmission:b})()).compute([Math.ceil(u/256),1,1],[256,1,1])),x.merging){let e=(0,n.storage)(this._mergeHeadAttr,`uint`).toAtomic();t.register(`mergeClear`,dE({head:e,hashSize:this._mergeHeadAttr.count})),t.register(`mergeInsert`,fE({hitBufferRW:i.hitBuffer.rw,head:e,bidirectional:x})().compute([Math.ceil(this._lightCacheSlots/256),1,1],[256,1,1])),t.register(`merge`,f(pE({rayBufferRW:i.rayBuffer.rw,hitBufferRO:i.hitBuffer.ro,activeIndicesRO:r.getActiveReadRO(),counters:a,head:e,materialBuffer:g,bidirectional:x,maxBounceCount:this.pt.maxBounces,globalIlluminationIntensity:this.pt.globalIlluminationIntensity,fireflyThreshold:this.pt.fireflyThreshold,accumFrame:this.pt.frame,diffuseTransmission:b})()).compute([Math.ceil(u/256),1,1],[256,1,1]))}let w=(0,n.storage)(this._splatAttr,`uint`).toAtomic();t.register(`lightSplat`,f(mE({hitBufferRO:i.hitBuffer.ro,splatBuffer:w,bvhBuffer:h,triangleBuffer:m,materialBuffer:g,lightPaths:x.lightPaths,slotsPerPath:x.slotsPerPath,lightTag:x.lightTag,strategyView:x.strategyView,cameraPosition:x.cameraPosition,cameraForward:x.cameraForward,cameraClipStart:this.pt.cameraClipStart,cameraViewMatrix:this.pt.cameraViewMatrix,cameraProjectionMatrix:this.pt.cameraProjectionMatrix,pixelArea:x.pixelArea,renderWidth:this.pt._wfRenderWidth,renderHeight:this.pt._wfRenderHeight,globalIlluminationIntensity:this.pt.globalIlluminationIntensity,fireflyThreshold:this.pt.fireflyThreshold,accumFrame:this.pt.frame,frame:this.pt.seedFrame,mergeVm:x.merging?e=>bE(x,e):null,diffuseTransmission:b})()).compute([Math.ceil(this._lightCacheSlots/256),1,1],[256,1,1])),t.register(`splatResolve`,hE({rayBufferRW:i.rayBuffer.rw,splatBuffer:w,renderWidth:this.pt._wfRenderWidth,chunkRowBase:this.pt._wfChunkRowBase,chunkRows:this.pt._wfChunkRows})().compute([Math.ceil(d/16),Math.ceil(this.pt._chunkRows/16),1],[16,16,1]))}beginFrame(e){let t=this._updateBidirectionalUniforms();return this._lightTraced=t&&this.uniforms.lightTrace.value>0,t&&(this._updateLightGuide(),this._traceLightPaths(e)),t}beforeShade(){this.uniforms.passTag.value=this._nextPassTag()}afterShade(e){e.dispatch(`connect`),this.merging&&e.dispatch(`merge`)}resolve(e){this._lightTraced&&e.dispatch(`splatResolve`)}get curveKey(){return this._lightCurveKey}applyLightCurve(e,t,n){this._lastLightBounceCounts=e,this._lastLightBounceEnergy=t,this._lastLightCurveKey=n}describe(){return`${this.name}: ${this._lightCacheSlots.toLocaleString(`en-US`)} light vertex slots`}gpuResources(){return this._splatAttr?[this._splatAttr,this._mergeHeadAttr].filter(Boolean):null}dispose(){Au(this.pt.renderer,this._splatAttr),this._splatAttr=null,Au(this.pt.renderer,this._mergeHeadAttr),this._mergeHeadAttr=null,this._disposeLightGuide()}setBidirectionalStrategy(e=`all`,{alone:t=!1}={}){let n={all:_E.ALL,hit:_E.HIT,nee:_E.NEE,connect:_E.CONNECT,lightTrace:_E.LIGHT_TRACE,merge:_E.MERGE}[e]??_E.ALL;this.uniforms.strategyView.value=n===_E.ALL?n:n+(t?vE:0)}setMergeRadius(e=EE){this._mergeRadiusPixels=Math.max(e,.001)}setMergeTrust(e=OE){this.uniforms.mergeTrust.value=Math.max(e,1e-4)}_updateBidirectionalUniforms(){let e=this.uniforms,t=this.pt._wfRenderWidth.value,n=this.pt._wfRenderHeight.value,r=this.pt.maxBounces.value+1,i=this._updateSourceTable()>0?Math.min(Math.ceil(t*n*wE),this.pt._packedBuffers.capacity,Math.floor(this._lightCacheSlots/r)):0;if(e.lightPaths.value=i,e.slotsPerPath.value=r,this._lightCurveKey=`${i}:${r}:${this.pt._bounceLoopBound()}`,i===0)return e.lightTrace.value=0,!1;this._lightTag=this._lightTag%TE+1,e.lightTag.value=this._lightTag;let a=this.pt.cameraWorldMatrix.value.elements;e.cameraPosition.value.set(a[12],a[13],a[14]),e.cameraForward.value.set(-a[8],-a[9],-a[10]).normalize();let o=this.pt.cameraProjectionMatrix.value.elements;e.pixelArea.value=4/(o[0]*o[5]*t*n);let s=this.pt.cameraProjection.value===at.perspective&&!this.pt.enableDOF.value;return e.lightTrace.value=+!!s,this.merging&&this._updateMergeRadius(t,n),!0}_updateMergeRadius(e,t){let n=this.uniforms,r=this._mergeRadiusPixels*(this.pt.frameCount+1)**((DE-1)/2),i=this.pt.cameraProjection.value,a=this.pt.cameraProjectionMatrix.value.elements,o=0,s=0;i===at.orthographic?s=r*2/(a[5]*t):o=i===at.equirectangular?r*2*Math.PI/e:r*Math.sqrt(n.pixelArea.value),n.mergeSlope.value=Math.min(o,.1),n.mergeConst.value=s,n.mergeMin.value=Math.max(s,o*.001*n.sceneRadius.value,1e-9)}_sizeSourceTable(){let e=this.uniforms,t=yE.LAMPS;[`directional`,`area`,`point`,`spot`].forEach((n,r)=>{e.sourceOffsets[r]=t,t+=this.pt[`${n}LightsBufferNode`].array.length/dt[n]}),e.sourceCount=t,e.sourceCdf.array.length!==t&&(e.sourceCdf.array=new Float32Array(t))}_updateSourceTable(){let e=this.uniforms,t=e.sourceCdf.array,n=new Float64Array(t.length),r=(e,t)=>Math.max(.2126*e[t]+.7152*e[t+1]+.0722*e[t+2],0),i=e=>({a:this.pt[`${e}LightsBufferNode`].array,n:this.pt[`num${e[0].toUpperCase()}${e.slice(1)}Lights`].value,f:dt[e]}),a=i(`directional`),o=this.pt.enableEnvironment.value>0,s=this.pt.environment.exactTable;e.envTable.value=+!!s;let c=o&&(this.pt.hasSun.value>0||s)||a.n>0,l=c||this.merging?this._sceneDisc():0,u=c?l*CE:0;if(o&&s&&(n[yE.ENVIRONMENT]=Math.max(s.radianceIntegral,0)*this.pt.environmentIntensity.value*u),this.pt.emissiveTriangleCount.value>0&&(n[yE.EMITTERS]=Math.PI*this.pt.emissiveBoost.value*this.pt.emissiveTotalPower.value),o&&this.pt.hasSun.value>0){let{x:e,y:t,z:r}=this.pt.sunRadiance.value;n[yE.SUN]=Math.max(.2126*e+.7152*t+.0722*r,0)*this.pt.environmentIntensity.value*this.pt.sunParams.value.y*u}for(let t=0;t<a.n;t++)n[e.sourceOffsets[0]+t]=r(a.a,t*a.f+3)*a.a[t*a.f+6]*u;let d=i(`area`);for(let t=0;t<d.n;t++){let i=d.a,a=t*d.f,o=i[a+4]*i[a+8]-i[a+5]*i[a+7],s=i[a+5]*i[a+6]-i[a+3]*i[a+8],c=i[a+3]*i[a+7]-i[a+4]*i[a+6],l=4*Math.hypot(o,s,c)*(i[a+15]>.5?Math.PI/4:1);n[e.sourceOffsets[1]+t]=l>0?r(i,a+9)*Math.max(i[a+12],0)*(i[a+13]>.5?1:l):0}let f=i(`point`);for(let t=0;t<f.n;t++)n[e.sourceOffsets[2]+t]=4*Math.PI*r(f.a,t*f.f+3)*Math.max(f.a[t*f.f+6],0);let p=i(`spot`);for(let t=0;t<p.n;t++){let i=t*p.f;n[e.sourceOffsets[3]+t]=2*Math.PI*(1-Math.cos(p.a[i+10]))*r(p.a,i+6)*Math.max(p.a[i+9],0)}let m=0;for(let e=0;e<n.length;e++)m+=Number.isFinite(n[e])?n[e]:0;let h=0;for(let e=0;e<n.length;e++)h+=Number.isFinite(n[e])?n[e]:0,t[e]=m>0?h/m:0;m>0&&(t[t.length-1]=1);let g=e=>Math.fround(t[e]-(e>0?t[e-1]:0));return e.sunPick.value=g(yE.SUN),e.emitterPick.value=g(yE.EMITTERS),e.envPick.value=g(yE.ENVIRONMENT),m}_sceneDisc(){let e=this.uniforms,t=this._visibleSceneBounds();if(!t)return 0;let[n,r,i]=t.min,[a,o,s]=t.max,c=.5*Math.hypot(a-n,o-r,s-i);return c>0&&Number.isFinite(c)?(e.sceneCenter.value.set((n+a)/2,(r+o)/2,(i+s)/2),e.sceneRadius.value=c,Math.PI*c*c):0}_visibleSceneBounds(){let e=this.pt._bvhRecords,t=e?null:this.pt.bvhStorageAttr?.array;if(!e&&!(t?.length>=16))return null;let n=this.pt._instanceTable?.blasBase??1;if(e&&!e.isResident(0,n))return this.pt._whenTLASResident(()=>{}),null;let r=e=>{let t=this._u32Views.get(e);return t||this._u32Views.set(e,t=new Uint32Array(e.buffer,e.byteOffset,e.length)),t},i=n=>{let i=e?e.chunkFor(n):t;return{f:i,u:r(i),o:e?e.baseOf(n):n*16}},a=e=>{if(e.u[e.o+3]!==Tt.CLUSTER_LEAF)return e.f[e.o+2]!==0;let t=(e.u[e.o]>>>28&3)+1;for(let n=0;n<t;n++)if(!(e.u[e.o+12+n]&2147483648))return!0;return!1},o=i(0);if(o.u[o.o+3]>=1073741824)return null;let s=e?e.recordCount:t.length/16,c=[],l=[];for(let e=0;e<3;e++)for(let t of[1,-1]){let n=(n,r)=>t>0?n.f[n.o+r*8+4+e]:-n.f[n.o+r*8+e],r=(e,t)=>e.u[e.o+3+t*4],u=-1/0,d=[],f=e=>{let t=n(e,0),i=n(e,1),a=t<=i?0:1;d.push(r(e,a),a===0?t:i,r(e,1-a),a===0?i:t)};f(o);let p=0;for(;d.length;){let e=d.pop(),t=d.pop();if(e<=u)continue;if(t>=s||++p>s)return null;let n=i(t);n.u[n.o+3]>=1073741824?a(n)&&(u=e):f(n)}if(u===-1/0)return null;(t>0?l:c)[e]=t>0?u:-u}return{min:c,max:l}}setLightGuiding(e){this._lightGuiding=e!==!1,this.uniforms.guide.value=0,this.pt.reset()}_updateLightGuide(){let e=this.uniforms,t=this.pt._kernelManager;e.guideLearning.value=+!!this._lightGuiding;let n=this.pt.frameCount;if(n===0){t.dispatch(`guideClear`),e.guide.value=0;return}if(!this._lightGuiding||!(n<=32?!(n&n-1):n%32==0))return;t.dispatch(`guideBuild`);let r=this.pt.renderer.backend;this.pt.renderer.initTexture(this._guideTexture);let i=r.device.createCommandEncoder({label:`LightGuide`});i.copyBufferToTexture({buffer:r.get(this._guideBuildAttr).buffer,bytesPerRow:WT*4,rowsPerImage:16},{texture:r.get(this._guideTexture).texture},[UT,16]),r.device.queue.submit([i.finish()]),e.guide.value=1}_disposeLightGuide(){Au(this.pt.renderer,this._guideBuildAttr),this._guideTexture?.dispose(),this._guideTexture=this._guideBuildAttr=null,this.uniforms.guideTexture=null}_nextPassTag(){return this._passTag=this._passTag+1&2147483647,(gE|this._passTag)>>>0}_traceLightPaths(e){let t=this.pt._kernelManager,n=this.uniforms.lightPaths.value;this.pt._wfChunkRowBase.value=0,this.pt._wfMaxRayCount.value=n,t.setDispatchForCount(`lightGenerate`,n),t.dispatch(`lightGenerate`);let r=this.pt._useDynamicDispatch,i=this._lastLightCurveKey===this._lightCurveKey,a=i?this._lastLightBounceCounts:null,o=i?this._lastLightBounceEnergy:null,s=this.pt._bounceEarlyExitThreshold>=0?this.pt._bounceEarlyExitThreshold*n*64:-1;for(let i=0;i<=e;i++){this.pt._wfCurrentBounce.value=i;let c=i>0?a?.[i-1]:void 0,l=r&&c>0?Math.min(n,Math.ceil(c*1.5)+1024):n;for(let e of M_)t.setDispatchForCount(e,l);if(r||t.dispatch(`enterFull`),t.dispatch(`extend`),this.pt._sortMaterials&&(t.dispatch(`resetGlobalHist`),t.dispatch(`globalHist`),t.dispatch(`globalPrefix`),t.dispatch(`globalScatter`)),t.dispatch(`shade`),t.dispatch(`compact`),t.dispatch(r?`lightCopyback`:`lightSnapshot`),s>=0&&i<e&&o?.[i]!==void 0&&o[i]<=s)break}this.uniforms.lightTrace.value>0&&(t.setDispatchForCount(`lightSplat`,n*this.uniforms.slotsPerPath.value),t.dispatch(`lightSplat`)),this.merging&&(t.dispatch(`mergeClear`),t.setDispatchForCount(`mergeInsert`,n*this.uniforms.slotsPerPath.value),t.dispatch(`mergeInsert`))}};function AE(e){let t=String(e??``);return/(hdr|pq|hlg|2100|st2084)/i.test(t)?null:/^display\s*p3\b/i.test(t)?`display-p3`:/^srgb\b(?!.*(p3|2020))/i.test(t)?`srgb`:null}var jE=new Set([`hdr-video`,`edr-video`]),ME=/(^|[^a-z])(hdr|pq|hlg|st-?2084|2100)([^a-z]|$)/i;function NE(e,t){let n=new Map;for(let t of e?.colorSpaces??[])for(let e of[t.name,...t.aliases??[]])n.set(e,t.encoding);let r=e=>e.colorSpace===`<USE_DISPLAY_NAME>`?t:e.colorSpace;return(e?.views?.[t]??[]).map(e=>n.get(r(e))).filter(Boolean)}function PE(e,t){let n=NE(e,t);return n.length?n.some(e=>jE.has(e)):ME.test(t)}var FE=1e3,IE=e=>String(e).replace(/\([^)]*\)/g,` `).split(/\s+-\s+/)[0].trim().replace(/\s+/g,` `).toLowerCase(),LE=e=>e.replace(/\s*\d+(\.\d+)*$/,``),RE=e=>/\bHDR\b/i.test(e)?`hdr`:/\bSDR\b/i.test(e)?`sdr`:null;function zE(e,t){let n=e.findIndex((e,n)=>e!==t[n]);return n>=0&&e[n]<t[n]}var BE=e=>new Set((e?.colorSpaces??[]).filter(e=>e.isData).flatMap(e=>[e.name,...e.aliases??[]]));function VE(e,t,n){return BE(e).has(e?.views?.[t]?.find(e=>e.name===n)?.colorSpace)}function HE(e,t){return IE(e)===IE(t)}var UE=(e,t)=>LE(IE(e))===LE(IE(t));function WE(e,t,n){let r=RE(t),i=Number(/(\d+)\s*nits/i.exec(t)?.[1]??FE);return[IE(t)===IE(e)?0:1,(n?r===`hdr`:r!==`hdr`)?0:1,t===e?0:1,n?Math.abs(Math.log2(i/FE)):0,+!/p3/i.test(t)]}function GE(e,t,n){let r=BE(e),i=PE(e,n),a=null;for(let o of e?.views?.[n]??[]){if(r.has(o.colorSpace)||!UE(t,o.name))continue;let e=WE(t,o.name,i);(!a||zE(e,a.rank))&&(a={view:o.name,rank:e})}return a}function KE(e,t,n,r){if(VE(e,t,n)){let t=BE(e);return e?.views?.[r]?.find(e=>t.has(e.colorSpace))?.name??null}return GE(e,n,r)?.view??null}function qE(e,t,n){if(VE(e,t,n))return null;if(PE(e,t))return{display:t,view:n};if(RE(n)===`hdr`)return null;let r=null;for(let t of e?.displays??[]){if(!PE(e,t))continue;let i=GE(e,n,t),a=RE(i?.view)===null;if(!i||RE(i.view)===`sdr`||a&&(i.rank[0]||RE(n)!==null))continue;let o=[...i.rank,NE(e,t).includes(`edr-video`)?0:/pq|st-?2084/i.test(t)?1:2];(!r||zE(o,r.rank))&&(r={display:t,view:i.view,rank:o})}return r&&{display:r.display,view:r.view}}ui(),Ae();var JE=ve(`ocio`);function YE(e){let t=String(e);/\[OpenColorIO Error\]/.test(t)?JE.error(t):/\[OpenColorIO Warning\]/.test(t)?JE.warn(t):JE.debug(t)}var XE=null,ZE=null,QE=null,$E=null,eD=null;async function tD(){let{ocioRuntimeFactory:e,ocioRuntimeUrl:t}=si();if(typeof e==`function`)return await e();if(typeof t==`string`&&t)return await import(t);throw Error(`OpenColorIO runtime not configured. Call configureAssets({ ocioRuntimeFactory: () => import('@bb-studio/ocio') }) before loading a config.`)}async function nD(){return ZE||(XE||=(async()=>{let e=await tD();if(typeof e.createOcioRuntime!=`function`)throw Error(`OCIO module has no createOcioRuntime() — wrong package or version`);let{ocioWasmUrl:t}=si();return ZE=await e.createOcioRuntime({...t?{wasmUrl:t}:{},moduleOptions:{print:YE,printErr:YE}}),ZE})().catch(e=>{throw XE=null,e}),await XE)}async function rD(){return(await nD()).ocio.listBuiltinConfigs()}async function iD({builtin:e,text:t,files:n=[],configPath:r=`config.ocio`,id:i}={}){let a=await nD();if(e)QE=a.loadBuiltinConfig(e),$E=e,eD=dD(a,e);else{let e=n.map(e=>({relativePath:e.relativePath??e.path??e.name,data:e.data instanceof Uint8Array?e.data:new Uint8Array(e.data)}));if(t!==void 0&&e.unshift({relativePath:r,data:new TextEncoder().encode(t)}),!e.some(e=>e.relativePath===r))throw Error(`config package has no "${r}" — pass configPath to name the .ocio file`);QE=a.loadConfigPackage({configRelativePath:r,files:e},i?{id:i}:void 0),$E=i??QE.id;let o=e.find(e=>e.relativePath===r);eD=o?new TextDecoder().decode(o.data):null}return uD()}function aD(){QE=null,$E=null,eD=null}function oD(){return QE!==null}function sD(){return QE?ZE:null}function cD(){return QE}function lD(){return eD}function uD(){if(!QE)return null;let e=Object.fromEntries(QE.roles.map(e=>[e.name,e.colorSpace]));return{id:$E,name:eD?.match(/^name:\s*(\S.*?)\s*$/m)?.[1]??null,ocioVersion:QE.ocioVersion,version:QE.version,roles:e,sceneLinear:e.scene_linear??null,colorPicking:e.color_picking??e.texture_paint??null,texturePaint:e.texture_paint??e.color_picking??null,data:e.data??null,compositingLog:e.compositing_log??e.color_timing??null,colorSpaces:QE.colorSpaces.map(e=>({name:e.name,family:e.family,categories:e.categories??[],encoding:e.encoding,isData:e.isData,aliases:e.aliases,description:e.description})),displays:QE.displays.slice(),defaultDisplay:QE.defaultDisplay,views:Object.fromEntries(Object.entries(QE.viewsByDisplay).map(([e,t])=>[e,t.map(e=>({name:e.name,transform:e.transform,colorSpace:e.colorSpace,looks:e.looks,description:e.description}))])),defaultViews:{...QE.defaultViewsByDisplay},looks:QE.looks.map(e=>({name:e.name,processSpace:e.processSpace,description:e.description,forward:e.hasForwardTransform,inverse:e.hasInverseTransform})),namedTransforms:QE.namedTransforms.map(e=>e.name),fileRules:QE.fileRules.map(e=>({index:e.index,name:e.name,colorSpace:e.colorSpace,pattern:e.pattern,extension:e.extension,regex:e.regex})),contextVariables:fD()}}function dD(e,t){for(let n of[t,t.replace(/^ocio:\/\//,``)])try{let t=e.ocio.getBuiltinConfigYaml(n);if(t)return t}catch{}return null}function fD(){if(!eD)return[];let e=new Map,t=eD.split(/\r?\n/),n=t.findIndex(e=>/^environment:\s*(\{\s*\})?\s*$/.test(e));if(n>=0&&!/\{\s*\}/.test(t[n]))for(let r=n+1;r<t.length;r++){let n=t[r];if(/^\S/.test(n))break;let i=n.match(/^\s+([A-Za-z_][A-Za-z0-9_]*)\s*:\s*(.*?)\s*$/);i&&e.set(i[1],{name:i[1],default:i[2].replace(/^["']|["']$/g,``)||null,declared:!0})}for(let t of eD.matchAll(/\$\{?([A-Za-z_][A-Za-z0-9_]*)\}?/g))e.has(t[1])||e.set(t[1],{name:t[1],default:null,declared:!1});return[...e.values()].sort((e,t)=>e.name.localeCompare(t.name))}function pD(){aD(),ZE?.dispose?.(),ZE=null,XE=null}var mD=1<<20,hD=new Map,gD=new Map,_D=4096,vD=new Map;function yD(e,t,n){return`${e}\u0000${t}\u0000${n?JSON.stringify(n):``}`}function bD(){for(let e of hD.values())e.dispose?.();hD.clear(),gD.clear(),vD.clear()}function xD(e,t,{context:n=null}={}){if(!sD()||e===t)return null;let r=yD(e,t,n),i=hD.get(r);if(i!==void 0)return i;try{i=TD().createColorSpaceProcessor(e,t,n?{context:n}:void 0),i.isNoOp&&(i.dispose(),i=null)}catch(n){throw Error(`no OCIO transform from "${e}" to "${t}": ${n.message}`)}return hD.set(r,i),i}var SD=null,CD=null,wD=!1;function TD(){let e=sD();if(!e)throw Error(`no OCIO config loaded`);if(e.config)return e.config;let t=cD();if(SD&&CD===t.id)return SD;if(wD&&SD?.dispose?.(),!t.id?.startsWith(`ocio://`))throw Error(`OCIO runtime exposes no Config handle for this config`);return SD=e.ocio.createBuiltinConfig(t.id),wD=!0,CD=t.id,SD}function ED(){wD&&SD?.dispose?.(),SD=null,CD=null,wD=!1,bD()}function DD(e,t,n,{context:r=null}={}){let i=sD();if(!i||t===n)return[e[0],e[1],e[2]];let a=`${yD(t,n,r)}\u0000${e[0]},${e[1]},${e[2]}`,o=gD.get(a);if(o)return o.slice();let s=i.transformRgb(t,n,[e[0],e[1],e[2]],r?{context:r}:void 0);return gD.size>=_D&&gD.clear(),gD.set(a,s),s.slice()}function OD(e,t,n,{context:r=null}={}){if(e.length%4!=0)throw Error(`convertPixelsF32 wants 4 floats per pixel`);let i=xD(t,n,{context:r});if(!i)return e;let a=e.length/4;if(a<=mD)return i.applyRGBAF32(e),e;for(let t=0;t<a;t+=mD){let n=Math.min(mD,a-t);i.applyRGBAF32(e.subarray(t*4,(t+n)*4))}return e}var kD=.055;function AD(e){return e<=.04045?e/12.92:((e+kD)/(1+kD))**2.4}function jD(e){return e<=0?0:e<=.0031308?12.92*e:(1+kD)*e**(1/2.4)-kD}var MD=new Float32Array(256);for(let e=0;e<256;e++)MD[e]=AD(e/255);var ND=new Float32Array(256);for(let e=0;e<256;e++)ND[e]=e/255;function PD(e){return e===`srgb`?MD:ND}function FD(e,t,n,{context:r=null,inputEncoding:i=`raw`,outputEncoding:a=`srgb`}={}){if(e.length%4!=0)throw Error(`convertEncodedRGBA8 wants 4 bytes per pixel`);let o=xD(t,n,{context:r});if(!o)return e;let s=e.length/4,c=PD(i),l=a===`srgb`?RD:zD,u=new Float32Array(Math.min(mD,s)*4);for(let t=0;t<s;t+=mD){let n=Math.min(mD,s-t),r=n*4===u.length?u:u.subarray(0,n*4);for(let i=0;i<n;i++){let n=(t+i)*4,a=i*4;r[a]=c[e[n]],r[a+1]=c[e[n+1]],r[a+2]=c[e[n+2]],r[a+3]=1}o.applyRGBAF32(r);for(let i=0;i<n;i++){let n=(t+i)*4,a=i*4;e[n]=l(r[a]),e[n+1]=l(r[a+1]),e[n+2]=l(r[a+2])}}return e}var ID=65536,LD=new Uint8Array(ID+1);for(let e=0;e<=ID;e++){let t=e/ID;LD[e]=Math.round(jD(t*t)*255)}function RD(e){return e>0?e>=1?255:LD[Math.sqrt(e)*ID+.5|0]:0}function zD(e){return e>0?e>=1?255:e*255+.5|0:0}function BD(e,t,n=`srgb`){if(!t)return e;let r=PD(n),i=n===`srgb`?RD:zD,[a,o,s,c,l,u,d,f,p]=t;for(let t=0;t<e.length;t+=4){let n=r[e[t]],m=r[e[t+1]],h=r[e[t+2]];e[t]=i(a*n+o*m+s*h),e[t+1]=i(c*n+l*m+u*h),e[t+2]=i(d*n+f*m+p*h)}return e}function VD(e,t,{context:n=null,tolerance:r=1e-4}={}){if(!sD())return null;if(e===t)return[1,0,0,0,1,0,0,0,1];let i=yD(e,t,n);if(vD.has(i))return vD.get(i);let a=xD(e,t,{context:n});if(!a)return vD.set(i,[1,0,0,0,1,0,0,0,1]),vD.get(i);let o=e=>{let t=new Float32Array([e[0],e[1],e[2],1]);return a.applyRGBAF32(t),[t[0],t[1],t[2]]},s=[o([1,0,0]),o([0,1,0]),o([0,0,1])],c=[s[0][0],s[1][0],s[2][0],s[0][1],s[1][1],s[2][1],s[0][2],s[1][2],s[2][2]],l=e=>[c[0]*e[0]+c[1]*e[1]+c[2]*e[2],c[3]*e[0]+c[4]*e[1]+c[5]*e[2],c[6]*e[0]+c[7]*e[1]+c[8]*e[2]],u=[[.18,.18,.18],[.5,.25,.75],[2,.1,.4],[.02,.9,.3],[8,4,1],[.001,.002,.004]],d=!0;for(let e of u){let t=o(e),n=l(e),i=Math.max(.001,Math.abs(n[0]),Math.abs(n[1]),Math.abs(n[2]));for(let e=0;e<3;e++)Math.abs(t[e]-n[e])>r*i&&(d=!1);if(!d)break}let f=d?c:null;return vD.set(i,f),f}function HD(e){let t=cD();if(!t)return!1;let n=t.colorSpaces.find(t=>t.name===e||t.aliases?.includes(e));return n?n.isData:!1}function UD(e){let t=cD();return!t||!e?!1:t.colorSpaces.some(t=>t.name===e||t.aliases?.includes(e))}var WD=1e-10;function GD(e,t,n,r){return e<=0?0:2**(n+e/(t-1)*(r-n))}function KD(e,t,n,r){let i=(Math.log2(Math.max(e,WD))-n)/(r-n);return Math.min(Math.max(i,0),1)*(t-1)}function qD({size:e,minEv:t,maxEv:n,apply:r}){let i=e*e*e,a=new Float32Array(i*4),o=new Float64Array(e);for(let r=0;r<e;r++)o[r]=GD(r,e,t,n);let s=0;for(let t=0;t<e;t++)for(let n=0;n<e;n++)for(let r=0;r<e;r++)a[s++]=o[r],a[s++]=o[n],a[s++]=o[t],a[s++]=1;return r(a),a}function JD(e){let t=new Uint16Array(e.length),n=new Float32Array(1),r=new Uint32Array(n.buffer);for(let i=0;i<e.length;i++){n[0]=e[i];let a=r[0],o=a>>>16&32768,s=a>>>23&255,c=a&8388607;if(s===255)t[i]=o|31744|(c?512:0);else if(s>142)t[i]=o|31743;else if(s<113){let e=13+(113-s);c|=8388608,t[i]=e>=32?o:o|c>>>e}else{let e=o|s-112<<10|c>>>13,n=c&8191;(n>4096||n===4096&&e&1)&&e++,t[i]=(e&32767)>=31744?o|31743:e}}return t}function YD(e,t=new Float32Array(e.length)){for(let n=0;n<e.length;n++){let r=e[n],i=r&32768?-1:1,a=(r&31744)>>10,o=r&1023;a===0?t[n]=i*2**-14*(o/1024):a===31?t[n]=o?NaN:i*(1/0):t[n]=i*2**(a-15)*(1+o/1024)}return t}var XD=null;function ZD(){if(!XD){let e=new Uint16Array(65536);for(let t=0;t<65536;t++)e[t]=t;XD=YD(e)}return XD}function QD(e,t,n){return e>t?t>n?{w:[e,t,n],c:[[1,0,0],[1,1,0],[1,1,1]]}:e>n?{w:[e,n,t],c:[[1,0,0],[1,0,1],[1,1,1]]}:{w:[n,e,t],c:[[0,0,1],[1,0,1],[1,1,1]]}:n>t?{w:[n,t,e],c:[[0,0,1],[0,1,1],[1,1,1]]}:n>e?{w:[t,n,e],c:[[0,1,0],[0,1,1],[1,1,1]]}:{w:[t,e,n],c:[[0,1,0],[1,1,0],[1,1,1]]}}function $D({data:e,size:t,minEv:n,maxEv:r}){let i=t*t,a=t-1,o=e instanceof Uint16Array,s=o?ZD():null,c=o?(n,r,a,o)=>s[e[(n+r*t+a*i)*4+o]]:(n,r,a,o)=>e[(n+r*t+a*i)*4+o];return function(e,i,o,s){let l=KD(e,t,n,r),u=KD(i,t,n,r),d=KD(o,t,n,r),f=Math.min(Math.floor(l),a-1),p=Math.min(Math.floor(u),a-1),m=Math.min(Math.floor(d),a-1),{w:h,c:g}=QD(Math.min(Math.max(l-f,0),1),Math.min(Math.max(u-p,0),1),Math.min(Math.max(d-m,0),1));for(let e=0;e<3;e++){let t=c(f,p,m,e),n=t,r=t;for(let t=0;t<3;t++){let i=c(f+g[t][0],p+g[t][1],m+g[t][2],e);n+=(i-r)*h[t],r=i}s[e]=n}}}function eO({fnName:e,texName:t,size:n,minEv:r,maxEv:i}){let a=e=>Number.isInteger(e)?`${e}.0`:String(e);return`
|
|
1376
1376
|
fn ${e}_shape( v: vec3<f32> ) -> vec3<f32> {
|
|
1377
1377
|
let ev = log2( max( v, vec3<f32>( 1e-10 ) ) );
|
|
1378
1378
|
let t = ( ev - vec3<f32>( ${a(r)} ) ) / ${a(i-r)};
|
|
@@ -1424,7 +1424,7 @@ fn ${e}( c: vec3<f32> ) -> vec3<f32> {
|
|
|
1424
1424
|
|
|
1425
1425
|
return c000 + ( v1 - c000 ) * w.x + ( v2 - v1 ) * w.y + ( v3 - v2 ) * w.z;
|
|
1426
1426
|
}
|
|
1427
|
-
`}function LD({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}}an(),vs();var RD=-12.47393,zD=12.5260688117,BD=65,VD=null,HD=new Map;function UD(e){VD=e}function WD(){let e=WE();if(!e)throw Error(`load an OCIO config first`);if(!e.config)throw Error(`OCIO runtime exposes no Config handle`);return e.config}function GD({source:e,display:t,view:n,look:r,context:i}){let a=WD(),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 KD({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 qD({display:e,view:t,look:n=null,context:r=null,source:i=null,size:a=65,minEv:o=RD,maxEv:s=zD,id:c=null,name:l=null}={}){let u=GE();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(`, `)}`);AE(e)===null&&VD?.warn(X.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=GD({source:f,display:e,view:t,look:n,context:r}),h=e=>m.applyRGBAF32(e),g,_;try{g=AD(kD({size:a,minEv:o,maxEv:s,apply:h})),_=LD({sampler:FD({data:g,size:a,minEv:o,maxEv:s}),apply:h})}finally{m.dispose()}return YD({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 JD(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 YD({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 YD({id:e,name:t,half:n,error:i,ocio:a}){let{size:o,minEv:s,maxEv:c}=a,l=FD({data:n,size:o,minEv:s,maxEv:c}),u=e??ns(),d=`TM_OCIO_${u}`,f=`tm_ocio_${u}`,p=HD.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=KD({texture:h,size:o,minEv:s,maxEv:c})),HD.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:ID({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 XD(e){return rs(qD(e))}function ZD({display:e=null,look:t=null,context:n=null,source:r=null,size:i=65}={}){let a=GE();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(XD({display:o,view:e.name,look:t,context:n,source:r,size:i}))}catch(t){l.push({view:e.name,reason:t.message}),VD?.warn(X.VIEW_TRANSFORM_BAKE_FAILED,`could not bake "${e.name}" (${o}): ${t.message}`,{display:o,view:e.name})}}return{added:c,skipped:l}}function QD(e){let t=HD.get(e);t&&(t.texture.dispose(),HD.delete(e))}function $D(e=null){for(let t of hs.values())t.source===`ocio`&&!e?.has(t.id)&&t.table?.texture?.dispose?.();for(let[t,n]of HD)e?.has(t)||(n.texture.dispose(),HD.delete(t))}var eO=[82,90,86,84],tO=`rayzee-baked-view`,nO=15360;async function rO(e,t){return new Uint8Array(await new Response(new Blob([e]).stream().pipeThrough(t)).arrayBuffer())}async function iO(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]!==nO)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:tO,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(eO,0),new DataView(h.buffer).setUint32(4,m.length,!0),h.set(m,8),h.set(s,8+m.length),await rO(h,new CompressionStream(`gzip`))}async function aO(e){let t=await rO(e,new DecompressionStream(`gzip`));if(t.length<8||eO.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!==tO||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]=nO;return{...r,data:l}}async function oO({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(`
|
|
1428
|
-
`)))}`}var sO=[],cO=0;function lO(){return cO}function uO(){cO++}function dO(e,t){sO.unshift({match:e,colorSpace:t}),cO++}function fO(){sO.length!==0&&(sO.length=0,cO++)}function pO(){return sO.map(e=>({match:String(e.match),colorSpace:e.colorSpace}))}function mO(e){if(!e)return null;for(let t of sO)if(t.match instanceof RegExp?t.match.test(e):e.includes(t.match))return t.colorSpace;return null}function hO(){return GE()?.fileRules.map(e=>({index:e.index,name:e.name,colorSpace:e.colorSpace,pattern:e.pattern,extension:e.extension,regex:e.regex}))??[]}function gO(e){let t=GE();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 _O(e,{threeColorSpace:t=null}={}){if(!GE())return null;let n=mO(e);if(n)return{colorSpace:n,via:`override`,rule:null};let r=WE();if(r&&e){let t=r.matchFileRule(e);if(t&&!t.isDefaultRule&&TD(t.colorSpace))return{colorSpace:t.colorSpace,via:`rule`,rule:{index:t.ruleIndex,name:t.ruleName}}}let i=gO(t);if(i)return{colorSpace:i,via:`three`,rule:null};let a=WE();if(a&&e){let t=a.matchFileRule(e);if(t&&TD(t.colorSpace))return{colorSpace:t.colorSpace,via:`rule`,rule:{index:t.ruleIndex,name:t.ruleName,isDefault:t.isDefaultRule}}}return null}function vO(e){if(!e)return!1;if(e.colorSpace===r.NoColorSpace)return!0;let t=e.userData?.ocioColorSpace;return!!(t&&wD(t))}function yO(e,t){return t??e.userData?.sourcePath??(e.name||null)??e.image?.src??null}function bO(e,t=null){if(!GE()||!e)return null;let n=e.userData?.ocioColorSpace;return n?TD(n)?{colorSpace:n,via:`tag`,rule:null}:null:vO(e)?null:_O(yO(e,t),{threeColorSpace:e.colorSpace})}function xO(e,t=null){return bO(e,t)?.colorSpace??null}an(),vs(),tr();function SO(e){return AE(e)??`srgb`}var CO=[`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`],wO=/^(lin(ear)?[\s_-]*(rec\.?\s*|bt\.?\s*)?709|linear[\s_-]*\(?srgb\)?$|utility - linear - (srgb|rec\.?709))/i;function TO(e){if(!e)return null;let t=e.colorSpaces.filter(e=>!e.isData),n=e=>[e.name,...e.aliases??[]];for(let e of CO){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=>wO.test(e)))?.name??null}var EO=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=gs,this._fingerprint=null,UD(e),this._offRegistry=Qo(()=>{this._renderer&&os(this._renderer),this._emit(`transforms`)}),ti(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 BE()}async loadConfig({adoptWorkingSpace:e=!1,registerViews:t=!0,display:n=null,lutSize:r,...i}={}){await zE();let a=oO(i).catch(()=>null),o=await this._bakedViewsFrom(i.builtin??i.id??null,a),s;try{s=await VE(i)}catch(e){throw this._issues?.warn(X.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,uO(),cD(),this._context=null;let c=this._workingSpace;if(e?this._workingSpace=s.sceneLinear:c&&!TD(c)&&(this._workingSpace=null),TO(GE())||this._issues?.warn(X.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}=ZD({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(X.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(),HE(),cD(),fO(),uO(),this._fingerprint=null,this._workingSpace=null,this._activeView=null,this._exportSpace=null,this._context=null,Jn(null),this._applyRendererOutputColorSpace(),this._emit(`config`,null),this._emit(`workingSpace`,this.workingSpace)}_releaseViews(e=null){$D(e),as(e);for(let t of this._lastUsed.keys())e?.has(t)||this._lastUsed.delete(t);this._renderer&&$o(this._renderer.toneMapping)===null&&(this._renderer.toneMapping=$o(this._lastBuiltin)?this._lastBuiltin:gs,this._activeView=null,this._applyRendererOutputColorSpace())}async _bakedViewsFrom(e,t){let n=[...hs.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 aO(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=KE();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=[...hs.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(),rs(JD(n,i?.id??null))}async saveBakedView(e){let t=$o(e);if(t?.source!==`ocio`)throw Error(`no OCIO view with id ${e}`);let n=KE();return await iO(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 UE()}describe(){return KE()}get workingSpace(){return this._workingSpace?this._workingSpace:UE()?this.nativeLinearSpace??KE()?.sceneLinear??`Linear Rec.709 (sRGB)`:Zr}get workingSpaceAdopted(){return this._workingSpace!==null}setWorkingSpace(e){if(e!==null){if(!UE())throw Error(`load an OCIO config before choosing a working space`);if(!TD(e))throw Error(`config has no colour space "${e}"`)}(this._workingSpace??null)!==(e??null)&&(this._workingSpace=e,nD(),this._publishWorkingMatrix(),this._rebakeViews(),this._emit(`workingSpace`,this.workingSpace))}matrixToWorking(e){return UE()?CD(e,this.workingSpace,{context:this._context}):null}listViews(){return es()}get activeView(){return this._activeView}setActiveView(e){let t=$o(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(!UE())throw Error(`load an OCIO config first`);let i=[...hs.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??XD({display:e,view:t,look:n,context:this._context,source:this.workingSpace,...r?{size:r}:{}});return this.setActiveView(a.id),$o(a.id)}_makeRoomForTable(){if(ts()<12)return;let e=this._renderer?.toneMapping??this._activeView?.id??null,t=[...hs.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&&(QD(t.id),is(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,UE()&&(this._context&&WE()?.invalidateContext(this._context),nD(),this._rebakeViews()),this._emit(`context`,this._context))}get context(){return this._context}_isStale(e){return e.source!==`ocio`||!UE()?!1:e.ocio.source!==this.workingSpace||JSON.stringify(e.ocio.context??null)!==JSON.stringify(this._context??null)}_rebakeView(e){try{let t=XD({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(X.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:$o(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,$o(e.toneMapping)?.source===`builtin`&&(this._lastBuiltin=e.toneMapping);let t=os(e);return this._applyRendererOutputColorSpace(),t}_applyRendererOutputColorSpace(){if(!this._renderer)return;let e=$o(this._renderer.toneMapping);this._renderer.outputColorSpace=e?.outputEncoded?r.LinearSRGBColorSpace:r.SRGBColorSpace,this._applyCanvasColorSpace(e?.source===`ocio`?SO(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(X.VIEW_TRANSFORM_DISPLAY_MISMATCH,`the canvas could not be set to ${e}: ${t.message}`,{colorSpace:e})}}}resolveInput(e,t){return _O(e,t)}textureSpace(e,t){return xO(e,t)}resolveTexture(e,t){return bO(e,t)}describeTextureSpace(e){let t=e?.userData??{},n=t.ocioColorSpace??t.__rayzeeColorSpaceChoice??null,i=null,a=t.__rayzeeOriginalColorSpace??e?.colorSpace;return UE()&&(i=bO({...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 UE()?`${KE()?.id}|${this.workingSpace}|${lO()}|${JSON.stringify(this._context)}`:`-`}overrideInput(e,t){dO(e,t)}fileRules(){return hO()}toWorkingPixels(e,t){return!UE()||!t?e:uD(e,t,this.workingSpace,{context:this._context})}get nativeLinearSpace(){return TO(GE())}_publishWorkingMatrix(){let e=$r();e!==null&&e!==this||Jn(UE()?this.primariesMatrixToWorking():null,this.workingSpace)}primariesMatrixToWorking(){if(!UE()||!this.workingSpaceAdopted)return null;let e=this.nativeLinearSpace;if(!e||e===this.workingSpace)return null;let t=CD(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 Zn(e)}convertLinearTriples(e,t,n){return Qn(e,t,n)}convertTexturePixels(e,{space:t=null}={}){if(!UE())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)uD(n,i,a,{context:this._context}),o=!0;else if(n instanceof Uint16Array){let e=jD(n);uD(e,i,a,{context:this._context}),n.set(AD(e)),o=!0}else if(n instanceof Uint8Array||n instanceof Uint8ClampedArray)_D(n,i,a,{context:this._context,inputEncoding:`srgb`,outputEncoding:`srgb`}),o=!0;else return this._issues?.warn(X.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(!UE())return!1;if(t)return t===this.workingSpace?!1:(_D(e,t,this.workingSpace,{context:this._context,inputEncoding:`raw`,outputEncoding:n}),!0);let r=this.primariesMatrixToWorking();return r?(SD(e,r,n),!0):!1}toWorkingColor(e,t){return!UE()||!t?[e[0],e[1],e[2]]:lD(e,t,this.workingSpace,{context:this._context})}convert(e,t,n){return lD(e,t,n,{context:this._context})}get exportSpace(){return this._exportSpace}setExportSpace(e){if(e!=null){if(!UE())throw Error(`load an OCIO config before choosing an export space`);if(!TD(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||!UE()?{rgba:e,colorSpace:this.workingSpace}:(uD(e,this.workingSpace,n,{context:this._context}),{rgba:e,colorSpace:n})}status(){let e=KE(),t=this._renderer?$o(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:es(),registryVersion:Zo(),bakeError:t?.error??null}}dispose(){this._offRegistry?.(),this._listeners.clear(),this._releaseViews(),UD(null),this._renderer=null,this._issues=null,$r()===this&&(Jn(null),ei(null))}static resetAll(){ei(null),Jn(null),$D(),cs(),cD(),fO(),YE()}};function DO(){return UE()}var OO=new Map;function kO(e,t){return e.exclusive||t===`exclusive`&&e.shared>0?!1:(t===`exclusive`?e.exclusive=!0:e.shared++,!0)}function AO(e,t,n){let r=OO.get(e);r||(r={shared:0,exclusive:!1,queue:[]},OO.set(e,r));let i=jO(()=>{for(t===`exclusive`?r.exclusive=!1:r.shared--;r.queue.length&&kO(r,r.queue[0].mode);)r.queue.shift().grant();!r.exclusive&&r.shared===0&&r.queue.length===0&&OO.delete(e)});return r.queue.length===0&&kO(r,t)?Promise.resolve(i):n?(!r.exclusive&&r.shared===0&&r.queue.length===0&&OO.delete(e),Promise.resolve(null)):new Promise(e=>r.queue.push({mode:t,grant:()=>e(i)}))}function jO(e){let t=!1;return()=>{t||(t=!0,e())}}var MO=()=>typeof navigator<`u`&&navigator.locks?.request?navigator.locks:null;function NO(e,{mode:t=`exclusive`,ifAvailable:n=!1}={}){let r=MO();return r?new Promise((i,a)=>{r.request(e,{mode:t,ifAvailable:n},e=>{if(!e){i(null);return}return new Promise(e=>i(jO(e)))}).catch(a)}):AO(e,t,n)}async function PO(){let e=MO();if(!e)return new Set(OO.keys());let{held:t=[]}=await e.query();return new Set(t.map(e=>e.name))}var FO=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)}},IO=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})}},LO=class{constructor(e){this._ops=new IO(e)}async call(e,t){return this._ops[e](t)}dispose(){this._ops.dispose()}};an(),Sv(),hn();var RO=`meta.json`,zO=1,BO=36e5,VO=.3,HO=100*1024**3,UO=64*1024**2,WO=8*1024**2,GO=4,KO=3e4,qO=new TextEncoder;function JO(e,{copy:t,transfer:n}){if(typeof e==`string`&&(e=qO.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 YO(e,t){try{let n=await(await e.getFileHandle(t)).getFile();return JSON.parse(await n.text())}catch{return null}}async function*XO(e){for await(let[t,n]of e.entries())n.kind===`directory`&&(yield[t,n])}var ZO=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(X.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}},QO=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:JO(t,{copy:!0,transfer:r}))??JO(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}=JO(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=WO}={}){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>=GO&&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:zO,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}=JO(JSON.stringify(n),{copy:!1});return await this._transport.call(`writeFile`,{path:this._path,name:RO,...i},a),this.area.kind===pn.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`)}},$O=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 YO(e,RO);if(!n||n.v!==zO||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 dv(e),r=await NO(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>BO&&this._touch(n,i),new ZO(this,n,i,t,r)):(r(),null)}catch(e){return r(),this.manager._issue(X.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}=JO(JSON.stringify(n),{copy:!1});this.manager._transport.call(`writeFile`,{path:[this.name,e],name:RO,...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 dv(e),s=await NO(this._lockName(o),{mode:`exclusive`});try{return r>0&&!await this.manager.ensureSpace(r,this.kind)?(s(),this.manager._issue(X.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 QO(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 dv(e),r=await NO(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}=JO(JSON.stringify({...i,...t,v:zO,key:e}),{copy:!1});return await this.manager._transport.call(`writeFile`,{path:[this.name,n],name:RO,...a},o),!0}finally{r()}}async edit(e){let t=await dv(e),n=await NO(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 QO(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 dv(e))}async removeById(e){let t=await NO(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 XO(e)){let e=await YO(r,RO);e?.v===zO&&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 PO(),n=0;for await(let[r,i]of XO(e))t.has(this._lockName(r))||await this._validMeta(i)||await this.removeById(r)&&n++;return n}},ek=class extends FO{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(mn))this.defineArea(e,{kind:e===mn.SPILL?pn.SCRATCH:pn.CACHE})}defineArea(e,{kind:t=pn.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 $O(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*VO,HO)}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>KO)&&(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===pn.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===pn.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 PO(),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=pn.CACHE){let n=async()=>{let{quota:n,usage:r}=await this.estimate(),i=e+UO-(n-r);return t===pn.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===pn.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?X.STORAGE_QUOTA_EXCEEDED:X.STORAGE_WRITE_FAILED,`${e}: ${t?.message??t}`,{area:e,error:t?.name})}dispose(){this._transport?.dispose(),this._transport=null,this._areas.clear()}};function tk({namespace:e,root:t}){let n=new LO(t);n.inline=!0;let r=new ek({root:t,transport:n,namespace:e});return r.sweep().catch(()=>{}),r}var nk="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}})}};",rk=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,nk],{type:`text/javascript;charset=utf-8`});function ik(e){let t;try{if(t=rk&&(self.URL||self.webkitURL).createObjectURL(rk),!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(nk),{type:`module`,name:e?.name})}}function ak({name:e,message:t}){let n=Error(t);return n.name=e,n}var ok=class{constructor({namespace:e,root:t=null}){this._worker=new ik,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(ak(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 sk(){return typeof WorkerGlobalScope<`u`&&globalThis instanceof WorkerGlobalScope}ii();async function ck(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 lk({namespace:e,root:t=null,transport:n=`auto`}={}){let r=t?{root:t}:await ck(e);if(!r.root)return{storage:null,reason:r.reason};if(n===`inline`||n===`auto`&&(sk()||typeof Worker>`u`))return{storage:tk({namespace:e,root:r.root})};let i=new ok({namespace:e,root:t}),a=new ek({root:r.root,transport:i,namespace:e});return a.sweep().catch(()=>{}),{storage:a}}async function uk(e){let t=ri.get(e);t||(t={refs:0,opened:lk({namespace:e})},ri.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)&&(ri.get(e)===t&&ri.delete(e),n?.dispose()))};return n?{storage:n,release:a}:(a(),{storage:null,reason:r,release:()=>{}})}function dk(e){return e.length>=2&&e[0]===31&&e[1]===139}function fk(e){return e.length>=4&&e[0]===80&&e[1]===75&&(e[2]===3||e[2]===5||e[2]===7)}function pk(e){return e.length>=263&&String.fromCharCode(...e.subarray(257,262))===`ustar`}function mk(e){return dk(e)?`gzip`:fk(e)?`zip`:pk(e)?`tar`:null}function hk(e,t,n){let r=t,i=t+n;for(;r<i&&e[r]!==0;)r++;return Pk.decode(e.subarray(t,r))}function gk(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=hk(e,t,n).trim();if(!r)return 0;let i=parseInt(r,8);return Number.isFinite(i)?i:0}function _k(e){let t=[];for(let n of e.replace(/\\/g,`/`).split(`/`))n===``||n===`.`||(n===`..`?t.pop():t.push(n));return t.join(`/`)}function vk(e){let t=Pk.decode(e).match(/^\d+ path=(.*)$/m);return t?t[1]:null}function yk(e){let t=hk(e,345,155),n=hk(e,0,100);return{type:String.fromCharCode(e[156]||48),size:gk(e,124,12),name:t?`${t}/${n}`:n}}function bk(e,t){return e===`5`||e===`g`||e===`K`||t.endsWith(`/`)||e!==`0`&&e!==` `?null:_k(t)||null}function xk(e){for(let t=0;t<jk;t++)if(e[t]!==0)return!1;return!0}async function Sk(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 Ck(e,(e,t)=>{if(r.push(e,t),n)throw n})}async function Ck(e,t){if(e instanceof Uint8Array){for(let n=0;n<e.length;n+=Mk){let r=Math.min(n+Mk,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+=Mk){let i=Math.min(r+Mk,n);t(new Uint8Array(await e.slice(r,i).arrayBuffer()),i===n)}n===0&&t(new Uint8Array,!0)}async function wk(e,t={}){let{onProgress:n,...r}=t,i=new Lk(r),a=0,o=0;return await Sk(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 Tk(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,Rk));return i=new Uint8Array(await e.slice(t,o).arrayBuffer()),a=t,i.subarray(0,r)};for(;s+jk<=n;){let e=await l(s,jk);if(xk(e))break;let{type:n,size:i,name:a}=yk(e),u=o??a;o=null;let d=s+jk;if(Ik(n)){let e=await l(d,i);o=n===`L`?hk(e,0,e.length):vk(e)}else{let e=bk(n,u);e&&r.push({path:e,size:i,offset:d})}s=d+Fk(i),t&&s>=c&&(c=s+(256<<20),t({entries:r.length,bytes:s}))}return r}function Ek({filter:e=null,sink:t=null}={}){let n=new Lk({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 Dk(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 Tk(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 Lk({...a});await Ck(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},slice:async t=>{if(o[t])return new Blob([o[t]]);let n=d.get(t);return n?e.slice(n.offset,n.offset+n.size):null},retainedBytes:c,truncated:l,indexed:d.size,index:u?{v:1,listing:u}:null}}function Ok(e,{filter:t=null}={}){let n=new Map,r=e.files.map(({path:e,file:r})=>t&&!t(e,r.size)?{path:e,size:r.size}:(n.set(e,r),{path:e,size:r.size,offset:0}));return{entries:Object.create(null),listing:r,read:async e=>{let t=n.get(e);return t?new Uint8Array(await t.arrayBuffer()):null},readHead:async(e,t)=>{let r=n.get(e);return r?new Uint8Array(await r.slice(0,t).arrayBuffer()):null},slice:async e=>n.get(e)??null,retainedBytes:0,truncated:!1,indexed:n.size}}function kk(e){let t=(Array.isArray(e)?e:[e]).filter(Boolean).map(_k);if(t.length===0)return()=>!0;let n=new Map;for(let e of t){let t=e.lastIndexOf(`/`),r=t<0?``:e.slice(0,t+1);n.has(r)||n.set(r,new Set),n.get(r).add(e.slice(t+1))}return e=>{for(let[t,r]of n){if(!e.startsWith(t))continue;let n=e.slice(t.length),i=n.indexOf(`/`);if(i<0)continue;let a=n.slice(0,i);if(!r.has(a)&&a!==`textures`)return!1}return!0}}function Ak(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 jk,Mk,Nk,Pk,Fk,Ik,Lk,Rk,zk=g((()=>{jk=512,Mk=4<<20,Nk=15e8,Pk=new TextDecoder,Fk=e=>e+(jk-e%jk)%jk,Ik=e=>e===`L`||e===`x`||e===`X`,Lk=class{constructor({filter:e=null,retain:t=null,byteBudget:n=Nk,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(jk),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(jk-this._headerLen,e.length-n);this._header.set(e.subarray(n,n+r),this._headerLen),this._headerLen+=r,n+=r,this._headerLen===jk&&(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<jk;n++)if(e[n]!==0){t=!1;break}if(t){this.finished=!0;return}let{type:n,size:r,name:i}=yk(e),a=this._pendingName??i;if(this._pendingName=null,this._size=r,this._copied=0,this._remaining=Fk(r),this._dst=null,this._special=null,this._indexed=!1,this._state=this._remaining>0?`body`:`header`,Ik(n)){this._special=n===`L`?`longname`:`pax`,this._dst=new Uint8Array(r);return}let o=bk(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=hk(this._dst,0,this._dst.length),this._dst=null;return}if(this._special===`pax`){let e=vk(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)}},Rk=1<<20}));async function Bk(e,t,n){return new Uint8Array(await e.slice(t,n).arrayBuffer())}function Vk(e,t){return e.getUint32(t+4,!0)*4294967296+e.getUint32(t,!0)}function Hk(e){let t=``;for(let n=0;n<e.length;n+=8192)t+=String.fromCharCode(...e.subarray(n,n+8192));return t}async function Uk(e){let t=e.size,n=await Bk(e,Math.max(0,t-Qk-20),t),r=new DataView(n.buffer),i=-1;for(let e=n.length-22;e>=0;e--)if(r.getUint32(e,!0)===qk){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)!==Jk)throw Error(`zip: ZIP64 locator missing`);let n=Vk(r,t+8),c=new DataView((await Bk(e,n,n+56)).buffer);if(c.getUint32(0,!0)!==Yk)throw Error(`zip: ZIP64 end record missing`);a=Vk(c,32),o=Vk(c,40),s=Vk(c,48)}let c=await Bk(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)!==Xk)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?$k.decode(f):Hk(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=Vk(l,t),t+=8),n===4294967295&&(n=Vk(l,t),t+=8),s===4294967295&&(s=Vk(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 Wk(e,t){if(t.encrypted)throw Error(`zip: "${t.name}" is encrypted`);let n=new DataView((await Bk(e,t.local,t.local+30)).buffer);if(n.getUint32(0,!0)!==Zk)throw Error(`zip: bad local header for "${t.name}"`);return t.local+30+n.getUint16(26,!0)+n.getUint16(28,!0)}async function Gk(e,t){let n=await Wk(e,t),r=await Bk(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 Kk(e,{filter:t=null}={}){let n=await Uk(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?Gk(e,n):null},o=async t=>{let n=r.get(t);if(!n)return null;if(n.method!==0)return new Blob([await Gk(e,n)]);let i=await Wk(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 qk,Jk,Yk,Xk,Zk,Qk,$k,eA=g((()=>{qk=101010256,Jk=117853008,Yk=101075792,Xk=33639248,Zk=67324752,Qk=65557,$k=new TextDecoder}));async function tA(e,t){return`${e}:${hv(await pv(t))}`}async function nA(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(mn.ARCHIVES),s=await tA(`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*oA});if(!s)return null;let u=null,d=Ek(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:aA,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(X.STORAGE_QUOTA_EXCEEDED,`ran out of room unpacking ${n}; reading it in memory instead`,{area:mn.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!==aA?(l.release(),null):{file:d,index:f,release:()=>l.release(),cached:u}}async function rA(e,t){if(!t)return null;let n=await t.area(mn.ARCHIVES).open(await tA(`tarindex`,e));if(!n)return null;try{let e=await n.json(`index.json`);return e?.v===aA?e:null}finally{n.release()}}async function iA(e,t,n){if(!t||!n)return!1;let r=await t.area(mn.ARCHIVES).create(await tA(`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 aA,oA,sA=g((()=>{zk(),hn(),Sv(),an(),aA=1,oA=3}));function cA(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 lA(e,t){try{let t=JSON.parse(JSON.stringify(e??{}));return delete t[wA],delete t[TA],t}catch{throw new NA(`${t}: userData is not plain JSON`)}}function uA(e,t,n){if(e.isInterleavedBufferAttribute||!ArrayBuffer.isView(e.array))throw new NA(`${n}: interleaved or non-typed attribute`);return{section:t.add(e.array),itemSize:e.itemSize,normalized:e.normalized===!0,name:e.name??``}}function dA(e,t){let n=`geometry ${e.name||e.uuid}`;if(Object.keys(e.morphAttributes??{}).length)throw new NA(`${n}: morph targets`);let r={};for(let[i,a]of Object.entries(e.attributes))r[i]=uA(a,t,n);return{uuid:e.uuid,name:e.name,attributes:r,index:e.index?uA(e.index,t,n):null,groups:e.groups.map(e=>({...e})),drawRange:{...e.drawRange},userData:lA(e.userData,n)}}function fA(e,t){let n={uuid:e.uuid,userData:lA(e.userData,`texture ${e.uuid}`)};for(let t of AA)n[t]=e[t];for(let t of[`repeat`,`offset`,`center`])n[t]=e[t].toArray();n.rotation=e.rotation;let r=e.userData?.[wA];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 NA(`texture ${e.name||e.uuid}: no archive path and no pixel data to keep`);return n}function pA(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),e.diffuseRoughness!==void 0&&(n.diffuseRoughness=e.diffuseRoughness);for(let t of CA)e[t]?.isTexture&&((n.engineTextures??={})[t]=e[t].uuid);return n}function mA(e,t){for(let n of Object.values(e))n?.isTexture&&t.set(n.uuid,n)}function hA(e,{environment:t=null,animations:n=[],stats:i={}}={}){let a=new PA,o=[],s=new Map,c=new Map,l=new Map,u=new Map,d=(e,t)=>{let n=cA(e);if(!n)throw new NA(`${e.type} "${e.name}" cannot be cached`);let r={type:n,uuid:e.uuid,parent:t,userData:lA(e.userData,`${n} "${e.name}"`)};for(let t of MA)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){c.set(e.geometry.uuid,e.geometry);let t=Array.isArray(e.material)?e.material:[e.material];for(let e of t)l.set(e.uuid,e),mA(e,u);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;let t=s.get(e.instanceMatrix);t||s.set(e.instanceMatrix,t=a.add(e.instanceMatrix.array)),r.instanceMatrix=t,r.instanceColor=e.instanceColor?a.add(e.instanceColor.array):null}if(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 jA)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)d(t,i)};d(e,-1),t&&u.set(t.uuid,t);let f={textures:{},images:{}};for(let e of u.keys())f.textures[e]={uuid:e};return{manifest:{v:2,nodes:o,geometries:[...c.values()].map(e=>dA(e,a)),textures:[...u.values()].map(e=>fA(e,a)),materials:[...l.values()].map(e=>pA(e,f)),animations:n.map(e=>r.AnimationClip.toJSON(e)),environment:t?t.uuid:null,stats:i},sections:a.sections,byteLength:a.length}}async function gA(e,{manifest:t,sections:n},{release:r=!1,signal:i=null}={}){for(let t of n){let{offset:n,array:a}=t,o=new Uint8Array(a.buffer,a.byteOffset,a.byteLength);for(let t=0;t<o.length;t+=DA)i?.throwIfAborted(),await e.write(`data.bin`,o.subarray(t,Math.min(o.length,t+DA)),{at:n+t});r&&(t.array=null)}n.length===0&&await e.write(`data.bin`,new Uint8Array),i?.throwIfAborted(),await e.writeJSON(`graph.json`,t)}function _A(e){let t=kA[e];if(!t)throw Error(`scene graph: unknown array type ${e}`);return t}async function vA(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=_A(s),l=r+o;if(o>OA){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+OA)).arrayBuffer()),n.set(r,new c(i.slice(r-a,l-a)))}return n}function yA(e){let t=[],n=new Set;for(let r of e.nodes)r.instanceMatrix&&!n.has(r.instanceMatrix.offset)&&(n.add(r.instanceMatrix.offset),t.push(r.instanceMatrix)),r.instanceColor&&t.push(r.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 bA(e,t){let n=new r.BufferAttribute(e.get(t.section.offset),t.itemSize,t.normalized);return n.name=t.name,n}function xA(e,t){for(let n of AA)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 SA(e,t,{loadTexture:n}){if(e?.v!==2)throw Error(`scene graph: unknown format`);let i=await vA(t,yA(e)),a=e=>i.get(e.offset),o=new Map,s={};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[wA]=t.path,e.userData[TA]=t.loader}else e=new r.DataTexture(a(t.data.section),t.data.width,t.data.height);xA(e,t),s[t.uuid]=e}let c=new r.MaterialLoader().setTextures(s),l={};for(let t of e.materials){let e=c.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),t.diffuseRoughness!==void 0&&(e.diffuseRoughness=t.diffuseRoughness);for(let[n,r]of Object.entries(t.engineTextures??{}))s[r]&&(e[n]=s[r]);l[t.uuid]=e}let u={};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,bA(i,r));t.index&&e.setIndex(bA(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,u[t.uuid]=e}let d=[];for(let t of e.nodes){let e=Array.isArray(t.material)?t.material.map(e=>l[e]):l[t.material],n;switch(t.type){case`InstancedMesh`:{n=new r.InstancedMesh(u[t.geometry],e,1);let i=o.get(t.instanceMatrix.offset);i||o.set(t.instanceMatrix.offset,i=new r.InstancedBufferAttribute(a(t.instanceMatrix),16)),n.instanceMatrix=i,n.count=t.count,t.instanceColor&&(n.instanceColor=new r.InstancedBufferAttribute(a(t.instanceColor),3));break}case`Mesh`:n=new r.Mesh(u[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 MA)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 jA)t[e]!==void 0&&(n[e]=t[e])}d.push(n),t.parent>=0&&d[t.parent].add(n)}let f=new Map(d.map(e=>[e.uuid,e]));return e.nodes.forEach((e,t)=>{e.target&&f.has(e.target)&&(d[t].target=f.get(e.target))}),{root:d[0],environment:e.environment?s[e.environment]:null,animations:e.animations.map(e=>r.AnimationClip.parse(e)),stats:e.stats}}var CA,wA,TA,EA,DA,OA,kA,AA,jA,MA,NA,PA,FA=g((()=>{CA=[`diffuseTransmissionMap`,`diffuseTransmissionColorMap`],wA=`__rayzeeArchivePath`,TA=`__rayzeeArchiveLoader`,EA=64,DA=32<<20,OA=64<<20,kA={Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint16Array,Uint32Array,Uint8ClampedArray},AA=[`name`,`mapping`,`channel`,`wrapS`,`wrapT`,`magFilter`,`minFilter`,`anisotropy`,`format`,`type`,`flipY`,`generateMipmaps`,`premultiplyAlpha`,`unpackAlignment`,`colorSpace`],jA=[`intensity`,`distance`,`decay`,`angle`,`penumbra`],MA=[`name`,`visible`,`castShadow`,`receiveShadow`,`frustumCulled`,`renderOrder`,`matrixAutoUpdate`],NA=class extends Error{constructor(e){super(e),this.name=`SceneGraphUnsupported`}},PA=class{constructor(){this.sections=[],this.length=0}add(e){let t=Math.ceil(this.length/EA)*EA;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 IA(e){e&&RA(e)&&e.buffer.transfer(0)}function LA(e,t){let n=e.constructor;if(RA(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 RA,zA=g((()=>{RA=e=>e.byteOffset===0&&e.byteLength===e.buffer.byteLength&&typeof e.buffer.transfer==`function`&&!(typeof SharedArrayBuffer<`u`&&e.buffer instanceof SharedArrayBuffer)}));function BA(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 lj.decode(e.subarray(t,n));let i=``;for(let r=t;r<n;r++)i+=String.fromCharCode(e[r]);return i}var VA,HA,UA,WA,GA,KA,qA,JA,YA,XA,ZA,QA,$A,ej,tj,nj,rj,ij,aj,oj,sj,cj,lj,uj,dj=g((()=>{VA={STRING:`string`,NUMBER:`number`,WORD:`word`,LBRACKET:`[`,RBRACKET:`]`},HA=9,UA=10,WA=12,GA=13,KA=32,qA=34,JA=35,YA=43,XA=45,ZA=46,QA=48,$A=57,ej=91,tj=93,nj=69,rj=101,ij=e=>e===KA||e===HA||e===UA||e===GA||e===WA,aj=e=>e>=QA&&e<=$A,oj=15,sj=22,cj=(()=>{let e=new Float64Array(sj+1);for(let t=0;t<e.length;t++)e[t]=10**t;return e})(),lj=new TextDecoder,uj=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&&ij(e[t]);)t++;if(t<n&&e[t]===JA){for(;t<n&&e[t]!==UA;)t++;continue}break}if(t>=n)return this.i=t,null;let r=e[t];if(r===ej)return this.i=t+1,{type:VA.LBRACKET};if(r===tj)return this.i=t+1,{type:VA.RBRACKET};if(r===qA){let r=++t;for(;t<n&&e[t]!==qA;)t++;if(t>=n)throw Error(`PBRT tokenizer: unterminated string literal`);return this.i=t+1,{type:VA.STRING,value:BA(e,r,t)}}if(aj(r)||r===ZA&&aj(e[t+1])||(r===XA||r===YA)&&(aj(e[t+1])||e[t+1]===ZA&&aj(e[t+2])))return this._scanNumber(t);let i=t;for(;t<n;){let n=e[t];if(ij(n)||n===qA||n===ej||n===tj||n===JA)break;t++}return this.i=t,{type:VA.WORD,value:BA(e,i,t)}}_scanNumber(e){let t=this.bytes,n=this.n,r=e,i=!1;t[r]===XA?(i=!0,r++):t[r]===YA&&r++;let a=0,o=0,s=0;for(;r<n&&aj(t[r]);)a=a*10+(t[r]-QA),o++,r++;if(r<n&&t[r]===ZA)for(r++;r<n&&aj(t[r]);)a=a*10+(t[r]-QA),o++,s++,r++;let c=0;if(r<n&&(t[r]===rj||t[r]===nj)){let e=r+1,i=!1;if(e<n&&(t[e]===XA||t[e]===YA)&&(i=t[e]===XA,e++),e<n&&aj(t[e])){let a=0;for(;e<n&&aj(t[e]);)a=a*10+(t[e]-QA),e++;c=i?-a:a,r=e}}if(this.i=r,o===0)throw Error(`PBRT tokenizer: invalid number "${BA(t,e,r)}"`);let l=c-s;if(!(o<=oj&&l>=-sj&&l<=sj)){let n=Number(BA(t,e,r));if(Number.isNaN(n))throw Error(`PBRT tokenizer: invalid number "${BA(t,e,r)}"`);return{type:VA.NUMBER,value:n}}let u=l===0?a:l>0?a*cj[l]:a/cj[-l];return i&&(u=-u),{type:VA.NUMBER,value:u}}}}));function fj(){return[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}function pj(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 mj(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 hj(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 gj(e,t,n){return[1,0,0,0,0,1,0,0,0,0,1,0,e,t,n,1]}function _j(e,t,n){return[e,0,0,0,0,t,0,0,0,0,n,0,0,0,0,1]}function vj(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 yj(e,t){return[e[0]-t[0],e[1]-t[1],e[2]-t[2]]}function bj(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 xj(e){let t=Math.hypot(e[0],e[1],e[2])||1;return[e[0]/t,e[1]/t,e[2]/t]}function Sj(e,t,n){let r=xj(yj(t,e)),i=xj(bj(xj(n),r)),a=bj(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 Cj(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 fj();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 wj=g((()=>{}));function Tj(e,t){if(e===t)return!0;for(let n=0;n<16;n++)if(e[n]!==t[n])return!1;return!0}function Ej(e,t){return Pj!==null&&Pj.params===e?Pj.read.push(t):Fj.size!==0&&Fj.get(e)?.read.push(t),e?.[t]}function Dj(e,t){let n=Pj!==null&&Pj.params===e?Pj:Fj.get(e);n&&(n.approximated??=new Set).add(t)}var Oj,kj,Aj,jj,Mj,Nj,Pj,Fj,Ij,Lj,Rj=g((()=>{zA(),dj(),wj(),Oj=8,kj=1,Aj=2,jj=3,Mj=new Set([`Identity`,`Transform`,`CoordinateSystem`,`CoordSysTransform`,`ActiveTransform`,`TransformTimes`,`Camera`,`Film`,`WorldBegin`,`MakeNamedMaterial`,`Texture`,`MakeNamedMedium`,`LightSource`,`AreaLightSource`,`ObjectBegin`,`ObjectEnd`,`ObjectInstance`]),Nj={integer:Int32Array,point3:Float32Array,point2:Float32Array,vector3:Float32Array,vector2:Float32Array,vector:Float32Array,normal:Float32Array,rgb:Float32Array},Pj=null,Fj=new Map,Ij=class{constructor(){this.unused=new Map,this.approximated=new Map}translate(e,t,n,r=null){if(Fj.has(e))return n();let i=Pj,a=Pj={params:e,label:t,approximated:null,read:[r]};try{return n()}finally{Pj=i;for(let t in e)this._count(a,t,!a.read.includes(t))}}open(e,t,n=null){e&&!Fj.has(e)&&Fj.set(e,{usage:this,label:t,approximated:null,read:[n]})}finish(){for(let[e,t]of Fj)if(t.usage===this){Fj.delete(e);for(let n in e)this._count(t,n,!t.read.includes(n))}let e=e=>[...e].flatMap(([e,t])=>[...t].map(([t,n])=>[`${e}: ${t}`,n])),t=t=>Object.fromEntries(e(t).sort((e,t)=>e[0]<t[0]?-1:1));return{unused:t(this.unused),approximated:t(this.approximated)}}_count(e,t,n){let r=e.approximated?.has(t)?this.approximated:n?this.unused:null;if(!r)return;let i=r.get(e.label);i||r.set(e.label,i=new Map),i.set(t,(i.get(t)??0)+1)}},Lj=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.usage=e.usage??null,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=fj(),this.ctmEnd=null,this.activeTransform=jj,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 uj(e)),this._movedShapes&&(this.ir.shapes=this.ir.shapes.filter(Boolean));for(let e of this.ir.instances.values())e.matrices=LA(e.matrices,e.count*16),e.matricesEnd&&=LA(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=LA(n.matrices,e),n.matricesEnd&&=LA(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||Tj(this.ctmEnd,this.ctm)?null:(this.ir.hasMotion=!0,this.ctmEnd.slice())}_concat(e){if(this.activeTransform===jj&&this.ctmEnd===null){this.ctm=hj(this.ctm,e);return}let t=this.ctmEnd??this.ctm;this.ctmEnd=this.activeTransform&Aj?hj(t,e):t,this.activeTransform&kj&&(this.ctm=hj(this.ctm,e))}_setCTM(e){if(this.activeTransform===jj){this.ctm=e,this.ctmEnd=null;return}let t=this.ctmEnd??this.ctm;this.ctmEnd=this.activeTransform&Aj?e:t,this.activeTransform&kj&&(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!==VA.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!==VA.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===VA.LBRACKET){this._next();let e=[];for(;this._peek()&&this._peek().type!==VA.RBRACKET;)e.push(this._expectNumber(`transform element`));return this._next(),e}return this._readNumbers(e)}_parseParams(){let e={};for(;this._peek()&&this._peek().type===VA.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===VA.LBRACKET;t&&this._next();let n=()=>{let e=this._peek();return t?e&&e.type!==VA.RBRACKET:!1};if(!t)return[this._coerceValueToken(this._next())];if(this._peek()&&this._peek().type===VA.NUMBER){let t=[];for(;n()&&t.length<Oj;){let e=this._next();if(e.type!==VA.NUMBER)return this._finishMixedValue(t,t.length,e);t.push(e.value)}if(!n())return this._next(),t;let r=new(Nj[e]||Float64Array)(Oj*4);r.set(t);let i=t.length;for(;n();){let e=this._next();if(e.type!==VA.NUMBER)return this._finishMixedValue(r,i,e);i===r.length&&(r=LA(r,r.length*2)),r[i++]=e.value}return this._next(),i===r.length?r:LA(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!==VA.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===VA.NUMBER||e.type===VA.STRING)return e.value;if(e.type===VA.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!==VA.WORD)throw Error(`PBRT parser: expected directive, got ${e.type} ${e.value??``}`);Mj.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(fj());break;case`Translate`:{let[e,t,n]=this._readNumbers(3);this._concat(gj(e,t,n));break}case`Scale`:{let[e,t,n]=this._readNumbers(3);this._concat(_j(e,t,n));break}case`Rotate`:{let[e,t,n,r]=this._readNumbers(4);this._concat(vj(e,t,n,r));break}case`LookAt`:{let e=this._readNumbers(9),t=Sj([e[0],e[1],e[2]],[e[3],e[4],e[5]],[e[6],e[7],e[8]]);this._concat(Cj(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:Cj(this.ctm)};let n=this._ctmEndSnapshot();n&&(this.ir.camera.cameraToWorldEnd=Cj(n));break}case`Film`:{let t=this._expectString(`Film type`),n=this._parseParams();this._translate(n,`${e} ${t}`,()=>{this.ir.film={xresolution:this._num(Ej(n,`xresolution`),1280),yresolution:this._num(Ej(n,`yresolution`),720),resolutionGiven:!!(n.xresolution||n.yresolution),filename:this._str(Ej(n,`filename`),null)}});break}case`Integrator`:{let t=this._expectString(`Integrator type`),n=this._parseParams();this._translate(n,`${e} ${t}`,()=>{n.maxdepth&&(this.ir.integrator={maxdepth:this._num(Ej(n,`maxdepth`),5)})});break}case`Sampler`:{let t=this._expectString(`Sampler type`),n=this._parseParams();this._translate(n,`${e} ${t}`,()=>{n.pixelsamples&&(this.ir.sampler={pixelsamples:this._num(Ej(n,`pixelsamples`),16)})});break}case`PixelFilter`:case`Filter`:case`Accelerator`:case`ColorSpace`:{let t=this._peek()?.type===VA.STRING?this._next().value:``;this._translate(this._parseParams(),`${e} ${t}`);break}case`Option`:this._translate(this._parseParams(),e);break;case`WorldBegin`:this.ctm=fj(),this.ctmEnd=null,this.activeTransform=jj,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`:{let t=this._expectString(`Attribute target`);this._translate(this._parseParams(),`${e} ${t}`);break}case`ActiveTransform`:{let e=this._next()?.value;e===`StartTime`?this.activeTransform=kj:e===`EndTime`?this.activeTransform=Aj:e===`All`?this.activeTransform=jj: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===VA.STRING?this._next().value:``;this._peek()?.type===VA.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(),i={dataType:t,class:n,params:r};this._str(r.mapping,`uv`)!==`uv`&&(i.ctm=this._ctmSnapshot()),this.ir.namedTextures.set(e,i);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&&!Tj(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&&!Tj(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._translate(this._parseParams(),e);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 uj(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!==jj||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===jj&&Tj(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=Cj(n.ctm),s=[],c=null,l=null;for(let e=r;e<i;e++){let t=this.ir.shapes[e];t.ctm!==c&&(l=hj(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}_translate(e,t,n=()=>{}){return this.usage?this.usage.translate(e,t,n):n()}_skipNamedAndParams(){this._peek()&&this._peek().type===VA.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 zj(e){let t=Hj[e];return t?{sigmaS:t[0].slice(),sigmaA:t[1].slice()}:null}function Bj(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 Vj(e,t){let n=Math.min(Math.max(e,0),Bj(1,t)),r=0,i=1;for(let e=0;e<48;e++){let e=(r+i)/2;Bj(e,t)<n?r=e:i=e}return(r+i)/2}var Hj,Uj=g((()=>{Hj={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 Wj(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 Gj(e,t,n){let r=Ej(e,t);return r&&r.type!==`float`&&r.type!==`integer`&&Dj(e,t),r&&typeof r.value[0]==`number`?r.value[0]:n}function Kj(e,t,n){let r=Ej(e,t);if(r?.type!==`spectrum`||typeof r.value[0]!=`number`)return Gj(e,t,n);Dj(e,t);let i=r.value;if(i.length<2)return n;let a=2;for(;a<i.length-1&&i[a]<550;)a+=2;return a>=i.length-1||i[a-2]>=550?i[a>=i.length-1?a-1:1]:i[a-1]+(i[a+1]-i[a-1])*(550-i[a-2])/(i[a]-i[a-2])}function qj(e,t,n){let r=Ej(e,t);return r&&typeof r.value[0]==`string`?r.value[0]:n}function Jj(e,t,n){let r=Ej(e,t)?.value?.[0];return r===void 0?n:r===!0||r===`true`}async function Yj(e,t,n,r=null){let i=Ej(e,t);if(!i)return{rgb:r,texture:null};if(i.type===`texture`){let a=i.value[0],o=await n.resolveNamedTexture(a);return o&&o.texture?{rgb:o.constant??null,texture:o.texture}:o&&o.constant?{rgb:o.constant,texture:null}:(n.warn(`texture "${a}" could not be resolved`),Dj(e,t),{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 Dj(e,t),{rgb:Wj(i.value[0]),texture:null};if(i.type===`spectrum`){if(Dj(e,t),typeof i.value[0]==`string`){let e=Xj(i.value[0]);return e&&iM[e]?{rgb:iM[e].slice(),texture:null}:(n.warn(`named spectrum "${i.value[0]}" approximated to gray`),{rgb:[.5,.5,.5],texture:null})}let r=0,a=0;for(let e=1;e<i.value.length;e+=2)r+=i.value[e],a++;let o=a?r/a:.5;return{rgb:[o,o,o],texture:null}}return Dj(e,t),{rgb:r,texture:null}}function Xj(e){let t=e.toLowerCase().match(/metal-([a-z]+)/);if(t)return t[1];for(let t of Object.keys(iM))if(e.toLowerCase().includes(t))return t;return null}async function Zj(e,t,n){let r=Ej(e,t);return r?typeof r.value[0]==`number`?r.value[0]:(Dj(e,t),r.type===`texture`?await n.floatTextureMean?.(r.value[0])??null:null):null}async function Qj(e,t,n,r=``){let i=oM(e),a=e=>i?Math.sqrt(Math.max(e,0)):e,o=null,s=await Zj(e,`${r}roughness`,n);if(s!==null)o=a(s);else{let t=await Zj(e,`${r}uroughness`,n),i=await Zj(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 $j(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=oM(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 Qj(n,r,i,a)}async function eM(e,t,n,r){let i=Ej(e,t);return i?.type===`texture`?(Dj(e,t),await n.textureMeanRGB?.(i.value[0])??r):(await Yj(e,t,n,r)).rgb??r}async function tM(e,t,n){let i=Kj(t,`eta`,1.33),a=Gj(t,`scale`,1),o=e=>e.map(e=>Math.max(0,e*a)),s=Gj(t,`g`,0),c,l,u=qj(t,`name`,``),d=u?zj(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 eM(t,`sigma_a`,n,sM)),l=o(await eM(t,`sigma_s`,n,cM));else if(t.reflectance&&!u){let e=await eM(t,`reflectance`,n,[.5,.5,.5]),r=o(t.mfp?await eM(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=Vj(e[t],i);l[t]=a*n/(1-s+a*s),c[t]=n-l[t]}}else c=o(sM),l=o(cM);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?Bj(n/(c[t]+n),i):0})),await $j(e,`roughness`,t,0,n)}async function nM(e,t,n,r,i,a){let o=await Yj(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 Yj(t,`${r}eta`,n,[.2,.92,1.1])).rgb,i=(await Yj(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 Yj(t,`${r}eta`,n,aM)).rgb||aM:iM.cu);e.metalness=1}async function rM(e,t){if(e?.material)return e.material;let n=e?.type||`diffuse`,i=e?.params||{};t.trackParams?.(i,`Material ${n}`,`type`);let 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 Yj(i,`reflectance`,t,[.5,.5,.5])),a.roughness=1,a.metalness=0,a.specularIntensity=0;break;case`conductor`:case`metal`:await nM(a,i,t,``,s,o),await $j(a,`roughness`,i,0,t);break;case`coatedconductor`:await nM(a,i,t,`conductor.`,s,o),await $j(a,`roughness`,i,0,t,`conductor.`),a.clearcoat=1,await $j(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=Kj(i,`eta`,1.5),await $j(a,`roughness`,i,0,t),a.thickness=n===`thindielectric`?0:Gj(i,`thickness`,0);break;case`coateddiffuse`:s(await Yj(i,`reflectance`,t,[.5,.5,.5])),a.roughness=.6,a.metalness=0,a.clearcoat=1,await $j(a,`clearcoatRoughness`,i,0,t);break;case`diffusetransmission`:{let e=Gj(i,`scale`,1),n=t=>Math.min(1,Math.max(0,e*t)),o=await Yj(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 Yj(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`),Dj(i,`transmittance`)),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=Ej(i,`materials`)?.value||[],n=Math.max(0,Math.min(1,Gj(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([rM(o,t),rM(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 tM(a,i,t);break;case`hair`:case`measured`:t.warn(`material "${n}" not supported — using diffuse approximation`),o((await Yj(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=qj(i,`normalmap`,null);return c&&t.resolveNormalMap&&(a.normalMap=await t.resolveNormalMap(c)),a.clearcoat>0&&a.normalMap&&(a.clearcoatNormalMap=a.normalMap),a.roughness=Math.max(0,Math.min(1,a.roughness)),a}var iM,aM,oM,sM,cM,lM=g((()=>{Uj(),Rj(),iM={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]},aM=[.92,.92,.92],oM=e=>{let t=Ej(e,`remaproughness`)?.value?.[0];return t!==!1&&t!==`false`},sM=[.0011,.0024,.014],cM=[2.55,3.21,3.77]}));function uM(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=n&&(e.data instanceof Uint8Array||e.data instanceof Uint8ClampedArray)?Float64Array.from({length:256},(e,t)=>n(t/255)):null,f=d?t=>d[e.data[t]]:t=>n?n(e.data[t]/255):e.data[t],p=t===1&&c===4&&dM(e),m=t===1&&c>=3&&!p;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*(p?f(s+3):m?(f(s)+f(s+1)+f(s+2))/3:f(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,uv:null,...a}}function dM(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 fM(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 pM({data:e,channels:t}){let n=[0,0,0];for(let r=0;r<e.length;r++)n[r%t]+=e[r];let r=e.length/t||1;return[0,1,2].map(e=>n[Math.min(e,t-1)]/r)}function mM(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 hM(e,t,{alphaOf:n=null,linear:r=!1}={}){let i=yM(e.find(e=>e.layer)?.layer.uv),a=null,o=0;if(e=e.map(e=>e.layer?yM(e.layer.uv)===i?((!a||e.layer.width*e.layer.height>a.width*a.height)&&(a=e.layer),e):(o++,{rgb:pM(e.layer).map((t,n)=>t*(e.tint?.[n]??1)),clamp:e.clamp}):e),!a)return null;let s=Math.min(a.width,vM),c=Math.min(a.height,vM),l=new Uint8Array(s*c*4),u=e.map(()=>[0,0,0]);for(let i=0;i<c;i++){let o=(i+.5)/c,d=(o-a.dv)/a.sv;for(let c=0;c<s;c++){let f=(c+.5)/s,p=(f-a.du)/a.su;for(let t=0;t<e.length;t++){let n=e[t],r=u[t];if(n.layer){let e=n.layer;if(mM(e,e===a?f:e.su*p+e.du,e===a?o: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(u),h=(i*s+c)*4;for(let e=0;e<3;e++){let t=Math.min(1,Math.max(0,m[e]));l[h+e]=Math.round(255*(r?t:xM(t)))}l[h+3]=n?Math.round(255*Math.min(1,Math.max(0,n(u)))):255}}return{data:l,width:s,height:c,mapping:{su:a.su,sv:a.sv,du:a.du,dv:a.dv,uv:a.uv??null},averaged:o}}function gM(e,t,n,r,i){if(e.type===`planar`){let{vs:a,vt:o}=e;i[0]=e.ds+t*a[0]+n*a[1]+r*a[2],i[1]=e.dt+t*o[0]+n*o[1]+r*o[2]}else if(e.type===`spherical`){let e=Math.hypot(t,n,r)||1,a=Math.atan2(n,t);i[0]=Math.acos(Math.min(1,Math.max(-1,r/e)))/Math.PI,i[1]=(a<0?a+2*Math.PI:a)/(2*Math.PI)}else i[0]=(Math.PI+Math.atan2(n,t))/(2*Math.PI),i[1]=r;return i}function _M(e,t,n,r){let i=e.length/3,a=n,o=CM[r.type],s=new Float64Array(i*2),c=o===void 0?null:new Float64Array(i),l=[0,0],u=0;for(let t=0;t<i;t++){let n=e[t*3],i=e[t*3+1],o=e[t*3+2],d=a[0]*n+a[4]*i+a[8]*o+a[12],f=a[1]*n+a[5]*i+a[9]*o+a[13];gM(r,d,f,a[2]*n+a[6]*i+a[10]*o+a[14],l),s[t*2]=l[0],s[t*2+1]=l[1],c&&(c[t]=Math.hypot(d,f),c[t]>u&&(u=c[t]))}let d=[],f=t;if(c){let e=u*1e-6,n=new Map,r=[0,0,0],a=[0,0,0],l=(t?t.length:i)/3;for(let u=0;u<l;u++){let l=1/0,p=-1/0,m=0,h=0;for(let n=0;n<3;n++){let i=r[n]=t?t[u*3+n]:u*3+n;c[i]<=e||(l=Math.min(l,s[i*2+o]),p=Math.max(p,s[i*2+o]))}let g=p-l>.5;for(let t=0;t<3;t++){let n=s[r[t]*2+o];c[r[t]]<=e?a[t]=NaN:(a[t]=g&&n<.5?n+1:n,m+=a[t],h++)}for(let e=0;e<3;e++){let c=r[e],l=Number.isNaN(a[e])?h>0?m/h:s[c*2+o]:a[e];if(l===s[c*2+o])continue;if(!t){s[c*2+o]=l;continue}let p=`${c}|${l}`,g=n.get(p);g===void 0&&(n.set(p,g=i+d.length/2),d.push(c,l)),f===t&&(f=Uint32Array.from(t)),f[u*3+e]=g}}}let p=d.length/2,m=new Float32Array((i+p)*2);for(let e=0;e<i*2;e++)m[e]=s[e];let h=new Uint32Array(p);for(let e=0;e<p;e++){let t=h[e]=d[e*2];m[(i+e)*2]=s[t*2],m[(i+e)*2+1]=s[t*2+1],m[(i+e)*2+o]=d[e*2+1]}return{uv:m,index:f===t?null:f,extra:h}}var vM,yM,bM,xM,SM,CM,wM=g((()=>{vM=4096,yM=e=>e?.key??``,bM=e=>e<=.04045?e/12.92:((e+.055)/1.055)**2.4,xM=e=>e<=.0031308?e*12.92:1.055*e**(1/2.4)-.055,SM=([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]},CM={spherical:1,cylindrical:0}}));function TM(e){return e===3?3/16:3/(8*e)}function EM(e){return 1/(e+3/(8*TM(e)))}function DM(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 OM(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 kM(e,t){let n=e.length/3,r=DM(n,t),i=r.edgeV0.length,a=OM(e,r,n,TM,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 AM(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=kM(i,a);i=e.positions,a=e.indices,o++}let s=i.length/3,c=OM(i,DM(s,a),s,EM,1/5);return{positions:Float32Array.from(c),indices:Uint32Array.from(a),levels:o}}var jM=g((()=>{}));function MM(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 NM(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 PM(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?Cj(t):null,c=e.srgb?FM: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]=MM(f,p,m);NM(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 FM,IM=g((()=>{wj(),FM=(()=>{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 LM(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 RM(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 zM(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 BM(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 VM(e,t){let n=e.length/3;return t===`bspline`?n-3:Math.max(1,(n-1)/3)}function HM(e,t,n,r,i,a,o){let s=Math.floor(r);s>=n&&(s=n-1);let c=r-s;t===`bspline`?LM(c,i):RM(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 UM(e,t,n){let r=[0,0,0,0];return i=>{let a=i*n,o=Math.floor(a);o>=n&&(o=n-1),t===`bspline`?LM(a-o,r):RM(a-o,r);let s=t===`bspline`?o:o*3;return r[0]*e[s]+r[1]*e[s+1]+r[2]*e[s+2]+r[3]*e[s+3]}}function WM(e,t,n){let r=VM(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++)HM(e,t,r,n/i*r,o,a,n*3);return{points:a,count:i+1,spans:r}}function GM(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 KM(e,t,n,r,i){let{points:a,count:o,spans:s}=n;if(o<3)return null;let c=new Float64Array((o-1)*3),l=[0,0,0,0],u=o-1;for(let n=0;n<u;n++)HM(e,t,s,(n+.5)/u*s,l,c,n*3);let d=0;for(let e=0;e<u;e++)d=Math.max(d,GM(c,e,a,e,e+1));let f=e=>Math.max(d,r*.5*i(e/u)),p=(e,t)=>{for(let n=e+1;n<t;n++)if(GM(a,n,a,e,t)>f(n))return!1;for(let n=e;n<t;n++)if(GM(c,n,a,e,t)>f(n+.5))return!1;return!0},m=new Int32Array(o),h=0;m[h++]=0;for(let e=0;e<u;){let t=e+1;for(;t<u&&p(e,t+1);)t++;m[h++]=t,e=t}return h===o?null:m.subarray(0,h)}function qM(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??QM)),s=Math.max(1,Math.round(e.sides??1));if(!t||t.length<12)return null;let c=WM(t,n,o);if(!c)return null;let{points:l,count:u,spans:d}=c,f=e.widths?UM(e.widths,n,d):e=>r+(i-r)*e,p=e.tolerance>0?KM(t,n,c,e.tolerance,f):null,m=p?p.length:u,h=s>=3?s:s*2,g=new Float32Array(m*h*3),_=[0,0,0],v=[0,0,0],y=[0,0,0],b=[0,0,0],x=!1,S=0;for(let e=0;e<u;e++){let t=Math.max(0,e-1),n=Math.min(u-1,e+1);if(_[0]=l[n*3]-l[t*3],_[1]=l[n*3+1]-l[t*3+1],_[2]=l[n*3+2]-l[t*3+2],zM(_),x){let e=v[0]*_[0]+v[1]*_[1]+v[2]*_[2];v[0]-=e*_[0],v[1]-=e*_[1],v[2]-=e*_[2],Math.hypot(v[0],v[1],v[2])<1e-9&&BM(_,[0,1,0],v),zM(v)}else{if(a&&a.length>=3)v[0]=a[0],v[1]=a[1],v[2]=a[2],BM(_,v,b),v[0]=b[0],v[1]=b[1],v[2]=b[2];else{let e=Math.abs(_[0]),t=Math.abs(_[1]),n=Math.abs(_[2]);BM(_,e<t&&e<n?[1,0,0]:t<n?[0,1,0]:[0,0,1],v)}Math.hypot(v[0],v[1],v[2])<1e-9&&BM(_,[0,1,0],v),zM(v),x=!0}if(p&&p[S]!==e)continue;BM(_,v,y),zM(y);let r=f(e/(u-1||1))*.5,i=l[e*3],o=l[e*3+1],c=l[e*3+2];for(let e=0;e<h;e++){let t,n,a;if(s>=3){let r=e/s*Math.PI*2,i=Math.cos(r),o=Math.sin(r);t=v[0]*i+y[0]*o,n=v[1]*i+y[1]*o,a=v[2]*i+y[2]*o}else{let r=e<2?v:y,i=e%2==0?-1:1;t=r[0]*i,n=r[1]*i,a=r[2]*i}let l=(S*h+e)*3;g[l]=i+t*r,g[l+1]=o+n*r,g[l+2]=c+a*r}S++}let C=s,w=new Uint32Array((m-1)*C*6),T=0;for(let e=0;e<m-1;e++)for(let t=0;t<C;t++){let n=s>=3?t:t*2,r=s>=3?(t+1)%s:t*2+1,i=e*h+n,a=e*h+r,o=(e+1)*h+r,c=(e+1)*h+n;w[T++]=i,w[T++]=a,w[T++]=o,w[T++]=i,w[T++]=o,w[T++]=c}return{positions:g,indices:T===w.length?w:LA(w,T)}}function JM(e,t,n,r){let i=new Float64Array((n.length*3+1)*3),a=t?new Float64Array(n.length*3+1):null,o=0;for(let s=0;s<n.length;s++){let[c,l,u,d]=n[s];if(s===0){for(let t=0;t<3;t++)i[t]=e[c*3+t];a&&(a[0]=t[c])}if(r===`linear`)$M(i,(o+1)*3,e,c,l,1/3),$M(i,(o+2)*3,e,c,l,2/3);else for(let t=0;t<3;t++)i[(o+1)*3+t]=e[c*3+t]+(e[l*3+t]-e[u*3+t])/6,i[(o+2)*3+t]=e[l*3+t]-(e[d*3+t]-e[c*3+t])/6;for(let t=0;t<3;t++)i[(o+3)*3+t]=e[l*3+t];a&&(a[o+1]=t[c]+(t[l]-t[c])/3,a[o+2]=t[c]+(t[l]-t[c])*2/3,a[o+3]=t[l]),o+=3}return{P:i,widths:a,basis:`bezier`}}function YM(e,t,n,r,i){let a=e.length/3,o=i===`periodic`;if(n===`linear`){if(a<2)return null;let n=[];for(let e=0;e+1<a;e++)n.push([e,e+1]);return o&&a>2&&n.push([a-1,0]),JM(e,t,n,`linear`)}if(r===`bspline`)return i===`pinned`?XM(e,t,[0,0,...Array.from({length:a},(e,t)=>t),a-1,a-1],`bspline`):o?XM(e,t,[...Array.from({length:a},(e,t)=>t),0,1,2],`bspline`):a>=4?{P:e,widths:t,basis:`bspline`}:null;if(r===`bezier`)return o?XM(e,t,[...Array.from({length:a},(e,t)=>t),0],`bezier`):a>=4?{P:e,widths:t,basis:`bezier`}:null;if(r===`catmullRom`){let n=[],r=e=>o?(e+a)%a:Math.min(a-1,Math.max(0,e)),s=o||i===`pinned`?0:1,c=o?a:i===`pinned`?a-1:a-2;for(let e=s;e<c;e++)n.push([r(e),r(e+1),r(e-1),r(e+2)]);return n.length?JM(e,t,n,`catmullRom`):null}return null}function XM(e,t,n,r){let i=new Float64Array(n.length*3),a=t?new Float64Array(n.length):null;return n.forEach((n,r)=>{for(let t=0;t<3;t++)i[r*3+t]=e[n*3+t];a&&(a[r]=t[n])}),{P:i,widths:a,basis:r}}function ZM(e){let{P:t,counts:n,widths:r=null,widthMode:i=`constant`,N:a=null,normalMode:o=`vertex`,type:s=`cubic`,basis:c=`bspline`,wrap:l=`nonperiodic`}=e,u=[],d=0,f=0,p=0,m=0,h=0;for(let g=0;g<n.length;g++){let _=n[g],v=t.subarray?t.subarray(m*3,(m+_)*3):t.slice(m*3,(m+_)*3),y=null,b=1;if(r?.length)if(i===`vertex`)y=Float64Array.from({length:_},(e,t)=>r[m+t]);else if(i===`uniform`)b=r[g]??r[0];else if(i===`varying`){let e=s===`linear`?_-1:c===`bezier`?(_-1)/3:_-3,t=Math.max(1,Math.round(e)+1),n=Array.from({length:t},(e,t)=>r[h+t]??r[r.length-1]);h+=t,y=Float64Array.from({length:_},(e,r)=>n[Math.min(t-1,Math.round(r/Math.max(1,_-1)*(t-1)))])}else b=r[0];let x=null;if(a?.length){let e=o===`uniform`?g:o===`constant`?0:m;x=[a[e*3],a[e*3+1],a[e*3+2]]}let S=YM(v,y,s,c,l),C=S&&qM({P:S.P,basis:S.basis,widths:S.widths,width0:b,width1:b,N:x,steps:e.steps,sides:e.sides,tolerance:e.tolerance});C?(u.push(C),d+=C.positions.length/3,f+=C.indices.length):p++,m+=_}if(u.length===0)return null;let g=new Float32Array(d*3),_=new Uint32Array(f),v=0,y=0;for(let e of u){g.set(e.positions,v*3);for(let t=0;t<e.indices.length;t++)_[y+t]=e.indices[t]+v;v+=e.positions.length/3,y+=e.indices.length}return{positions:g,indices:_,skipped:p}}var QM,$M,eN=g((()=>{zA(),QM=2,$M=(e,t,n,r,i,a)=>{for(let o=0;o<3;o++)e[t+o]=n[r*3+o]+(n[i*3+o]-n[r*3+o])*a}}));async function tN(e,t,n){let r=Ej(e,t);if(r?.type===`spectrum`&&typeof r.value[0]==`string`&&r.value[0].startsWith(`stdillum`))return[1,1,1];let i=(await Yj(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 nN(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 rN(e,t){if(t<=e.length)return e;let n=e.length||1;for(;n<t;)n*=2;return LA(e,n)}function iN(e){return e instanceof Float32Array?e:Float32Array.from(e)}function aN(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 oN(e,t){let n=Math.min(e.width,jN),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 sN(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 cN(e){let t=qj(e,`encoding`,`sRGB`);if(t===`linear`)return e=>e;let n=/^gamma\s+([\d.]+)$/.exec(t);return n?e=>e**Number(n[1]):bM}function lN(e){return{su:Gj(e,`uscale`,1),sv:Gj(e,`vscale`,1),du:Gj(e,`udelta`,0),dv:Gj(e,`vdelta`,0)}}function uN(e,t,n){let r=Ej(e,t)?.value;return r&&r.length>=3?[r[0],r[1],r[2]]:n}function dN(e,t){let n=qj(e,`mapping`,`uv`);if(!HN.has(n))return{...lN(e),uv:null};let r={type:n,textureFromWorld:Cj(t??fj())};return n===`planar`&&Object.assign(r,{vs:uN(e,`v1`,[1,0,0]),vt:uN(e,`v2`,[0,1,0]),ds:Gj(e,`udelta`,0),dt:Gj(e,`vdelta`,0)}),r.key=JSON.stringify(r),{su:1,sv:1,du:0,dv:0,uv:r}}function fN(e,{su:t,sv:n,du:r,dv:i,uv:a=null}){e.repeat.set(t,n),e.offset.set(r,i),a&&(e.userData.pbrtUV=a)}function pN(e){for(let t of UN)if(e[t])return e[t].userData.pbrtUV??null;return null}function mN(e,t){let{array:n,itemSize:i,count:a}=e,o=new n.constructor((a+t.length)*i);o.set(n.subarray(0,a*i));for(let e=0;e<t.length;e++)for(let r=0;r<i;r++)o[(a+e)*i+r]=n[t[e]*i+r];return new r.BufferAttribute(o,i,e.normalized)}function hN(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?xM(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 gN({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,fN(o,i),o.needsUpdate=!0,o}function _N(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 vN(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 yN(e){let t=Gj(e,`radius`,1),n=Gj(e,`zmin`,-t),r=Gj(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:KN(e)}}function bN(e){let t=Gj(e,`zmin`,-1),n=Gj(e,`zmax`,1);return{radius:Gj(e,`radius`,1),zMin:Math.min(t,n),zMax:Math.max(t,n),phiMax:KN(e)}}function xN(e){return{radius:Gj(e,`radius`,1),inner:Gj(e,`innerradius`,0),height:Gj(e,`height`,0),phiMax:KN(e)}}function SN(e,t,n){let i=Math.max(3,Math.ceil(GN*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 CN(e,t){let n=e.params;switch(e.type){case`sphere`:{let{radius:e,zMin:t,zMax:r,phiMax:i}=yN(n);return i*e*(r-t)}case`cylinder`:{let{radius:e,zMin:t,zMax:r,phiMax:i}=bN(n);return i*e*(r-t)}case`disk`:{let{radius:e,inner:t,phiMax:r}=xN(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 wN(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*xM(Math.min(1,Math.max(0,o[e]))));r[s+3]=255}return r}function TN(e){let t=e.clone();for(let n of Object.keys(e))n in t||(t[n]=e[n]);return t}function EN(e,t){let n=TN(e);return n.transparent=!0,n.opacity=e.opacity*t,n}function DN(e,t){if(e.float||!dM(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 ON(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 kN,AN,jN,MN,NN,PN,FN,IN,LN,RN,zN,BN,VN,HN,UN,WN,GN,KN,qN,JN,YN,XN,ZN=g((()=>{zA(),lM(),wM(),jM(),Rj(),IM(),eN(),wj(),qn(),Do(),kN=new Set([`distant`,`point`,`spot`]),AN=[1,0,0,0,0,1,0,0,0,0,-1,0,0,0,0,1],jN=4096,MN=1e3,NN=45e6,PN=6e6,FN=256,IN=4096,LN=5e5,RN=1e6,zN=2,BN={flat:1,ribbon:1,cylinder:2},VN=.05,HN=new Set([`planar`,`spherical`,`cylindrical`]),UN=[`map`,`roughnessMap`,`clearcoatRoughnessMap`,`normalMap`,`clearcoatNormalMap`],WN={roughnessMap:`roughness`,clearcoatRoughnessMap:`clearcoatRoughness`},GN=48,KN=e=>Math.min(360,Math.max(0,Gj(e,`phimax`,360)))*Math.PI/180,qN=64,JN=64,YN=(e,{su:t,sv:n,du:r,dv:i,uv:a})=>e.repeat.x===t&&e.repeat.y===n&&e.offset.x===r&&e.offset.y===i&&yM(e.userData.pbrtUV)===yM(a),XN=class{constructor(e={}){this.maxTriangles=e.maxTriangles??NN,this.maxPlacements=e.maxPlacements??PN,this.mergeShapesAbove=e.mergeShapesAbove??FN,this.curveSteps=e.curveSteps??zN,this.curveSides=e.curveSides??null,this.curveTolerance=e.curveTolerance??VN,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._usage=e.usage??null,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,this._mappings=new Map,this._oneUVSets=new WeakMap,this._uvWarnings=new Set}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._usage?.open(n.params,`Shape ${n.type}`,`alpha`);this._plyUsers=new Map,this._plyHeld=new Set;for(let t of e.shapes)if(t?.type===`plymesh`){let e=qj(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(qj(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&&!r.shared?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&&!r.shared&&i.getAttribute(`position`).count<=IN){this._mergeShape(r,i,o,t),e.shapes[n]=null;continue}r.type===`plymesh`&&this._plyHeld.add(qj(r.params,`filename`,null));let s=this._meshFromGeometry(r,this._mappedGeometry(i,o,r.ctm),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):[];for(let t of e.lights)this._usage?.open(t.params,`LightSource ${t.type}`);let 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:vN(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=new Map,s=(e,s,c,l,u,d,f)=>{let p=l?Array.prototype.join.call(l,`,`):``,m=o.get(e);m||o.set(e,m=new Map);let h=m.get(p),g=Math.max(0,this.maxPlacements-this.placementCount),_=h?h.count:Math.min(e.count,g);if(!h&&_<e.count&&(this.skippedForBudget+=e.count-_),_===0)return;let v=new r.InstancedMesh(s,c,_);if(v.name=`instance_${n++}`,v.frustumCulled=!1,h)v.instanceMatrix=h.attribute;else{for(let t=0;t<_;t++){if(l)mj(i,e.matrices,t*16,l);else for(let n=0;n<16;n++)i[n]=e.matrices[t*16+n];v.setMatrixAt(t,a.fromArray(this.convertHandedness?hj(AN,i):i))}v.instanceMatrix.needsUpdate=!0,m.set(p,{attribute:v.instanceMatrix,count:_}),this.placementCount+=_}t.add(v),this.reportedMeshes+=_,this.report.length<MN&&this.report.push({mesh:`${v.name} ×${_}`,shape:u,material:d,color:`#`+c.color.getHexString(),map:c.map?`yes`:`-`,uv:s.getAttribute(`uv`)?`yes`:`NO`,normals:s.getAttribute(`normal`)?`yes`:`NO`,emissive:c.emissiveIntensity>0?`#${c.emissive.getHexString()}×${c.emissiveIntensity}`:`-`,size:`instanced`,tris:f})},c=(e,t)=>{t&&t.triangles>0&&s(e,this._batchGeometry(t),t.material,null,`merged`,`-`,t.triangles)};for(let{name:n,list:r,template:i}of this._samePlacementGroups(e)){if(!i){this.droppedNoTemplate+=r.count,this.warn(`ObjectInstance "${n}" has no template — ${r.count.toLocaleString()} placement(s) dropped`);continue}let e=0;for(let t of i)t.type!==`plymesh`&&!t.shared&&e++;let a=e>=2?new Map:null;for(let e of i){if(this._overBudget()){this.skippedForBudget+=r.count;continue}let[i,o]=await Promise.all([this._buildGeometry(e),this._getMaterial(e)]);if(!i)continue;let l=i,u=e.relativeCTM||e.ctm;if(pN(o)){if(this._placeMapped(r,e,l,o,u,t,n))continue;l=this._mappedGeometry(l,o,mj(Array(16),r.matrices,0,u))}else if(a&&e.type!==`plymesh`&&!e.shared&&l.getAttribute(`position`).count<=IN){this._geometryCache.delete(e);let t=this._appendToBatch(a,e,l,o,u);this._releaseMerged(e,l),c(r,t);continue}let d=this._accountGeometry(l),f=this._materialForGeometry(e,l,o,`instances_${n}`);s(r,l,f,u,e.type,e.material?.type||`diffuse`,d)}if(a)for(let e of a.values())c(r,e[0]),c(r,e[1]);IA(r.matrices),IA(r.matricesEnd)}}_placeMapped(e,t,n,r,i,a,o){let s=(n.index?n.index.count:n.getAttribute(`position`).count)/3;if(e.count*s>RN)return this.warn(`ObjectInstance "${o}": its ${e.count.toLocaleString()} copies share the first one's uv from a position-mapped texture`),!1;let c=0;for(;c<e.count&&!this._overBudget();c++){let s=mj(Array(16),e.matrices,c*16,i);a.add(this._meshFromGeometry(t,this._mappedGeometry(n,r,s),r,s,`instances_${o}_${c}`))}return this.skippedForBudget+=e.count-c,!0}_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=>aN(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);IA(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?hj(AN,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=t.relativeCTM||t.ctm,a=this._mappedGeometry(n,r,hj(l,i)),o=this._meshFromGeometry(t,a,r,i,`${c.name}_${e}`,!0);o&&c.add(o)}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?hj(AN,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?hj(AN,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<MN&&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=TN(n),i.map=null,this._noUVMaterials.set(n,i)),i}_mergeShape(e,t,n,r){this.reportedMeshes++;let i=this.convertHandedness?hj(AN,e.ctm):e.ctm,a=this._appendToBatch(this._batches,e,this._mappedGeometry(t,n,e.ctm),n,i);this._releaseMerged(e,t),a&&this._flushBatch(a,r)}_releaseMerged(e,t){if(!this._keepShapes?.has(e)&&!(e.type===`plymesh`&&!this._lastPlyUse(qj(e.params,`filename`,null)))){for(let e in t.attributes)IA(t.attributes[e].array);IA(t.index?.array);for(let t in e.params)ArrayBuffer.isView(e.params[t]?.value)&&IA(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=Cj(m),g=p.vertexCount;p.positions=rN(p.positions,(g+u)*3),p.normals=rN(p.normals,(g+u)*3),c&&(p.uvs=rN(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=rN(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>=LN?(d[f]=null,p):null}_batchGeometry(e){let t=new r.BufferGeometry;return t.setAttribute(`position`,new r.BufferAttribute(LA(e.positions,e.vertexCount*3),3)),t.setAttribute(`normal`,new r.BufferAttribute(LA(e.normals,e.vertexCount*3),3)),e.uvs&&t.setAttribute(`uv`,new r.BufferAttribute(LA(e.uvs,e.vertexCount*2),2)),t.setIndex(new r.BufferAttribute(LA(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<MN&&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=e.geometryKey??e,n=this._geometryCache.get(t);return n||this._geometryCache.set(t,n=this._createGeometry(e)),n}async _createGeometry(e){let t=()=>this._shapeGeometry(e),n=await(this._usage?this._usage.translate(e.params,`Shape ${e.type}`,t,`alpha`):t());return n&&e.areaLight&&!Jj(e.areaLight.params,`twosided`,!1)?this._facingEmission(e,n):n}_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`curves`:return this._curves(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=Ej(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(iN(t),3));let i=Ej(e,`N`)?.value;i&&i.length===t.length&&(n.setAttribute(`normal`,new r.Float32BufferAttribute(iN(i),3)),n.userData.pbrtNormals=!0);let a=Ej(e,e.uv?`uv`:`st`)?.value;a&&a.length===t.length/3*2&&n.setAttribute(`uv`,new r.Float32BufferAttribute(iN(a),2));let o=Ej(e,`indices`)?.value;return o&&o.length&&n.setIndex(nN(o)),i||n.computeVertexNormals(),n}_curve(e){let t=Ej(e,`P`)?.value;if(!t||t.length<12)return this.warn(`curve needs at least 4 control points`),null;let n=Math.round(Gj(e,`degree`,3));if(n!==3)return this.warn(`curve degree ${n} not supported — only cubic`),null;let i=qj(e,`type`,`flat`),a=Gj(e,`width`,1),o=qM({P:t,basis:qj(e,`basis`,`bezier`),width0:Gj(e,`width0`,a),width1:Gj(e,`width1`,a),N:Ej(e,`N`)?.value||null,steps:this.curveSteps,sides:this.curveSides??BN[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.BufferAttribute(o.positions,3)),s.setIndex(new r.BufferAttribute(o.indices,1)),s.computeVertexNormals(),zn(s,`normal`),s}_curves(e){let t=ZM({P:Ej(e,`P`).value,counts:Ej(e,`counts`).value,widths:Ej(e,`widths`)?.value??null,widthMode:qj(e,`widthMode`,`constant`),N:Ej(e,`N`)?.value??null,normalMode:qj(e,`normalMode`,`vertex`),type:qj(e,`type`,`cubic`),basis:qj(e,`basis`,`bspline`),wrap:qj(e,`wrap`,`nonperiodic`),steps:this.curveSteps,sides:this.curveSides??1,tolerance:this.curveTolerance});if(!t)return this.warn(`curves could not be tessellated`),null;t.skipped>0&&this.warn(`${t.skipped} curve(s) of an unsupported basis or too few points skipped`);let n=new r.BufferGeometry;return n.setAttribute(`position`,new r.BufferAttribute(t.positions,3)),n.setIndex(new r.BufferAttribute(t.indices,1)),n.computeVertexNormals(),zn(n,`normal`),n}_loopSubdiv(e){let t=Ej(e,`P`)?.value,n=Ej(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(Gj(e,`levels`,3)))),{positions:a,indices:o,levels:s}=AM(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=Ej(e,`P`)?.value,n=Ej(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=Ej(e,`uv`)?.value?.length===i*2?e.uv.value:null,o=Ej(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=qj(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}=yN(e),a=Math.acos(n/t),o=Math.acos(r/t);return SN(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}=bN(e);return SN(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}=xN(e);return SN(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&&(t=await this._withAlpha(t,e.params.alpha)),this._oneUVSet(t)}_oneUVSet(e){let t=this._oneUVSets.get(e);if(t)return t;t=e;let n=pN(e),r=e=>e?`a "${e.type}" mapping`:`the mesh's uv`;for(let i of UN){let a=e[i];if(!a||yM(a.userData.pbrtUV)===yM(n))continue;t===e&&(t=TN(e)),t[i]=null;let o=WN[i],s=o&&this._textureLayer(a,1);s&&(t[o]*=fM(s));let c=`a ${i} in ${r(a.userData.pbrtUV)} on a surface textured in ${r(n)}: one uv set a surface — ${s?`its mean used`:`dropped`}`;this._uvWarnings.has(c)||(this._uvWarnings.add(c),this.warn(c))}return this._oneUVSets.set(e,t),t}_mappedGeometry(e,t,n){let i=pN(t);if(!i)return e;let{uv:a,index:o,extra:s}=_M(e.getAttribute(`position`).array,e.index?.array??null,hj(i.textureFromWorld,n),i),c=new r.BufferGeometry;c.name=e.name,Object.assign(c.userData,e.userData);for(let t in e.attributes)t!==`uv`&&c.setAttribute(t,s.length?mN(e.getAttribute(t),s):e.getAttribute(t));return c.setAttribute(`uv`,new r.BufferAttribute(a,2)),o?c.setIndex(new r.Uint32BufferAttribute(o,1)):e.index&&c.setIndex(e.index),c}_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?EN(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?EN(e,r.constant):e;let i=TN(e);return i.map=r,i.transparent=!0,i}async _alphaMap(e,t){let n=this._textureDef(t),r=n?.class===`imagemap`?qj(n.params,`filename`,null):null,i=r&&this._textureMapping(t,n);if(r&&e?.userData.pbrtImage===r&&Gj(n.params,`scale`,1)===1&&!Jj(n.params,`invert`,!1)&&YN(e,i)){let t=sN(e),r=t&&DN(t,cN(n.params));if(r)return fN(r,i),r}let a=await this._bakeTerm(t,1);if(!a)return null;if(!a.layer)return{constant:a.rgb[0]};let o=e?this._textureLayer(e,3):null;if(e&&!o)return null;let s=this._bake(`alpha "${t}"`,[o?{layer:o}:{rgb:[1,1,1]},a],([e])=>e,{alphaOf:([,e])=>e[0]});return s&&gN(s)}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 rM(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,trackParams:(e,t,n)=>this._usage?.open(e,t,n),warn:e=>this.warn(e),floatTextureMean:async e=>{let t=await this._bakeTerm(e,1);return t?t.layer?fM(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=hN(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&&qj(n,`type`,``);if(this._usage?.open(n,`MakeNamedMedium ${r}`,`type`),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 "${qj(n,`preset`,``)}" is not supported — using sigma_a / sigma_s`),Dj(n,`preset`));let i=this._materialContext(),a=(await Yj(n,`sigma_a`,i,[1,1,1])).rgb,o=(await Yj(n,`sigma_s`,i,[1,1,1])).rgb,s=Gj(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=TN(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}|${e.diffuseRoughness??0}`;return this._materialBySignature.get(r)||(this._materialBySignature.set(r,e),e)}_poweredMaterial(e,t,n){let r=Gj(e.areaLight.params,`power`,-1);if(!(r>0))return n;let i=CN(e,t)*(Jj(e.areaLight.params,`twosided`,!1)?2:1);if(!(i>0))return n;let a=TN(n);return a.emissiveIntensity=n.emissiveIntensity*r/(Math.PI*i),a}async _applyAreaLight(e,t,n){this._usage?.open(t.params,`AreaLightSource ${t.type}`);let i=await tN(t.params,`L`,n),a=Gj(t.params,`scale`,1);e.emissive.setRGB(i[0],i[1],i[2]),e.emissiveIntensity=a,e.side=Jj(t.params,`twosided`,!1)?r.DoubleSide:r.FrontSide}_textureDef(e){let t=this.ir.namedTextures.get(e);return t&&this._usage?.open(t.params,`Texture ${t.class}`),t}async _resolveNamedTexture(e){if(this._textureCache.has(e))return this._textureCache.get(e);let t=this._textureDef(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=Ej(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=Ej(n,e);return i?.type===`texture`?(Dj(n,e),await r.textureMeanRGB(i.value[0])??t):(await Yj(n,e,r,t)).rgb??t},{su:a,sv:o,du:s,dv:c,uv:l}=this._textureMapping(e,t);if(t.class===`checkerboard`){if(Gj(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])]),u=2*qN;return{texture:gN({data:wN(u,u,(e,n)=>(Math.floor(2*e)+Math.floor(2*n))%2?r:t),width:u,height:u,mapping:{su:a/2,sv:o/2,du:s/2,dv:c/2,uv:l}})}}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:gN({data:wN(JN,JN,(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:JN,height:JN,mapping:{su:a,sv:o,du:s,dv:c,uv:l}})}}_textureMapping(e,t){let n=this._mappings.get(e);if(!n){let r=qj(t.params,`mapping`,`uv`);r!==`uv`&&!HN.has(r)&&this.warn(`texture "${e}": unknown mapping "${r}" — using the mesh's uv`),this._mappings.set(e,n=dN(t.params,t.ctm))}return n}_bake(e,t,n,r){let i=hM(t,n,r);return i?.averaged&&this.warn(`${e}: ${i.averaged} input(s) in another uv set than the first image — read as their mean`),i}_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=qj(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=this._textureMapping(e,t),a=Gj(t.params,`scale`,1);if(a>1||Jj(t.params,`invert`,!1)){let t=await this._bakeTerm(e,3),n=t?.layer&&this._bake(`texture "${e}"`,[{...t,clamp:!0}],([e])=>e);if(n)return{texture:gN(n)};this.warn(`texture "${e}": its scale or invert could not be baked here — ignored`)}let o=hN(r,{srgb:!0}),s=o===r?r.clone():o;return s.userData.pbrtImage=n,fN(s,i),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=this._bake(`"${t.join(`", "`)}"`,r,e=>{let t=n(e.map(e=>e[0]));return[t,t,t]},{linear:!0});return i&&gN(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=this._bake(`texture "${e}"`,[{...n,clamp:!0},{...r,clamp:!0},i],SM);return o?{texture:gN(o)}:{constant:SM([a(n.rgb),a(r.rgb),i.rgb])}}async _paramTerm(e,t,n,r){let i=Ej(e,t);if(!i)return{rgb:r};if(i.type===`texture`)return this._bakeTerm(i.value[0],n);let a=(await Yj(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._textureDef(e);if(n?.class===`imagemap`){let r=qj(n.params,`filename`,null),i=sN(r&&await this._image(r));return i?{layer:uM(i,{channels:t,decode:i.float?null:cN(n.params),scale:Gj(n.params,`scale`,1),invert:Jj(n.params,`invert`,!1),mapping:this._textureMapping(e,n)})}: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=sN(e);if(!n)return null;let i=!n.float&&e.colorSpace===r.SRGBColorSpace;return uM(n,{channels:t,decode:n.float?null:i?bM:e=>e,mapping:{su:e.repeat.x,sv:e.repeat.y,du:e.offset.x,dv:e.offset.y,uv:e.userData.pbrtUV??null}})}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=fM(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=this._bake(`mix amount "${n}"`,[o,s,r],SM);return{mean:i,texture:c?gN(c):null}}_colorFromLikeNamedMaterial(e){for(let t of ON(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 t=this._bake(`texture "${e}"`,[{...n,clamp:!0},r],i);return t?{texture:gN(t)}:{constant:i([n.rgb,r.rgb])}}this.warn(`texture "${e}": its "scale" texture could not be read here — ignored`)}let n=Ej(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=Ej(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;this._usage?.open(e.params,`Camera ${e.type}`);let i;if(e.type===`orthographic`){let t=Ej(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=Gj(e.params,`lensradius`,0);return a>0&&(i.userData.__rayzeeEffects=_N(i,a,Gj(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)),pj(t)>0!==this.convertHandedness&&(e.scale.x=-1)}_verticalFov(e,t){let n=Gj(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=oN(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}=PM(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=Gj(t.params,`scale`,1),i=qj(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 tN(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(!kN.has(i.type))continue;let e=new r.Matrix4().fromArray(this.convertHandedness?hj(AN,i.ctm):i.ctm),a=(t,n)=>{let a=Ej(i.params,t)?.value;return new r.Vector3().fromArray(a?.length>=3?a:n).applyMatrix4(e)},o=await tN(i.params,i.type===`distant`?`L`:`I`,n),s=Gj(i.params,`scale`,1),c=a(`from`,[0,0,0]),l=a(`to`,[0,0,1]),u;if(i.type===`distant`){let e=Gj(i.params,`illuminance`,-1);e>0&&(s*=e),u=new r.DirectionalLight,u.userData.__luxConverted=!0}else if(i.type===`point`){let e=Gj(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(Gj(i.params,`coneangle`,30),0),90)*Math.PI/180,t=Math.min(Math.max(Gj(i.params,`conedeltaangle`,5)*Math.PI/180,0),e),n=Math.cos(e),a=Math.cos(e-t),o=Gj(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`&&!kN.has(t.type)&&this.warn(`light "${t.type}" not supported (only infinite, distant, point and spot lights and emissive area lights are mapped)`)}}}));function QN(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,lP).map(([e,t])=>({path:t,number:e}))}function $N(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 eP(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?`#`+$N(i):i.join(`,`)};`}return t}function tP(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&&!nP(e,r,i,t,r,a,n)&&iP(e,r,i,t,r,a,n),n}function nP(e,t,n,r,i,a,o){let s=n-t,c=a-i,l=Math.min(s+c,uP),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)),rP(f,s,c,t,i,o),!0}f.push(d.slice(u-n,u+n+1))}return!1}function rP(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 iP(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 aP(e,t,n,r){for(let i=0;i<16;i++)if(e[t+i]!==n[r+i])return!1;return!0}function oP(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 sP(e){if(e.visible)return!1;let t=e.matrices;for(let e=16;e<t.length;e+=16)if(!aP(t,0,t,e))return!1;return!0}function cP(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;aP(t.matrices,i,t.matricesEnd,i)||e.animatedInstances.length>=dP?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 lP,uP,dP,fP,pP,mP=g((()=>{lP=1e3,uP=2048,dP=1e5,fP=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}|${eP(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+`:`+eP(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+`:`+eP(e.params)),t}},pP=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 fP(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?tP(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&&!aP(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&&aP(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=oP(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=oP(t,()=>!0,e=>r[e].cameraToWorld),i=r.map(e=>e.fov??r[0].fov),a=i.some(e=>e!==i[0]);(!sP(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<dP){let n=oP(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 ${dP.toLocaleString()} left static`),r}}}));function hP(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 gP(e,t){return!e||t.startsWith(`/`)?hP(t):hP(`${e}/${t}`)}function _P(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 vP(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 yP(e){for(let t=_P(e,MP);t>=0;t=_P(e,MP,t+1))if(vP(e,t))return!0;return!1}function bP(e,t){for(let n of NP)for(let r=_P(e,n);r>=0;r=_P(e,n,r+1)){if(!vP(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=OP.decode(e.subarray(a,i));t.add(hP(o).toLowerCase().split(`/`).pop())}}function xP(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,yP(t)),bP(t,n)}return SP(t,r,n)}function SP(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 CP(e){return xP(e)[0]||null}async function wP(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,yP(t)),bP(t,r),t.length>=jP&&(a=!0),o.lazy&&(e.release(o),IA(t)))}return{included:r,worlds:i,cut:a}},r=await n(t=>e.readHead(t,jP)),{included:i,worlds:a}=[...r.worlds.values()].filter(Boolean).length===1||!r.cut?r:await n(t=>e.read(t));return SP(t.map(e=>e.key),a,i)}async function TP(e){let{vfs:t,source:n,plyParser:r,imageFromBytes:i,envFromBytes:a,convertHandedness:o}=e,s=new kP(t,n),c=[],l=await wP(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=new Ij,p=async t=>{let n=await s.readPath(t);if(!n)throw Error(`PBRT loader: entry "${t}" not readable`);let r=await new Lj({resolveInclude:(e,t)=>s.readPath(e,t),releaseInclude:(e,t,n)=>s.releasePath(e,t,n),maxPlacements:e.maxPlacements,instanceIncludes:e.instanceIncludes,usage:f}).parse(n,t.includes(`/`)?t.slice(0,t.lastIndexOf(`/`)):``);return s.releasePath(t,null,n),r},m=performance.now(),h=!u&&e.animation!==!1?QN(l):null,g;if(h){let e=await p(h[0].path);if(e.shapes.length+e.instanceCount>DP)c.push(`${h.length} animation frames found, but the scene is too large to parse once per frame — loaded "${h[0].path}" only`),h=null,g=cP(e);else{let t=new pP(h.map(e=>(e.number-h[0].number)/30),EP(h));t.addFrame(e);for(let e=1;e<h.length;e++)t.addFrame(await p(h[e].path));g=t.finish()}}else g=cP(await p(d));let _=performance.now()-m;s.releaseScenes();let v=e=>e.byteOffset===0&&e.byteLength===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength),y=new Map,b=async e=>{let t=await s.read(e);return t?(s.release(e),r(v(t))):null},x=new XN({convertHandedness:o,maxTriangles:e.maxTriangles,maxPlacements:e.maxPlacements,mergeShapesAbove:e.mergeShapesAbove,curveSteps:e.curveSteps,curveSides:e.curveSides,curveTolerance:e.curveTolerance,usage:f,resolvePLY:async e=>{let t=s.findRecord(e);return t?(y.has(t.norm)||y.set(t.norm,await b(t)),y.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}}),S=performance.now(),C,w;try{C=await x.build(g)}finally{w=f.finish()}return{...C,parameters:w,entryPath:h?h[0].path:d,frames:h?h.map(e=>e.path):null,candidates:l,warnings:[...c,...C.warnings??[]],parseMs:_,buildMs:performance.now()-S}}function EP(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 DP,OP,kP,AP,jP,MP,NP,PP=g((()=>{zA(),Rj(),ZN(),mP(),dj(),DP=2e6,OP=new TextDecoder,kP=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=hP(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(gP(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(gP(t,e))||this.findRecord(e);r?.lazy&&(this.release(r),IA(n))}releaseScenes(){for(let e of this.records)e.norm.endsWith(`.pbrt`)&&this.release(e)}findRecord(e){let t=hP(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}},AP=e=>Uint8Array.from(e,e=>e.charCodeAt(0)),jP=4*1024*1024,MP=AP(`WorldBegin`),NP=[AP(`Include`),AP(`Import`)]}));function FP(e,t=null){let n=[];for(let r=e.length-1;r>=0;r--){let i=e[r];if(!i)continue;let a=e=>e.map(e=>({value:e,source:t?t[r]:null}));if(i.explicit){n=a(i.explicit);continue}let o=e=>{let t=new Set(e.map(GP));t.size&&(n=n.filter(e=>!t.has(GP(e.value))))};o(i.delete);let s=new Set(n.map(e=>GP(e.value)));for(let e of a(i.add))s.has(GP(e.value))||n.push(e);o(i.prepend),n=[...a(i.prepend),...n],o(i.append),n=[...n,...a(i.append)]}return n}function IP(e,t,n){t===`explicit`?e.explicit=n:t!==`reorder`&&e[t].push(...n)}function LP(){if(QP)return QP;QP=new Float32Array(65536);for(let e=0;e<65536;e++){let t=e&32768?-1:1,n=e>>10&31,r=e&1023;QP[e]=n===0?t*2**-14*(r/1024):n===31?r?NaN:t*(1/0):t*2**(n-15)*(1+r/1024)}return QP}function RP(e,t,n,r,i){let a=t;for(;a<n;){let t=e[a++],o=t>>4;if(o===15){let t;do t=e[a++],o+=t;while(t===255)}if(r.set(e.subarray(a,a+o),i),a+=o,i+=o,a>=n)break;let s=e[a]|e[a+1]<<8;a+=2;let c=(t&15)+4;if(c===19){let t;do t=e[a++],c+=t;while(t===255)}let l=i-s;if(s>=c)r.copyWithin(i,l,l+c),i+=c;else for(let e=0;e<c;e++)r[i++]=r[l++]}return i}function zP(e,t){let n=new Uint8Array(t),r=e[0];if(r===0)return n.subarray(0,RP(e,1,e.length,n,0));let i=new DataView(e.buffer,e.byteOffset,e.byteLength),a=1,o=0;for(let t=0;t<r;t++){let t=i.getInt32(a,!0);a+=4,o=RP(e,a,a+t,n,o),a+=t}return n.subarray(0,o)}function BP(e,t,n){let r=new DataView(e.buffer,e.byteOffset,e.byteLength),i=n?Number(r.getBigInt64(0,!0)):r.getInt32(0,!0),a=n?8:4,o=a+(t*2+7>>3),s=n?new Float64Array(t):new Int32Array(t),c=0;for(let l=0;l<t;){let u=e[a++];for(let e=0;e<4&&l<t;e++,l++){let t=u>>e*2&3,a;t===0?a=i:n?t===1?(a=r.getInt16(o,!0),o+=2):t===2?(a=r.getInt32(o,!0),o+=4):(a=Number(r.getBigInt64(o,!0)),o+=8):t===1?(a=r.getInt8(o),o+=1):t===2?(a=r.getInt16(o,!0),o+=2):(a=r.getInt32(o,!0),o+=4),c=n?c+a:c+a|0,s[l]=c}}return s}function VP(e,t,n){switch(t){case`specifier`:e.specifier=oF[n]??`over`;break;case`typeName`:e.typeName=n||``;break;case`primChildren`:case`properties`:case`variantChildren`:case`variantSetChildren`:break;case`references`:case`specializes`:case`apiSchemas`:case`variantSetNames`:n&&((e.arcs??={})[t]=n);break;case`inheritPaths`:n&&((e.arcs??={}).inherits=n);break;case`payload`:n instanceof UP?(e.arcs??={}).payload={...WP(),explicit:[n]}:n&&((e.arcs??={}).payload=n);break;case`variantSelection`:n&&(e.variantSelection=n);break;default:e.meta[t]=n}}function HP(e,t=``){let n=new eF(e),r=new JP(t),i=new Map,a=e=>{let t=i.get(e);if(t)return t;let o=n.pathParent[e];if(o<0)t=r.root;else{let r=a(o),i=n.pathElement[e];if(i.startsWith(`{`)){let[e,n]=i.slice(1,-1).split(`=`);t=r.variant(e,n,!0)??r}else t=r.child(i,!0)}return i.set(e,t),t},o=[];for(let e=0;e<n.specTypes.length;e++){let t=n.specTypes[e],i=n.specPaths[e],s=n.fieldsOf(n.specFieldSets[e]);if(t===nF){for(let[e,t,i]of s)e!==`primChildren`&&(r.meta[e]=n.value(t,i));continue}if(t===tF||t===rF){let e=a(i);for(let[t,r,i]of s){let a=n.value(r,i);t===`primChildren`&&a?.length&&o.push([e,a]),VP(e,t,a)}continue}if(t!==iF&&t!==aF||!n.pathIsProperty[i])continue;let c=a(n.pathParent[i]).property(n.pathElement[i],!0);c.rel=t===aF;for(let[e,t,r]of s)if(e===`default`)c.hasValue=!0,c._lazyValue=()=>n.value(t,r);else if(e===`timeSamples`)c._lazySamples=()=>n.value(t,r);else{let i=n.value(t,r);e===`typeName`?c.type=i:e===`targetPaths`?c.targets=i:e===`connectionPaths`?c.connections=i:e===`variability`?c.uniform=i===1:e===`custom`?c.custom=i===!0:c.meta[e]=i}}for(let[e,t]of o){if(!e.children)continue;let n=new Map;for(let r of t)e.children.has(r)&&n.set(r,e.children.get(r));for(let[t,r]of e.children)n.has(t)||n.set(t,r);e.children=n}return r}var UP,WP,GP,KP,qP,JP,$,YP,XP,ZP,QP,$P,eF,tF,nF,rF,iF,aF,oF,sF=g((()=>{UP=class{constructor(e,t){this.asset=e,this.path=t}},WP=()=>({explicit:null,prepend:[],append:[],add:[],delete:[]}),GP=e=>e instanceof UP?`${e.asset}\u0000${e.path}`:String(e),KP=class{constructor(e){this.name=e,this.rel=!1,this.type=``,this._value=void 0,this._lazyValue=null,this.hasValue=!1,this._timeSamples=null,this._lazySamples=null,this.targets=null,this.connections=null,this.meta={},this.uniform=!1,this.custom=!1}get value(){return this._lazyValue&&=(this._value=this._lazyValue(),null),this._value}set value(e){this._value=e,this._lazyValue=null}get timeSamples(){return this._lazySamples&&=(this._timeSamples=this._lazySamples(),null),this._timeSamples}set timeSamples(e){this._timeSamples=e,this._lazySamples=null}setTargets(e,t){IP(this.targets??=WP(),e,t)}setConnections(e,t){IP(this.connections??=WP(),e,t)}},qP=class e{constructor(e){this.name=e,this.specifier=`over`,this.typeName=``,this.meta={},this.arcs=null,this.variantSelection=null,this.variantSets=null,this.children=null,this.props=null,this.reorder=null}child(t,n=!1){let r=this.children?.get(t)??null;return!r&&n&&(this.children??=new Map,this.children.set(t,r=new e(t))),r}variant(t,n,r=!1){let i=this.variantSets?.get(t)??null;if(!i){if(!r)return null;this.variantSets??=new Map,this.variantSets.set(t,i=new Map)}let a=i.get(n)??null;return!a&&r&&n&&i.set(n,a=new e(n)),a}property(e,t=!1){let n=this.props?.get(e)??null;return!n&&t&&(this.props??=new Map,this.props.set(e,n=new KP(e))),n}setArc(e,t,n){this.arcs??={},IP(this.arcs[e]??=WP(),t,n)}},JP=class{constructor(e){this.path=e,this.meta={},this.root=new qP(``),this.root.specifier=`def`}},$={Bool:1,UChar:2,Int:3,UInt:4,Int64:5,UInt64:6,Half:7,Float:8,Double:9,String:10,Token:11,AssetPath:12,Matrix2d:13,Matrix3d:14,Matrix4d:15,Quatd:16,Quatf:17,Quath:18,Vec2d:19,Vec2f:20,Vec2h:21,Vec2i:22,Vec3d:23,Vec3f:24,Vec3h:25,Vec3i:26,Vec4d:27,Vec4f:28,Vec4h:29,Vec4i:30,Dictionary:31,TokenListOp:32,StringListOp:33,PathListOp:34,ReferenceListOp:35,IntListOp:36,Int64ListOp:37,UIntListOp:38,UInt64ListOp:39,PathVector:40,TokenVector:41,Specifier:42,Permission:43,Variability:44,VariantSelectionMap:45,TimeSamples:46,Payload:47,DoubleVector:48,LayerOffsetVector:49,StringVector:50,ValueBlock:51,Value:52,PayloadListOp:55,TimeCode:56},YP={[$.Bool]:[1,`bool`],[$.UChar]:[1,`u8`],[$.Int]:[1,`i32`],[$.UInt]:[1,`u32`],[$.Int64]:[1,`i64`],[$.UInt64]:[1,`u64`],[$.Half]:[1,`f16`],[$.Float]:[1,`f32`],[$.Double]:[1,`f64`],[$.TimeCode]:[1,`f64`],[$.Matrix2d]:[4,`f64`],[$.Matrix3d]:[9,`f64`],[$.Matrix4d]:[16,`f64`],[$.Quatd]:[4,`f64`],[$.Quatf]:[4,`f32`],[$.Quath]:[4,`f16`],[$.Vec2d]:[2,`f64`],[$.Vec2f]:[2,`f32`],[$.Vec2h]:[2,`f16`],[$.Vec2i]:[2,`i32`],[$.Vec3d]:[3,`f64`],[$.Vec3f]:[3,`f32`],[$.Vec3h]:[3,`f16`],[$.Vec3i]:[3,`i32`],[$.Vec4d]:[4,`f64`],[$.Vec4f]:[4,`f32`],[$.Vec4h]:[4,`f16`],[$.Vec4i]:[4,`i32`]},XP=new Set([$.Vec2d,$.Vec2f,$.Vec2i,$.Vec3d,$.Vec3f,$.Vec3h,$.Vec3i,$.Vec4d,$.Vec4f,$.Vec4h,$.Vec4i]),ZP={[$.Matrix2d]:2,[$.Matrix3d]:3,[$.Matrix4d]:4},QP=null,$P=new DataView(new ArrayBuffer(4)),eF=class{constructor(e){if(this.buffer=e,this.bytes=new Uint8Array(e),this.view=new DataView(e),this.pos=0,String.fromCharCode(...this.bytes.subarray(0,8))!==`PXR-USDC`)throw Error(`not a usdc layer`);if(this.major=this.bytes[8],this.minor=this.bytes[9],this.patch=this.bytes[10],this.older(0,4))throw Error(`usdc ${this.major}.${this.minor}.${this.patch} predates 0.4.0 and is not read`);this.pos=16,this.pos=this.u64(),this.sections={};for(let e=this.u64();e>0;e--){let e=``;for(let t=0;t<16;t++){let n=this.bytes[this.pos+t];if(n===0)break;e+=String.fromCharCode(n)}this.pos+=16,this.sections[e]={start:this.u64(),size:this.u64()}}this.readTokens(),this.readStrings(),this.readFields(),this.readFieldSets(),this.readPaths(),this.readSpecs()}older(e,t){return this.major<e||this.major===e&&this.minor<t}seek(e){let t=this.sections[e];return t?(this.pos=t.start,!0):!1}u8(){return this.bytes[this.pos++]}i8(){let e=this.view.getInt8(this.pos);return this.pos+=1,e}u32(){let e=this.view.getUint32(this.pos,!0);return this.pos+=4,e}i32(){let e=this.view.getInt32(this.pos,!0);return this.pos+=4,e}u64(){let e=this.view.getUint32(this.pos,!0),t=this.view.getUint32(this.pos+4,!0);return this.pos+=8,t*4294967296+e}i64(){let e=this.view.getUint32(this.pos,!0),t=this.view.getInt32(this.pos+4,!0);return this.pos+=8,t*4294967296+e}f64(){let e=this.view.getFloat64(this.pos,!0);return this.pos+=8,e}ints(e,t=!1){let n=this.u64(),r=this.bytes.subarray(this.pos,this.pos+n);return this.pos+=n,BP(zP(r,(t?8:4)+(e*2+7>>3)+e*(t?8:4)),e,t)}readTokens(){if(this.tokens=[],!this.seek(`TOKENS`))return;let e=this.u64(),t=this.u64(),n=this.u64(),r=zP(this.bytes.subarray(this.pos,this.pos+n),t),i=new TextDecoder,a=0;for(let t=0;t<e;t++){let e=a;for(;e<r.length&&r[e]!==0;)e++;this.tokens.push(i.decode(r.subarray(a,e))),a=e+1}}readStrings(){if(this.strings=[],this.seek(`STRINGS`))for(let e=this.u64();e>0;e--)this.strings.push(this.u32())}readFields(){if(!this.seek(`FIELDS`))return;let e=this.u64();this.fieldTokens=this.ints(e);let t=this.u64(),n=zP(this.bytes.subarray(this.pos,this.pos+t),e*8);this.fieldReps=new Uint32Array(n.slice().buffer)}readFieldSets(){this.fieldSets=new Int32Array,this.seek(`FIELDSETS`)&&(this.fieldSets=this.ints(this.u64()))}readPaths(){if(!this.seek(`PATHS`))return;let e=this.u64(),t=this.u64(),n=this.ints(t),r=this.ints(t),i=this.ints(t);this.pathParent=new Int32Array(e).fill(-1),this.pathElement=Array(e).fill(``),this.pathIsProperty=new Uint8Array(e);let a=[[0,-1]];for(;a.length;){let[e,t]=a.pop();for(;;){let o=n[e];if(t>=0){let n=r[e];this.pathParent[o]=t,this.pathElement[o]=this.tokens[Math.abs(n)]??``,this.pathIsProperty[o]=+(n<0)}let s=i[e],c=s>0||s===-1,l=s>=0;if(c&&l&&a.push([e+s,t]),c)t=o;else if(!l)break;e++}}this.pathStrings=Array(e)}readSpecs(){if(this.specPaths=this.specFieldSets=this.specTypes=new Int32Array,!this.seek(`SPECS`))return;let e=this.u64();this.specPaths=this.ints(e),this.specFieldSets=this.ints(e),this.specTypes=this.ints(e)}path(e){let t=this.pathStrings[e];if(t!==void 0)return t;let n=this.pathParent[e],r=this.pathElement[e];if(n<0)t=`/`;else{let i=this.path(n);t=this.pathIsProperty[e]?`${i}.${r}`:r.startsWith(`{`)?i+r:i===`/`?`/${r}`:`${i}/${r}`}return this.pathStrings[e]=t,t}fieldsOf(e){let t=[];for(let n=e;n<this.fieldSets.length;n++){let e=this.fieldSets[n];if(e<0)break;t.push([this.tokens[this.fieldTokens[e]],this.fieldReps[e*2],this.fieldReps[e*2+1]])}return t}value(e,t){let n=t>>>16&255,r=e+(t&65535)*4294967296;if(n===$.TimeSamples)return this.timeSamples(r);if(t&1073741824)return this.inlined(n,e);let i=(t&2147483648)!=0;if(i&&r===0)return[];let a=this.pos;this.pos=r;let o=i?this.array(n,(t&536870912)!=0):this.scalar(n);return this.pos=a,o}inlined(e,t){switch(e){case $.Bool:return t!==0;case $.Int:return t|0;case $.Float:case $.Double:case $.TimeCode:return $P.setUint32(0,t,!0),$P.getFloat32(0,!0);case $.Half:return LP()[t&65535];case $.Token:case $.AssetPath:return this.tokens[t]??``;case $.String:return this.tokens[this.strings[t]]??``;case $.Vec2h:return[LP()[t&65535],LP()[t>>>16]];case $.ValueBlock:return null;case $.Dictionary:return{}}let n=e=>t>>>e*8<<24>>24;if(XP.has(e))return Array.from({length:YP[e][0]},(e,t)=>n(t));let r=ZP[e];if(r){let e=Array(r*r).fill(0);for(let t=0;t<r;t++)e[t*r+t]=n(t);return e}return t}element(e){switch(e){case`bool`:return this.u8()!==0;case`u8`:return this.u8();case`i32`:return this.i32();case`u32`:return this.u32();case`i64`:return this.i64();case`u64`:return this.u64();case`f16`:{let e=LP()[this.view.getUint16(this.pos,!0)];return this.pos+=2,e}case`f32`:{let e=this.view.getFloat32(this.pos,!0);return this.pos+=4,e}default:return this.f64()}}listOp(e){let t=this.u8(),n=WP(),r=()=>{let t=[];for(let n=this.u64();n>0;n--)t.push(e());return t};return t&1&&(n.explicit=[]),t&2&&(n.explicit=r()),t&4&&(n.add=r()),t&32&&(n.prepend=r()),t&64&&(n.append=r()),t&8&&(n.delete=r()),t&16&&r(),n}string(){return this.tokens[this.strings[this.u32()]]??``}reference(){let e=this.string(),t=this.path(this.u32());return this.f64(),this.f64(),this.dictionary(),new UP(e,t===`/`?``:t)}payload(){let e=this.string(),t=this.path(this.u32());return this.older(0,8)||(this.f64(),this.f64()),new UP(e,t===`/`?``:t)}recursive(){return this.pos+=this.i64(),this.value(this.u32(),this.u32())}dictionary(){let e={};for(let t=this.u64();t>0;t--){let t=this.string();e[t]=this.recursive()}return e}scalar(e){let t=YP[e];if(t)return t[0]===1?this.element(t[1]):Array.from({length:t[0]},()=>this.element(t[1]));switch(e){case $.String:return this.string();case $.Token:case $.AssetPath:return this.tokens[this.u32()]??``;case $.Specifier:case $.Permission:case $.Variability:return this.u32();case $.Dictionary:return this.dictionary();case $.TokenListOp:return this.listOp(()=>this.tokens[this.u32()]??``);case $.StringListOp:return this.listOp(()=>this.string());case $.PathListOp:return this.listOp(()=>this.path(this.u32()));case $.ReferenceListOp:return this.listOp(()=>this.reference());case $.PayloadListOp:return this.listOp(()=>this.payload());case $.IntListOp:return this.listOp(()=>this.i32());case $.UIntListOp:return this.listOp(()=>this.u32());case $.Int64ListOp:return this.listOp(()=>this.i64());case $.UInt64ListOp:return this.listOp(()=>this.u64());case $.Payload:return this.payload();case $.PathVector:return Array.from({length:this.u64()},()=>this.path(this.u32()));case $.TokenVector:return Array.from({length:this.u64()},()=>this.tokens[this.u32()]??``);case $.StringVector:return Array.from({length:this.u64()},()=>this.string());case $.DoubleVector:return Float64Array.from({length:this.u64()},()=>this.f64());case $.LayerOffsetVector:return Array.from({length:this.u64()},()=>[this.f64(),this.f64()]);case $.VariantSelectionMap:{let e={};for(let t=this.u64();t>0;t--){let t=this.string();e[t]=this.string()}return e}case $.Value:return this.recursive();default:return null}}typed(e,t){let n=t*e.BYTES_PER_ELEMENT,r=new e(this.buffer.slice(this.pos,this.pos+n));return this.pos+=n,r}array(e,t){this.older(0,5)&&this.u32();let n=this.older(0,7)?this.u32():this.u64();if(t)return this.compressedArray(e,n);let r=YP[e];if(r){let[e,t]=r,i=n*e;switch(t){case`f32`:return this.typed(Float32Array,i);case`f64`:return this.typed(Float64Array,i);case`i32`:return this.typed(Int32Array,i);case`u32`:return this.typed(Uint32Array,i);case`u8`:return this.typed(Uint8Array,i);case`f16`:{let e=this.typed(Uint16Array,i),t=LP(),n=new Float32Array(i);for(let r=0;r<i;r++)n[r]=t[e[r]];return n}default:return Array.from({length:i},()=>this.element(t))}}switch(e){case $.String:return Array.from({length:n},()=>this.string());case $.Token:case $.AssetPath:return Array.from({length:n},()=>this.tokens[this.u32()]??``);default:return null}}compressedArray(e,t){switch(e){case $.Int:return this.ints(t);case $.UInt:return new Uint32Array(this.ints(t).buffer);case $.Int64:case $.UInt64:return this.ints(t,!0);case $.Half:case $.Float:case $.Double:{let n=e===$.Double?Float64Array:Float32Array,r=this.i8();if(r===105)return n.from(this.ints(t));if(r!==116)throw Error(`usdc: unknown float array coding ${r}`);let i=Array.from({length:this.u32()},()=>this.element(e===$.Half?`f16`:e===$.Float?`f32`:`f64`)),a=this.ints(t),o=new n(t);for(let e=0;e<t;e++)o[e]=i[a[e]];return o}default:throw Error(`usdc: compressed array of type ${e} is not read`)}}timeSamples(e){let t=this.pos;this.pos=e,this.pos=e+this.i64();let n=[this.u32(),this.u32()];this.pos+=this.i64();let r=[];for(let e=this.u64();e>0;e--)r.push([this.u32(),this.u32()]);this.pos=t;let i=r.map(([e,t])=>this.value(e,t));return new Map(Array.from(this.value(...n)??[],(e,t)=>[e,i[t]]))}},tF=6,nF=7,rF=10,iF=1,aF=8,oF=[`def`,`over`,`class`]}));function cF(e){if(e===null)return[];let t=Array.isArray(e)?e:[e],n=[];for(let e of t)e instanceof UP?n.push(e):e instanceof SF?n.push(new UP(e.asset,``)):e instanceof CF&&n.push(new UP(``,e.path));return n}function lF(e){return e===null?[]:(Array.isArray(e)?e:[e]).filter(e=>e instanceof CF).map(e=>e.path)}function uF(e){return e===null?[]:(Array.isArray(e)?e:[e]).map(String)}function dF(e){return e instanceof SF?e.asset:e instanceof CF?e.path:Array.isArray(e)?e.map(dF):e}function fF(e,t){for(let n of e)Array.isArray(n)?fF(n,t):t.push(n);return t}function pF(e,t){if(t==null)return t;let n=e.endsWith(`[]`),r=n?e.slice(0,-2):e;if(xF.has(r)||!Array.isArray(t))return dF(t);let i=fF(t,[]);if(r.startsWith(`quat`))for(let e=0;e+3<i.length;e+=4)i.splice(e,4,i[e+1],i[e+2],i[e+3],i[e]);return n?yF.has(r)?Int32Array.from(i):bF.has(r)?Float64Array.from(i):Float32Array.from(i):i}function mF(e,t,n,r){switch(t){case`references`:case`payload`:e.setArc(t,n,cF(r));return;case`inherits`:case`specializes`:e.setArc(t,n,lF(r));return;case`variantSets`:e.setArc(`variantSetNames`,n,uF(r));return;case`apiSchemas`:e.setArc(`apiSchemas`,n,uF(r));return;case`variants`:e.variantSelection={...e.variantSelection??{},...r};return;default:e.meta[t]=dF(r)}}function hF(e,t=``){return new DF(e).parse(t)}var gF,_F,vF,yF,bF,xF,SF,CF,wF,TF,EF,DF,OF=g((()=>{sF(),gF=new Set([`prepend`,`append`,`add`,`delete`,`reorder`]),_F=new Set([`def`,`over`,`class`]),vF=new Set([`custom`,`uniform`,`varying`,`config`]),yF=new Set([`int`,`int2`,`int3`,`int4`,`uint`,`int64`,`uint64`,`uchar`]),bF=new Set([`double`,`double2`,`double3`,`double4`,`matrix2d`,`matrix3d`,`matrix4d`,`quatd`,`timecode`,`point3d`,`vector3d`,`normal3d`,`color3d`,`color4d`,`texCoord2d`,`texCoord3d`,`frame4d`]),xF=new Set([`token`,`string`,`asset`,`bool`,`dictionary`,`opaque`,`pathExpression`]),SF=class{constructor(e){this.asset=e}},CF=class{constructor(e){this.path=e}},wF=e=>e>=65&&e<=90||e>=97&&e<=122||e===95,TF=e=>wF(e)||e>=48&&e<=57||e===58||e===46,EF=class{constructor(e){this.s=e,this.i=0}fail(e){let t=1;for(let e=0;e<this.i&&e<this.s.length;e++)this.s.charCodeAt(e)===10&&t++;throw Error(`usda line ${t}: ${e}`)}skip(){let e=this.s;for(;;){let t=e.charCodeAt(this.i);if(t===32||t===9||t===10||t===13||t===59)this.i++;else if(t===35)for(;this.i<e.length&&e.charCodeAt(this.i)!==10;)this.i++;else return t}}peek(){return this.skip()}startsNumber(e){if(e>=48&&e<=57||e===46)return!0;if(e!==45&&e!==43)return!1;let t=this.s.charCodeAt(this.i+1);return t>=48&&t<=57||t===46||t===105}skipLayerOffset(){let e=this.i;if(this.peek()!==40)return;this.i++;let t=this.peekIdent();if(this.i=e,t!==`offset`&&t!==`scale`)return;this.skip();let n=this.s.indexOf(`)`,this.i);n<0&&this.fail(`unterminated layer offset`),this.i=n+1}eat(e){this.skip()!==e.charCodeAt(0)&&this.fail(`expected "${e}", found "${this.s[this.i]??`end of file`}"`),this.i++}maybe(e){return this.skip()===e.charCodeAt(0)?(this.i++,!0):!1}ident(){wF(this.skip())||this.fail(`expected a name, found "${this.s[this.i]??`end of file`}"`);let e=this.i++;for(;TF(this.s.charCodeAt(this.i));)this.i++;return this.s.slice(e,this.i)}peekIdent(){let e=this.i;if(!wF(this.skip()))return this.i=e,null;let t=this.ident();return this.i=e,t}string(){let e=this.skip();e!==34&&e!==39&&this.fail(`expected a string, found "${this.s[this.i]??`end of file`}"`);let t=this.s,n=t[this.i];if(t.startsWith(n+n+n,this.i)){let e=t.indexOf(n+n+n,this.i+3);e<0&&this.fail(`unterminated string`);let r=t.slice(this.i+3,e);return this.i=e+3,r}let r=``,i=++this.i;for(;;){let e=t.charCodeAt(this.i);if(Number.isNaN(e)&&this.fail(`unterminated string`),e===92){r+=t.slice(i,this.i);let e=t[this.i+1];r+=e===`n`?`
|
|
1429
|
-
`:e===`t`?` `:e,this.i+=2,i=this.i;continue}if(t[this.i]===n)break;this.i++}return r+=t.slice(i,this.i),this.i++,r}asset(){let e=this.s;if(e.startsWith(`@@@`,this.i)){let t=e.indexOf(`@@@`,this.i+3);t<0&&this.fail(`unterminated asset path`);let n=e.slice(this.i+3,t);return this.i=t+3,n}let t=e.indexOf(`@`,this.i+1);t<0&&this.fail(`unterminated asset path`);let n=e.slice(this.i+1,t);return this.i=t+1,n}path(){let e=this.s.indexOf(`>`,this.i+1);e<0&&this.fail(`unterminated path`);let t=this.s.slice(this.i+1,e);return this.i=e+1,t}number(){let e=this.s,t=this.i;if((e[this.i]===`-`||e[this.i]===`+`)&&this.i++,e.startsWith(`inf`,this.i))return this.i+=3,e[t]===`-`?-1/0:1/0;for(;this.i<e.length;){let t=e.charCodeAt(this.i);if(t>=48&&t<=57||t===46)this.i++;else if(t===101||t===69)this.i++,(e[this.i]===`-`||e[this.i]===`+`)&&this.i++;else break}let n=Number(e.slice(t,this.i));return Number.isNaN(n)&&this.fail(`bad number "${e.slice(t,this.i)}"`),n}value(){let e=this.skip();if(e===40)return this.sequence(`)`);if(e===91)return this.sequence(`]`);if(e===123)return this.dictionary();if(e===34||e===39)return this.string();if(e===64){let e=this.asset(),t=this.peek()===60?new UP(e,this.path()):new SF(e);return this.skipLayerOffset(),t}if(e===60){let e=new CF(this.path());return this.skipLayerOffset(),e}if(this.startsNumber(e))return this.number();let t=this.ident();return t===`true`?!0:t===`false`?!1:t===`None`?null:t===`inf`?1/0:t===`nan`?NaN:t}sequence(e){this.i++;let t=[];for(;this.peek()!==e.charCodeAt(0)&&(t.push(this.value()),this.maybe(`,`)););return this.eat(e),t}dictionary(){this.i++;let e={};for(;this.peek()!==125;){if(this.startsNumber(this.peek())){let t=this.number();this.eat(`:`),e[t]=this.value(),this.maybe(`,`);continue}let t=this.ident();this.peek()===91&&this.s[this.i+1]===`]`&&(this.i+=2,t+=`[]`);let n=this.peek()===34||this.peek()===39?this.string():this.ident();this.eat(`=`),e[n]=t===`dictionary`?this.dictionary():this.value(),this.maybe(`,`)}return this.eat(`}`),e}},DF=class extends EF{parse(e){let t=new JP(e);if(this.s.charCodeAt(0)===65279&&(this.i=1),!this.s.startsWith(`#usda`,this.i))throw Error(`not a usda layer`);for(;this.i<this.s.length&&this.s.charCodeAt(this.i)!==10;)this.i++;for(this.peek()===40&&this.metadata((e,n,r)=>{e===`subLayers`?t.meta.subLayers=cF(r).map(e=>e.asset):t.meta[e]=dF(r)},e=>{t.meta.doc=e});!Number.isNaN(this.peek());)this.prim(t.root);return t}metadata(e,t=null){for(this.eat(`(`);this.peek()!==41;){let n=this.peek();if(n===34||n===39){let e=this.string();t&&t(e);continue}let r=this.ident(),i=`explicit`;gF.has(r)&&(i=r,r=this.ident()),this.eat(`=`),e(r,i,this.value())}this.eat(`)`)}prim(e){let t=this.ident();_F.has(t)||this.fail(`expected def, over or class, found "${t}"`);let n=this.peek()===34||this.peek()===39?``:this.ident(),r=this.string(),i=e.child(r,!0);i.specifier=t,i.typeName=n,this.peek()===40&&this.metadata((e,t,n)=>mF(i,e,t,n),e=>{i.meta.doc=e}),this.body(i)}body(e){for(this.eat(`{`);this.peek()!==125;){let t=this.peekIdent();if(t===null&&this.fail(`unexpected "${this.s[this.i]??`end of file`}" in a prim`),_F.has(t))this.prim(e);else if(t===`variantSet`)this.variantSet(e);else if(t===`reorder`){this.ident();let t=this.ident();this.eat(`=`);let n=uF(this.value());t===`nameChildren`&&(e.reorder=n)}else this.property(e)}this.eat(`}`)}variantSet(e){this.ident();let t=this.string();for(this.eat(`=`),this.eat(`{`);this.peek()!==125;){let n=e.variant(t,this.string(),!0);this.peek()===40&&this.metadata((e,t,r)=>mF(n,e,t,r)),this.body(n)}this.eat(`}`)}property(e){let t=this.ident(),n=`explicit`,r=!1,i=!1;for(;;){if(gF.has(t))n=t;else if(vF.has(t))t===`uniform`&&(r=!0),t===`custom`&&(i=!0);else break;t=this.ident()}if(t===`rel`){let t=this.ident(),r=e.property(t,!0);if(r.rel=!0,r.custom=i,this.maybe(`=`)){let e=this.value();r.setTargets(n,lF(e))}this.peek()===40&&this.metadata((e,t,n)=>{r.meta[e]=dF(n)},()=>{});return}let a=t;this.peek()===91&&this.s[this.i+1]===`]`&&(this.i+=2,a+=`[]`);let o=this.ident(),s=`default`;for(let e of[`.connect`,`.timeSamples`,`.spline`])o.endsWith(e)&&(s=e.slice(1),o=o.slice(0,-e.length));let c=e.property(o,!0);if(c.type=a,c.uniform=r||c.uniform,c.custom=i,this.maybe(`=`))if(s===`connect`)c.setConnections(n,lF(this.value()));else if(s===`timeSamples`){let e=this.value();c.timeSamples=new Map(Object.entries(e).map(([e,t])=>[Number(e),pF(a,t)]).sort((e,t)=>e[0]-t[0]))}else if(s===`spline`)this.value();else{let e=this.value();c.value=e===null?null:pF(a,e),c.hasValue=!0}this.peek()===40&&this.metadata((e,t,n)=>{c.meta[e]=dF(n)},e=>{c.meta.doc=e})}}}));function kF(e,t){return e.length>=8&&e[0]===80&&e[1]===88&&e[2]===82&&e[3]===45&&e[4]===85&&e[5]===83&&e[6]===68&&e[7]===67?HP(e.byteOffset===0&&e.byteLength===e.buffer.byteLength?e.buffer:e.slice().buffer,t):hF(new TextDecoder().decode(e),t)}function AF(e){let t=[];for(let n of e.replace(/\\/g,`/`).split(`/`))n===``||n===`.`||(n===`..`?t.pop():t.push(n));return t.join(`/`)}function jF(e,t,n){return e===t?n:r=>{if(r===e)return n(t);let i=r.charCodeAt(e.length);return r.startsWith(e)&&(i===47||i===46||i===123)?n(t+r.slice(e.length)):n(r)}}function*MF(e){yield e;for(let t of e.children)yield*MF(t)}function NF(e,t){let n=e=>e.map(t);return{explicit:e.explicit?n(e.explicit):null,prepend:n(e.prepend),append:n(e.append),add:n(e.add),delete:n(e.delete)}}var PF,FF,IF,LF,RF,zF,BF,VF,HF,UF=g((()=>{sF(),OF(),PF={local:0,inherit:1,variant:2,reference:3,payload:4,specialize:5},FF=32,IF=e=>e.includes(`/`)?e.slice(0,e.lastIndexOf(`/`)):``,LF=class{constructor(e,t,{omitted:n=[]}={}){this.read=t,this.exact=new Map,this.lower=new Map,this.byName=new Map,this.omitted=new Set(n.map(e=>AF(e).toLowerCase()));for(let t of e){let e=AF(t);this.exact.set(e,t),this.lower.set(e.toLowerCase(),t);let n=e.split(`/`).pop().toLowerCase(),r=this.byName.get(n);r?r.push(t):this.byName.set(n,[t])}}isOmitted(e,t=``){return this.omitted.has(this.key(e,t).toLowerCase())}key(e,t){let n=e.replace(/\\/g,`/`);return AF(n.startsWith(`/`)?n:`${IF(t)}/${n}`)}resolve(e,t=``){if(!e)return null;let n=e.replace(/\\/g,`/`),r=this.key(e,t),i=this.exact.get(r)??this.lower.get(r.toLowerCase());if(i)return i;let a=AF(n).toLowerCase(),o=(this.byName.get(a.split(`/`).pop())??[]).filter(e=>AF(e).toLowerCase().endsWith(`/${a}`));return o.length===1?o[0]:null}},RF=e=>e,zF=(e,t)=>e===`/`?`/${t}`:`${e}/${t}`,BF=class{constructor(e,t,n,r,i){this.stack=e,this.path=t,this.map=n,this.arc=r,this.depth=i,this.specs=[],this.layers=[],this.children=[],this.choice=null,this.doneSets=null}add(e){let t=PF[e.arc],n=this.children.length;for(;n>0;){let r=this.children[n-1],i=PF[r.arc];if(i<t||i===t&&r.depth>=e.depth)break;n--}this.children.splice(n,0,e)}},VF=class{constructor(e,t,n){this.stage=e,this.path=t,this.root=n,this._sites=null}get name(){return this.path===`/`?``:this.path.slice(this.path.lastIndexOf(`/`)+1)}get sites(){if(this._sites)return this._sites;this._sites=[];for(let e of MF(this.root))for(let t=0;t<e.specs.length;t++)this._sites.push([e,e.specs[t],e.layers[t]]);return this._sites}get typeName(){for(let[,e]of this.sites)if(e.typeName)return e.typeName;return``}get isDefined(){for(let[,e]of this.sites){if(e.specifier===`def`)return!0;if(e.specifier===`class`)return!1}return!1}meta(e){for(let[,t]of this.sites)if(t.meta[e]!==void 0)return t.meta[e]}property(e){for(let[,t]of this.sites){let n=t.props?.get(e);if(n&&(n.hasValue||n.timeSamples))return n}return null}value(e){let t=this.property(e);if(!t)return;if(t.hasValue)return t.value??void 0;let n=t.timeSamples?.values().next();return n&&!n.done?n.value??void 0:void 0}propertyMeta(e,t){for(let[,n]of this.sites){let r=n.props?.get(e)?.meta[t];if(r!==void 0)return r}}assetPath(e){for(let[,t,n]of this.sites){let r=t.props?.get(e);if(!r?.hasValue)continue;let i=r.value;return typeof i==`string`&&i?{asset:i,path:this.stage.files.resolve(i,n.path)}:null}return null}propertyNames(){let e=new Set;for(let[,t]of this.sites)for(let n of t.props?.keys()??[])e.add(n);return[...e]}_paths(e,t){let n=[];for(let[r,i]of this.sites){let a=i.props?.get(e)?.[t];a&&n.push(NF(a,r.map))}return FP(n).map(e=>e.value)}targets(e){return this._paths(e,`targets`)}connections(e){return this._paths(e,`connections`)}childNames(){let e=new Set;for(let[,t]of this.sites)for(let n of t.children?.keys()??[])e.add(n);return[...e]}instanceKey(){let e=this.path.split(`/`).length-1,t=[],n=r=>{r.arc!==`local`&&r.depth>=e&&t.push(`${r.arc}|${r.stack.id}|${r.path}|${r.choice??``}`);for(let e of r.children)n(e)};return n(this.root),t.join(`;`)}},HF=class{constructor(e,{warn:t=()=>{}}={}){this.files=e,this.warn=t,this._layers=new Map,this._stacks=new Map,this._prims=new Map,this._warned=new Set,this.omittedArcs=0,this.root=null,this.pseudoRoot=null}warnOnce(e,t){this._warned.has(e)||(this._warned.add(e),this.warn(t))}async open(e){if(this.root=await this.stack(e),!this.root)throw Error(`USD layer "${e}" could not be read`);let t=this.root.layers[0].meta;return this.upAxis=t.upAxis??`Y`,this.metersPerUnit=t.metersPerUnit??.01,this.defaultPrim=t.defaultPrim??``,this.pseudoRoot=new VF(this,`/`,this.rootNode(this.root,RF,`local`,0)),this._prims.set(`/`,this.pseudoRoot),this.pseudoRoot}layer(e){let t=this._layers.get(e);return t||(t=(async()=>{let t=await this.files.read(e);if(!t)return null;try{return kF(t,e)}catch(t){return this.warnOnce(`parse:${e}`,`USD layer "${e}" could not be parsed: ${t.message}`),null}})(),this._layers.set(e,t)),t}stack(e,t=new Set){let n=this._stacks.get(e);return n||(n=(async()=>{let n=[],r=async e=>{if(t.has(e))return;t.add(e);let i=await this.layer(e);if(i){n.push(i);for(let t of i.meta.subLayers??[]){let n=this.files.resolve(t,e);n?await r(n):this.warnOnce(`missing:${t}`,`USD sublayer "${t}" of "${e}" not found`)}}};return await r(e),n.length===0?null:{id:e,layers:n,defaultPrim:n[0].meta.defaultPrim??``}})(),this._stacks.set(e,n)),n}rootNode(e,t,n,r){let i=new BF(e,`/`,t,n,r);return i.layers=e.layers.slice(),i.specs=e.layers.map(e=>e.root),i}async child(e,t){let n=zF(e.path,t),r=this._prims.get(n);if(r)return r;let i=n.split(`/`).length-1,a=await this.childNode(e.root,t,i,new Set);if(!a)return null;await this.addVariants(a,i,new Set);let o=new VF(this,n,a);return this._prims.set(n,o),o}async primAt(e){if(!this.pseudoRoot)return null;let t=this._prims.get(e);if(t)return t;let n=this.pseudoRoot;for(let t of e.split(`/`).filter(Boolean))if(n=await this.child(n,t),!n)return null;return n}release(){this._prims.clear(),this._prims.set(`/`,this.pseudoRoot);let e=new Set(this.root.layers.map(e=>e.path));for(let t of this._layers.keys())e.has(t)||this._layers.delete(t);for(let e of this._stacks.keys())e!==this.root.id&&this._stacks.delete(e)}async childNode(e,t,n,r){let i=new BF(e.stack,zF(e.path,t),e.map,e.arc,e.depth);i.choice=e.choice;for(let n=0;n<e.specs.length;n++){let r=e.specs[n].child(t);r&&(i.specs.push(r),i.layers.push(e.layers[n]))}for(let a of e.children){let e=await this.childNode(a,t,n,r);e&&i.children.push(e)}return i.specs.length&&await this.addArcs(i,n,r),i.specs.length||i.children.length?i:null}async addArcs(e,t,n){let r=t=>FP(e.specs.map(e=>e.arcs?.[t]??null),e.layers);for(let{value:i}of r(`inherits`))await this.addClass(e,i,`inherit`,t,n);for(let{value:i,source:a}of r(`references`))await this.addReference(e,i,a,`reference`,t,n);for(let{value:i,source:a}of r(`payload`))await this.addReference(e,i,a,`payload`,t,n);for(let{value:i}of r(`specializes`))await this.addClass(e,i,`specialize`,t,n)}async addClass(e,t,n,r,i){let a=await this.subtree(e.stack,t,jF(t,e.path,e.map),n,r,i);a&&e.add(a)}async addReference(e,t,n,r,i,a){let o=e.stack;if(t.asset){let e=this.files.resolve(t.asset,n?.path??``);if(!e){this.files.isOmitted(t.asset,n?.path??``)?this.omittedArcs++:this.warnOnce(`missing:${t.asset}`,`USD ${r} "${t.asset}" (from "${n?.path}") not found — skipped`);return}if(o=await this.stack(e),!o)return}let s=t.path||(o.defaultPrim?`/${o.defaultPrim}`:``);if(!s){this.warnOnce(`nodefault:${o.id}`,`USD ${r} to "${o.id}" names no prim and the layer has no defaultPrim — skipped`);return}let c=await this.subtree(o,s,jF(s,e.path,e.map),r,i,a);c&&e.add(c)}async subtree(e,t,n,r,i,a){let o=`${e.id}\u0000${t}`;if(a.has(o))return this.warnOnce(`cycle:${o}`,`USD composition cycle through "${t}" in "${e.id}" — skipped`),null;let s=new Set(a).add(o),c=this.rootNode(e,n,r,i),l=t.split(`/`).filter(Boolean);for(let e=0;e<l.length;e++)if(e>0&&await this.addVariants(c,i,s),c=await this.childNode(c,l[e],i,s),!c)return null;return c}async addVariants(e,t,n){for(let r=!0;r;){r=!1;for(let i of[...MF(e)]){let a=new Set(FP(i.specs.map(e=>e.arcs?.variantSetNames??null)).map(e=>e.value));for(let e of i.specs)for(let t of e.variantSets?.keys()??[])a.add(t);for(let o of a){if(i.doneSets??=new Set,i.doneSets.has(o))continue;i.doneSets.add(o);let a=this.selection(e,o);if(!a)continue;let s=new BF(i.stack,i.path,i.map,`variant`,t);s.choice=`${o}=${a}`;for(let e=0;e<i.specs.length;e++){let t=i.specs[e].variant(o,a);t&&(s.specs.push(t),s.layers.push(i.layers[e]))}s.specs.length!==0&&(i.add(s),await this.addArcs(s,t,n),r=!0)}}}}selection(e,t){for(let n of MF(e))for(let e of n.specs){let n=e.variantSelection?.[t];if(n)return n}return null}async connectionSource(e,t){let[n]=e.connections(t);for(let e=0;n&&e<FF;e++){let e=n.lastIndexOf(`.`),t=await this.primAt(n.slice(0,e));if(!t)return null;let r=n.slice(e+1),i=t.connections(r)[0];if(!i||t.value(`info:id`))return{prim:t,name:r};n=i}return null}}}));function WF(e,t,n){if(yI(e)&&yI(t))return n(e,t);let r=Math.max(yI(e)?1:e.length,yI(t)?1:t.length);return Array.from({length:r},(r,i)=>n(yI(e)?e:e[i]??e[0],yI(t)?t:t[i]??t[0]))}function GF(e,t){let n=Math.cos(t*sI),r=Math.sin(t*sI);return[n*e[0]+r*e[3],n*e[1]+r*e[4],n*e[2]+r*e[5],n*e[3]-r*e[0],n*e[4]-r*e[1],n*e[5]-r*e[2]]}function KF(){return{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:[]}}function qF(e,t){let n=e.split(`:`)[1];if(t==null)return null;let i=new r.Matrix4;switch(n){case`translate`:return i.makeTranslation(t[0],t[1],t[2]);case`scale`:return typeof t==`number`?i.makeScale(t,t,t):i.makeScale(t[0],t[1],t[2]);case`rotateX`:return i.makeRotationX(t*sI);case`rotateY`:return i.makeRotationY(t*sI);case`rotateZ`:return i.makeRotationZ(t*sI);case`orient`:return i.makeRotationFromQuaternion(new r.Quaternion(t[0],t[1],t[2],t[3]).normalize());case`transform`:return i.fromArray(t);default:{let e=/^rotate([XYZ]{3})$/.exec(n);return e?i.makeRotationFromEuler(new r.Euler(t[0]*sI,t[1]*sI,t[2]*sI,[...e[1]].reverse().join(``))):null}}}function JF(e){let t=new r.Matrix4,n=!1;for(let r of e.value(`xformOpOrder`)??[]){if(r===`!resetXformStack!`){n=!0,t.identity();continue}let i=r.startsWith(`!invert!`),a=i?r.slice(8):r,o=qF(a,e.value(a));o&&(i&&o.invert(),t.multiply(o))}return{matrix:t,reset:n}}function YF(e,t){let n=`primvars:${t}`,r=e.value(n);if(r==null||r.length===0)return null;let i=e.value(`${n}:indices`);return{values:r,interpolation:e.propertyMeta(n,`interpolation`)??`constant`,indices:i?.length?i:null}}function XF(e){if(!e)return null;let{values:t}=e,n=[0,0,0],r=Math.floor(t.length/3);if(r===0)return null;for(let e=0;e<r;e++)for(let r=0;r<3;r++)n[r]+=t[e*3+r];return n.map(e=>e/r)}function ZF(e,t,n,r){let i=e.interpolation===`faceVarying`?n:e.interpolation===`uniform`?t:e.interpolation===`constant`?0:r;return e.indices?e.indices[i]:i}function QF(e,t){let{points:n,counts:r,offsets:i,fvi:a,leftHanded:o,normals:s,uv:c}=e,l=DI(s)||DI(c),u=0,d=0;for(let e of t)r[e]>=3&&(u+=r[e]-2,d+=r[e]);let f=new Uint32Array(u*3),p=0,m=(e,t,n)=>{for(let r=1;r+1<t;r++)f[p++]=n(e,0),f[p++]=n(e,o?r+1:r),f[p++]=n(e,o?r:r+1)};if(!l){for(let e of t)r[e]>=3&&m(i[e],r[e],(e,t)=>a[e+t]);let e=n.length/3;return{P:n,N:s&&s.values.length===e*3?s.values:null,uv:c&&c.values.length===e*2?c.values:null,index:f}}let h=new Float32Array(d*3),g=s?new Float32Array(d*3):null,_=c?new Float32Array(d*2):null,v=0;for(let e of t){let t=r[e];if(t<3)continue;let o=v;for(let r=0;r<t;r++){let t=i[e]+r,o=a[t];if(h[v*3]=n[o*3],h[v*3+1]=n[o*3+1],h[v*3+2]=n[o*3+2],g){let n=ZF(s,e,t,o)*3;g[v*3]=s.values[n],g[v*3+1]=s.values[n+1],g[v*3+2]=s.values[n+2]}if(_){let n=ZF(c,e,t,o)*2;_[v*2]=c.values[n],_[v*2+1]=c.values[n+1]}v++}m(o,t,(e,t)=>e+t)}return{P:h,N:g,uv:_,index:f}}function $F(e,t){t===`Z`?e.rotateX(Math.PI/2):t===`X`&&e.rotateZ(-Math.PI/2);let n=e.getAttribute(`position`).array;return{P:n,N:e.getAttribute(`normal`)?.array??null,uv:e.getAttribute(`uv`)?.array??null,index:e.index?Uint32Array.from(e.index.array):Uint32Array.from({length:n.length/3},(e,t)=>t)}}function eI(e){return e.map(e=>Math.round(Math.min(Math.max(e,0),64)/cI)*cI)}function tI(e,t){let n=Math.imul(e^t,2654435761);return n=Math.imul(n^n>>>15,2246822507),n=Math.imul(n^n>>>13,3266489909),((n^n>>>16)>>>0)/4294967296}function nI(e){let t=2166136261;for(let n=0;n<e.length;n++)t=Math.imul(t^e.charCodeAt(n),16777619);return t}function rI(e,t,n,r){return t===`linear`?r===`periodic`?e:e-1:n===`bezier`?r===`periodic`?e/3:(e-1)/3:r===`periodic`?e:r===`pinned`?e+1:e-3}function iI(e,t){let n=new Map,r=[...e].sort((e,t)=>e[1]-t[1]),i=Math.max(0,t);for(let e=0;e<r.length;e++){let t=r[e][1],a=i/(r.length-e);if(t<=a){i-=t;continue}for(let t=e;t<r.length;t++)n.set(r[t][0],a/r[t][1]);break}return n}function aI(e,t,n,r){return t===`vertex`?e:t===`varying`?Math.max(1,Math.round(n===`linear`?e-1:r===`bezier`?(e-1)/3:e-3)+1):1}function oI(e,t,n){let{counts:r,type:i,basis:a}=e,o=[],s=Math.floor(r.length*t);for(let e=0;e<r.length&&o.length<s;e++)tI(e,n)<t&&o.push(e);if(o.length===0)return null;if(o.length===r.length)return e;let c=(e,t,n)=>{if(!e?.length||!n||n===`constant`)return e;let s=new Int32Array(r.length+1);for(let e=0;e<r.length;e++)s[e+1]=s[e]+aI(r[e],n,i,a);let c=0;for(let e of o)c+=s[e+1]-s[e];let l=new e.constructor(c*t),u=0;for(let n of o){let r=e.subarray(s[n]*t,s[n+1]*t);l.set(r,u),u+=r.length}return l};return{...e,points:c(e.points,3,`vertex`),counts:Int32Array.from(o,e=>r[e]),widths:c(e.widths,1,e.widthMode),normals:c(e.normals,3,e.normalMode)}}var sI,cI,lI,uI,dI,fI,pI,mI,hI,gI,_I,vI,yI,bI,xI,SI,CI,wI,TI,EI,DI,OI,kI,AI=g((()=>{ZN(),sI=Math.PI/180,cI=1/255,lI=new Set([`RectLight`,`DiskLight`,`SphereLight`,`DistantLight`,`DomeLight`,`CylinderLight`]),uI=new Set([`Sphere`,`Cube`,`Cylinder`,`Cone`,`Capsule`,`Plane`]),dI=new Set([`Material`,`Shader`,`NodeGraph`,`GeomSubset`,`Volume`,`OpenVDBAsset`,`Field3DAsset`,`SkelAnimation`,`BlendShape`]),fI=/\.(ptx|ptex)$/i,pI={repeat:r.RepeatWrapping,mirror:r.MirroredRepeatWrapping,clamp:r.ClampToEdgeWrapping,black:r.ClampToEdgeWrapping},mI=/_(?:float|integer|boolean|string|filename|color3|color4|vector2|vector3|vector4|matrix33|matrix44|surfaceshader|BSDF|EDF)(?:FA|I|B)?(?=_|$)/,hI=e=>{let t=e.slice(3),n=t.search(mI);return n>0?t.slice(0,n):t},gI={open_pbr_surface:`openPbrSurface`,standard_surface:`standardSurface`,gltf_pbr:`gltfPbrSurface`,UsdPreviewSurface:`previewSurface`,surface:`bsdfSurface`},_I={periodic:`repeat`,mirror:`mirror`,clamp:`clamp`,constant:`black`},vI=[1,0,0,0,1,0],yI=e=>typeof e==`number`,bI=e=>yI(e)||Array.isArray(e),xI=(e,t)=>yI(e)?t(e):e.map(t),SI=e=>yI(e)?e:e.slice(0,3).reduce((e,t)=>e+t,0)/Math.min(e.length,3),CI=(e,[t,n])=>[e[0]*t,e[1]*t,e[2]*t,e[3]*n,e[4]*n,e[5]*n],wI=(e,[t,n])=>[e[0],e[1],e[2]+t,e[3],e[4],e[5]+n],TI=(e,t=`float`)=>({type:t,value:e}),EI=e=>({type:`string`,value:[e]}),DI=e=>e&&(e.indices||e.interpolation===`faceVarying`||e.interpolation===`uniform`||e.interpolation===`constant`),OI=.65,kI=class{constructor(e,{maxTriangles:t=1/0,maxPlacements:n=1/0,curveSteps:r=2,resolveImage:i=async()=>null,warn:a=()=>{}}={}){this.stage=e,this.maxTriangles=t,this.maxPlacements=n,this.curveSteps=r,this.resolveImage=i,this.warn=a,this.ir=KF(),this.cameras=[],this.lights=[],this.domes=[],this.prototypes=new Map,this._surfaces=new Map,this._colored=new Map,this._wrappers=new Map,this._images=new Map,this._handed=new WeakSet,this._warned=new Set,this._protoCount=0,this._geometries=new Map,this._specIds=new WeakMap,this._nextSpecId=0,this.dry=!1,this.cost=null,this.placementRates=new Map,this.curveRates=new Map,this.fitNote=null}warnOnce(e,t){this._warned.has(e)||(this._warned.add(e),this.warn(t))}async read(){return(Number.isFinite(this.maxTriangles)||Number.isFinite(this.maxPlacements))&&await this.fit(),await this.walk(),this.shareGeometry(),{ir:this.ir,cameras:this.cameras,lights:this.lights,dome:this.pickDome(),cost:this.cost}}async walk(){let e=this.stage.pseudoRoot,t=this.stage.upAxis===`Z`?new r.Matrix4().makeRotationX(-Math.PI/2):new r.Matrix4;for(let n of e.childNames()){let r=await this.stage.child(e,n);r&&await this.visit(r,t,this.world(),{binding:null,depth:0}),this.stage.release()}}async fit(){this.dry=!0,this.cost={mesh:0,curves:0,placements:0,scatter:0,counted:new Set,curveSets:new Map,instancers:new Map},await this.walk(),this.dry=!1,this.prototypes.clear();let{mesh:e,curves:t,placements:n,scatter:r,curveSets:i,instancers:a}=this.cost;delete this.cost.counted,delete this.cost.curveSets,delete this.cost.instancers,n>this.maxPlacements&&(this.placementRates=iI(a,(this.maxPlacements-(n-r))*.98)),e+t>this.maxTriangles&&(this.curveRates=iI(i,(this.maxTriangles-e)*.95));let o=e=>`${(e/1e6).toFixed(1)}M`,s=(e,t)=>{let n=0,r=0;for(let[i,a]of t)n+=a,r+=a*(e.get(i)??1);return`${Math.round(r/n*100)} %`},c=[];(this.placementRates.size||this.curveRates.size)&&c.push(`USD scene is ${o(e+t)} triangles (${o(t)} of curves) and ${o(n)} placed copies, past the budgets (${o(this.maxTriangles)}, ${o(this.maxPlacements)}): ${s(this.curveRates,i)} of the curves and ${s(this.placementRates,a)} of the scattered copies kept, the largest sets thinned most`),e>this.maxTriangles&&c.push(`its meshes alone are ${o(e)} triangles, past the ${o(this.maxTriangles)} budget: what is read last is cut. Load fewer parts, or raise maxTriangles (memory spill raises it)`),this.fitNote=c.join(`; `)||null,this.fitNote&&this.warn(this.fitNote)}world(){return this.dry?{isWorld:!0,shape:()=>this.cost.placements++,place:e=>this.countPrototype(e,1,!1),instancer:e=>this.countInstancer(e,1)}:{isWorld:!0,shape:(e,t)=>{e.ctm=Array.from(t.elements),this.ir.shapes.push(e)},place:(e,t)=>this.placePrototype(e,t),instancer:(e,t)=>this.placeInstancer(e,t)}}collector(e){return this.dry?{isWorld:!1,shape:(t,n)=>e.shapes.push(n?n.elements.join(`,`):``),place:t=>e.nested.push({proto:t}),instancer:t=>e.nested.push({instancer:t})}:{isWorld:!1,shape:(t,n)=>{t.ctm=Array.from(n.elements),e.shapes.push(t)},place:(t,n)=>e.nested.push({proto:t,matrix:n.clone()}),instancer:(t,n)=>e.nested.push({instancer:t,matrix:n.clone()})}}async visit(e,t,n,i){if(!e.isDefined||e.meta(`active`)===!1||e.value(`visibility`)===`invisible`)return;let a=e.value(`purpose`);if(a===`guide`||a===`proxy`)return;let o=e.typeName;if(dI.has(o)){o===`Volume`&&this.warnOnce(`volume`,`USD volumes are not rendered — skipped`);return}let{matrix:s,reset:c}=JF(e),l=c?s:new r.Matrix4().multiplyMatrices(t,s),u=this.bindingOf(e)??i.binding;if(e.meta(`instanceable`)===!0&&e.childNames().length){let t=await this.instancePrototype(e,u);t&&n.place(t,l);return}if(o===`Mesh`)await this.mesh(e,l,n,u);else if(o===`BasisCurves`)await this.curves(e,l,n,u);else if(uI.has(o))await this.gprim(e,l,n,u);else if(o===`PointInstancer`){await this.pointInstancer(e,l,n,u);return}else if(o===`Camera`)n.isWorld&&!this.dry&&this.camera(e,l);else if(lI.has(o)){if(this.dry)return;n.isWorld?this.light(e,o,l):this.warnOnce(`protoLight`,`USD lights inside instanced prims are not placed — skipped`)}else (o===`NurbsPatch`||o===`NurbsCurves`||o===`Points`||o===`HermiteCurves`)&&this.warnOnce(`type:${o}`,`USD ${o} prims are not supported — skipped`);for(let t of e.childNames()){let r=await this.stage.child(e,t);r&&await this.visit(r,l,n,{binding:u,depth:i.depth+1}),i.depth===0&&n.isWorld&&this.stage.release()}}bindingOf(e){for(let t of[`material:binding:full`,`material:binding`]){let[n]=e.targets(t);if(n)return n}return null}newPrototype(){return{name:`usd_proto_${this._protoCount++}`,shapes:[],nested:[],registered:!1}}register(e){return e.shapes.length&&!e.registered&&!this.dry&&(this.ir.objects.set(e.name,e.shapes),e.registered=!0),e.shapes.length||e.nested.length?e:null}async instancePrototype(e,t){let n=`instance|${e.instanceKey()}|${t??``}`;if(this.prototypes.has(n))return this.prototypes.get(n);let i=this.newPrototype();this.prototypes.set(n,i);let a=this.collector(i);for(let n of e.childNames()){let i=await this.stage.child(e,n);i&&await this.visit(i,new r.Matrix4,a,{binding:t,depth:1/0})}let o=this.register(i);return this.prototypes.set(n,o),o}async instancerPrototype(e,t){let n=`proto|${e.path}`;if(this.prototypes.has(n))return this.prototypes.get(n);let i=this.newPrototype();this.prototypes.set(n,i),await this.visit(e,new r.Matrix4,this.collector(i),{binding:t,depth:1/0});let a=this.register(i);return this.prototypes.set(n,a),a}addInstance(e,t){let n=this.ir;if(n.instanceCount>=this.maxPlacements){n.skippedInstances++;return}let r=n.instances.get(e);r||n.instances.set(e,r={name:e,count:0,matrices:new Float32Array(512),matricesEnd:null});let i=(r.count+1)*16;if(i>r.matrices.length){let e=new Float32Array(Math.max(i,r.matrices.length*2));e.set(r.matrices),r.matrices=e}r.matrices.set(t.elements,r.count*16),r.count++,n.instanceCount++}countPrototype(e,t,n){e.shapes.length&&(e.placeKeys??=new Set(e.shapes).size,this.cost.placements+=t*e.placeKeys,n&&(this.cost.scatter+=t*e.placeKeys));for(let r of e.nested)r.proto?this.countPrototype(r.proto,t,n):this.countInstancer(r.instancer,t)}countInstancer(e,t){let n=this.cost.scatter;e.histogram.forEach((n,r)=>{e.protos[r]&&n&&this.countPrototype(e.protos[r],t*n,!0)}),this.cost.instancers.set(e.path,(this.cost.instancers.get(e.path)??0)+this.cost.scatter-n)}placePrototype(e,t){e.shapes.length&&this.addInstance(e.name,t);for(let n of e.nested){let e=new r.Matrix4().multiplyMatrices(t,n.matrix);n.proto?this.placePrototype(n.proto,e):this.placeInstancer(n.instancer,e)}}placeInstancer(e,t){let{protos:n,protoIndices:i,positions:a,orientations:o,scales:s,hidden:c,salt:l}=e,u=e.rate,d=u<1?Math.floor(i.length*u):1/0,f=new r.Matrix4,p=new r.Matrix4,m=new r.Quaternion,h=new r.Vector3,g=new r.Vector3;for(let e=0;e<i.length;e++){if(this.ir.instanceCount>=this.maxPlacements){this.ir.skippedInstances+=i.length-e;return}let r=n[i[e]];!r||c?.has(e)||u<1&&(d<=0||tI(e,l)>=u)||(d--,h.set(a[e*3],a[e*3+1],a[e*3+2]),o?m.set(o[e*4],o[e*4+1],o[e*4+2],o[e*4+3]).normalize():m.identity(),s?g.set(s[e*3],s[e*3+1],s[e*3+2]):g.set(1,1,1),f.compose(h,m,g),this.placePrototype(r,p.multiplyMatrices(t,f)))}}async pointInstancer(e,t,n,r){let i=e.value(`protoIndices`);if(!i?.length)return;let a=this.dry?null:e.value(`positions`);if(!this.dry&&!a?.length)return;let o=[];for(let t of e.targets(`prototypes`)){let e=await this.stage.primAt(t);o.push(e?await this.instancerPrototype(e,r):null)}let s=e.value(`invisibleIds`),c=null;if(s?.length){let t=e.value(`ids`),n=new Map;if(t?.length)for(let e=0;e<t.length;e++)n.set(Number(t[e]),e);c=new Set(Array.from(s,e=>t?.length?n.get(Number(e)):Number(e)))}if(this.dry){let t=new Float64Array(o.length);for(let e=0;e<i.length;e++)c?.has(e)||t[i[e]]++;n.instancer({protos:o,histogram:t,path:e.path});return}let l=e.value(`orientations`),u=e.value(`scales`);n.instancer({protos:o,protoIndices:i,positions:a,salt:nI(e.path),rate:this.placementRates.get(e.path)??1,orientations:l?.length===i.length*4?l:null,scales:u?.length===i.length*3?u:null,hidden:c},t)}own(e){return e&&(this._handed.has(e)?e.slice():(this._handed.add(e),e))}shape(e,t,n,r){return{type:t,params:n,ctm:null,material:r,areaLight:null,reverseOrientation:!1,interior:null,name:e.path}}specId(e){if(!e)return 0;let t=this._specIds.get(e);return t||this._specIds.set(e,t=++this._nextSpecId),t}geometryKey(e,t){let n=t=>this.specId(e.property(t)),r=t??`st`;return[n(`points`),n(`faceVertexIndices`),n(`faceVertexCounts`),n(`holeIndices`),n(`primvars:normals`),n(`normals`),r,n(`primvars:${r}`),n(`primvars:${r}:indices`),e.value(`orientation`)??``].join(`|`)}countGeometry(e,t,n){this.cost.counted.has(e)||(this.cost.counted.add(e),this.cost[t]+=n)}meshParams(e,t,n){let r=e.value(`points`),i=e.value(`faceVertexCounts`),a=e.value(`faceVertexIndices`);if(!r?.length||!i?.length||!a?.length)return null;let o=new Int32Array(i.length);for(let e=1;e<i.length;e++)o[e]=o[e-1]+i[e-1];if(!t){let n=new Set(e.value(`holeIndices`)??[]);t=[];for(let e=0;e<i.length;e++)n.has(e)||t.push(e)}let s=YF(e,`normals`)??(e.value(`normals`)?.length?{values:e.value(`normals`),interpolation:e.propertyMeta(`normals`,`interpolation`)??`vertex`,indices:null}:null),c=YF(e,n)??(n===`st`?YF(e,`uv`)??YF(e,`st0`)??YF(e,`UVMap`):null),l=QF({points:r,counts:i,offsets:o,fvi:a,leftHanded:e.value(`orientation`)===`leftHanded`,normals:s,uv:c},t);if(l.index.length===0)return null;let u={P:TI(this.own(l.P),`point3`),indices:TI(l.index,`integer`)};return l.N&&(u.N=TI(this.own(l.N),`normal`)),l.uv&&(u.uv=TI(this.own(l.uv),`point2`)),u}async mesh(e,t,n,r){let i=[];for(let t of e.childNames()){let n=await this.stage.child(e,t);if(n?.typeName!==`GeomSubset`||(n.value(`elementType`)??`face`)!==`face`)continue;let r=n.value(`familyName`),a=this.bindingOf(n);a&&(!r||r===`materialBind`)&&i.push({subset:n,target:a})}if(this.dry){let r=e.value(`faceVertexCounts`);if(!e.property(`points`)||!r?.length)return;let i=new Set(e.value(`holeIndices`)??[]),a=0;for(let e=0;e<r.length;e++)r[e]>2&&!i.has(e)&&(a+=r[e]-2);this.countGeometry(this.geometryKey(e,null),`mesh`,a),n.shape(null,t);return}if(i.length===0){let{material:i,uvSet:a}=await this.materialFor(r,e),o=this.geometryKey(e,a),s=this._geometries.get(o);if(s){let r=this.shape(e,`trianglemesh`,s.params,i);s.shapes.push(r),n.shape(r,t);return}let c=this.meshParams(e,null,a);if(!c)return;let l=this.shape(e,`trianglemesh`,c,i);this._geometries.set(o,{params:c,shapes:[l]}),n.shape(l,t);return}let a=e.value(`faceVertexCounts`);if(!a?.length)return;let o=new Set(e.value(`holeIndices`)??[]),s=[],c=new Set;for(let{subset:e,target:t}of i){let n=Array.from(e.value(`indices`)??[]).filter(e=>e<a.length&&!o.has(e)&&!c.has(e));for(let e of n)c.add(e);n.length&&s.push({faces:n,binding:t})}let l=[];for(let e=0;e<a.length;e++)!o.has(e)&&!c.has(e)&&l.push(e);l.length&&s.unshift({faces:l,binding:r});for(let r of s){let{material:i,uvSet:a}=await this.materialFor(r.binding,e),o=this.meshParams(e,r.faces,a);o&&n.shape(this.shape(e,`trianglemesh`,o,i),t)}}async curves(e,t,n,r){let i=e.value(`curveVertexCounts`);if(!i?.length||!e.property(`points`))return;let a=e.value(`type`)??`cubic`,o=e.value(`basis`)??`bezier`,s=e.value(`wrap`)??`nonperiodic`;if(this.dry){let r=0;for(let e=0;e<i.length;e++)r+=Math.max(1,Math.round(rI(i[e],a,o,s)*this.curveSteps)*OI);let c=`curves|${this.specId(e.property(`points`))}|${this.specId(e.property(`curveVertexCounts`))}`;this.cost.counted.has(c)||this.cost.curveSets.set(e.path,r*2),this.countGeometry(c,`curves`,r*2),n.shape(null,t);return}let c=e.property(`widths`)?`widths`:`primvars:widths`,l=e.property(`normals`)?`normals`:`primvars:normals`,u={points:e.value(`points`),counts:i,type:a,basis:o,wrap:s,widths:e.value(c)??null,widthMode:e.propertyMeta(c,`interpolation`)??null,normals:e.value(l)??null,normalMode:e.propertyMeta(l,`interpolation`)??`vertex`};u.widths?.length&&(u.widthMode??=u.widths.length===1?`constant`:`vertex`);let d=this.curveRates.get(e.path)??1;if(d<1&&(u=oI(u,d,nI(e.path))),!u)return;let f={P:TI(this.own(u.points),`point3`),counts:TI(this.own(u.counts),`integer`),type:EI(a),basis:EI(o),wrap:EI(s)};u.widths?.length&&(f.widths=TI(this.own(u.widths)),f.widthMode=EI(u.widthMode)),u.normals?.length&&(f.N=TI(this.own(u.normals),`normal`),f.normalMode=EI(u.normalMode));let{material:p}=await this.materialFor(r,e);n.shape(this.shape(e,`curves`,f,p),t)}shareGeometry(){for(let[e,{shapes:t}]of this._geometries)if(!(t.length<2))for(let n of t)n.shared=!0,n.geometryKey=e;this._geometries.clear()}async gprim(e,t,n,i){let a=e.value(`axis`)??`Z`,o=e.value(`radius`)??1,s=e.value(`height`)??2,c;switch(e.typeName){case`Sphere`:c=new r.SphereGeometry(o,48,24);break;case`Cube`:{let t=e.value(`size`)??2;c=new r.BoxGeometry(t,t,t);break}case`Cylinder`:c=new r.CylinderGeometry(o,o,s,48);break;case`Cone`:c=new r.ConeGeometry(o,s,48);break;case`Capsule`:c=new r.CapsuleGeometry(o,s,8,32);break;default:c=new r.PlaneGeometry(e.value(`width`)??2,e.value(`length`)??2)}let l=$F(c,e.typeName===`Plane`&&a===`Z`?`none`:a);if(c.dispose(),this.dry){this.countGeometry(`gprim|${e.path}`,`mesh`,l.index.length/3),n.shape(null,t);return}let u={P:TI(l.P,`point3`),indices:TI(l.index,`integer`)};l.N&&(u.N=TI(l.N,`normal`)),l.uv&&(u.uv=TI(l.uv,`point2`));let{material:d}=await this.materialFor(i,e);n.shape(this.shape(e,`trianglemesh`,u,d),t)}async materialFor(e,t){let n=e?await this.surface(e):null,r=n?.material??null,i=YF(t,`displayColor`);if(!r){let e=XF(i)??[.18,.18,.18];r=this.colored(null,e)}else if(n.perMesh){let i=XF(YF(t,n.perMesh.primvar));i?r=this.colored(r,i.map((e,t)=>Math.max(e,0)**(n.perMesh.exponent?.[t]??1))):this.warnOnce(`nodisplay`,`USD material "${e}" takes its colour from "${n.perMesh.primvar}", which a mesh lacks — its fallback used`)}let a=this._wrappers.get(r);return a||this._wrappers.set(r,a={type:`usd`,material:r}),{material:a,uvSet:n?.uvSet??`st`}}colored(e,t){let n=eI(t),i=`${e?.uuid??`plain`}|${n.join(`,`)}`,a=this._colored.get(i);return a||(a=e?TN(e):new r.MeshPhysicalMaterial({side:r.DoubleSide,roughness:.5,metalness:0}),a.color.setRGB(n[0],n[1],n[2]),e?.userData.diffuseTransmissionFromBase&&(a.diffuseTransmissionColor=a.color.clone()),this._colored.set(i,a)),a}async surface(e){if(this._surfaces.has(e))return this._surfaces.get(e);let t=this.buildSurface(e);return this._surfaces.set(e,t),t}async buildSurface(e){let t=await this.stage.primAt(e);if(!t)return this.warnOnce(`nomat:${e}`,`USD material "${e}" not found`),null;let n=await this.stage.connectionSource(t,`outputs:mtlx:surface`),r=gI[hI(n?.prim.value(`info:id`)??`ND_`)];if(r)return this[r](n.prim);for(let e of[`outputs:ri:surface`,`outputs:surface`,`outputs:glslfx:surface`]){let n=await this.stage.connectionSource(t,e),r=n?.prim.value(`info:id`);if(r===`PxrDisneyBsdf`)return this.disney(n.prim);if(r===`PxrSurface`)return this.pxrSurface(n.prim);if(r===`UsdPreviewSurface`)return this.previewSurface(n.prim)}return this.warnOnce(`nosurface:${e}`,`USD material "${e}" has no surface shader read here — shaded grey`),null}async term(e,t,n=0){let r=`inputs:${t}`,[i]=e.connections(r);if(i&&n<32){let e=i.lastIndexOf(`.`),t=await this.stage.primAt(i.slice(0,e)),r=i.slice(e+1);if(t){let e=r.startsWith(`inputs:`)?await this.term(t,r.slice(7),n+1):r.startsWith(`outputs:`)?await this.output(t,r.slice(8),n+1):null;if(e)return e}}let a=e.value(r);return a===void 0?null:{value:a}}async output(e,t,n){let r=e.value(`info:id`);switch(r){case`PxrColorCorrect`:{let t=await this.term(e,`inputRGB`,n+1),r=(await this.term(e,`gamma`,n+1))?.value;if(!t||!Array.isArray(r))return t;let i=r.map(e=>e>0?1/e:1);return Array.isArray(t.value)?{value:t.value.map((e,t)=>Math.max(e,0)**i[t])}:{...t,exponent:i}}case`PxrBlend`:return await this.term(e,`bottomRGB`,n+1)??this.term(e,`topRGB`,n+1);case`PxrPtexture`:case`HwPtexTexture_1`:return{primvar:`displayColor`};case`UsdUVTexture`:return this.texture(e,t,n);case`UsdPrimvarReader_float`:case`UsdPrimvarReader_float2`:case`UsdPrimvarReader_float3`:case`UsdPrimvarReader_float4`:case`UsdPrimvarReader_normal`:case`UsdPrimvarReader_point`:case`UsdPrimvarReader_vector`:{let t=(await this.term(e,`varname`,n+1))?.value;return t?{primvar:t}:await this.term(e,`fallback`,n+1)}case`UsdTransform2d`:{let t=await this.term(e,`in`,n+1);return t?.texture?{...t,transform:{scale:e.value(`inputs:scale`),translation:e.value(`inputs:translation`),rotation:e.value(`inputs:rotation`)}}:t}case void 0:{let[r]=e.connections(`outputs:${t}`);if(!r)return null;let i=r.lastIndexOf(`.`),a=await this.stage.primAt(r.slice(0,i)),o=r.slice(i+1);return a?o.startsWith(`outputs:`)?this.output(a,o.slice(8),n+1):this.term(a,o.slice(7),n+1):null}default:return r?.startsWith(`ND_`)?this.mtlxOutput(e,r,t,n):(this.warnOnce(`shader:${r}`,`USD shader "${r}" is not read — its input left at its default`),null)}}async texture(e,t,n){let r=e.assetPath(`inputs:file`),i=e.value(`inputs:fallback`);if(!r?.path)return r?.asset&&this.warnOnce(`tex:${r.asset}`,`USD texture "${r.asset}" not found`),i?{value:i}:null;if(fI.test(r.path))return{primvar:`displayColor`};if(/<udim>/i.test(r.asset))return this.warnOnce(`udim`,`USD UDIM textures are not supported — skipped`),null;let a=await this.term(e,`st`,n+1);return{texture:{path:r.path,uvSet:a?.primvar??`st`,wrapS:e.value(`inputs:wrapS`)??`repeat`,wrapT:e.value(`inputs:wrapT`)??`repeat`,colorSpace:e.value(`inputs:sourceColorSpace`)??`auto`,scale:e.value(`inputs:scale`)??null},channel:t}}async image(e,t){let n=`${e.path}|${t}|${e.wrapS}|${e.wrapT}`;return this._images.has(n)||this._images.set(n,(async()=>{let n=await this.resolveImage(e.path);if(!n)return this.warnOnce(`img:${e.path}`,`USD texture "${e.path}" could not be read`),null;let i=n.clone();return i.userData.usdPath=e.path,i.colorSpace=t?r.SRGBColorSpace:r.NoColorSpace,i.wrapS=pI[e.wrapS]??r.RepeatWrapping,i.wrapT=pI[e.wrapT]??r.RepeatWrapping,i.needsUpdate=!0,i})()),this._images.get(n)}async applyColor(e,t,n,r,i){if(n){if(Array.isArray(n.value))e[t].setRGB(n.value[0],n.value[1],n.value[2]);else if(typeof n.value==`number`)e[t].setRGB(n.value,n.value,n.value);else if(n.primvar&&t===`color`)r.perMesh={primvar:n.primvar,exponent:n.exponent??null};else if(n.texture&&i){let a=await this.image(n.texture,n.texture.colorSpace!==`raw`);if(a){e[i]=this.transformTexture(a,n.transform);let o=n.texture.scale;e[t].setRGB(o?.[0]??1,o?.[1]??1,o?.[2]??1),r.uvSet=n.texture.uvSet}}}}async applyScalar(e,t,n,r,i=null,a=null){if(n){if(typeof n.value==`number`)e[t]=n.value;else if(n.texture&&i){if(n.channel!==a&&!n.mono){this.warnOnce(`chan:${i}:${n.channel}`,`USD ${t} from a texture's "${n.channel}" channel is not supported (the engine reads "${a}") — constant used`);return}let o=await this.image(n.texture,!1);o&&(e[i]=this.transformTexture(o,n.transform),e[t]=n.texture.scale?.[0]??1,r.uvSet=n.texture.uvSet)}}}transformTexture(e,t){if(!t)return e;let n=e.clone();if(t.matrix){let[e,r,i,a,o,s]=t.matrix;return n.matrixAutoUpdate=!1,n.matrix.set(e,r,i,a,o,s,0,0,1),n}return t.scale&&n.repeat.set(t.scale[0],t.scale[1]),t.translation&&n.offset.set(t.translation[0],t.translation[1]),t.rotation&&(n.rotation=t.rotation*sI),n}async disney(e){let t=t=>this.term(e,t),n=async(e,n)=>{let r=await t(e);return typeof r?.value==`number`?r.value:n},i=new r.MeshPhysicalMaterial({side:r.DoubleSide}),a={material:i,perMesh:null,uvSet:`st`};i.color.setRGB(.2,.5,.8),await this.applyColor(i,`color`,await t(`baseColor`),a,`map`),i.metalness=await n(`metallic`,0),i.roughness=await n(`roughness`,.5),i.ior=await n(`ior`,1.5);let o=a.perMesh?null:i.color.clone(),s=e=>{let t=.3*e.r+.6*e.g+.1*e.b;return t>0?e.clone().multiplyScalar(1/t):new r.Color(1,1,1)},c=await n(`specularTint`,0);c>0&&o&&i.specularColor.lerp(s(o),c);let l=await n(`sheen`,0);if(l>0){let e=await n(`sheenTint`,.5);i.sheen=Math.min(1,l),i.sheenColor.set(1,1,1),o&&i.sheenColor.lerp(s(o),e),i.sheenRoughness=.5}let u=await n(`clearcoat`,0);u>0&&(i.clearcoat=.25*u,i.clearcoatRoughness=Math.sqrt(.1+-.099*await n(`clearcoatGloss`,1)));let d=await n(`specTrans`,0);if(d>0){i.transmission=d;let e=(await t(`transColor`))?.value,r=await n(`transDistance`,0);Array.isArray(e)&&r>0&&(i.attenuationColor.setRGB(e[0],e[1],e[2]),i.attenuationDistance=r)}let f=await n(`isThin`,0),p=await n(`diffTrans`,0);f&&p>0&&(i.diffuseTransmission=Math.min(1,p/2),i.diffuseTransmissionColor=i.color.clone(),i.userData.diffuseTransmissionFromBase=!0);let m=await n(`opacity`,1);return m<1&&(i.opacity=m,i.transparent=!0),await this.applyColor(i,`emissive`,await t(`emitColor`),a,`emissiveMap`),a}async pxrSurface(e){let t=t=>this.term(e,t),n=async(e,n)=>{let r=await t(e);return typeof r?.value==`number`?r.value:n},i=new r.MeshPhysicalMaterial({side:r.DoubleSide}),a={material:i,perMesh:null,uvSet:`st`};await this.applyColor(i,`color`,await t(`diffuseColor`),a,`map`),i.color.multiplyScalar(await n(`diffuseGain`,1)),i.roughness=await n(`specularRoughness`,.2),i.metalness=0;let o=await n(`refractionGain`,0);if(o>0)i.transmission=Math.min(1,o),i.ior=await n(`glassIor`,1.5),i.roughness=await n(`glassRoughness`,.1),i.color.setRGB(1,1,1);else{let e=await n(`diffuseTransmitGain`,0);if(e>0){let n=(await t(`diffuseTransmitColor`))?.value;i.diffuseTransmission=Math.min(1,e),i.diffuseTransmissionColor=Array.isArray(n)?new r.Color().setRGB(n[0],n[1],n[2]):new r.Color(1,1,1)}}let s=await n(`presence`,1);return s<1&&(i.opacity=s,i.transparent=!0),a}async previewSurface(e){let t=t=>this.term(e,t),n=new r.MeshPhysicalMaterial({side:r.DoubleSide,roughness:.5,metalness:0}),i={material:n,perMesh:null,uvSet:`st`};if(n.color.setRGB(.18,.18,.18),await this.applyColor(n,`color`,await t(`diffuseColor`),i,`map`),await this.applyColor(n,`emissive`,await t(`emissiveColor`),i,`emissiveMap`),(n.emissiveMap||n.emissive.r+n.emissive.g+n.emissive.b>0)&&(n.emissiveIntensity=1),await this.applyScalar(n,`roughness`,await t(`roughness`),i,`roughnessMap`,`g`),await this.applyScalar(n,`clearcoat`,await t(`clearcoat`),i),await this.applyScalar(n,`clearcoatRoughness`,await t(`clearcoatRoughness`),i),await this.applyScalar(n,`ior`,await t(`ior`),i),(await t(`useSpecularWorkflow`))?.value===1){n.metalness=0;let e=(await t(`specularColor`))?.value;Array.isArray(e)&&n.specularColor.setRGB(e[0],e[1],e[2])}else await this.applyScalar(n,`metalness`,await t(`metallic`),i,`metalnessMap`,`b`);let a=await t(`opacity`),o=(await t(`opacityThreshold`))?.value??0;typeof a?.value==`number`&&a.value<1?o>0?n.alphaTest=o:n.transmission=1-a.value:a?.texture&&(a.texture.path===n.map?.userData.usdPath&&a.channel===`a`?(n.transparent=!0,o>0&&(n.alphaTest=o)):this.warnOnce(`opacitymap`,`USD opacity from a texture other than the colour map's alpha is not supported`));let s=await t(`normal`);if(s?.texture){let e=await this.image(s.texture,!1);e&&(n.normalMap=e,i.uvSet=s.texture.uvSet)}return i}async mtlxOutput(e,t,n,r){let i=hI(t),a=t=>this.term(e,t,r+1),o=async(e,t)=>{let n=(await a(e))?.value;return n===void 0?t:n};switch(i){case`image`:case`tiledimage`:return this.mtlxImage(e,t,i,r);case`texcoord`:return await o(`index`,0)>0&&this.warnOnce(`mtlx:texcoord`,`MaterialX texture coordinates past the first set are read as the first`),{uv:{set:`st`,m:vI}};case`geompropvalue`:{let e=await o(`geomprop`,null);return e?/vector2/.test(t)?{uv:{set:e,m:vI}}:{primvar:e}:a(`default`)}case`constant`:return a(`value`);case`dot`:return a(`in`);case`convert`:return this.mtlxConvert(await a(`in`),t);case`extract`:return this.mtlxChannel(await a(`in`),await o(`index`,0));case`separate2`:case`separate3`:case`separate4`:return this.mtlxChannel(await a(`in`),{outx:0,outy:1,outz:2,outw:3,outr:0,outg:1,outb:2,outa:3}[n]??0);case`combine2`:case`combine3`:case`combine4`:{let e=await Promise.all([`in1`,`in2`,`in3`,`in4`].slice(0,Number(i.slice(-1))).map(a));return e.every(e=>yI(e?.value))?{value:e.map(e=>e.value)}:e.find(e=>e?.texture)??null}case`mix`:{let[e,t,n]=await Promise.all([a(`fg`),a(`bg`),a(`mix`)]);if(bI(e?.value)&&bI(t?.value)&&yI(n?.value))return{value:WF(t.value,e.value,(e,t)=>e+(t-e)*n.value)};this.warnOnce(`mtlx:mix`,`MaterialX mixes of a texture are read as their larger part`);let r=!yI(n?.value)||n.value>=.5;return(r?e:t)??(r?t:e)}case`multiply`:case`divide`:case`add`:case`subtract`:case`min`:case`max`:case`power`:case`modulo`:return this.mtlxArithmetic(i,await a(`in1`),await a(`in2`));case`invert`:{let e=await a(`in`),t=await o(`amount`,1);return bI(e?.value)?{value:WF(t,e.value,(e,t)=>e-t)}:e}case`clamp`:{let e=await a(`in`);if(!bI(e?.value))return e;let[t,n]=[await o(`low`,0),await o(`high`,1)];return{value:WF(WF(e.value,t,Math.max),n,Math.min)}}case`hsvadjust`:return this.mtlxHsv(await a(`in`),await o(`amount`,[0,1,1]));case`rotate2d`:case`rotate3d`:{let e=await a(`in`),t=await o(`amount`,0),n=i===`rotate3d`?await o(`axis`,[0,1,0]):[0,0,1];return!e?.uv||!t?e:Math.abs(n[0])>1e-6||Math.abs(n[1])>1e-6?(this.warnOnce(`mtlx:rotate`,`MaterialX texture coordinates turned about an axis other than z are left unturned`),e):{uv:{...e.uv,m:GF(e.uv.m,Math.sign(n[2])*t)}}}case`place2d`:{let e=await a(`texcoord`);if(!e?.uv)return e;let[t,n,r,i]=[await o(`pivot`,[0,0]),await o(`scale`,[1,1]),await o(`rotate`,0),await o(`offset`,[0,0])],s=await o(`operationorder`,0)!==0,c=wI(e.uv.m,[-t[0],-t[1]]),l=n.map(e=>e?1/e:1);return c=s?CI(GF(wI(c,[-i[0],-i[1]]),r),l):wI(GF(CI(c,l),r),[-i[0],-i[1]]),{uv:{...e.uv,m:wI(c,t)}}}case`normalmap`:{let e=await a(`in`);return e?.texture?{...e,normalScale:await o(`scale`,1)}:null}case`heighttonormal`:{let e=await a(`in`);return e?.texture?{...e,bump:await o(`scale`,1)}:null}case`artistic_ior`:return{artistic:{reflectivity:await a(`reflectivity`),edge:await a(`edge_color`)}};case`normal`:case`tangent`:case`bitangent`:case`position`:case`viewdirection`:return null}return this.warnOnce(`mtlx:${i}`,`MaterialX node "${i}" is not read — its input left at its default`),null}async mtlxImage(e,t,n,r){let i=e.assetPath(`inputs:file`);if(!i?.path)return i?.asset&&this.warnOnce(`tex:${i.asset}`,`USD texture "${i.asset}" not found`),this.term(e,`default`,r+1);if(/<udim>/i.test(i.asset))return this.warnOnce(`udim`,`USD UDIM textures are not supported — skipped`),null;let a=await this.term(e,`texcoord`,r+1),o=a?.uv?.m??vI;if(n===`tiledimage`){let t=e.value(`inputs:uvtiling`)??[1,1],n=e.value(`inputs:uvoffset`)??[0,0];o=wI(CI(o,t),[-n[0],-n[1]])}let s=e.propertyMeta(`inputs:file`,`colorSpace`)??e.value(`inputs:file:colorSpace`),c=/_float$/.test(t);return{texture:{path:i.path,uvSet:a?.uv?.set??a?.primvar??`st`,wrapS:_I[e.value(`inputs:uaddressmode`)]??`repeat`,wrapT:_I[e.value(`inputs:vaddressmode`)]??`repeat`,colorSpace:s?/srgb/i.test(s)?`sRGB`:`raw`:`auto`,scale:null},channel:c?`r`:`rgb`,mono:c,transform:o.every((e,t)=>Math.abs(e-vI[t])<1e-9)?null:{matrix:o}}}mtlxConvert(e,t){if(!bI(e?.value))return e;let n={float:1,color3:3,vector3:3,color4:4,vector4:4,vector2:2}[t.slice(t.lastIndexOf(`_`)+1)]??3,r=e.value;return n===1?{value:yI(r)?r:r[0]}:yI(r)?{value:Array(n).fill(r)}:{value:Array.from({length:n},(e,t)=>r[t]??+(t===3))}}mtlxChannel(e,t){return bI(e?.value)?{value:yI(e.value)?e.value:e.value[t]??0}:e?.texture?{...e,channel:`rgba`[t]??`r`,mono:!1}:e}mtlxArithmetic(e,t,n){let r={multiply:(e,t)=>e*t,divide:(e,t)=>t?e/t:0,add:(e,t)=>e+t,subtract:(e,t)=>e-t,min:Math.min,max:Math.max,power:(e,t)=>Math.max(e,0)**t,modulo:(e,t)=>t?e-t*Math.floor(e/t):0};if(bI(t?.value)&&bI(n?.value))return{value:WF(t.value,n.value,r[e])};let i=t?.uv??n?.uv,a=t?.uv?n?.value:t?.value;if(i&&bI(a)&&(e===`multiply`||e===`add`||t?.uv&&(e===`divide`||e===`subtract`))){let t=yI(a)?[a,a]:a;return e===`multiply`?{uv:{...i,m:CI(i.m,t)}}:e===`divide`?{uv:{...i,m:CI(i.m,t.map(e=>e?1/e:1))}}:{uv:{...i,m:wI(i.m,e===`add`?t:t.map(e=>-e))}}}let o=t?.texture?t:n?.texture?n:null,s=t?.texture?n?.value:t?.value;if(o&&bI(s)&&(e===`multiply`||t?.texture&&e===`divide`)){let t=e===`divide`?xI(s,e=>e?1/e:1):s,n=WF(o.texture.scale??[1,1,1],t,(e,t)=>e*t);return{...o,texture:{...o.texture,scale:yI(n)?[n,n,n]:n}}}return o&&this.warnOnce(`mtlx:${e}`,`MaterialX ${e} of a texture is read as the texture alone`),o??t??n}mtlxHsv(e,t){if(!Array.isArray(e?.value))return e?.texture&&(t[0]||t[1]!==1||t[2]!==1)&&this.warnOnce(`mtlx:hsv`,`MaterialX hue, saturation and value changes to a texture are not applied`),e;let n=new r.Color().setRGB(e.value[0],e.value[1],e.value[2]),i=n.getHSL({});return n.setHSL((i.h+t[0]+1)%1,Math.min(1,i.s*t[1]),i.l),{value:[n.r*t[2],n.g*t[2],n.b*t[2]]}}async mtlxNormal(e,t,n){if(!t?.texture)return;let r=this.transformTexture(await this.image(t.texture,!1),t.transform);r&&(t.bump===void 0?(e.normalMap=r,e.normalScale.set(t.normalScale??1,t.normalScale??1)):(e.bumpMap=r,e.bumpScale=t.bump),n.uvSet=t.texture.uvSet)}mtlxOpacity(e,t){bI(t?.value)&&SI(t.value)<1?(e.opacity=SI(t.value),e.transparent=!0):t?.texture&&(t.texture.path===e.map?.userData.usdPath&&t.channel===`a`?e.transparent=!0:this.warnOnce(`opacitymap`,`USD opacity from a texture other than the colour map's alpha is not supported`))}async mtlxWeighted(e,t,n,r,i,a){await this.applyColor(e,t,n,i,a),yI(r)&&e[t].multiplyScalar(r)}mtlxSurfaceOf(e){return{material:e,perMesh:null,uvSet:`st`}}mtlxDiffuseRoughness(e){return e?.texture&&this.warnOnce(`mtlx:diffuseroughness`,`MaterialX diffuse roughness from a texture is not read`),yI(e?.value)?e.value:0}async openPbrSurface(e){let t=t=>this.term(e,t),n=async(e,n)=>{let r=(await t(e))?.value;return yI(r)?r:n},i=new r.MeshPhysicalMaterial({side:r.DoubleSide}),a=this.mtlxSurfaceOf(i);i.color.setRGB(.8,.8,.8),await this.mtlxWeighted(i,`color`,await t(`base_color`),await n(`base_weight`,1),a,`map`),i.metalness=0,await this.applyScalar(i,`metalness`,await t(`base_metalness`),a,`metalnessMap`,`b`),i.roughness=.3,await this.applyScalar(i,`roughness`,await t(`specular_roughness`),a,`roughnessMap`,`g`),i.specularIntensity=Math.min(1,await n(`specular_weight`,1));let o=(await t(`specular_color`))?.value;Array.isArray(o)&&i.specularColor.setRGB(o[0],o[1],o[2]),i.ior=await n(`specular_ior`,1.5),i.anisotropy=await n(`specular_roughness_anisotropy`,0),i.diffuseRoughness=this.mtlxDiffuseRoughness(await t(`base_diffuse_roughness`));let s=await n(`transmission_weight`,0);if(s>0){i.transmission=s;let e=(await t(`transmission_color`))?.value,a=await n(`transmission_depth`,0);Array.isArray(e)&&a>0?(i.attenuationColor.setRGB(e[0],e[1],e[2]),i.attenuationDistance=a):Array.isArray(e)&&i.color.lerp(new r.Color().setRGB(e[0],e[1],e[2]),s);let o=await n(`transmission_dispersion_abbe_number`,20),c=await n(`transmission_dispersion_scale`,0);c>0&&o>0&&(i.dispersion=c*20/o)}let c=await n(`subsurface_weight`,0);if(c>0){let e=(await t(`subsurface_color`))?.value,a=await n(`subsurface_radius`,1),o=(await t(`subsurface_radius_scale`))?.value;i.subsurface=c,i.subsurfaceColor=Array.isArray(e)?new r.Color().setRGB(e[0],e[1],e[2]):i.color.clone(),i.subsurfaceRadius=Array.isArray(o)?[...o]:[1,1,1],i.subsurfaceRadiusScale=a,i.subsurfaceAnisotropy=await n(`subsurface_scatter_anisotropy`,0)}i.clearcoat=await n(`coat_weight`,0),i.clearcoatRoughness=await n(`coat_roughness`,0);let l=await n(`fuzz_weight`,0);if(l>0){let e=(await t(`fuzz_color`))?.value??[1,1,1];i.sheen=Math.min(1,l),i.sheenColor.setRGB(e[0],e[1],e[2]),i.sheenRoughness=await n(`fuzz_roughness`,.5)}let u=await n(`thin_film_weight`,0);if(u>0){let e=await n(`thin_film_thickness`,.5)*1e3;i.iridescence=Math.min(1,u),i.iridescenceIOR=await n(`thin_film_ior`,1.4),i.iridescenceThicknessRange=[e,e]}let d=await n(`emission_luminance`,0);return d>0&&(i.emissive.setRGB(1,1,1),await this.applyColor(i,`emissive`,await t(`emission_color`),a,`emissiveMap`),i.emissiveIntensity=d),this.mtlxOpacity(i,await t(`geometry_opacity`)),await this.mtlxNormal(i,await t(`geometry_normal`),a),a}async standardSurface(e){let t=t=>this.term(e,t),n=async(e,n)=>{let r=(await t(e))?.value;return yI(r)?r:n},i=new r.MeshPhysicalMaterial({side:r.DoubleSide}),a=this.mtlxSurfaceOf(i);i.color.setRGB(.8,.8,.8),await this.mtlxWeighted(i,`color`,await t(`base_color`),await n(`base`,1),a,`map`),i.metalness=0,await this.applyScalar(i,`metalness`,await t(`metalness`),a,`metalnessMap`,`b`),i.roughness=.2,await this.applyScalar(i,`roughness`,await t(`specular_roughness`),a,`roughnessMap`,`g`),i.specularIntensity=Math.min(1,await n(`specular`,1));let o=(await t(`specular_color`))?.value;Array.isArray(o)&&i.specularColor.setRGB(o[0],o[1],o[2]),i.ior=await n(`specular_IOR`,1.5),i.anisotropy=await n(`specular_anisotropy`,0),i.anisotropyRotation=await n(`specular_rotation`,0)*Math.PI*2,i.diffuseRoughness=this.mtlxDiffuseRoughness(await t(`diffuse_roughness`));let s=await n(`transmission`,0);if(s>0){i.transmission=s;let e=(await t(`transmission_color`))?.value,a=await n(`transmission_depth`,0);Array.isArray(e)&&a>0?(i.attenuationColor.setRGB(e[0],e[1],e[2]),i.attenuationDistance=a):Array.isArray(e)&&i.color.lerp(new r.Color().setRGB(e[0],e[1],e[2]),s);let o=await n(`transmission_dispersion`,0);o>0&&(i.dispersion=20/o)}let c=await n(`subsurface`,0);if(c>0){let e=(await t(`subsurface_color`))?.value,a=(await t(`subsurface_radius`))?.value;i.subsurface=c,i.subsurfaceColor=Array.isArray(e)?new r.Color().setRGB(e[0],e[1],e[2]):i.color.clone(),i.subsurfaceRadius=Array.isArray(a)?[...a]:[1,1,1],i.subsurfaceRadiusScale=await n(`subsurface_scale`,1),i.subsurfaceAnisotropy=await n(`subsurface_anisotropy`,0)}let l=await n(`sheen`,0);if(l>0){let e=(await t(`sheen_color`))?.value??[1,1,1];i.sheen=Math.min(1,l),i.sheenColor.setRGB(e[0],e[1],e[2]),i.sheenRoughness=await n(`sheen_roughness`,.3)}i.clearcoat=await n(`coat`,0),i.clearcoatRoughness=await n(`coat_roughness`,.1);let u=await n(`thin_film_thickness`,0);u>0&&(i.iridescence=1,i.iridescenceIOR=await n(`thin_film_IOR`,1.5),i.iridescenceThicknessRange=[u,u]);let d=await n(`emission`,0);return d>0&&(i.emissive.setRGB(1,1,1),await this.applyColor(i,`emissive`,await t(`emission_color`),a,`emissiveMap`),i.emissiveIntensity=d),this.mtlxOpacity(i,await t(`opacity`)),await this.mtlxNormal(i,await t(`normal`),a),a}async gltfPbrSurface(e){let t=t=>this.term(e,t),n=async(e,n)=>{let r=(await t(e))?.value;return yI(r)?r:n},i=new r.MeshPhysicalMaterial({side:r.DoubleSide}),a=this.mtlxSurfaceOf(i);await this.applyColor(i,`color`,await t(`base_color`),a,`map`),i.metalness=1,await this.applyScalar(i,`metalness`,await t(`metallic`),a,`metalnessMap`,`b`),i.roughness=1,await this.applyScalar(i,`roughness`,await t(`roughness`),a,`roughnessMap`,`g`),i.ior=await n(`ior`,1.5),i.specularIntensity=await n(`specular`,1);let o=(await t(`specular_color`))?.value;Array.isArray(o)&&i.specularColor.setRGB(o[0],o[1],o[2]),i.transmission=await n(`transmission`,0),i.thickness=await n(`thickness`,0);let s=(await t(`attenuation_color`))?.value;Array.isArray(s)&&i.attenuationColor.setRGB(s[0],s[1],s[2]);let c=await n(`attenuation_distance`,0);c>0&&(i.attenuationDistance=c),i.dispersion=await n(`dispersion`,0),i.clearcoat=await n(`clearcoat`,0),i.clearcoatRoughness=await n(`clearcoat_roughness`,0);let l=(await t(`sheen_color`))?.value;Array.isArray(l)&&SI(l)>0&&(i.sheen=1,i.sheenColor.setRGB(l[0],l[1],l[2]),i.sheenRoughness=await n(`sheen_roughness`,0));let u=await n(`iridescence`,0);if(u>0){let e=await n(`iridescence_thickness`,100);i.iridescence=u,i.iridescenceIOR=await n(`iridescence_ior`,1.3),i.iridescenceThicknessRange=[e,e]}await this.applyColor(i,`emissive`,await t(`emissive`),a,`emissiveMap`),i.emissiveIntensity=await n(`emissive_strength`,1);let d=await n(`alpha_mode`,0);return d>0&&(this.mtlxOpacity(i,await t(`alpha`)),d===1&&(i.alphaTest=await n(`alpha_cutoff`,.5))),await this.mtlxNormal(i,await t(`normal`),a),a}async bsdfSurface(e){let t=[],n=[];await this.mtlxLobes(e,`inputs:bsdf`,1,t,0),await this.mtlxEmission(e,`inputs:edf`,1,n,0);let i=new r.MeshPhysicalMaterial({side:r.DoubleSide}),a=this.mtlxSurfaceOf(i),o=e=>t.filter(t=>e.includes(t.kind)).reduce((e,t)=>e+t.w,0),s=o([`diffuse`,`conductor`,`transmission`]);if(s>0){let e=t.filter(e=>[`diffuse`,`conductor`,`transmission`].includes(e.kind)&&e.w>0),n=e.filter(e=>e.color?.texture).sort((e,t)=>t.w-e.w)[0],r=[0,0,0];for(let t of e){let e=bI(t.color?.value)?t.color.value:t.color?.texture?t.color.texture.scale??[1,1,1]:[.8,.8,.8];for(let n=0;n<3;n++)r[n]+=(yI(e)?e:e[n])*t.w/s}n&&n.w/s>=.5?(await this.applyColor(i,`color`,n.color,a,`map`),e.some(e=>e!==n&&e.w>0)&&this.warnOnce(`mtlx:lobecolor`,`MaterialX lobes of different colours over a texture are read as the texture`)):i.color.setRGB(r[0],r[1],r[2]),i.metalness=o([`conductor`])/s,i.transmission=o([`transmission`])/s;let c=t.filter(e=>e.kind===`diffuse`&&e.w>0),l=o([`diffuse`]);l>0&&(i.diffuseRoughness=c.reduce((e,t)=>e+t.roughness*t.w,0)/l)}else i.color.setRGB(0,0,0);let c=t.filter(e=>[`conductor`,`transmission`,`reflection`].includes(e.kind)&&e.w>0),l=c.reduce((e,t)=>e+t.w,0);i.roughness=l>0?c.reduce((e,t)=>e+t.roughness*t.w,0)/l:1;let u=t.filter(e=>[`transmission`,`reflection`].includes(e.kind)&&e.w>0);i.ior=u.length?u.reduce((e,t)=>e+t.ior*t.w,0)/u.reduce((e,t)=>e+t.w,0):1.5;let d=t.filter(e=>e.kind===`reflection`&&e.w>0);if(d.length){let e=d.find(e=>bI(e.tint))?.tint;Array.isArray(e)&&i.specularColor.setRGB(e[0],e[1],e[2]),i.specularIntensity=Math.min(1,o([`reflection`]))}else i.transmission===0&&(i.specularIntensity=0);let f=t.find(e=>e.kind===`sheen`);f&&(i.sheen=Math.min(1,o([`sheen`])),Array.isArray(f.color)&&i.sheenColor.setRGB(f.color[0],f.color[1],f.color[2]),i.sheenRoughness=f.roughness);let p=t.find(e=>e.kind===`subsurface`);p&&s+p.w>0&&(i.subsurface=Math.min(1,o([`subsurface`])/(s+o([`subsurface`]))),i.subsurfaceColor=Array.isArray(p.color)?new r.Color().setRGB(p.color[0],p.color[1],p.color[2]):i.color.clone(),i.subsurfaceRadius=Array.isArray(p.radius)?[...p.radius]:[1,1,1],i.subsurfaceAnisotropy=p.anisotropy);let m=t.find(e=>e.kind===`translucent`);if(m){let e=o([`translucent`])/(o([`diffuse`])+o([`translucent`]));i.diffuseTransmission=Math.min(1,e),i.diffuseTransmissionColor=Array.isArray(m.color)?new r.Color().setRGB(m.color[0],m.color[1],m.color[2]):new r.Color(1,1,1)}if(n.length){let e=n.find(e=>e.color?.texture);if(e)i.emissive.setRGB(1,1,1),await this.applyColor(i,`emissive`,e.color,a,`emissiveMap`),i.emissiveIntensity=e.w;else{let e=[0,0,0];for(let t of n){let n=bI(t.color?.value)?t.color.value:[1,1,1];for(let r=0;r<3;r++)e[r]+=(yI(n)?n:n[r])*t.w}let t=Math.max(...e);t>0&&(i.emissive.setRGB(e[0]/t,e[1]/t,e[2]/t),i.emissiveIntensity=t)}}return await this.mtlxNormal(i,t.find(e=>e.normal?.texture)?.normal,a),this.mtlxOpacity(i,await this.term(e,`opacity`)),a}async mtlxLobes(e,t,n,r,i){let a=i<32?await this.stage.connectionSource(e,t):null,o=a?.prim.value(`info:id`);if(!o||n<=0)return;let s=a.prim,c=e=>this.term(s,e,i+1),l=async(e,t)=>{let n=(await c(e))?.value;return yI(n)?n:Array.isArray(n)?SI(n):t},u=n*await l(`weight`,1);switch(hI(o)){case`oren_nayar_diffuse_bsdf`:r.push({kind:`diffuse`,w:u,color:await c(`color`),normal:await c(`normal`),roughness:this.mtlxDiffuseRoughness(await c(`roughness`))});return;case`burley_diffuse_bsdf`:r.push({kind:`diffuse`,w:u,color:await c(`color`),normal:await c(`normal`),roughness:0});return;case`conductor_bsdf`:{let e=await c(`ior`),t=e?.artistic?.reflectivity??null;t||={value:WF(bI(e?.value)?e.value:[.18,.42,1.37],(await c(`extinction`))?.value??[3.42,2.35,1.77],(e,t)=>((e-1)**2+t*t)/((e+1)**2+t*t))},r.push({kind:`conductor`,w:u,color:t,roughness:await l(`roughness`,.2),normal:await c(`normal`)});return}case`dielectric_bsdf`:case`generalized_schlick_bsdf`:{let e=(await c(`scatter_mode`))?.value??`R`,t=await l(`roughness`,.05),n=await c(`normal`);if(hI(o)===`generalized_schlick_bsdf`){let i=(await c(`color0`))?.value??[1,1,1];SI(i)>.2&&e===`R`?r.push({kind:`conductor`,w:u,color:{value:i},roughness:t,normal:n}):r.push({kind:e===`R`?`reflection`:`transmission`,w:u,tint:[1,1,1],color:{value:[1,1,1]},ior:1.5,roughness:t,normal:n});return}let i=(await c(`tint`))?.value??[1,1,1],a=await l(`ior`,1.5);r.push({kind:e===`R`?`reflection`:`transmission`,w:u,tint:i,color:{value:i},ior:a,roughness:t,normal:n});return}case`sheen_bsdf`:r.push({kind:`sheen`,w:u,color:(await c(`color`))?.value??[1,1,1],roughness:await l(`roughness`,.3)});return;case`subsurface_bsdf`:r.push({kind:`subsurface`,w:u,color:(await c(`color`))?.value,radius:(await c(`radius`))?.value,anisotropy:await l(`anisotropy`,0)});return;case`translucent_bsdf`:r.push({kind:`translucent`,w:u,color:(await c(`color`))?.value});return;case`mix_bsdf`:{let e=(await c(`mix`))?.value;yI(e)||this.warnOnce(`mtlx:mixbsdf`,`MaterialX BSDF mixes driven by a texture are read as an even split`);let t=yI(e)?Math.min(1,Math.max(0,e)):.5;await this.mtlxLobes(s,`inputs:fg`,n*t,r,i+1),await this.mtlxLobes(s,`inputs:bg`,n*(1-t),r,i+1);return}case`add_bsdf`:await this.mtlxLobes(s,`inputs:in1`,n,r,i+1),await this.mtlxLobes(s,`inputs:in2`,n,r,i+1);return;case`layer`:case`layer_bsdf`:await this.mtlxLobes(s,`inputs:top`,n,r,i+1),await this.mtlxLobes(s,`inputs:base`,n,r,i+1);return;case`multiply_bsdfC`:case`multiply_bsdfF`:{let e=(await c(`in2`))?.value,t=r.length;if(await this.mtlxLobes(s,`inputs:in1`,n*(yI(e)?e:1),r,i+1),Array.isArray(e))for(let n of r.slice(t))bI(n.color?.value)&&(n.color={value:WF(n.color.value,e,(e,t)=>e*t)});return}case`thin_film_bsdf`:return}this.warnOnce(`mtlx:${hI(o)}`,`MaterialX node "${hI(o)}" is not read — its lobe left out`)}async mtlxEmission(e,t,n,r,i){let a=i<32?await this.stage.connectionSource(e,t):null,o=a?.prim.value(`info:id`);if(!o||n<=0)return;let s=a.prim,c=e=>this.term(s,e,i+1);switch(hI(o)){case`uniform_edf`:case`conical_edf`:case`measured_edf`:r.push({w:n,color:await c(`color`)});return;case`add_edf`:await this.mtlxEmission(s,`inputs:in1`,n,r,i+1),await this.mtlxEmission(s,`inputs:in2`,n,r,i+1);return;case`mix_edf`:{let e=(await c(`mix`))?.value,t=yI(e)?e:.5;await this.mtlxEmission(s,`inputs:fg`,n*t,r,i+1),await this.mtlxEmission(s,`inputs:bg`,n*(1-t),r,i+1);return}case`multiply_edfC`:case`multiply_edfF`:{let e=(await c(`in2`))?.value;await this.mtlxEmission(s,`inputs:in1`,n*(bI(e)?SI(e):1),r,i+1);return}}this.warnOnce(`mtlx:${hI(o)}`,`MaterialX node "${hI(o)}" is not read — its emission left out`)}camera(e,t){let n=e.value(`horizontalAperture`)??20.955,i=e.value(`verticalAperture`)??15.2908,a=e.value(`focalLength`)??50,o=e.value(`clippingRange`),[s,c]=o??[1,1e6],l=e.value(`projection`)===`orthographic`?new r.OrthographicCamera(-n/20,n/20,i/20,-i/20,s,c):new r.PerspectiveCamera(2*Math.atan(i/(2*a))/sI,n/i,s,c);l.name=e.name,o&&s>0&&(l.userData.clipStart=s);let u=new r.Vector3;t.decompose(l.position,l.quaternion,u),l.updateMatrixWorld(!0),this.cameras.push(l)}light(e,t,n){let i=(t,n)=>e.value(`inputs:${t}`)??e.value(t)??n,a=i(`color`,[1,1,1]),o=i(`intensity`,t===`DistantLight`?5e4:1)*2**i(`exposure`,0);if(i(`enableColorTemperature`,!1)&&this.warnOnce(`temperature`,`USD light colour temperature is not applied`),e.propertyNames().some(e=>e.startsWith(`collection:lightLink`)||e.startsWith(`collection:shadowLink`))&&t!==`DomeLight`&&this.warnOnce(`linking`,`USD light linking is not supported — every light lights everything`),t===`DomeLight`){let t=e.assetPath(`inputs:texture:file`)??e.assetPath(`texture:file`),r=e.targets(`collection:lightLink:excludes`),i=this.stage.pseudoRoot.childNames().map(e=>`/${e}`);this.domes.push({name:e.name,file:t?.path??null,asset:t?.asset??null,intensity:o,matrix:n.clone(),color:a,lightsScene:!r.some(e=>i.includes(e))});return}let s=!!i(`normalize`,!1),c;if(t===`RectLight`||t===`DiskLight`){let e=t===`DiskLight`,n=i(`radius`,.5);c=new r.RectAreaLight(new r.Color,o,e?n*2:i(`width`,1),e?n*2:i(`height`,1)),c.userData.normalize=s,e&&(c.userData.shape=`disk`),s&&(c.intensity=Math.PI*o,c.userData.__radianceConverted=!0)}else if(t===`SphereLight`||t===`CylinderLight`){let e=i(`radius`,.5),n=i(`shaping:cone:angle`,180),a=t===`SphereLight`?4*Math.PI*e*e:2*Math.PI*e*i(`length`,1),l=Math.PI*o*(s?1:a);n<90?(c=new r.SpotLight(new r.Color,l),c.angle=n*sI,c.penumbra=Math.min(1,Math.max(0,i(`shaping:cone:softness`,0)))):c=new r.PointLight(new r.Color,l),c.decay=2,c.distance=0,!i(`treatAsPoint`,!1)&&e>0&&(c.userData.radius=e),c.userData.__candelaConverted=!0,t===`CylinderLight`&&this.warnOnce(`cylinder`,`USD cylinder lights are placed as point lights`)}else{let e=Math.max(i(`angle`,.53),0)*sI,t=Math.min(e/2,Math.PI),n=Math.sin(t)**2,a=t===0?1:t<=Math.PI/2?Math.PI*n:Math.PI*(2-n);c=new r.DirectionalLight(new r.Color,o*(s?1:a)),c.userData.angle=e,c.userData.__luxConverted=!0}let l=Math.max(a[0],a[1],a[2]);!(l>0)||!(o>0)||(c.color.setRGB(a[0]/l,a[1]/l,a[2]/l),c.intensity*=l,c.name=e.name,n.decompose(c.position,c.quaternion,c.scale),c.target&&(c.target.position.set(0,0,-1),c.add(c.target)),this.lights.push(c))}pickDome(){let e=this.domes.find(e=>e.lightsScene&&e.file)??null;if(this.domes.length>1&&this.warnOnce(`domes`,`${this.domes.length} USD dome lights; "${e?.name??this.domes[0].name}" lights the scene`),!e){let e=this.domes.find(e=>e.asset);return e&&this.warnOnce(`domefile`,`USD dome light texture "${e.asset}" not found`),null}new r.Vector3(0,1,0).transformDirection(e.matrix).y<.999&&this.warnOnce(`domepole`,`USD dome light is tilted; only its turn about the up axis is applied`);let t=new r.Vector3(0,0,1).transformDirection(e.matrix),n=Math.atan2(t.x,t.z)/sI;return{file:e.file,intensity:e.intensity*Math.max(...e.color),rotation:90-n}}}}));function jI(e){let t=e.filter(e=>PI.test(e)&&!e.split(`/`).pop().startsWith(`._`));if(t.length===0)return[];let n=e=>e.split(`/`).length,r=Math.min(...t.map(n));return t.filter(e=>n(e)===r).sort((e,t)=>{let n=e.split(`/`).pop(),r=t.split(`/`).pop();return n.length-r.length||(n<r?-1:+(n>r))})}async function MI(e,t){let n=new Map,r=e.pseudoRoot,i=e.root.id.includes(`/`)?e.root.id.slice(0,e.root.id.lastIndexOf(`/`)):``;for(let t of r.childNames())for(let[,a,o]of(await e.child(r,t))?.sites??[])for(let[t,r]of a.children??[])for(let a of[`references`,`payload`]){let s=r.arcs?.[a];for(let r of[...s?.explicit??[],...s?.prepend??[],...s?.append??[],...s?.add??[]]){let a=e.files.resolve(r.asset,o.path);if(!a?.includes(`/`))continue;let s=a.slice(0,a.lastIndexOf(`/`));s===i||!s.startsWith(i)||n.has(s)||n.set(s,{name:t,prefix:s,files:0,bytes:0,scenes:1})}}let a=new Map;for(let e of n.values()){let t=e.prefix.slice(0,e.prefix.lastIndexOf(`/`));a.has(t)||a.set(t,[]),a.get(t).push(e)}let o=[...a.values()].sort((e,t)=>t.length-e.length)[0]??[];for(let e of o)for(let n of t)!n.path.startsWith(`${e.prefix}/`)||!PI.test(n.path)||(e.files++,e.bytes+=n.size);return o.sort((e,t)=>e.bytes-t.bytes)}async function NI(e){let t=[],n=e=>t.push(e),r=new XN({maxTriangles:e.maxTriangles,maxPlacements:e.maxPlacements,mergeShapesAbove:e.mergeShapesAbove,curveSteps:e.curveSteps,curveSides:e.curveSides,curveTolerance:e.curveTolerance}),i=performance.now(),a=new HF(e.files,{warn:n});await a.open(e.entryPath);let o=new kI(a,{maxTriangles:r.maxTriangles,maxPlacements:r.maxPlacements,curveSteps:r.curveSteps,resolveImage:e.resolveImage,warn:n}),s=await o.read();a.omittedArcs>0&&n(`${a.omittedArcs} reference(s) into the parts left out of this load skipped`);let c=performance.now()-i,l=performance.now(),u=await r.build(s.ir);for(let e of[...s.cameras,...s.lights])u.group.add(e);let d=null;if(s.dome){let t=await e.resolveEnvironment(s.dome.file);t?d={texture:t,intensity:s.dome.intensity,rotation:s.dome.rotation}:n(`USD dome light texture "${s.dome.file}" could not be read`)}return{...u,environment:d,cameras:s.cameras,lights:s.lights,cost:s.cost,fitNote:o.fitNote,warnings:[...t,...u.warnings],parseMs:c,buildMs:performance.now()-l}}var PI,FI=g((()=>{ZN(),UF(),AI(),PI=/\.(usd|usda|usdc)$/i}));function II(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 LI(e){let{data:t,width:n,height:i}=II(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 RI=g((()=>{})),zI=_({ARCHIVE_ELEMENT_PROMPT_BYTES:()=>qI,ArchiveImporter:()=>YI,USD_ELEMENT_PROMPT_BYTES:()=>JI}),BI,VI,HI,UI,WI,GI,KI,qI,JI,YI,XI=g((()=>{zk(),eA(),sA(),yi(),Sv(),hn(),FA(),Oc(),wc(),de(),PP(),FI(),RI(),xy(),an(),Ov(),Fr(),ny(),BI=3e4,VI=[`scene.gltf`,`scene.glb`,`model.gltf`,`model.glb`,`main.gltf`,`main.glb`,`asset.gltf`,`asset.glb`],HI=e=>e instanceof Blob?e:new Blob([e],{type:`application/octet-stream`}),UI=async e=>e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e,WI=async e=>e instanceof Blob?e.text():(0,m.strFromU8)(e),GI=(e,t)=>{let n=[];for(let r of`${e}/${t}`.split(`/`))r===`..`?n.pop():r&&r!==`.`&&n.push(r);return n.join(`/`)},KI=async e=>{let t=await UI(e);return t.byteOffset===0&&t.byteLength===t.buffer.byteLength?t.buffer:t.slice().buffer},qI=4e9,JI=1e9,YI=class{static FORMATS=wv;constructor(e){this.loader=e,this._store=null,this.lastPBRTStats=null,this.lastUSDStats=null}release(){this._store?.decide(!1),this._store=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=mk(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 wk(e,{filter:()=>!1,onProgress:n})}else r=t===`tar`?(await rA(e,this.loader.storage))?.listing??await Tk(e,{onProgress:n}):(await Uk(e)).map(e=>({path:e.name,size:e.size}));let{root:i,elements:a}=Ak(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 nA(e,{storage:this.loader.storage,label:t,...r.length?{filter:kk(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=mk(await this._readHead(e)),c=this.loader.storage?hv(await pv(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(CP(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 loadFolder(e,{pbrtEntry:t=null,element:n=null,promptBytes:r,...i}={}){let a=(Array.isArray(n)?n:[n]).filter(Boolean),o=Ok(e,{filter:a.length?kk(a):null}),s=o.listing.reduce((e,t)=>e+t.size,0);a.length===0&&this._requireElementChoice(e.name,o.listing,s,r),console.info(`Folder "${e.name}": ${o.listing.length} files, ${(s/1e9).toFixed(1)} GB`+(a.length?`, ${a.length} part${a.length>1?`s`:``} selected.`:`.`));let c=this.loader.storage?hv(await mv(e)):null;return await this._loadSource(o,e.name,{element:n,pbrtEntry:t,pbrt:i,archiveId:c,promptBytes:r,kind:`folder`})}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});return await this._loadSource(l,t,{element:n,pbrtEntry:i,pbrt:a,archiveId:c,promptBytes:r})}async _loadSource(e,t,{element:n,pbrtEntry:r,pbrt:i,archiveId:a,promptBytes:o,kind:s=`archive`}){if(e.archiveId=a,e.elements=(Array.isArray(n)?n:[n]).filter(Boolean),e.listing.some(e=>e.path.toLowerCase().endsWith(`.pbrt`)))return await this.loadPBRTFromZip({},t,r,i,e);let c=Object.create(null);for(let t of e.listing)t.offset!==void 0&&(c[t.path]=e.entries[t.path]??await e.slice(t.path));let l=this._mainModelPath(Object.keys(c))?.usd?await this.loadUSDScene(c,t,{...i,element:n,promptBytes:o,listing:e.listing}):await this._loadNonPBRTArchive(c,t);return this.loader._sourceKey=this.loader._keyed(s,a),l}async _loadStoredGraph(e,t,{imageFromBytes:n,envFromBytes:r}){let i=this.loader.storage?.area(mn.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 kP({},t),c=await SA(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(X.STORAGE_ENTRY_CORRUPT,`stored scene unusable: ${s.message}`,{key:e}),i.remove(e).catch(()=>{}))}}_storeGraph(e,t,n){let r=this.loader.storage?.area(mn.SCENES);if(!r)return;let i;try{i=hA(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,parameters:t.parameters??null}})}catch(e){e instanceof NA?console.info(`Scene not stored for next time: ${e.message}`):console.warn(`Scene not stored for next time:`,e);return}let a,o=new AbortController,s={key:e,encoded:i,label:n,model:t.group,writing:!1,signal:o.signal,parseMs:(t.parseMs??0)+(t.buildMs??0),triangles:t.triangleCount??null,accepted:new Promise(e=>{a=e}),decide:e=>{a(e),e||o.abort()}};this._store=s,Tc(s.parseMs,i.byteLength)&&this._writeGraph(r,s)}flushPendingGraph(e){let t=this._store;if(!t||t.writing)return;let n=this.loader.storage?.area(mn.SCENES);n&&Tc(t.parseMs+e,t.encoded.byteLength)?this._writeGraph(n,t):this._store=null}commitPendingGraph(e){let t=this._store;!t||t.model!==e||(this._store=null,t.model=null,t.decide(t.writing))}_writeGraph(e,t){t.writing=!0,(async()=>{let n=null;try{if(n=await e.create(t.key,{label:`${t.label} (scene)`,expectedBytes:t.encoded.byteLength}),!n)return;await gA(n,t.encoded,{release:!0,signal:t.signal}),t.encoded=null,await t.accepted?await n.commit({triangles:t.triangles}):await n.abort()}catch(e){await n?.abort().catch(()=>{}),t.signal.aborted||console.warn(`Storing the scene failed:`,e)}finally{t.encoded=null}})()}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?kk(o):null,c;if(a)c=await Kk(e,{filter:s});else{let t=i??await rA(e,this.loader.storage);c=await Dk(e,{index:t,headersOnly:!0,filter:s,onProgress:e=>z({isLoading:!0,status:`Indexing archive… ${(e.bytes/1e9).toFixed(1)} GB`,progress:4})}),t||iA(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=qI){if(n<r)return;let{root:i,elements:a}=Ak(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(X.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},tn.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 wk(e,{filter:a.length?kk(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}=Ak(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(X.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},tn.WARNING),i}if(l){let e=kk(a),t=s.filter(t=>e(t.path,t.size)&&!o[t.path]).length;this.loader._issues?.record(X.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},tn.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,r={},i=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 a=e=>this.loader.loaderCache.ply.parse(e),o=(e,t)=>this._archiveImage(e,t),s=(e,t)=>this._archiveEnvironment(e,t),c=performance.now(),l={animation:r.animation,maxTriangles:r.maxTriangles,maxPlacements:r.maxPlacements,mergeShapesAbove:r.mergeShapesAbove,curveSteps:r.curveSteps,curveSides:r.curveSides,curveTolerance:r.curveTolerance,instanceIncludes:r.instanceIncludes},u=i?.archiveId?this.loader._keyed(`pbrt:2.14:${Cc}`,`${i.archiveId}|${n??``}|${[...i.elements??[]].sort().join(`,`)}|${JSON.stringify(l)}`):null,d=u?await this._loadStoredGraph(u,i,{imageFromBytes:o,envFromBytes:s}):null,f=d??await TP({vfs:e,source:i,entryPath:n,plyParser:a,imageFromBytes:o,envFromBytes:s,...l});this.loader._throwDeferred();let{group:p,environment:m,animations:h,report:g,warnings:_,meshCount:v,entryPath:y,candidates:b,frames:x,parseMs:S,buildMs:C,triangleCount:w,placementCount:T,mergedShapes:E,skippedForBudget:D,droppedNoTemplate:O,parameters:k}=f;d&&console.info(`PBRT scene "${y}" opened from storage in ${(C/1e3).toFixed(1)} s, skipping the parse`),this.lastPBRTStats={parseMs:S,buildMs:C,loaderMs:performance.now()-c,triangleCount:w,placementCount:T,mergedShapes:E,skippedForBudget:D,droppedNoTemplate:O,meshCount:v,frames:x?.length??1};let A=new Set(x??[y]),j=b.filter(e=>!A.has(e));if(j.length>0&&(console.warn(`PBRT archive holds ${b.length} scenes; loaded "${y}". Others: ${j.join(`, `)}`),this.loader._issues?.record(X.ASSET_AMBIGUOUS_ENTRY,`archive holds ${b.length} pbrt scenes; loaded "${y}"`,{loaded:y,alternatives:j},tn.WARNING)),k&&this._reportParameters(k,y),g&&g.length&&typeof console.table==`function`){let e=g.length<v?` (first ${g.length} of ${v})`:``;console.groupCollapsed(`PBRT loader: ${v} mesh(es) from "${y}"${e}`),console.table(g),console.groupEnd()}return _&&_.length&&(console.warn(`PBRT loader: ${_.length} warning(s) parsing "${y}"`),_.forEach(e=>console.warn(` •`,e))),m?.texture&&(m.texture.generateMipmaps=!0,this.loader.applyEnvironmentToScene(m.texture)),p.name=y||t,this.loader.releaseTargetModel(),this.loader._sourceKey=u,u&&!d&&this._storeGraph(u,f,t),this.loader.targetModel=p,this.loader.animations=h??[],this.loader.sceneMetadata={environment:m?.texture?{rotation:0,intensity:1}:{enabled:!1},...f.render?{render:{...f.render}}:{}},z({isLoading:!0,status:`Processing PBRT geometry...`,progress:10}),await this.loader.onModelLoad(this.loader.targetModel),this.loader.dispatchEvent({type:`load`,model:p,filename:`${y} (from ${t})`}),p}_reportParameters({unused:e,approximated:t},n){let r=Object.keys(e).length,i=Object.keys(t).length;if(r+i===0)return;let a=`${r} pbrt parameter(s) ignored and ${i} approximated in "${n}"`,o=[...Object.entries(e).map(([e,t])=>` ignored ${e} ×${t}`),...Object.entries(t).map(([e,t])=>` approximated ${e} ×${t}`)];console.warn(`PBRT loader: ${a} (× directives that set it)\n${o.join(`
|
|
1430
|
-
`)}`),this.loader._issues?.warn(X.ASSET_PARAMETERS_IGNORED,a,{entry:n,unused:e,approximated:t})}async _archiveImage(e,t){let n;try{n=await this._pbrtTextureFromBytes(e,t)}catch(e){if(e instanceof nn)throw e;return this.loader._reportImageFailure(t,e),null}return n&&(n.userData[wA]=t),n}async _archiveEnvironment(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}):LI(e);return o.mapping=r.EquirectangularReflectionMapping,di(o,`bytes:${await fv(i)}`),o.userData[wA]=t,o.userData[TA]=`environment`,o}finally{a&&URL.revokeObjectURL(a)}}async loadUSDScene(e,t,n={}){z({isLoading:!0,status:`Reading USD scene...`,progress:5});let r=Object.keys(e),i=new LF(r,async t=>e[t]?UI(e[t]):null,{omitted:(n.listing??[]).filter(t=>!(t.path in e)).map(e=>e.path)}),a=jI(r);if(a.length===0)throw Error(`No USD layer found in ${t}`);let o=a[0];a.length>1&&(console.warn(`${t} holds ${a.length} top-level USD layers; loaded "${o}". Others: ${a.slice(1).join(`, `)}`),this.loader._issues?.record(X.ASSET_AMBIGUOUS_ENTRY,`${t} holds ${a.length} top-level USD layers; loaded "${o}"`,{loaded:o,alternatives:a.slice(1)},tn.WARNING)),(Array.isArray(n.element)?n.element:[n.element]).filter(Boolean).length===0&&await this._requireUSDPartChoice(t,i,o,n.listing??r.map(t=>({path:t,size:e[t]?.size??e[t]?.byteLength??0})),n.promptBytes);let s=performance.now(),c=await NI({files:i,entryPath:o,resolveImage:async e=>{let t=await i.read(e);return t?this._archiveImage(t,e):null},resolveEnvironment:async e=>{let t=await i.read(e);return t?this._archiveEnvironment(t,e):null},maxTriangles:n.maxTriangles,maxPlacements:n.maxPlacements,mergeShapesAbove:n.mergeShapesAbove,curveSteps:n.curveSteps,curveSides:n.curveSides,curveTolerance:n.curveTolerance});this.loader._throwDeferred();let{group:l,environment:u,warnings:d,triangleCount:f,placementCount:p,skippedForBudget:m,meshCount:h,parseMs:g,buildMs:_,fitNote:v}=c;return this.lastUSDStats={parseMs:g,buildMs:_,loaderMs:performance.now()-s,triangleCount:f,placementCount:p,skippedForBudget:m,meshCount:h,fitNote:v},(v||m>0)&&this.loader._issues?.record(X.SCENE_MEMORY_BUDGET,v??`${m.toLocaleString()} placements past the scene budgets left out`,{triangleCount:f,placementCount:p,skippedForBudget:m},tn.WARNING),d.length&&(console.warn(`USD loader: ${d.length} warning(s) loading "${o}"`),d.forEach(e=>console.warn(` •`,e))),u?.texture&&(u.texture.generateMipmaps=!0,this.loader.applyEnvironmentToScene(u.texture)),l.name=o.split(`/`).pop(),this.loader.releaseTargetModel(),this.loader.targetModel=l,this.loader.animations=[],this.loader.sceneMetadata=u?.texture?{environment:{rotation:u.rotation,intensity:u.intensity}}:null,z({isLoading:!0,status:`Processing USD geometry...`,progress:10}),await this.loader.onModelLoad(l),this.loader.dispatchEvent({type:`load`,model:l,filename:`${o} (from ${t})`}),l}async _requireUSDPartChoice(e,t,n,r,i=JI){let a=r.reduce((e,t)=>e+(PI.test(t.path)?t.size:0),0);if(a<i)return;let o=new HF(t);await o.open(n);let s=await MI(o,r);if(s.length<2)return;let c=r.reduce((e,t)=>e+t.size,0),l=Error(`"${e}" holds ${(a/1e9).toFixed(1)} GB of USD across ${s.length} parts. Choose which to load — loading all of them at once may exhaust memory.`);throw l.code=`ARCHIVE_NEEDS_ELEMENT`,l.root=n.includes(`/`)?n.slice(0,n.lastIndexOf(`/`)):``,l.elements=s,l.totalBytes=c,this.loader._issues?.record(X.ASSET_ARCHIVE_TOO_LARGE,`USD scene holds ${(a/1e9).toFixed(1)} GB of layers across ${s.length} parts; choose which to load`,{root:l.root,elements:s.map(e=>e.prefix),totalBytes:c},tn.WARNING),l}_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=LI(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{if(Dr().decodeImage)i=await Zv(e,t);else if(typeof createImageBitmap==`function`)i=new r.Texture(await createImageBitmap(new Blob([e])));else throw Error(`no image decoder in this runtime: configurePlatform( nodePlatform( { decodeImage } ) ) — see "Running in Node"`);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}_mainModelPath(e){let t=e[0]?.split(`/`)[0],n=t!==void 0&&e.every(e=>e.startsWith(t+`/`))?t+`/`:``,r=e.filter(e=>e.split(`.`).pop().toLowerCase()===`obj`||this.loader.getFileFormat(e)?.type===`model`);if(r.length===0)return null;let i=e=>e.split(`/`).length*2+ +!/\.(gltf|glb)$/i.test(e),a=new Set(e),o=VI.map(e=>n+e).find(e=>a.has(e)),s=o??r.reduce((e,t)=>i(t)<i(e)?t:e);return{path:s,models:r,main:!!o,usd:!o&&PI.test(s)}}async findAndLoadModelFromZip(e,t=`the ZIP archive`){let n=this._mainModelPath(Object.keys(e));if(!n)throw Error(`No supported model files found in ${t}`);if(n.usd)return await this.loadUSDScene(e,t);let{path:r,models:i}=n,a=i.filter(e=>e!==r&&!PI.test(e));return a.length>0&&(console.warn(`${t} holds ${a.length+1} models; loaded "${r}". Others: ${a.join(`, `)}`),this.loader._issues?.record(X.ASSET_AMBIGUOUS_ENTRY,`${t} holds ${a.length+1} models; loaded "${r}"`,{loaded:r,alternatives:a.slice(0,50)},tn.WARNING)),console.log(`Loading model file from ${t}: ${r}`),await this.loadModelFromZipEntry(e[r],r,r.split(`.`).pop().toLowerCase(),e,t)}async loadModelFromZipEntry(e,t,n,r,i=`ZIP`){try{z({isLoading:!0,status:`Processing ${n.toUpperCase()} from ${i}...`,progress:5});let a;switch(n){case`glb`:case`gltf`:a=await this.handleGltfFromZip(n,e,t,r);break;case`obj`:a=await this.handleObjFromZip(e,t,r);break;default:a=await this.loader._loadModelFileByExtension(new File([e],t),t)}return this.loader.dispatchEvent({type:`load`,model:this.loader.targetModel,filename:`${t} (from ${i})`}),a}catch(e){throw console.error(`Error loading ${n} from ${i}:`,e),this.loader.dispatchEvent({type:`error`,message:e.message,filename:t}),e}}async handleGltfFromZip(e,t,n,i){if(e===`gltf`){let e=await WI(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{let t=await jr(()=>new Promise((t,n)=>s.parse(e,``,t,n)));return this.loader._throwDeferred(),this.loader.releaseTargetModel(),this.loader.targetModel=t.scene,this.loader.sceneMetadata=vy(t),await this.loader.onModelLoad(this.loader.targetModel),t}finally{this.loader._disposeGLTFLoader(s)}}else return await this.loader.loadGLBFromArrayBuffer(await KI(t),n)}async handleObjFromZip(e,t,n){let r=await WI(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),BI))]);return clearTimeout(r),i||this.loader._issues?.record(X.TEXTURE_BUILD_FAILED,`MTL textures did not decode within ${BI}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=await WI(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){if(/^(data|blob|https?):/i.test(e))return e;let r=e.replace(/^\.\/|^\//,``),i=r;try{i=decodeURIComponent(r)}catch{}for(let e of new Set([r,i])){let r=e.split(`/`).pop(),i=[GI(t,e),e,r].find(e=>n[e])??(r?Object.keys(n).find(e=>e.endsWith(`/${r}`)):void 0);if(i)return URL.createObjectURL(HI(n[i]))}return console.warn(`Resource not found in the archive: ${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=await this.prepareFixedMtlContent(t),f=new a(c).parse(d,u);await this.preloadMtlTextures(f);let p=new o(c);p.setMaterials(f);let m=await WI(e.content),h=p.parse(m);return this.loader.releaseTargetModel(),this.loader.targetModel=h,await this.loader.onModelLoad(this.loader.targetModel),s.forEach(e=>URL.revokeObjectURL(e)),this.loader.dispatchEvent({type:`load`,model:h,filename:`${e.path} (from ${i})`}),h}async prepareFixedMtlContent(e){return(await WI(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=URL.createObjectURL(HI(i[e]));return a.push(t),t}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=URL.createObjectURL(HI(t[e]));return n.push(r),r}if(r&&r.length>5)for(let e in t){let i=e.split(`/`).pop();if(i.includes(r)||r.includes(i)){let r=URL.createObjectURL(HI(t[e]));return n.push(r),r}}return null}}}));function ZI(e){let t=(e/1e3)**2;return .002152*(1.0455996-341.29061/t-.9023085*t)/(1+.0027059889/t-85.968563*t)}function QI(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 $I(e,t){let n=0,r=bL+e*xL;for(let e=0;e<xL;e++)n+=t(r+e+.5);return n/xL}function eL(e){let t=new Float64Array(16);for(let n=0;n<16;n++)t[n]=$I(n,e);return t}function tL(e=1){let t=new Float32Array(48);for(let n=0;n<16;n++){let r=NL[n*3],i=NL[n*3+1],a=NL[n*3+2];for(let o=0;o<3;o++){let s=EL;t[o*16+n]=(s[o*3]*r+s[o*3+1]*i+s[o*3+2]*a)*e}}return t}function nL(e){let t=0,n=0,r=0;for(let i=0;i<16;i++)t+=e[i]*NL[i*3],n+=e[i]*NL[i*3+1],r+=e[i]*NL[i*3+2];return[t,n,r]}function rL([e,t,n]){let r=EL;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 iL(e){return Math.max(0,.0460836582205*e-.04586025928522)}function aL([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(OL,i=>{let a=1-r(470,520,i),o=r(560,610,i);return n*a+e*o+t*(1-a-o)})}function oL({airDensity:e=1,turbidity:t=2,ozone:n=300,groundAlbedo:r=[.3,.3,.3]}={}){let i=iL(t)/gL,a=n*DL/(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]=AL[t]*e,s[t]=ML[t]*i,c[t]=s[t]*_L,l[t]=jL[t]*a;return{rayleigh:o,mieScattering:c,mieExtinction:s,ozone:l,albedo:aL(r)}}function sL(e){let t=Math.max(e,0);return Math.sqrt(t*(2*mL+t))/(mL+t)}function cL(e,t,n=1024){let r=Math.max(e,0),i=mL+r,a=i*t,o=r*(2*mL+r);if(t<0&&a*a>=o)return null;let s=-a+Math.sqrt(a*a+(hL-i)*(hL+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))+mL),p=r-t;c+=PL(f)*p,l+=FL(f)*p,u+=IL(f)*p}return[c,l,u]}function lL(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 uL(e){let t=Math.sin(e/2);return 4*Math.PI*t*t}function dL({direction:e,altitude:t,angularDiameter:n,strength:r=1,coefficients:i}){let a=n/2,o=uL(a),s=sL(t),[c,l,u]=e,d=Math.sin(a),f=new Float64Array(16),p=0,m=e=>{if(e<-s)return;let n=lL(i,cL(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]=kL[e]*r/o*f[e]/p;return{radiance:rL(nL(h)).map(e=>Math.max(0,e*SL)),visibleFraction:p/g,solidAngle:o,direction:[c,l,u]}}function fL(e,t=vL){let n=t*t;return 3/(8*Math.PI)*(1-n)/(2+n)*(1+e*e)/(1+n-2*t*e)**1.5}function pL(e,t,n,r,i=8){let a=n*r,o=e*t,s=new Float32Array(2*o*a);return[LL,e=>fL(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 mL,hL,gL,_L,vL,yL,bL,xL,SL,CL,wL,TL,EL,DL,OL,kL,AL,jL,ML,NL,PL,FL,IL,LL,RL=g((()=>{Dh(),mL=6360,hL=6420,gL=1.2,_L=.9,vL=.76,yL=1.3,bL=380,xL=25,SL=1/32,CL=[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],wL=[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],TL=[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],EL=[3.2406,-1.5372,-.4986,-.9689,1.8758,.0415,.0557,-.204,1.057],DL=0xe90f62a5dcb760000,OL=Float64Array.from({length:16},(e,t)=>bL+(t+.5)*xL),kL=eL(e=>QI(CL,360,10,e)),AL=eL(e=>ZI(e)/8),jL=eL(e=>QI(wL,360,10,e)),ML=eL(e=>(e/1e3)**-yL),NL=(()=>{let e=new Float64Array(48);for(let t=0;t<16;t++)for(let n=0;n<3;n++)e[t*3+n]=$I(t,e=>QI(TL,360,5,e,3,n))*xL;return e})(),PL=e=>Math.exp(-e/8),FL=e=>Math.exp(-e/gL),IL=e=>Math.max(0,1-Math.abs(e-25)/15),LL=e=>3/(16*Math.PI)*(1+e*e)}));function zL(e){return{r:(0,n.exp)(e.mul(-1/8)),m:(0,n.exp)(e.mul(-1/gL)),o:(0,n.max)((0,n.float)(0),(0,n.float)(1).sub((0,n.abs)(e.sub(25)).div(15)))}}function BL(e,t){return cR(n=>e.rayleigh[n].mul(t.r).add(e.mieExtinction[n].mul(t.m)).add(e.ozone[n].mul(t.o)))}function VL(e,t){return cR(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 HL(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 UL(e,t){let r=e.add(mL),i=(0,n.sqrt)((0,n.max)(e.mul(e.add(2*mL)),0)),a=r.mul(t),o=a.negate().add((0,n.sqrt)((0,n.max)(a.mul(a).add(iR*iR).sub(i.mul(i)),0))),s=(0,n.float)(aR).sub(e),c=i.add(iR);return{x:o.sub(s).div((0,n.max)(c.sub(s),1e-6)).mul(255),y:i.div(iR).mul(63),rho:i,r}}function WL(e,t,r,i,a){let o=UL(r,i),s=HL(e,256,64,o.x,o.y).xyz,c=(0,n.smoothstep)(a.negate(),a,i.add(o.rho.div(o.r)));return cR(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 GL(e,t,r,i,a){let o=[[(0,n.clamp)(gR(r,64),0,63),64],[(0,n.clamp)(uR(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/oR),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 KL(e,t){let r=gR(t,128);return cR(t=>(0,n.exp)(HL(e,128,1,r,(0,n.float)(0),4,t)))}function qL(e,t){let r=e.add(mL).toVar(),i=r.mul(t).toVar(),a=e.mul(e.add(2*mL)).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)(hL).sub(r).mul(r.add(hL))),0)));return{r,b:i,cGround:a,hitsGround:s,tMax:s.select(c,l).toVar()}}function JL(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(mL)),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 YL(e,t){let r=t*t,i=3/(8*oR)*(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 XL({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(iR).toVar(),s=(0,n.sqrt)(o.mul(o).add(mL*mL)).toVar(),c=(0,n.float)(hL).sub(s),l=o.add(iR),u=c.add(a.mul(l.sub(c))).toVar(),d=(0,n.clamp)((0,n.float)(iR*iR).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=zL((0,n.max)(f.add(l).div((0,n.sqrt)(s.mul(s).add(l)).add(mL)),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 ZL(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(oR/8);return(0,n.vec3)(o.mul((0,n.cos)(s)),a,o.mul((0,n.sin)(s)))}function QL(e,t){let r=gR(t,64);return cR(t=>HL(e,64,1,r,(0,n.float)(0),4,t))}function $L(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),_=hR(g.mod(64),64).toVar(),v=(0,n.max)(lR(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=cR(()=>(0,n.vec4)(0).toVar()),x=t?cR(()=>(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=ZL(h.div(8),h.mod(8),e,i).toVar(),s=(0,n.dot)(r,y).toVar(),p=t?bR(s).toVar():null,m=t?YL(s,f).toVar():null,g=t?null:Array.from({length:8},()=>(0,n.vec4)(0).toVar()),S=qL(v,r.y),C=cR(()=>(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=JL(S,l.add(f.mul(.5)),_,s),v=zL(h.h),y=cR(e=>u.rayleigh[e].mul(v.r)),w=cR(e=>u.mieScattering[e].mul(v.m)),T=VL(BL(u,v),f),E;if(t){let e=WL(o,u,h.h,h.muS,d);E=cR(t=>e[t].mul(y[t].mul(p).add(w[t].mul(m))))}else (0,n.If)(e.mod(2).equal(0),()=>{let e=GL(c,h.h,h.muS,h.mu,yR(s,h.mu,h.muS));for(let t=0;t<8;t++)g[t].assign(e[t])}),E=cR(e=>y[e].mul(g[e]).add(w[e].mul(g[4+e])));for(let e of sR)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(mL),-1,1),r;if(t){let t=WL(o,u,(0,n.float)(0),e,d);r=cR(r=>t[r].mul((0,n.max)(e,0)))}else r=QL(l,e);for(let e of sR)b[e].addAssign(C[e].mul(r[e]).mul(u.albedo[e]).mul(1/oR))})});for(let t of sR)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 eR(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=cR(()=>(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 sR)e[r].addAssign(i.element(p.add((0,n.uint)(t)).mul(4).add(r)))}),m=cR(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=cR(()=>(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 sR)c[e].addAssign(t.element(a.add(e)).mul(o))}});for(let t of sR){let n=e.mul(8).add(i*4+t);r===`first`?(s.element(n).assign(c[t]),o.element(n).assign(vR(c[t]))):r===`middle`?(s.element(n).addAssign(c[t]),o.element(n).assign(vR(c[t]))):o.element(n).assign(vR(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=cR(()=>(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 sR)e[a].addAssign(t.element(p.add((0,n.uint)(r)).mul(4).add(a)).mul(i))});for(let t of sR)c.element(f.mul(4).add(t)).assign(e[t].mul(xR))})})().compute(l,[64])}function tR({transmittance:e,multipleScattering:t,coefficients:r,sunSinRadius:i,mieG:a},o,s,c,l){let u=cR(()=>(0,n.vec4)(0).toVar()),d=cR(()=>(0,n.vec4)(1).toVar()),f=t?Array.from({length:8},()=>(0,n.vec4)(0).toVar()):null,p=bR(c).toVar(),m=YL(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=JL(o,v.add(y.mul(.5)),s,c),x=zL(b.h),S=cR(e=>r.rayleigh[e].mul(x.r)),C=cR(e=>r.mieScattering[e].mul(x.m)),w=WL(e,r,b.h,b.muS,i),T=VL(BL(r,x),y);f&&(0,n.If)(a.mod(SR).equal(0),()=>{let e=GL(t,b.h,b.muS,b.mu,yR(c,b.mu,b.muS));for(let t=0;t<8;t++)f[t].assign(e[t])});for(let e of sR){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 nR(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=hR(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=cR(()=>(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*oR),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}=tR(e,qL(o,p.y),c,(0,n.dot)(p,l),r);for(let e of sR)u[e].addAssign(m[e])});for(let e of sR)i.element(s.mul(4).add(e)).assign(vR(u[e].mul(oR/a)))})().compute(128,[64])}function rR(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(oR),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)(CR(e.mod(256)))).mul((0,n.sqrt)((0,n.max)((0,n.float)(1).sub(_.mul(_)),0))).add(a.mul(_)).toVar(),y=qL(o,a),{L:b,throughput:x}=tR(h,y,_,v,i);(0,n.If)(y.hitsGround,()=>{let e=(0,n.clamp)(y.r.mul(_).add(y.tMax.mul(v)).div(mL),-1,1).toVar(),t=WL(m,l,(0,n.float)(0),e,p),r=KL(c,e);for(let i of sR)b[i].addAssign(x[i].mul(l.albedo[i]).mul(1/oR).mul(t[i].mul((0,n.max)(e,0)).add(r[i])))});let S=cR(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*oR).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(oR)).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 iR,aR,oR,sR,cR,lR,uR,dR,fR,pR,mR,hR,gR,_R,vR,yR,bR,xR,SR,CR,wR=g((()=>{RL(),iR=Math.sqrt(hL*hL-mL*mL),aR=hL-mL,oR=Math.PI,sR=[0,1,2,3],cR=e=>sR.map(e),lR=e=>(0,n.float)(e).div(15).pow(2).mul(aR),uR=e=>(0,n.sqrt)((0,n.clamp)(e.div(aR),0,1)).mul(15),dR=-3*oR/180,fR=15*oR/180,pR=.5+Math.atan((-oR/2-dR)/fR)/oR,mR=.5+Math.atan((oR/2-dR)/fR)/oR,hR=(e,t)=>(0,n.sin)((0,n.clamp)((0,n.tan)((0,n.float)(e).div(t-1).mul(mR-pR).add(pR-.5).mul(oR)).mul(fR).add(dR),-oR/2,oR/2)),gR=(e,t)=>(0,n.atan)((0,n.asin)((0,n.clamp)(e,-1,1)).sub(dR).div(fR)).div(oR).add(.5-pR).div(mR-pR).mul(t-1),_R=1e-30,vR=e=>(0,n.log)((0,n.max)(e,(0,n.vec4)(_R))),yR=(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)),bR=e=>e.mul(e).add(1).mul(3/(16*oR)),xR=4*oR/128,SR=4,CR=e=>(0,n.float)(e).div(255).pow(2).mul(oR)}));function TR(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 ER({pixels:e,rows:t,prefix:r,stats:i,cdf:a,width:o,height:s}){let c=DR(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,Bl).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=TR(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=TR(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 DR,OR=g((()=>{xu(),DR=e=>Math.ceil((e+1)*16/256)*64})),kR=_({PhysicalSky:()=>jR});function AR(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 jR,MR=g((()=>{O(),Vd(),wR(),OR(),tr(),RL(),jR=class{constructor(e=1024,t=512,n={}){this.width=e,this.height=t,this._quality=n,this.lastRenderTime=0,this._texture=AR(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=AR(e+1,t,r.RGBAFormat),this._rec709Weights=tL(SL),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(DR(this.width)*this.height,1),phaseCells:new t.StorageInstancedBufferAttribute(pL(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:vL},l=this._quality,u=o(`incomingA`),d=o(`incomingB`);this._kernels={transmittance:XL(c),air:[$L(c,{first:!0,out:u,...l.incoming}),eR(c,{incoming:u,stage:`first`}),$L(c,{first:!1,out:d,...l.incoming}),eR(c,{incoming:d,stage:`middle`}),$L(c,{first:!1,out:u,...l.incoming}),eR(c,{incoming:u,stage:`last`}),nR(c,l.irradiance)],sky:rR(c,{width:this.width,height:this.height,...l.sky}),cdf:ER({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,kL)}_setColorWeights(){let e=this._rec709Weights,t=Yn(),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:DR(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=oL(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=dL({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=sL(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:DR(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??{}))Au(e,t);this._kernels=null,this._attrs=null,this._texture.dispose(),this._cdfTexture.dispose()}}}));lt(),Ae(),F(),an(),Ov();var NR=ve(`engine`),PR=class extends Qy{constructor(e,t={}){super(e,t),this.setColorManagement(EO),this.setStorageOpener(uk),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 Fw}_createCamera(){return this.cameraManager=new ES(this.canvas),this.timeline=new MS({cameraManager:this.cameraManager,onReset:()=>this.reset()}),this.cameraManager.camera}_initAssetPipeline(){super._initAssetPipeline(),this.assetLoader.controls=this.cameraManager.controls,this.assetLoader.registerFormat(...Qw),this.assetLoader.setArchiveImporterLoader(()=>Promise.resolve().then(()=>(XI(),zI)).then(e=>new e.ArchiveImporter(this.assetLoader)),wv);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 cb(e,{pathTracer:t.pathTracer}),t.motionVector=new lb(e,this.camera,{pathTracer:t.pathTracer}),t.nrd=new tx(e,{enabled:!1,pathTracer:t.pathTracer}),t.autoExposure=new kx(e,{enabled:nx.autoExposure}),t.localExposure=new Qx(e,{enabled:Ax.localExposure}),[t.normalDepth,t.motionVector,t.nrd,t.autoExposure,t.localExposure]}_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(()=>(MR(),kR)).then(e=>e.PhysicalSky)),this.stages.pathTracer.registerIntegrator([`bidirectional`,`vcm`],e=>new kE(e)),this.stages.pathTracer.requestOutput(`gBuffer`),this.interactionManager=new rS({scene:this.meshScene,camera:this.camera,canvas:this.canvas,assetLoader:this.assetLoader,pathTracer:null,floorPlane:this.assetLoader.floorPlane,isGeometryOnDisk:()=>this.geometryOnDisk}),this.interactionManager.wireAppEvents(this),this.cameraManager.setInteractionManager(this.interactionManager),this.goboManager=new NS(this.stages.pathTracer,{onReset:()=>this.reset(),issues:this._issues}),this.iesManager=new GS(this.stages.pathTracer,{onReset:()=>this.reset(),issues:this._issues}),this._setupDenoisingManager(),this._headless||(await this._setupOverlayManager(),this.transformManager=new Rw({camera:this.camera,canvas:this.canvas,orbitControls:this.cameraManager.controls,app:this}),this.overlayManager.register(`transform`,new zw(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,N.CAMERA_SWITCHED,e=>this.dispatchEvent(e)),this._addTrackedListener(this.cameraManager,N.AUTO_FOCUS_UPDATED,e=>this.dispatchEvent(e)),this._addTrackedListener(this.cameraManager,N.ORTHO_HEIGHT_UPDATED,e=>this.dispatchEvent(e)),this._addTrackedListener(this.timeline,N.TIMELINE_CHANGED,e=>this.dispatchEvent(e)),this._forwardEvents(this.denoisingManager,[N.DENOISING_START,N.DENOISING_END,N.DENOISER_LOADING,N.UPSCALING_START,N.UPSCALING_PROGRESS,N.UPSCALING_END,N.RESOLUTION_CHANGED]),this._setupAutoExposureListener(),this.animationManager.wakeCallback=()=>this.wake(),this.animationManager.applyPoseCallback=e=>this._applyAnimationPose(e),this._forwardEvents(this.animationManager,[N.ANIMATION_STARTED,N.ANIMATION_PAUSED,N.ANIMATION_STOPPED]),this._addTrackedListener(this.animationManager,N.ANIMATION_PAUSED,()=>{this._animRefitInFlight=!1,this._refreshMovedEmitters()}),this._addTrackedListener(this.animationManager,N.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`,`nrd:output`]}_settingsBindings(){let e=super._settingsBindings();return{...e,applyExposure:t=>{this.stages.autoExposure?this.stages.autoExposure.setCompensation(t):e.applyExposure(t),this.stages.compositor?.setBackdropExposure(t)},onCameraProjection:e=>{this.cameraManager.applyProjection(e),e===`equirectangular`&&this.denoisingManager?.requiresMotionVectors?this.denoisingManager.setDenoiserStrategy(`oidn`):this.denoisingManager?._syncGBufferStages?.()}}}_beginFrame(){if(this.timeline.update(),this.cameraManager.updateControls(),this._updateExposure(),this._applyPendingRenderScale(),this.animationManager?.isPlaying&&!this._animRefitInFlight){let e=this.animationManager.update();e&&(this._animRefitInFlight=!0,this.refitBVH(e).catch(e=>NR.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.stages.autoExposure?.enabled&&this._refreshFinished(),this.denoisingManager.onRenderComplete({isStillComplete:()=>this.completion.renderCompleteDispatched,context:this.pipeline?.context})}_settling(){return!!this.stages.autoExposure?.settling}_displayGain(){let e=this.stages.localExposure;e?.wantsBuild&&e.build(this.pipeline.context);let t=e?.toneGain()??null;if(this.pipeline?.context.getState(`pathtracer:backdrop`)!==`color`)return t;let{toneMappingExposure:n,toneMapping:r}=this.renderer;return{...t,backdrop:Ts(this.settings.get(`exposure`)??1,n,r)}}setLocalExposure(e){let t=this.stages.localExposure;t&&(t.setEnabled(e),this.stages.compositor.setDisplayGain(e?(e,n)=>t.gainNode(e,n):null),this.refreshFrame())}setLocalExposureParams(e){this.stages.localExposure?.updateParameters(e)}_finishImage(){let e=this.stages.autoExposure;return e?.enabled?e.meter(this.pipeline.context).then(()=>e.advance(1/0)):null}getProvenance(){let e=super.getProvenance(),t=this.stages.autoExposure,n=this.stages.localExposure;return e.exposure={auto:t?.enabled?{exposure:t.getExposure(),strength:t.strength,metering:t.metering,keyValue:t.keyValue}:null,local:n?.enabled?{highlightContrast:n.highlightContrast,shadowContrast:n.shadowContrast,detailStrength:n.detailStrength}:null},e}_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?.setEnabled(!1),this.denoisingManager?.setContinuousDenoise(!1);return}t.autoFocusMode!==void 0&&this.cameraManager?.setAutoFocusMode(t.autoFocusMode),t.autoExposure!==void 0&&this.stages.autoExposure?.setEnabled(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 qw(this)}async importSceneState(e,t){return await Zw(this,e,t)}_dispatchCamerasUpdated(){this.dispatchEvent({type:N.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.takeMoveRanges()),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.matrixWorldOf(r))}}_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?st:ct;this.denoisingManager?.setCadenceSuspended(n),this.timeline.stop(),this.cameraManager.controls.enabled=!n,this.stages.autoExposure&&(this.stages.autoExposure.holdSamples=n?8:0),this.settings.setMany(it(r),{silent:!0,source:Av.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(X.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:N.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:N.ANIMATION_FINISHED})}}this.transformManager?.setMeshData(this._sdf.meshes)}_setupDenoisingManager(){this.denoisingManager=new ww({renderer:this.renderer,mainCanvas:this.canvas,stages:{pathTracer:this.stages.pathTracer,normalDepth:this.stages.normalDepth,motionVector:this.stages.motionVector,nrd:this.stages.nrd,autoExposure:this.stages.autoExposure,compositor:this.stages.compositor},pipeline:this.pipeline,getExposure:()=>this.settings.get(`exposure`)??1,getSaturation:()=>this.settings.get(`saturation`)??1,getDisplayGain:()=>this._displayGain(),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(){let e=this.stages.autoExposure;e&&(e.setCompensation(this.settings.get(`exposure`)??1),this.stages.compositor.setBackdropExposure(this.settings.get(`exposure`)??1),this.stages.localExposure&&(this.stages.localExposure.onChange=()=>this._refreshFinished()),e.onChange=()=>this._refreshFinished(),this._addTrackedListener(this.cameraManager,N.CAMERA_SWITCHED,()=>e.resetHistory()),e.on(`autoexposure:updated`,({exposure:e,autoExposure:t,targetExposure:n,luminance:r})=>{this.dispatchEvent({type:N.AUTO_EXPOSURE_UPDATED,exposure:e,autoExposure:t,targetExposure:n,luminance:r})}))}_refreshFinished(){this.completion.renderCompleteDispatched&&(this._needsDisplayRefresh=!0,this.wake())}_updateExposure(){let e=this.stages.localExposure;e?.wantsBuild&&this.completion.renderCompleteDispatched&&e.build(this.pipeline.context);let t=this.stages.autoExposure;if(!t?.enabled)return;this._noteExposureView();let n=this.cameraManager.afScreenPoint;t.metering===`spot`&&(t.meteringPoint.x!==n.x||t.meteringPoint.y!==n.y)&&t.updateParameters({meteringPoint:n}),t.wantsMetering&&this.completion.renderCompleteDispatched&&t.meter(this.pipeline.context),t.update()&&(this._needsDisplayRefresh=!0)}_noteExposureView(){let{matrixWorld:e,projectionMatrix:t}=this.camera,n=this._exposureView;n?.view.equals(e)&&n.projection.equals(t)||(this._exposureView={view:e.clone(),projection:t.clone()},n&&this.stages.autoExposure?.noteViewChanged())}async _setupOverlayManager(){this.overlayManager=new Nw(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 FR(e){let t=await LR(e);try{return await IR(t,e)}finally{t.dispose()}}async function IR(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 LR({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 PR(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}}Sv(),yn(),F(),lt(),de();var RR=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=st.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`);let _=d.stages.autoExposure?.enabled?d.stages.autoExposure:null;_&&(_.instant=!1),d.settings.setMany({maxSamples:i,renderLimitMode:`frames`},{silent:!0,reset:!1}),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(),_&&d._noteExposureView(),await this._accumulateFrame(d),this._cancelled||(_&&(await _.meter(d.pipeline.context),_.advance(e===Math.max(0,s)?1/0:h),d._presentDisplay()),a&&d.denoisingManager?.finalDenoise&&await this._waitForDenoise(d),this._cancelled))break;let u=d.getCanvas();if(u&&c){let t=await createImageBitmap(u);await c(t,e,m),t.close()}let p={frame:e+1,totalFrames:m,percent:(e+1)/m*100};l?.(p),d.dispatchEvent({type:N.VIDEO_RENDER_PROGRESS,...p})}}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:N.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&&(ue({samples:L(t)}),await new Promise(e=>setTimeout(e,0)))}}_waitForDenoise(e){return new Promise(t=>{let n,r=()=>{e.removeEventListener(N.DENOISING_END,i),clearTimeout(n)},i=()=>{r(),t()};n=setTimeout(()=>{console.warn(`VideoRenderManager: Denoise timed out, skipping`),r(),t()},3e4),e.addEventListener(N.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(it(st)),`renderLimitMode`];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,instantExposure:t.stages.autoExposure?.instant,holdExposureSamples:t.stages.autoExposure?.holdSamples,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,t.stages.autoExposure&&(t.stages.autoExposure.instant=e.instantExposure??!1,t.stages.autoExposure.holdSamples=e.holdExposureSamples??0),e.view&&t.cameraManager.applyPose(e.view),t.denoisingManager?.setCadenceSuspended(!1),t.animationManager?.stop(),t.reset(),t.wake()}};O(),F(),an(),ui(),Fr(),eA(),Ov(),wc(),qn(),xy(),Ae(),lt(),Ft(),Do(),QC(),fw(),vs(),e.ARCHIVE_FORMATS=wv,e.AUTO_EXPOSURE_DEFAULTS=nx,e.AUTO_FOCUS_DEFAULTS=bS,e.AnimationManager=Fw,e.BVH_LEAF_MARKERS=Tt,e.CameraManager=ES,e.CameraTrack=AS,e.ColorManagement=EO,e.DEFAULT_LUT_SIZE=BD,e.DEFAULT_MAX_EV=zD,e.DEFAULT_MIN_EV=RD,e.DEFAULT_SUN_PATH=xi,e.DEFAULT_VIEW=_s,e.DEFAULT_WORKING_SPACE=Zr,e.DENOISER_DEFAULTS=sb,e.DENOISER_STRATEGIES=tb,e.DOWNLOAD_POLICY=Z_,e.DenoisingManager=ww,e.DownloadCache=av,e.ENGINE_AREAS=mn,e.ENGINE_DEFAULTS=H,e.EngineEvents=N,e.EngineIssueError=nn,e.GoboManager=NS,e.IESManager=GS,e.INTERACTIVE_RENDER_CONFIG=ct,e.ISSUE_CODES=X,e.ISSUE_SEVERITY=tn,e.InteractionManager=rS,e.IssueLog=rn,e.LEGACY_EVENT_NAMES=P,e.LOCAL_EXPOSURE_DEFAULTS=Ax,e.LOG_LEVELS=xe,e.LightManager=zy,e.Logger=Oe,e.MATERIAL_DEFAULTS=ot,e.MATERIAL_VALUE_SOURCE=Un,e.MAX_RESERVABLE_RENDER_SIZE=je,e.MAX_SCENE_BYTES=bo,e.MAX_TABLE_TRANSFORMS=us,e.MemoryLedger=Eo,e.NRD_DEFAULTS=ib,e.NRD_HIT_DIST_A=nb,e.NRD_HIT_DIST_B=rb,e.NRD_PRESET_KEYS=ab,e.NRD_QUALITY_PRESETS=ob,e.OCIO_VIEW_BASE=ls,e.OverlayManager=Nw,e.PRODUCTION_RENDER_CONFIG=st,e.PathTracerApp=PR,e.PipelineContext=F_,e.RETOUCH_DEFAULTS=rw,e.RETOUCH_MAX_PIXELS=aw,e.RETOUCH_RANGES=ow,e.RayzeeRenderer=Qy,e.RenderPipeline=q_,e.RenderSettings=jv,e.RenderStage=j,e.SAFE_SCENE_BYTES=yo,e.SCENE_STATE_VERSION=Bw,e.SETTING_SOURCE=Av,e.SKY_DEFAULTS=Ci,e.SR_MAX_INPUT=qC,e.SR_SCALE=GC,e.STORAGE_KIND=pn,e.StageExecutionMode=A,e.StorageManager=ek,e.TRIANGLE_DATA_LAYOUT=K,e.TimelineManager=MS,e.TransformManager=Rw,e.VERSION=Cc,e.VIEW_TRANSFORMS=hs,e.VRAMTracker=ef,e.VideoRenderManager=RR,e.acquireLock=NO,e.addAllOcioViews=ZD,e.addOcioView=XD,e.addViewTransform=rs,e.applyMatrixRGBA8=SD,e.bakeLut=kD,e.bufferBytes=Qd,e.buildOcioView=qD,e.buildToneMapWGSL=ss,e.cachedObjectURL=cv,e.canvasColorSpaceFor=SO,e.captureHeadless=IR,e.clearBindingAuditFindings=H_,e.clearInputOverrides=fO,e.configureAssets=ai,e.configurePlatform=Er,e.convertColor=lD,e.convertEncodedRGBA8=_D,e.convertPixelsF32=uD,e.createLogger=ve,e.dayOfYearForMonth=Xr,e.deriveAlphaMode=jn,e.describeAdapter=Zy,e.displayCanvasFit=AE,e.estimateSceneBytes=lo,e.extractMatrix=CD,e.extractSceneMetadata=vy,e.fetchFile=ov,e.fileIdentity=pv,e.findNativeLinearSpace=TO,e.fmt=V,e.folderIdentity=mv,e.fromPortable=rr,e.getActiveColorManagement=$r,e.getAssetConfig=si,e.getBindingAuditFindings=V_,e.getPlatform=Dr,e.getRegistryVersion=Zo,e.getViewTransform=$o,e.hasColorSpace=TD,e.heldLockNames=PO,e.identityKey=hv,e.isColorManaged=DO,e.isDataSpace=wD,e.isDataTexture=vO,e.linearToSrgb=pD,e.listFileRules=hO,e.listInputOverrides=pO,e.listViewTransforms=es,e.localFolder=Cv,e.makeCpuSampler=FD,e.measureBakeError=LD,e.nameFromUrl=tv,e.onRegistryChange=Qo,e.openHeadless=LR,e.openStorage=lk,e.openZip=Kk,e.parseSceneMetadata=_y,e.probeAddressSpace=fo,e.readZipDirectory=Uk,e.removeViewTransform=is,e.renderHeadless=FR,e.renderUpscaled=HC,e.resolveInputSpace=_O,e.sameIdentity=gv,e.setActiveColorManagement=ei,e.setBindingAudit=B_,e.setInputOverride=dO,e.srgbToLinear=fD,e.sunPosition=Jr,e.textureBytes=$d,e.textureInputSpace=xO,e.timeForSunElevation=Yr,e.toPortable=nr});
|
|
1427
|
+
`}function tO({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}}an(),vs();var nO=-12.47393,rO=12.5260688117,iO=65,aO=null,oO=new Map;function sO(e){aO=e}function cO(){let e=sD();if(!e)throw Error(`load an OCIO config first`);if(!e.config)throw Error(`OCIO runtime exposes no Config handle`);return e.config}function lO({source:e,display:t,view:n,look:r,context:i,decodeFrom:a=null,decodeTo:o=null}){let s=cO(),c=i?{context:i}:void 0;return!r&&!o?s.createDisplayViewProcessor({source:e,display:t,view:n,...i?{context:i}:{}}):s.createGroupTransformProcessor([...r?[{type:`look`,source:e,destination:e,looks:r}]:[],{type:`displayView`,source:e,display:t,view:n},...o?[{type:`colorSpace`,source:a,destination:o}]:[]],c)}function uO(e,t,n){let r=e.viewsByDisplay[t]?.find(e=>e.name===n)?.colorSpace;return!r||r===`<USE_DISPLAY_NAME>`?t:r}var dO=new WeakMap,fO=e=>Math.sign(e)*(Math.abs(e)<=.04045?Math.abs(e)/12.92:((Math.abs(e)+.055)/1.055)**2.4),pO=(e,t)=>[0,3,6].map(n=>e[n]*t[0]+e[n+1]*t[1]+e[n+2]*t[2]);function mO(e){let[t,n,r,i,a,o,s,c,l]=e,u=a*l-o*c,d=o*s-i*l,f=i*c-a*s,p=t*u+n*d+r*f;return[u,r*c-n*l,n*o-r*a,d,t*l-r*s,r*i-t*o,f,n*s-t*c,t*a-n*i].map(e=>e/p)}function hO(e){let t=cD();if(!t)return{fit:AE(e),wide:!1,convertible:!1};let n=dO.get(t);if(n||dO.set(t,n=new Map),n.has(e))return n.get(e);let r=t.colorSpaces.find(t=>t.name===e||t.aliases?.includes(e)),i=TO(),a={fit:AE(e),wide:!1,convertible:!1};if(i&&!r?.isData&&r?.referenceSpace!==0){let t=[[1,0,0],[0,1,0],[0,0,1],[.5,.5,.5],[.2,.7,.1],[.9,.05,.4],[.02,.02,.02],[1,1,1]],n=new Float32Array(t.flatMap(e=>[...e,1])),r=cO().createColorSpaceProcessor(e,i);try{r.applyRGBAF32(n)}finally{r.dispose()}let o=e=>[n[e*4],n[e*4+1],n[e*4+2]],s=e=>{let n=mO(CO[e]);return t.every((e,t)=>pO(n,e.map(fO)).every((e,n)=>Math.abs(o(t)[n]-e)<=.002*Math.max(1,Math.abs(e))))},c=[0,1,2].some(e=>{let t=pO(CO.srgb,o(e));return Math.min(...t)<-.001*Math.max(...t.map(Math.abs))});a={fit:[`srgb`,`display-p3`].find(s)??null,wide:c,convertible:!0}}return n.set(e,a),a}function gO(e,t){let n=CO[t];for(let t=0;t<e.length;t+=4){let r=e[t],i=e[t+1],a=e[t+2];e[t]=wO(n[0]*r+n[1]*i+n[2]*a),e[t+1]=wO(n[3]*r+n[4]*i+n[5]*a),e[t+2]=wO(n[6]*r+n[7]*i+n[8]*a)}}function _O({source:e,display:t,view:n,look:r,context:i,canvas:a=null,size:o,minEv:s,maxEv:c}){let l=lO({source:e,display:t,view:n,look:r,context:i,decodeFrom:a?uO(cD(),t,n):null,decodeTo:a&&TO()}),u=e=>{l.applyRGBAF32(e),a&&gO(e,a)};try{let e=JD(qD({size:o,minEv:s,maxEv:c,apply:u}));return{half:e,error:tO({sampler:$D({data:e,size:o,minEv:s,maxEv:c}),apply:u})}}finally{l.dispose()}}function vO({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 yO({display:e,view:t,look:n=null,context:r=null,source:i=null,size:a=65,minEv:o=nO,maxEv:s=rO,id:c=null,name:l=null}={}){let u=cD();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(`, `)}`);let{fit:m,wide:h,convertible:g}=hO(uO(u,e,t)),_=!m&&g,v=m??(_&&h?`display-p3`:`srgb`);!m&&!TO()&&!VE(uD(),e,t)&&aO?.warn(X.VIEW_TRANSFORM_DISPLAY_MISMATCH,`"${e}" is no canvas colour space and the config cannot convert it, so the screen shows its codes as sRGB`,{display:e,view:t});let{half:y,error:b}=_O({source:f,display:e,view:t,look:n,context:r,canvas:_?v:null,size:a,minEv:o,maxEv:s});return SO({id:c,half:y,error:b,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,canvas:v,emulated:_}})}function bO(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,canvas:g,emulated:_}=e;return SO({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,canvas:g??AE(o)??`srgb`,emulated:!!_,baked:{fingerprint:m??null,ocioVersion:h??null}}})}function xO(e,t){let n=new r.Data3DTexture(e,t,t,t);return n.format=r.RGBAFormat,n.type=r.HalfFloatType,n.minFilter=r.NearestFilter,n.magFilter=r.NearestFilter,n.wrapS=n.wrapT=n.wrapR=r.ClampToEdgeWrapping,n.needsUpdate=!0,n}function SO({id:e,name:t,half:n,error:r,ocio:i}){let{size:a,minEv:o,maxEv:s}=i,c=$D({data:n,size:a,minEv:o,maxEv:s}),l=e??ns(),u=`TM_OCIO_${l}`,d=`tm_ocio_${l}`,f=oO.get(l),p=f&&f.size===a&&f.minEv===o&&f.maxEv===s,m,h;return p?(m=f.texture,m.image.data=n,m.needsUpdate=!0,h=f.tsl):(f?.texture.dispose(),m=xO(n,a),h=vO({texture:m,size:a,minEv:o,maxEv:s})),oO.set(l,{texture:m,tsl:h,size:a,minEv:o,maxEv:s}),{id:l,name:t,wgslConst:u,source:`ocio`,outputEncoded:!0,appliesExposure:!0,cpu:(e,t,n,r,i)=>c(e*r,t*r,n*r,i),wgsl:eO({fnName:d,texName:`${u.toLowerCase()}_tex`,size:a,minEv:o,maxEv:s}),call:`${d}( c )`,tsl:h,table:{data:n,size:a,texture:m},error:r,ocio:i}}var CO=Object.freeze({srgb:[3.2409699419045226,-1.537383177570094,-.4986107602930034,-.9692436362808796,1.8759675015077202,.04155505740717559,.05563007969699366,-.20397695888897652,1.0569715142428786],"display-p3":[446124/178915,-333277/357830,-72051/178915,-14852/17905,63121/35810,423/17905,11844/330415,-50337/660830,316169/330415]});function wO(e){let t=Math.abs(e),n=t<=.0031308?12.92*t:1.055*t**(1/2.4)-.055;return e<0?-n:n}function TO(){let e=cD()?.colorSpaces.find(e=>e.encoding===`display-linear`)?.name,t=(lD()?.split(/^display_colorspaces:[^\n]*$/m)[1]?.split(/^\S/m)[0]??``).split(/-\s*!<ColorSpace>/).slice(1),n=t.find(e=>/^\s*encoding:\s*display-linear\s*$/m.test(e))??t.find(e=>!/_display_reference:/.test(e)),r=e??n?.match(/^\s*name:\s*(.+?)\s*$/m)?.[1].replace(/^["']|["']$/g,``)??null;return r&&/xyz/i.test(r)?r:null}function EO({display:e,view:t,look:n=null,context:r=null,source:i=null,canvas:a=`srgb`,for:o=null,size:s=65,minEv:c=nO,maxEv:l=rO}={}){let u=cD();if(!u)throw Error(`load an OCIO config first`);let d=i??u.roles.find(e=>e.name===`scene_linear`)?.colorSpace;if(!TO())throw Error(`the config names no display-referred CIE XYZ space to decode its displays in`);if(!CO[a])throw Error(`no encoding for a "${a}" canvas`);let{half:f,error:p}=_O({source:d,display:e,view:t,look:n,context:r,canvas:a,size:s,minEv:c,maxEv:l});return OO({name:n?`${t} + ${n} (${e})`:`${t} (${e})`,half:f,error:p,ocio:{display:e,view:t,look:n,context:r,source:d,configId:u.id,size:s,minEv:c,maxEv:l,canvas:a,for:o}})}function DO(e){let{name:t,data:n,error:r,configId:i,display:a,view:o,look:s,context:c,source:l,size:u,minEv:d,maxEv:f,canvas:p,for:m}=e;return OO({name:t,half:n,error:r,ocio:{display:a,view:o,look:s??null,context:c??null,source:l,configId:i,size:u,minEv:d,maxEv:f,canvas:p??`srgb`,for:m??null}})}function OO({name:e,half:t,error:n,ocio:r}){let{size:i,minEv:a,maxEv:o}=r,s=xO(t,i);return{name:e,source:`ocio`,error:n,ocio:r,table:{data:t,size:i,texture:s},tsl:vO({texture:s,size:i,minEv:a,maxEv:o}),dispose:()=>s.dispose()}}function kO(e){return rs(yO(e))}function AO({display:e=null,look:t=null,context:n=null,source:r=null,size:i=65}={}){let a=cD();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(kO({display:o,view:e.name,look:t,context:n,source:r,size:i}))}catch(t){l.push({view:e.name,reason:t.message}),aO?.warn(X.VIEW_TRANSFORM_BAKE_FAILED,`could not bake "${e.name}" (${o}): ${t.message}`,{display:o,view:e.name})}}return{added:c,skipped:l}}function jO(e){let t=oO.get(e);t&&(t.texture.dispose(),oO.delete(e))}function MO(e=null){for(let t of hs.values())t.source===`ocio`&&!e?.has(t.id)&&t.table?.texture?.dispose?.();for(let[t,n]of oO)e?.has(t)||(n.texture.dispose(),oO.delete(t))}var NO=[82,90,86,84],PO=`rayzee-baked-view`,FO=15360;async function IO(e,t){return new Uint8Array(await new Response(new Blob([e]).stream().pipeThrough(t)).arrayBuffer())}async function LO(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]!==FO)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,canvas:m,emulated:h,for:g}=e.ocio,_=new TextEncoder().encode(JSON.stringify({format:PO,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,...h||g||m&&m!==`srgb`?{canvas:m,emulated:!!h}:{},...g?{for:g}:{},...t})),v=new Uint8Array(8+_.length+s.length);return v.set(NO,0),new DataView(v.buffer).setUint32(4,_.length,!0),v.set(_,8),v.set(s,8+_.length),await IO(v,new CompressionStream(`gzip`))}async function RO(e){let t=await IO(e,new DecompressionStream(`gzip`));if(t.length<8||NO.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!==PO||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]=FO;return{...r,data:l}}async function zO({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(`
|
|
1428
|
+
`)))}`}var BO=[],VO=0;function HO(){return VO}function UO(){VO++}function WO(e,t){BO.unshift({match:e,colorSpace:t}),VO++}function GO(){BO.length!==0&&(BO.length=0,VO++)}function KO(){return BO.map(e=>({match:String(e.match),colorSpace:e.colorSpace}))}function qO(e){if(!e)return null;for(let t of BO)if(t.match instanceof RegExp?t.match.test(e):e.includes(t.match))return t.colorSpace;return null}function JO(){return cD()?.fileRules.map(e=>({index:e.index,name:e.name,colorSpace:e.colorSpace,pattern:e.pattern,extension:e.extension,regex:e.regex}))??[]}function YO(e){let t=cD();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 XO(e,{threeColorSpace:t=null}={}){if(!cD())return null;let n=qO(e);if(n)return{colorSpace:n,via:`override`,rule:null};let r=sD();if(r&&e){let t=r.matchFileRule(e);if(t&&!t.isDefaultRule&&UD(t.colorSpace))return{colorSpace:t.colorSpace,via:`rule`,rule:{index:t.ruleIndex,name:t.ruleName}}}let i=YO(t);if(i)return{colorSpace:i,via:`three`,rule:null};let a=sD();if(a&&e){let t=a.matchFileRule(e);if(t&&UD(t.colorSpace))return{colorSpace:t.colorSpace,via:`rule`,rule:{index:t.ruleIndex,name:t.ruleName,isDefault:t.isDefaultRule}}}return null}function ZO(e){if(!e)return!1;if(e.colorSpace===r.NoColorSpace)return!0;let t=e.userData?.ocioColorSpace;return!!(t&&HD(t))}function QO(e,t){return t??e.userData?.sourcePath??(e.name||null)??e.image?.src??null}function $O(e,t=null){if(!cD()||!e)return null;let n=e.userData?.ocioColorSpace;return n?UD(n)?{colorSpace:n,via:`tag`,rule:null}:null:ZO(e)?null:XO(QO(e,t),{threeColorSpace:e.colorSpace})}function ek(e,t=null){return $O(e,t)?.colorSpace??null}an(),vs(),tr();function tk(e){return AE(e)??`srgb`}function nk(e){return e?.source===`ocio`?e.ocio.canvas??tk(e.ocio.display):`srgb`}var rk=4;function ik(e,t){return JSON.stringify([e.configId,e.display,e.view,e.look??null,e.source,e.context??null,t])}var ak=[`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`],ok=/^(lin(ear)?[\s_-]*(rec\.?\s*|bt\.?\s*)?709|linear[\s_-]*\(?srgb\)?$|utility - linear - (srgb|rec\.?709))/i;function sk(e){if(!e)return null;let t=e.colorSpaces.filter(e=>!e.isData),n=e=>[e.name,...e.aliases??[]];for(let e of ak){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=>ok.test(e)))?.name??null}var ck=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=gs,this._fingerprint=null,this._hdrOutput=!1,this._canvasView=null,this._canvasReason=null,this._bakedCanvasViews=new Map,this._recentCanvasViews=new Map,sO(e),this._offRegistry=Qo(()=>{this._renderer&&os(this._renderer),this._emit(`transforms`)}),ti(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 rD()}async loadConfig({adoptWorkingSpace:e=!1,registerViews:t=!0,display:n=null,lutSize:r,...i}={}){await nD();let a=zO(i).catch(()=>null),o=await this._bakedViewsFrom(i.builtin??i.id??null,a),s;try{s=await iD(i)}catch(e){throw this._issues?.warn(X.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,UO(),ED(),this._context=null;let c=this._workingSpace;if(e?this._workingSpace=s.sceneLinear:c&&!UD(c)&&(this._workingSpace=null),sk(cD())||this._issues?.warn(X.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}=AO({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),this._updateCanvasView(),s}unloadConfig(){this.workingSpaceAdopted&&this._issues?.warn(X.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(),aD(),ED(),GO(),UO(),this._fingerprint=null,this._workingSpace=null,this._activeView=null,this._exportSpace=null,this._context=null,Jn(null),this._applyRendererOutputColorSpace(),this._updateCanvasView(),this._emit(`config`,null),this._emit(`workingSpace`,this.workingSpace)}_releaseViews(e=null){MO(e),as(e);for(let t of this._lastUsed.keys())e?.has(t)||this._lastUsed.delete(t);this._renderer&&$o(this._renderer.toneMapping)===null&&(this._renderer.toneMapping=$o(this._lastBuiltin)?this._lastBuiltin:gs,this._activeView=null,this._applyRendererOutputColorSpace(),this._updateCanvasView())}async _bakedViewsFrom(e,t){let n=[...hs.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 RO(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=uD();if(r&&(r.id!==n.configId||await this._fingerprint!==n.fingerprint))throw Error(`baked view is from "${n.configId}", not the loaded "${r.id}"`);if(n.for){let e=ik({...n,...n.for},n.canvas??`srgb`),t=this._bakedCanvasViews.get(e);return this._bakedCanvasViews.set(e,DO(n)),t&&t!==this._canvasView?.table&&t.dispose(),this._updateCanvasView(),[...hs.values()].find(e=>e.source===`ocio`&&e.ocio.display===n.for.display&&e.ocio.view===n.for.view&&(e.ocio.look??null)===(n.look??null))??null}let i=[...hs.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(),rs(bO(n,i?.id??null))}async saveBakedView(e,{hdr:t=!1}={}){let n=$o(e);if(n?.source!==`ocio`)throw Error(`no OCIO view with id ${e}`);let r=uD(),i={configId:r?.id??n.ocio.configId,fingerprint:(r?await this._fingerprint:null)??n.ocio.baked?.fingerprint??null,ocioVersion:r?.ocioVersion??n.ocio.baked?.ocioVersion??null};if(!t)return await LO(n,i);let a=nk(n),o=ik(n.ocio,a),s=this._canvasView?.key===o?this._canvasView.table:this._bakedCanvasViews.get(o)??this._recentCanvasViews.get(o),c=s?null:r&&qE(r,n.ocio.display,n.ocio.view);if(!s&&!c)throw Error(`"${n.name}" has no HDR version${r?` in this config`:` without its config loaded`}`);let l=s??this._buildCanvasView(n,c,a);try{return await LO(l,i)}finally{l!==s&&l.dispose()}}get hasConfig(){return oD()}describe(){return uD()}get workingSpace(){return this._workingSpace?this._workingSpace:oD()?this.nativeLinearSpace??uD()?.sceneLinear??`Linear Rec.709 (sRGB)`:Zr}get workingSpaceAdopted(){return this._workingSpace!==null}setWorkingSpace(e){if(e!==null){if(!oD())throw Error(`load an OCIO config before choosing a working space`);if(!UD(e))throw Error(`config has no colour space "${e}"`)}(this._workingSpace??null)!==(e??null)&&(this._workingSpace=e,bD(),this._publishWorkingMatrix(),this._rebakeViews(),this._emit(`workingSpace`,this.workingSpace))}matrixToWorking(e){return oD()?VD(e,this.workingSpace,{context:this._context}):null}listViews(){return es()}get activeView(){return this._activeView}setActiveView(e){let t=$o(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._updateCanvasView(),this._emit(`view`,t),t}setView({display:e,view:t,look:n=null,size:r}={}){if(!oD())throw Error(`load an OCIO config first`);let i=[...hs.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??kO({display:e,view:t,look:n,context:this._context,source:this.workingSpace,...r?{size:r}:{}});return this.setActiveView(a.id),$o(a.id)}_makeRoomForTable(){if(ts()<12)return;let e=this._renderer?.toneMapping??this._activeView?.id??null,t=[...hs.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&&(jO(t.id),is(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,oD()&&(this._context&&sD()?.invalidateContext(this._context),bD(),this._rebakeViews()),this._emit(`context`,this._context))}get context(){return this._context}_isStale(e){return e.source!==`ocio`||!oD()?!1:e.ocio.source!==this.workingSpace||JSON.stringify(e.ocio.context??null)!==JSON.stringify(this._context??null)}_rebakeView(e){try{let t=kO({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(X.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:$o(e);if(!t||!this._isStale(t))return;let n=this._rebakeView(t);n&&(this._activeView={...n.ocio,id:n.id,name:n.name}),this._updateCanvasView()}attachRenderer(e){this._renderer=e,$o(e.toneMapping)?.source===`builtin`&&(this._lastBuiltin=e.toneMapping);let t=os(e);return this._applyRendererOutputColorSpace(),this._updateCanvasView(),t}_applyRendererOutputColorSpace(){if(!this._renderer)return;let e=$o(this._renderer.toneMapping);this._renderer.outputColorSpace=e?.outputEncoded?r.LinearSRGBColorSpace:r.SRGBColorSpace,this._applyCanvasColorSpace(nk(e))}_applyCanvasColorSpace(e){this._canvasColorSpace=e;let t=(this._renderer?.domElement)?.getContext?.(`webgpu`);if(!t?.configure)return;if(!t.__rayzeeConfigure){let e=t.configure.bind(t);t.__rayzeeConfigure=e,t.configure=n=>e({...n,colorSpace:t.__rayzeeColorSpace??n.colorSpace})}t.__rayzeeColorSpace=e;let n=t.getConfiguration?.();if(!(!n||n.colorSpace===e))try{t.configure({...n,colorSpace:e})}catch(t){this._issues?.warn(X.VIEW_TRANSFORM_DISPLAY_MISMATCH,`the canvas could not be set to ${e}: ${t.message}`,{colorSpace:e})}}setHdrOutput(e){!!e!==this._hdrOutput&&(this._hdrOutput=!!e,this._updateCanvasView())}get hdrOutput(){return this._hdrOutput}get canvasColorSpace(){return this._canvasColorSpace??`srgb`}displayFit(e){return oD()?hO(e).fit:AE(e)}get canvasTransform(){return this._canvasView?.table?.tsl??null}_canvasOnScreen(){let e=this._renderer?.domElement;return typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement||typeof OffscreenCanvas<`u`&&e instanceof OffscreenCanvas}_canvasPlan(){let e=this._renderer?$o(this._renderer.toneMapping):null;if(!e||!this._hdrOutput)return{reason:null};if(e.source!==`ocio`)return e.id===r.NoToneMapping?{key:`none`,table:null,hdr:!0}:{reason:`no-hdr-version`};let t=uD();if(PE(t,e.ocio.display))return{key:`own`,table:null,hdr:!0};let n=nk(e),i=ik(e.ocio,n),a=this._bakedCanvasViews.get(i);if(a)return{key:i,table:a,hdr:!0};let o=t&&qE(t,e.ocio.display,e.ocio.view);return o?{key:i,target:o,canvas:n,view:e,hdr:!0}:{reason:t?`no-hdr-version`:`needs-config`}}_buildCanvasView(e,t,n){let{look:r,context:i,source:a,size:o,display:s,view:c}=e.ocio;return EO({...t,look:r,context:i,source:a,size:o,canvas:n,for:{display:s,view:c}})}_updateCanvasView(){let e=this._canvasPlan(),t=this._canvasView,n=e.table??(e.key&&e.key===t?.key?t.table:null)??this._recentCanvasViews.get(e.key)??null;if(e.target&&!n)try{n=this._buildCanvasView(e.view,e.target,e.canvas)}catch(t){this._issues?.warn(X.VIEW_TRANSFORM_BAKE_FAILED,`could not bake how the screen shows "${e.view.name}": ${t.message}`,{...e.target}),this._setCanvasView(null,`bake-failed`);return}e.target&&this._rememberCanvasView(e.key,n),this._setCanvasView(e.key?{key:e.key,table:n,hdr:e.hdr}:null,e.reason??null)}_rememberCanvasView(e,t){let n=this._recentCanvasViews;for(n.delete(e),n.set(e,t);n.size>rk;){let[e,r]=n.entries().next().value;n.delete(e),r!==this._canvasView?.table&&r!==t&&r.dispose()}}_setCanvasView(e,t){let n=this._canvasView,i=new Set([...this._bakedCanvasViews.values(),...this._recentCanvasViews.values()]);n?.table&&n.table!==e?.table&&!i.has(n.table)&&n.table.dispose();let a=!!e?.hdr&&this._canvasOnScreen(),o=t??(e?.hdr&&!a?`no-screen`:null),s=(n?.table??null)!==(e?.table??null)||!!n?.hdr!=!!e?.hdr||this._canvasReason!==o;this._canvasView=e,this._canvasReason=o;let c=this._renderer?.backend,l=a?r.HalfFloatType:void 0;c?.parameters&&c.parameters.outputType!==l&&(c.parameters.outputType=l,c.updateSize?.()),s&&this._emit(`canvas`,this.canvasTransform)}resolveInput(e,t){return XO(e,t)}textureSpace(e,t){return ek(e,t)}resolveTexture(e,t){return $O(e,t)}describeTextureSpace(e){let t=e?.userData??{},n=t.ocioColorSpace??t.__rayzeeColorSpaceChoice??null,i=null,a=t.__rayzeeOriginalColorSpace??e?.colorSpace;return oD()&&(i=$O({...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 oD()?`${uD()?.id}|${this.workingSpace}|${HO()}|${JSON.stringify(this._context)}`:`-`}overrideInput(e,t){WO(e,t)}fileRules(){return JO()}toWorkingPixels(e,t){return!oD()||!t?e:OD(e,t,this.workingSpace,{context:this._context})}get nativeLinearSpace(){return sk(cD())}_publishWorkingMatrix(){let e=$r();e!==null&&e!==this||Jn(oD()?this.primariesMatrixToWorking():null,this.workingSpace)}primariesMatrixToWorking(){if(!oD()||!this.workingSpaceAdopted)return null;let e=this.nativeLinearSpace;if(!e||e===this.workingSpace)return null;let t=VD(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 Zn(e)}convertLinearTriples(e,t,n){return Qn(e,t,n)}convertTexturePixels(e,{space:t=null}={}){if(!oD())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)OD(n,i,a,{context:this._context}),o=!0;else if(n instanceof Uint16Array){let e=YD(n);OD(e,i,a,{context:this._context}),n.set(JD(e)),o=!0}else if(n instanceof Uint8Array||n instanceof Uint8ClampedArray)FD(n,i,a,{context:this._context,inputEncoding:`srgb`,outputEncoding:`srgb`}),o=!0;else return this._issues?.warn(X.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(!oD())return!1;if(t)return t===this.workingSpace?!1:(FD(e,t,this.workingSpace,{context:this._context,inputEncoding:`raw`,outputEncoding:n}),!0);let r=this.primariesMatrixToWorking();return r?(BD(e,r,n),!0):!1}toWorkingColor(e,t){return!oD()||!t?[e[0],e[1],e[2]]:DD(e,t,this.workingSpace,{context:this._context})}convert(e,t,n){return DD(e,t,n,{context:this._context})}get exportSpace(){return this._exportSpace}setExportSpace(e){if(e!=null){if(!oD())throw Error(`load an OCIO config before choosing an export space`);if(!UD(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||!oD()?{rgba:e,colorSpace:this.workingSpace}:(OD(e,this.workingSpace,n,{context:this._context}),{rgba:e,colorSpace:n})}status(){let e=uD(),t=this._renderer?$o(this._renderer.toneMapping):null,n=!!this._canvasView?.hdr&&this._canvasOnScreen();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:es(),registryVersion:Zo(),bakeError:t?.error??null,canvasColorSpace:this.canvasColorSpace,hdr:{on:this._hdrOutput,showing:n,view:n?this._canvasView.table?.name??t?.name??null:null,reason:this._canvasReason}}}dispose(){this._offRegistry?.(),this._listeners.clear(),this._releaseViews();for(let e of new Set([this._canvasView?.table,...this._bakedCanvasViews.values(),...this._recentCanvasViews.values()]))e?.dispose();this._canvasView=null,this._bakedCanvasViews.clear(),this._recentCanvasViews.clear(),sO(null),this._renderer=null,this._issues=null,$r()===this&&(Jn(null),ei(null))}static resetAll(){ei(null),Jn(null),MO(),cs(),ED(),GO(),pD()}};function lk(){return oD()}var uk=new Map;function dk(e,t){return e.exclusive||t===`exclusive`&&e.shared>0?!1:(t===`exclusive`?e.exclusive=!0:e.shared++,!0)}function fk(e,t,n){let r=uk.get(e);r||(r={shared:0,exclusive:!1,queue:[]},uk.set(e,r));let i=pk(()=>{for(t===`exclusive`?r.exclusive=!1:r.shared--;r.queue.length&&dk(r,r.queue[0].mode);)r.queue.shift().grant();!r.exclusive&&r.shared===0&&r.queue.length===0&&uk.delete(e)});return r.queue.length===0&&dk(r,t)?Promise.resolve(i):n?(!r.exclusive&&r.shared===0&&r.queue.length===0&&uk.delete(e),Promise.resolve(null)):new Promise(e=>r.queue.push({mode:t,grant:()=>e(i)}))}function pk(e){let t=!1;return()=>{t||(t=!0,e())}}var mk=()=>typeof navigator<`u`&&navigator.locks?.request?navigator.locks:null;function hk(e,{mode:t=`exclusive`,ifAvailable:n=!1}={}){let r=mk();return r?new Promise((i,a)=>{r.request(e,{mode:t,ifAvailable:n},e=>{if(!e){i(null);return}return new Promise(e=>i(pk(e)))}).catch(a)}):fk(e,t,n)}async function gk(){let e=mk();if(!e)return new Set(uk.keys());let{held:t=[]}=await e.query();return new Set(t.map(e=>e.name))}var _k=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)}},vk=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})}},yk=class{constructor(e){this._ops=new vk(e)}async call(e,t){return this._ops[e](t)}dispose(){this._ops.dispose()}};an(),Sv(),hn();var bk=`meta.json`,xk=1,Sk=36e5,Ck=.3,wk=100*1024**3,Tk=64*1024**2,Ek=8*1024**2,Dk=4,Ok=3e4,kk=new TextEncoder;function Ak(e,{copy:t,transfer:n}){if(typeof e==`string`&&(e=kk.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 jk(e,t){try{let n=await(await e.getFileHandle(t)).getFile();return JSON.parse(await n.text())}catch{return null}}async function*Mk(e){for await(let[t,n]of e.entries())n.kind===`directory`&&(yield[t,n])}var Nk=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(X.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}},Pk=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:Ak(t,{copy:!0,transfer:r}))??Ak(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}=Ak(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=Ek}={}){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>=Dk&&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:xk,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}=Ak(JSON.stringify(n),{copy:!1});return await this._transport.call(`writeFile`,{path:this._path,name:bk,...i},a),this.area.kind===pn.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`)}},Fk=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 jk(e,bk);if(!n||n.v!==xk||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 dv(e),r=await hk(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>Sk&&this._touch(n,i),new Nk(this,n,i,t,r)):(r(),null)}catch(e){return r(),this.manager._issue(X.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}=Ak(JSON.stringify(n),{copy:!1});this.manager._transport.call(`writeFile`,{path:[this.name,e],name:bk,...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 dv(e),s=await hk(this._lockName(o),{mode:`exclusive`});try{return r>0&&!await this.manager.ensureSpace(r,this.kind)?(s(),this.manager._issue(X.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 Pk(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 dv(e),r=await hk(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}=Ak(JSON.stringify({...i,...t,v:xk,key:e}),{copy:!1});return await this.manager._transport.call(`writeFile`,{path:[this.name,n],name:bk,...a},o),!0}finally{r()}}async edit(e){let t=await dv(e),n=await hk(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 Pk(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 dv(e))}async removeById(e){let t=await hk(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 Mk(e)){let e=await jk(r,bk);e?.v===xk&&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 gk(),n=0;for await(let[r,i]of Mk(e))t.has(this._lockName(r))||await this._validMeta(i)||await this.removeById(r)&&n++;return n}},Ik=class extends _k{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(mn))this.defineArea(e,{kind:e===mn.SPILL?pn.SCRATCH:pn.CACHE})}defineArea(e,{kind:t=pn.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 Fk(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*Ck,wk)}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>Ok)&&(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===pn.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===pn.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 gk(),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=pn.CACHE){let n=async()=>{let{quota:n,usage:r}=await this.estimate(),i=e+Tk-(n-r);return t===pn.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===pn.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?X.STORAGE_QUOTA_EXCEEDED:X.STORAGE_WRITE_FAILED,`${e}: ${t?.message??t}`,{area:e,error:t?.name})}dispose(){this._transport?.dispose(),this._transport=null,this._areas.clear()}};function Lk({namespace:e,root:t}){let n=new yk(t);n.inline=!0;let r=new Ik({root:t,transport:n,namespace:e});return r.sweep().catch(()=>{}),r}var Rk="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}})}};",zk=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,Rk],{type:`text/javascript;charset=utf-8`});function Bk(e){let t;try{if(t=zk&&(self.URL||self.webkitURL).createObjectURL(zk),!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(Rk),{type:`module`,name:e?.name})}}function Vk({name:e,message:t}){let n=Error(t);return n.name=e,n}var Hk=class{constructor({namespace:e,root:t=null}){this._worker=new Bk,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(Vk(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 Uk(){return typeof WorkerGlobalScope<`u`&&globalThis instanceof WorkerGlobalScope}ii();async function Wk(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 Gk({namespace:e,root:t=null,transport:n=`auto`}={}){let r=t?{root:t}:await Wk(e);if(!r.root)return{storage:null,reason:r.reason};if(n===`inline`||n===`auto`&&(Uk()||typeof Worker>`u`))return{storage:Lk({namespace:e,root:r.root})};let i=new Hk({namespace:e,root:t}),a=new Ik({root:r.root,transport:i,namespace:e});return a.sweep().catch(()=>{}),{storage:a}}async function Kk(e){let t=ri.get(e);t||(t={refs:0,opened:Gk({namespace:e})},ri.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)&&(ri.get(e)===t&&ri.delete(e),n?.dispose()))};return n?{storage:n,release:a}:(a(),{storage:null,reason:r,release:()=>{}})}function qk(e){return e.length>=2&&e[0]===31&&e[1]===139}function Jk(e){return e.length>=4&&e[0]===80&&e[1]===75&&(e[2]===3||e[2]===5||e[2]===7)}function Yk(e){return e.length>=263&&String.fromCharCode(...e.subarray(257,262))===`ustar`}function Xk(e){return qk(e)?`gzip`:Jk(e)?`zip`:Yk(e)?`tar`:null}function Zk(e,t,n){let r=t,i=t+n;for(;r<i&&e[r]!==0;)r++;return gA.decode(e.subarray(t,r))}function Qk(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=Zk(e,t,n).trim();if(!r)return 0;let i=parseInt(r,8);return Number.isFinite(i)?i:0}function $k(e){let t=[];for(let n of e.replace(/\\/g,`/`).split(`/`))n===``||n===`.`||(n===`..`?t.pop():t.push(n));return t.join(`/`)}function eA(e){let t=gA.decode(e).match(/^\d+ path=(.*)$/m);return t?t[1]:null}function tA(e){let t=Zk(e,345,155),n=Zk(e,0,100);return{type:String.fromCharCode(e[156]||48),size:Qk(e,124,12),name:t?`${t}/${n}`:n}}function nA(e,t){return e===`5`||e===`g`||e===`K`||t.endsWith(`/`)||e!==`0`&&e!==` `?null:$k(t)||null}function rA(e){for(let t=0;t<pA;t++)if(e[t]!==0)return!1;return!0}async function iA(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 aA(e,(e,t)=>{if(r.push(e,t),n)throw n})}async function aA(e,t){if(e instanceof Uint8Array){for(let n=0;n<e.length;n+=mA){let r=Math.min(n+mA,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+=mA){let i=Math.min(r+mA,n);t(new Uint8Array(await e.slice(r,i).arrayBuffer()),i===n)}n===0&&t(new Uint8Array,!0)}async function oA(e,t={}){let{onProgress:n,...r}=t,i=new yA(r),a=0,o=0;return await iA(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 sA(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,bA));return i=new Uint8Array(await e.slice(t,o).arrayBuffer()),a=t,i.subarray(0,r)};for(;s+pA<=n;){let e=await l(s,pA);if(rA(e))break;let{type:n,size:i,name:a}=tA(e),u=o??a;o=null;let d=s+pA;if(vA(n)){let e=await l(d,i);o=n===`L`?Zk(e,0,e.length):eA(e)}else{let e=nA(n,u);e&&r.push({path:e,size:i,offset:d})}s=d+_A(i),t&&s>=c&&(c=s+(256<<20),t({entries:r.length,bytes:s}))}return r}function cA({filter:e=null,sink:t=null}={}){let n=new yA({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 lA(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 sA(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 yA({...a});await aA(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},slice:async t=>{if(o[t])return new Blob([o[t]]);let n=d.get(t);return n?e.slice(n.offset,n.offset+n.size):null},retainedBytes:c,truncated:l,indexed:d.size,index:u?{v:1,listing:u}:null}}function uA(e,{filter:t=null}={}){let n=new Map,r=e.files.map(({path:e,file:r})=>t&&!t(e,r.size)?{path:e,size:r.size}:(n.set(e,r),{path:e,size:r.size,offset:0}));return{entries:Object.create(null),listing:r,read:async e=>{let t=n.get(e);return t?new Uint8Array(await t.arrayBuffer()):null},readHead:async(e,t)=>{let r=n.get(e);return r?new Uint8Array(await r.slice(0,t).arrayBuffer()):null},slice:async e=>n.get(e)??null,retainedBytes:0,truncated:!1,indexed:n.size}}function dA(e){let t=(Array.isArray(e)?e:[e]).filter(Boolean).map($k);if(t.length===0)return()=>!0;let n=new Map;for(let e of t){let t=e.lastIndexOf(`/`),r=t<0?``:e.slice(0,t+1);n.has(r)||n.set(r,new Set),n.get(r).add(e.slice(t+1))}return e=>{for(let[t,r]of n){if(!e.startsWith(t))continue;let n=e.slice(t.length),i=n.indexOf(`/`);if(i<0)continue;let a=n.slice(0,i);if(!r.has(a)&&a!==`textures`)return!1}return!0}}function fA(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 pA,mA,hA,gA,_A,vA,yA,bA,xA=g((()=>{pA=512,mA=4<<20,hA=15e8,gA=new TextDecoder,_A=e=>e+(pA-e%pA)%pA,vA=e=>e===`L`||e===`x`||e===`X`,yA=class{constructor({filter:e=null,retain:t=null,byteBudget:n=hA,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(pA),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(pA-this._headerLen,e.length-n);this._header.set(e.subarray(n,n+r),this._headerLen),this._headerLen+=r,n+=r,this._headerLen===pA&&(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<pA;n++)if(e[n]!==0){t=!1;break}if(t){this.finished=!0;return}let{type:n,size:r,name:i}=tA(e),a=this._pendingName??i;if(this._pendingName=null,this._size=r,this._copied=0,this._remaining=_A(r),this._dst=null,this._special=null,this._indexed=!1,this._state=this._remaining>0?`body`:`header`,vA(n)){this._special=n===`L`?`longname`:`pax`,this._dst=new Uint8Array(r);return}let o=nA(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=Zk(this._dst,0,this._dst.length),this._dst=null;return}if(this._special===`pax`){let e=eA(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)}},bA=1<<20}));async function SA(e,t,n){return new Uint8Array(await e.slice(t,n).arrayBuffer())}function CA(e,t){return e.getUint32(t+4,!0)*4294967296+e.getUint32(t,!0)}function wA(e){let t=``;for(let n=0;n<e.length;n+=8192)t+=String.fromCharCode(...e.subarray(n,n+8192));return t}async function TA(e){let t=e.size,n=await SA(e,Math.max(0,t-PA-20),t),r=new DataView(n.buffer),i=-1;for(let e=n.length-22;e>=0;e--)if(r.getUint32(e,!0)===kA){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)!==AA)throw Error(`zip: ZIP64 locator missing`);let n=CA(r,t+8),c=new DataView((await SA(e,n,n+56)).buffer);if(c.getUint32(0,!0)!==jA)throw Error(`zip: ZIP64 end record missing`);a=CA(c,32),o=CA(c,40),s=CA(c,48)}let c=await SA(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)!==MA)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?FA.decode(f):wA(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=CA(l,t),t+=8),n===4294967295&&(n=CA(l,t),t+=8),s===4294967295&&(s=CA(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 EA(e,t){if(t.encrypted)throw Error(`zip: "${t.name}" is encrypted`);let n=new DataView((await SA(e,t.local,t.local+30)).buffer);if(n.getUint32(0,!0)!==NA)throw Error(`zip: bad local header for "${t.name}"`);return t.local+30+n.getUint16(26,!0)+n.getUint16(28,!0)}async function DA(e,t){let n=await EA(e,t),r=await SA(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 OA(e,{filter:t=null}={}){let n=await TA(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?DA(e,n):null},o=async t=>{let n=r.get(t);if(!n)return null;if(n.method!==0)return new Blob([await DA(e,n)]);let i=await EA(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 kA,AA,jA,MA,NA,PA,FA,IA=g((()=>{kA=101010256,AA=117853008,jA=101075792,MA=33639248,NA=67324752,PA=65557,FA=new TextDecoder}));async function LA(e,t){return`${e}:${hv(await pv(t))}`}async function RA(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(mn.ARCHIVES),s=await LA(`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*HA});if(!s)return null;let u=null,d=cA(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:VA,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(X.STORAGE_QUOTA_EXCEEDED,`ran out of room unpacking ${n}; reading it in memory instead`,{area:mn.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!==VA?(l.release(),null):{file:d,index:f,release:()=>l.release(),cached:u}}async function zA(e,t){if(!t)return null;let n=await t.area(mn.ARCHIVES).open(await LA(`tarindex`,e));if(!n)return null;try{let e=await n.json(`index.json`);return e?.v===VA?e:null}finally{n.release()}}async function BA(e,t,n){if(!t||!n)return!1;let r=await t.area(mn.ARCHIVES).create(await LA(`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 VA,HA,UA=g((()=>{xA(),hn(),Sv(),an(),VA=1,HA=3}));function WA(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 GA(e,t){try{let t=JSON.parse(JSON.stringify(e??{}));return delete t[oj],delete t[sj],t}catch{throw new hj(`${t}: userData is not plain JSON`)}}function KA(e,t,n){if(e.isInterleavedBufferAttribute||!ArrayBuffer.isView(e.array))throw new hj(`${n}: interleaved or non-typed attribute`);return{section:t.add(e.array),itemSize:e.itemSize,normalized:e.normalized===!0,name:e.name??``}}function qA(e,t){let n=`geometry ${e.name||e.uuid}`;if(Object.keys(e.morphAttributes??{}).length)throw new hj(`${n}: morph targets`);let r={};for(let[i,a]of Object.entries(e.attributes))r[i]=KA(a,t,n);return{uuid:e.uuid,name:e.name,attributes:r,index:e.index?KA(e.index,t,n):null,groups:e.groups.map(e=>({...e})),drawRange:{...e.drawRange},userData:GA(e.userData,n)}}function JA(e,t){let n={uuid:e.uuid,userData:GA(e.userData,`texture ${e.uuid}`)};for(let t of fj)n[t]=e[t];for(let t of[`repeat`,`offset`,`center`])n[t]=e[t].toArray();n.rotation=e.rotation;let r=e.userData?.[oj];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 hj(`texture ${e.name||e.uuid}: no archive path and no pixel data to keep`);return n}function YA(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),e.diffuseRoughness!==void 0&&(n.diffuseRoughness=e.diffuseRoughness);for(let t of aj)e[t]?.isTexture&&((n.engineTextures??={})[t]=e[t].uuid);return n}function XA(e,t){for(let n of Object.values(e))n?.isTexture&&t.set(n.uuid,n)}function ZA(e,{environment:t=null,animations:n=[],stats:i={}}={}){let a=new gj,o=[],s=new Map,c=new Map,l=new Map,u=new Map,d=(e,t)=>{let n=WA(e);if(!n)throw new hj(`${e.type} "${e.name}" cannot be cached`);let r={type:n,uuid:e.uuid,parent:t,userData:GA(e.userData,`${n} "${e.name}"`)};for(let t of mj)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){c.set(e.geometry.uuid,e.geometry);let t=Array.isArray(e.material)?e.material:[e.material];for(let e of t)l.set(e.uuid,e),XA(e,u);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;let t=s.get(e.instanceMatrix);t||s.set(e.instanceMatrix,t=a.add(e.instanceMatrix.array)),r.instanceMatrix=t,r.instanceColor=e.instanceColor?a.add(e.instanceColor.array):null}if(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 pj)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)d(t,i)};d(e,-1),t&&u.set(t.uuid,t);let f={textures:{},images:{}};for(let e of u.keys())f.textures[e]={uuid:e};return{manifest:{v:2,nodes:o,geometries:[...c.values()].map(e=>qA(e,a)),textures:[...u.values()].map(e=>JA(e,a)),materials:[...l.values()].map(e=>YA(e,f)),animations:n.map(e=>r.AnimationClip.toJSON(e)),environment:t?t.uuid:null,stats:i},sections:a.sections,byteLength:a.length}}async function QA(e,{manifest:t,sections:n},{release:r=!1,signal:i=null}={}){for(let t of n){let{offset:n,array:a}=t,o=new Uint8Array(a.buffer,a.byteOffset,a.byteLength);for(let t=0;t<o.length;t+=lj)i?.throwIfAborted(),await e.write(`data.bin`,o.subarray(t,Math.min(o.length,t+lj)),{at:n+t});r&&(t.array=null)}n.length===0&&await e.write(`data.bin`,new Uint8Array),i?.throwIfAborted(),await e.writeJSON(`graph.json`,t)}function $A(e){let t=dj[e];if(!t)throw Error(`scene graph: unknown array type ${e}`);return t}async function ej(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=$A(s),l=r+o;if(o>uj){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+uj)).arrayBuffer()),n.set(r,new c(i.slice(r-a,l-a)))}return n}function tj(e){let t=[],n=new Set;for(let r of e.nodes)r.instanceMatrix&&!n.has(r.instanceMatrix.offset)&&(n.add(r.instanceMatrix.offset),t.push(r.instanceMatrix)),r.instanceColor&&t.push(r.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 nj(e,t){let n=new r.BufferAttribute(e.get(t.section.offset),t.itemSize,t.normalized);return n.name=t.name,n}function rj(e,t){for(let n of fj)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 ij(e,t,{loadTexture:n}){if(e?.v!==2)throw Error(`scene graph: unknown format`);let i=await ej(t,tj(e)),a=e=>i.get(e.offset),o=new Map,s={};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[oj]=t.path,e.userData[sj]=t.loader}else e=new r.DataTexture(a(t.data.section),t.data.width,t.data.height);rj(e,t),s[t.uuid]=e}let c=new r.MaterialLoader().setTextures(s),l={};for(let t of e.materials){let e=c.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),t.diffuseRoughness!==void 0&&(e.diffuseRoughness=t.diffuseRoughness);for(let[n,r]of Object.entries(t.engineTextures??{}))s[r]&&(e[n]=s[r]);l[t.uuid]=e}let u={};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,nj(i,r));t.index&&e.setIndex(nj(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,u[t.uuid]=e}let d=[];for(let t of e.nodes){let e=Array.isArray(t.material)?t.material.map(e=>l[e]):l[t.material],n;switch(t.type){case`InstancedMesh`:{n=new r.InstancedMesh(u[t.geometry],e,1);let i=o.get(t.instanceMatrix.offset);i||o.set(t.instanceMatrix.offset,i=new r.InstancedBufferAttribute(a(t.instanceMatrix),16)),n.instanceMatrix=i,n.count=t.count,t.instanceColor&&(n.instanceColor=new r.InstancedBufferAttribute(a(t.instanceColor),3));break}case`Mesh`:n=new r.Mesh(u[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 mj)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 pj)t[e]!==void 0&&(n[e]=t[e])}d.push(n),t.parent>=0&&d[t.parent].add(n)}let f=new Map(d.map(e=>[e.uuid,e]));return e.nodes.forEach((e,t)=>{e.target&&f.has(e.target)&&(d[t].target=f.get(e.target))}),{root:d[0],environment:e.environment?s[e.environment]:null,animations:e.animations.map(e=>r.AnimationClip.parse(e)),stats:e.stats}}var aj,oj,sj,cj,lj,uj,dj,fj,pj,mj,hj,gj,_j=g((()=>{aj=[`diffuseTransmissionMap`,`diffuseTransmissionColorMap`],oj=`__rayzeeArchivePath`,sj=`__rayzeeArchiveLoader`,cj=64,lj=32<<20,uj=64<<20,dj={Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint16Array,Uint32Array,Uint8ClampedArray},fj=[`name`,`mapping`,`channel`,`wrapS`,`wrapT`,`magFilter`,`minFilter`,`anisotropy`,`format`,`type`,`flipY`,`generateMipmaps`,`premultiplyAlpha`,`unpackAlignment`,`colorSpace`],pj=[`intensity`,`distance`,`decay`,`angle`,`penumbra`],mj=[`name`,`visible`,`castShadow`,`receiveShadow`,`frustumCulled`,`renderOrder`,`matrixAutoUpdate`],hj=class extends Error{constructor(e){super(e),this.name=`SceneGraphUnsupported`}},gj=class{constructor(){this.sections=[],this.length=0}add(e){let t=Math.ceil(this.length/cj)*cj;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 vj(e){e&&bj(e)&&e.buffer.transfer(0)}function yj(e,t){let n=e.constructor;if(bj(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 bj,xj=g((()=>{bj=e=>e.byteOffset===0&&e.byteLength===e.buffer.byteLength&&typeof e.buffer.transfer==`function`&&!(typeof SharedArrayBuffer<`u`&&e.buffer instanceof SharedArrayBuffer)}));function Sj(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 Gj.decode(e.subarray(t,n));let i=``;for(let r=t;r<n;r++)i+=String.fromCharCode(e[r]);return i}var Cj,wj,Tj,Ej,Dj,Oj,kj,Aj,jj,Mj,Nj,Pj,Fj,Ij,Lj,Rj,zj,Bj,Vj,Hj,Uj,Wj,Gj,Kj,qj=g((()=>{Cj={STRING:`string`,NUMBER:`number`,WORD:`word`,LBRACKET:`[`,RBRACKET:`]`},wj=9,Tj=10,Ej=12,Dj=13,Oj=32,kj=34,Aj=35,jj=43,Mj=45,Nj=46,Pj=48,Fj=57,Ij=91,Lj=93,Rj=69,zj=101,Bj=e=>e===Oj||e===wj||e===Tj||e===Dj||e===Ej,Vj=e=>e>=Pj&&e<=Fj,Hj=15,Uj=22,Wj=(()=>{let e=new Float64Array(Uj+1);for(let t=0;t<e.length;t++)e[t]=10**t;return e})(),Gj=new TextDecoder,Kj=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&&Bj(e[t]);)t++;if(t<n&&e[t]===Aj){for(;t<n&&e[t]!==Tj;)t++;continue}break}if(t>=n)return this.i=t,null;let r=e[t];if(r===Ij)return this.i=t+1,{type:Cj.LBRACKET};if(r===Lj)return this.i=t+1,{type:Cj.RBRACKET};if(r===kj){let r=++t;for(;t<n&&e[t]!==kj;)t++;if(t>=n)throw Error(`PBRT tokenizer: unterminated string literal`);return this.i=t+1,{type:Cj.STRING,value:Sj(e,r,t)}}if(Vj(r)||r===Nj&&Vj(e[t+1])||(r===Mj||r===jj)&&(Vj(e[t+1])||e[t+1]===Nj&&Vj(e[t+2])))return this._scanNumber(t);let i=t;for(;t<n;){let n=e[t];if(Bj(n)||n===kj||n===Ij||n===Lj||n===Aj)break;t++}return this.i=t,{type:Cj.WORD,value:Sj(e,i,t)}}_scanNumber(e){let t=this.bytes,n=this.n,r=e,i=!1;t[r]===Mj?(i=!0,r++):t[r]===jj&&r++;let a=0,o=0,s=0;for(;r<n&&Vj(t[r]);)a=a*10+(t[r]-Pj),o++,r++;if(r<n&&t[r]===Nj)for(r++;r<n&&Vj(t[r]);)a=a*10+(t[r]-Pj),o++,s++,r++;let c=0;if(r<n&&(t[r]===zj||t[r]===Rj)){let e=r+1,i=!1;if(e<n&&(t[e]===Mj||t[e]===jj)&&(i=t[e]===Mj,e++),e<n&&Vj(t[e])){let a=0;for(;e<n&&Vj(t[e]);)a=a*10+(t[e]-Pj),e++;c=i?-a:a,r=e}}if(this.i=r,o===0)throw Error(`PBRT tokenizer: invalid number "${Sj(t,e,r)}"`);let l=c-s;if(!(o<=Hj&&l>=-Uj&&l<=Uj)){let n=Number(Sj(t,e,r));if(Number.isNaN(n))throw Error(`PBRT tokenizer: invalid number "${Sj(t,e,r)}"`);return{type:Cj.NUMBER,value:n}}let u=l===0?a:l>0?a*Wj[l]:a/Wj[-l];return i&&(u=-u),{type:Cj.NUMBER,value:u}}}}));function Jj(){return[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}function Yj(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 Xj(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 Zj(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 Qj(e,t,n){return[1,0,0,0,0,1,0,0,0,0,1,0,e,t,n,1]}function $j(e,t,n){return[e,0,0,0,0,t,0,0,0,0,n,0,0,0,0,1]}function eM(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 tM(e,t){return[e[0]-t[0],e[1]-t[1],e[2]-t[2]]}function nM(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 rM(e){let t=Math.hypot(e[0],e[1],e[2])||1;return[e[0]/t,e[1]/t,e[2]/t]}function iM(e,t,n){let r=rM(tM(t,e)),i=rM(nM(rM(n),r)),a=nM(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 aM(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 Jj();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 oM=g((()=>{}));function sM(e,t){if(e===t)return!0;for(let n=0;n<16;n++)if(e[n]!==t[n])return!1;return!0}function cM(e,t){return gM!==null&&gM.params===e?gM.read.push(t):_M.size!==0&&_M.get(e)?.read.push(t),e?.[t]}function lM(e,t){let n=gM!==null&&gM.params===e?gM:_M.get(e);n&&(n.approximated??=new Set).add(t)}var uM,dM,fM,pM,mM,hM,gM,_M,vM,yM,bM=g((()=>{xj(),qj(),oM(),uM=8,dM=1,fM=2,pM=3,mM=new Set([`Identity`,`Transform`,`CoordinateSystem`,`CoordSysTransform`,`ActiveTransform`,`TransformTimes`,`Camera`,`Film`,`WorldBegin`,`MakeNamedMaterial`,`Texture`,`MakeNamedMedium`,`LightSource`,`AreaLightSource`,`ObjectBegin`,`ObjectEnd`,`ObjectInstance`]),hM={integer:Int32Array,point3:Float32Array,point2:Float32Array,vector3:Float32Array,vector2:Float32Array,vector:Float32Array,normal:Float32Array,rgb:Float32Array},gM=null,_M=new Map,vM=class{constructor(){this.unused=new Map,this.approximated=new Map}translate(e,t,n,r=null){if(_M.has(e))return n();let i=gM,a=gM={params:e,label:t,approximated:null,read:[r]};try{return n()}finally{gM=i;for(let t in e)this._count(a,t,!a.read.includes(t))}}open(e,t,n=null){e&&!_M.has(e)&&_M.set(e,{usage:this,label:t,approximated:null,read:[n]})}finish(){for(let[e,t]of _M)if(t.usage===this){_M.delete(e);for(let n in e)this._count(t,n,!t.read.includes(n))}let e=e=>[...e].flatMap(([e,t])=>[...t].map(([t,n])=>[`${e}: ${t}`,n])),t=t=>Object.fromEntries(e(t).sort((e,t)=>e[0]<t[0]?-1:1));return{unused:t(this.unused),approximated:t(this.approximated)}}_count(e,t,n){let r=e.approximated?.has(t)?this.approximated:n?this.unused:null;if(!r)return;let i=r.get(e.label);i||r.set(e.label,i=new Map),i.set(t,(i.get(t)??0)+1)}},yM=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.usage=e.usage??null,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=Jj(),this.ctmEnd=null,this.activeTransform=pM,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 Kj(e)),this._movedShapes&&(this.ir.shapes=this.ir.shapes.filter(Boolean));for(let e of this.ir.instances.values())e.matrices=yj(e.matrices,e.count*16),e.matricesEnd&&=yj(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=yj(n.matrices,e),n.matricesEnd&&=yj(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||sM(this.ctmEnd,this.ctm)?null:(this.ir.hasMotion=!0,this.ctmEnd.slice())}_concat(e){if(this.activeTransform===pM&&this.ctmEnd===null){this.ctm=Zj(this.ctm,e);return}let t=this.ctmEnd??this.ctm;this.ctmEnd=this.activeTransform&fM?Zj(t,e):t,this.activeTransform&dM&&(this.ctm=Zj(this.ctm,e))}_setCTM(e){if(this.activeTransform===pM){this.ctm=e,this.ctmEnd=null;return}let t=this.ctmEnd??this.ctm;this.ctmEnd=this.activeTransform&fM?e:t,this.activeTransform&dM&&(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!==Cj.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!==Cj.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===Cj.LBRACKET){this._next();let e=[];for(;this._peek()&&this._peek().type!==Cj.RBRACKET;)e.push(this._expectNumber(`transform element`));return this._next(),e}return this._readNumbers(e)}_parseParams(){let e={};for(;this._peek()&&this._peek().type===Cj.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===Cj.LBRACKET;t&&this._next();let n=()=>{let e=this._peek();return t?e&&e.type!==Cj.RBRACKET:!1};if(!t)return[this._coerceValueToken(this._next())];if(this._peek()&&this._peek().type===Cj.NUMBER){let t=[];for(;n()&&t.length<uM;){let e=this._next();if(e.type!==Cj.NUMBER)return this._finishMixedValue(t,t.length,e);t.push(e.value)}if(!n())return this._next(),t;let r=new(hM[e]||Float64Array)(uM*4);r.set(t);let i=t.length;for(;n();){let e=this._next();if(e.type!==Cj.NUMBER)return this._finishMixedValue(r,i,e);i===r.length&&(r=yj(r,r.length*2)),r[i++]=e.value}return this._next(),i===r.length?r:yj(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!==Cj.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===Cj.NUMBER||e.type===Cj.STRING)return e.value;if(e.type===Cj.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!==Cj.WORD)throw Error(`PBRT parser: expected directive, got ${e.type} ${e.value??``}`);mM.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(Jj());break;case`Translate`:{let[e,t,n]=this._readNumbers(3);this._concat(Qj(e,t,n));break}case`Scale`:{let[e,t,n]=this._readNumbers(3);this._concat($j(e,t,n));break}case`Rotate`:{let[e,t,n,r]=this._readNumbers(4);this._concat(eM(e,t,n,r));break}case`LookAt`:{let e=this._readNumbers(9),t=iM([e[0],e[1],e[2]],[e[3],e[4],e[5]],[e[6],e[7],e[8]]);this._concat(aM(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:aM(this.ctm)};let n=this._ctmEndSnapshot();n&&(this.ir.camera.cameraToWorldEnd=aM(n));break}case`Film`:{let t=this._expectString(`Film type`),n=this._parseParams();this._translate(n,`${e} ${t}`,()=>{this.ir.film={xresolution:this._num(cM(n,`xresolution`),1280),yresolution:this._num(cM(n,`yresolution`),720),resolutionGiven:!!(n.xresolution||n.yresolution),filename:this._str(cM(n,`filename`),null)}});break}case`Integrator`:{let t=this._expectString(`Integrator type`),n=this._parseParams();this._translate(n,`${e} ${t}`,()=>{n.maxdepth&&(this.ir.integrator={maxdepth:this._num(cM(n,`maxdepth`),5)})});break}case`Sampler`:{let t=this._expectString(`Sampler type`),n=this._parseParams();this._translate(n,`${e} ${t}`,()=>{n.pixelsamples&&(this.ir.sampler={pixelsamples:this._num(cM(n,`pixelsamples`),16)})});break}case`PixelFilter`:case`Filter`:case`Accelerator`:case`ColorSpace`:{let t=this._peek()?.type===Cj.STRING?this._next().value:``;this._translate(this._parseParams(),`${e} ${t}`);break}case`Option`:this._translate(this._parseParams(),e);break;case`WorldBegin`:this.ctm=Jj(),this.ctmEnd=null,this.activeTransform=pM,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`:{let t=this._expectString(`Attribute target`);this._translate(this._parseParams(),`${e} ${t}`);break}case`ActiveTransform`:{let e=this._next()?.value;e===`StartTime`?this.activeTransform=dM:e===`EndTime`?this.activeTransform=fM:e===`All`?this.activeTransform=pM: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===Cj.STRING?this._next().value:``;this._peek()?.type===Cj.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(),i={dataType:t,class:n,params:r};this._str(r.mapping,`uv`)!==`uv`&&(i.ctm=this._ctmSnapshot()),this.ir.namedTextures.set(e,i);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&&!sM(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&&!sM(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._translate(this._parseParams(),e);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 Kj(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!==pM||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===pM&&sM(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=aM(n.ctm),s=[],c=null,l=null;for(let e=r;e<i;e++){let t=this.ir.shapes[e];t.ctm!==c&&(l=Zj(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}_translate(e,t,n=()=>{}){return this.usage?this.usage.translate(e,t,n):n()}_skipNamedAndParams(){this._peek()&&this._peek().type===Cj.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 xM(e){let t=wM[e];return t?{sigmaS:t[0].slice(),sigmaA:t[1].slice()}:null}function SM(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 CM(e,t){let n=Math.min(Math.max(e,0),SM(1,t)),r=0,i=1;for(let e=0;e<48;e++){let e=(r+i)/2;SM(e,t)<n?r=e:i=e}return(r+i)/2}var wM,TM=g((()=>{wM={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 EM(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 DM(e,t,n){let r=cM(e,t);return r&&r.type!==`float`&&r.type!==`integer`&&lM(e,t),r&&typeof r.value[0]==`number`?r.value[0]:n}function OM(e,t,n){let r=cM(e,t);if(r?.type!==`spectrum`||typeof r.value[0]!=`number`)return DM(e,t,n);lM(e,t);let i=r.value;if(i.length<2)return n;let a=2;for(;a<i.length-1&&i[a]<550;)a+=2;return a>=i.length-1||i[a-2]>=550?i[a>=i.length-1?a-1:1]:i[a-1]+(i[a+1]-i[a-1])*(550-i[a-2])/(i[a]-i[a-2])}function kM(e,t,n){let r=cM(e,t);return r&&typeof r.value[0]==`string`?r.value[0]:n}function AM(e,t,n){let r=cM(e,t)?.value?.[0];return r===void 0?n:r===!0||r===`true`}async function jM(e,t,n,r=null){let i=cM(e,t);if(!i)return{rgb:r,texture:null};if(i.type===`texture`){let a=i.value[0],o=await n.resolveNamedTexture(a);return o&&o.texture?{rgb:o.constant??null,texture:o.texture}:o&&o.constant?{rgb:o.constant,texture:null}:(n.warn(`texture "${a}" could not be resolved`),lM(e,t),{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 lM(e,t),{rgb:EM(i.value[0]),texture:null};if(i.type===`spectrum`){if(lM(e,t),typeof i.value[0]==`string`){let e=MM(i.value[0]);return e&&BM[e]?{rgb:BM[e].slice(),texture:null}:(n.warn(`named spectrum "${i.value[0]}" approximated to gray`),{rgb:[.5,.5,.5],texture:null})}let r=0,a=0;for(let e=1;e<i.value.length;e+=2)r+=i.value[e],a++;let o=a?r/a:.5;return{rgb:[o,o,o],texture:null}}return lM(e,t),{rgb:r,texture:null}}function MM(e){let t=e.toLowerCase().match(/metal-([a-z]+)/);if(t)return t[1];for(let t of Object.keys(BM))if(e.toLowerCase().includes(t))return t;return null}async function NM(e,t,n){let r=cM(e,t);return r?typeof r.value[0]==`number`?r.value[0]:(lM(e,t),r.type===`texture`?await n.floatTextureMean?.(r.value[0])??null:null):null}async function PM(e,t,n,r=``){let i=HM(e),a=e=>i?Math.sqrt(Math.max(e,0)):e,o=null,s=await NM(e,`${r}roughness`,n);if(s!==null)o=a(s);else{let t=await NM(e,`${r}uroughness`,n),i=await NM(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 FM(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=HM(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 PM(n,r,i,a)}async function IM(e,t,n,r){let i=cM(e,t);return i?.type===`texture`?(lM(e,t),await n.textureMeanRGB?.(i.value[0])??r):(await jM(e,t,n,r)).rgb??r}async function LM(e,t,n){let i=OM(t,`eta`,1.33),a=DM(t,`scale`,1),o=e=>e.map(e=>Math.max(0,e*a)),s=DM(t,`g`,0),c,l,u=kM(t,`name`,``),d=u?xM(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 IM(t,`sigma_a`,n,UM)),l=o(await IM(t,`sigma_s`,n,WM));else if(t.reflectance&&!u){let e=await IM(t,`reflectance`,n,[.5,.5,.5]),r=o(t.mfp?await IM(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=CM(e[t],i);l[t]=a*n/(1-s+a*s),c[t]=n-l[t]}}else c=o(UM),l=o(WM);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?SM(n/(c[t]+n),i):0})),await FM(e,`roughness`,t,0,n)}async function RM(e,t,n,r,i,a){let o=await jM(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 jM(t,`${r}eta`,n,[.2,.92,1.1])).rgb,i=(await jM(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 jM(t,`${r}eta`,n,VM)).rgb||VM:BM.cu);e.metalness=1}async function zM(e,t){if(e?.material)return e.material;let n=e?.type||`diffuse`,i=e?.params||{};t.trackParams?.(i,`Material ${n}`,`type`);let 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 jM(i,`reflectance`,t,[.5,.5,.5])),a.roughness=1,a.metalness=0,a.specularIntensity=0;break;case`conductor`:case`metal`:await RM(a,i,t,``,s,o),await FM(a,`roughness`,i,0,t);break;case`coatedconductor`:await RM(a,i,t,`conductor.`,s,o),await FM(a,`roughness`,i,0,t,`conductor.`),a.clearcoat=1,await FM(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=OM(i,`eta`,1.5),await FM(a,`roughness`,i,0,t),a.thickness=n===`thindielectric`?0:DM(i,`thickness`,0);break;case`coateddiffuse`:s(await jM(i,`reflectance`,t,[.5,.5,.5])),a.roughness=.6,a.metalness=0,a.clearcoat=1,await FM(a,`clearcoatRoughness`,i,0,t);break;case`diffusetransmission`:{let e=DM(i,`scale`,1),n=t=>Math.min(1,Math.max(0,e*t)),o=await jM(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 jM(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`),lM(i,`transmittance`)),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=cM(i,`materials`)?.value||[],n=Math.max(0,Math.min(1,DM(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([zM(o,t),zM(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 LM(a,i,t);break;case`hair`:case`measured`:t.warn(`material "${n}" not supported — using diffuse approximation`),o((await jM(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=kM(i,`normalmap`,null);return c&&t.resolveNormalMap&&(a.normalMap=await t.resolveNormalMap(c)),a.clearcoat>0&&a.normalMap&&(a.clearcoatNormalMap=a.normalMap),a.roughness=Math.max(0,Math.min(1,a.roughness)),a}var BM,VM,HM,UM,WM,GM=g((()=>{TM(),bM(),BM={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]},VM=[.92,.92,.92],HM=e=>{let t=cM(e,`remaproughness`)?.value?.[0];return t!==!1&&t!==`false`},UM=[.0011,.0024,.014],WM=[2.55,3.21,3.77]}));function KM(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=n&&(e.data instanceof Uint8Array||e.data instanceof Uint8ClampedArray)?Float64Array.from({length:256},(e,t)=>n(t/255)):null,f=d?t=>d[e.data[t]]:t=>n?n(e.data[t]/255):e.data[t],p=t===1&&c===4&&qM(e),m=t===1&&c>=3&&!p;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*(p?f(s+3):m?(f(s)+f(s+1)+f(s+2))/3:f(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,uv:null,...a}}function qM(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 JM(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 YM({data:e,channels:t}){let n=[0,0,0];for(let r=0;r<e.length;r++)n[r%t]+=e[r];let r=e.length/t||1;return[0,1,2].map(e=>n[Math.min(e,t-1)]/r)}function XM(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 ZM(e,t,{alphaOf:n=null,linear:r=!1}={}){let i=tN(e.find(e=>e.layer)?.layer.uv),a=null,o=0;if(e=e.map(e=>e.layer?tN(e.layer.uv)===i?((!a||e.layer.width*e.layer.height>a.width*a.height)&&(a=e.layer),e):(o++,{rgb:YM(e.layer).map((t,n)=>t*(e.tint?.[n]??1)),clamp:e.clamp}):e),!a)return null;let s=Math.min(a.width,eN),c=Math.min(a.height,eN),l=new Uint8Array(s*c*4),u=e.map(()=>[0,0,0]);for(let i=0;i<c;i++){let o=(i+.5)/c,d=(o-a.dv)/a.sv;for(let c=0;c<s;c++){let f=(c+.5)/s,p=(f-a.du)/a.su;for(let t=0;t<e.length;t++){let n=e[t],r=u[t];if(n.layer){let e=n.layer;if(XM(e,e===a?f:e.su*p+e.du,e===a?o: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(u),h=(i*s+c)*4;for(let e=0;e<3;e++){let t=Math.min(1,Math.max(0,m[e]));l[h+e]=Math.round(255*(r?t:rN(t)))}l[h+3]=n?Math.round(255*Math.min(1,Math.max(0,n(u)))):255}}return{data:l,width:s,height:c,mapping:{su:a.su,sv:a.sv,du:a.du,dv:a.dv,uv:a.uv??null},averaged:o}}function QM(e,t,n,r,i){if(e.type===`planar`){let{vs:a,vt:o}=e;i[0]=e.ds+t*a[0]+n*a[1]+r*a[2],i[1]=e.dt+t*o[0]+n*o[1]+r*o[2]}else if(e.type===`spherical`){let e=Math.hypot(t,n,r)||1,a=Math.atan2(n,t);i[0]=Math.acos(Math.min(1,Math.max(-1,r/e)))/Math.PI,i[1]=(a<0?a+2*Math.PI:a)/(2*Math.PI)}else i[0]=(Math.PI+Math.atan2(n,t))/(2*Math.PI),i[1]=r;return i}function $M(e,t,n,r){let i=e.length/3,a=n,o=aN[r.type],s=new Float64Array(i*2),c=o===void 0?null:new Float64Array(i),l=[0,0],u=0;for(let t=0;t<i;t++){let n=e[t*3],i=e[t*3+1],o=e[t*3+2],d=a[0]*n+a[4]*i+a[8]*o+a[12],f=a[1]*n+a[5]*i+a[9]*o+a[13];QM(r,d,f,a[2]*n+a[6]*i+a[10]*o+a[14],l),s[t*2]=l[0],s[t*2+1]=l[1],c&&(c[t]=Math.hypot(d,f),c[t]>u&&(u=c[t]))}let d=[],f=t;if(c){let e=u*1e-6,n=new Map,r=[0,0,0],a=[0,0,0],l=(t?t.length:i)/3;for(let u=0;u<l;u++){let l=1/0,p=-1/0,m=0,h=0;for(let n=0;n<3;n++){let i=r[n]=t?t[u*3+n]:u*3+n;c[i]<=e||(l=Math.min(l,s[i*2+o]),p=Math.max(p,s[i*2+o]))}let g=p-l>.5;for(let t=0;t<3;t++){let n=s[r[t]*2+o];c[r[t]]<=e?a[t]=NaN:(a[t]=g&&n<.5?n+1:n,m+=a[t],h++)}for(let e=0;e<3;e++){let c=r[e],l=Number.isNaN(a[e])?h>0?m/h:s[c*2+o]:a[e];if(l===s[c*2+o])continue;if(!t){s[c*2+o]=l;continue}let p=`${c}|${l}`,g=n.get(p);g===void 0&&(n.set(p,g=i+d.length/2),d.push(c,l)),f===t&&(f=Uint32Array.from(t)),f[u*3+e]=g}}}let p=d.length/2,m=new Float32Array((i+p)*2);for(let e=0;e<i*2;e++)m[e]=s[e];let h=new Uint32Array(p);for(let e=0;e<p;e++){let t=h[e]=d[e*2];m[(i+e)*2]=s[t*2],m[(i+e)*2+1]=s[t*2+1],m[(i+e)*2+o]=d[e*2+1]}return{uv:m,index:f===t?null:f,extra:h}}var eN,tN,nN,rN,iN,aN,oN=g((()=>{eN=4096,tN=e=>e?.key??``,nN=e=>e<=.04045?e/12.92:((e+.055)/1.055)**2.4,rN=e=>e<=.0031308?e*12.92:1.055*e**(1/2.4)-.055,iN=([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]},aN={spherical:1,cylindrical:0}}));function sN(e){return e===3?3/16:3/(8*e)}function cN(e){return 1/(e+3/(8*sN(e)))}function lN(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 uN(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 dN(e,t){let n=e.length/3,r=lN(n,t),i=r.edgeV0.length,a=uN(e,r,n,sN,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 fN(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=dN(i,a);i=e.positions,a=e.indices,o++}let s=i.length/3,c=uN(i,lN(s,a),s,cN,1/5);return{positions:Float32Array.from(c),indices:Uint32Array.from(a),levels:o}}var pN=g((()=>{}));function mN(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 hN(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 gN(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?aM(t):null,c=e.srgb?_N: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]=mN(f,p,m);hN(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 _N,vN=g((()=>{oM(),_N=(()=>{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 yN(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 bN(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 xN(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 SN(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 CN(e,t){let n=e.length/3;return t===`bspline`?n-3:Math.max(1,(n-1)/3)}function wN(e,t,n,r,i,a,o){let s=Math.floor(r);s>=n&&(s=n-1);let c=r-s;t===`bspline`?yN(c,i):bN(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 TN(e,t,n){let r=[0,0,0,0];return i=>{let a=i*n,o=Math.floor(a);o>=n&&(o=n-1),t===`bspline`?yN(a-o,r):bN(a-o,r);let s=t===`bspline`?o:o*3;return r[0]*e[s]+r[1]*e[s+1]+r[2]*e[s+2]+r[3]*e[s+3]}}function EN(e,t,n){let r=CN(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++)wN(e,t,r,n/i*r,o,a,n*3);return{points:a,count:i+1,spans:r}}function DN(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 ON(e,t,n,r,i){let{points:a,count:o,spans:s}=n;if(o<3)return null;let c=new Float64Array((o-1)*3),l=[0,0,0,0],u=o-1;for(let n=0;n<u;n++)wN(e,t,s,(n+.5)/u*s,l,c,n*3);let d=0;for(let e=0;e<u;e++)d=Math.max(d,DN(c,e,a,e,e+1));let f=e=>Math.max(d,r*.5*i(e/u)),p=(e,t)=>{for(let n=e+1;n<t;n++)if(DN(a,n,a,e,t)>f(n))return!1;for(let n=e;n<t;n++)if(DN(c,n,a,e,t)>f(n+.5))return!1;return!0},m=new Int32Array(o),h=0;m[h++]=0;for(let e=0;e<u;){let t=e+1;for(;t<u&&p(e,t+1);)t++;m[h++]=t,e=t}return h===o?null:m.subarray(0,h)}function kN(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??PN)),s=Math.max(1,Math.round(e.sides??1));if(!t||t.length<12)return null;let c=EN(t,n,o);if(!c)return null;let{points:l,count:u,spans:d}=c,f=e.widths?TN(e.widths,n,d):e=>r+(i-r)*e,p=e.tolerance>0?ON(t,n,c,e.tolerance,f):null,m=p?p.length:u,h=s>=3?s:s*2,g=new Float32Array(m*h*3),_=[0,0,0],v=[0,0,0],y=[0,0,0],b=[0,0,0],x=!1,S=0;for(let e=0;e<u;e++){let t=Math.max(0,e-1),n=Math.min(u-1,e+1);if(_[0]=l[n*3]-l[t*3],_[1]=l[n*3+1]-l[t*3+1],_[2]=l[n*3+2]-l[t*3+2],xN(_),x){let e=v[0]*_[0]+v[1]*_[1]+v[2]*_[2];v[0]-=e*_[0],v[1]-=e*_[1],v[2]-=e*_[2],Math.hypot(v[0],v[1],v[2])<1e-9&&SN(_,[0,1,0],v),xN(v)}else{if(a&&a.length>=3)v[0]=a[0],v[1]=a[1],v[2]=a[2],SN(_,v,b),v[0]=b[0],v[1]=b[1],v[2]=b[2];else{let e=Math.abs(_[0]),t=Math.abs(_[1]),n=Math.abs(_[2]);SN(_,e<t&&e<n?[1,0,0]:t<n?[0,1,0]:[0,0,1],v)}Math.hypot(v[0],v[1],v[2])<1e-9&&SN(_,[0,1,0],v),xN(v),x=!0}if(p&&p[S]!==e)continue;SN(_,v,y),xN(y);let r=f(e/(u-1||1))*.5,i=l[e*3],o=l[e*3+1],c=l[e*3+2];for(let e=0;e<h;e++){let t,n,a;if(s>=3){let r=e/s*Math.PI*2,i=Math.cos(r),o=Math.sin(r);t=v[0]*i+y[0]*o,n=v[1]*i+y[1]*o,a=v[2]*i+y[2]*o}else{let r=e<2?v:y,i=e%2==0?-1:1;t=r[0]*i,n=r[1]*i,a=r[2]*i}let l=(S*h+e)*3;g[l]=i+t*r,g[l+1]=o+n*r,g[l+2]=c+a*r}S++}let C=s,w=new Uint32Array((m-1)*C*6),T=0;for(let e=0;e<m-1;e++)for(let t=0;t<C;t++){let n=s>=3?t:t*2,r=s>=3?(t+1)%s:t*2+1,i=e*h+n,a=e*h+r,o=(e+1)*h+r,c=(e+1)*h+n;w[T++]=i,w[T++]=a,w[T++]=o,w[T++]=i,w[T++]=o,w[T++]=c}return{positions:g,indices:T===w.length?w:yj(w,T)}}function AN(e,t,n,r){let i=new Float64Array((n.length*3+1)*3),a=t?new Float64Array(n.length*3+1):null,o=0;for(let s=0;s<n.length;s++){let[c,l,u,d]=n[s];if(s===0){for(let t=0;t<3;t++)i[t]=e[c*3+t];a&&(a[0]=t[c])}if(r===`linear`)FN(i,(o+1)*3,e,c,l,1/3),FN(i,(o+2)*3,e,c,l,2/3);else for(let t=0;t<3;t++)i[(o+1)*3+t]=e[c*3+t]+(e[l*3+t]-e[u*3+t])/6,i[(o+2)*3+t]=e[l*3+t]-(e[d*3+t]-e[c*3+t])/6;for(let t=0;t<3;t++)i[(o+3)*3+t]=e[l*3+t];a&&(a[o+1]=t[c]+(t[l]-t[c])/3,a[o+2]=t[c]+(t[l]-t[c])*2/3,a[o+3]=t[l]),o+=3}return{P:i,widths:a,basis:`bezier`}}function jN(e,t,n,r,i){let a=e.length/3,o=i===`periodic`;if(n===`linear`){if(a<2)return null;let n=[];for(let e=0;e+1<a;e++)n.push([e,e+1]);return o&&a>2&&n.push([a-1,0]),AN(e,t,n,`linear`)}if(r===`bspline`)return i===`pinned`?MN(e,t,[0,0,...Array.from({length:a},(e,t)=>t),a-1,a-1],`bspline`):o?MN(e,t,[...Array.from({length:a},(e,t)=>t),0,1,2],`bspline`):a>=4?{P:e,widths:t,basis:`bspline`}:null;if(r===`bezier`)return o?MN(e,t,[...Array.from({length:a},(e,t)=>t),0],`bezier`):a>=4?{P:e,widths:t,basis:`bezier`}:null;if(r===`catmullRom`){let n=[],r=e=>o?(e+a)%a:Math.min(a-1,Math.max(0,e)),s=o||i===`pinned`?0:1,c=o?a:i===`pinned`?a-1:a-2;for(let e=s;e<c;e++)n.push([r(e),r(e+1),r(e-1),r(e+2)]);return n.length?AN(e,t,n,`catmullRom`):null}return null}function MN(e,t,n,r){let i=new Float64Array(n.length*3),a=t?new Float64Array(n.length):null;return n.forEach((n,r)=>{for(let t=0;t<3;t++)i[r*3+t]=e[n*3+t];a&&(a[r]=t[n])}),{P:i,widths:a,basis:r}}function NN(e){let{P:t,counts:n,widths:r=null,widthMode:i=`constant`,N:a=null,normalMode:o=`vertex`,type:s=`cubic`,basis:c=`bspline`,wrap:l=`nonperiodic`}=e,u=[],d=0,f=0,p=0,m=0,h=0;for(let g=0;g<n.length;g++){let _=n[g],v=t.subarray?t.subarray(m*3,(m+_)*3):t.slice(m*3,(m+_)*3),y=null,b=1;if(r?.length)if(i===`vertex`)y=Float64Array.from({length:_},(e,t)=>r[m+t]);else if(i===`uniform`)b=r[g]??r[0];else if(i===`varying`){let e=s===`linear`?_-1:c===`bezier`?(_-1)/3:_-3,t=Math.max(1,Math.round(e)+1),n=Array.from({length:t},(e,t)=>r[h+t]??r[r.length-1]);h+=t,y=Float64Array.from({length:_},(e,r)=>n[Math.min(t-1,Math.round(r/Math.max(1,_-1)*(t-1)))])}else b=r[0];let x=null;if(a?.length){let e=o===`uniform`?g:o===`constant`?0:m;x=[a[e*3],a[e*3+1],a[e*3+2]]}let S=jN(v,y,s,c,l),C=S&&kN({P:S.P,basis:S.basis,widths:S.widths,width0:b,width1:b,N:x,steps:e.steps,sides:e.sides,tolerance:e.tolerance});C?(u.push(C),d+=C.positions.length/3,f+=C.indices.length):p++,m+=_}if(u.length===0)return null;let g=new Float32Array(d*3),_=new Uint32Array(f),v=0,y=0;for(let e of u){g.set(e.positions,v*3);for(let t=0;t<e.indices.length;t++)_[y+t]=e.indices[t]+v;v+=e.positions.length/3,y+=e.indices.length}return{positions:g,indices:_,skipped:p}}var PN,FN,IN=g((()=>{xj(),PN=2,FN=(e,t,n,r,i,a)=>{for(let o=0;o<3;o++)e[t+o]=n[r*3+o]+(n[i*3+o]-n[r*3+o])*a}}));async function LN(e,t,n){let r=cM(e,t);if(r?.type===`spectrum`&&typeof r.value[0]==`string`&&r.value[0].startsWith(`stdillum`))return[1,1,1];let i=(await jM(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 RN(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 zN(e,t){if(t<=e.length)return e;let n=e.length||1;for(;n<t;)n*=2;return yj(e,n)}function BN(e){return e instanceof Float32Array?e:Float32Array.from(e)}function VN(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 HN(e,t){let n=Math.min(e.width,pP),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 UN(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 WN(e){let t=kM(e,`encoding`,`sRGB`);if(t===`linear`)return e=>e;let n=/^gamma\s+([\d.]+)$/.exec(t);return n?e=>e**Number(n[1]):nN}function GN(e){return{su:DM(e,`uscale`,1),sv:DM(e,`vscale`,1),du:DM(e,`udelta`,0),dv:DM(e,`vdelta`,0)}}function KN(e,t,n){let r=cM(e,t)?.value;return r&&r.length>=3?[r[0],r[1],r[2]]:n}function qN(e,t){let n=kM(e,`mapping`,`uv`);if(!wP.has(n))return{...GN(e),uv:null};let r={type:n,textureFromWorld:aM(t??Jj())};return n===`planar`&&Object.assign(r,{vs:KN(e,`v1`,[1,0,0]),vt:KN(e,`v2`,[0,1,0]),ds:DM(e,`udelta`,0),dt:DM(e,`vdelta`,0)}),r.key=JSON.stringify(r),{su:1,sv:1,du:0,dv:0,uv:r}}function JN(e,{su:t,sv:n,du:r,dv:i,uv:a=null}){e.repeat.set(t,n),e.offset.set(r,i),a&&(e.userData.pbrtUV=a)}function YN(e){for(let t of TP)if(e[t])return e[t].userData.pbrtUV??null;return null}function XN(e,t){let{array:n,itemSize:i,count:a}=e,o=new n.constructor((a+t.length)*i);o.set(n.subarray(0,a*i));for(let e=0;e<t.length;e++)for(let r=0;r<i;r++)o[(a+e)*i+r]=n[t[e]*i+r];return new r.BufferAttribute(o,i,e.normalized)}function ZN(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?rN(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 QN({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,JN(o,i),o.needsUpdate=!0,o}function $N(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 eP(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 tP(e){let t=DM(e,`radius`,1),n=DM(e,`zmin`,-t),r=DM(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:OP(e)}}function nP(e){let t=DM(e,`zmin`,-1),n=DM(e,`zmax`,1);return{radius:DM(e,`radius`,1),zMin:Math.min(t,n),zMax:Math.max(t,n),phiMax:OP(e)}}function rP(e){return{radius:DM(e,`radius`,1),inner:DM(e,`innerradius`,0),height:DM(e,`height`,0),phiMax:OP(e)}}function iP(e,t,n){let i=Math.max(3,Math.ceil(DP*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 aP(e,t){let n=e.params;switch(e.type){case`sphere`:{let{radius:e,zMin:t,zMax:r,phiMax:i}=tP(n);return i*e*(r-t)}case`cylinder`:{let{radius:e,zMin:t,zMax:r,phiMax:i}=nP(n);return i*e*(r-t)}case`disk`:{let{radius:e,inner:t,phiMax:r}=rP(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 oP(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*rN(Math.min(1,Math.max(0,o[e]))));r[s+3]=255}return r}function sP(e){let t=e.clone();for(let n of Object.keys(e))n in t||(t[n]=e[n]);return t}function cP(e,t){let n=sP(e);return n.transparent=!0,n.opacity=e.opacity*t,n}function lP(e,t){if(e.float||!qM(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 uP(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 dP,fP,pP,mP,hP,gP,_P,vP,yP,bP,xP,SP,CP,wP,TP,EP,DP,OP,kP,AP,jP,MP,NP=g((()=>{xj(),GM(),oN(),pN(),bM(),vN(),IN(),oM(),qn(),Do(),dP=new Set([`distant`,`point`,`spot`]),fP=[1,0,0,0,0,1,0,0,0,0,-1,0,0,0,0,1],pP=4096,mP=1e3,hP=45e6,gP=6e6,_P=256,vP=4096,yP=5e5,bP=1e6,xP=2,SP={flat:1,ribbon:1,cylinder:2},CP=.05,wP=new Set([`planar`,`spherical`,`cylindrical`]),TP=[`map`,`roughnessMap`,`clearcoatRoughnessMap`,`normalMap`,`clearcoatNormalMap`],EP={roughnessMap:`roughness`,clearcoatRoughnessMap:`clearcoatRoughness`},DP=48,OP=e=>Math.min(360,Math.max(0,DM(e,`phimax`,360)))*Math.PI/180,kP=64,AP=64,jP=(e,{su:t,sv:n,du:r,dv:i,uv:a})=>e.repeat.x===t&&e.repeat.y===n&&e.offset.x===r&&e.offset.y===i&&tN(e.userData.pbrtUV)===tN(a),MP=class{constructor(e={}){this.maxTriangles=e.maxTriangles??hP,this.maxPlacements=e.maxPlacements??gP,this.mergeShapesAbove=e.mergeShapesAbove??_P,this.curveSteps=e.curveSteps??xP,this.curveSides=e.curveSides??null,this.curveTolerance=e.curveTolerance??CP,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._usage=e.usage??null,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,this._mappings=new Map,this._oneUVSets=new WeakMap,this._uvWarnings=new Set}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._usage?.open(n.params,`Shape ${n.type}`,`alpha`);this._plyUsers=new Map,this._plyHeld=new Set;for(let t of e.shapes)if(t?.type===`plymesh`){let e=kM(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(kM(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&&!r.shared?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&&!r.shared&&i.getAttribute(`position`).count<=vP){this._mergeShape(r,i,o,t),e.shapes[n]=null;continue}r.type===`plymesh`&&this._plyHeld.add(kM(r.params,`filename`,null));let s=this._meshFromGeometry(r,this._mappedGeometry(i,o,r.ctm),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):[];for(let t of e.lights)this._usage?.open(t.params,`LightSource ${t.type}`);let 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:eP(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=new Map,s=(e,s,c,l,u,d,f)=>{let p=l?Array.prototype.join.call(l,`,`):``,m=o.get(e);m||o.set(e,m=new Map);let h=m.get(p),g=Math.max(0,this.maxPlacements-this.placementCount),_=h?h.count:Math.min(e.count,g);if(!h&&_<e.count&&(this.skippedForBudget+=e.count-_),_===0)return;let v=new r.InstancedMesh(s,c,_);if(v.name=`instance_${n++}`,v.frustumCulled=!1,h)v.instanceMatrix=h.attribute;else{for(let t=0;t<_;t++){if(l)Xj(i,e.matrices,t*16,l);else for(let n=0;n<16;n++)i[n]=e.matrices[t*16+n];v.setMatrixAt(t,a.fromArray(this.convertHandedness?Zj(fP,i):i))}v.instanceMatrix.needsUpdate=!0,m.set(p,{attribute:v.instanceMatrix,count:_}),this.placementCount+=_}t.add(v),this.reportedMeshes+=_,this.report.length<mP&&this.report.push({mesh:`${v.name} ×${_}`,shape:u,material:d,color:`#`+c.color.getHexString(),map:c.map?`yes`:`-`,uv:s.getAttribute(`uv`)?`yes`:`NO`,normals:s.getAttribute(`normal`)?`yes`:`NO`,emissive:c.emissiveIntensity>0?`#${c.emissive.getHexString()}×${c.emissiveIntensity}`:`-`,size:`instanced`,tris:f})},c=(e,t)=>{t&&t.triangles>0&&s(e,this._batchGeometry(t),t.material,null,`merged`,`-`,t.triangles)};for(let{name:n,list:r,template:i}of this._samePlacementGroups(e)){if(!i){this.droppedNoTemplate+=r.count,this.warn(`ObjectInstance "${n}" has no template — ${r.count.toLocaleString()} placement(s) dropped`);continue}let e=0;for(let t of i)t.type!==`plymesh`&&!t.shared&&e++;let a=e>=2?new Map:null;for(let e of i){if(this._overBudget()){this.skippedForBudget+=r.count;continue}let[i,o]=await Promise.all([this._buildGeometry(e),this._getMaterial(e)]);if(!i)continue;let l=i,u=e.relativeCTM||e.ctm;if(YN(o)){if(this._placeMapped(r,e,l,o,u,t,n))continue;l=this._mappedGeometry(l,o,Xj(Array(16),r.matrices,0,u))}else if(a&&e.type!==`plymesh`&&!e.shared&&l.getAttribute(`position`).count<=vP){this._geometryCache.delete(e);let t=this._appendToBatch(a,e,l,o,u);this._releaseMerged(e,l),c(r,t);continue}let d=this._accountGeometry(l),f=this._materialForGeometry(e,l,o,`instances_${n}`);s(r,l,f,u,e.type,e.material?.type||`diffuse`,d)}if(a)for(let e of a.values())c(r,e[0]),c(r,e[1]);vj(r.matrices),vj(r.matricesEnd)}}_placeMapped(e,t,n,r,i,a,o){let s=(n.index?n.index.count:n.getAttribute(`position`).count)/3;if(e.count*s>bP)return this.warn(`ObjectInstance "${o}": its ${e.count.toLocaleString()} copies share the first one's uv from a position-mapped texture`),!1;let c=0;for(;c<e.count&&!this._overBudget();c++){let s=Xj(Array(16),e.matrices,c*16,i);a.add(this._meshFromGeometry(t,this._mappedGeometry(n,r,s),r,s,`instances_${o}_${c}`))}return this.skippedForBudget+=e.count-c,!0}_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=>VN(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);vj(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?Zj(fP,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=t.relativeCTM||t.ctm,a=this._mappedGeometry(n,r,Zj(l,i)),o=this._meshFromGeometry(t,a,r,i,`${c.name}_${e}`,!0);o&&c.add(o)}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?Zj(fP,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?Zj(fP,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<mP&&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=sP(n),i.map=null,this._noUVMaterials.set(n,i)),i}_mergeShape(e,t,n,r){this.reportedMeshes++;let i=this.convertHandedness?Zj(fP,e.ctm):e.ctm,a=this._appendToBatch(this._batches,e,this._mappedGeometry(t,n,e.ctm),n,i);this._releaseMerged(e,t),a&&this._flushBatch(a,r)}_releaseMerged(e,t){if(!this._keepShapes?.has(e)&&!(e.type===`plymesh`&&!this._lastPlyUse(kM(e.params,`filename`,null)))){for(let e in t.attributes)vj(t.attributes[e].array);vj(t.index?.array);for(let t in e.params)ArrayBuffer.isView(e.params[t]?.value)&&vj(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=aM(m),g=p.vertexCount;p.positions=zN(p.positions,(g+u)*3),p.normals=zN(p.normals,(g+u)*3),c&&(p.uvs=zN(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=zN(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>=yP?(d[f]=null,p):null}_batchGeometry(e){let t=new r.BufferGeometry;return t.setAttribute(`position`,new r.BufferAttribute(yj(e.positions,e.vertexCount*3),3)),t.setAttribute(`normal`,new r.BufferAttribute(yj(e.normals,e.vertexCount*3),3)),e.uvs&&t.setAttribute(`uv`,new r.BufferAttribute(yj(e.uvs,e.vertexCount*2),2)),t.setIndex(new r.BufferAttribute(yj(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<mP&&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=e.geometryKey??e,n=this._geometryCache.get(t);return n||this._geometryCache.set(t,n=this._createGeometry(e)),n}async _createGeometry(e){let t=()=>this._shapeGeometry(e),n=await(this._usage?this._usage.translate(e.params,`Shape ${e.type}`,t,`alpha`):t());return n&&e.areaLight&&!AM(e.areaLight.params,`twosided`,!1)?this._facingEmission(e,n):n}_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`curves`:return this._curves(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=cM(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(BN(t),3));let i=cM(e,`N`)?.value;i&&i.length===t.length&&(n.setAttribute(`normal`,new r.Float32BufferAttribute(BN(i),3)),n.userData.pbrtNormals=!0);let a=cM(e,e.uv?`uv`:`st`)?.value;a&&a.length===t.length/3*2&&n.setAttribute(`uv`,new r.Float32BufferAttribute(BN(a),2));let o=cM(e,`indices`)?.value;return o&&o.length&&n.setIndex(RN(o)),i||n.computeVertexNormals(),n}_curve(e){let t=cM(e,`P`)?.value;if(!t||t.length<12)return this.warn(`curve needs at least 4 control points`),null;let n=Math.round(DM(e,`degree`,3));if(n!==3)return this.warn(`curve degree ${n} not supported — only cubic`),null;let i=kM(e,`type`,`flat`),a=DM(e,`width`,1),o=kN({P:t,basis:kM(e,`basis`,`bezier`),width0:DM(e,`width0`,a),width1:DM(e,`width1`,a),N:cM(e,`N`)?.value||null,steps:this.curveSteps,sides:this.curveSides??SP[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.BufferAttribute(o.positions,3)),s.setIndex(new r.BufferAttribute(o.indices,1)),s.computeVertexNormals(),zn(s,`normal`),s}_curves(e){let t=NN({P:cM(e,`P`).value,counts:cM(e,`counts`).value,widths:cM(e,`widths`)?.value??null,widthMode:kM(e,`widthMode`,`constant`),N:cM(e,`N`)?.value??null,normalMode:kM(e,`normalMode`,`vertex`),type:kM(e,`type`,`cubic`),basis:kM(e,`basis`,`bspline`),wrap:kM(e,`wrap`,`nonperiodic`),steps:this.curveSteps,sides:this.curveSides??1,tolerance:this.curveTolerance});if(!t)return this.warn(`curves could not be tessellated`),null;t.skipped>0&&this.warn(`${t.skipped} curve(s) of an unsupported basis or too few points skipped`);let n=new r.BufferGeometry;return n.setAttribute(`position`,new r.BufferAttribute(t.positions,3)),n.setIndex(new r.BufferAttribute(t.indices,1)),n.computeVertexNormals(),zn(n,`normal`),n}_loopSubdiv(e){let t=cM(e,`P`)?.value,n=cM(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(DM(e,`levels`,3)))),{positions:a,indices:o,levels:s}=fN(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=cM(e,`P`)?.value,n=cM(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=cM(e,`uv`)?.value?.length===i*2?e.uv.value:null,o=cM(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=kM(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}=tP(e),a=Math.acos(n/t),o=Math.acos(r/t);return iP(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}=nP(e);return iP(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}=rP(e);return iP(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&&(t=await this._withAlpha(t,e.params.alpha)),this._oneUVSet(t)}_oneUVSet(e){let t=this._oneUVSets.get(e);if(t)return t;t=e;let n=YN(e),r=e=>e?`a "${e.type}" mapping`:`the mesh's uv`;for(let i of TP){let a=e[i];if(!a||tN(a.userData.pbrtUV)===tN(n))continue;t===e&&(t=sP(e)),t[i]=null;let o=EP[i],s=o&&this._textureLayer(a,1);s&&(t[o]*=JM(s));let c=`a ${i} in ${r(a.userData.pbrtUV)} on a surface textured in ${r(n)}: one uv set a surface — ${s?`its mean used`:`dropped`}`;this._uvWarnings.has(c)||(this._uvWarnings.add(c),this.warn(c))}return this._oneUVSets.set(e,t),t}_mappedGeometry(e,t,n){let i=YN(t);if(!i)return e;let{uv:a,index:o,extra:s}=$M(e.getAttribute(`position`).array,e.index?.array??null,Zj(i.textureFromWorld,n),i),c=new r.BufferGeometry;c.name=e.name,Object.assign(c.userData,e.userData);for(let t in e.attributes)t!==`uv`&&c.setAttribute(t,s.length?XN(e.getAttribute(t),s):e.getAttribute(t));return c.setAttribute(`uv`,new r.BufferAttribute(a,2)),o?c.setIndex(new r.Uint32BufferAttribute(o,1)):e.index&&c.setIndex(e.index),c}_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?cP(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?cP(e,r.constant):e;let i=sP(e);return i.map=r,i.transparent=!0,i}async _alphaMap(e,t){let n=this._textureDef(t),r=n?.class===`imagemap`?kM(n.params,`filename`,null):null,i=r&&this._textureMapping(t,n);if(r&&e?.userData.pbrtImage===r&&DM(n.params,`scale`,1)===1&&!AM(n.params,`invert`,!1)&&jP(e,i)){let t=UN(e),r=t&&lP(t,WN(n.params));if(r)return JN(r,i),r}let a=await this._bakeTerm(t,1);if(!a)return null;if(!a.layer)return{constant:a.rgb[0]};let o=e?this._textureLayer(e,3):null;if(e&&!o)return null;let s=this._bake(`alpha "${t}"`,[o?{layer:o}:{rgb:[1,1,1]},a],([e])=>e,{alphaOf:([,e])=>e[0]});return s&&QN(s)}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 zM(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,trackParams:(e,t,n)=>this._usage?.open(e,t,n),warn:e=>this.warn(e),floatTextureMean:async e=>{let t=await this._bakeTerm(e,1);return t?t.layer?JM(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=ZN(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&&kM(n,`type`,``);if(this._usage?.open(n,`MakeNamedMedium ${r}`,`type`),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 "${kM(n,`preset`,``)}" is not supported — using sigma_a / sigma_s`),lM(n,`preset`));let i=this._materialContext(),a=(await jM(n,`sigma_a`,i,[1,1,1])).rgb,o=(await jM(n,`sigma_s`,i,[1,1,1])).rgb,s=DM(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=sP(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}|${e.diffuseRoughness??0}`;return this._materialBySignature.get(r)||(this._materialBySignature.set(r,e),e)}_poweredMaterial(e,t,n){let r=DM(e.areaLight.params,`power`,-1);if(!(r>0))return n;let i=aP(e,t)*(AM(e.areaLight.params,`twosided`,!1)?2:1);if(!(i>0))return n;let a=sP(n);return a.emissiveIntensity=n.emissiveIntensity*r/(Math.PI*i),a}async _applyAreaLight(e,t,n){this._usage?.open(t.params,`AreaLightSource ${t.type}`);let i=await LN(t.params,`L`,n),a=DM(t.params,`scale`,1);e.emissive.setRGB(i[0],i[1],i[2]),e.emissiveIntensity=a,e.side=AM(t.params,`twosided`,!1)?r.DoubleSide:r.FrontSide}_textureDef(e){let t=this.ir.namedTextures.get(e);return t&&this._usage?.open(t.params,`Texture ${t.class}`),t}async _resolveNamedTexture(e){if(this._textureCache.has(e))return this._textureCache.get(e);let t=this._textureDef(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=cM(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=cM(n,e);return i?.type===`texture`?(lM(n,e),await r.textureMeanRGB(i.value[0])??t):(await jM(n,e,r,t)).rgb??t},{su:a,sv:o,du:s,dv:c,uv:l}=this._textureMapping(e,t);if(t.class===`checkerboard`){if(DM(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])]),u=2*kP;return{texture:QN({data:oP(u,u,(e,n)=>(Math.floor(2*e)+Math.floor(2*n))%2?r:t),width:u,height:u,mapping:{su:a/2,sv:o/2,du:s/2,dv:c/2,uv:l}})}}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:QN({data:oP(AP,AP,(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:AP,height:AP,mapping:{su:a,sv:o,du:s,dv:c,uv:l}})}}_textureMapping(e,t){let n=this._mappings.get(e);if(!n){let r=kM(t.params,`mapping`,`uv`);r!==`uv`&&!wP.has(r)&&this.warn(`texture "${e}": unknown mapping "${r}" — using the mesh's uv`),this._mappings.set(e,n=qN(t.params,t.ctm))}return n}_bake(e,t,n,r){let i=ZM(t,n,r);return i?.averaged&&this.warn(`${e}: ${i.averaged} input(s) in another uv set than the first image — read as their mean`),i}_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=kM(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=this._textureMapping(e,t),a=DM(t.params,`scale`,1);if(a>1||AM(t.params,`invert`,!1)){let t=await this._bakeTerm(e,3),n=t?.layer&&this._bake(`texture "${e}"`,[{...t,clamp:!0}],([e])=>e);if(n)return{texture:QN(n)};this.warn(`texture "${e}": its scale or invert could not be baked here — ignored`)}let o=ZN(r,{srgb:!0}),s=o===r?r.clone():o;return s.userData.pbrtImage=n,JN(s,i),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=this._bake(`"${t.join(`", "`)}"`,r,e=>{let t=n(e.map(e=>e[0]));return[t,t,t]},{linear:!0});return i&&QN(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=this._bake(`texture "${e}"`,[{...n,clamp:!0},{...r,clamp:!0},i],iN);return o?{texture:QN(o)}:{constant:iN([a(n.rgb),a(r.rgb),i.rgb])}}async _paramTerm(e,t,n,r){let i=cM(e,t);if(!i)return{rgb:r};if(i.type===`texture`)return this._bakeTerm(i.value[0],n);let a=(await jM(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._textureDef(e);if(n?.class===`imagemap`){let r=kM(n.params,`filename`,null),i=UN(r&&await this._image(r));return i?{layer:KM(i,{channels:t,decode:i.float?null:WN(n.params),scale:DM(n.params,`scale`,1),invert:AM(n.params,`invert`,!1),mapping:this._textureMapping(e,n)})}: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=UN(e);if(!n)return null;let i=!n.float&&e.colorSpace===r.SRGBColorSpace;return KM(n,{channels:t,decode:n.float?null:i?nN:e=>e,mapping:{su:e.repeat.x,sv:e.repeat.y,du:e.offset.x,dv:e.offset.y,uv:e.userData.pbrtUV??null}})}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=JM(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=this._bake(`mix amount "${n}"`,[o,s,r],iN);return{mean:i,texture:c?QN(c):null}}_colorFromLikeNamedMaterial(e){for(let t of uP(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 t=this._bake(`texture "${e}"`,[{...n,clamp:!0},r],i);return t?{texture:QN(t)}:{constant:i([n.rgb,r.rgb])}}this.warn(`texture "${e}": its "scale" texture could not be read here — ignored`)}let n=cM(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=cM(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;this._usage?.open(e.params,`Camera ${e.type}`);let i;if(e.type===`orthographic`){let t=cM(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=DM(e.params,`lensradius`,0);return a>0&&(i.userData.__rayzeeEffects=$N(i,a,DM(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)),Yj(t)>0!==this.convertHandedness&&(e.scale.x=-1)}_verticalFov(e,t){let n=DM(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=HN(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}=gN(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=DM(t.params,`scale`,1),i=kM(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 LN(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(!dP.has(i.type))continue;let e=new r.Matrix4().fromArray(this.convertHandedness?Zj(fP,i.ctm):i.ctm),a=(t,n)=>{let a=cM(i.params,t)?.value;return new r.Vector3().fromArray(a?.length>=3?a:n).applyMatrix4(e)},o=await LN(i.params,i.type===`distant`?`L`:`I`,n),s=DM(i.params,`scale`,1),c=a(`from`,[0,0,0]),l=a(`to`,[0,0,1]),u;if(i.type===`distant`){let e=DM(i.params,`illuminance`,-1);e>0&&(s*=e),u=new r.DirectionalLight,u.userData.__luxConverted=!0}else if(i.type===`point`){let e=DM(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(DM(i.params,`coneangle`,30),0),90)*Math.PI/180,t=Math.min(Math.max(DM(i.params,`conedeltaangle`,5)*Math.PI/180,0),e),n=Math.cos(e),a=Math.cos(e-t),o=DM(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`&&!dP.has(t.type)&&this.warn(`light "${t.type}" not supported (only infinite, distant, point and spot lights and emissive area lights are mapped)`)}}}));function PP(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,GP).map(([e,t])=>({path:t,number:e}))}function FP(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 IP(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?`#`+FP(i):i.join(`,`)};`}return t}function LP(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&&!RP(e,r,i,t,r,a,n)&&BP(e,r,i,t,r,a,n),n}function RP(e,t,n,r,i,a,o){let s=n-t,c=a-i,l=Math.min(s+c,KP),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)),zP(f,s,c,t,i,o),!0}f.push(d.slice(u-n,u+n+1))}return!1}function zP(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 BP(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 VP(e,t,n,r){for(let i=0;i<16;i++)if(e[t+i]!==n[r+i])return!1;return!0}function HP(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 UP(e){if(e.visible)return!1;let t=e.matrices;for(let e=16;e<t.length;e+=16)if(!VP(t,0,t,e))return!1;return!0}function WP(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;VP(t.matrices,i,t.matricesEnd,i)||e.animatedInstances.length>=qP?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 GP,KP,qP,JP,YP,XP=g((()=>{GP=1e3,KP=2048,qP=1e5,JP=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}|${IP(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+`:`+IP(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+`:`+IP(e.params)),t}},YP=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 JP(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?LP(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&&!VP(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&&VP(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=HP(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=HP(t,()=>!0,e=>r[e].cameraToWorld),i=r.map(e=>e.fov??r[0].fov),a=i.some(e=>e!==i[0]);(!UP(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<qP){let n=HP(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 ${qP.toLocaleString()} left static`),r}}}));function ZP(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 QP(e,t){return!e||t.startsWith(`/`)?ZP(t):ZP(`${e}/${t}`)}function $P(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 eF(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 tF(e){for(let t=$P(e,mF);t>=0;t=$P(e,mF,t+1))if(eF(e,t))return!0;return!1}function nF(e,t){for(let n of hF)for(let r=$P(e,n);r>=0;r=$P(e,n,r+1)){if(!eF(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=uF.decode(e.subarray(a,i));t.add(ZP(o).toLowerCase().split(`/`).pop())}}function rF(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,tF(t)),nF(t,n)}return iF(t,r,n)}function iF(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 aF(e){return rF(e)[0]||null}async function oF(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,tF(t)),nF(t,r),t.length>=pF&&(a=!0),o.lazy&&(e.release(o),vj(t)))}return{included:r,worlds:i,cut:a}},r=await n(t=>e.readHead(t,pF)),{included:i,worlds:a}=[...r.worlds.values()].filter(Boolean).length===1||!r.cut?r:await n(t=>e.read(t));return iF(t.map(e=>e.key),a,i)}async function sF(e){let{vfs:t,source:n,plyParser:r,imageFromBytes:i,envFromBytes:a,convertHandedness:o}=e,s=new dF(t,n),c=[],l=await oF(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=new vM,p=async t=>{let n=await s.readPath(t);if(!n)throw Error(`PBRT loader: entry "${t}" not readable`);let r=await new yM({resolveInclude:(e,t)=>s.readPath(e,t),releaseInclude:(e,t,n)=>s.releasePath(e,t,n),maxPlacements:e.maxPlacements,instanceIncludes:e.instanceIncludes,usage:f}).parse(n,t.includes(`/`)?t.slice(0,t.lastIndexOf(`/`)):``);return s.releasePath(t,null,n),r},m=performance.now(),h=!u&&e.animation!==!1?PP(l):null,g;if(h){let e=await p(h[0].path);if(e.shapes.length+e.instanceCount>lF)c.push(`${h.length} animation frames found, but the scene is too large to parse once per frame — loaded "${h[0].path}" only`),h=null,g=WP(e);else{let t=new YP(h.map(e=>(e.number-h[0].number)/30),cF(h));t.addFrame(e);for(let e=1;e<h.length;e++)t.addFrame(await p(h[e].path));g=t.finish()}}else g=WP(await p(d));let _=performance.now()-m;s.releaseScenes();let v=e=>e.byteOffset===0&&e.byteLength===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength),y=new Map,b=async e=>{let t=await s.read(e);return t?(s.release(e),r(v(t))):null},x=new MP({convertHandedness:o,maxTriangles:e.maxTriangles,maxPlacements:e.maxPlacements,mergeShapesAbove:e.mergeShapesAbove,curveSteps:e.curveSteps,curveSides:e.curveSides,curveTolerance:e.curveTolerance,usage:f,resolvePLY:async e=>{let t=s.findRecord(e);return t?(y.has(t.norm)||y.set(t.norm,await b(t)),y.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}}),S=performance.now(),C,w;try{C=await x.build(g)}finally{w=f.finish()}return{...C,parameters:w,entryPath:h?h[0].path:d,frames:h?h.map(e=>e.path):null,candidates:l,warnings:[...c,...C.warnings??[]],parseMs:_,buildMs:performance.now()-S}}function cF(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 lF,uF,dF,fF,pF,mF,hF,gF=g((()=>{xj(),bM(),NP(),XP(),qj(),lF=2e6,uF=new TextDecoder,dF=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=ZP(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(QP(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(QP(t,e))||this.findRecord(e);r?.lazy&&(this.release(r),vj(n))}releaseScenes(){for(let e of this.records)e.norm.endsWith(`.pbrt`)&&this.release(e)}findRecord(e){let t=ZP(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}},fF=e=>Uint8Array.from(e,e=>e.charCodeAt(0)),pF=4*1024*1024,mF=fF(`WorldBegin`),hF=[fF(`Include`),fF(`Import`)]}));function _F(e,t=null){let n=[];for(let r=e.length-1;r>=0;r--){let i=e[r];if(!i)continue;let a=e=>e.map(e=>({value:e,source:t?t[r]:null}));if(i.explicit){n=a(i.explicit);continue}let o=e=>{let t=new Set(e.map(DF));t.size&&(n=n.filter(e=>!t.has(DF(e.value))))};o(i.delete);let s=new Set(n.map(e=>DF(e.value)));for(let e of a(i.add))s.has(DF(e.value))||n.push(e);o(i.prepend),n=[...a(i.prepend),...n],o(i.append),n=[...n,...a(i.append)]}return n}function vF(e,t,n){t===`explicit`?e.explicit=n:t!==`reorder`&&e[t].push(...n)}function yF(){if(PF)return PF;PF=new Float32Array(65536);for(let e=0;e<65536;e++){let t=e&32768?-1:1,n=e>>10&31,r=e&1023;PF[e]=n===0?t*2**-14*(r/1024):n===31?r?NaN:t*(1/0):t*2**(n-15)*(1+r/1024)}return PF}function bF(e,t,n,r,i){let a=t;for(;a<n;){let t=e[a++],o=t>>4;if(o===15){let t;do t=e[a++],o+=t;while(t===255)}if(r.set(e.subarray(a,a+o),i),a+=o,i+=o,a>=n)break;let s=e[a]|e[a+1]<<8;a+=2;let c=(t&15)+4;if(c===19){let t;do t=e[a++],c+=t;while(t===255)}let l=i-s;if(s>=c)r.copyWithin(i,l,l+c),i+=c;else for(let e=0;e<c;e++)r[i++]=r[l++]}return i}function xF(e,t){let n=new Uint8Array(t),r=e[0];if(r===0)return n.subarray(0,bF(e,1,e.length,n,0));let i=new DataView(e.buffer,e.byteOffset,e.byteLength),a=1,o=0;for(let t=0;t<r;t++){let t=i.getInt32(a,!0);a+=4,o=bF(e,a,a+t,n,o),a+=t}return n.subarray(0,o)}function SF(e,t,n){let r=new DataView(e.buffer,e.byteOffset,e.byteLength),i=n?Number(r.getBigInt64(0,!0)):r.getInt32(0,!0),a=n?8:4,o=a+(t*2+7>>3),s=n?new Float64Array(t):new Int32Array(t),c=0;for(let l=0;l<t;){let u=e[a++];for(let e=0;e<4&&l<t;e++,l++){let t=u>>e*2&3,a;t===0?a=i:n?t===1?(a=r.getInt16(o,!0),o+=2):t===2?(a=r.getInt32(o,!0),o+=4):(a=Number(r.getBigInt64(o,!0)),o+=8):t===1?(a=r.getInt8(o),o+=1):t===2?(a=r.getInt16(o,!0),o+=2):(a=r.getInt32(o,!0),o+=4),c=n?c+a:c+a|0,s[l]=c}}return s}function CF(e,t,n){switch(t){case`specifier`:e.specifier=HF[n]??`over`;break;case`typeName`:e.typeName=n||``;break;case`primChildren`:case`properties`:case`variantChildren`:case`variantSetChildren`:break;case`references`:case`specializes`:case`apiSchemas`:case`variantSetNames`:n&&((e.arcs??={})[t]=n);break;case`inheritPaths`:n&&((e.arcs??={}).inherits=n);break;case`payload`:n instanceof TF?(e.arcs??={}).payload={...EF(),explicit:[n]}:n&&((e.arcs??={}).payload=n);break;case`variantSelection`:n&&(e.variantSelection=n);break;default:e.meta[t]=n}}function wF(e,t=``){let n=new IF(e),r=new AF(t),i=new Map,a=e=>{let t=i.get(e);if(t)return t;let o=n.pathParent[e];if(o<0)t=r.root;else{let r=a(o),i=n.pathElement[e];if(i.startsWith(`{`)){let[e,n]=i.slice(1,-1).split(`=`);t=r.variant(e,n,!0)??r}else t=r.child(i,!0)}return i.set(e,t),t},o=[];for(let e=0;e<n.specTypes.length;e++){let t=n.specTypes[e],i=n.specPaths[e],s=n.fieldsOf(n.specFieldSets[e]);if(t===RF){for(let[e,t,i]of s)e!==`primChildren`&&(r.meta[e]=n.value(t,i));continue}if(t===LF||t===zF){let e=a(i);for(let[t,r,i]of s){let a=n.value(r,i);t===`primChildren`&&a?.length&&o.push([e,a]),CF(e,t,a)}continue}if(t!==BF&&t!==VF||!n.pathIsProperty[i])continue;let c=a(n.pathParent[i]).property(n.pathElement[i],!0);c.rel=t===VF;for(let[e,t,r]of s)if(e===`default`)c.hasValue=!0,c._lazyValue=()=>n.value(t,r);else if(e===`timeSamples`)c._lazySamples=()=>n.value(t,r);else{let i=n.value(t,r);e===`typeName`?c.type=i:e===`targetPaths`?c.targets=i:e===`connectionPaths`?c.connections=i:e===`variability`?c.uniform=i===1:e===`custom`?c.custom=i===!0:c.meta[e]=i}}for(let[e,t]of o){if(!e.children)continue;let n=new Map;for(let r of t)e.children.has(r)&&n.set(r,e.children.get(r));for(let[t,r]of e.children)n.has(t)||n.set(t,r);e.children=n}return r}var TF,EF,DF,OF,kF,AF,$,jF,MF,NF,PF,FF,IF,LF,RF,zF,BF,VF,HF,UF=g((()=>{TF=class{constructor(e,t){this.asset=e,this.path=t}},EF=()=>({explicit:null,prepend:[],append:[],add:[],delete:[]}),DF=e=>e instanceof TF?`${e.asset}\u0000${e.path}`:String(e),OF=class{constructor(e){this.name=e,this.rel=!1,this.type=``,this._value=void 0,this._lazyValue=null,this.hasValue=!1,this._timeSamples=null,this._lazySamples=null,this.targets=null,this.connections=null,this.meta={},this.uniform=!1,this.custom=!1}get value(){return this._lazyValue&&=(this._value=this._lazyValue(),null),this._value}set value(e){this._value=e,this._lazyValue=null}get timeSamples(){return this._lazySamples&&=(this._timeSamples=this._lazySamples(),null),this._timeSamples}set timeSamples(e){this._timeSamples=e,this._lazySamples=null}setTargets(e,t){vF(this.targets??=EF(),e,t)}setConnections(e,t){vF(this.connections??=EF(),e,t)}},kF=class e{constructor(e){this.name=e,this.specifier=`over`,this.typeName=``,this.meta={},this.arcs=null,this.variantSelection=null,this.variantSets=null,this.children=null,this.props=null,this.reorder=null}child(t,n=!1){let r=this.children?.get(t)??null;return!r&&n&&(this.children??=new Map,this.children.set(t,r=new e(t))),r}variant(t,n,r=!1){let i=this.variantSets?.get(t)??null;if(!i){if(!r)return null;this.variantSets??=new Map,this.variantSets.set(t,i=new Map)}let a=i.get(n)??null;return!a&&r&&n&&i.set(n,a=new e(n)),a}property(e,t=!1){let n=this.props?.get(e)??null;return!n&&t&&(this.props??=new Map,this.props.set(e,n=new OF(e))),n}setArc(e,t,n){this.arcs??={},vF(this.arcs[e]??=EF(),t,n)}},AF=class{constructor(e){this.path=e,this.meta={},this.root=new kF(``),this.root.specifier=`def`}},$={Bool:1,UChar:2,Int:3,UInt:4,Int64:5,UInt64:6,Half:7,Float:8,Double:9,String:10,Token:11,AssetPath:12,Matrix2d:13,Matrix3d:14,Matrix4d:15,Quatd:16,Quatf:17,Quath:18,Vec2d:19,Vec2f:20,Vec2h:21,Vec2i:22,Vec3d:23,Vec3f:24,Vec3h:25,Vec3i:26,Vec4d:27,Vec4f:28,Vec4h:29,Vec4i:30,Dictionary:31,TokenListOp:32,StringListOp:33,PathListOp:34,ReferenceListOp:35,IntListOp:36,Int64ListOp:37,UIntListOp:38,UInt64ListOp:39,PathVector:40,TokenVector:41,Specifier:42,Permission:43,Variability:44,VariantSelectionMap:45,TimeSamples:46,Payload:47,DoubleVector:48,LayerOffsetVector:49,StringVector:50,ValueBlock:51,Value:52,PayloadListOp:55,TimeCode:56},jF={[$.Bool]:[1,`bool`],[$.UChar]:[1,`u8`],[$.Int]:[1,`i32`],[$.UInt]:[1,`u32`],[$.Int64]:[1,`i64`],[$.UInt64]:[1,`u64`],[$.Half]:[1,`f16`],[$.Float]:[1,`f32`],[$.Double]:[1,`f64`],[$.TimeCode]:[1,`f64`],[$.Matrix2d]:[4,`f64`],[$.Matrix3d]:[9,`f64`],[$.Matrix4d]:[16,`f64`],[$.Quatd]:[4,`f64`],[$.Quatf]:[4,`f32`],[$.Quath]:[4,`f16`],[$.Vec2d]:[2,`f64`],[$.Vec2f]:[2,`f32`],[$.Vec2h]:[2,`f16`],[$.Vec2i]:[2,`i32`],[$.Vec3d]:[3,`f64`],[$.Vec3f]:[3,`f32`],[$.Vec3h]:[3,`f16`],[$.Vec3i]:[3,`i32`],[$.Vec4d]:[4,`f64`],[$.Vec4f]:[4,`f32`],[$.Vec4h]:[4,`f16`],[$.Vec4i]:[4,`i32`]},MF=new Set([$.Vec2d,$.Vec2f,$.Vec2i,$.Vec3d,$.Vec3f,$.Vec3h,$.Vec3i,$.Vec4d,$.Vec4f,$.Vec4h,$.Vec4i]),NF={[$.Matrix2d]:2,[$.Matrix3d]:3,[$.Matrix4d]:4},PF=null,FF=new DataView(new ArrayBuffer(4)),IF=class{constructor(e){if(this.buffer=e,this.bytes=new Uint8Array(e),this.view=new DataView(e),this.pos=0,String.fromCharCode(...this.bytes.subarray(0,8))!==`PXR-USDC`)throw Error(`not a usdc layer`);if(this.major=this.bytes[8],this.minor=this.bytes[9],this.patch=this.bytes[10],this.older(0,4))throw Error(`usdc ${this.major}.${this.minor}.${this.patch} predates 0.4.0 and is not read`);this.pos=16,this.pos=this.u64(),this.sections={};for(let e=this.u64();e>0;e--){let e=``;for(let t=0;t<16;t++){let n=this.bytes[this.pos+t];if(n===0)break;e+=String.fromCharCode(n)}this.pos+=16,this.sections[e]={start:this.u64(),size:this.u64()}}this.readTokens(),this.readStrings(),this.readFields(),this.readFieldSets(),this.readPaths(),this.readSpecs()}older(e,t){return this.major<e||this.major===e&&this.minor<t}seek(e){let t=this.sections[e];return t?(this.pos=t.start,!0):!1}u8(){return this.bytes[this.pos++]}i8(){let e=this.view.getInt8(this.pos);return this.pos+=1,e}u32(){let e=this.view.getUint32(this.pos,!0);return this.pos+=4,e}i32(){let e=this.view.getInt32(this.pos,!0);return this.pos+=4,e}u64(){let e=this.view.getUint32(this.pos,!0),t=this.view.getUint32(this.pos+4,!0);return this.pos+=8,t*4294967296+e}i64(){let e=this.view.getUint32(this.pos,!0),t=this.view.getInt32(this.pos+4,!0);return this.pos+=8,t*4294967296+e}f64(){let e=this.view.getFloat64(this.pos,!0);return this.pos+=8,e}ints(e,t=!1){let n=this.u64(),r=this.bytes.subarray(this.pos,this.pos+n);return this.pos+=n,SF(xF(r,(t?8:4)+(e*2+7>>3)+e*(t?8:4)),e,t)}readTokens(){if(this.tokens=[],!this.seek(`TOKENS`))return;let e=this.u64(),t=this.u64(),n=this.u64(),r=xF(this.bytes.subarray(this.pos,this.pos+n),t),i=new TextDecoder,a=0;for(let t=0;t<e;t++){let e=a;for(;e<r.length&&r[e]!==0;)e++;this.tokens.push(i.decode(r.subarray(a,e))),a=e+1}}readStrings(){if(this.strings=[],this.seek(`STRINGS`))for(let e=this.u64();e>0;e--)this.strings.push(this.u32())}readFields(){if(!this.seek(`FIELDS`))return;let e=this.u64();this.fieldTokens=this.ints(e);let t=this.u64(),n=xF(this.bytes.subarray(this.pos,this.pos+t),e*8);this.fieldReps=new Uint32Array(n.slice().buffer)}readFieldSets(){this.fieldSets=new Int32Array,this.seek(`FIELDSETS`)&&(this.fieldSets=this.ints(this.u64()))}readPaths(){if(!this.seek(`PATHS`))return;let e=this.u64(),t=this.u64(),n=this.ints(t),r=this.ints(t),i=this.ints(t);this.pathParent=new Int32Array(e).fill(-1),this.pathElement=Array(e).fill(``),this.pathIsProperty=new Uint8Array(e);let a=[[0,-1]];for(;a.length;){let[e,t]=a.pop();for(;;){let o=n[e];if(t>=0){let n=r[e];this.pathParent[o]=t,this.pathElement[o]=this.tokens[Math.abs(n)]??``,this.pathIsProperty[o]=+(n<0)}let s=i[e],c=s>0||s===-1,l=s>=0;if(c&&l&&a.push([e+s,t]),c)t=o;else if(!l)break;e++}}this.pathStrings=Array(e)}readSpecs(){if(this.specPaths=this.specFieldSets=this.specTypes=new Int32Array,!this.seek(`SPECS`))return;let e=this.u64();this.specPaths=this.ints(e),this.specFieldSets=this.ints(e),this.specTypes=this.ints(e)}path(e){let t=this.pathStrings[e];if(t!==void 0)return t;let n=this.pathParent[e],r=this.pathElement[e];if(n<0)t=`/`;else{let i=this.path(n);t=this.pathIsProperty[e]?`${i}.${r}`:r.startsWith(`{`)?i+r:i===`/`?`/${r}`:`${i}/${r}`}return this.pathStrings[e]=t,t}fieldsOf(e){let t=[];for(let n=e;n<this.fieldSets.length;n++){let e=this.fieldSets[n];if(e<0)break;t.push([this.tokens[this.fieldTokens[e]],this.fieldReps[e*2],this.fieldReps[e*2+1]])}return t}value(e,t){let n=t>>>16&255,r=e+(t&65535)*4294967296;if(n===$.TimeSamples)return this.timeSamples(r);if(t&1073741824)return this.inlined(n,e);let i=(t&2147483648)!=0;if(i&&r===0)return[];let a=this.pos;this.pos=r;let o=i?this.array(n,(t&536870912)!=0):this.scalar(n);return this.pos=a,o}inlined(e,t){switch(e){case $.Bool:return t!==0;case $.Int:return t|0;case $.Float:case $.Double:case $.TimeCode:return FF.setUint32(0,t,!0),FF.getFloat32(0,!0);case $.Half:return yF()[t&65535];case $.Token:case $.AssetPath:return this.tokens[t]??``;case $.String:return this.tokens[this.strings[t]]??``;case $.Vec2h:return[yF()[t&65535],yF()[t>>>16]];case $.ValueBlock:return null;case $.Dictionary:return{}}let n=e=>t>>>e*8<<24>>24;if(MF.has(e))return Array.from({length:jF[e][0]},(e,t)=>n(t));let r=NF[e];if(r){let e=Array(r*r).fill(0);for(let t=0;t<r;t++)e[t*r+t]=n(t);return e}return t}element(e){switch(e){case`bool`:return this.u8()!==0;case`u8`:return this.u8();case`i32`:return this.i32();case`u32`:return this.u32();case`i64`:return this.i64();case`u64`:return this.u64();case`f16`:{let e=yF()[this.view.getUint16(this.pos,!0)];return this.pos+=2,e}case`f32`:{let e=this.view.getFloat32(this.pos,!0);return this.pos+=4,e}default:return this.f64()}}listOp(e){let t=this.u8(),n=EF(),r=()=>{let t=[];for(let n=this.u64();n>0;n--)t.push(e());return t};return t&1&&(n.explicit=[]),t&2&&(n.explicit=r()),t&4&&(n.add=r()),t&32&&(n.prepend=r()),t&64&&(n.append=r()),t&8&&(n.delete=r()),t&16&&r(),n}string(){return this.tokens[this.strings[this.u32()]]??``}reference(){let e=this.string(),t=this.path(this.u32());return this.f64(),this.f64(),this.dictionary(),new TF(e,t===`/`?``:t)}payload(){let e=this.string(),t=this.path(this.u32());return this.older(0,8)||(this.f64(),this.f64()),new TF(e,t===`/`?``:t)}recursive(){return this.pos+=this.i64(),this.value(this.u32(),this.u32())}dictionary(){let e={};for(let t=this.u64();t>0;t--){let t=this.string();e[t]=this.recursive()}return e}scalar(e){let t=jF[e];if(t)return t[0]===1?this.element(t[1]):Array.from({length:t[0]},()=>this.element(t[1]));switch(e){case $.String:return this.string();case $.Token:case $.AssetPath:return this.tokens[this.u32()]??``;case $.Specifier:case $.Permission:case $.Variability:return this.u32();case $.Dictionary:return this.dictionary();case $.TokenListOp:return this.listOp(()=>this.tokens[this.u32()]??``);case $.StringListOp:return this.listOp(()=>this.string());case $.PathListOp:return this.listOp(()=>this.path(this.u32()));case $.ReferenceListOp:return this.listOp(()=>this.reference());case $.PayloadListOp:return this.listOp(()=>this.payload());case $.IntListOp:return this.listOp(()=>this.i32());case $.UIntListOp:return this.listOp(()=>this.u32());case $.Int64ListOp:return this.listOp(()=>this.i64());case $.UInt64ListOp:return this.listOp(()=>this.u64());case $.Payload:return this.payload();case $.PathVector:return Array.from({length:this.u64()},()=>this.path(this.u32()));case $.TokenVector:return Array.from({length:this.u64()},()=>this.tokens[this.u32()]??``);case $.StringVector:return Array.from({length:this.u64()},()=>this.string());case $.DoubleVector:return Float64Array.from({length:this.u64()},()=>this.f64());case $.LayerOffsetVector:return Array.from({length:this.u64()},()=>[this.f64(),this.f64()]);case $.VariantSelectionMap:{let e={};for(let t=this.u64();t>0;t--){let t=this.string();e[t]=this.string()}return e}case $.Value:return this.recursive();default:return null}}typed(e,t){let n=t*e.BYTES_PER_ELEMENT,r=new e(this.buffer.slice(this.pos,this.pos+n));return this.pos+=n,r}array(e,t){this.older(0,5)&&this.u32();let n=this.older(0,7)?this.u32():this.u64();if(t)return this.compressedArray(e,n);let r=jF[e];if(r){let[e,t]=r,i=n*e;switch(t){case`f32`:return this.typed(Float32Array,i);case`f64`:return this.typed(Float64Array,i);case`i32`:return this.typed(Int32Array,i);case`u32`:return this.typed(Uint32Array,i);case`u8`:return this.typed(Uint8Array,i);case`f16`:{let e=this.typed(Uint16Array,i),t=yF(),n=new Float32Array(i);for(let r=0;r<i;r++)n[r]=t[e[r]];return n}default:return Array.from({length:i},()=>this.element(t))}}switch(e){case $.String:return Array.from({length:n},()=>this.string());case $.Token:case $.AssetPath:return Array.from({length:n},()=>this.tokens[this.u32()]??``);default:return null}}compressedArray(e,t){switch(e){case $.Int:return this.ints(t);case $.UInt:return new Uint32Array(this.ints(t).buffer);case $.Int64:case $.UInt64:return this.ints(t,!0);case $.Half:case $.Float:case $.Double:{let n=e===$.Double?Float64Array:Float32Array,r=this.i8();if(r===105)return n.from(this.ints(t));if(r!==116)throw Error(`usdc: unknown float array coding ${r}`);let i=Array.from({length:this.u32()},()=>this.element(e===$.Half?`f16`:e===$.Float?`f32`:`f64`)),a=this.ints(t),o=new n(t);for(let e=0;e<t;e++)o[e]=i[a[e]];return o}default:throw Error(`usdc: compressed array of type ${e} is not read`)}}timeSamples(e){let t=this.pos;this.pos=e,this.pos=e+this.i64();let n=[this.u32(),this.u32()];this.pos+=this.i64();let r=[];for(let e=this.u64();e>0;e--)r.push([this.u32(),this.u32()]);this.pos=t;let i=r.map(([e,t])=>this.value(e,t));return new Map(Array.from(this.value(...n)??[],(e,t)=>[e,i[t]]))}},LF=6,RF=7,zF=10,BF=1,VF=8,HF=[`def`,`over`,`class`]}));function WF(e){if(e===null)return[];let t=Array.isArray(e)?e:[e],n=[];for(let e of t)e instanceof TF?n.push(e):e instanceof iI?n.push(new TF(e.asset,``)):e instanceof aI&&n.push(new TF(``,e.path));return n}function GF(e){return e===null?[]:(Array.isArray(e)?e:[e]).filter(e=>e instanceof aI).map(e=>e.path)}function KF(e){return e===null?[]:(Array.isArray(e)?e:[e]).map(String)}function qF(e){return e instanceof iI?e.asset:e instanceof aI?e.path:Array.isArray(e)?e.map(qF):e}function JF(e,t){for(let n of e)Array.isArray(n)?JF(n,t):t.push(n);return t}function YF(e,t){if(t==null)return t;let n=e.endsWith(`[]`),r=n?e.slice(0,-2):e;if(rI.has(r)||!Array.isArray(t))return qF(t);let i=JF(t,[]);if(r.startsWith(`quat`))for(let e=0;e+3<i.length;e+=4)i.splice(e,4,i[e+1],i[e+2],i[e+3],i[e]);return n?tI.has(r)?Int32Array.from(i):nI.has(r)?Float64Array.from(i):Float32Array.from(i):i}function XF(e,t,n,r){switch(t){case`references`:case`payload`:e.setArc(t,n,WF(r));return;case`inherits`:case`specializes`:e.setArc(t,n,GF(r));return;case`variantSets`:e.setArc(`variantSetNames`,n,KF(r));return;case`apiSchemas`:e.setArc(`apiSchemas`,n,KF(r));return;case`variants`:e.variantSelection={...e.variantSelection??{},...r};return;default:e.meta[t]=qF(r)}}function ZF(e,t=``){return new lI(e).parse(t)}var QF,$F,eI,tI,nI,rI,iI,aI,oI,sI,cI,lI,uI=g((()=>{UF(),QF=new Set([`prepend`,`append`,`add`,`delete`,`reorder`]),$F=new Set([`def`,`over`,`class`]),eI=new Set([`custom`,`uniform`,`varying`,`config`]),tI=new Set([`int`,`int2`,`int3`,`int4`,`uint`,`int64`,`uint64`,`uchar`]),nI=new Set([`double`,`double2`,`double3`,`double4`,`matrix2d`,`matrix3d`,`matrix4d`,`quatd`,`timecode`,`point3d`,`vector3d`,`normal3d`,`color3d`,`color4d`,`texCoord2d`,`texCoord3d`,`frame4d`]),rI=new Set([`token`,`string`,`asset`,`bool`,`dictionary`,`opaque`,`pathExpression`]),iI=class{constructor(e){this.asset=e}},aI=class{constructor(e){this.path=e}},oI=e=>e>=65&&e<=90||e>=97&&e<=122||e===95,sI=e=>oI(e)||e>=48&&e<=57||e===58||e===46,cI=class{constructor(e){this.s=e,this.i=0}fail(e){let t=1;for(let e=0;e<this.i&&e<this.s.length;e++)this.s.charCodeAt(e)===10&&t++;throw Error(`usda line ${t}: ${e}`)}skip(){let e=this.s;for(;;){let t=e.charCodeAt(this.i);if(t===32||t===9||t===10||t===13||t===59)this.i++;else if(t===35)for(;this.i<e.length&&e.charCodeAt(this.i)!==10;)this.i++;else return t}}peek(){return this.skip()}startsNumber(e){if(e>=48&&e<=57||e===46)return!0;if(e!==45&&e!==43)return!1;let t=this.s.charCodeAt(this.i+1);return t>=48&&t<=57||t===46||t===105}skipLayerOffset(){let e=this.i;if(this.peek()!==40)return;this.i++;let t=this.peekIdent();if(this.i=e,t!==`offset`&&t!==`scale`)return;this.skip();let n=this.s.indexOf(`)`,this.i);n<0&&this.fail(`unterminated layer offset`),this.i=n+1}eat(e){this.skip()!==e.charCodeAt(0)&&this.fail(`expected "${e}", found "${this.s[this.i]??`end of file`}"`),this.i++}maybe(e){return this.skip()===e.charCodeAt(0)?(this.i++,!0):!1}ident(){oI(this.skip())||this.fail(`expected a name, found "${this.s[this.i]??`end of file`}"`);let e=this.i++;for(;sI(this.s.charCodeAt(this.i));)this.i++;return this.s.slice(e,this.i)}peekIdent(){let e=this.i;if(!oI(this.skip()))return this.i=e,null;let t=this.ident();return this.i=e,t}string(){let e=this.skip();e!==34&&e!==39&&this.fail(`expected a string, found "${this.s[this.i]??`end of file`}"`);let t=this.s,n=t[this.i];if(t.startsWith(n+n+n,this.i)){let e=t.indexOf(n+n+n,this.i+3);e<0&&this.fail(`unterminated string`);let r=t.slice(this.i+3,e);return this.i=e+3,r}let r=``,i=++this.i;for(;;){let e=t.charCodeAt(this.i);if(Number.isNaN(e)&&this.fail(`unterminated string`),e===92){r+=t.slice(i,this.i);let e=t[this.i+1];r+=e===`n`?`
|
|
1429
|
+
`:e===`t`?` `:e,this.i+=2,i=this.i;continue}if(t[this.i]===n)break;this.i++}return r+=t.slice(i,this.i),this.i++,r}asset(){let e=this.s;if(e.startsWith(`@@@`,this.i)){let t=e.indexOf(`@@@`,this.i+3);t<0&&this.fail(`unterminated asset path`);let n=e.slice(this.i+3,t);return this.i=t+3,n}let t=e.indexOf(`@`,this.i+1);t<0&&this.fail(`unterminated asset path`);let n=e.slice(this.i+1,t);return this.i=t+1,n}path(){let e=this.s.indexOf(`>`,this.i+1);e<0&&this.fail(`unterminated path`);let t=this.s.slice(this.i+1,e);return this.i=e+1,t}number(){let e=this.s,t=this.i;if((e[this.i]===`-`||e[this.i]===`+`)&&this.i++,e.startsWith(`inf`,this.i))return this.i+=3,e[t]===`-`?-1/0:1/0;for(;this.i<e.length;){let t=e.charCodeAt(this.i);if(t>=48&&t<=57||t===46)this.i++;else if(t===101||t===69)this.i++,(e[this.i]===`-`||e[this.i]===`+`)&&this.i++;else break}let n=Number(e.slice(t,this.i));return Number.isNaN(n)&&this.fail(`bad number "${e.slice(t,this.i)}"`),n}value(){let e=this.skip();if(e===40)return this.sequence(`)`);if(e===91)return this.sequence(`]`);if(e===123)return this.dictionary();if(e===34||e===39)return this.string();if(e===64){let e=this.asset(),t=this.peek()===60?new TF(e,this.path()):new iI(e);return this.skipLayerOffset(),t}if(e===60){let e=new aI(this.path());return this.skipLayerOffset(),e}if(this.startsNumber(e))return this.number();let t=this.ident();return t===`true`?!0:t===`false`?!1:t===`None`?null:t===`inf`?1/0:t===`nan`?NaN:t}sequence(e){this.i++;let t=[];for(;this.peek()!==e.charCodeAt(0)&&(t.push(this.value()),this.maybe(`,`)););return this.eat(e),t}dictionary(){this.i++;let e={};for(;this.peek()!==125;){if(this.startsNumber(this.peek())){let t=this.number();this.eat(`:`),e[t]=this.value(),this.maybe(`,`);continue}let t=this.ident();this.peek()===91&&this.s[this.i+1]===`]`&&(this.i+=2,t+=`[]`);let n=this.peek()===34||this.peek()===39?this.string():this.ident();this.eat(`=`),e[n]=t===`dictionary`?this.dictionary():this.value(),this.maybe(`,`)}return this.eat(`}`),e}},lI=class extends cI{parse(e){let t=new AF(e);if(this.s.charCodeAt(0)===65279&&(this.i=1),!this.s.startsWith(`#usda`,this.i))throw Error(`not a usda layer`);for(;this.i<this.s.length&&this.s.charCodeAt(this.i)!==10;)this.i++;for(this.peek()===40&&this.metadata((e,n,r)=>{e===`subLayers`?t.meta.subLayers=WF(r).map(e=>e.asset):t.meta[e]=qF(r)},e=>{t.meta.doc=e});!Number.isNaN(this.peek());)this.prim(t.root);return t}metadata(e,t=null){for(this.eat(`(`);this.peek()!==41;){let n=this.peek();if(n===34||n===39){let e=this.string();t&&t(e);continue}let r=this.ident(),i=`explicit`;QF.has(r)&&(i=r,r=this.ident()),this.eat(`=`),e(r,i,this.value())}this.eat(`)`)}prim(e){let t=this.ident();$F.has(t)||this.fail(`expected def, over or class, found "${t}"`);let n=this.peek()===34||this.peek()===39?``:this.ident(),r=this.string(),i=e.child(r,!0);i.specifier=t,i.typeName=n,this.peek()===40&&this.metadata((e,t,n)=>XF(i,e,t,n),e=>{i.meta.doc=e}),this.body(i)}body(e){for(this.eat(`{`);this.peek()!==125;){let t=this.peekIdent();if(t===null&&this.fail(`unexpected "${this.s[this.i]??`end of file`}" in a prim`),$F.has(t))this.prim(e);else if(t===`variantSet`)this.variantSet(e);else if(t===`reorder`){this.ident();let t=this.ident();this.eat(`=`);let n=KF(this.value());t===`nameChildren`&&(e.reorder=n)}else this.property(e)}this.eat(`}`)}variantSet(e){this.ident();let t=this.string();for(this.eat(`=`),this.eat(`{`);this.peek()!==125;){let n=e.variant(t,this.string(),!0);this.peek()===40&&this.metadata((e,t,r)=>XF(n,e,t,r)),this.body(n)}this.eat(`}`)}property(e){let t=this.ident(),n=`explicit`,r=!1,i=!1;for(;;){if(QF.has(t))n=t;else if(eI.has(t))t===`uniform`&&(r=!0),t===`custom`&&(i=!0);else break;t=this.ident()}if(t===`rel`){let t=this.ident(),r=e.property(t,!0);if(r.rel=!0,r.custom=i,this.maybe(`=`)){let e=this.value();r.setTargets(n,GF(e))}this.peek()===40&&this.metadata((e,t,n)=>{r.meta[e]=qF(n)},()=>{});return}let a=t;this.peek()===91&&this.s[this.i+1]===`]`&&(this.i+=2,a+=`[]`);let o=this.ident(),s=`default`;for(let e of[`.connect`,`.timeSamples`,`.spline`])o.endsWith(e)&&(s=e.slice(1),o=o.slice(0,-e.length));let c=e.property(o,!0);if(c.type=a,c.uniform=r||c.uniform,c.custom=i,this.maybe(`=`))if(s===`connect`)c.setConnections(n,GF(this.value()));else if(s===`timeSamples`){let e=this.value();c.timeSamples=new Map(Object.entries(e).map(([e,t])=>[Number(e),YF(a,t)]).sort((e,t)=>e[0]-t[0]))}else if(s===`spline`)this.value();else{let e=this.value();c.value=e===null?null:YF(a,e),c.hasValue=!0}this.peek()===40&&this.metadata((e,t,n)=>{c.meta[e]=qF(n)},e=>{c.meta.doc=e})}}}));function dI(e,t){return e.length>=8&&e[0]===80&&e[1]===88&&e[2]===82&&e[3]===45&&e[4]===85&&e[5]===83&&e[6]===68&&e[7]===67?wF(e.byteOffset===0&&e.byteLength===e.buffer.byteLength?e.buffer:e.slice().buffer,t):ZF(new TextDecoder().decode(e),t)}function fI(e){let t=[];for(let n of e.replace(/\\/g,`/`).split(`/`))n===``||n===`.`||(n===`..`?t.pop():t.push(n));return t.join(`/`)}function pI(e,t,n){return e===t?n:r=>{if(r===e)return n(t);let i=r.charCodeAt(e.length);return r.startsWith(e)&&(i===47||i===46||i===123)?n(t+r.slice(e.length)):n(r)}}function*mI(e){yield e;for(let t of e.children)yield*mI(t)}function hI(e,t){let n=e=>e.map(t);return{explicit:e.explicit?n(e.explicit):null,prepend:n(e.prepend),append:n(e.append),add:n(e.add),delete:n(e.delete)}}var gI,_I,vI,yI,bI,xI,SI,CI,wI,TI=g((()=>{UF(),uI(),gI={local:0,inherit:1,variant:2,reference:3,payload:4,specialize:5},_I=32,vI=e=>e.includes(`/`)?e.slice(0,e.lastIndexOf(`/`)):``,yI=class{constructor(e,t,{omitted:n=[]}={}){this.read=t,this.exact=new Map,this.lower=new Map,this.byName=new Map,this.omitted=new Set(n.map(e=>fI(e).toLowerCase()));for(let t of e){let e=fI(t);this.exact.set(e,t),this.lower.set(e.toLowerCase(),t);let n=e.split(`/`).pop().toLowerCase(),r=this.byName.get(n);r?r.push(t):this.byName.set(n,[t])}}isOmitted(e,t=``){return this.omitted.has(this.key(e,t).toLowerCase())}key(e,t){let n=e.replace(/\\/g,`/`);return fI(n.startsWith(`/`)?n:`${vI(t)}/${n}`)}resolve(e,t=``){if(!e)return null;let n=e.replace(/\\/g,`/`),r=this.key(e,t),i=this.exact.get(r)??this.lower.get(r.toLowerCase());if(i)return i;let a=fI(n).toLowerCase(),o=(this.byName.get(a.split(`/`).pop())??[]).filter(e=>fI(e).toLowerCase().endsWith(`/${a}`));return o.length===1?o[0]:null}},bI=e=>e,xI=(e,t)=>e===`/`?`/${t}`:`${e}/${t}`,SI=class{constructor(e,t,n,r,i){this.stack=e,this.path=t,this.map=n,this.arc=r,this.depth=i,this.specs=[],this.layers=[],this.children=[],this.choice=null,this.doneSets=null}add(e){let t=gI[e.arc],n=this.children.length;for(;n>0;){let r=this.children[n-1],i=gI[r.arc];if(i<t||i===t&&r.depth>=e.depth)break;n--}this.children.splice(n,0,e)}},CI=class{constructor(e,t,n){this.stage=e,this.path=t,this.root=n,this._sites=null}get name(){return this.path===`/`?``:this.path.slice(this.path.lastIndexOf(`/`)+1)}get sites(){if(this._sites)return this._sites;this._sites=[];for(let e of mI(this.root))for(let t=0;t<e.specs.length;t++)this._sites.push([e,e.specs[t],e.layers[t]]);return this._sites}get typeName(){for(let[,e]of this.sites)if(e.typeName)return e.typeName;return``}get isDefined(){for(let[,e]of this.sites){if(e.specifier===`def`)return!0;if(e.specifier===`class`)return!1}return!1}meta(e){for(let[,t]of this.sites)if(t.meta[e]!==void 0)return t.meta[e]}property(e){for(let[,t]of this.sites){let n=t.props?.get(e);if(n&&(n.hasValue||n.timeSamples))return n}return null}value(e){let t=this.property(e);if(!t)return;if(t.hasValue)return t.value??void 0;let n=t.timeSamples?.values().next();return n&&!n.done?n.value??void 0:void 0}propertyMeta(e,t){for(let[,n]of this.sites){let r=n.props?.get(e)?.meta[t];if(r!==void 0)return r}}assetPath(e){for(let[,t,n]of this.sites){let r=t.props?.get(e);if(!r?.hasValue)continue;let i=r.value;return typeof i==`string`&&i?{asset:i,path:this.stage.files.resolve(i,n.path)}:null}return null}propertyNames(){let e=new Set;for(let[,t]of this.sites)for(let n of t.props?.keys()??[])e.add(n);return[...e]}_paths(e,t){let n=[];for(let[r,i]of this.sites){let a=i.props?.get(e)?.[t];a&&n.push(hI(a,r.map))}return _F(n).map(e=>e.value)}targets(e){return this._paths(e,`targets`)}connections(e){return this._paths(e,`connections`)}childNames(){let e=new Set;for(let[,t]of this.sites)for(let n of t.children?.keys()??[])e.add(n);return[...e]}instanceKey(){let e=this.path.split(`/`).length-1,t=[],n=r=>{r.arc!==`local`&&r.depth>=e&&t.push(`${r.arc}|${r.stack.id}|${r.path}|${r.choice??``}`);for(let e of r.children)n(e)};return n(this.root),t.join(`;`)}},wI=class{constructor(e,{warn:t=()=>{}}={}){this.files=e,this.warn=t,this._layers=new Map,this._stacks=new Map,this._prims=new Map,this._warned=new Set,this.omittedArcs=0,this.root=null,this.pseudoRoot=null}warnOnce(e,t){this._warned.has(e)||(this._warned.add(e),this.warn(t))}async open(e){if(this.root=await this.stack(e),!this.root)throw Error(`USD layer "${e}" could not be read`);let t=this.root.layers[0].meta;return this.upAxis=t.upAxis??`Y`,this.metersPerUnit=t.metersPerUnit??.01,this.defaultPrim=t.defaultPrim??``,this.pseudoRoot=new CI(this,`/`,this.rootNode(this.root,bI,`local`,0)),this._prims.set(`/`,this.pseudoRoot),this.pseudoRoot}layer(e){let t=this._layers.get(e);return t||(t=(async()=>{let t=await this.files.read(e);if(!t)return null;try{return dI(t,e)}catch(t){return this.warnOnce(`parse:${e}`,`USD layer "${e}" could not be parsed: ${t.message}`),null}})(),this._layers.set(e,t)),t}stack(e,t=new Set){let n=this._stacks.get(e);return n||(n=(async()=>{let n=[],r=async e=>{if(t.has(e))return;t.add(e);let i=await this.layer(e);if(i){n.push(i);for(let t of i.meta.subLayers??[]){let n=this.files.resolve(t,e);n?await r(n):this.warnOnce(`missing:${t}`,`USD sublayer "${t}" of "${e}" not found`)}}};return await r(e),n.length===0?null:{id:e,layers:n,defaultPrim:n[0].meta.defaultPrim??``}})(),this._stacks.set(e,n)),n}rootNode(e,t,n,r){let i=new SI(e,`/`,t,n,r);return i.layers=e.layers.slice(),i.specs=e.layers.map(e=>e.root),i}async child(e,t){let n=xI(e.path,t),r=this._prims.get(n);if(r)return r;let i=n.split(`/`).length-1,a=await this.childNode(e.root,t,i,new Set);if(!a)return null;await this.addVariants(a,i,new Set);let o=new CI(this,n,a);return this._prims.set(n,o),o}async primAt(e){if(!this.pseudoRoot)return null;let t=this._prims.get(e);if(t)return t;let n=this.pseudoRoot;for(let t of e.split(`/`).filter(Boolean))if(n=await this.child(n,t),!n)return null;return n}release(){this._prims.clear(),this._prims.set(`/`,this.pseudoRoot);let e=new Set(this.root.layers.map(e=>e.path));for(let t of this._layers.keys())e.has(t)||this._layers.delete(t);for(let e of this._stacks.keys())e!==this.root.id&&this._stacks.delete(e)}async childNode(e,t,n,r){let i=new SI(e.stack,xI(e.path,t),e.map,e.arc,e.depth);i.choice=e.choice;for(let n=0;n<e.specs.length;n++){let r=e.specs[n].child(t);r&&(i.specs.push(r),i.layers.push(e.layers[n]))}for(let a of e.children){let e=await this.childNode(a,t,n,r);e&&i.children.push(e)}return i.specs.length&&await this.addArcs(i,n,r),i.specs.length||i.children.length?i:null}async addArcs(e,t,n){let r=t=>_F(e.specs.map(e=>e.arcs?.[t]??null),e.layers);for(let{value:i}of r(`inherits`))await this.addClass(e,i,`inherit`,t,n);for(let{value:i,source:a}of r(`references`))await this.addReference(e,i,a,`reference`,t,n);for(let{value:i,source:a}of r(`payload`))await this.addReference(e,i,a,`payload`,t,n);for(let{value:i}of r(`specializes`))await this.addClass(e,i,`specialize`,t,n)}async addClass(e,t,n,r,i){let a=await this.subtree(e.stack,t,pI(t,e.path,e.map),n,r,i);a&&e.add(a)}async addReference(e,t,n,r,i,a){let o=e.stack;if(t.asset){let e=this.files.resolve(t.asset,n?.path??``);if(!e){this.files.isOmitted(t.asset,n?.path??``)?this.omittedArcs++:this.warnOnce(`missing:${t.asset}`,`USD ${r} "${t.asset}" (from "${n?.path}") not found — skipped`);return}if(o=await this.stack(e),!o)return}let s=t.path||(o.defaultPrim?`/${o.defaultPrim}`:``);if(!s){this.warnOnce(`nodefault:${o.id}`,`USD ${r} to "${o.id}" names no prim and the layer has no defaultPrim — skipped`);return}let c=await this.subtree(o,s,pI(s,e.path,e.map),r,i,a);c&&e.add(c)}async subtree(e,t,n,r,i,a){let o=`${e.id}\u0000${t}`;if(a.has(o))return this.warnOnce(`cycle:${o}`,`USD composition cycle through "${t}" in "${e.id}" — skipped`),null;let s=new Set(a).add(o),c=this.rootNode(e,n,r,i),l=t.split(`/`).filter(Boolean);for(let e=0;e<l.length;e++)if(e>0&&await this.addVariants(c,i,s),c=await this.childNode(c,l[e],i,s),!c)return null;return c}async addVariants(e,t,n){for(let r=!0;r;){r=!1;for(let i of[...mI(e)]){let a=new Set(_F(i.specs.map(e=>e.arcs?.variantSetNames??null)).map(e=>e.value));for(let e of i.specs)for(let t of e.variantSets?.keys()??[])a.add(t);for(let o of a){if(i.doneSets??=new Set,i.doneSets.has(o))continue;i.doneSets.add(o);let a=this.selection(e,o);if(!a)continue;let s=new SI(i.stack,i.path,i.map,`variant`,t);s.choice=`${o}=${a}`;for(let e=0;e<i.specs.length;e++){let t=i.specs[e].variant(o,a);t&&(s.specs.push(t),s.layers.push(i.layers[e]))}s.specs.length!==0&&(i.add(s),await this.addArcs(s,t,n),r=!0)}}}}selection(e,t){for(let n of mI(e))for(let e of n.specs){let n=e.variantSelection?.[t];if(n)return n}return null}async connectionSource(e,t){let[n]=e.connections(t);for(let e=0;n&&e<_I;e++){let e=n.lastIndexOf(`.`),t=await this.primAt(n.slice(0,e));if(!t)return null;let r=n.slice(e+1),i=t.connections(r)[0];if(!i||t.value(`info:id`))return{prim:t,name:r};n=i}return null}}}));function EI(e,t,n){if(tL(e)&&tL(t))return n(e,t);let r=Math.max(tL(e)?1:e.length,tL(t)?1:t.length);return Array.from({length:r},(r,i)=>n(tL(e)?e:e[i]??e[0],tL(t)?t:t[i]??t[0]))}function DI(e,t){let n=Math.cos(t*UI),r=Math.sin(t*UI);return[n*e[0]+r*e[3],n*e[1]+r*e[4],n*e[2]+r*e[5],n*e[3]-r*e[0],n*e[4]-r*e[1],n*e[5]-r*e[2]]}function OI(){return{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:[]}}function kI(e,t){let n=e.split(`:`)[1];if(t==null)return null;let i=new r.Matrix4;switch(n){case`translate`:return i.makeTranslation(t[0],t[1],t[2]);case`scale`:return typeof t==`number`?i.makeScale(t,t,t):i.makeScale(t[0],t[1],t[2]);case`rotateX`:return i.makeRotationX(t*UI);case`rotateY`:return i.makeRotationY(t*UI);case`rotateZ`:return i.makeRotationZ(t*UI);case`orient`:return i.makeRotationFromQuaternion(new r.Quaternion(t[0],t[1],t[2],t[3]).normalize());case`transform`:return i.fromArray(t);default:{let e=/^rotate([XYZ]{3})$/.exec(n);return e?i.makeRotationFromEuler(new r.Euler(t[0]*UI,t[1]*UI,t[2]*UI,[...e[1]].reverse().join(``))):null}}}function AI(e){let t=new r.Matrix4,n=!1;for(let r of e.value(`xformOpOrder`)??[]){if(r===`!resetXformStack!`){n=!0,t.identity();continue}let i=r.startsWith(`!invert!`),a=i?r.slice(8):r,o=kI(a,e.value(a));o&&(i&&o.invert(),t.multiply(o))}return{matrix:t,reset:n}}function jI(e,t){let n=`primvars:${t}`,r=e.value(n);if(r==null||r.length===0)return null;let i=e.value(`${n}:indices`);return{values:r,interpolation:e.propertyMeta(n,`interpolation`)??`constant`,indices:i?.length?i:null}}function MI(e){if(!e)return null;let{values:t}=e,n=[0,0,0],r=Math.floor(t.length/3);if(r===0)return null;for(let e=0;e<r;e++)for(let r=0;r<3;r++)n[r]+=t[e*3+r];return n.map(e=>e/r)}function NI(e,t,n,r){let i=e.interpolation===`faceVarying`?n:e.interpolation===`uniform`?t:e.interpolation===`constant`?0:r;return e.indices?e.indices[i]:i}function PI(e,t){let{points:n,counts:r,offsets:i,fvi:a,leftHanded:o,normals:s,uv:c}=e,l=lL(s)||lL(c),u=0,d=0;for(let e of t)r[e]>=3&&(u+=r[e]-2,d+=r[e]);let f=new Uint32Array(u*3),p=0,m=(e,t,n)=>{for(let r=1;r+1<t;r++)f[p++]=n(e,0),f[p++]=n(e,o?r+1:r),f[p++]=n(e,o?r:r+1)};if(!l){for(let e of t)r[e]>=3&&m(i[e],r[e],(e,t)=>a[e+t]);let e=n.length/3;return{P:n,N:s&&s.values.length===e*3?s.values:null,uv:c&&c.values.length===e*2?c.values:null,index:f}}let h=new Float32Array(d*3),g=s?new Float32Array(d*3):null,_=c?new Float32Array(d*2):null,v=0;for(let e of t){let t=r[e];if(t<3)continue;let o=v;for(let r=0;r<t;r++){let t=i[e]+r,o=a[t];if(h[v*3]=n[o*3],h[v*3+1]=n[o*3+1],h[v*3+2]=n[o*3+2],g){let n=NI(s,e,t,o)*3;g[v*3]=s.values[n],g[v*3+1]=s.values[n+1],g[v*3+2]=s.values[n+2]}if(_){let n=NI(c,e,t,o)*2;_[v*2]=c.values[n],_[v*2+1]=c.values[n+1]}v++}m(o,t,(e,t)=>e+t)}return{P:h,N:g,uv:_,index:f}}function FI(e,t){t===`Z`?e.rotateX(Math.PI/2):t===`X`&&e.rotateZ(-Math.PI/2);let n=e.getAttribute(`position`).array;return{P:n,N:e.getAttribute(`normal`)?.array??null,uv:e.getAttribute(`uv`)?.array??null,index:e.index?Uint32Array.from(e.index.array):Uint32Array.from({length:n.length/3},(e,t)=>t)}}function II(e){return e.map(e=>Math.round(Math.min(Math.max(e,0),64)/WI)*WI)}function LI(e,t){let n=Math.imul(e^t,2654435761);return n=Math.imul(n^n>>>15,2246822507),n=Math.imul(n^n>>>13,3266489909),((n^n>>>16)>>>0)/4294967296}function RI(e){let t=2166136261;for(let n=0;n<e.length;n++)t=Math.imul(t^e.charCodeAt(n),16777619);return t}function zI(e,t,n,r){return t===`linear`?r===`periodic`?e:e-1:n===`bezier`?r===`periodic`?e/3:(e-1)/3:r===`periodic`?e:r===`pinned`?e+1:e-3}function BI(e,t){let n=new Map,r=[...e].sort((e,t)=>e[1]-t[1]),i=Math.max(0,t);for(let e=0;e<r.length;e++){let t=r[e][1],a=i/(r.length-e);if(t<=a){i-=t;continue}for(let t=e;t<r.length;t++)n.set(r[t][0],a/r[t][1]);break}return n}function VI(e,t,n,r){return t===`vertex`?e:t===`varying`?Math.max(1,Math.round(n===`linear`?e-1:r===`bezier`?(e-1)/3:e-3)+1):1}function HI(e,t,n){let{counts:r,type:i,basis:a}=e,o=[],s=Math.floor(r.length*t);for(let e=0;e<r.length&&o.length<s;e++)LI(e,n)<t&&o.push(e);if(o.length===0)return null;if(o.length===r.length)return e;let c=(e,t,n)=>{if(!e?.length||!n||n===`constant`)return e;let s=new Int32Array(r.length+1);for(let e=0;e<r.length;e++)s[e+1]=s[e]+VI(r[e],n,i,a);let c=0;for(let e of o)c+=s[e+1]-s[e];let l=new e.constructor(c*t),u=0;for(let n of o){let r=e.subarray(s[n]*t,s[n+1]*t);l.set(r,u),u+=r.length}return l};return{...e,points:c(e.points,3,`vertex`),counts:Int32Array.from(o,e=>r[e]),widths:c(e.widths,1,e.widthMode),normals:c(e.normals,3,e.normalMode)}}var UI,WI,GI,KI,qI,JI,YI,XI,ZI,QI,$I,eL,tL,nL,rL,iL,aL,oL,sL,cL,lL,uL,dL,fL=g((()=>{NP(),UI=Math.PI/180,WI=1/255,GI=new Set([`RectLight`,`DiskLight`,`SphereLight`,`DistantLight`,`DomeLight`,`CylinderLight`]),KI=new Set([`Sphere`,`Cube`,`Cylinder`,`Cone`,`Capsule`,`Plane`]),qI=new Set([`Material`,`Shader`,`NodeGraph`,`GeomSubset`,`Volume`,`OpenVDBAsset`,`Field3DAsset`,`SkelAnimation`,`BlendShape`]),JI=/\.(ptx|ptex)$/i,YI={repeat:r.RepeatWrapping,mirror:r.MirroredRepeatWrapping,clamp:r.ClampToEdgeWrapping,black:r.ClampToEdgeWrapping},XI=/_(?:float|integer|boolean|string|filename|color3|color4|vector2|vector3|vector4|matrix33|matrix44|surfaceshader|BSDF|EDF)(?:FA|I|B)?(?=_|$)/,ZI=e=>{let t=e.slice(3),n=t.search(XI);return n>0?t.slice(0,n):t},QI={open_pbr_surface:`openPbrSurface`,standard_surface:`standardSurface`,gltf_pbr:`gltfPbrSurface`,UsdPreviewSurface:`previewSurface`,surface:`bsdfSurface`},$I={periodic:`repeat`,mirror:`mirror`,clamp:`clamp`,constant:`black`},eL=[1,0,0,0,1,0],tL=e=>typeof e==`number`,nL=e=>tL(e)||Array.isArray(e),rL=(e,t)=>tL(e)?t(e):e.map(t),iL=e=>tL(e)?e:e.slice(0,3).reduce((e,t)=>e+t,0)/Math.min(e.length,3),aL=(e,[t,n])=>[e[0]*t,e[1]*t,e[2]*t,e[3]*n,e[4]*n,e[5]*n],oL=(e,[t,n])=>[e[0],e[1],e[2]+t,e[3],e[4],e[5]+n],sL=(e,t=`float`)=>({type:t,value:e}),cL=e=>({type:`string`,value:[e]}),lL=e=>e&&(e.indices||e.interpolation===`faceVarying`||e.interpolation===`uniform`||e.interpolation===`constant`),uL=.65,dL=class{constructor(e,{maxTriangles:t=1/0,maxPlacements:n=1/0,curveSteps:r=2,resolveImage:i=async()=>null,warn:a=()=>{}}={}){this.stage=e,this.maxTriangles=t,this.maxPlacements=n,this.curveSteps=r,this.resolveImage=i,this.warn=a,this.ir=OI(),this.cameras=[],this.lights=[],this.domes=[],this.prototypes=new Map,this._surfaces=new Map,this._colored=new Map,this._wrappers=new Map,this._images=new Map,this._handed=new WeakSet,this._warned=new Set,this._protoCount=0,this._geometries=new Map,this._specIds=new WeakMap,this._nextSpecId=0,this.dry=!1,this.cost=null,this.placementRates=new Map,this.curveRates=new Map,this.fitNote=null}warnOnce(e,t){this._warned.has(e)||(this._warned.add(e),this.warn(t))}async read(){return(Number.isFinite(this.maxTriangles)||Number.isFinite(this.maxPlacements))&&await this.fit(),await this.walk(),this.shareGeometry(),{ir:this.ir,cameras:this.cameras,lights:this.lights,dome:this.pickDome(),cost:this.cost}}async walk(){let e=this.stage.pseudoRoot,t=this.stage.upAxis===`Z`?new r.Matrix4().makeRotationX(-Math.PI/2):new r.Matrix4;for(let n of e.childNames()){let r=await this.stage.child(e,n);r&&await this.visit(r,t,this.world(),{binding:null,depth:0}),this.stage.release()}}async fit(){this.dry=!0,this.cost={mesh:0,curves:0,placements:0,scatter:0,counted:new Set,curveSets:new Map,instancers:new Map},await this.walk(),this.dry=!1,this.prototypes.clear();let{mesh:e,curves:t,placements:n,scatter:r,curveSets:i,instancers:a}=this.cost;delete this.cost.counted,delete this.cost.curveSets,delete this.cost.instancers,n>this.maxPlacements&&(this.placementRates=BI(a,(this.maxPlacements-(n-r))*.98)),e+t>this.maxTriangles&&(this.curveRates=BI(i,(this.maxTriangles-e)*.95));let o=e=>`${(e/1e6).toFixed(1)}M`,s=(e,t)=>{let n=0,r=0;for(let[i,a]of t)n+=a,r+=a*(e.get(i)??1);return`${Math.round(r/n*100)} %`},c=[];(this.placementRates.size||this.curveRates.size)&&c.push(`USD scene is ${o(e+t)} triangles (${o(t)} of curves) and ${o(n)} placed copies, past the budgets (${o(this.maxTriangles)}, ${o(this.maxPlacements)}): ${s(this.curveRates,i)} of the curves and ${s(this.placementRates,a)} of the scattered copies kept, the largest sets thinned most`),e>this.maxTriangles&&c.push(`its meshes alone are ${o(e)} triangles, past the ${o(this.maxTriangles)} budget: what is read last is cut. Load fewer parts, or raise maxTriangles (memory spill raises it)`),this.fitNote=c.join(`; `)||null,this.fitNote&&this.warn(this.fitNote)}world(){return this.dry?{isWorld:!0,shape:()=>this.cost.placements++,place:e=>this.countPrototype(e,1,!1),instancer:e=>this.countInstancer(e,1)}:{isWorld:!0,shape:(e,t)=>{e.ctm=Array.from(t.elements),this.ir.shapes.push(e)},place:(e,t)=>this.placePrototype(e,t),instancer:(e,t)=>this.placeInstancer(e,t)}}collector(e){return this.dry?{isWorld:!1,shape:(t,n)=>e.shapes.push(n?n.elements.join(`,`):``),place:t=>e.nested.push({proto:t}),instancer:t=>e.nested.push({instancer:t})}:{isWorld:!1,shape:(t,n)=>{t.ctm=Array.from(n.elements),e.shapes.push(t)},place:(t,n)=>e.nested.push({proto:t,matrix:n.clone()}),instancer:(t,n)=>e.nested.push({instancer:t,matrix:n.clone()})}}async visit(e,t,n,i){if(!e.isDefined||e.meta(`active`)===!1||e.value(`visibility`)===`invisible`)return;let a=e.value(`purpose`);if(a===`guide`||a===`proxy`)return;let o=e.typeName;if(qI.has(o)){o===`Volume`&&this.warnOnce(`volume`,`USD volumes are not rendered — skipped`);return}let{matrix:s,reset:c}=AI(e),l=c?s:new r.Matrix4().multiplyMatrices(t,s),u=this.bindingOf(e)??i.binding;if(e.meta(`instanceable`)===!0&&e.childNames().length){let t=await this.instancePrototype(e,u);t&&n.place(t,l);return}if(o===`Mesh`)await this.mesh(e,l,n,u);else if(o===`BasisCurves`)await this.curves(e,l,n,u);else if(KI.has(o))await this.gprim(e,l,n,u);else if(o===`PointInstancer`){await this.pointInstancer(e,l,n,u);return}else if(o===`Camera`)n.isWorld&&!this.dry&&this.camera(e,l);else if(GI.has(o)){if(this.dry)return;n.isWorld?this.light(e,o,l):this.warnOnce(`protoLight`,`USD lights inside instanced prims are not placed — skipped`)}else (o===`NurbsPatch`||o===`NurbsCurves`||o===`Points`||o===`HermiteCurves`)&&this.warnOnce(`type:${o}`,`USD ${o} prims are not supported — skipped`);for(let t of e.childNames()){let r=await this.stage.child(e,t);r&&await this.visit(r,l,n,{binding:u,depth:i.depth+1}),i.depth===0&&n.isWorld&&this.stage.release()}}bindingOf(e){for(let t of[`material:binding:full`,`material:binding`]){let[n]=e.targets(t);if(n)return n}return null}newPrototype(){return{name:`usd_proto_${this._protoCount++}`,shapes:[],nested:[],registered:!1}}register(e){return e.shapes.length&&!e.registered&&!this.dry&&(this.ir.objects.set(e.name,e.shapes),e.registered=!0),e.shapes.length||e.nested.length?e:null}async instancePrototype(e,t){let n=`instance|${e.instanceKey()}|${t??``}`;if(this.prototypes.has(n))return this.prototypes.get(n);let i=this.newPrototype();this.prototypes.set(n,i);let a=this.collector(i);for(let n of e.childNames()){let i=await this.stage.child(e,n);i&&await this.visit(i,new r.Matrix4,a,{binding:t,depth:1/0})}let o=this.register(i);return this.prototypes.set(n,o),o}async instancerPrototype(e,t){let n=`proto|${e.path}`;if(this.prototypes.has(n))return this.prototypes.get(n);let i=this.newPrototype();this.prototypes.set(n,i),await this.visit(e,new r.Matrix4,this.collector(i),{binding:t,depth:1/0});let a=this.register(i);return this.prototypes.set(n,a),a}addInstance(e,t){let n=this.ir;if(n.instanceCount>=this.maxPlacements){n.skippedInstances++;return}let r=n.instances.get(e);r||n.instances.set(e,r={name:e,count:0,matrices:new Float32Array(512),matricesEnd:null});let i=(r.count+1)*16;if(i>r.matrices.length){let e=new Float32Array(Math.max(i,r.matrices.length*2));e.set(r.matrices),r.matrices=e}r.matrices.set(t.elements,r.count*16),r.count++,n.instanceCount++}countPrototype(e,t,n){e.shapes.length&&(e.placeKeys??=new Set(e.shapes).size,this.cost.placements+=t*e.placeKeys,n&&(this.cost.scatter+=t*e.placeKeys));for(let r of e.nested)r.proto?this.countPrototype(r.proto,t,n):this.countInstancer(r.instancer,t)}countInstancer(e,t){let n=this.cost.scatter;e.histogram.forEach((n,r)=>{e.protos[r]&&n&&this.countPrototype(e.protos[r],t*n,!0)}),this.cost.instancers.set(e.path,(this.cost.instancers.get(e.path)??0)+this.cost.scatter-n)}placePrototype(e,t){e.shapes.length&&this.addInstance(e.name,t);for(let n of e.nested){let e=new r.Matrix4().multiplyMatrices(t,n.matrix);n.proto?this.placePrototype(n.proto,e):this.placeInstancer(n.instancer,e)}}placeInstancer(e,t){let{protos:n,protoIndices:i,positions:a,orientations:o,scales:s,hidden:c,salt:l}=e,u=e.rate,d=u<1?Math.floor(i.length*u):1/0,f=new r.Matrix4,p=new r.Matrix4,m=new r.Quaternion,h=new r.Vector3,g=new r.Vector3;for(let e=0;e<i.length;e++){if(this.ir.instanceCount>=this.maxPlacements){this.ir.skippedInstances+=i.length-e;return}let r=n[i[e]];!r||c?.has(e)||u<1&&(d<=0||LI(e,l)>=u)||(d--,h.set(a[e*3],a[e*3+1],a[e*3+2]),o?m.set(o[e*4],o[e*4+1],o[e*4+2],o[e*4+3]).normalize():m.identity(),s?g.set(s[e*3],s[e*3+1],s[e*3+2]):g.set(1,1,1),f.compose(h,m,g),this.placePrototype(r,p.multiplyMatrices(t,f)))}}async pointInstancer(e,t,n,r){let i=e.value(`protoIndices`);if(!i?.length)return;let a=this.dry?null:e.value(`positions`);if(!this.dry&&!a?.length)return;let o=[];for(let t of e.targets(`prototypes`)){let e=await this.stage.primAt(t);o.push(e?await this.instancerPrototype(e,r):null)}let s=e.value(`invisibleIds`),c=null;if(s?.length){let t=e.value(`ids`),n=new Map;if(t?.length)for(let e=0;e<t.length;e++)n.set(Number(t[e]),e);c=new Set(Array.from(s,e=>t?.length?n.get(Number(e)):Number(e)))}if(this.dry){let t=new Float64Array(o.length);for(let e=0;e<i.length;e++)c?.has(e)||t[i[e]]++;n.instancer({protos:o,histogram:t,path:e.path});return}let l=e.value(`orientations`),u=e.value(`scales`);n.instancer({protos:o,protoIndices:i,positions:a,salt:RI(e.path),rate:this.placementRates.get(e.path)??1,orientations:l?.length===i.length*4?l:null,scales:u?.length===i.length*3?u:null,hidden:c},t)}own(e){return e&&(this._handed.has(e)?e.slice():(this._handed.add(e),e))}shape(e,t,n,r){return{type:t,params:n,ctm:null,material:r,areaLight:null,reverseOrientation:!1,interior:null,name:e.path}}specId(e){if(!e)return 0;let t=this._specIds.get(e);return t||this._specIds.set(e,t=++this._nextSpecId),t}geometryKey(e,t){let n=t=>this.specId(e.property(t)),r=t??`st`;return[n(`points`),n(`faceVertexIndices`),n(`faceVertexCounts`),n(`holeIndices`),n(`primvars:normals`),n(`normals`),r,n(`primvars:${r}`),n(`primvars:${r}:indices`),e.value(`orientation`)??``].join(`|`)}countGeometry(e,t,n){this.cost.counted.has(e)||(this.cost.counted.add(e),this.cost[t]+=n)}meshParams(e,t,n){let r=e.value(`points`),i=e.value(`faceVertexCounts`),a=e.value(`faceVertexIndices`);if(!r?.length||!i?.length||!a?.length)return null;let o=new Int32Array(i.length);for(let e=1;e<i.length;e++)o[e]=o[e-1]+i[e-1];if(!t){let n=new Set(e.value(`holeIndices`)??[]);t=[];for(let e=0;e<i.length;e++)n.has(e)||t.push(e)}let s=jI(e,`normals`)??(e.value(`normals`)?.length?{values:e.value(`normals`),interpolation:e.propertyMeta(`normals`,`interpolation`)??`vertex`,indices:null}:null),c=jI(e,n)??(n===`st`?jI(e,`uv`)??jI(e,`st0`)??jI(e,`UVMap`):null),l=PI({points:r,counts:i,offsets:o,fvi:a,leftHanded:e.value(`orientation`)===`leftHanded`,normals:s,uv:c},t);if(l.index.length===0)return null;let u={P:sL(this.own(l.P),`point3`),indices:sL(l.index,`integer`)};return l.N&&(u.N=sL(this.own(l.N),`normal`)),l.uv&&(u.uv=sL(this.own(l.uv),`point2`)),u}async mesh(e,t,n,r){let i=[];for(let t of e.childNames()){let n=await this.stage.child(e,t);if(n?.typeName!==`GeomSubset`||(n.value(`elementType`)??`face`)!==`face`)continue;let r=n.value(`familyName`),a=this.bindingOf(n);a&&(!r||r===`materialBind`)&&i.push({subset:n,target:a})}if(this.dry){let r=e.value(`faceVertexCounts`);if(!e.property(`points`)||!r?.length)return;let i=new Set(e.value(`holeIndices`)??[]),a=0;for(let e=0;e<r.length;e++)r[e]>2&&!i.has(e)&&(a+=r[e]-2);this.countGeometry(this.geometryKey(e,null),`mesh`,a),n.shape(null,t);return}if(i.length===0){let{material:i,uvSet:a}=await this.materialFor(r,e),o=this.geometryKey(e,a),s=this._geometries.get(o);if(s){let r=this.shape(e,`trianglemesh`,s.params,i);s.shapes.push(r),n.shape(r,t);return}let c=this.meshParams(e,null,a);if(!c)return;let l=this.shape(e,`trianglemesh`,c,i);this._geometries.set(o,{params:c,shapes:[l]}),n.shape(l,t);return}let a=e.value(`faceVertexCounts`);if(!a?.length)return;let o=new Set(e.value(`holeIndices`)??[]),s=[],c=new Set;for(let{subset:e,target:t}of i){let n=Array.from(e.value(`indices`)??[]).filter(e=>e<a.length&&!o.has(e)&&!c.has(e));for(let e of n)c.add(e);n.length&&s.push({faces:n,binding:t})}let l=[];for(let e=0;e<a.length;e++)!o.has(e)&&!c.has(e)&&l.push(e);l.length&&s.unshift({faces:l,binding:r});for(let r of s){let{material:i,uvSet:a}=await this.materialFor(r.binding,e),o=this.meshParams(e,r.faces,a);o&&n.shape(this.shape(e,`trianglemesh`,o,i),t)}}async curves(e,t,n,r){let i=e.value(`curveVertexCounts`);if(!i?.length||!e.property(`points`))return;let a=e.value(`type`)??`cubic`,o=e.value(`basis`)??`bezier`,s=e.value(`wrap`)??`nonperiodic`;if(this.dry){let r=0;for(let e=0;e<i.length;e++)r+=Math.max(1,Math.round(zI(i[e],a,o,s)*this.curveSteps)*uL);let c=`curves|${this.specId(e.property(`points`))}|${this.specId(e.property(`curveVertexCounts`))}`;this.cost.counted.has(c)||this.cost.curveSets.set(e.path,r*2),this.countGeometry(c,`curves`,r*2),n.shape(null,t);return}let c=e.property(`widths`)?`widths`:`primvars:widths`,l=e.property(`normals`)?`normals`:`primvars:normals`,u={points:e.value(`points`),counts:i,type:a,basis:o,wrap:s,widths:e.value(c)??null,widthMode:e.propertyMeta(c,`interpolation`)??null,normals:e.value(l)??null,normalMode:e.propertyMeta(l,`interpolation`)??`vertex`};u.widths?.length&&(u.widthMode??=u.widths.length===1?`constant`:`vertex`);let d=this.curveRates.get(e.path)??1;if(d<1&&(u=HI(u,d,RI(e.path))),!u)return;let f={P:sL(this.own(u.points),`point3`),counts:sL(this.own(u.counts),`integer`),type:cL(a),basis:cL(o),wrap:cL(s)};u.widths?.length&&(f.widths=sL(this.own(u.widths)),f.widthMode=cL(u.widthMode)),u.normals?.length&&(f.N=sL(this.own(u.normals),`normal`),f.normalMode=cL(u.normalMode));let{material:p}=await this.materialFor(r,e);n.shape(this.shape(e,`curves`,f,p),t)}shareGeometry(){for(let[e,{shapes:t}]of this._geometries)if(!(t.length<2))for(let n of t)n.shared=!0,n.geometryKey=e;this._geometries.clear()}async gprim(e,t,n,i){let a=e.value(`axis`)??`Z`,o=e.value(`radius`)??1,s=e.value(`height`)??2,c;switch(e.typeName){case`Sphere`:c=new r.SphereGeometry(o,48,24);break;case`Cube`:{let t=e.value(`size`)??2;c=new r.BoxGeometry(t,t,t);break}case`Cylinder`:c=new r.CylinderGeometry(o,o,s,48);break;case`Cone`:c=new r.ConeGeometry(o,s,48);break;case`Capsule`:c=new r.CapsuleGeometry(o,s,8,32);break;default:c=new r.PlaneGeometry(e.value(`width`)??2,e.value(`length`)??2)}let l=FI(c,e.typeName===`Plane`&&a===`Z`?`none`:a);if(c.dispose(),this.dry){this.countGeometry(`gprim|${e.path}`,`mesh`,l.index.length/3),n.shape(null,t);return}let u={P:sL(l.P,`point3`),indices:sL(l.index,`integer`)};l.N&&(u.N=sL(l.N,`normal`)),l.uv&&(u.uv=sL(l.uv,`point2`));let{material:d}=await this.materialFor(i,e);n.shape(this.shape(e,`trianglemesh`,u,d),t)}async materialFor(e,t){let n=e?await this.surface(e):null,r=n?.material??null,i=jI(t,`displayColor`);if(!r){let e=MI(i)??[.18,.18,.18];r=this.colored(null,e)}else if(n.perMesh){let i=MI(jI(t,n.perMesh.primvar));i?r=this.colored(r,i.map((e,t)=>Math.max(e,0)**(n.perMesh.exponent?.[t]??1))):this.warnOnce(`nodisplay`,`USD material "${e}" takes its colour from "${n.perMesh.primvar}", which a mesh lacks — its fallback used`)}let a=this._wrappers.get(r);return a||this._wrappers.set(r,a={type:`usd`,material:r}),{material:a,uvSet:n?.uvSet??`st`}}colored(e,t){let n=II(t),i=`${e?.uuid??`plain`}|${n.join(`,`)}`,a=this._colored.get(i);return a||(a=e?sP(e):new r.MeshPhysicalMaterial({side:r.DoubleSide,roughness:.5,metalness:0}),a.color.setRGB(n[0],n[1],n[2]),e?.userData.diffuseTransmissionFromBase&&(a.diffuseTransmissionColor=a.color.clone()),this._colored.set(i,a)),a}async surface(e){if(this._surfaces.has(e))return this._surfaces.get(e);let t=this.buildSurface(e);return this._surfaces.set(e,t),t}async buildSurface(e){let t=await this.stage.primAt(e);if(!t)return this.warnOnce(`nomat:${e}`,`USD material "${e}" not found`),null;let n=await this.stage.connectionSource(t,`outputs:mtlx:surface`),r=QI[ZI(n?.prim.value(`info:id`)??`ND_`)];if(r)return this[r](n.prim);for(let e of[`outputs:ri:surface`,`outputs:surface`,`outputs:glslfx:surface`]){let n=await this.stage.connectionSource(t,e),r=n?.prim.value(`info:id`);if(r===`PxrDisneyBsdf`)return this.disney(n.prim);if(r===`PxrSurface`)return this.pxrSurface(n.prim);if(r===`UsdPreviewSurface`)return this.previewSurface(n.prim)}return this.warnOnce(`nosurface:${e}`,`USD material "${e}" has no surface shader read here — shaded grey`),null}async term(e,t,n=0){let r=`inputs:${t}`,[i]=e.connections(r);if(i&&n<32){let e=i.lastIndexOf(`.`),t=await this.stage.primAt(i.slice(0,e)),r=i.slice(e+1);if(t){let e=r.startsWith(`inputs:`)?await this.term(t,r.slice(7),n+1):r.startsWith(`outputs:`)?await this.output(t,r.slice(8),n+1):null;if(e)return e}}let a=e.value(r);return a===void 0?null:{value:a}}async output(e,t,n){let r=e.value(`info:id`);switch(r){case`PxrColorCorrect`:{let t=await this.term(e,`inputRGB`,n+1),r=(await this.term(e,`gamma`,n+1))?.value;if(!t||!Array.isArray(r))return t;let i=r.map(e=>e>0?1/e:1);return Array.isArray(t.value)?{value:t.value.map((e,t)=>Math.max(e,0)**i[t])}:{...t,exponent:i}}case`PxrBlend`:return await this.term(e,`bottomRGB`,n+1)??this.term(e,`topRGB`,n+1);case`PxrPtexture`:case`HwPtexTexture_1`:return{primvar:`displayColor`};case`UsdUVTexture`:return this.texture(e,t,n);case`UsdPrimvarReader_float`:case`UsdPrimvarReader_float2`:case`UsdPrimvarReader_float3`:case`UsdPrimvarReader_float4`:case`UsdPrimvarReader_normal`:case`UsdPrimvarReader_point`:case`UsdPrimvarReader_vector`:{let t=(await this.term(e,`varname`,n+1))?.value;return t?{primvar:t}:await this.term(e,`fallback`,n+1)}case`UsdTransform2d`:{let t=await this.term(e,`in`,n+1);return t?.texture?{...t,transform:{scale:e.value(`inputs:scale`),translation:e.value(`inputs:translation`),rotation:e.value(`inputs:rotation`)}}:t}case void 0:{let[r]=e.connections(`outputs:${t}`);if(!r)return null;let i=r.lastIndexOf(`.`),a=await this.stage.primAt(r.slice(0,i)),o=r.slice(i+1);return a?o.startsWith(`outputs:`)?this.output(a,o.slice(8),n+1):this.term(a,o.slice(7),n+1):null}default:return r?.startsWith(`ND_`)?this.mtlxOutput(e,r,t,n):(this.warnOnce(`shader:${r}`,`USD shader "${r}" is not read — its input left at its default`),null)}}async texture(e,t,n){let r=e.assetPath(`inputs:file`),i=e.value(`inputs:fallback`);if(!r?.path)return r?.asset&&this.warnOnce(`tex:${r.asset}`,`USD texture "${r.asset}" not found`),i?{value:i}:null;if(JI.test(r.path))return{primvar:`displayColor`};if(/<udim>/i.test(r.asset))return this.warnOnce(`udim`,`USD UDIM textures are not supported — skipped`),null;let a=await this.term(e,`st`,n+1);return{texture:{path:r.path,uvSet:a?.primvar??`st`,wrapS:e.value(`inputs:wrapS`)??`repeat`,wrapT:e.value(`inputs:wrapT`)??`repeat`,colorSpace:e.value(`inputs:sourceColorSpace`)??`auto`,scale:e.value(`inputs:scale`)??null},channel:t}}async image(e,t){let n=`${e.path}|${t}|${e.wrapS}|${e.wrapT}`;return this._images.has(n)||this._images.set(n,(async()=>{let n=await this.resolveImage(e.path);if(!n)return this.warnOnce(`img:${e.path}`,`USD texture "${e.path}" could not be read`),null;let i=n.clone();return i.userData.usdPath=e.path,i.colorSpace=t?r.SRGBColorSpace:r.NoColorSpace,i.wrapS=YI[e.wrapS]??r.RepeatWrapping,i.wrapT=YI[e.wrapT]??r.RepeatWrapping,i.needsUpdate=!0,i})()),this._images.get(n)}async applyColor(e,t,n,r,i){if(n){if(Array.isArray(n.value))e[t].setRGB(n.value[0],n.value[1],n.value[2]);else if(typeof n.value==`number`)e[t].setRGB(n.value,n.value,n.value);else if(n.primvar&&t===`color`)r.perMesh={primvar:n.primvar,exponent:n.exponent??null};else if(n.texture&&i){let a=await this.image(n.texture,n.texture.colorSpace!==`raw`);if(a){e[i]=this.transformTexture(a,n.transform);let o=n.texture.scale;e[t].setRGB(o?.[0]??1,o?.[1]??1,o?.[2]??1),r.uvSet=n.texture.uvSet}}}}async applyScalar(e,t,n,r,i=null,a=null){if(n){if(typeof n.value==`number`)e[t]=n.value;else if(n.texture&&i){if(n.channel!==a&&!n.mono){this.warnOnce(`chan:${i}:${n.channel}`,`USD ${t} from a texture's "${n.channel}" channel is not supported (the engine reads "${a}") — constant used`);return}let o=await this.image(n.texture,!1);o&&(e[i]=this.transformTexture(o,n.transform),e[t]=n.texture.scale?.[0]??1,r.uvSet=n.texture.uvSet)}}}transformTexture(e,t){if(!t)return e;let n=e.clone();if(t.matrix){let[e,r,i,a,o,s]=t.matrix;return n.matrixAutoUpdate=!1,n.matrix.set(e,r,i,a,o,s,0,0,1),n}return t.scale&&n.repeat.set(t.scale[0],t.scale[1]),t.translation&&n.offset.set(t.translation[0],t.translation[1]),t.rotation&&(n.rotation=t.rotation*UI),n}async disney(e){let t=t=>this.term(e,t),n=async(e,n)=>{let r=await t(e);return typeof r?.value==`number`?r.value:n},i=new r.MeshPhysicalMaterial({side:r.DoubleSide}),a={material:i,perMesh:null,uvSet:`st`};i.color.setRGB(.2,.5,.8),await this.applyColor(i,`color`,await t(`baseColor`),a,`map`),i.metalness=await n(`metallic`,0),i.roughness=await n(`roughness`,.5),i.ior=await n(`ior`,1.5);let o=a.perMesh?null:i.color.clone(),s=e=>{let t=.3*e.r+.6*e.g+.1*e.b;return t>0?e.clone().multiplyScalar(1/t):new r.Color(1,1,1)},c=await n(`specularTint`,0);c>0&&o&&i.specularColor.lerp(s(o),c);let l=await n(`sheen`,0);if(l>0){let e=await n(`sheenTint`,.5);i.sheen=Math.min(1,l),i.sheenColor.set(1,1,1),o&&i.sheenColor.lerp(s(o),e),i.sheenRoughness=.5}let u=await n(`clearcoat`,0);u>0&&(i.clearcoat=.25*u,i.clearcoatRoughness=Math.sqrt(.1+-.099*await n(`clearcoatGloss`,1)));let d=await n(`specTrans`,0);if(d>0){i.transmission=d;let e=(await t(`transColor`))?.value,r=await n(`transDistance`,0);Array.isArray(e)&&r>0&&(i.attenuationColor.setRGB(e[0],e[1],e[2]),i.attenuationDistance=r)}let f=await n(`isThin`,0),p=await n(`diffTrans`,0);f&&p>0&&(i.diffuseTransmission=Math.min(1,p/2),i.diffuseTransmissionColor=i.color.clone(),i.userData.diffuseTransmissionFromBase=!0);let m=await n(`opacity`,1);return m<1&&(i.opacity=m,i.transparent=!0),await this.applyColor(i,`emissive`,await t(`emitColor`),a,`emissiveMap`),a}async pxrSurface(e){let t=t=>this.term(e,t),n=async(e,n)=>{let r=await t(e);return typeof r?.value==`number`?r.value:n},i=new r.MeshPhysicalMaterial({side:r.DoubleSide}),a={material:i,perMesh:null,uvSet:`st`};await this.applyColor(i,`color`,await t(`diffuseColor`),a,`map`),i.color.multiplyScalar(await n(`diffuseGain`,1)),i.roughness=await n(`specularRoughness`,.2),i.metalness=0;let o=await n(`refractionGain`,0);if(o>0)i.transmission=Math.min(1,o),i.ior=await n(`glassIor`,1.5),i.roughness=await n(`glassRoughness`,.1),i.color.setRGB(1,1,1);else{let e=await n(`diffuseTransmitGain`,0);if(e>0){let n=(await t(`diffuseTransmitColor`))?.value;i.diffuseTransmission=Math.min(1,e),i.diffuseTransmissionColor=Array.isArray(n)?new r.Color().setRGB(n[0],n[1],n[2]):new r.Color(1,1,1)}}let s=await n(`presence`,1);return s<1&&(i.opacity=s,i.transparent=!0),a}async previewSurface(e){let t=t=>this.term(e,t),n=new r.MeshPhysicalMaterial({side:r.DoubleSide,roughness:.5,metalness:0}),i={material:n,perMesh:null,uvSet:`st`};if(n.color.setRGB(.18,.18,.18),await this.applyColor(n,`color`,await t(`diffuseColor`),i,`map`),await this.applyColor(n,`emissive`,await t(`emissiveColor`),i,`emissiveMap`),(n.emissiveMap||n.emissive.r+n.emissive.g+n.emissive.b>0)&&(n.emissiveIntensity=1),await this.applyScalar(n,`roughness`,await t(`roughness`),i,`roughnessMap`,`g`),await this.applyScalar(n,`clearcoat`,await t(`clearcoat`),i),await this.applyScalar(n,`clearcoatRoughness`,await t(`clearcoatRoughness`),i),await this.applyScalar(n,`ior`,await t(`ior`),i),(await t(`useSpecularWorkflow`))?.value===1){n.metalness=0;let e=(await t(`specularColor`))?.value;Array.isArray(e)&&n.specularColor.setRGB(e[0],e[1],e[2])}else await this.applyScalar(n,`metalness`,await t(`metallic`),i,`metalnessMap`,`b`);let a=await t(`opacity`),o=(await t(`opacityThreshold`))?.value??0;typeof a?.value==`number`&&a.value<1?o>0?n.alphaTest=o:n.transmission=1-a.value:a?.texture&&(a.texture.path===n.map?.userData.usdPath&&a.channel===`a`?(n.transparent=!0,o>0&&(n.alphaTest=o)):this.warnOnce(`opacitymap`,`USD opacity from a texture other than the colour map's alpha is not supported`));let s=await t(`normal`);if(s?.texture){let e=await this.image(s.texture,!1);e&&(n.normalMap=e,i.uvSet=s.texture.uvSet)}return i}async mtlxOutput(e,t,n,r){let i=ZI(t),a=t=>this.term(e,t,r+1),o=async(e,t)=>{let n=(await a(e))?.value;return n===void 0?t:n};switch(i){case`image`:case`tiledimage`:return this.mtlxImage(e,t,i,r);case`texcoord`:return await o(`index`,0)>0&&this.warnOnce(`mtlx:texcoord`,`MaterialX texture coordinates past the first set are read as the first`),{uv:{set:`st`,m:eL}};case`geompropvalue`:{let e=await o(`geomprop`,null);return e?/vector2/.test(t)?{uv:{set:e,m:eL}}:{primvar:e}:a(`default`)}case`constant`:return a(`value`);case`dot`:return a(`in`);case`convert`:return this.mtlxConvert(await a(`in`),t);case`extract`:return this.mtlxChannel(await a(`in`),await o(`index`,0));case`separate2`:case`separate3`:case`separate4`:return this.mtlxChannel(await a(`in`),{outx:0,outy:1,outz:2,outw:3,outr:0,outg:1,outb:2,outa:3}[n]??0);case`combine2`:case`combine3`:case`combine4`:{let e=await Promise.all([`in1`,`in2`,`in3`,`in4`].slice(0,Number(i.slice(-1))).map(a));return e.every(e=>tL(e?.value))?{value:e.map(e=>e.value)}:e.find(e=>e?.texture)??null}case`mix`:{let[e,t,n]=await Promise.all([a(`fg`),a(`bg`),a(`mix`)]);if(nL(e?.value)&&nL(t?.value)&&tL(n?.value))return{value:EI(t.value,e.value,(e,t)=>e+(t-e)*n.value)};this.warnOnce(`mtlx:mix`,`MaterialX mixes of a texture are read as their larger part`);let r=!tL(n?.value)||n.value>=.5;return(r?e:t)??(r?t:e)}case`multiply`:case`divide`:case`add`:case`subtract`:case`min`:case`max`:case`power`:case`modulo`:return this.mtlxArithmetic(i,await a(`in1`),await a(`in2`));case`invert`:{let e=await a(`in`),t=await o(`amount`,1);return nL(e?.value)?{value:EI(t,e.value,(e,t)=>e-t)}:e}case`clamp`:{let e=await a(`in`);if(!nL(e?.value))return e;let[t,n]=[await o(`low`,0),await o(`high`,1)];return{value:EI(EI(e.value,t,Math.max),n,Math.min)}}case`hsvadjust`:return this.mtlxHsv(await a(`in`),await o(`amount`,[0,1,1]));case`rotate2d`:case`rotate3d`:{let e=await a(`in`),t=await o(`amount`,0),n=i===`rotate3d`?await o(`axis`,[0,1,0]):[0,0,1];return!e?.uv||!t?e:Math.abs(n[0])>1e-6||Math.abs(n[1])>1e-6?(this.warnOnce(`mtlx:rotate`,`MaterialX texture coordinates turned about an axis other than z are left unturned`),e):{uv:{...e.uv,m:DI(e.uv.m,Math.sign(n[2])*t)}}}case`place2d`:{let e=await a(`texcoord`);if(!e?.uv)return e;let[t,n,r,i]=[await o(`pivot`,[0,0]),await o(`scale`,[1,1]),await o(`rotate`,0),await o(`offset`,[0,0])],s=await o(`operationorder`,0)!==0,c=oL(e.uv.m,[-t[0],-t[1]]),l=n.map(e=>e?1/e:1);return c=s?aL(DI(oL(c,[-i[0],-i[1]]),r),l):oL(DI(aL(c,l),r),[-i[0],-i[1]]),{uv:{...e.uv,m:oL(c,t)}}}case`normalmap`:{let e=await a(`in`);return e?.texture?{...e,normalScale:await o(`scale`,1)}:null}case`heighttonormal`:{let e=await a(`in`);return e?.texture?{...e,bump:await o(`scale`,1)}:null}case`artistic_ior`:return{artistic:{reflectivity:await a(`reflectivity`),edge:await a(`edge_color`)}};case`normal`:case`tangent`:case`bitangent`:case`position`:case`viewdirection`:return null}return this.warnOnce(`mtlx:${i}`,`MaterialX node "${i}" is not read — its input left at its default`),null}async mtlxImage(e,t,n,r){let i=e.assetPath(`inputs:file`);if(!i?.path)return i?.asset&&this.warnOnce(`tex:${i.asset}`,`USD texture "${i.asset}" not found`),this.term(e,`default`,r+1);if(/<udim>/i.test(i.asset))return this.warnOnce(`udim`,`USD UDIM textures are not supported — skipped`),null;let a=await this.term(e,`texcoord`,r+1),o=a?.uv?.m??eL;if(n===`tiledimage`){let t=e.value(`inputs:uvtiling`)??[1,1],n=e.value(`inputs:uvoffset`)??[0,0];o=oL(aL(o,t),[-n[0],-n[1]])}let s=e.propertyMeta(`inputs:file`,`colorSpace`)??e.value(`inputs:file:colorSpace`),c=/_float$/.test(t);return{texture:{path:i.path,uvSet:a?.uv?.set??a?.primvar??`st`,wrapS:$I[e.value(`inputs:uaddressmode`)]??`repeat`,wrapT:$I[e.value(`inputs:vaddressmode`)]??`repeat`,colorSpace:s?/srgb/i.test(s)?`sRGB`:`raw`:`auto`,scale:null},channel:c?`r`:`rgb`,mono:c,transform:o.every((e,t)=>Math.abs(e-eL[t])<1e-9)?null:{matrix:o}}}mtlxConvert(e,t){if(!nL(e?.value))return e;let n={float:1,color3:3,vector3:3,color4:4,vector4:4,vector2:2}[t.slice(t.lastIndexOf(`_`)+1)]??3,r=e.value;return n===1?{value:tL(r)?r:r[0]}:tL(r)?{value:Array(n).fill(r)}:{value:Array.from({length:n},(e,t)=>r[t]??+(t===3))}}mtlxChannel(e,t){return nL(e?.value)?{value:tL(e.value)?e.value:e.value[t]??0}:e?.texture?{...e,channel:`rgba`[t]??`r`,mono:!1}:e}mtlxArithmetic(e,t,n){let r={multiply:(e,t)=>e*t,divide:(e,t)=>t?e/t:0,add:(e,t)=>e+t,subtract:(e,t)=>e-t,min:Math.min,max:Math.max,power:(e,t)=>Math.max(e,0)**t,modulo:(e,t)=>t?e-t*Math.floor(e/t):0};if(nL(t?.value)&&nL(n?.value))return{value:EI(t.value,n.value,r[e])};let i=t?.uv??n?.uv,a=t?.uv?n?.value:t?.value;if(i&&nL(a)&&(e===`multiply`||e===`add`||t?.uv&&(e===`divide`||e===`subtract`))){let t=tL(a)?[a,a]:a;return e===`multiply`?{uv:{...i,m:aL(i.m,t)}}:e===`divide`?{uv:{...i,m:aL(i.m,t.map(e=>e?1/e:1))}}:{uv:{...i,m:oL(i.m,e===`add`?t:t.map(e=>-e))}}}let o=t?.texture?t:n?.texture?n:null,s=t?.texture?n?.value:t?.value;if(o&&nL(s)&&(e===`multiply`||t?.texture&&e===`divide`)){let t=e===`divide`?rL(s,e=>e?1/e:1):s,n=EI(o.texture.scale??[1,1,1],t,(e,t)=>e*t);return{...o,texture:{...o.texture,scale:tL(n)?[n,n,n]:n}}}return o&&this.warnOnce(`mtlx:${e}`,`MaterialX ${e} of a texture is read as the texture alone`),o??t??n}mtlxHsv(e,t){if(!Array.isArray(e?.value))return e?.texture&&(t[0]||t[1]!==1||t[2]!==1)&&this.warnOnce(`mtlx:hsv`,`MaterialX hue, saturation and value changes to a texture are not applied`),e;let n=new r.Color().setRGB(e.value[0],e.value[1],e.value[2]),i=n.getHSL({});return n.setHSL((i.h+t[0]+1)%1,Math.min(1,i.s*t[1]),i.l),{value:[n.r*t[2],n.g*t[2],n.b*t[2]]}}async mtlxNormal(e,t,n){if(!t?.texture)return;let r=this.transformTexture(await this.image(t.texture,!1),t.transform);r&&(t.bump===void 0?(e.normalMap=r,e.normalScale.set(t.normalScale??1,t.normalScale??1)):(e.bumpMap=r,e.bumpScale=t.bump),n.uvSet=t.texture.uvSet)}mtlxOpacity(e,t){nL(t?.value)&&iL(t.value)<1?(e.opacity=iL(t.value),e.transparent=!0):t?.texture&&(t.texture.path===e.map?.userData.usdPath&&t.channel===`a`?e.transparent=!0:this.warnOnce(`opacitymap`,`USD opacity from a texture other than the colour map's alpha is not supported`))}async mtlxWeighted(e,t,n,r,i,a){await this.applyColor(e,t,n,i,a),tL(r)&&e[t].multiplyScalar(r)}mtlxSurfaceOf(e){return{material:e,perMesh:null,uvSet:`st`}}mtlxDiffuseRoughness(e){return e?.texture&&this.warnOnce(`mtlx:diffuseroughness`,`MaterialX diffuse roughness from a texture is not read`),tL(e?.value)?e.value:0}async openPbrSurface(e){let t=t=>this.term(e,t),n=async(e,n)=>{let r=(await t(e))?.value;return tL(r)?r:n},i=new r.MeshPhysicalMaterial({side:r.DoubleSide}),a=this.mtlxSurfaceOf(i);i.color.setRGB(.8,.8,.8),await this.mtlxWeighted(i,`color`,await t(`base_color`),await n(`base_weight`,1),a,`map`),i.metalness=0,await this.applyScalar(i,`metalness`,await t(`base_metalness`),a,`metalnessMap`,`b`),i.roughness=.3,await this.applyScalar(i,`roughness`,await t(`specular_roughness`),a,`roughnessMap`,`g`),i.specularIntensity=Math.min(1,await n(`specular_weight`,1));let o=(await t(`specular_color`))?.value;Array.isArray(o)&&i.specularColor.setRGB(o[0],o[1],o[2]),i.ior=await n(`specular_ior`,1.5),i.anisotropy=await n(`specular_roughness_anisotropy`,0),i.diffuseRoughness=this.mtlxDiffuseRoughness(await t(`base_diffuse_roughness`));let s=await n(`transmission_weight`,0);if(s>0){i.transmission=s;let e=(await t(`transmission_color`))?.value,a=await n(`transmission_depth`,0);Array.isArray(e)&&a>0?(i.attenuationColor.setRGB(e[0],e[1],e[2]),i.attenuationDistance=a):Array.isArray(e)&&i.color.lerp(new r.Color().setRGB(e[0],e[1],e[2]),s);let o=await n(`transmission_dispersion_abbe_number`,20),c=await n(`transmission_dispersion_scale`,0);c>0&&o>0&&(i.dispersion=c*20/o)}let c=await n(`subsurface_weight`,0);if(c>0){let e=(await t(`subsurface_color`))?.value,a=await n(`subsurface_radius`,1),o=(await t(`subsurface_radius_scale`))?.value;i.subsurface=c,i.subsurfaceColor=Array.isArray(e)?new r.Color().setRGB(e[0],e[1],e[2]):i.color.clone(),i.subsurfaceRadius=Array.isArray(o)?[...o]:[1,1,1],i.subsurfaceRadiusScale=a,i.subsurfaceAnisotropy=await n(`subsurface_scatter_anisotropy`,0)}i.clearcoat=await n(`coat_weight`,0),i.clearcoatRoughness=await n(`coat_roughness`,0);let l=await n(`fuzz_weight`,0);if(l>0){let e=(await t(`fuzz_color`))?.value??[1,1,1];i.sheen=Math.min(1,l),i.sheenColor.setRGB(e[0],e[1],e[2]),i.sheenRoughness=await n(`fuzz_roughness`,.5)}let u=await n(`thin_film_weight`,0);if(u>0){let e=await n(`thin_film_thickness`,.5)*1e3;i.iridescence=Math.min(1,u),i.iridescenceIOR=await n(`thin_film_ior`,1.4),i.iridescenceThicknessRange=[e,e]}let d=await n(`emission_luminance`,0);return d>0&&(i.emissive.setRGB(1,1,1),await this.applyColor(i,`emissive`,await t(`emission_color`),a,`emissiveMap`),i.emissiveIntensity=d),this.mtlxOpacity(i,await t(`geometry_opacity`)),await this.mtlxNormal(i,await t(`geometry_normal`),a),a}async standardSurface(e){let t=t=>this.term(e,t),n=async(e,n)=>{let r=(await t(e))?.value;return tL(r)?r:n},i=new r.MeshPhysicalMaterial({side:r.DoubleSide}),a=this.mtlxSurfaceOf(i);i.color.setRGB(.8,.8,.8),await this.mtlxWeighted(i,`color`,await t(`base_color`),await n(`base`,1),a,`map`),i.metalness=0,await this.applyScalar(i,`metalness`,await t(`metalness`),a,`metalnessMap`,`b`),i.roughness=.2,await this.applyScalar(i,`roughness`,await t(`specular_roughness`),a,`roughnessMap`,`g`),i.specularIntensity=Math.min(1,await n(`specular`,1));let o=(await t(`specular_color`))?.value;Array.isArray(o)&&i.specularColor.setRGB(o[0],o[1],o[2]),i.ior=await n(`specular_IOR`,1.5),i.anisotropy=await n(`specular_anisotropy`,0),i.anisotropyRotation=await n(`specular_rotation`,0)*Math.PI*2,i.diffuseRoughness=this.mtlxDiffuseRoughness(await t(`diffuse_roughness`));let s=await n(`transmission`,0);if(s>0){i.transmission=s;let e=(await t(`transmission_color`))?.value,a=await n(`transmission_depth`,0);Array.isArray(e)&&a>0?(i.attenuationColor.setRGB(e[0],e[1],e[2]),i.attenuationDistance=a):Array.isArray(e)&&i.color.lerp(new r.Color().setRGB(e[0],e[1],e[2]),s);let o=await n(`transmission_dispersion`,0);o>0&&(i.dispersion=20/o)}let c=await n(`subsurface`,0);if(c>0){let e=(await t(`subsurface_color`))?.value,a=(await t(`subsurface_radius`))?.value;i.subsurface=c,i.subsurfaceColor=Array.isArray(e)?new r.Color().setRGB(e[0],e[1],e[2]):i.color.clone(),i.subsurfaceRadius=Array.isArray(a)?[...a]:[1,1,1],i.subsurfaceRadiusScale=await n(`subsurface_scale`,1),i.subsurfaceAnisotropy=await n(`subsurface_anisotropy`,0)}let l=await n(`sheen`,0);if(l>0){let e=(await t(`sheen_color`))?.value??[1,1,1];i.sheen=Math.min(1,l),i.sheenColor.setRGB(e[0],e[1],e[2]),i.sheenRoughness=await n(`sheen_roughness`,.3)}i.clearcoat=await n(`coat`,0),i.clearcoatRoughness=await n(`coat_roughness`,.1);let u=await n(`thin_film_thickness`,0);u>0&&(i.iridescence=1,i.iridescenceIOR=await n(`thin_film_IOR`,1.5),i.iridescenceThicknessRange=[u,u]);let d=await n(`emission`,0);return d>0&&(i.emissive.setRGB(1,1,1),await this.applyColor(i,`emissive`,await t(`emission_color`),a,`emissiveMap`),i.emissiveIntensity=d),this.mtlxOpacity(i,await t(`opacity`)),await this.mtlxNormal(i,await t(`normal`),a),a}async gltfPbrSurface(e){let t=t=>this.term(e,t),n=async(e,n)=>{let r=(await t(e))?.value;return tL(r)?r:n},i=new r.MeshPhysicalMaterial({side:r.DoubleSide}),a=this.mtlxSurfaceOf(i);await this.applyColor(i,`color`,await t(`base_color`),a,`map`),i.metalness=1,await this.applyScalar(i,`metalness`,await t(`metallic`),a,`metalnessMap`,`b`),i.roughness=1,await this.applyScalar(i,`roughness`,await t(`roughness`),a,`roughnessMap`,`g`),i.ior=await n(`ior`,1.5),i.specularIntensity=await n(`specular`,1);let o=(await t(`specular_color`))?.value;Array.isArray(o)&&i.specularColor.setRGB(o[0],o[1],o[2]),i.transmission=await n(`transmission`,0),i.thickness=await n(`thickness`,0);let s=(await t(`attenuation_color`))?.value;Array.isArray(s)&&i.attenuationColor.setRGB(s[0],s[1],s[2]);let c=await n(`attenuation_distance`,0);c>0&&(i.attenuationDistance=c),i.dispersion=await n(`dispersion`,0),i.clearcoat=await n(`clearcoat`,0),i.clearcoatRoughness=await n(`clearcoat_roughness`,0);let l=(await t(`sheen_color`))?.value;Array.isArray(l)&&iL(l)>0&&(i.sheen=1,i.sheenColor.setRGB(l[0],l[1],l[2]),i.sheenRoughness=await n(`sheen_roughness`,0));let u=await n(`iridescence`,0);if(u>0){let e=await n(`iridescence_thickness`,100);i.iridescence=u,i.iridescenceIOR=await n(`iridescence_ior`,1.3),i.iridescenceThicknessRange=[e,e]}await this.applyColor(i,`emissive`,await t(`emissive`),a,`emissiveMap`),i.emissiveIntensity=await n(`emissive_strength`,1);let d=await n(`alpha_mode`,0);return d>0&&(this.mtlxOpacity(i,await t(`alpha`)),d===1&&(i.alphaTest=await n(`alpha_cutoff`,.5))),await this.mtlxNormal(i,await t(`normal`),a),a}async bsdfSurface(e){let t=[],n=[];await this.mtlxLobes(e,`inputs:bsdf`,1,t,0),await this.mtlxEmission(e,`inputs:edf`,1,n,0);let i=new r.MeshPhysicalMaterial({side:r.DoubleSide}),a=this.mtlxSurfaceOf(i),o=e=>t.filter(t=>e.includes(t.kind)).reduce((e,t)=>e+t.w,0),s=o([`diffuse`,`conductor`,`transmission`]);if(s>0){let e=t.filter(e=>[`diffuse`,`conductor`,`transmission`].includes(e.kind)&&e.w>0),n=e.filter(e=>e.color?.texture).sort((e,t)=>t.w-e.w)[0],r=[0,0,0];for(let t of e){let e=nL(t.color?.value)?t.color.value:t.color?.texture?t.color.texture.scale??[1,1,1]:[.8,.8,.8];for(let n=0;n<3;n++)r[n]+=(tL(e)?e:e[n])*t.w/s}n&&n.w/s>=.5?(await this.applyColor(i,`color`,n.color,a,`map`),e.some(e=>e!==n&&e.w>0)&&this.warnOnce(`mtlx:lobecolor`,`MaterialX lobes of different colours over a texture are read as the texture`)):i.color.setRGB(r[0],r[1],r[2]),i.metalness=o([`conductor`])/s,i.transmission=o([`transmission`])/s;let c=t.filter(e=>e.kind===`diffuse`&&e.w>0),l=o([`diffuse`]);l>0&&(i.diffuseRoughness=c.reduce((e,t)=>e+t.roughness*t.w,0)/l)}else i.color.setRGB(0,0,0);let c=t.filter(e=>[`conductor`,`transmission`,`reflection`].includes(e.kind)&&e.w>0),l=c.reduce((e,t)=>e+t.w,0);i.roughness=l>0?c.reduce((e,t)=>e+t.roughness*t.w,0)/l:1;let u=t.filter(e=>[`transmission`,`reflection`].includes(e.kind)&&e.w>0);i.ior=u.length?u.reduce((e,t)=>e+t.ior*t.w,0)/u.reduce((e,t)=>e+t.w,0):1.5;let d=t.filter(e=>e.kind===`reflection`&&e.w>0);if(d.length){let e=d.find(e=>nL(e.tint))?.tint;Array.isArray(e)&&i.specularColor.setRGB(e[0],e[1],e[2]),i.specularIntensity=Math.min(1,o([`reflection`]))}else i.transmission===0&&(i.specularIntensity=0);let f=t.find(e=>e.kind===`sheen`);f&&(i.sheen=Math.min(1,o([`sheen`])),Array.isArray(f.color)&&i.sheenColor.setRGB(f.color[0],f.color[1],f.color[2]),i.sheenRoughness=f.roughness);let p=t.find(e=>e.kind===`subsurface`);p&&s+p.w>0&&(i.subsurface=Math.min(1,o([`subsurface`])/(s+o([`subsurface`]))),i.subsurfaceColor=Array.isArray(p.color)?new r.Color().setRGB(p.color[0],p.color[1],p.color[2]):i.color.clone(),i.subsurfaceRadius=Array.isArray(p.radius)?[...p.radius]:[1,1,1],i.subsurfaceAnisotropy=p.anisotropy);let m=t.find(e=>e.kind===`translucent`);if(m){let e=o([`translucent`])/(o([`diffuse`])+o([`translucent`]));i.diffuseTransmission=Math.min(1,e),i.diffuseTransmissionColor=Array.isArray(m.color)?new r.Color().setRGB(m.color[0],m.color[1],m.color[2]):new r.Color(1,1,1)}if(n.length){let e=n.find(e=>e.color?.texture);if(e)i.emissive.setRGB(1,1,1),await this.applyColor(i,`emissive`,e.color,a,`emissiveMap`),i.emissiveIntensity=e.w;else{let e=[0,0,0];for(let t of n){let n=nL(t.color?.value)?t.color.value:[1,1,1];for(let r=0;r<3;r++)e[r]+=(tL(n)?n:n[r])*t.w}let t=Math.max(...e);t>0&&(i.emissive.setRGB(e[0]/t,e[1]/t,e[2]/t),i.emissiveIntensity=t)}}return await this.mtlxNormal(i,t.find(e=>e.normal?.texture)?.normal,a),this.mtlxOpacity(i,await this.term(e,`opacity`)),a}async mtlxLobes(e,t,n,r,i){let a=i<32?await this.stage.connectionSource(e,t):null,o=a?.prim.value(`info:id`);if(!o||n<=0)return;let s=a.prim,c=e=>this.term(s,e,i+1),l=async(e,t)=>{let n=(await c(e))?.value;return tL(n)?n:Array.isArray(n)?iL(n):t},u=n*await l(`weight`,1);switch(ZI(o)){case`oren_nayar_diffuse_bsdf`:r.push({kind:`diffuse`,w:u,color:await c(`color`),normal:await c(`normal`),roughness:this.mtlxDiffuseRoughness(await c(`roughness`))});return;case`burley_diffuse_bsdf`:r.push({kind:`diffuse`,w:u,color:await c(`color`),normal:await c(`normal`),roughness:0});return;case`conductor_bsdf`:{let e=await c(`ior`),t=e?.artistic?.reflectivity??null;t||={value:EI(nL(e?.value)?e.value:[.18,.42,1.37],(await c(`extinction`))?.value??[3.42,2.35,1.77],(e,t)=>((e-1)**2+t*t)/((e+1)**2+t*t))},r.push({kind:`conductor`,w:u,color:t,roughness:await l(`roughness`,.2),normal:await c(`normal`)});return}case`dielectric_bsdf`:case`generalized_schlick_bsdf`:{let e=(await c(`scatter_mode`))?.value??`R`,t=await l(`roughness`,.05),n=await c(`normal`);if(ZI(o)===`generalized_schlick_bsdf`){let i=(await c(`color0`))?.value??[1,1,1];iL(i)>.2&&e===`R`?r.push({kind:`conductor`,w:u,color:{value:i},roughness:t,normal:n}):r.push({kind:e===`R`?`reflection`:`transmission`,w:u,tint:[1,1,1],color:{value:[1,1,1]},ior:1.5,roughness:t,normal:n});return}let i=(await c(`tint`))?.value??[1,1,1],a=await l(`ior`,1.5);r.push({kind:e===`R`?`reflection`:`transmission`,w:u,tint:i,color:{value:i},ior:a,roughness:t,normal:n});return}case`sheen_bsdf`:r.push({kind:`sheen`,w:u,color:(await c(`color`))?.value??[1,1,1],roughness:await l(`roughness`,.3)});return;case`subsurface_bsdf`:r.push({kind:`subsurface`,w:u,color:(await c(`color`))?.value,radius:(await c(`radius`))?.value,anisotropy:await l(`anisotropy`,0)});return;case`translucent_bsdf`:r.push({kind:`translucent`,w:u,color:(await c(`color`))?.value});return;case`mix_bsdf`:{let e=(await c(`mix`))?.value;tL(e)||this.warnOnce(`mtlx:mixbsdf`,`MaterialX BSDF mixes driven by a texture are read as an even split`);let t=tL(e)?Math.min(1,Math.max(0,e)):.5;await this.mtlxLobes(s,`inputs:fg`,n*t,r,i+1),await this.mtlxLobes(s,`inputs:bg`,n*(1-t),r,i+1);return}case`add_bsdf`:await this.mtlxLobes(s,`inputs:in1`,n,r,i+1),await this.mtlxLobes(s,`inputs:in2`,n,r,i+1);return;case`layer`:case`layer_bsdf`:await this.mtlxLobes(s,`inputs:top`,n,r,i+1),await this.mtlxLobes(s,`inputs:base`,n,r,i+1);return;case`multiply_bsdfC`:case`multiply_bsdfF`:{let e=(await c(`in2`))?.value,t=r.length;if(await this.mtlxLobes(s,`inputs:in1`,n*(tL(e)?e:1),r,i+1),Array.isArray(e))for(let n of r.slice(t))nL(n.color?.value)&&(n.color={value:EI(n.color.value,e,(e,t)=>e*t)});return}case`thin_film_bsdf`:return}this.warnOnce(`mtlx:${ZI(o)}`,`MaterialX node "${ZI(o)}" is not read — its lobe left out`)}async mtlxEmission(e,t,n,r,i){let a=i<32?await this.stage.connectionSource(e,t):null,o=a?.prim.value(`info:id`);if(!o||n<=0)return;let s=a.prim,c=e=>this.term(s,e,i+1);switch(ZI(o)){case`uniform_edf`:case`conical_edf`:case`measured_edf`:r.push({w:n,color:await c(`color`)});return;case`add_edf`:await this.mtlxEmission(s,`inputs:in1`,n,r,i+1),await this.mtlxEmission(s,`inputs:in2`,n,r,i+1);return;case`mix_edf`:{let e=(await c(`mix`))?.value,t=tL(e)?e:.5;await this.mtlxEmission(s,`inputs:fg`,n*t,r,i+1),await this.mtlxEmission(s,`inputs:bg`,n*(1-t),r,i+1);return}case`multiply_edfC`:case`multiply_edfF`:{let e=(await c(`in2`))?.value;await this.mtlxEmission(s,`inputs:in1`,n*(nL(e)?iL(e):1),r,i+1);return}}this.warnOnce(`mtlx:${ZI(o)}`,`MaterialX node "${ZI(o)}" is not read — its emission left out`)}camera(e,t){let n=e.value(`horizontalAperture`)??20.955,i=e.value(`verticalAperture`)??15.2908,a=e.value(`focalLength`)??50,o=e.value(`clippingRange`),[s,c]=o??[1,1e6],l=e.value(`projection`)===`orthographic`?new r.OrthographicCamera(-n/20,n/20,i/20,-i/20,s,c):new r.PerspectiveCamera(2*Math.atan(i/(2*a))/UI,n/i,s,c);l.name=e.name,o&&s>0&&(l.userData.clipStart=s);let u=new r.Vector3;t.decompose(l.position,l.quaternion,u),l.updateMatrixWorld(!0),this.cameras.push(l)}light(e,t,n){let i=(t,n)=>e.value(`inputs:${t}`)??e.value(t)??n,a=i(`color`,[1,1,1]),o=i(`intensity`,t===`DistantLight`?5e4:1)*2**i(`exposure`,0);if(i(`enableColorTemperature`,!1)&&this.warnOnce(`temperature`,`USD light colour temperature is not applied`),e.propertyNames().some(e=>e.startsWith(`collection:lightLink`)||e.startsWith(`collection:shadowLink`))&&t!==`DomeLight`&&this.warnOnce(`linking`,`USD light linking is not supported — every light lights everything`),t===`DomeLight`){let t=e.assetPath(`inputs:texture:file`)??e.assetPath(`texture:file`),r=e.targets(`collection:lightLink:excludes`),i=this.stage.pseudoRoot.childNames().map(e=>`/${e}`);this.domes.push({name:e.name,file:t?.path??null,asset:t?.asset??null,intensity:o,matrix:n.clone(),color:a,lightsScene:!r.some(e=>i.includes(e))});return}let s=!!i(`normalize`,!1),c;if(t===`RectLight`||t===`DiskLight`){let e=t===`DiskLight`,n=i(`radius`,.5);c=new r.RectAreaLight(new r.Color,o,e?n*2:i(`width`,1),e?n*2:i(`height`,1)),c.userData.normalize=s,e&&(c.userData.shape=`disk`),s&&(c.intensity=Math.PI*o,c.userData.__radianceConverted=!0)}else if(t===`SphereLight`||t===`CylinderLight`){let e=i(`radius`,.5),n=i(`shaping:cone:angle`,180),a=t===`SphereLight`?4*Math.PI*e*e:2*Math.PI*e*i(`length`,1),l=Math.PI*o*(s?1:a);n<90?(c=new r.SpotLight(new r.Color,l),c.angle=n*UI,c.penumbra=Math.min(1,Math.max(0,i(`shaping:cone:softness`,0)))):c=new r.PointLight(new r.Color,l),c.decay=2,c.distance=0,!i(`treatAsPoint`,!1)&&e>0&&(c.userData.radius=e),c.userData.__candelaConverted=!0,t===`CylinderLight`&&this.warnOnce(`cylinder`,`USD cylinder lights are placed as point lights`)}else{let e=Math.max(i(`angle`,.53),0)*UI,t=Math.min(e/2,Math.PI),n=Math.sin(t)**2,a=t===0?1:t<=Math.PI/2?Math.PI*n:Math.PI*(2-n);c=new r.DirectionalLight(new r.Color,o*(s?1:a)),c.userData.angle=e,c.userData.__luxConverted=!0}let l=Math.max(a[0],a[1],a[2]);!(l>0)||!(o>0)||(c.color.setRGB(a[0]/l,a[1]/l,a[2]/l),c.intensity*=l,c.name=e.name,n.decompose(c.position,c.quaternion,c.scale),c.target&&(c.target.position.set(0,0,-1),c.add(c.target)),this.lights.push(c))}pickDome(){let e=this.domes.find(e=>e.lightsScene&&e.file)??null;if(this.domes.length>1&&this.warnOnce(`domes`,`${this.domes.length} USD dome lights; "${e?.name??this.domes[0].name}" lights the scene`),!e){let e=this.domes.find(e=>e.asset);return e&&this.warnOnce(`domefile`,`USD dome light texture "${e.asset}" not found`),null}new r.Vector3(0,1,0).transformDirection(e.matrix).y<.999&&this.warnOnce(`domepole`,`USD dome light is tilted; only its turn about the up axis is applied`);let t=new r.Vector3(0,0,1).transformDirection(e.matrix),n=Math.atan2(t.x,t.z)/UI;return{file:e.file,intensity:e.intensity*Math.max(...e.color),rotation:90-n}}}}));function pL(e){let t=e.filter(e=>gL.test(e)&&!e.split(`/`).pop().startsWith(`._`));if(t.length===0)return[];let n=e=>e.split(`/`).length,r=Math.min(...t.map(n));return t.filter(e=>n(e)===r).sort((e,t)=>{let n=e.split(`/`).pop(),r=t.split(`/`).pop();return n.length-r.length||(n<r?-1:+(n>r))})}async function mL(e,t){let n=new Map,r=e.pseudoRoot,i=e.root.id.includes(`/`)?e.root.id.slice(0,e.root.id.lastIndexOf(`/`)):``;for(let t of r.childNames())for(let[,a,o]of(await e.child(r,t))?.sites??[])for(let[t,r]of a.children??[])for(let a of[`references`,`payload`]){let s=r.arcs?.[a];for(let r of[...s?.explicit??[],...s?.prepend??[],...s?.append??[],...s?.add??[]]){let a=e.files.resolve(r.asset,o.path);if(!a?.includes(`/`))continue;let s=a.slice(0,a.lastIndexOf(`/`));s===i||!s.startsWith(i)||n.has(s)||n.set(s,{name:t,prefix:s,files:0,bytes:0,scenes:1})}}let a=new Map;for(let e of n.values()){let t=e.prefix.slice(0,e.prefix.lastIndexOf(`/`));a.has(t)||a.set(t,[]),a.get(t).push(e)}let o=[...a.values()].sort((e,t)=>t.length-e.length)[0]??[];for(let e of o)for(let n of t)!n.path.startsWith(`${e.prefix}/`)||!gL.test(n.path)||(e.files++,e.bytes+=n.size);return o.sort((e,t)=>e.bytes-t.bytes)}async function hL(e){let t=[],n=e=>t.push(e),r=new MP({maxTriangles:e.maxTriangles,maxPlacements:e.maxPlacements,mergeShapesAbove:e.mergeShapesAbove,curveSteps:e.curveSteps,curveSides:e.curveSides,curveTolerance:e.curveTolerance}),i=performance.now(),a=new wI(e.files,{warn:n});await a.open(e.entryPath);let o=new dL(a,{maxTriangles:r.maxTriangles,maxPlacements:r.maxPlacements,curveSteps:r.curveSteps,resolveImage:e.resolveImage,warn:n}),s=await o.read();a.omittedArcs>0&&n(`${a.omittedArcs} reference(s) into the parts left out of this load skipped`);let c=performance.now()-i,l=performance.now(),u=await r.build(s.ir);for(let e of[...s.cameras,...s.lights])u.group.add(e);let d=null;if(s.dome){let t=await e.resolveEnvironment(s.dome.file);t?d={texture:t,intensity:s.dome.intensity,rotation:s.dome.rotation}:n(`USD dome light texture "${s.dome.file}" could not be read`)}return{...u,environment:d,cameras:s.cameras,lights:s.lights,cost:s.cost,fitNote:o.fitNote,warnings:[...t,...u.warnings],parseMs:c,buildMs:performance.now()-l}}var gL,_L=g((()=>{NP(),TI(),fL(),gL=/\.(usd|usda|usdc)$/i}));function vL(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 yL(e){let{data:t,width:n,height:i}=vL(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 bL=g((()=>{})),xL=_({ARCHIVE_ELEMENT_PROMPT_BYTES:()=>kL,ArchiveImporter:()=>jL,USD_ELEMENT_PROMPT_BYTES:()=>AL}),SL,CL,wL,TL,EL,DL,OL,kL,AL,jL,ML=g((()=>{xA(),IA(),UA(),yi(),Sv(),hn(),_j(),Oc(),wc(),de(),gF(),_L(),bL(),xy(),an(),Ov(),Fr(),ny(),SL=3e4,CL=[`scene.gltf`,`scene.glb`,`model.gltf`,`model.glb`,`main.gltf`,`main.glb`,`asset.gltf`,`asset.glb`],wL=e=>e instanceof Blob?e:new Blob([e],{type:`application/octet-stream`}),TL=async e=>e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e,EL=async e=>e instanceof Blob?e.text():(0,m.strFromU8)(e),DL=(e,t)=>{let n=[];for(let r of`${e}/${t}`.split(`/`))r===`..`?n.pop():r&&r!==`.`&&n.push(r);return n.join(`/`)},OL=async e=>{let t=await TL(e);return t.byteOffset===0&&t.byteLength===t.buffer.byteLength?t.buffer:t.slice().buffer},kL=4e9,AL=1e9,jL=class{static FORMATS=wv;constructor(e){this.loader=e,this._store=null,this.lastPBRTStats=null,this.lastUSDStats=null}release(){this._store?.decide(!1),this._store=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=Xk(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 oA(e,{filter:()=>!1,onProgress:n})}else r=t===`tar`?(await zA(e,this.loader.storage))?.listing??await sA(e,{onProgress:n}):(await TA(e)).map(e=>({path:e.name,size:e.size}));let{root:i,elements:a}=fA(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 RA(e,{storage:this.loader.storage,label:t,...r.length?{filter:dA(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=Xk(await this._readHead(e)),c=this.loader.storage?hv(await pv(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(aF(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 loadFolder(e,{pbrtEntry:t=null,element:n=null,promptBytes:r,...i}={}){let a=(Array.isArray(n)?n:[n]).filter(Boolean),o=uA(e,{filter:a.length?dA(a):null}),s=o.listing.reduce((e,t)=>e+t.size,0);a.length===0&&this._requireElementChoice(e.name,o.listing,s,r),console.info(`Folder "${e.name}": ${o.listing.length} files, ${(s/1e9).toFixed(1)} GB`+(a.length?`, ${a.length} part${a.length>1?`s`:``} selected.`:`.`));let c=this.loader.storage?hv(await mv(e)):null;return await this._loadSource(o,e.name,{element:n,pbrtEntry:t,pbrt:i,archiveId:c,promptBytes:r,kind:`folder`})}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});return await this._loadSource(l,t,{element:n,pbrtEntry:i,pbrt:a,archiveId:c,promptBytes:r})}async _loadSource(e,t,{element:n,pbrtEntry:r,pbrt:i,archiveId:a,promptBytes:o,kind:s=`archive`}){if(e.archiveId=a,e.elements=(Array.isArray(n)?n:[n]).filter(Boolean),e.listing.some(e=>e.path.toLowerCase().endsWith(`.pbrt`)))return await this.loadPBRTFromZip({},t,r,i,e);let c=Object.create(null);for(let t of e.listing)t.offset!==void 0&&(c[t.path]=e.entries[t.path]??await e.slice(t.path));let l=this._mainModelPath(Object.keys(c))?.usd?await this.loadUSDScene(c,t,{...i,element:n,promptBytes:o,listing:e.listing}):await this._loadNonPBRTArchive(c,t);return this.loader._sourceKey=this.loader._keyed(s,a),l}async _loadStoredGraph(e,t,{imageFromBytes:n,envFromBytes:r}){let i=this.loader.storage?.area(mn.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 dF({},t),c=await ij(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(X.STORAGE_ENTRY_CORRUPT,`stored scene unusable: ${s.message}`,{key:e}),i.remove(e).catch(()=>{}))}}_storeGraph(e,t,n){let r=this.loader.storage?.area(mn.SCENES);if(!r)return;let i;try{i=ZA(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,parameters:t.parameters??null}})}catch(e){e instanceof hj?console.info(`Scene not stored for next time: ${e.message}`):console.warn(`Scene not stored for next time:`,e);return}let a,o=new AbortController,s={key:e,encoded:i,label:n,model:t.group,writing:!1,signal:o.signal,parseMs:(t.parseMs??0)+(t.buildMs??0),triangles:t.triangleCount??null,accepted:new Promise(e=>{a=e}),decide:e=>{a(e),e||o.abort()}};this._store=s,Tc(s.parseMs,i.byteLength)&&this._writeGraph(r,s)}flushPendingGraph(e){let t=this._store;if(!t||t.writing)return;let n=this.loader.storage?.area(mn.SCENES);n&&Tc(t.parseMs+e,t.encoded.byteLength)?this._writeGraph(n,t):this._store=null}commitPendingGraph(e){let t=this._store;!t||t.model!==e||(this._store=null,t.model=null,t.decide(t.writing))}_writeGraph(e,t){t.writing=!0,(async()=>{let n=null;try{if(n=await e.create(t.key,{label:`${t.label} (scene)`,expectedBytes:t.encoded.byteLength}),!n)return;await QA(n,t.encoded,{release:!0,signal:t.signal}),t.encoded=null,await t.accepted?await n.commit({triangles:t.triangles}):await n.abort()}catch(e){await n?.abort().catch(()=>{}),t.signal.aborted||console.warn(`Storing the scene failed:`,e)}finally{t.encoded=null}})()}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?dA(o):null,c;if(a)c=await OA(e,{filter:s});else{let t=i??await zA(e,this.loader.storage);c=await lA(e,{index:t,headersOnly:!0,filter:s,onProgress:e=>z({isLoading:!0,status:`Indexing archive… ${(e.bytes/1e9).toFixed(1)} GB`,progress:4})}),t||BA(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=kL){if(n<r)return;let{root:i,elements:a}=fA(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(X.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},tn.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 oA(e,{filter:a.length?dA(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}=fA(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(X.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},tn.WARNING),i}if(l){let e=dA(a),t=s.filter(t=>e(t.path,t.size)&&!o[t.path]).length;this.loader._issues?.record(X.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},tn.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,r={},i=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 a=e=>this.loader.loaderCache.ply.parse(e),o=(e,t)=>this._archiveImage(e,t),s=(e,t)=>this._archiveEnvironment(e,t),c=performance.now(),l={animation:r.animation,maxTriangles:r.maxTriangles,maxPlacements:r.maxPlacements,mergeShapesAbove:r.mergeShapesAbove,curveSteps:r.curveSteps,curveSides:r.curveSides,curveTolerance:r.curveTolerance,instanceIncludes:r.instanceIncludes},u=i?.archiveId?this.loader._keyed(`pbrt:2.14:${Cc}`,`${i.archiveId}|${n??``}|${[...i.elements??[]].sort().join(`,`)}|${JSON.stringify(l)}`):null,d=u?await this._loadStoredGraph(u,i,{imageFromBytes:o,envFromBytes:s}):null,f=d??await sF({vfs:e,source:i,entryPath:n,plyParser:a,imageFromBytes:o,envFromBytes:s,...l});this.loader._throwDeferred();let{group:p,environment:m,animations:h,report:g,warnings:_,meshCount:v,entryPath:y,candidates:b,frames:x,parseMs:S,buildMs:C,triangleCount:w,placementCount:T,mergedShapes:E,skippedForBudget:D,droppedNoTemplate:O,parameters:k}=f;d&&console.info(`PBRT scene "${y}" opened from storage in ${(C/1e3).toFixed(1)} s, skipping the parse`),this.lastPBRTStats={parseMs:S,buildMs:C,loaderMs:performance.now()-c,triangleCount:w,placementCount:T,mergedShapes:E,skippedForBudget:D,droppedNoTemplate:O,meshCount:v,frames:x?.length??1};let A=new Set(x??[y]),j=b.filter(e=>!A.has(e));if(j.length>0&&(console.warn(`PBRT archive holds ${b.length} scenes; loaded "${y}". Others: ${j.join(`, `)}`),this.loader._issues?.record(X.ASSET_AMBIGUOUS_ENTRY,`archive holds ${b.length} pbrt scenes; loaded "${y}"`,{loaded:y,alternatives:j},tn.WARNING)),k&&this._reportParameters(k,y),g&&g.length&&typeof console.table==`function`){let e=g.length<v?` (first ${g.length} of ${v})`:``;console.groupCollapsed(`PBRT loader: ${v} mesh(es) from "${y}"${e}`),console.table(g),console.groupEnd()}return _&&_.length&&(console.warn(`PBRT loader: ${_.length} warning(s) parsing "${y}"`),_.forEach(e=>console.warn(` •`,e))),m?.texture&&(m.texture.generateMipmaps=!0,this.loader.applyEnvironmentToScene(m.texture)),p.name=y||t,this.loader.releaseTargetModel(),this.loader._sourceKey=u,u&&!d&&this._storeGraph(u,f,t),this.loader.targetModel=p,this.loader.animations=h??[],this.loader.sceneMetadata={environment:m?.texture?{rotation:0,intensity:1}:{enabled:!1},...f.render?{render:{...f.render}}:{}},z({isLoading:!0,status:`Processing PBRT geometry...`,progress:10}),await this.loader.onModelLoad(this.loader.targetModel),this.loader.dispatchEvent({type:`load`,model:p,filename:`${y} (from ${t})`}),p}_reportParameters({unused:e,approximated:t},n){let r=Object.keys(e).length,i=Object.keys(t).length;if(r+i===0)return;let a=`${r} pbrt parameter(s) ignored and ${i} approximated in "${n}"`,o=[...Object.entries(e).map(([e,t])=>` ignored ${e} ×${t}`),...Object.entries(t).map(([e,t])=>` approximated ${e} ×${t}`)];console.warn(`PBRT loader: ${a} (× directives that set it)\n${o.join(`
|
|
1430
|
+
`)}`),this.loader._issues?.warn(X.ASSET_PARAMETERS_IGNORED,a,{entry:n,unused:e,approximated:t})}async _archiveImage(e,t){let n;try{n=await this._pbrtTextureFromBytes(e,t)}catch(e){if(e instanceof nn)throw e;return this.loader._reportImageFailure(t,e),null}return n&&(n.userData[oj]=t),n}async _archiveEnvironment(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}):yL(e);return o.mapping=r.EquirectangularReflectionMapping,di(o,`bytes:${await fv(i)}`),o.userData[oj]=t,o.userData[sj]=`environment`,o}finally{a&&URL.revokeObjectURL(a)}}async loadUSDScene(e,t,n={}){z({isLoading:!0,status:`Reading USD scene...`,progress:5});let r=Object.keys(e),i=new yI(r,async t=>e[t]?TL(e[t]):null,{omitted:(n.listing??[]).filter(t=>!(t.path in e)).map(e=>e.path)}),a=pL(r);if(a.length===0)throw Error(`No USD layer found in ${t}`);let o=a[0];a.length>1&&(console.warn(`${t} holds ${a.length} top-level USD layers; loaded "${o}". Others: ${a.slice(1).join(`, `)}`),this.loader._issues?.record(X.ASSET_AMBIGUOUS_ENTRY,`${t} holds ${a.length} top-level USD layers; loaded "${o}"`,{loaded:o,alternatives:a.slice(1)},tn.WARNING)),(Array.isArray(n.element)?n.element:[n.element]).filter(Boolean).length===0&&await this._requireUSDPartChoice(t,i,o,n.listing??r.map(t=>({path:t,size:e[t]?.size??e[t]?.byteLength??0})),n.promptBytes);let s=performance.now(),c=await hL({files:i,entryPath:o,resolveImage:async e=>{let t=await i.read(e);return t?this._archiveImage(t,e):null},resolveEnvironment:async e=>{let t=await i.read(e);return t?this._archiveEnvironment(t,e):null},maxTriangles:n.maxTriangles,maxPlacements:n.maxPlacements,mergeShapesAbove:n.mergeShapesAbove,curveSteps:n.curveSteps,curveSides:n.curveSides,curveTolerance:n.curveTolerance});this.loader._throwDeferred();let{group:l,environment:u,warnings:d,triangleCount:f,placementCount:p,skippedForBudget:m,meshCount:h,parseMs:g,buildMs:_,fitNote:v}=c;return this.lastUSDStats={parseMs:g,buildMs:_,loaderMs:performance.now()-s,triangleCount:f,placementCount:p,skippedForBudget:m,meshCount:h,fitNote:v},(v||m>0)&&this.loader._issues?.record(X.SCENE_MEMORY_BUDGET,v??`${m.toLocaleString()} placements past the scene budgets left out`,{triangleCount:f,placementCount:p,skippedForBudget:m},tn.WARNING),d.length&&(console.warn(`USD loader: ${d.length} warning(s) loading "${o}"`),d.forEach(e=>console.warn(` •`,e))),u?.texture&&(u.texture.generateMipmaps=!0,this.loader.applyEnvironmentToScene(u.texture)),l.name=o.split(`/`).pop(),this.loader.releaseTargetModel(),this.loader.targetModel=l,this.loader.animations=[],this.loader.sceneMetadata=u?.texture?{environment:{rotation:u.rotation,intensity:u.intensity}}:null,z({isLoading:!0,status:`Processing USD geometry...`,progress:10}),await this.loader.onModelLoad(l),this.loader.dispatchEvent({type:`load`,model:l,filename:`${o} (from ${t})`}),l}async _requireUSDPartChoice(e,t,n,r,i=AL){let a=r.reduce((e,t)=>e+(gL.test(t.path)?t.size:0),0);if(a<i)return;let o=new wI(t);await o.open(n);let s=await mL(o,r);if(s.length<2)return;let c=r.reduce((e,t)=>e+t.size,0),l=Error(`"${e}" holds ${(a/1e9).toFixed(1)} GB of USD across ${s.length} parts. Choose which to load — loading all of them at once may exhaust memory.`);throw l.code=`ARCHIVE_NEEDS_ELEMENT`,l.root=n.includes(`/`)?n.slice(0,n.lastIndexOf(`/`)):``,l.elements=s,l.totalBytes=c,this.loader._issues?.record(X.ASSET_ARCHIVE_TOO_LARGE,`USD scene holds ${(a/1e9).toFixed(1)} GB of layers across ${s.length} parts; choose which to load`,{root:l.root,elements:s.map(e=>e.prefix),totalBytes:c},tn.WARNING),l}_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=yL(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{if(Dr().decodeImage)i=await Zv(e,t);else if(typeof createImageBitmap==`function`)i=new r.Texture(await createImageBitmap(new Blob([e])));else throw Error(`no image decoder in this runtime: configurePlatform( nodePlatform( { decodeImage } ) ) — see "Running in Node"`);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}_mainModelPath(e){let t=e[0]?.split(`/`)[0],n=t!==void 0&&e.every(e=>e.startsWith(t+`/`))?t+`/`:``,r=e.filter(e=>e.split(`.`).pop().toLowerCase()===`obj`||this.loader.getFileFormat(e)?.type===`model`);if(r.length===0)return null;let i=e=>e.split(`/`).length*2+ +!/\.(gltf|glb)$/i.test(e),a=new Set(e),o=CL.map(e=>n+e).find(e=>a.has(e)),s=o??r.reduce((e,t)=>i(t)<i(e)?t:e);return{path:s,models:r,main:!!o,usd:!o&&gL.test(s)}}async findAndLoadModelFromZip(e,t=`the ZIP archive`){let n=this._mainModelPath(Object.keys(e));if(!n)throw Error(`No supported model files found in ${t}`);if(n.usd)return await this.loadUSDScene(e,t);let{path:r,models:i}=n,a=i.filter(e=>e!==r&&!gL.test(e));return a.length>0&&(console.warn(`${t} holds ${a.length+1} models; loaded "${r}". Others: ${a.join(`, `)}`),this.loader._issues?.record(X.ASSET_AMBIGUOUS_ENTRY,`${t} holds ${a.length+1} models; loaded "${r}"`,{loaded:r,alternatives:a.slice(0,50)},tn.WARNING)),console.log(`Loading model file from ${t}: ${r}`),await this.loadModelFromZipEntry(e[r],r,r.split(`.`).pop().toLowerCase(),e,t)}async loadModelFromZipEntry(e,t,n,r,i=`ZIP`){try{z({isLoading:!0,status:`Processing ${n.toUpperCase()} from ${i}...`,progress:5});let a;switch(n){case`glb`:case`gltf`:a=await this.handleGltfFromZip(n,e,t,r);break;case`obj`:a=await this.handleObjFromZip(e,t,r);break;default:a=await this.loader._loadModelFileByExtension(new File([e],t),t)}return this.loader.dispatchEvent({type:`load`,model:this.loader.targetModel,filename:`${t} (from ${i})`}),a}catch(e){throw console.error(`Error loading ${n} from ${i}:`,e),this.loader.dispatchEvent({type:`error`,message:e.message,filename:t}),e}}async handleGltfFromZip(e,t,n,i){if(e===`gltf`){let e=await EL(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{let t=await jr(()=>new Promise((t,n)=>s.parse(e,``,t,n)));return this.loader._throwDeferred(),this.loader.releaseTargetModel(),this.loader.targetModel=t.scene,this.loader.sceneMetadata=vy(t),await this.loader.onModelLoad(this.loader.targetModel),t}finally{this.loader._disposeGLTFLoader(s)}}else return await this.loader.loadGLBFromArrayBuffer(await OL(t),n)}async handleObjFromZip(e,t,n){let r=await EL(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),SL))]);return clearTimeout(r),i||this.loader._issues?.record(X.TEXTURE_BUILD_FAILED,`MTL textures did not decode within ${SL}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=await EL(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){if(/^(data|blob|https?):/i.test(e))return e;let r=e.replace(/^\.\/|^\//,``),i=r;try{i=decodeURIComponent(r)}catch{}for(let e of new Set([r,i])){let r=e.split(`/`).pop(),i=[DL(t,e),e,r].find(e=>n[e])??(r?Object.keys(n).find(e=>e.endsWith(`/${r}`)):void 0);if(i)return URL.createObjectURL(wL(n[i]))}return console.warn(`Resource not found in the archive: ${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=await this.prepareFixedMtlContent(t),f=new a(c).parse(d,u);await this.preloadMtlTextures(f);let p=new o(c);p.setMaterials(f);let m=await EL(e.content),h=p.parse(m);return this.loader.releaseTargetModel(),this.loader.targetModel=h,await this.loader.onModelLoad(this.loader.targetModel),s.forEach(e=>URL.revokeObjectURL(e)),this.loader.dispatchEvent({type:`load`,model:h,filename:`${e.path} (from ${i})`}),h}async prepareFixedMtlContent(e){return(await EL(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=URL.createObjectURL(wL(i[e]));return a.push(t),t}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=URL.createObjectURL(wL(t[e]));return n.push(r),r}if(r&&r.length>5)for(let e in t){let i=e.split(`/`).pop();if(i.includes(r)||r.includes(i)){let r=URL.createObjectURL(wL(t[e]));return n.push(r),r}}return null}}}));function NL(e){let t=(e/1e3)**2;return .002152*(1.0455996-341.29061/t-.9023085*t)/(1+.0027059889/t-85.968563*t)}function PL(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 FL(e,t){let n=0,r=nR+e*rR;for(let e=0;e<rR;e++)n+=t(r+e+.5);return n/rR}function IL(e){let t=new Float64Array(16);for(let n=0;n<16;n++)t[n]=FL(n,e);return t}function LL(e=1){let t=new Float32Array(48);for(let n=0;n<16;n++){let r=hR[n*3],i=hR[n*3+1],a=hR[n*3+2];for(let o=0;o<3;o++){let s=cR;t[o*16+n]=(s[o*3]*r+s[o*3+1]*i+s[o*3+2]*a)*e}}return t}function RL(e){let t=0,n=0,r=0;for(let i=0;i<16;i++)t+=e[i]*hR[i*3],n+=e[i]*hR[i*3+1],r+=e[i]*hR[i*3+2];return[t,n,r]}function zL([e,t,n]){let r=cR;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 BL(e){return Math.max(0,.0460836582205*e-.04586025928522)}function VL([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(uR,i=>{let a=1-r(470,520,i),o=r(560,610,i);return n*a+e*o+t*(1-a-o)})}function HL({airDensity:e=1,turbidity:t=2,ozone:n=300,groundAlbedo:r=[.3,.3,.3]}={}){let i=BL(t)/QL,a=n*lR/(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]=fR[t]*e,s[t]=mR[t]*i,c[t]=s[t]*$L,l[t]=pR[t]*a;return{rayleigh:o,mieScattering:c,mieExtinction:s,ozone:l,albedo:VL(r)}}function UL(e){let t=Math.max(e,0);return Math.sqrt(t*(2*XL+t))/(XL+t)}function WL(e,t,n=1024){let r=Math.max(e,0),i=XL+r,a=i*t,o=r*(2*XL+r);if(t<0&&a*a>=o)return null;let s=-a+Math.sqrt(a*a+(ZL-i)*(ZL+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))+XL),p=r-t;c+=gR(f)*p,l+=_R(f)*p,u+=vR(f)*p}return[c,l,u]}function GL(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 KL(e){let t=Math.sin(e/2);return 4*Math.PI*t*t}function qL({direction:e,altitude:t,angularDiameter:n,strength:r=1,coefficients:i}){let a=n/2,o=KL(a),s=UL(t),[c,l,u]=e,d=Math.sin(a),f=new Float64Array(16),p=0,m=e=>{if(e<-s)return;let n=GL(i,WL(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]=dR[e]*r/o*f[e]/p;return{radiance:zL(RL(h)).map(e=>Math.max(0,e*iR)),visibleFraction:p/g,solidAngle:o,direction:[c,l,u]}}function JL(e,t=eR){let n=t*t;return 3/(8*Math.PI)*(1-n)/(2+n)*(1+e*e)/(1+n-2*t*e)**1.5}function YL(e,t,n,r,i=8){let a=n*r,o=e*t,s=new Float32Array(2*o*a);return[yR,e=>JL(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 XL,ZL,QL,$L,eR,tR,nR,rR,iR,aR,oR,sR,cR,lR,uR,dR,fR,pR,mR,hR,gR,_R,vR,yR,bR=g((()=>{Dh(),XL=6360,ZL=6420,QL=1.2,$L=.9,eR=.76,tR=1.3,nR=380,rR=25,iR=1/32,aR=[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],oR=[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],sR=[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],cR=[3.2406,-1.5372,-.4986,-.9689,1.8758,.0415,.0557,-.204,1.057],lR=0xe90f62a5dcb760000,uR=Float64Array.from({length:16},(e,t)=>nR+(t+.5)*rR),dR=IL(e=>PL(aR,360,10,e)),fR=IL(e=>NL(e)/8),pR=IL(e=>PL(oR,360,10,e)),mR=IL(e=>(e/1e3)**-tR),hR=(()=>{let e=new Float64Array(48);for(let t=0;t<16;t++)for(let n=0;n<3;n++)e[t*3+n]=FL(t,e=>PL(sR,360,5,e,3,n))*rR;return e})(),gR=e=>Math.exp(-e/8),_R=e=>Math.exp(-e/QL),vR=e=>Math.max(0,1-Math.abs(e-25)/15),yR=e=>3/(16*Math.PI)*(1+e*e)}));function xR(e){return{r:(0,n.exp)(e.mul(-1/8)),m:(0,n.exp)(e.mul(-1/QL)),o:(0,n.max)((0,n.float)(0),(0,n.float)(1).sub((0,n.abs)(e.sub(25)).div(15)))}}function SR(e,t){return WR(n=>e.rayleigh[n].mul(t.r).add(e.mieExtinction[n].mul(t.m)).add(e.ozone[n].mul(t.o)))}function CR(e,t){return WR(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 wR(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 TR(e,t){let r=e.add(XL),i=(0,n.sqrt)((0,n.max)(e.mul(e.add(2*XL)),0)),a=r.mul(t),o=a.negate().add((0,n.sqrt)((0,n.max)(a.mul(a).add(BR*BR).sub(i.mul(i)),0))),s=(0,n.float)(VR).sub(e),c=i.add(BR);return{x:o.sub(s).div((0,n.max)(c.sub(s),1e-6)).mul(255),y:i.div(BR).mul(63),rho:i,r}}function ER(e,t,r,i,a){let o=TR(r,i),s=wR(e,256,64,o.x,o.y).xyz,c=(0,n.smoothstep)(a.negate(),a,i.add(o.rho.div(o.r)));return WR(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 DR(e,t,r,i,a){let o=[[(0,n.clamp)(QR(r,64),0,63),64],[(0,n.clamp)(KR(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/HR),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 OR(e,t){let r=QR(t,128);return WR(t=>(0,n.exp)(wR(e,128,1,r,(0,n.float)(0),4,t)))}function kR(e,t){let r=e.add(XL).toVar(),i=r.mul(t).toVar(),a=e.mul(e.add(2*XL)).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)(ZL).sub(r).mul(r.add(ZL))),0)));return{r,b:i,cGround:a,hitsGround:s,tMax:s.select(c,l).toVar()}}function AR(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(XL)),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 jR(e,t){let r=t*t,i=3/(8*HR)*(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 MR({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(BR).toVar(),s=(0,n.sqrt)(o.mul(o).add(XL*XL)).toVar(),c=(0,n.float)(ZL).sub(s),l=o.add(BR),u=c.add(a.mul(l.sub(c))).toVar(),d=(0,n.clamp)((0,n.float)(BR*BR).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=xR((0,n.max)(f.add(l).div((0,n.sqrt)(s.mul(s).add(l)).add(XL)),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 NR(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(HR/8);return(0,n.vec3)(o.mul((0,n.cos)(s)),a,o.mul((0,n.sin)(s)))}function PR(e,t){let r=QR(t,64);return WR(t=>wR(e,64,1,r,(0,n.float)(0),4,t))}function FR(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),_=ZR(g.mod(64),64).toVar(),v=(0,n.max)(GR(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=WR(()=>(0,n.vec4)(0).toVar()),x=t?WR(()=>(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=NR(h.div(8),h.mod(8),e,i).toVar(),s=(0,n.dot)(r,y).toVar(),p=t?nz(s).toVar():null,m=t?jR(s,f).toVar():null,g=t?null:Array.from({length:8},()=>(0,n.vec4)(0).toVar()),S=kR(v,r.y),C=WR(()=>(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=AR(S,l.add(f.mul(.5)),_,s),v=xR(h.h),y=WR(e=>u.rayleigh[e].mul(v.r)),w=WR(e=>u.mieScattering[e].mul(v.m)),T=CR(SR(u,v),f),E;if(t){let e=ER(o,u,h.h,h.muS,d);E=WR(t=>e[t].mul(y[t].mul(p).add(w[t].mul(m))))}else (0,n.If)(e.mod(2).equal(0),()=>{let e=DR(c,h.h,h.muS,h.mu,tz(s,h.mu,h.muS));for(let t=0;t<8;t++)g[t].assign(e[t])}),E=WR(e=>y[e].mul(g[e]).add(w[e].mul(g[4+e])));for(let e of UR)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(XL),-1,1),r;if(t){let t=ER(o,u,(0,n.float)(0),e,d);r=WR(r=>t[r].mul((0,n.max)(e,0)))}else r=PR(l,e);for(let e of UR)b[e].addAssign(C[e].mul(r[e]).mul(u.albedo[e]).mul(1/HR))})});for(let t of UR)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 IR(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=WR(()=>(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 UR)e[r].addAssign(i.element(p.add((0,n.uint)(t)).mul(4).add(r)))}),m=WR(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=WR(()=>(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 UR)c[e].addAssign(t.element(a.add(e)).mul(o))}});for(let t of UR){let n=e.mul(8).add(i*4+t);r===`first`?(s.element(n).assign(c[t]),o.element(n).assign(ez(c[t]))):r===`middle`?(s.element(n).addAssign(c[t]),o.element(n).assign(ez(c[t]))):o.element(n).assign(ez(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=WR(()=>(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 UR)e[a].addAssign(t.element(p.add((0,n.uint)(r)).mul(4).add(a)).mul(i))});for(let t of UR)c.element(f.mul(4).add(t)).assign(e[t].mul(rz))})})().compute(l,[64])}function LR({transmittance:e,multipleScattering:t,coefficients:r,sunSinRadius:i,mieG:a},o,s,c,l){let u=WR(()=>(0,n.vec4)(0).toVar()),d=WR(()=>(0,n.vec4)(1).toVar()),f=t?Array.from({length:8},()=>(0,n.vec4)(0).toVar()):null,p=nz(c).toVar(),m=jR(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=AR(o,v.add(y.mul(.5)),s,c),x=xR(b.h),S=WR(e=>r.rayleigh[e].mul(x.r)),C=WR(e=>r.mieScattering[e].mul(x.m)),w=ER(e,r,b.h,b.muS,i),T=CR(SR(r,x),y);f&&(0,n.If)(a.mod(iz).equal(0),()=>{let e=DR(t,b.h,b.muS,b.mu,tz(c,b.mu,b.muS));for(let t=0;t<8;t++)f[t].assign(e[t])});for(let e of UR){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 RR(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=ZR(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=WR(()=>(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*HR),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}=LR(e,kR(o,p.y),c,(0,n.dot)(p,l),r);for(let e of UR)u[e].addAssign(m[e])});for(let e of UR)i.element(s.mul(4).add(e)).assign(ez(u[e].mul(HR/a)))})().compute(128,[64])}function zR(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(HR),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)(az(e.mod(256)))).mul((0,n.sqrt)((0,n.max)((0,n.float)(1).sub(_.mul(_)),0))).add(a.mul(_)).toVar(),y=kR(o,a),{L:b,throughput:x}=LR(h,y,_,v,i);(0,n.If)(y.hitsGround,()=>{let e=(0,n.clamp)(y.r.mul(_).add(y.tMax.mul(v)).div(XL),-1,1).toVar(),t=ER(m,l,(0,n.float)(0),e,p),r=OR(c,e);for(let i of UR)b[i].addAssign(x[i].mul(l.albedo[i]).mul(1/HR).mul(t[i].mul((0,n.max)(e,0)).add(r[i])))});let S=WR(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*HR).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(HR)).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 BR,VR,HR,UR,WR,GR,KR,qR,JR,YR,XR,ZR,QR,$R,ez,tz,nz,rz,iz,az,oz=g((()=>{bR(),BR=Math.sqrt(ZL*ZL-XL*XL),VR=ZL-XL,HR=Math.PI,UR=[0,1,2,3],WR=e=>UR.map(e),GR=e=>(0,n.float)(e).div(15).pow(2).mul(VR),KR=e=>(0,n.sqrt)((0,n.clamp)(e.div(VR),0,1)).mul(15),qR=-3*HR/180,JR=15*HR/180,YR=.5+Math.atan((-HR/2-qR)/JR)/HR,XR=.5+Math.atan((HR/2-qR)/JR)/HR,ZR=(e,t)=>(0,n.sin)((0,n.clamp)((0,n.tan)((0,n.float)(e).div(t-1).mul(XR-YR).add(YR-.5).mul(HR)).mul(JR).add(qR),-HR/2,HR/2)),QR=(e,t)=>(0,n.atan)((0,n.asin)((0,n.clamp)(e,-1,1)).sub(qR).div(JR)).div(HR).add(.5-YR).div(XR-YR).mul(t-1),$R=1e-30,ez=e=>(0,n.log)((0,n.max)(e,(0,n.vec4)($R))),tz=(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)),nz=e=>e.mul(e).add(1).mul(3/(16*HR)),rz=4*HR/128,iz=4,az=e=>(0,n.float)(e).div(255).pow(2).mul(HR)}));function sz(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 cz({pixels:e,rows:t,prefix:r,stats:i,cdf:a,width:o,height:s}){let c=lz(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,Bl).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=sz(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=sz(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 lz,uz=g((()=>{xu(),lz=e=>Math.ceil((e+1)*16/256)*64})),dz=_({PhysicalSky:()=>pz});function fz(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 pz,mz=g((()=>{O(),Vd(),oz(),uz(),tr(),bR(),pz=class{constructor(e=1024,t=512,n={}){this.width=e,this.height=t,this._quality=n,this.lastRenderTime=0,this._texture=fz(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=fz(e+1,t,r.RGBAFormat),this._rec709Weights=LL(iR),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(lz(this.width)*this.height,1),phaseCells:new t.StorageInstancedBufferAttribute(YL(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:eR},l=this._quality,u=o(`incomingA`),d=o(`incomingB`);this._kernels={transmittance:MR(c),air:[FR(c,{first:!0,out:u,...l.incoming}),IR(c,{incoming:u,stage:`first`}),FR(c,{first:!1,out:d,...l.incoming}),IR(c,{incoming:d,stage:`middle`}),FR(c,{first:!1,out:u,...l.incoming}),IR(c,{incoming:u,stage:`last`}),RR(c,l.irradiance)],sky:zR(c,{width:this.width,height:this.height,...l.sky}),cdf:cz({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,dR)}_setColorWeights(){let e=this._rec709Weights,t=Yn(),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:lz(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=HL(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=qL({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=UL(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:lz(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??{}))Au(e,t);this._kernels=null,this._attrs=null,this._texture.dispose(),this._cdfTexture.dispose()}}}));lt(),Ae(),F(),an(),Ov();var hz=ve(`engine`),gz=class extends Qy{constructor(e,t={}){super(e,t),this.setColorManagement(ck),this.setStorageOpener(Kk),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 Fw}_createCamera(){return this.cameraManager=new ES(this.canvas),this.timeline=new MS({cameraManager:this.cameraManager,onReset:()=>this.reset()}),this.cameraManager.camera}_initAssetPipeline(){super._initAssetPipeline(),this.assetLoader.controls=this.cameraManager.controls,this.assetLoader.registerFormat(...Qw),this.assetLoader.setArchiveImporterLoader(()=>Promise.resolve().then(()=>(ML(),xL)).then(e=>new e.ArchiveImporter(this.assetLoader)),wv);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 cb(e,{pathTracer:t.pathTracer}),t.motionVector=new lb(e,this.camera,{pathTracer:t.pathTracer}),t.nrd=new tx(e,{enabled:!1,pathTracer:t.pathTracer}),t.autoExposure=new kx(e,{enabled:nx.autoExposure}),t.localExposure=new Qx(e,{enabled:Ax.localExposure}),[t.normalDepth,t.motionVector,t.nrd,t.autoExposure,t.localExposure]}_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(()=>(mz(),dz)).then(e=>e.PhysicalSky)),this.stages.pathTracer.registerIntegrator([`bidirectional`,`vcm`],e=>new kE(e)),this.stages.pathTracer.requestOutput(`gBuffer`),this.interactionManager=new rS({scene:this.meshScene,camera:this.camera,canvas:this.canvas,assetLoader:this.assetLoader,pathTracer:null,floorPlane:this.assetLoader.floorPlane,isGeometryOnDisk:()=>this.geometryOnDisk}),this.interactionManager.wireAppEvents(this),this.cameraManager.setInteractionManager(this.interactionManager),this.goboManager=new NS(this.stages.pathTracer,{onReset:()=>this.reset(),issues:this._issues}),this.iesManager=new GS(this.stages.pathTracer,{onReset:()=>this.reset(),issues:this._issues}),this._setupDenoisingManager(),this._headless||(await this._setupOverlayManager(),this.transformManager=new Rw({camera:this.camera,canvas:this.canvas,orbitControls:this.cameraManager.controls,app:this}),this.overlayManager.register(`transform`,new zw(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,N.CAMERA_SWITCHED,e=>this.dispatchEvent(e)),this._addTrackedListener(this.cameraManager,N.AUTO_FOCUS_UPDATED,e=>this.dispatchEvent(e)),this._addTrackedListener(this.cameraManager,N.ORTHO_HEIGHT_UPDATED,e=>this.dispatchEvent(e)),this._addTrackedListener(this.timeline,N.TIMELINE_CHANGED,e=>this.dispatchEvent(e)),this._forwardEvents(this.denoisingManager,[N.DENOISING_START,N.DENOISING_END,N.DENOISER_LOADING,N.UPSCALING_START,N.UPSCALING_PROGRESS,N.UPSCALING_END,N.RESOLUTION_CHANGED]),this._setupAutoExposureListener(),this.animationManager.wakeCallback=()=>this.wake(),this.animationManager.applyPoseCallback=e=>this._applyAnimationPose(e),this._forwardEvents(this.animationManager,[N.ANIMATION_STARTED,N.ANIMATION_PAUSED,N.ANIMATION_STOPPED]),this._addTrackedListener(this.animationManager,N.ANIMATION_PAUSED,()=>{this._animRefitInFlight=!1,this._refreshMovedEmitters()}),this._addTrackedListener(this.animationManager,N.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`,`nrd:output`]}_settingsBindings(){let e=super._settingsBindings();return{...e,applyExposure:t=>{this.stages.autoExposure?this.stages.autoExposure.setCompensation(t):e.applyExposure(t),this.stages.compositor?.setBackdropExposure(t)},onCameraProjection:e=>{this.cameraManager.applyProjection(e),e===`equirectangular`&&this.denoisingManager?.requiresMotionVectors?this.denoisingManager.setDenoiserStrategy(`oidn`):this.denoisingManager?._syncGBufferStages?.()}}}_beginFrame(){if(this.timeline.update(),this.cameraManager.updateControls(),this._updateExposure(),this._applyPendingRenderScale(),this.animationManager?.isPlaying&&!this._animRefitInFlight){let e=this.animationManager.update();e&&(this._animRefitInFlight=!0,this.refitBVH(e).catch(e=>hz.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.stages.autoExposure?.enabled&&this._refreshFinished(),this.denoisingManager.onRenderComplete({isStillComplete:()=>this.completion.renderCompleteDispatched,context:this.pipeline?.context})}_settling(){return!!this.stages.autoExposure?.settling}_displayGain(){let e=this.stages.localExposure;e?.wantsBuild&&e.build(this.pipeline.context);let t=e?.toneGain()??null;if(this.pipeline?.context.getState(`pathtracer:backdrop`)!==`color`)return t;let{toneMappingExposure:n,toneMapping:r}=this.renderer;return{...t,backdrop:Ts(this.settings.get(`exposure`)??1,n,r)}}setLocalExposure(e){let t=this.stages.localExposure;t&&(t.setEnabled(e),this.stages.compositor.setDisplayGain(e?(e,n)=>t.gainNode(e,n):null),this.refreshFrame())}setLocalExposureParams(e){this.stages.localExposure?.updateParameters(e)}_finishImage(){let e=this.stages.autoExposure;return e?.enabled?e.meter(this.pipeline.context).then(()=>e.advance(1/0)):null}getProvenance(){let e=super.getProvenance(),t=this.stages.autoExposure,n=this.stages.localExposure;return e.exposure={auto:t?.enabled?{exposure:t.getExposure(),strength:t.strength,metering:t.metering,keyValue:t.keyValue}:null,local:n?.enabled?{highlightContrast:n.highlightContrast,shadowContrast:n.shadowContrast,detailStrength:n.detailStrength}:null},e}_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?.setEnabled(!1),this.denoisingManager?.setContinuousDenoise(!1);return}t.autoFocusMode!==void 0&&this.cameraManager?.setAutoFocusMode(t.autoFocusMode),t.autoExposure!==void 0&&this.stages.autoExposure?.setEnabled(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 qw(this)}async importSceneState(e,t){return await Zw(this,e,t)}_dispatchCamerasUpdated(){this.dispatchEvent({type:N.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.takeMoveRanges()),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.matrixWorldOf(r))}}_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?st:ct;this.denoisingManager?.setCadenceSuspended(n),this.timeline.stop(),this.cameraManager.controls.enabled=!n,this.stages.autoExposure&&(this.stages.autoExposure.holdSamples=n?8:0),this.settings.setMany(it(r),{silent:!0,source:Av.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(X.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:N.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:N.ANIMATION_FINISHED})}}this.transformManager?.setMeshData(this._sdf.meshes)}_setupDenoisingManager(){this.denoisingManager=new ww({renderer:this.renderer,mainCanvas:this.canvas,stages:{pathTracer:this.stages.pathTracer,normalDepth:this.stages.normalDepth,motionVector:this.stages.motionVector,nrd:this.stages.nrd,autoExposure:this.stages.autoExposure,compositor:this.stages.compositor},pipeline:this.pipeline,getExposure:()=>this.settings.get(`exposure`)??1,getSaturation:()=>this.settings.get(`saturation`)??1,getDisplayGain:()=>this._displayGain(),getPictureCanvas:()=>this._pictureCanvas(),getColorSpace:()=>this.color?.canvasColorSpace??`srgb`,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(){let e=this.stages.autoExposure;e&&(e.setCompensation(this.settings.get(`exposure`)??1),this.stages.compositor.setBackdropExposure(this.settings.get(`exposure`)??1),this.stages.localExposure&&(this.stages.localExposure.onChange=()=>this._refreshFinished()),e.onChange=()=>this._refreshFinished(),this._addTrackedListener(this.cameraManager,N.CAMERA_SWITCHED,()=>e.resetHistory()),e.on(`autoexposure:updated`,({exposure:e,autoExposure:t,targetExposure:n,luminance:r})=>{this.dispatchEvent({type:N.AUTO_EXPOSURE_UPDATED,exposure:e,autoExposure:t,targetExposure:n,luminance:r})}))}_refreshFinished(){this.completion.renderCompleteDispatched&&(this._needsDisplayRefresh=!0,this.wake())}_updateExposure(){let e=this.stages.localExposure;e?.wantsBuild&&this.completion.renderCompleteDispatched&&e.build(this.pipeline.context);let t=this.stages.autoExposure;if(!t?.enabled)return;this._noteExposureView();let n=this.cameraManager.afScreenPoint;t.metering===`spot`&&(t.meteringPoint.x!==n.x||t.meteringPoint.y!==n.y)&&t.updateParameters({meteringPoint:n}),t.wantsMetering&&this.completion.renderCompleteDispatched&&t.meter(this.pipeline.context),t.update()&&(this._needsDisplayRefresh=!0)}_noteExposureView(){let{matrixWorld:e,projectionMatrix:t}=this.camera,n=this._exposureView;n?.view.equals(e)&&n.projection.equals(t)||(this._exposureView={view:e.clone(),projection:t.clone()},n&&this.stages.autoExposure?.noteViewChanged())}async _setupOverlayManager(){this.overlayManager=new Nw(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 _z(e){let t=await yz(e);try{return await vz(t,e)}finally{t.dispose()}}async function vz(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 yz({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 gz(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}}Sv(),yn(),F(),lt(),de();function bz(e){let t=new OffscreenCanvas(e.width,e.height);return t.getContext(`2d`).drawImage(e,0,0),t}var xz=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=st.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`);let _=d.stages.autoExposure?.enabled?d.stages.autoExposure:null;_&&(_.instant=!1),d.settings.setMany({maxSamples:i,renderLimitMode:`frames`},{silent:!0,reset:!1}),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(),_&&d._noteExposureView(),await this._accumulateFrame(d),this._cancelled||(_&&(await _.meter(d.pipeline.context),_.advance(e===Math.max(0,s)?1/0:h),d._presentDisplay()),a&&d.denoisingManager?.finalDenoise&&await this._waitForDenoise(d),this._cancelled))break;let u=d.getCanvas();if(u&&c){let t=await createImageBitmap(d.color?.canvasColorSpace===`display-p3`?bz(u):u);await c(t,e,m),t.close()}let p={frame:e+1,totalFrames:m,percent:(e+1)/m*100};l?.(p),d.dispatchEvent({type:N.VIDEO_RENDER_PROGRESS,...p})}}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:N.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&&(ue({samples:L(t)}),await new Promise(e=>setTimeout(e,0)))}}_waitForDenoise(e){return new Promise(t=>{let n,r=()=>{e.removeEventListener(N.DENOISING_END,i),clearTimeout(n)},i=()=>{r(),t()};n=setTimeout(()=>{console.warn(`VideoRenderManager: Denoise timed out, skipping`),r(),t()},3e4),e.addEventListener(N.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(it(st)),`renderLimitMode`];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,instantExposure:t.stages.autoExposure?.instant,holdExposureSamples:t.stages.autoExposure?.holdSamples,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,t.stages.autoExposure&&(t.stages.autoExposure.instant=e.instantExposure??!1,t.stages.autoExposure.holdSamples=e.holdExposureSamples??0),e.view&&t.cameraManager.applyPose(e.view),t.denoisingManager?.setCadenceSuspended(!1),t.animationManager?.stop(),t.reset(),t.wake()}};O(),F(),an(),ui(),Fr(),IA(),Ov(),wc(),qn(),xy(),Ae(),lt(),Ft(),Do(),QC(),fw(),vs(),e.ARCHIVE_FORMATS=wv,e.AUTO_EXPOSURE_DEFAULTS=nx,e.AUTO_FOCUS_DEFAULTS=bS,e.AnimationManager=Fw,e.BVH_LEAF_MARKERS=Tt,e.CameraManager=ES,e.CameraTrack=AS,e.ColorManagement=ck,e.DEFAULT_LUT_SIZE=iO,e.DEFAULT_MAX_EV=rO,e.DEFAULT_MIN_EV=nO,e.DEFAULT_SUN_PATH=xi,e.DEFAULT_VIEW=_s,e.DEFAULT_WORKING_SPACE=Zr,e.DENOISER_DEFAULTS=sb,e.DENOISER_STRATEGIES=tb,e.DOWNLOAD_POLICY=Z_,e.DenoisingManager=ww,e.DownloadCache=av,e.ENGINE_AREAS=mn,e.ENGINE_DEFAULTS=H,e.EngineEvents=N,e.EngineIssueError=nn,e.GoboManager=NS,e.IESManager=GS,e.INTERACTIVE_RENDER_CONFIG=ct,e.ISSUE_CODES=X,e.ISSUE_SEVERITY=tn,e.InteractionManager=rS,e.IssueLog=rn,e.LEGACY_EVENT_NAMES=P,e.LOCAL_EXPOSURE_DEFAULTS=Ax,e.LOG_LEVELS=xe,e.LightManager=zy,e.Logger=Oe,e.MATERIAL_DEFAULTS=ot,e.MATERIAL_VALUE_SOURCE=Un,e.MAX_RESERVABLE_RENDER_SIZE=je,e.MAX_SCENE_BYTES=bo,e.MAX_TABLE_TRANSFORMS=us,e.MemoryLedger=Eo,e.NRD_DEFAULTS=ib,e.NRD_HIT_DIST_A=nb,e.NRD_HIT_DIST_B=rb,e.NRD_PRESET_KEYS=ab,e.NRD_QUALITY_PRESETS=ob,e.OCIO_VIEW_BASE=ls,e.OverlayManager=Nw,e.PRODUCTION_RENDER_CONFIG=st,e.PathTracerApp=gz,e.PipelineContext=F_,e.RETOUCH_DEFAULTS=rw,e.RETOUCH_MAX_PIXELS=aw,e.RETOUCH_RANGES=ow,e.RayzeeRenderer=Qy,e.RenderPipeline=q_,e.RenderSettings=jv,e.RenderStage=j,e.SAFE_SCENE_BYTES=yo,e.SCENE_STATE_VERSION=Bw,e.SETTING_SOURCE=Av,e.SKY_DEFAULTS=Ci,e.SR_MAX_INPUT=qC,e.SR_SCALE=GC,e.STORAGE_KIND=pn,e.StageExecutionMode=A,e.StorageManager=Ik,e.TRIANGLE_DATA_LAYOUT=K,e.TimelineManager=MS,e.TransformManager=Rw,e.VERSION=Cc,e.VIEW_TRANSFORMS=hs,e.VRAMTracker=ef,e.VideoRenderManager=xz,e.acquireLock=hk,e.addAllOcioViews=AO,e.addOcioView=kO,e.addViewTransform=rs,e.applyMatrixRGBA8=BD,e.bakeLut=qD,e.bufferBytes=Qd,e.buildCanvasView=EO,e.buildOcioView=yO,e.buildToneMapWGSL=ss,e.cachedObjectURL=cv,e.canvasColorSpaceFor=tk,e.captureHeadless=vz,e.clearBindingAuditFindings=H_,e.clearInputOverrides=GO,e.configureAssets=ai,e.configurePlatform=Er,e.convertColor=DD,e.convertEncodedRGBA8=FD,e.convertPixelsF32=OD,e.createLogger=ve,e.dayOfYearForMonth=Xr,e.deriveAlphaMode=jn,e.describeAdapter=Zy,e.displayCanvasFit=AE,e.estimateSceneBytes=lo,e.extractMatrix=VD,e.extractSceneMetadata=vy,e.fetchFile=ov,e.fileIdentity=pv,e.findNativeLinearSpace=sk,e.fmt=V,e.folderIdentity=mv,e.fromPortable=rr,e.getActiveColorManagement=$r,e.getAssetConfig=si,e.getBindingAuditFindings=V_,e.getPlatform=Dr,e.getRegistryVersion=Zo,e.getViewTransform=$o,e.hasColorSpace=UD,e.hdrViewFor=qE,e.heldLockNames=gk,e.identityKey=hv,e.isColorManaged=lk,e.isDataSpace=HD,e.isDataTexture=ZO,e.isHdrDisplay=PE,e.linearToSrgb=jD,e.listFileRules=JO,e.listInputOverrides=KO,e.listViewTransforms=es,e.localFolder=Cv,e.makeCpuSampler=$D,e.matchingView=KE,e.measureBakeError=tO,e.nameFromUrl=tv,e.onRegistryChange=Qo,e.openHeadless=yz,e.openStorage=Gk,e.openZip=OA,e.parseSceneMetadata=_y,e.probeAddressSpace=fo,e.readZipDirectory=TA,e.removeViewTransform=is,e.renderHeadless=_z,e.renderUpscaled=HC,e.resolveInputSpace=XO,e.sameIdentity=gv,e.sameToneMapping=HE,e.setActiveColorManagement=ei,e.setBindingAudit=B_,e.setInputOverride=WO,e.srgbToLinear=AD,e.sunPosition=Jr,e.textureBytes=$d,e.textureInputSpace=ek,e.timeForSunElevation=Yr,e.toPortable=nr});
|