rayzee 11.4.0 → 11.5.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-Cgyx5AF7.js → ArchiveImporter-29Nl1567.js} +2 -2
- package/dist/{BidirectionalIntegrator-BKF-cwH2.js → BidirectionalIntegrator-CJay8tXK.js} +2 -2
- package/dist/{NeuralRetouch-C3Q2XqbF.js → NeuralRetouch-KqGVPV7u.js} +2 -2
- package/dist/{NeuralSuperRes-DV5TtURP.js → NeuralSuperRes-BHxhYzlD.js} +2 -2
- package/dist/{PathTracer-D3MvEaZK.js → PathTracer-Cldt0mXi.js} +1 -1
- package/dist/{PhysicalSky-CY4jiz6a.js → PhysicalSky-CUWrTcmT.js} +1 -1
- package/dist/{RayzeeRenderer-D23m6NqG.js → RayzeeRenderer-Dd-Dit0v.js} +3 -3
- package/dist/{ToneMapGPU-CTDBvmmS.js → ToneMapGPU-sAs8wdgI.js} +14 -1
- package/dist/addons/archives.es.js +1 -1
- package/dist/addons/bidirectional.es.js +1 -1
- package/dist/addons/physical-sky.es.js +1 -1
- package/dist/rayzee-core.es.js +3 -3
- package/dist/rayzee.es.js +102 -61
- package/dist/rayzee.umd.js +5 -5
- package/dist/{sceneCachePolicy-AKOEu2lf.js → sceneCachePolicy--ta6moJu.js} +1 -1
- package/package.json +1 -1
- package/src/Passes/AIUpscaler.js +15 -12
- package/src/Processor/ToneMapGPU.js +22 -3
- package/src/Stages/LocalExposure.js +25 -2
- package/src/managers/DenoisingManager.js +82 -19
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 rs(){os.length=0,os.push(...Uo),ss.clear();for(let e of os)ss.set(e.id,e);Go()}var is,as,os,ss,cs,ls,us,ds,fs,ps=g((()=>{Wo(),is=200,as=12,os=[...Uo],ss=new Map(os.map(e=>[e.id,e])),cs=1,ls=new Set,us=ss,ds=r.NoToneMapping,fs=r.AgXToneMapping}));ps();var ms=e=>(t,n,r,i,a)=>e(t>0?t:0,n>0?n:0,r>0?r:0,i,a),hs=new Map;function gs(){hs.clear();for(let e of us.values())hs.set(e.id,ms(e.cpu))}gs(),qo(gs);function _s(e){return Jo(e)?.outputEncoded===!0}function vs(e){return e<=.0031308?12.92*e:1.055*e**(1/2.4)-.055}function ys(e,t){let n=Jo(t);return n?n.appliesExposure?e:1:t===r.NoToneMapping?1:e}var bs=.2126,xs=.7152,Ss=.0722;function Cs(e,t){if(t===1)return;let n=e[0]*bs+e[1]*xs+e[2]*Ss;e[0]=n+(e[0]-n)*t,e[1]=n+(e[1]-n)*t,e[2]=n+(e[2]-n)*t}function ws(e,{exposure:t,toneMapping:n,saturation:i=1,preserveAlpha:a=!1,pixelGain:o=null}){let s=hs.get(n)??hs.get(r.NoToneMapping),c=ys(t,n),l=_s(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=t>>2,i=r%o.width,a=(r-i)/o.width,s=e[t]*.2126+e[t+1]*.7152+e[t+2]*.0722;n*=o.fn((i+.5)/o.width,(a+.5)/o.height,s,f)}d[0]=e[t]*n,d[1]=e[t+1]*n,d[2]=e[t+2]*n,Cs(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]=vs(d[0])*255+.5,u[t+1]=vs(d[1])*255+.5,u[t+2]=vs(d[2])*255+.5),u[t+3]=a?e[t+3]*255+.5:255}return u}Pt(),$t(),rn(),Oe(),Ar();var Ts=_e(`textures`),Es={MAX_BUFFER_MEMORY:1024*1024*1024,MAX_TEXTURE_MEMORY:2048*1024*1024,CLEANUP_THRESHOLD:.8,STREAM_BATCH_SIZE:4},Ds=8*2**20,Os=16,ks=4,As=8192*8192,js={busy:0,waiting:[]};async function Ms(){return js.busy<Math.max(1,Cr()-1)?js.busy++:await new Promise(e=>js.waiting.push(e)),()=>{let e=js.waiting.shift();e?e():js.busy--}}var Ns={toSRGB:null,toLinear:null};function Ps(e){if(!Ns[e]){let t=new Uint8Array(256);for(let n=0;n<256;n++){let r=n/255,i=e===`toSRGB`?vs(r):r<=.04045?r/12.92:((r+.055)/1.055)**2.4;t[n]=Math.max(0,Math.min(255,Math.round(i*255)))}Ns[e]=t}return Ns[e]}var Fs=class{constructor(){this.canvasContextPairs=[],this.maxPoolSize=Zt.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=[]}},Is=class{constructor(e={}){this.pools=new Map,this.memoryUsage=0,this.maxMemoryUsage=e.maxMemory||Es.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*Es.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<Zt.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`}},Ls=class{constructor(e=Zt.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=[]}},Rs=class{constructor(e={}){this.useWorkers=typeof Worker<`u`,this.maxConcurrentWorkers=Zt.MAX_CONCURRENT_WORKERS,this.activeWorkers=0,this._issues=e.issues??null,this.maxTextureSize=this._clampTextureSize(e.maxTextureSize??Zt.DEFAULT_MAX_TEXTURE_SIZE),this.canvasPool=new Fs,this.bufferPool=new Is({maxMemory:e.maxBufferMemory||Es.MAX_BUFFER_MEMORY,sizeStrategy:e.bufferSizeStrategy||`adaptive`}),this.textureCache=new Ls,this.capabilities=this.detectCapabilities(),this.optimalMethod=this.selectOptimalMethod()}_reportTextureFailure(e,t){if(t instanceof tn)throw t;this._issues?.record(Z.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(Z.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)||Zt.DEFAULT_MAX_TEXTURE_SIZE);return Math.max(Zt.MIN_TEXTURE_WIDTH,Math.min(t,Zt.MAX_TEXTURE_SIZE))}setMaxTextureSize(e){let t=this._clampTextureSize(e);return t===this.maxTextureSize?t:(this.maxTextureSize=t,this.textureCache?.dispose(),this.textureCache=new Ls,this.maxTextureSize)}detectCapabilities(){return{offscreenCanvas:typeof OffscreenCanvas<`u`,imageBitmap:typeof createImageBitmap<`u`,workers:typeof Worker<`u`,hardwareConcurrency:Cr()}}selectOptimalMethod(){return this.capabilities.workers&&this.capabilities.offscreenCanvas?`worker-offscreen`:this.capabilities.imageBitmap?`imageBitmap`:`canvas`}_applyColorManagement(e,t,n,i=new Set){let a=Jr();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){Ts.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(Z.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(Z.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,Ts.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=Ps(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?Ts.info(`re-encoded ${l.length}/${o.length} linear-declared colour map(s) to sRGB so the GPU decode round-trips: ${u}`):Ts.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=Jr()?.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 tn)throw n;this._issues?.warn(Z.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>Es.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 To;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)<As)return 0;let t=this.maxConcurrentWorkers-this.activeWorkers;return Math.max(0,Math.min(e.length,ks,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=Dr(To);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=Dr(To);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>=Es.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>Os&&(await new Promise(e=>setTimeout(e,0)),l=performance.now())}return a.postMessage({stream:`end`}),this.createDataArrayTextureFromResult(await c)}finally{a.terminate(),this.activeWorkers--}}async prepareTexturesForWorkerDirect(e){let t=[],n=()=>({data:new Uint8ClampedArray([255,255,255,255]).buffer,width:1,height:1,isImageData:!0});for(let r=0;r<e.length;r++){let i=e[r];if(!i?.image){this._reportTextureLayer(r,`no image`),t.push(n());continue}let a=i.flipY!==!1;try{let e=i.image;if(typeof createImageBitmap<`u`&&(typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement||typeof ImageBitmap<`u`&&e instanceof ImageBitmap||typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement||typeof OffscreenCanvas<`u`&&e instanceof OffscreenCanvas)){let e=await createImageBitmap(i.image,{imageOrientation:a?`flipY`:`none`});t.push({bitmap:e,width:i.image.width,height:i.image.height,isDirect:!0})}else{let e=i.image.width,n=i.image.height,r=await createImageBitmap(i.image,{imageOrientation:a?`flipY`:`none`}),o=this.canvasPool.getCanvasWithContext(e,n);o.context.drawImage(r,0,0),r.close();let s=o.context.getImageData(0,0,e,n);t.push({data:s.data.buffer,width:e,height:n,isImageData:!0}),this.canvasPool.releaseCanvasWithContext(o)}}catch(e){this._reportTextureLayer(r,e),t.push(n())}}return t}async processOnCPU(e){let t=e.map((e,t)=>{let n=e?.image,r=e?.isCompressedTexture?e.mipmaps?.[0]:n,i=r?.data;return i&&r.width>0&&r.height>0&&i.byteLength>=r.width*r.height*4?{data:new Uint8Array(i.buffer,i.byteOffset,r.width*r.height*4),width:r.width,height:r.height,flipY:e.flipY!==!1}:(this._reportTextureLayer(t,n?`not decoded to pixels, and there is no browser to decode it`:`no image`),{data:new Uint8Array([255,255,255,255]),width:1,height:1,flipY:!1})}),{maxWidth:n,maxHeight:r}=this.calculateOptimalDimensions(t.map(e=>({image:e}))),i=n*r*4,a=Tr()&&i*t.length>=Ds?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)=>ko(e,o,t*i,n,r)),this.createDataArrayTextureFromBuffer(o,n,r,t.length)}async _packInWorker(e,t,n){let r=await Ms(),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=Dr(Oo),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(Z.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%Es.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=J.FLOATS_PER_MATERIAL,n=new Float32Array(e.length*t);for(let r=0;r<e.length;r++)Vt(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=Zt.VEC4_PER_BVH_NODE*Zt.FLOATS_PER_VEC4;vt(t.length,`BVH node count`);let i=t.length*r,a=new Float32Array(i),o=_t(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]=wt.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 Ls;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:Ht(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:zs(e.data,e.width,e.height)});continue}if(n.isCompressedTexture){console.warn(`[TextureCreator] GPU-compressed texture in mixed group — using placeholder`),t.push(null);continue}if(n.image.data&&!(typeof HTMLImageElement<`u`&&n.image instanceof HTMLImageElement)&&!(typeof HTMLCanvasElement<`u`&&n.image instanceof HTMLCanvasElement)&&!(typeof ImageBitmap<`u`&&n.image instanceof ImageBitmap)){let e=t.length;t.push(null),i.push({index:e,flipY:n.flipY,promise:zs(n.image.data,n.image.width,n.image.height)});continue}t.push(n)}if(i.length>0){let e=await Promise.allSettled(i.map(e=>e.promise));for(let r=0;r<i.length;r++){let{index:a,flipY:o}=i[r],s=e[r];if(s.status===`fulfilled`){let e=s.value;n.push(e),t[a]={image:e,flipY:o}}else this._reportTextureLayer(a,s.reason)}}for(let e=0;e<t.length;e++)if(t[e]===null){let r=new Uint8ClampedArray([255,255,255,255]),i=await createImageBitmap(new ImageData(r,1,1));n.push(i),t[e]={image:i,flipY:!1}}return{normalized:t,bitmapsToClose:n}}createFallbackTexture(){let e=new r.DataArrayTexture(new Uint8Array([255,255,255,255]),1,1,1);return e.minFilter=r.LinearFilter,e.magFilter=r.LinearFilter,e.format=r.RGBAFormat,e.type=r.UnsignedByteType,e.needsUpdate=!0,e.generateMipmaps=!1,e}dispose(){this.canvasPool.dispose(),this.bufferPool.dispose(),this.textureCache.dispose()}};function zs(e,t,n){let r=new Uint8ClampedArray(e.buffer,e.byteOffset,e.byteLength);return createImageBitmap(new ImageData(r,t,n))}var Bs=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=Hs(E,Vs(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=Hs(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 Vs(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 Hs(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)}}Pt(),Oe(),er();var Us=Object.freeze({r:0,g:0,b:0});function Ws(e){if(!e)return Us;if(!Jn())return e;let t=[e.r,e.g,e.b];return Xn(t),{r:t[0],g:t[1],b:t[2]}}var Gs=_e(`emissive`),Ks=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=q.FLOATS_PER_TRIANGLE,a=q.MATERIAL_FLAGS_OFFSET,o=q.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]&yt,h=n[p+o],g=t[m];if(!g)continue;let _=d.get(g);_===void 0&&(_=Ws(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),R=(O-T)*(M-E)-(k-E)*(j-T),ee=Math.sqrt(I*I+L*L+R*R)||1,z=g.side===1?-1:1;I=I/ee*z,L=L/ee*z,R=R/ee*z;let te=g.side===2,ne=(T+O+j)/3,re=(E+k+M)/3,ie=(D+A+N)/3,ae=Math.min(T,O,j),oe=Math.min(E,k,M),se=Math.min(D,A,N),ce=Math.max(T,O,j),B=Math.max(E,k,M),le=Math.max(D,A,N);this.emissiveTriangles.push({triangleIndex:e,materialIndex:m,meshIndex:h,sideSign:z,instanceLeaf:n?r.tlasLeafIndex[t]:-1,power:F,area:P,emissive:{r:_.r,g:_.g,b:_.b},emissiveIntensity:v,cx:ne,cy:re,cz:ie,bMinX:ae,bMinY:oe,bMinZ:se,bMaxX:ce,bMaxY:B,bMaxZ:le,nx:I,ny:L,nz:R,twoSided:te}),this.totalEmissivePower+=F}}return this.emissiveCount=this.emissiveTriangles.length,this.emissiveCount>0&&Gs.debug(`${U.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=q.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,Gs.debug(`emissive texture ${U.px(t,n)} · ${U.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 Gs.debug(`emissive raw data ${U.n(this.emissiveCount)} entries (${U.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=Ws(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 Bs().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,Gs.debug(`rebuilt sorted emissive data · ${U.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}};Oe();var qs=class{constructor(e=`Build`,{namespace:t=`build`,level:n=`debug`}={}){this.label=e,this.level=n,this.logger=_e(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=U.list([this.label,...e,U.ms(t)]);return this.level===`info`?this.logger.summary(r,n):this.logger.debug(U.list([r,n.join(` · `)])),{steps:Object.fromEntries(this.order.map(e=>[e,Math.round(this.entries.get(e)?.duration??0)])),total:Math.round(t)}}};mn();var Js=1<<20,Ys=1<<21,Xs=()=>new Promise(e=>setTimeout(e,0)),Zs=[0,1,2,4,5,6,8,9,10];function Qs(e,t,n,r=Zs){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 $s(e,t){let n=[],r=0;for(let{triOffset:i,triCount:a}of t)n.push(Qs(e,i,a)),r+=a,r>=Ys&&(r=0,await Xs());return n}async function ec(e,t){let n=await e?.area(pn.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 tc(e,t,{index:n,bvh:r,orders:i,isStale:a,label:o=``}){let s=e?.area(pn.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,Js),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+=Js*4)await u.write(`order.u32`,e.subarray(t,Math.min(e.length,t+Js*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 nc(e,t,n,r){for(let i=0;i<r;i+=Js){let a=Math.min(Js,r-i),o=await e.slice(i*64,(i+a)*64).arrayBuffer();t.setRecords(n+i,new Float32Array(o))}}async function rc(e,t,n){return new Uint32Array(await e.slice(t*4,(t+n)*4).arrayBuffer())}Pt();var ic=16,ac=q.POSITION_A_OFFSET,oc=q.POSITION_B_OFFSET,sc=q.POSITION_C_OFFSET;async function cc(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+ac]+o[n+oc]+o[n+sc],c[r]=o[n+ac+1]+o[n+oc+1]+o[n+sc+1],l[r]=o[n+ac+2]+o[n+oc+2]+o[n+sc+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 uc(u,o,lc(o,e,t),e,t,n),{left:f(e,n),right:f(n,t)}},p=f(0,n);return await i?.(),await dc(e,t,n,u,i),{order:u,pieces:d,tree:p}}function lc(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 uc(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 dc(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 fc(e,t,n,r){let i=t.length-1,a=[],o=i;for(let{bvhData:e}of n)a.push(o),o+=e.length/ic;let s=new Float32Array(i*ic),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];Ri(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*ic;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 pc,mc=g((()=>{pc=`11.4.0`})),hc,gc=g((()=>{mc(),hc=pc}));function _c(e,t,n=vc){return e>=n&&t/yc<e/3}var vc,yc,bc=g((()=>{vc=1e4,yc=15e5}));gc(),bc();var xc="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})}};",Sc=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,xc],{type:`text/javascript;charset=utf-8`});function Cc(e){let t;try{if(t=Sc&&(self.URL||self.webkitURL).createObjectURL(Sc),!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(xc),{type:`module`,name:e?.name})}}var wc="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})}};",Tc=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,wc],{type:`text/javascript;charset=utf-8`});function Ec(e){let t;try{if(t=Tc&&(self.URL||self.webkitURL).createObjectURL(Tc),!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(wc),{type:`module`,name:e?.name})}}dn(),Kn(),Oe(),Pt(),$t(),rn(),$r(),vn(),Dn(),ai(),Ar();var Dc=5e4,Oc=2e5,kc=2e6,Ac=1<<19,jc=4e7,Mc=1e6,Nc=1024**3,Pc=1024**3,Fc=32*1024*1024,Ic=64*1024*1024,Lc=256*1024*1024,Rc=_e(`scene`),zc=e=>Array.isArray(e)?e:[e],Bc=e=>zc(e).reduce((e,t)=>e+t.byteLength,0),Vc=64*1024*1024;async function Hc(e,t,n){for(let r of zc(n))await e.writeAt(t,r),t+=r.byteLength}function Uc(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 Wc=1024,Gc=64;function Kc(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<=Wc){i=t[e];continue}n.push({offset:r*16,count:(i-r+1)*16}),r=i=t[e]}return n.length>Gc?[{offset:t[0]*16,count:(t.at(-1)-t[0]+1)*16}]:n}var qc=class{constructor(e={}){this.config={useWorkers:!0,bvhDepth:30,maxLeafSize:4,verbose:!1,useFloat32Array:!0,textureQuality:`adaptive`,maxTextureSize:Zt.DEFAULT_MAX_TEXTURE_SIZE,enableTextureCache:!0,maxConcurrentTextureTasks:Math.min(Cr(),6),maxSceneBytes:ho,sceneCache:!0,sceneCacheMinBuildMs:vc,...e},this.triangleData=null,this.triangleFloats=null,this.triangleCount=0,this.materials=[],this.maps=[],this.normalMaps=[],this.bumpMaps=[],this.roughnessMaps=[],this.metalnessMaps=[],this.emissiveMaps=[],this.displacementMaps=[],this.anisotropyMaps=[],this.transmissionMaps=[],this.clearcoatMaps=[],this.clearcoatRoughnessMaps=[],this.sheenColorMaps=[],this.sheenRoughnessMaps=[],this.iridescenceMaps=[],this.iridescenceThicknessMaps=[],this.specularIntensityMaps=[],this.specularColorMaps=[],this.diffuseTransmissionMaps=[],this.diffuseTransmissionColorMaps=[],this.directionalLights=[],this.cameras=[],this.spheres=[],this.bvhRoot=null,this.bvh=null,this.bvhData=null,this.bvhIndexChunks=null,this.bvhIndex=null,this.materialData=null,this.instanceTable=null,this._refitWorker=null,this._refitSharedBuffers=null,this._rebuildGeneration=0,this._pendingRebuilds=new Map,this.srgbBucketTextures=null,this.linearBucketTextures=null,this.emissiveTriangleData=null,this.emissiveTriangleCount=0,this.lightBVHNodeData=null,this.lightBVHNodeCount=0,this.emissiveBitTrailMap=null,this._initProcessors(),this.isProcessing=!1,this.processingStage=null,this.memory=new xo,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 Gn({issues:this.config.issues}),this.bvhBuilder=new qi,this.bvhBuilder.maxLeafSize=this.config.maxLeafSize,this.textureCreator=new Rs({maxTextureSize:this.config.maxTextureSize,issues:this.config.issues}),this.emissiveTriangleBuilder=new Ks,this.tlasBuilder=new no,this._tlasWorker=null,this._tlasWorkerFailed=!1}_log(e,t){t===void 0?Rc.debug(e):Rc.debug(e,t)}needsSpill(e){return io(this.geometryExtractor.surveyScene(e)).total>mo}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=io(n);if(this._streaming){let t=Nc+Uc(e)*(q.FLOATS_PER_TRIANGLE*4+44);r.total=ao(r,n.placements,Math.min(r.triangles,t))}else this._progressive&&(r.total-=r.bvh);let i={...n,estimate:r,safeBytes:mo,maxBytes:t,fits:r.total<=mo};if(this.memoryPreflight=i,r.total<1610612736)return i;if(Rc.debug(U.list([`memory preflight: ${U.mb(r.total)} estimated`,`triangles ${U.mb(r.triangles)} · bvh ${U.mb(r.bvh)} · geometry ${U.mb(r.geometry)}`,`${U.n(n.triangles)} tris · ${U.n(n.placements)} placements`])),r.total>t){let e=`Scene needs about ${U.mb(r.total)} of CPU memory, past the ${U.mb(t)} a browser tab can hold — loading it would crash the tab rather than fail. Reduce the scene (it has ${U.n(n.triangles)} triangles), or raise maxSceneBytes to try anyway.`;throw this.config.issues?.record(Z.SCENE_MEMORY_BUDGET,e,{...n,estimate:r,maxBytes:t}),Error(e)}return i.fits||this.config.issues?.warn(Z.SCENE_MEMORY_BUDGET,`Scene needs about ${U.mb(r.total)} of CPU memory, above the ${U.mb(mo)} 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:mo}),i}_checkAssemblyHeadroom(e){let t=e*64;if(t<1610612736)return!0;let n=oo(Math.ceil(t*yo),{shared:cn});return this.memoryPreflight&&(this.memoryPreflight.assemblyProbed=n.placed),n.exhausted&&this.config.issues?.warn(Z.SCENE_MEMORY_BUDGET,`BVH assembly needs ${U.mb(t)} but only ${U.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?Bc(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} ${U.mb(n[e].allocated)}`),i=this.memoryPreflight?.estimate?.total;Rc.debug(U.list([`memory: peak live ${U.mb(t)}`,`allocated ${U.mb(e)}`,i?`predicted ${U.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,an(e=>this.memory.alloc(e));let r=new qs(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/(q.FLOATS_PER_TRIANGLE*4)),this._foldLeaves=i>jc,this.textureCoordinates=Ln(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=jn(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,B({status:`Building light data...`,progress:77}),r.start(`Emissive extraction + Light BVH`),this._buildEmissiveData(),r.end(`Emissive extraction + Light BVH`),a||B({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>=Pc?this._geometryOwner=e:await this._restoreGeometry(e),B({status:`Scene data ready`,progress:85}),this._blasKey&&!this._blasRestored&&this.performanceMetrics.totalProcessingTime>=this.config.sceneCacheMinBuildMs&&(this._blasStoring=this._storeBLASes(e.name??``).catch(e=>Rc.debug(`storing BLASes failed:`,e))),this}catch(e){throw this.processingStage=`error`,Rc.error(`processing failed:`,e),B({status:`Error: ${e.message}`,failed:!0,progress:100}),e}finally{this._geometryOwner||this._disposeGeometrySpill(),an(null),this._sampleMemory(`at ${this.processingStage}`),this._logMemoryReport(),this.isProcessing=!1}}async _extractGeometry(e){B({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}),B({status:`Extracted ${this.triangleCount.toLocaleString()} triangles`,progress:25})}catch(e){throw Rc.error(`geometry extraction failed:`,e),B({status:`Extraction error: ${e.message}`,failed:!0,progress:25}),e}}async _extractStreaming(e){B({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=un.lazy(o,q.FLOATS_PER_TRIANGLE,Uint32Array),c=s.recordsPerChunk*s.lanesPerRecord*4,l=await _n.create(r,`${a}:tri`,c,{label:`Triangle records`,expectedBytes:o*c/s.recordsPerChunk}),u=l&&await _n.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 En.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);Va.rootAABB(zc(r)[0],v,t.start,t.count,i,0),p.set(e,{result:n,aabb:i});let a=f.blasBytes;f.blasBytes+=Bc(r),f.blasAt.set(e,a),n.nodeCount=Bc(r)/64,n.bvhData=null,this._queueSpill(f,()=>Hc(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>Lc&&await d.written(),B({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>Nc&&(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),Rc.error(`streamed extraction failed:`,e),B({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=vt(e.triangleCount,`triangle count`),this._foldLeaves&&this.triangleCount>134217728)throw RangeError(`${this.triangleCount.toLocaleString()} triangles is past the ${Mt.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.maps=e.maps,this.normalMaps=e.normalMaps,this.bumpMaps=e.bumpMaps,this.roughnessMaps=e.roughnessMaps,this.metalnessMaps=e.metalnessMaps,this.emissiveMaps=e.emissiveMaps,this.displacementMaps=e.displacementMaps,this.anisotropyMaps=e.anisotropyMaps,this.transmissionMaps=e.transmissionMaps,this.clearcoatMaps=e.clearcoatMaps,this.clearcoatRoughnessMaps=e.clearcoatRoughnessMaps,this.sheenColorMaps=e.sheenColorMaps,this.sheenRoughnessMaps=e.sheenRoughnessMaps,this.iridescenceMaps=e.iridescenceMaps,this.iridescenceThicknessMaps=e.iridescenceThicknessMaps,this.specularIntensityMaps=e.specularIntensityMaps,this.specularColorMaps=e.specularColorMaps,this.diffuseTransmissionMaps=e.diffuseTransmissionMaps??[],this.diffuseTransmissionColorMaps=e.diffuseTransmissionColorMaps??[],this.directionalLights=e.directionalLights,this.cameras=e.cameras}async _buildBVH(){if(B({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 Va,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=no.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++,B({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,B({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??Bc(r.bvhData)/64,triOffset:t.start,triCount:t.count,originalToBvhMap:r.originalToBvh||null,bvhData:r.bvhData,matrixWorld:n?Pa: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?Pa:this.meshes?.[e]?.matrixWorld?.elements??null,t[o(e)].expandedStart,o(e))}B({status:`Built all BLASes`,progress:70}),this.performanceMetrics.blasBuildTime=performance.now()-e,B({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(no.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(un.lazy(j,16,Float32Array,void 0,cn));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 nc(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 zc(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;Rc.debug(U.list([`${U.n(A.setCount)} BLASes + TLAS`,`${U.n(this.bvh.recordCount)} nodes`,`SAH ${U.n(O.sah)} · objMed ${O.objMed} · spatMed ${O.spatMed} · failed ${O.failed}`,U.ms(I)])),B({status:`BVH construction complete`,progress:75})}catch(e){throw Rc.error(`BVH build failed:`,e),B({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:V()}}_isLargeMesh(e){return e.count>=Oc&&Ma(e.count)}async _buildLargeBLAS(e,t){if(e.count>kc)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 ka(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 cc(n,e.start,e.count,Ac,{pause:()=>new Promise(e=>setTimeout(e,0))}),o=this._blasPool(t,null,null,Math.min(Cr(),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),Va.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{...fc(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:${hc}:${JSON.stringify(t)}:${n}:${this._sceneKey}`}async _restoreBLASes(e,t,n){if(!this._sceneKey||this.config.sceneCache===!1)return null;let r=Zr(ni().cacheNamespace);if(!r)return null;this._blasKey=this._blasCacheKey(n);let i=await ec(r,this._blasKey);if(!i)return null;let a=e=>(Rc.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 $s(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 rc(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},Rc.debug(`restored ${U.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=Zr(ni().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 $s(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 tc(t,r,{index:{v:2,tlasNodeCount:n.blasBase,totalNodes:n.treeNodeCount,templates:d},bvh:this.bvh,orders:u,isStale:a,label:e});return f&&Rc.debug(`stored ${U.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 _n.create(t,`${i}:tri`,a,{label:`Triangle records`,expectedBytes:r.byteLength}),s=o&&await _n.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(zc(a)[0],t,this.triangles,i.tplObjectAABB,t*6);let o=e.blasBytes;e.blasBytes+=Bc(a),e.blasAt.set(t,o),r.nodeCount=Bc(a)/64,r.bvhData=null,this._queueSpill(e,()=>Hc(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=q.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+=Vc)i.push(new Float32Array(await e.blasStore.readAt(n+t,Math.min(Vc,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 _n.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);Ri(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=Dr(xa);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 Rc.error(`texture creation failed:`,e),e}}_bucketTextures(){let e=this.config.maxTextureSize,t=Zt.MATERIAL_BUCKET_COUNT,n=Zt.BUCKET_LAYER_STRIDE,r=e=>{let t=new Set,n=[];for(let r of e)for(let e of r||[]){if(!e?.image)continue;let r=e.source?.uuid??e.uuid;t.has(r)||(t.add(r),n.push({width:e.image.width,height:e.image.height}))}return n},i=[this.maps,this.emissiveMaps,this.sheenColorMaps,this.specularColorMaps,this.diffuseTransmissionColorMaps],a=[this.normalMaps,this.bumpMaps,this.roughnessMaps,this.metalnessMaps,this.displacementMaps,this.anisotropyMaps,this.transmissionMaps,this.clearcoatMaps,this.clearcoatRoughnessMaps,this.sheenRoughnessMaps,this.iridescenceMaps,this.iridescenceThicknessMaps,this.specularIntensityMaps,this.diffuseTransmissionMaps],o=Jt(r(i),e,t),s=Jt(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(Z.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=Yt(e.image.width,e.image.height,a),s=e.source?.uuid??e.uuid,c=r[o].get(s);if(c!==void 0)return Xt(o,c);if(t[o].length>=n)return Rc.warn(`texture bucket ${o} full (${n}); dropping a map`),f||this.config.issues?.record(Z.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=Xt(o,l);return i.set(s,u),u},h=(e,t,n,r,i)=>(e||[]).map(e=>m(e,t,n,r,i));return{srgbLists:c,linearLists:l,remap:{albedo:h(this.maps,c,u,this._srgbTexPacked,o),emissive:h(this.emissiveMaps,c,u,this._srgbTexPacked,o),normal:h(this.normalMaps,l,d,this._linearTexPacked,s),bump:h(this.bumpMaps,l,d,this._linearTexPacked,s),roughness:h(this.roughnessMaps,l,d,this._linearTexPacked,s),metalness:h(this.metalnessMaps,l,d,this._linearTexPacked,s),displacement:h(this.displacementMaps,l,d,this._linearTexPacked,s),anisotropy:h(this.anisotropyMaps,l,d,this._linearTexPacked,s),transmission:h(this.transmissionMaps,l,d,this._linearTexPacked,s),clearcoat:h(this.clearcoatMaps,l,d,this._linearTexPacked,s),clearcoatRoughness:h(this.clearcoatRoughnessMaps,l,d,this._linearTexPacked,s),sheenColor:h(this.sheenColorMaps,c,u,this._srgbTexPacked,o),sheenRoughness:h(this.sheenRoughnessMaps,l,d,this._linearTexPacked,s),iridescence:h(this.iridescenceMaps,l,d,this._linearTexPacked,s),iridescenceThickness:h(this.iridescenceThicknessMaps,l,d,this._linearTexPacked,s),specularIntensity:h(this.specularIntensityMaps,l,d,this._linearTexPacked,s),specularColor:h(this.specularColorMaps,c,u,this._srgbTexPacked,o),diffuseTransmission:h(this.diffuseTransmissionMaps,l,d,this._linearTexPacked,s),diffuseTransmissionColor:h(this.diffuseTransmissionColorMaps,c,u,this._srgbTexPacked,o)}}}_remapMaterialTextureIndices(e){let t=(e,t)=>e>=0&&e<t.length?t[e]:-1;for(let n of this.materials)n.map=t(n.map,e.albedo),n.emissiveMap=t(n.emissiveMap,e.emissive),n.normalMap=t(n.normalMap,e.normal),n.bumpMap=t(n.bumpMap,e.bump),n.roughnessMap=t(n.roughnessMap,e.roughness),n.metalnessMap=t(n.metalnessMap,e.metalness),n.displacementMap=t(n.displacementMap,e.displacement),n.anisotropyMap=t(n.anisotropyMap,e.anisotropy),n.transmissionMap=t(n.transmissionMap,e.transmission),n.clearcoatMap=t(n.clearcoatMap,e.clearcoat),n.clearcoatRoughnessMap=t(n.clearcoatRoughnessMap,e.clearcoatRoughness),n.sheenColorMap=t(n.sheenColorMap,e.sheenColor),n.sheenRoughnessMap=t(n.sheenRoughnessMap,e.sheenRoughness),n.iridescenceMap=t(n.iridescenceMap,e.iridescence),n.iridescenceThicknessMap=t(n.iridescenceThicknessMap,e.iridescenceThickness),n.specularIntensityMap=t(n.specularIntensityMap,e.specularIntensity),n.specularColorMap=t(n.specularColorMap,e.specularColor),n.diffuseTransmissionMap=t(n.diffuseTransmissionMap,e.diffuseTransmission),n.diffuseTransmissionColorMap=t(n.diffuseTransmissionColorMap,e.diffuseTransmissionColor)}_buildEmissiveData(){this.emissiveTriangleCount=this.emissiveTriangleBuilder.extractEmissiveTriangles(this.triangles,this.materials,this.triangleCount,this.instanceTable??null),this.emissiveTriangleData=this.emissiveTriangleBuilder.createEmissiveRawData(),this.emissiveTotalPower=this.emissiveTriangleBuilder.totalEmissivePower,this._log(`Emissive triangle extraction complete`,this.emissiveTriangleBuilder.getStats()),this.emissiveTriangleBuilder.buildLightBVH(),this.lightBVHNodeData=this.emissiveTriangleBuilder.lightBVHNodeData,this.lightBVHNodeCount=this.emissiveTriangleBuilder.lightBVHNodeCount,this.emissiveTriangleData=this.emissiveTriangleBuilder.emissiveTriangleData||this.emissiveTriangleData,this.emissiveBitTrailMap=this.emissiveTriangleBuilder.emissiveBitTrailMap,this.emissiveTriangleCount=this.emissiveTriangleBuilder.emissiveCount,this.emissiveTotalPower=this.emissiveTriangleBuilder.totalEmissivePower}_createSpheres(){return[]}_reset(){this._geometryVersion=(this._geometryVersion??0)+1,this._disposeSpill(),this._disposeGeometrySpill(),this._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.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){Rc.warn(`error disposing ${e}:`,t)}this[e]=null}}}async rebuildMaterials(e){if(this.isProcessing)throw Error(`Already processing. Cannot rebuild materials during processing.`);this._log(`Rebuilding materials and textures`);let t=performance.now();try{this.isProcessing=!0;let n=this.geometryExtractor.extractMaterialsOnly(e);this._disposeMaterialTextures(),this.materials=n.materials,this.meshes=n.meshes,this.maps=n.maps,this.normalMaps=n.normalMaps,this.bumpMaps=n.bumpMaps,this.roughnessMaps=n.roughnessMaps,this.metalnessMaps=n.metalnessMaps,this.emissiveMaps=n.emissiveMaps,this.displacementMaps=n.displacementMaps,await this._createMaterialTextures();let r=performance.now()-t;return this._log(`Material rebuild complete (${r.toFixed(2)}ms)`,{materials:this.materials.length,textures:this.maps.length}),this}catch(e){throw Rc.error(`material rebuild failed:`,e),e}finally{this.isProcessing=!1}}_disposeMaterialTextures(){this._disposeBucketTextures(),this.textureCreator&&this.textureCreator.textureCache&&(this.textureCreator.textureCache.dispose(),this.textureCreator.textureCache=new this.textureCreator.textureCache.constructor)}getStatistics(){let e={triangleCount:this.triangleCount,materialCount:this.materials.length,textureCount:this.maps.length,lightCount:this.directionalLights.length,cameraCount:this.cameras.length,processingComplete:this.processingStage===`complete`,hasBVH:!!this.bvhRoot,hasTextures:!!this.materialData&&!!this.bvh,useFloat32Array:this.config.useFloat32Array,triangleDataSize:this.triangles?(this.triangles.byteLength/(1024*1024)).toFixed(2)+`MB`:`0MB`};return this.performanceMetrics.totalProcessingTime>0&&(e.performance={totalTime:this.performanceMetrics.totalProcessingTime,textureTime:this.performanceMetrics.textureCreationTime,bvhTime:this.performanceMetrics.bvhBuildTime,extractionTime:this.performanceMetrics.geometryExtractionTime,texturePercentage:(this.performanceMetrics.textureCreationTime/this.performanceMetrics.totalProcessingTime*100).toFixed(1)+`%`}),this.textureCreator&&this.textureCreator.capabilities&&(e.textureCapabilities=this.textureCreator.capabilities),e}updateConfig(e){Object.assign(this.config,e),this.bvhBuilder&&(this.bvhBuilder.maxLeafSize=this.config.maxLeafSize),this._log(`Configuration updated`,this.config)}_adoptSharedChunks(e,t){let n=this[e];if(n.shared)return;let r=n.chunks.map(e=>{let n=new t(new SharedArrayBuffer(e.byteLength));return n.set(e),n}),i=un.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||=Dr(Cc),!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=q.FLOATS_PER_TRIANGLE,o=[],s=[],c=0;for(let e=0;e<i.count;e++){if(!i.isSet[e]||!i.isOwner(e))continue;c++;let t=n(e);if(!t)continue;if(this._updateMeshTrianglePositions(e,t),s.push(i.blasOffsetOf(e),i.blasNodeCountOf(e)),r){let t=r(e);t&&this._patchMeshSmoothNormals(e,t)}let l=i.triOffsetOf(e)*a,u=i.triCountOf(e)*a,d=o.at(-1);d&&d.offset+d.count===l?d.count+=u:o.push({offset:l,count:u})}let l=i.tlasNodeCount,u=l>0&&s.length/2<c,d=u?[this.computeTLASDirtyRange()]:null;for(let e=0;u&&e<s.length;e+=2)d.push({offset:s[e]*16,count:s[e+1]*16});return new Promise((e,t)=>{this._refitWorker.onmessage=n=>{let r=n.data;r.type===`refitComplete`?e({refitTimeMs:r.refitTimeMs,triRanges:o,bvhRanges:d}):r.type===`error`&&t(Error(r.error))},this._refitWorker.postMessage({type:`refit`,blasRanges:u?s:null,tlasNodeCount:l,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 va;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(Z.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?(La(o,s,e*16,r),n.setPlacementMatrix(t,r)):c?(La(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}}_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}no.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=Ra(n.matrixWorldOf(t));o[s]=(o[s]&~St|(c?St: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=q.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)):Rc.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):(Rc.error(`failed to get BVH data`),!1)):(Rc.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 _n.create(e,`${a}:tri`,o(t),{label:`Triangle records`,expectedBytes:t.byteLength}),c=s&&await _n.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 Rc.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 En.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,Rc.info(`${U.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});Rc.info(`spilled ${U.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 _n.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(Fc),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>Ic){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(Ic,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||B({status:`Reading scene geometry back...`,progress:84});let n=performance.now(),r=t.bytes;await t.restore(),this._disposeGeometrySpill(),this._geometryBytes=jn(e),Rc.info(`read ${U.mb(r)} of scene geometry back from disk in ${U.ms(performance.now()-n)}`),t.error&&Rc.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>=Mc: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>=Dc&&!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 no.fillLeaves(i,a,e),i}catch(e){this._tlasWorkerFailed=!0,Rc.warn(`TLAS worker unavailable (${e.message}); building on the main thread`)}return this.tlasBuilder.build(e).data}_runTLASWorker(e,t){this._tlasWorker||=Dr(Ec);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:V()},[e.buffer])})}_setBVHData(e){let t=e?e instanceof un?e:un.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=q.FLOATS_PER_TRIANGLE,n=e?e instanceof un?e:un.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=q.POSITION_A_OFFSET,r=q.POSITION_B_OFFSET,i=q.POSITION_C_OFFSET,a=q.NORMAL_A_PACKED_OFFSET,o=q.NORMAL_B_PACKED_OFFSET,s=q.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=Ra(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=pt(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=q.NORMAL_A_PACKED_OFFSET,o=q.NORMAL_B_PACKED_OFFSET,s=q.NORMAL_C_PACKED_OFFSET,c=r,l=!c||Ra(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]]=pt(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===wt.BLAS_POINTER_LEAF){let n=e[p+1]&Ct;if(n>=t.entryCount)continue;t.writeEntryWorldAABB(n,c,0)}else if(i===wt.CLUSTER_LEAF)t.encodeClusterBoxes(f,e,p,t.clusterOf(e[p]&Tt),null,c,0);else if(i<wt.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=Kc(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){Rc.error(`background BLAS rebuild failed (mesh ${e}):`,o.error);return}n===this._rebuildGeneration&&this._swapBLAS(e,r,o,t)},i.onerror=t=>{Rc.error(`background BLAS rebuild worker failed (mesh ${e}):`,t),i.terminate(),this._pendingRebuilds.delete(e)},i.postMessage({triangleData:a.buffer,triangleByteOffset:a.byteOffset,triangleByteLength:a.byteLength,triangleCount:r.triCount,depth:this.config.bvhDepth,maxLeafSize:this.bvhBuilder.maxLeafSize,numBins:this.bvhBuilder.numBins,maxBins:this.bvhBuilder.maxBins,minBins:this.bvhBuilder.minBins,reportProgress:!1,sharedReorderBuffer:null,reinsertionOptimization:{enabled:this.bvhBuilder.enableReinsertionOptimization,batchSizeRatio:this.bvhBuilder.reinsertionBatchSizeRatio,maxIterations:this.bvhBuilder.reinsertionMaxIterations}},[a.buffer])};for(let t of e){let e=this._placementOf(t);if(e<0)continue;let n=this.instanceTable.entryAt(e);if(!n||!this.instanceTable.isOwner(e))continue;let i=this._pendingRebuilds.get(e);i&&i.terminate(),r(e,n,Dr(xa))}}_swapBLAS(e,t,n,r){this._geometryVersion=(this._geometryVersion??0)+1;let i=n.bvhData,a=i.length/16;if(a>t.blasNodeCount){Rc.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}},Jc=[[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]],Yc=[[-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]],Xc=[[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 Zc(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=Jc[i],o=Yc[i],s=Xc[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)]}er();var Qc=1/(4*Math.PI);function $c(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]=Zc(t.temperature??6500);i[0]*=e,i[1]*=n,i[2]*=r}return Xn(i),{r:i[0],g:i[1],b:i[2],intensity:r}}var el=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=$c(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=$c(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=$c(e);this.pointLightCache.push({data:[t.x,t.y,t.z,i.r,i.g,i.b,i.intensity*Qc,e.distance||0,e.decay===void 0?2:e.decay],importance:n,light:e})}addSpotLight(e){if(!e.visible||e.intensity<=0)return;e.updateMatrixWorld();let t=e.getWorldPosition(new r.Vector3),n=(e.target?e.target.getWorldPosition(new r.Vector3):new r.Vector3(0,0,-1)).sub(t).normalize(),i=this.calculateLightImportance(e,`spot`),a=e.userData?.gobo,o=a&&Number.isInteger(a.index)?a.index:-1,s=a&&typeof a.intensity==`number`?a.intensity:1,c=a&&a.inverted?-Math.abs(s):Math.abs(s),l=e.userData?.ies,u=l&&Number.isInteger(l.index)?l.index:-1,d=l&&typeof l.intensity==`number`?l.intensity:1,f=$c(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*Qc,e.angle||Math.PI/4,e.penumbra||0,e.distance||0,e.decay===void 0?2:e.decay,o,c,u,d,0,0],importance:i,light:e})}preprocessLights(){this.directionalLightCache.sort((e,t)=>t.importance-e.importance),this.areaLightCache.sort((e,t)=>t.importance-e.importance),this.pointLightCache.sort((e,t)=>t.importance-e.importance),this.spotLightCache.sort((e,t)=>t.importance-e.importance),this.lightData.directional=[],this.lightData.rectArea=[],this.lightData.point=[],this.lightData.spot=[],this.directionalLightCache.forEach(e=>{this.lightData.directional.push(...e.data)}),this.areaLightCache.forEach(e=>{this.lightData.rectArea.push(...e.data)}),this.pointLightCache.forEach(e=>{this.lightData.point.push(...e.data)}),this.spotLightCache.forEach(e=>{this.lightData.spot.push(...e.data)}),this.areaLightCache.length>0&&console.log(`Preprocessed ${this.areaLightCache.length} area lights by importance`),this.pointLightCache.length>0&&console.log(`Preprocessed ${this.pointLightCache.length} point lights by importance`),this.spotLightCache.length>0&&console.log(`Preprocessed ${this.spotLightCache.length} spot lights by importance`)}updateShaderUniforms(e){let t=Math.floor(this.lightData.directional.length/12),n=Math.floor(this.lightData.rectArea.length/16),r=Math.floor(this.lightData.point.length/9),i=Math.floor(this.lightData.spot.length/20);e.defines.MAX_DIRECTIONAL_LIGHTS=t,e.defines.MAX_AREA_LIGHTS=n,e.defines.MAX_POINT_LIGHTS=r,e.defines.MAX_SPOT_LIGHTS=i,e.uniforms.directionalLights.value=new Float32Array(this.lightData.directional),e.uniforms.areaLights.value=new Float32Array(this.lightData.rectArea),e.uniforms.pointLights.value=new Float32Array(this.lightData.point),e.uniforms.spotLights.value=new Float32Array(this.lightData.spot),e.needsUpdate=!0}processSceneLights(e,t){this.clear(),e.traverse(e=>{e.isDirectionalLight?this.addDirectionalLight(e):e.isRectAreaLight?this.addRectAreaLight(e):e.isPointLight?this.addPointLight(e):e.isSpotLight&&this.addSpotLight(e)}),this.preprocessLights(),this.updateShaderUniforms(t)}getLightStatistics(){return{directionalLights:this.directionalLightCache.map(e=>({intensity:e.light.intensity,importance:e.importance,color:e.light.color})),areaLights:this.areaLightCache.map(e=>({intensity:e.light.intensity,importance:e.importance,color:e.light.color,size:e.light.width*e.light.height}))}}},tl,nl,rl,il,al,ol,sl,cl,ll,ul,dl,fl,pl,ml,hl,gl,_l=g((()=>{tl=x({origin:`vec3`,direction:`vec3`}),nl=x({color:`vec4`,emissive:`vec3`,emissiveIntensity:`float`,roughness:`float`,metalness:`float`,ior:`float`,transmission:`float`,thickness:`float`,clearcoat:`float`,clearcoatRoughness:`float`,opacity:`float`,transparent:`bool`,attenuationColor:`vec3`,attenuationDistance:`float`,dispersion:`float`,sheen:`float`,sheenRoughness:`float`,sheenColor:`vec3`,specularIntensity:`float`,specularColor:`vec3`,alphaTest:`float`,alphaMode:`int`,side:`int`,depthWrite:`int`,albedoMapIndex:`int`,emissiveMapIndex:`int`,normalMapIndex:`int`,bumpMapIndex:`int`,bumpScale:`float`,displacementScale:`float`,metalnessMapIndex:`int`,roughnessMapIndex:`int`,displacementMapIndex:`int`,normalScale:`vec2`,albedoTransform:`mat3`,emissiveTransform:`mat3`,normalTransform:`mat3`,bumpTransform:`mat3`,metalnessTransform:`mat3`,roughnessTransform:`mat3`,displacementTransform:`mat3`,iridescence:`float`,iridescenceIOR:`float`,iridescenceThicknessRange:`vec2`,subsurface:`float`,subsurfaceColor:`vec3`,subsurfaceRadius:`vec3`,subsurfaceRadiusScale:`float`,subsurfaceAnisotropy:`float`,anisotropy:`float`,anisotropyRotation:`float`,anisotropyMapIndex:`int`,transmissionMapIndex:`int`,clearcoatMapIndex:`int`,clearcoatRoughnessMapIndex:`int`,sheenColorMapIndex:`int`,sheenRoughnessMapIndex:`int`,iridescenceMapIndex:`int`,iridescenceThicknessMapIndex:`int`,specularIntensityMapIndex:`int`,specularColorMapIndex:`int`,diffuseTransmission:`float`,diffuseTransmissionColor:`vec3`,diffuseTransmissionMapIndex:`int`,diffuseTransmissionColorMapIndex:`int`}),rl=x({transmission:`float`,clearcoat:`float`,clearcoatRoughness:`float`,sheenColor:`vec3`,sheenRoughness:`float`,iridescence:`float`,iridescenceThickness:`float`,specularIntensity:`float`,specularColor:`vec3`,diffuseTransmission:`float`,diffuseTransmissionColor:`vec3`}),il=x({color:`vec4`,ior:`float`,transmission:`float`,attenuationColor:`vec3`,attenuationDistance:`float`,albedoMapIndex:`int`,opacity:`float`,transparent:`bool`,alphaTest:`float`,alphaMode:`int`,albedoTransform:`mat3`}),al=x({shadowed:`vec3`,unoccluded:`vec3`}),x({position:`vec3`,radius:`float`,material:nl}),ol=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:nl,materialIndex:`int`,meshIndex:`int`}),x({color:`vec4`,samples:`int`}),sl=x({direction:`vec3`,value:`vec3`,pdf:`float`,isTransmission:`bool`,colorWeight:`vec3`,isDiffuseTransmission:`bool`}),cl=x({specular:`float`,diffuse:`float`,sheen:`float`,clearcoat:`float`,transmission:`float`,iridescence:`float`,diffuseTransmission:`float`}),ll=x({Ta:`vec3`,Ba:`vec3`}),ul=x({NoL:`float`,NoV:`float`,NoH:`float`,VoH:`float`,LoH:`float`,ToH:`float`,BoH:`float`,ToV:`float`,BoV:`float`,ToL:`float`,BoL:`float`}),dl=x({compensation:`vec3`,E_total:`vec3`}),fl=x({f0:`vec3`,f90:`float`,eta:`float`,F0m:`vec3`,F0:`vec3`}),pl=x({albedo:`vec4`,emissive:`vec3`,metalness:`float`,roughness:`float`,normal:`vec3`,hasTextures:`bool`}),ml=x({isMetallic:`bool`,isRough:`bool`,isSmooth:`bool`,isTransmissive:`bool`,hasClearcoat:`bool`,isEmissive:`bool`,complexityScore:`float`}),hl=x({albedoUV:`vec2`,normalUV:`vec2`,metalnessUV:`vec2`,emissiveUV:`vec2`,bumpUV:`vec2`,roughnessUV:`vec2`,normalBumpSameUV:`bool`,metalRoughSameUV:`bool`,albedoEmissiveSameUV:`bool`,allSameUV:`bool`}),gl=x({invRoughness:`float`,metalFactor:`float`,iorFactor:`float`,maxSheenColor:`float`}),x({traversals:`int`,transmissiveTraversals:`int`,rayType:`int`,isPrimaryRay:`bool`,actualBounceDepth:`int`})}));function vl(e,t,n){return e.length===1?e[0]:{isSplitStorage:!0,parts:e,perPart:t,type:n,value:e[0].value}}function yl(e,t){if(!e.isSplitStorage)return e.element(t);let{parts:r,perPart:i}=e,a=(0,n.int)(t).toVar(),o=({uvec4:n.uvec4,uvec2:n.uvec2}[e.type]??n.vec4)(0).toVar(),s=e=>()=>o.assign(r[e].element(e===0?a:a.sub((0,n.int)(i*e)))),c=(0,n.If)(a.lessThan((0,n.int)(i)),s(0));for(let e=1;e<r.length-1;e++)c=c.ElseIf(a.lessThan((0,n.int)(i*(e+1))),s(e));return c.Else(s(r.length-1)),o}var bl,xl,Sl,Cl,wl,Tl,El,Dl,Ol,kl,Al,jl,Ml,Nl,Pl,Fl,Il,Ll,Rl,zl,Bl,Vl,Hl,Ul,Wl,Gl,Kl,ql,Jl,Q,Yl,Xl,Zl,Ql,$l,eu,tu,nu,ru,iu,au,ou,su,cu=g((()=>{_l(),Pt(),bl=(0,n.wgslFn)(`
|
|
247
|
+
`,bindings:n}}function rs(){os.length=0,os.push(...Uo),ss.clear();for(let e of os)ss.set(e.id,e);Go()}var is,as,os,ss,cs,ls,us,ds,fs,ps=g((()=>{Wo(),is=200,as=12,os=[...Uo],ss=new Map(os.map(e=>[e.id,e])),cs=1,ls=new Set,us=ss,ds=r.NoToneMapping,fs=r.AgXToneMapping}));ps();var ms=e=>(t,n,r,i,a)=>e(t>0?t:0,n>0?n:0,r>0?r:0,i,a),hs=new Map;function gs(){hs.clear();for(let e of us.values())hs.set(e.id,ms(e.cpu))}gs(),qo(gs);function _s(e){return Jo(e)?.outputEncoded===!0}function vs(e){return e<=.0031308?12.92*e:1.055*e**(1/2.4)-.055}function ys(e,t){let n=Jo(t);return n?n.appliesExposure?e:1:t===r.NoToneMapping?1:e}var bs=.2126,xs=.7152,Ss=.0722;function Cs(e,t){if(t===1)return;let n=e[0]*bs+e[1]*xs+e[2]*Ss;e[0]=n+(e[0]-n)*t,e[1]=n+(e[1]-n)*t,e[2]=n+(e[2]-n)*t}function ws(e,{exposure:t,toneMapping:n,saturation:i=1,preserveAlpha:a=!1,pixelGain:o=null}){let s=hs.get(n)??hs.get(r.NoToneMapping),c=ys(t,n),l=_s(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=t>>2,i=r%o.width,a=(r-i)/o.width,s=e[t]*.2126+e[t+1]*.7152+e[t+2]*.0722;n*=o.fn((i+.5)/o.width,(a+.5)/o.height,s,f)}d[0]=e[t]*n,d[1]=e[t+1]*n,d[2]=e[t+2]*n,Cs(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]=vs(d[0])*255+.5,u[t+1]=vs(d[1])*255+.5,u[t+2]=vs(d[2])*255+.5),u[t+3]=a?e[t+3]*255+.5:255}return u}Pt(),$t(),rn(),Oe(),Ar();var Ts=_e(`textures`),Es={MAX_BUFFER_MEMORY:1024*1024*1024,MAX_TEXTURE_MEMORY:2048*1024*1024,CLEANUP_THRESHOLD:.8,STREAM_BATCH_SIZE:4},Ds=8*2**20,Os=16,ks=4,As=8192*8192,js={busy:0,waiting:[]};async function Ms(){return js.busy<Math.max(1,Cr()-1)?js.busy++:await new Promise(e=>js.waiting.push(e)),()=>{let e=js.waiting.shift();e?e():js.busy--}}var Ns={toSRGB:null,toLinear:null};function Ps(e){if(!Ns[e]){let t=new Uint8Array(256);for(let n=0;n<256;n++){let r=n/255,i=e===`toSRGB`?vs(r):r<=.04045?r/12.92:((r+.055)/1.055)**2.4;t[n]=Math.max(0,Math.min(255,Math.round(i*255)))}Ns[e]=t}return Ns[e]}var Fs=class{constructor(){this.canvasContextPairs=[],this.maxPoolSize=Zt.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=[]}},Is=class{constructor(e={}){this.pools=new Map,this.memoryUsage=0,this.maxMemoryUsage=e.maxMemory||Es.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*Es.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<Zt.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`}},Ls=class{constructor(e=Zt.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=[]}},Rs=class{constructor(e={}){this.useWorkers=typeof Worker<`u`,this.maxConcurrentWorkers=Zt.MAX_CONCURRENT_WORKERS,this.activeWorkers=0,this._issues=e.issues??null,this.maxTextureSize=this._clampTextureSize(e.maxTextureSize??Zt.DEFAULT_MAX_TEXTURE_SIZE),this.canvasPool=new Fs,this.bufferPool=new Is({maxMemory:e.maxBufferMemory||Es.MAX_BUFFER_MEMORY,sizeStrategy:e.bufferSizeStrategy||`adaptive`}),this.textureCache=new Ls,this.capabilities=this.detectCapabilities(),this.optimalMethod=this.selectOptimalMethod()}_reportTextureFailure(e,t){if(t instanceof tn)throw t;this._issues?.record(Z.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(Z.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)||Zt.DEFAULT_MAX_TEXTURE_SIZE);return Math.max(Zt.MIN_TEXTURE_WIDTH,Math.min(t,Zt.MAX_TEXTURE_SIZE))}setMaxTextureSize(e){let t=this._clampTextureSize(e);return t===this.maxTextureSize?t:(this.maxTextureSize=t,this.textureCache?.dispose(),this.textureCache=new Ls,this.maxTextureSize)}detectCapabilities(){return{offscreenCanvas:typeof OffscreenCanvas<`u`,imageBitmap:typeof createImageBitmap<`u`,workers:typeof Worker<`u`,hardwareConcurrency:Cr()}}selectOptimalMethod(){return this.capabilities.workers&&this.capabilities.offscreenCanvas?`worker-offscreen`:this.capabilities.imageBitmap?`imageBitmap`:`canvas`}_applyColorManagement(e,t,n,i=new Set){let a=Jr();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){Ts.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(Z.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(Z.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,Ts.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=Ps(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?Ts.info(`re-encoded ${l.length}/${o.length} linear-declared colour map(s) to sRGB so the GPU decode round-trips: ${u}`):Ts.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=Jr()?.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 tn)throw n;this._issues?.warn(Z.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>Es.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 To;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)<As)return 0;let t=this.maxConcurrentWorkers-this.activeWorkers;return Math.max(0,Math.min(e.length,ks,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=Dr(To);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=Dr(To);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>=Es.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>Os&&(await new Promise(e=>setTimeout(e,0)),l=performance.now())}return a.postMessage({stream:`end`}),this.createDataArrayTextureFromResult(await c)}finally{a.terminate(),this.activeWorkers--}}async prepareTexturesForWorkerDirect(e){let t=[],n=()=>({data:new Uint8ClampedArray([255,255,255,255]).buffer,width:1,height:1,isImageData:!0});for(let r=0;r<e.length;r++){let i=e[r];if(!i?.image){this._reportTextureLayer(r,`no image`),t.push(n());continue}let a=i.flipY!==!1;try{let e=i.image;if(typeof createImageBitmap<`u`&&(typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement||typeof ImageBitmap<`u`&&e instanceof ImageBitmap||typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement||typeof OffscreenCanvas<`u`&&e instanceof OffscreenCanvas)){let e=await createImageBitmap(i.image,{imageOrientation:a?`flipY`:`none`});t.push({bitmap:e,width:i.image.width,height:i.image.height,isDirect:!0})}else{let e=i.image.width,n=i.image.height,r=await createImageBitmap(i.image,{imageOrientation:a?`flipY`:`none`}),o=this.canvasPool.getCanvasWithContext(e,n);o.context.drawImage(r,0,0),r.close();let s=o.context.getImageData(0,0,e,n);t.push({data:s.data.buffer,width:e,height:n,isImageData:!0}),this.canvasPool.releaseCanvasWithContext(o)}}catch(e){this._reportTextureLayer(r,e),t.push(n())}}return t}async processOnCPU(e){let t=e.map((e,t)=>{let n=e?.image,r=e?.isCompressedTexture?e.mipmaps?.[0]:n,i=r?.data;return i&&r.width>0&&r.height>0&&i.byteLength>=r.width*r.height*4?{data:new Uint8Array(i.buffer,i.byteOffset,r.width*r.height*4),width:r.width,height:r.height,flipY:e.flipY!==!1}:(this._reportTextureLayer(t,n?`not decoded to pixels, and there is no browser to decode it`:`no image`),{data:new Uint8Array([255,255,255,255]),width:1,height:1,flipY:!1})}),{maxWidth:n,maxHeight:r}=this.calculateOptimalDimensions(t.map(e=>({image:e}))),i=n*r*4,a=Tr()&&i*t.length>=Ds?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)=>ko(e,o,t*i,n,r)),this.createDataArrayTextureFromBuffer(o,n,r,t.length)}async _packInWorker(e,t,n){let r=await Ms(),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=Dr(Oo),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(Z.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%Es.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=J.FLOATS_PER_MATERIAL,n=new Float32Array(e.length*t);for(let r=0;r<e.length;r++)Vt(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=Zt.VEC4_PER_BVH_NODE*Zt.FLOATS_PER_VEC4;vt(t.length,`BVH node count`);let i=t.length*r,a=new Float32Array(i),o=_t(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]=wt.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 Ls;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:Ht(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:zs(e.data,e.width,e.height)});continue}if(n.isCompressedTexture){console.warn(`[TextureCreator] GPU-compressed texture in mixed group — using placeholder`),t.push(null);continue}if(n.image.data&&!(typeof HTMLImageElement<`u`&&n.image instanceof HTMLImageElement)&&!(typeof HTMLCanvasElement<`u`&&n.image instanceof HTMLCanvasElement)&&!(typeof ImageBitmap<`u`&&n.image instanceof ImageBitmap)){let e=t.length;t.push(null),i.push({index:e,flipY:n.flipY,promise:zs(n.image.data,n.image.width,n.image.height)});continue}t.push(n)}if(i.length>0){let e=await Promise.allSettled(i.map(e=>e.promise));for(let r=0;r<i.length;r++){let{index:a,flipY:o}=i[r],s=e[r];if(s.status===`fulfilled`){let e=s.value;n.push(e),t[a]={image:e,flipY:o}}else this._reportTextureLayer(a,s.reason)}}for(let e=0;e<t.length;e++)if(t[e]===null){let r=new Uint8ClampedArray([255,255,255,255]),i=await createImageBitmap(new ImageData(r,1,1));n.push(i),t[e]={image:i,flipY:!1}}return{normalized:t,bitmapsToClose:n}}createFallbackTexture(){let e=new r.DataArrayTexture(new Uint8Array([255,255,255,255]),1,1,1);return e.minFilter=r.LinearFilter,e.magFilter=r.LinearFilter,e.format=r.RGBAFormat,e.type=r.UnsignedByteType,e.needsUpdate=!0,e.generateMipmaps=!1,e}dispose(){this.canvasPool.dispose(),this.bufferPool.dispose(),this.textureCache.dispose()}};function zs(e,t,n){let r=new Uint8ClampedArray(e.buffer,e.byteOffset,e.byteLength);return createImageBitmap(new ImageData(r,t,n))}var Bs=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=Hs(E,Vs(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=Hs(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 Vs(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 Hs(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)}}Pt(),Oe(),er();var Us=Object.freeze({r:0,g:0,b:0});function Ws(e){if(!e)return Us;if(!Jn())return e;let t=[e.r,e.g,e.b];return Xn(t),{r:t[0],g:t[1],b:t[2]}}var Gs=_e(`emissive`),Ks=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=q.FLOATS_PER_TRIANGLE,a=q.MATERIAL_FLAGS_OFFSET,o=q.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]&yt,h=n[p+o],g=t[m];if(!g)continue;let _=d.get(g);_===void 0&&(_=Ws(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),R=(O-T)*(M-E)-(k-E)*(j-T),ee=Math.sqrt(I*I+L*L+R*R)||1,z=g.side===1?-1:1;I=I/ee*z,L=L/ee*z,R=R/ee*z;let te=g.side===2,ne=(T+O+j)/3,re=(E+k+M)/3,ie=(D+A+N)/3,ae=Math.min(T,O,j),oe=Math.min(E,k,M),se=Math.min(D,A,N),ce=Math.max(T,O,j),B=Math.max(E,k,M),le=Math.max(D,A,N);this.emissiveTriangles.push({triangleIndex:e,materialIndex:m,meshIndex:h,sideSign:z,instanceLeaf:n?r.tlasLeafIndex[t]:-1,power:F,area:P,emissive:{r:_.r,g:_.g,b:_.b},emissiveIntensity:v,cx:ne,cy:re,cz:ie,bMinX:ae,bMinY:oe,bMinZ:se,bMaxX:ce,bMaxY:B,bMaxZ:le,nx:I,ny:L,nz:R,twoSided:te}),this.totalEmissivePower+=F}}return this.emissiveCount=this.emissiveTriangles.length,this.emissiveCount>0&&Gs.debug(`${U.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=q.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,Gs.debug(`emissive texture ${U.px(t,n)} · ${U.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 Gs.debug(`emissive raw data ${U.n(this.emissiveCount)} entries (${U.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=Ws(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 Bs().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,Gs.debug(`rebuilt sorted emissive data · ${U.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}};Oe();var qs=class{constructor(e=`Build`,{namespace:t=`build`,level:n=`debug`}={}){this.label=e,this.level=n,this.logger=_e(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=U.list([this.label,...e,U.ms(t)]);return this.level===`info`?this.logger.summary(r,n):this.logger.debug(U.list([r,n.join(` · `)])),{steps:Object.fromEntries(this.order.map(e=>[e,Math.round(this.entries.get(e)?.duration??0)])),total:Math.round(t)}}};mn();var Js=1<<20,Ys=1<<21,Xs=()=>new Promise(e=>setTimeout(e,0)),Zs=[0,1,2,4,5,6,8,9,10];function Qs(e,t,n,r=Zs){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 $s(e,t){let n=[],r=0;for(let{triOffset:i,triCount:a}of t)n.push(Qs(e,i,a)),r+=a,r>=Ys&&(r=0,await Xs());return n}async function ec(e,t){let n=await e?.area(pn.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 tc(e,t,{index:n,bvh:r,orders:i,isStale:a,label:o=``}){let s=e?.area(pn.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,Js),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+=Js*4)await u.write(`order.u32`,e.subarray(t,Math.min(e.length,t+Js*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 nc(e,t,n,r){for(let i=0;i<r;i+=Js){let a=Math.min(Js,r-i),o=await e.slice(i*64,(i+a)*64).arrayBuffer();t.setRecords(n+i,new Float32Array(o))}}async function rc(e,t,n){return new Uint32Array(await e.slice(t*4,(t+n)*4).arrayBuffer())}Pt();var ic=16,ac=q.POSITION_A_OFFSET,oc=q.POSITION_B_OFFSET,sc=q.POSITION_C_OFFSET;async function cc(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+ac]+o[n+oc]+o[n+sc],c[r]=o[n+ac+1]+o[n+oc+1]+o[n+sc+1],l[r]=o[n+ac+2]+o[n+oc+2]+o[n+sc+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 uc(u,o,lc(o,e,t),e,t,n),{left:f(e,n),right:f(n,t)}},p=f(0,n);return await i?.(),await dc(e,t,n,u,i),{order:u,pieces:d,tree:p}}function lc(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 uc(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 dc(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 fc(e,t,n,r){let i=t.length-1,a=[],o=i;for(let{bvhData:e}of n)a.push(o),o+=e.length/ic;let s=new Float32Array(i*ic),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];Ri(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*ic;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 pc,mc=g((()=>{pc=`11.5.0`})),hc,gc=g((()=>{mc(),hc=pc}));function _c(e,t,n=vc){return e>=n&&t/yc<e/3}var vc,yc,bc=g((()=>{vc=1e4,yc=15e5}));gc(),bc();var xc="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})}};",Sc=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,xc],{type:`text/javascript;charset=utf-8`});function Cc(e){let t;try{if(t=Sc&&(self.URL||self.webkitURL).createObjectURL(Sc),!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(xc),{type:`module`,name:e?.name})}}var wc="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})}};",Tc=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,wc],{type:`text/javascript;charset=utf-8`});function Ec(e){let t;try{if(t=Tc&&(self.URL||self.webkitURL).createObjectURL(Tc),!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(wc),{type:`module`,name:e?.name})}}dn(),Kn(),Oe(),Pt(),$t(),rn(),$r(),vn(),Dn(),ai(),Ar();var Dc=5e4,Oc=2e5,kc=2e6,Ac=1<<19,jc=4e7,Mc=1e6,Nc=1024**3,Pc=1024**3,Fc=32*1024*1024,Ic=64*1024*1024,Lc=256*1024*1024,Rc=_e(`scene`),zc=e=>Array.isArray(e)?e:[e],Bc=e=>zc(e).reduce((e,t)=>e+t.byteLength,0),Vc=64*1024*1024;async function Hc(e,t,n){for(let r of zc(n))await e.writeAt(t,r),t+=r.byteLength}function Uc(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 Wc=1024,Gc=64;function Kc(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<=Wc){i=t[e];continue}n.push({offset:r*16,count:(i-r+1)*16}),r=i=t[e]}return n.length>Gc?[{offset:t[0]*16,count:(t.at(-1)-t[0]+1)*16}]:n}var qc=class{constructor(e={}){this.config={useWorkers:!0,bvhDepth:30,maxLeafSize:4,verbose:!1,useFloat32Array:!0,textureQuality:`adaptive`,maxTextureSize:Zt.DEFAULT_MAX_TEXTURE_SIZE,enableTextureCache:!0,maxConcurrentTextureTasks:Math.min(Cr(),6),maxSceneBytes:ho,sceneCache:!0,sceneCacheMinBuildMs:vc,...e},this.triangleData=null,this.triangleFloats=null,this.triangleCount=0,this.materials=[],this.maps=[],this.normalMaps=[],this.bumpMaps=[],this.roughnessMaps=[],this.metalnessMaps=[],this.emissiveMaps=[],this.displacementMaps=[],this.anisotropyMaps=[],this.transmissionMaps=[],this.clearcoatMaps=[],this.clearcoatRoughnessMaps=[],this.sheenColorMaps=[],this.sheenRoughnessMaps=[],this.iridescenceMaps=[],this.iridescenceThicknessMaps=[],this.specularIntensityMaps=[],this.specularColorMaps=[],this.diffuseTransmissionMaps=[],this.diffuseTransmissionColorMaps=[],this.directionalLights=[],this.cameras=[],this.spheres=[],this.bvhRoot=null,this.bvh=null,this.bvhData=null,this.bvhIndexChunks=null,this.bvhIndex=null,this.materialData=null,this.instanceTable=null,this._refitWorker=null,this._refitSharedBuffers=null,this._rebuildGeneration=0,this._pendingRebuilds=new Map,this.srgbBucketTextures=null,this.linearBucketTextures=null,this.emissiveTriangleData=null,this.emissiveTriangleCount=0,this.lightBVHNodeData=null,this.lightBVHNodeCount=0,this.emissiveBitTrailMap=null,this._initProcessors(),this.isProcessing=!1,this.processingStage=null,this.memory=new xo,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 Gn({issues:this.config.issues}),this.bvhBuilder=new qi,this.bvhBuilder.maxLeafSize=this.config.maxLeafSize,this.textureCreator=new Rs({maxTextureSize:this.config.maxTextureSize,issues:this.config.issues}),this.emissiveTriangleBuilder=new Ks,this.tlasBuilder=new no,this._tlasWorker=null,this._tlasWorkerFailed=!1}_log(e,t){t===void 0?Rc.debug(e):Rc.debug(e,t)}needsSpill(e){return io(this.geometryExtractor.surveyScene(e)).total>mo}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=io(n);if(this._streaming){let t=Nc+Uc(e)*(q.FLOATS_PER_TRIANGLE*4+44);r.total=ao(r,n.placements,Math.min(r.triangles,t))}else this._progressive&&(r.total-=r.bvh);let i={...n,estimate:r,safeBytes:mo,maxBytes:t,fits:r.total<=mo};if(this.memoryPreflight=i,r.total<1610612736)return i;if(Rc.debug(U.list([`memory preflight: ${U.mb(r.total)} estimated`,`triangles ${U.mb(r.triangles)} · bvh ${U.mb(r.bvh)} · geometry ${U.mb(r.geometry)}`,`${U.n(n.triangles)} tris · ${U.n(n.placements)} placements`])),r.total>t){let e=`Scene needs about ${U.mb(r.total)} of CPU memory, past the ${U.mb(t)} a browser tab can hold — loading it would crash the tab rather than fail. Reduce the scene (it has ${U.n(n.triangles)} triangles), or raise maxSceneBytes to try anyway.`;throw this.config.issues?.record(Z.SCENE_MEMORY_BUDGET,e,{...n,estimate:r,maxBytes:t}),Error(e)}return i.fits||this.config.issues?.warn(Z.SCENE_MEMORY_BUDGET,`Scene needs about ${U.mb(r.total)} of CPU memory, above the ${U.mb(mo)} 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:mo}),i}_checkAssemblyHeadroom(e){let t=e*64;if(t<1610612736)return!0;let n=oo(Math.ceil(t*yo),{shared:cn});return this.memoryPreflight&&(this.memoryPreflight.assemblyProbed=n.placed),n.exhausted&&this.config.issues?.warn(Z.SCENE_MEMORY_BUDGET,`BVH assembly needs ${U.mb(t)} but only ${U.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?Bc(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} ${U.mb(n[e].allocated)}`),i=this.memoryPreflight?.estimate?.total;Rc.debug(U.list([`memory: peak live ${U.mb(t)}`,`allocated ${U.mb(e)}`,i?`predicted ${U.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,an(e=>this.memory.alloc(e));let r=new qs(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/(q.FLOATS_PER_TRIANGLE*4)),this._foldLeaves=i>jc,this.textureCoordinates=Ln(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=jn(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,B({status:`Building light data...`,progress:77}),r.start(`Emissive extraction + Light BVH`),this._buildEmissiveData(),r.end(`Emissive extraction + Light BVH`),a||B({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>=Pc?this._geometryOwner=e:await this._restoreGeometry(e),B({status:`Scene data ready`,progress:85}),this._blasKey&&!this._blasRestored&&this.performanceMetrics.totalProcessingTime>=this.config.sceneCacheMinBuildMs&&(this._blasStoring=this._storeBLASes(e.name??``).catch(e=>Rc.debug(`storing BLASes failed:`,e))),this}catch(e){throw this.processingStage=`error`,Rc.error(`processing failed:`,e),B({status:`Error: ${e.message}`,failed:!0,progress:100}),e}finally{this._geometryOwner||this._disposeGeometrySpill(),an(null),this._sampleMemory(`at ${this.processingStage}`),this._logMemoryReport(),this.isProcessing=!1}}async _extractGeometry(e){B({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}),B({status:`Extracted ${this.triangleCount.toLocaleString()} triangles`,progress:25})}catch(e){throw Rc.error(`geometry extraction failed:`,e),B({status:`Extraction error: ${e.message}`,failed:!0,progress:25}),e}}async _extractStreaming(e){B({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=un.lazy(o,q.FLOATS_PER_TRIANGLE,Uint32Array),c=s.recordsPerChunk*s.lanesPerRecord*4,l=await _n.create(r,`${a}:tri`,c,{label:`Triangle records`,expectedBytes:o*c/s.recordsPerChunk}),u=l&&await _n.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 En.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);Va.rootAABB(zc(r)[0],v,t.start,t.count,i,0),p.set(e,{result:n,aabb:i});let a=f.blasBytes;f.blasBytes+=Bc(r),f.blasAt.set(e,a),n.nodeCount=Bc(r)/64,n.bvhData=null,this._queueSpill(f,()=>Hc(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>Lc&&await d.written(),B({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>Nc&&(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),Rc.error(`streamed extraction failed:`,e),B({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=vt(e.triangleCount,`triangle count`),this._foldLeaves&&this.triangleCount>134217728)throw RangeError(`${this.triangleCount.toLocaleString()} triangles is past the ${Mt.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.maps=e.maps,this.normalMaps=e.normalMaps,this.bumpMaps=e.bumpMaps,this.roughnessMaps=e.roughnessMaps,this.metalnessMaps=e.metalnessMaps,this.emissiveMaps=e.emissiveMaps,this.displacementMaps=e.displacementMaps,this.anisotropyMaps=e.anisotropyMaps,this.transmissionMaps=e.transmissionMaps,this.clearcoatMaps=e.clearcoatMaps,this.clearcoatRoughnessMaps=e.clearcoatRoughnessMaps,this.sheenColorMaps=e.sheenColorMaps,this.sheenRoughnessMaps=e.sheenRoughnessMaps,this.iridescenceMaps=e.iridescenceMaps,this.iridescenceThicknessMaps=e.iridescenceThicknessMaps,this.specularIntensityMaps=e.specularIntensityMaps,this.specularColorMaps=e.specularColorMaps,this.diffuseTransmissionMaps=e.diffuseTransmissionMaps??[],this.diffuseTransmissionColorMaps=e.diffuseTransmissionColorMaps??[],this.directionalLights=e.directionalLights,this.cameras=e.cameras}async _buildBVH(){if(B({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 Va,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=no.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++,B({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,B({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??Bc(r.bvhData)/64,triOffset:t.start,triCount:t.count,originalToBvhMap:r.originalToBvh||null,bvhData:r.bvhData,matrixWorld:n?Pa: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?Pa:this.meshes?.[e]?.matrixWorld?.elements??null,t[o(e)].expandedStart,o(e))}B({status:`Built all BLASes`,progress:70}),this.performanceMetrics.blasBuildTime=performance.now()-e,B({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(no.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(un.lazy(j,16,Float32Array,void 0,cn));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 nc(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 zc(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;Rc.debug(U.list([`${U.n(A.setCount)} BLASes + TLAS`,`${U.n(this.bvh.recordCount)} nodes`,`SAH ${U.n(O.sah)} · objMed ${O.objMed} · spatMed ${O.spatMed} · failed ${O.failed}`,U.ms(I)])),B({status:`BVH construction complete`,progress:75})}catch(e){throw Rc.error(`BVH build failed:`,e),B({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:V()}}_isLargeMesh(e){return e.count>=Oc&&Ma(e.count)}async _buildLargeBLAS(e,t){if(e.count>kc)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 ka(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 cc(n,e.start,e.count,Ac,{pause:()=>new Promise(e=>setTimeout(e,0))}),o=this._blasPool(t,null,null,Math.min(Cr(),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),Va.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{...fc(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:${hc}:${JSON.stringify(t)}:${n}:${this._sceneKey}`}async _restoreBLASes(e,t,n){if(!this._sceneKey||this.config.sceneCache===!1)return null;let r=Zr(ni().cacheNamespace);if(!r)return null;this._blasKey=this._blasCacheKey(n);let i=await ec(r,this._blasKey);if(!i)return null;let a=e=>(Rc.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 $s(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 rc(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},Rc.debug(`restored ${U.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=Zr(ni().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 $s(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 tc(t,r,{index:{v:2,tlasNodeCount:n.blasBase,totalNodes:n.treeNodeCount,templates:d},bvh:this.bvh,orders:u,isStale:a,label:e});return f&&Rc.debug(`stored ${U.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 _n.create(t,`${i}:tri`,a,{label:`Triangle records`,expectedBytes:r.byteLength}),s=o&&await _n.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(zc(a)[0],t,this.triangles,i.tplObjectAABB,t*6);let o=e.blasBytes;e.blasBytes+=Bc(a),e.blasAt.set(t,o),r.nodeCount=Bc(a)/64,r.bvhData=null,this._queueSpill(e,()=>Hc(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=q.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+=Vc)i.push(new Float32Array(await e.blasStore.readAt(n+t,Math.min(Vc,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 _n.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);Ri(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=Dr(xa);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 Rc.error(`texture creation failed:`,e),e}}_bucketTextures(){let e=this.config.maxTextureSize,t=Zt.MATERIAL_BUCKET_COUNT,n=Zt.BUCKET_LAYER_STRIDE,r=e=>{let t=new Set,n=[];for(let r of e)for(let e of r||[]){if(!e?.image)continue;let r=e.source?.uuid??e.uuid;t.has(r)||(t.add(r),n.push({width:e.image.width,height:e.image.height}))}return n},i=[this.maps,this.emissiveMaps,this.sheenColorMaps,this.specularColorMaps,this.diffuseTransmissionColorMaps],a=[this.normalMaps,this.bumpMaps,this.roughnessMaps,this.metalnessMaps,this.displacementMaps,this.anisotropyMaps,this.transmissionMaps,this.clearcoatMaps,this.clearcoatRoughnessMaps,this.sheenRoughnessMaps,this.iridescenceMaps,this.iridescenceThicknessMaps,this.specularIntensityMaps,this.diffuseTransmissionMaps],o=Jt(r(i),e,t),s=Jt(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(Z.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=Yt(e.image.width,e.image.height,a),s=e.source?.uuid??e.uuid,c=r[o].get(s);if(c!==void 0)return Xt(o,c);if(t[o].length>=n)return Rc.warn(`texture bucket ${o} full (${n}); dropping a map`),f||this.config.issues?.record(Z.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=Xt(o,l);return i.set(s,u),u},h=(e,t,n,r,i)=>(e||[]).map(e=>m(e,t,n,r,i));return{srgbLists:c,linearLists:l,remap:{albedo:h(this.maps,c,u,this._srgbTexPacked,o),emissive:h(this.emissiveMaps,c,u,this._srgbTexPacked,o),normal:h(this.normalMaps,l,d,this._linearTexPacked,s),bump:h(this.bumpMaps,l,d,this._linearTexPacked,s),roughness:h(this.roughnessMaps,l,d,this._linearTexPacked,s),metalness:h(this.metalnessMaps,l,d,this._linearTexPacked,s),displacement:h(this.displacementMaps,l,d,this._linearTexPacked,s),anisotropy:h(this.anisotropyMaps,l,d,this._linearTexPacked,s),transmission:h(this.transmissionMaps,l,d,this._linearTexPacked,s),clearcoat:h(this.clearcoatMaps,l,d,this._linearTexPacked,s),clearcoatRoughness:h(this.clearcoatRoughnessMaps,l,d,this._linearTexPacked,s),sheenColor:h(this.sheenColorMaps,c,u,this._srgbTexPacked,o),sheenRoughness:h(this.sheenRoughnessMaps,l,d,this._linearTexPacked,s),iridescence:h(this.iridescenceMaps,l,d,this._linearTexPacked,s),iridescenceThickness:h(this.iridescenceThicknessMaps,l,d,this._linearTexPacked,s),specularIntensity:h(this.specularIntensityMaps,l,d,this._linearTexPacked,s),specularColor:h(this.specularColorMaps,c,u,this._srgbTexPacked,o),diffuseTransmission:h(this.diffuseTransmissionMaps,l,d,this._linearTexPacked,s),diffuseTransmissionColor:h(this.diffuseTransmissionColorMaps,c,u,this._srgbTexPacked,o)}}}_remapMaterialTextureIndices(e){let t=(e,t)=>e>=0&&e<t.length?t[e]:-1;for(let n of this.materials)n.map=t(n.map,e.albedo),n.emissiveMap=t(n.emissiveMap,e.emissive),n.normalMap=t(n.normalMap,e.normal),n.bumpMap=t(n.bumpMap,e.bump),n.roughnessMap=t(n.roughnessMap,e.roughness),n.metalnessMap=t(n.metalnessMap,e.metalness),n.displacementMap=t(n.displacementMap,e.displacement),n.anisotropyMap=t(n.anisotropyMap,e.anisotropy),n.transmissionMap=t(n.transmissionMap,e.transmission),n.clearcoatMap=t(n.clearcoatMap,e.clearcoat),n.clearcoatRoughnessMap=t(n.clearcoatRoughnessMap,e.clearcoatRoughness),n.sheenColorMap=t(n.sheenColorMap,e.sheenColor),n.sheenRoughnessMap=t(n.sheenRoughnessMap,e.sheenRoughness),n.iridescenceMap=t(n.iridescenceMap,e.iridescence),n.iridescenceThicknessMap=t(n.iridescenceThicknessMap,e.iridescenceThickness),n.specularIntensityMap=t(n.specularIntensityMap,e.specularIntensity),n.specularColorMap=t(n.specularColorMap,e.specularColor),n.diffuseTransmissionMap=t(n.diffuseTransmissionMap,e.diffuseTransmission),n.diffuseTransmissionColorMap=t(n.diffuseTransmissionColorMap,e.diffuseTransmissionColor)}_buildEmissiveData(){this.emissiveTriangleCount=this.emissiveTriangleBuilder.extractEmissiveTriangles(this.triangles,this.materials,this.triangleCount,this.instanceTable??null),this.emissiveTriangleData=this.emissiveTriangleBuilder.createEmissiveRawData(),this.emissiveTotalPower=this.emissiveTriangleBuilder.totalEmissivePower,this._log(`Emissive triangle extraction complete`,this.emissiveTriangleBuilder.getStats()),this.emissiveTriangleBuilder.buildLightBVH(),this.lightBVHNodeData=this.emissiveTriangleBuilder.lightBVHNodeData,this.lightBVHNodeCount=this.emissiveTriangleBuilder.lightBVHNodeCount,this.emissiveTriangleData=this.emissiveTriangleBuilder.emissiveTriangleData||this.emissiveTriangleData,this.emissiveBitTrailMap=this.emissiveTriangleBuilder.emissiveBitTrailMap,this.emissiveTriangleCount=this.emissiveTriangleBuilder.emissiveCount,this.emissiveTotalPower=this.emissiveTriangleBuilder.totalEmissivePower}_createSpheres(){return[]}_reset(){this._geometryVersion=(this._geometryVersion??0)+1,this._disposeSpill(),this._disposeGeometrySpill(),this._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.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){Rc.warn(`error disposing ${e}:`,t)}this[e]=null}}}async rebuildMaterials(e){if(this.isProcessing)throw Error(`Already processing. Cannot rebuild materials during processing.`);this._log(`Rebuilding materials and textures`);let t=performance.now();try{this.isProcessing=!0;let n=this.geometryExtractor.extractMaterialsOnly(e);this._disposeMaterialTextures(),this.materials=n.materials,this.meshes=n.meshes,this.maps=n.maps,this.normalMaps=n.normalMaps,this.bumpMaps=n.bumpMaps,this.roughnessMaps=n.roughnessMaps,this.metalnessMaps=n.metalnessMaps,this.emissiveMaps=n.emissiveMaps,this.displacementMaps=n.displacementMaps,await this._createMaterialTextures();let r=performance.now()-t;return this._log(`Material rebuild complete (${r.toFixed(2)}ms)`,{materials:this.materials.length,textures:this.maps.length}),this}catch(e){throw Rc.error(`material rebuild failed:`,e),e}finally{this.isProcessing=!1}}_disposeMaterialTextures(){this._disposeBucketTextures(),this.textureCreator&&this.textureCreator.textureCache&&(this.textureCreator.textureCache.dispose(),this.textureCreator.textureCache=new this.textureCreator.textureCache.constructor)}getStatistics(){let e={triangleCount:this.triangleCount,materialCount:this.materials.length,textureCount:this.maps.length,lightCount:this.directionalLights.length,cameraCount:this.cameras.length,processingComplete:this.processingStage===`complete`,hasBVH:!!this.bvhRoot,hasTextures:!!this.materialData&&!!this.bvh,useFloat32Array:this.config.useFloat32Array,triangleDataSize:this.triangles?(this.triangles.byteLength/(1024*1024)).toFixed(2)+`MB`:`0MB`};return this.performanceMetrics.totalProcessingTime>0&&(e.performance={totalTime:this.performanceMetrics.totalProcessingTime,textureTime:this.performanceMetrics.textureCreationTime,bvhTime:this.performanceMetrics.bvhBuildTime,extractionTime:this.performanceMetrics.geometryExtractionTime,texturePercentage:(this.performanceMetrics.textureCreationTime/this.performanceMetrics.totalProcessingTime*100).toFixed(1)+`%`}),this.textureCreator&&this.textureCreator.capabilities&&(e.textureCapabilities=this.textureCreator.capabilities),e}updateConfig(e){Object.assign(this.config,e),this.bvhBuilder&&(this.bvhBuilder.maxLeafSize=this.config.maxLeafSize),this._log(`Configuration updated`,this.config)}_adoptSharedChunks(e,t){let n=this[e];if(n.shared)return;let r=n.chunks.map(e=>{let n=new t(new SharedArrayBuffer(e.byteLength));return n.set(e),n}),i=un.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||=Dr(Cc),!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=q.FLOATS_PER_TRIANGLE,o=[],s=[],c=0;for(let e=0;e<i.count;e++){if(!i.isSet[e]||!i.isOwner(e))continue;c++;let t=n(e);if(!t)continue;if(this._updateMeshTrianglePositions(e,t),s.push(i.blasOffsetOf(e),i.blasNodeCountOf(e)),r){let t=r(e);t&&this._patchMeshSmoothNormals(e,t)}let l=i.triOffsetOf(e)*a,u=i.triCountOf(e)*a,d=o.at(-1);d&&d.offset+d.count===l?d.count+=u:o.push({offset:l,count:u})}let l=i.tlasNodeCount,u=l>0&&s.length/2<c,d=u?[this.computeTLASDirtyRange()]:null;for(let e=0;u&&e<s.length;e+=2)d.push({offset:s[e]*16,count:s[e+1]*16});return new Promise((e,t)=>{this._refitWorker.onmessage=n=>{let r=n.data;r.type===`refitComplete`?e({refitTimeMs:r.refitTimeMs,triRanges:o,bvhRanges:d}):r.type===`error`&&t(Error(r.error))},this._refitWorker.postMessage({type:`refit`,blasRanges:u?s:null,tlasNodeCount:l,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 va;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(Z.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?(La(o,s,e*16,r),n.setPlacementMatrix(t,r)):c?(La(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}}_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}no.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=Ra(n.matrixWorldOf(t));o[s]=(o[s]&~St|(c?St: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=q.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)):Rc.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):(Rc.error(`failed to get BVH data`),!1)):(Rc.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 _n.create(e,`${a}:tri`,o(t),{label:`Triangle records`,expectedBytes:t.byteLength}),c=s&&await _n.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 Rc.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 En.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,Rc.info(`${U.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});Rc.info(`spilled ${U.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 _n.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(Fc),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>Ic){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(Ic,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||B({status:`Reading scene geometry back...`,progress:84});let n=performance.now(),r=t.bytes;await t.restore(),this._disposeGeometrySpill(),this._geometryBytes=jn(e),Rc.info(`read ${U.mb(r)} of scene geometry back from disk in ${U.ms(performance.now()-n)}`),t.error&&Rc.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>=Mc: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>=Dc&&!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 no.fillLeaves(i,a,e),i}catch(e){this._tlasWorkerFailed=!0,Rc.warn(`TLAS worker unavailable (${e.message}); building on the main thread`)}return this.tlasBuilder.build(e).data}_runTLASWorker(e,t){this._tlasWorker||=Dr(Ec);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:V()},[e.buffer])})}_setBVHData(e){let t=e?e instanceof un?e:un.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=q.FLOATS_PER_TRIANGLE,n=e?e instanceof un?e:un.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=q.POSITION_A_OFFSET,r=q.POSITION_B_OFFSET,i=q.POSITION_C_OFFSET,a=q.NORMAL_A_PACKED_OFFSET,o=q.NORMAL_B_PACKED_OFFSET,s=q.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=Ra(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=pt(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=q.NORMAL_A_PACKED_OFFSET,o=q.NORMAL_B_PACKED_OFFSET,s=q.NORMAL_C_PACKED_OFFSET,c=r,l=!c||Ra(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]]=pt(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===wt.BLAS_POINTER_LEAF){let n=e[p+1]&Ct;if(n>=t.entryCount)continue;t.writeEntryWorldAABB(n,c,0)}else if(i===wt.CLUSTER_LEAF)t.encodeClusterBoxes(f,e,p,t.clusterOf(e[p]&Tt),null,c,0);else if(i<wt.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=Kc(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){Rc.error(`background BLAS rebuild failed (mesh ${e}):`,o.error);return}n===this._rebuildGeneration&&this._swapBLAS(e,r,o,t)},i.onerror=t=>{Rc.error(`background BLAS rebuild worker failed (mesh ${e}):`,t),i.terminate(),this._pendingRebuilds.delete(e)},i.postMessage({triangleData:a.buffer,triangleByteOffset:a.byteOffset,triangleByteLength:a.byteLength,triangleCount:r.triCount,depth:this.config.bvhDepth,maxLeafSize:this.bvhBuilder.maxLeafSize,numBins:this.bvhBuilder.numBins,maxBins:this.bvhBuilder.maxBins,minBins:this.bvhBuilder.minBins,reportProgress:!1,sharedReorderBuffer:null,reinsertionOptimization:{enabled:this.bvhBuilder.enableReinsertionOptimization,batchSizeRatio:this.bvhBuilder.reinsertionBatchSizeRatio,maxIterations:this.bvhBuilder.reinsertionMaxIterations}},[a.buffer])};for(let t of e){let e=this._placementOf(t);if(e<0)continue;let n=this.instanceTable.entryAt(e);if(!n||!this.instanceTable.isOwner(e))continue;let i=this._pendingRebuilds.get(e);i&&i.terminate(),r(e,n,Dr(xa))}}_swapBLAS(e,t,n,r){this._geometryVersion=(this._geometryVersion??0)+1;let i=n.bvhData,a=i.length/16;if(a>t.blasNodeCount){Rc.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}},Jc=[[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]],Yc=[[-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]],Xc=[[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 Zc(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=Jc[i],o=Yc[i],s=Xc[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)]}er();var Qc=1/(4*Math.PI);function $c(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]=Zc(t.temperature??6500);i[0]*=e,i[1]*=n,i[2]*=r}return Xn(i),{r:i[0],g:i[1],b:i[2],intensity:r}}var el=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=$c(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=$c(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=$c(e);this.pointLightCache.push({data:[t.x,t.y,t.z,i.r,i.g,i.b,i.intensity*Qc,e.distance||0,e.decay===void 0?2:e.decay],importance:n,light:e})}addSpotLight(e){if(!e.visible||e.intensity<=0)return;e.updateMatrixWorld();let t=e.getWorldPosition(new r.Vector3),n=(e.target?e.target.getWorldPosition(new r.Vector3):new r.Vector3(0,0,-1)).sub(t).normalize(),i=this.calculateLightImportance(e,`spot`),a=e.userData?.gobo,o=a&&Number.isInteger(a.index)?a.index:-1,s=a&&typeof a.intensity==`number`?a.intensity:1,c=a&&a.inverted?-Math.abs(s):Math.abs(s),l=e.userData?.ies,u=l&&Number.isInteger(l.index)?l.index:-1,d=l&&typeof l.intensity==`number`?l.intensity:1,f=$c(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*Qc,e.angle||Math.PI/4,e.penumbra||0,e.distance||0,e.decay===void 0?2:e.decay,o,c,u,d,0,0],importance:i,light:e})}preprocessLights(){this.directionalLightCache.sort((e,t)=>t.importance-e.importance),this.areaLightCache.sort((e,t)=>t.importance-e.importance),this.pointLightCache.sort((e,t)=>t.importance-e.importance),this.spotLightCache.sort((e,t)=>t.importance-e.importance),this.lightData.directional=[],this.lightData.rectArea=[],this.lightData.point=[],this.lightData.spot=[],this.directionalLightCache.forEach(e=>{this.lightData.directional.push(...e.data)}),this.areaLightCache.forEach(e=>{this.lightData.rectArea.push(...e.data)}),this.pointLightCache.forEach(e=>{this.lightData.point.push(...e.data)}),this.spotLightCache.forEach(e=>{this.lightData.spot.push(...e.data)}),this.areaLightCache.length>0&&console.log(`Preprocessed ${this.areaLightCache.length} area lights by importance`),this.pointLightCache.length>0&&console.log(`Preprocessed ${this.pointLightCache.length} point lights by importance`),this.spotLightCache.length>0&&console.log(`Preprocessed ${this.spotLightCache.length} spot lights by importance`)}updateShaderUniforms(e){let t=Math.floor(this.lightData.directional.length/12),n=Math.floor(this.lightData.rectArea.length/16),r=Math.floor(this.lightData.point.length/9),i=Math.floor(this.lightData.spot.length/20);e.defines.MAX_DIRECTIONAL_LIGHTS=t,e.defines.MAX_AREA_LIGHTS=n,e.defines.MAX_POINT_LIGHTS=r,e.defines.MAX_SPOT_LIGHTS=i,e.uniforms.directionalLights.value=new Float32Array(this.lightData.directional),e.uniforms.areaLights.value=new Float32Array(this.lightData.rectArea),e.uniforms.pointLights.value=new Float32Array(this.lightData.point),e.uniforms.spotLights.value=new Float32Array(this.lightData.spot),e.needsUpdate=!0}processSceneLights(e,t){this.clear(),e.traverse(e=>{e.isDirectionalLight?this.addDirectionalLight(e):e.isRectAreaLight?this.addRectAreaLight(e):e.isPointLight?this.addPointLight(e):e.isSpotLight&&this.addSpotLight(e)}),this.preprocessLights(),this.updateShaderUniforms(t)}getLightStatistics(){return{directionalLights:this.directionalLightCache.map(e=>({intensity:e.light.intensity,importance:e.importance,color:e.light.color})),areaLights:this.areaLightCache.map(e=>({intensity:e.light.intensity,importance:e.importance,color:e.light.color,size:e.light.width*e.light.height}))}}},tl,nl,rl,il,al,ol,sl,cl,ll,ul,dl,fl,pl,ml,hl,gl,_l=g((()=>{tl=x({origin:`vec3`,direction:`vec3`}),nl=x({color:`vec4`,emissive:`vec3`,emissiveIntensity:`float`,roughness:`float`,metalness:`float`,ior:`float`,transmission:`float`,thickness:`float`,clearcoat:`float`,clearcoatRoughness:`float`,opacity:`float`,transparent:`bool`,attenuationColor:`vec3`,attenuationDistance:`float`,dispersion:`float`,sheen:`float`,sheenRoughness:`float`,sheenColor:`vec3`,specularIntensity:`float`,specularColor:`vec3`,alphaTest:`float`,alphaMode:`int`,side:`int`,depthWrite:`int`,albedoMapIndex:`int`,emissiveMapIndex:`int`,normalMapIndex:`int`,bumpMapIndex:`int`,bumpScale:`float`,displacementScale:`float`,metalnessMapIndex:`int`,roughnessMapIndex:`int`,displacementMapIndex:`int`,normalScale:`vec2`,albedoTransform:`mat3`,emissiveTransform:`mat3`,normalTransform:`mat3`,bumpTransform:`mat3`,metalnessTransform:`mat3`,roughnessTransform:`mat3`,displacementTransform:`mat3`,iridescence:`float`,iridescenceIOR:`float`,iridescenceThicknessRange:`vec2`,subsurface:`float`,subsurfaceColor:`vec3`,subsurfaceRadius:`vec3`,subsurfaceRadiusScale:`float`,subsurfaceAnisotropy:`float`,anisotropy:`float`,anisotropyRotation:`float`,anisotropyMapIndex:`int`,transmissionMapIndex:`int`,clearcoatMapIndex:`int`,clearcoatRoughnessMapIndex:`int`,sheenColorMapIndex:`int`,sheenRoughnessMapIndex:`int`,iridescenceMapIndex:`int`,iridescenceThicknessMapIndex:`int`,specularIntensityMapIndex:`int`,specularColorMapIndex:`int`,diffuseTransmission:`float`,diffuseTransmissionColor:`vec3`,diffuseTransmissionMapIndex:`int`,diffuseTransmissionColorMapIndex:`int`}),rl=x({transmission:`float`,clearcoat:`float`,clearcoatRoughness:`float`,sheenColor:`vec3`,sheenRoughness:`float`,iridescence:`float`,iridescenceThickness:`float`,specularIntensity:`float`,specularColor:`vec3`,diffuseTransmission:`float`,diffuseTransmissionColor:`vec3`}),il=x({color:`vec4`,ior:`float`,transmission:`float`,attenuationColor:`vec3`,attenuationDistance:`float`,albedoMapIndex:`int`,opacity:`float`,transparent:`bool`,alphaTest:`float`,alphaMode:`int`,albedoTransform:`mat3`}),al=x({shadowed:`vec3`,unoccluded:`vec3`}),x({position:`vec3`,radius:`float`,material:nl}),ol=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:nl,materialIndex:`int`,meshIndex:`int`}),x({color:`vec4`,samples:`int`}),sl=x({direction:`vec3`,value:`vec3`,pdf:`float`,isTransmission:`bool`,colorWeight:`vec3`,isDiffuseTransmission:`bool`}),cl=x({specular:`float`,diffuse:`float`,sheen:`float`,clearcoat:`float`,transmission:`float`,iridescence:`float`,diffuseTransmission:`float`}),ll=x({Ta:`vec3`,Ba:`vec3`}),ul=x({NoL:`float`,NoV:`float`,NoH:`float`,VoH:`float`,LoH:`float`,ToH:`float`,BoH:`float`,ToV:`float`,BoV:`float`,ToL:`float`,BoL:`float`}),dl=x({compensation:`vec3`,E_total:`vec3`}),fl=x({f0:`vec3`,f90:`float`,eta:`float`,F0m:`vec3`,F0:`vec3`}),pl=x({albedo:`vec4`,emissive:`vec3`,metalness:`float`,roughness:`float`,normal:`vec3`,hasTextures:`bool`}),ml=x({isMetallic:`bool`,isRough:`bool`,isSmooth:`bool`,isTransmissive:`bool`,hasClearcoat:`bool`,isEmissive:`bool`,complexityScore:`float`}),hl=x({albedoUV:`vec2`,normalUV:`vec2`,metalnessUV:`vec2`,emissiveUV:`vec2`,bumpUV:`vec2`,roughnessUV:`vec2`,normalBumpSameUV:`bool`,metalRoughSameUV:`bool`,albedoEmissiveSameUV:`bool`,allSameUV:`bool`}),gl=x({invRoughness:`float`,metalFactor:`float`,iorFactor:`float`,maxSheenColor:`float`}),x({traversals:`int`,transmissiveTraversals:`int`,rayType:`int`,isPrimaryRay:`bool`,actualBounceDepth:`int`})}));function vl(e,t,n){return e.length===1?e[0]:{isSplitStorage:!0,parts:e,perPart:t,type:n,value:e[0].value}}function yl(e,t){if(!e.isSplitStorage)return e.element(t);let{parts:r,perPart:i}=e,a=(0,n.int)(t).toVar(),o=({uvec4:n.uvec4,uvec2:n.uvec2}[e.type]??n.vec4)(0).toVar(),s=e=>()=>o.assign(r[e].element(e===0?a:a.sub((0,n.int)(i*e)))),c=(0,n.If)(a.lessThan((0,n.int)(i)),s(0));for(let e=1;e<r.length-1;e++)c=c.ElseIf(a.lessThan((0,n.int)(i*(e+1))),s(e));return c.Else(s(r.length-1)),o}var bl,xl,Sl,Cl,wl,Tl,El,Dl,Ol,kl,Al,jl,Ml,Nl,Pl,Fl,Il,Ll,Rl,zl,Bl,Vl,Hl,Ul,Wl,Gl,Kl,ql,Jl,Q,Yl,Xl,Zl,Ql,$l,eu,tu,nu,ru,iu,au,ou,su,cu=g((()=>{_l(),Pt(),bl=(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 );
|
|
@@ -915,7 +915,7 @@ fn main( @builtin(global_invocation_id) gid: vec3<u32> ) {
|
|
|
915
915
|
let rgb = linear.rgb${r?` * rayzee_gain( uv, linear.rgb, params.exposure )`:``};
|
|
916
916
|
rayzee_store( gid.y * params.width + gid.x, linear, rayzee_tone_map( rgb, params.mode, params.exposure, params.saturation ) );
|
|
917
917
|
}
|
|
918
|
-
`,mv=32,hv=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(mv),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}=sv();this._shaderVersion!==r&&(this._pipelines.clear(),this._bindings=n,this._shaderVersion=r);let i=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:pv(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*fv[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:mv,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,{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*fv[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.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&&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()}}}}));gv(),ps(),er(),rn();var _v=class{constructor({issues:e=null}={}){this._issues=e,this._renderer=null,this._offRegistry=qo(()=>{this._renderer&&ts(this._renderer)})}get hasConfig(){return!1}get workingSpace(){return Kr}get workingSpaceAdopted(){return!1}get inputKey(){return`-`}attachRenderer(e){this._renderer=e;let t=ts(e);return e.outputColorSpace=r.SRGBColorSpace,t}listViews(){return Yo()}get activeView(){return null}setActiveView(e){let t=Jo(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(){qn(null,Kr)}loadConfig(){let e=`colour configs need the OCIO pipeline: renderer.setColorManagement( ColorManagement ), from rayzee/addons/color`;return this._issues?.record(Z.CAPABILITY_MISSING,e,{capability:`color`}),Promise.reject(Error(e))}unloadConfig(){}setWorkingSpace(){}exportPixels(e){return{rgba:e,colorSpace:Kr}}status(){let e=this._renderer?Jo(this._renderer.toneMapping):null;return{config:null,workingSpace:Kr,workingSpaceAdopted:!1,activeTransform:e?{id:e.id,name:e.name,source:e.source}:null,activeView:null,context:null,exportSpace:null,views:Yo(),registryVersion:Ko(),bakeError:e?.error??null}}dispose(){this._offRegistry?.(),this._renderer=null,this._issues=null,Jr()===this&&(qn(null),Yr(null))}};Ar();var vv=[[/\.jpe?g(\?|#|$)/i,`image/jpeg`],[/\.webp(\?|#|$)/i,`image/webp`],[/\.avif(\?|#|$)/i,`image/avif`]];function yv(e){return e.mimeType?e.mimeType:e.uri?.startsWith(`data:`)?e.uri.slice(5,e.uri.indexOf(`;`)):vv.find(([t])=>t.test(e.uri??``))?.[1]??`image/png`}function bv(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 xv({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 Sv(e,t){return Sr().decodeImage(t===`image/png`?bv(e):e,t)}async function Cv(e){let t=await fetch(e);if(!t.ok)throw Error(`HTTP ${t.status}`);return new Uint8Array(await t.arrayBuffer())}function wv(e,t){return t.bufferView===void 0?Cv(e.options.manager.resolveURL(r.LoaderUtils.resolveURL(t.uri,e.options.path))):e.getDependency(`bufferView`,t.bufferView).then(e=>new Uint8Array(e))}var Tv=(e,t)=>!!t&&t!==e.textureLoader&&typeof t.parse==`function`;function Ev(e,t,n){if(e.sourceCache[t]!==void 0)return e.sourceCache[t].then(e=>e.clone());let r=wv(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 Dv(e,t=yv({uri:e})){let n=xv(await Sv(await Cv(e),t));return n.flipY=!0,n}function Ov(e,t=null){return e.loadImageSource=function(e,n){if(Tv(this,n))return Ev(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 kv(e,t=null){return e.loadImageSource=function(e,n){if(Tv(this,n))return Ev(this,e,n);if(this.sourceCache[e]!==void 0)return this.sourceCache[e].then(e=>e.clone());let r=this.json.images[e],i=yv(r),a=r.uri??`bufferView ${r.bufferView}`,o=wv(this,r).then(e=>Sv(e,i)).then(e=>{let t=xv(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 Av=`KHR_materials_diffuse_transmission`;function jv(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:Av,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?.[Av];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)}}}ai();var Mv=`KHR_draco_mesh_compression`,Nv=`KHR_texture_basisu`,Pv=[`EXT_meshopt_compression`,`KHR_meshopt_compression`],Fv=new TextDecoder;function Iv(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 Fv.decode(e);let n=Math.min(t.getUint32(12,!0),e.byteLength-20);return Fv.decode(new Uint8Array(e,20,n))}async function Lv(e,t,n){let{dracoDecoderPath:r,ktx2TranscoderPath:i}=ni(),[a,o,s]=await Promise.all([t.includes(Mv)&&!e.dracoLoader?import(`three/addons/loaders/DRACOLoader.js`):null,t.includes(Nv)&&!e.ktx2Loader?import(`three/addons/loaders/KTX2Loader.js`):null,Pv.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 Rv(e,t){let n=e.parse.bind(e);return e.parse=(r,i,a,o)=>{Lv(e,Iv(r),t).then(()=>n(r,i,a,o),e=>o?.(e))},e}function zv(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 Bv(e){let t=typeof e==`string`?parseFloat(e):e;return Number.isFinite(t)?t:void 0}function Vv(e){let t=zv(e);if(!t)return null;let n=e=>e&&(e.environment!==void 0||e.render!==void 0),r=zv(t.rayzee);return n(r)?r:n(t)?t:null}function Hv(e){let t=zv(e);if(!t)return null;let n=Kv.map(e=>t[e]).find(e=>typeof e==`string`&&e.trim());if(!n)return null;let r=Bv(t.rotation),i=Bv(t.intensity),a={sourceFile:n.trim()};return r!==void 0&&(a.rotation=r),i!==void 0&&(a.intensity=Math.max(0,i)),a}function Uv(e){let t=zv(e);if(!t)return null;let n={};for(let e of qv){let r=Bv(t[e]);r!==void 0&&r>0&&(n[e]=Math.round(r))}return Object.keys(n).length?n:null}function Wv(e){let t=Vv(e);if(!t)return null;let n=Hv(t.environment),r=Uv(t.render);return!n&&!r?null:{...n?{environment:n}:{},...r?{render:r}:{}}}function Gv(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=Wv(e);if(t)return t}return null}var Kv,qv,Jv=g((()=>{Kv=[`sourceFile`,`url`,`file`],qv=[`maxBounces`,`samples`,`width`,`height`]}));mi(),ue(),Ar(),Jv(),rn(),at(),Oe();var Yv=_e(`assets`),Xv={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`}},Zv={addOn:`rayzee/addons/archives`,install:`assetLoader.setArchiveImporter()`},Qv={addOn:`rayzee/addons/formats`,install:`assetLoader.registerFormat()`},$v={zip:Zv,gz:Zv,tgz:Zv,tar:Zv,fbx:Qv,obj:Qv,stl:Qv,ply:Qv,dae:Qv,"3mf":Qv,usd:Qv,usda:Qv,usdc:Qv,usdz:Qv,exr:Qv};function ey(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 ty=683;function ny(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 ry=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??(()=>K.areaLightIntensityScale),this._loadingManager.onError=e=>{this._loadCancelled||this._issues?.record(Z.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 L_(t,{downloads:this.downloads,key:i,policy:a,name:A_(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 P_(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;B({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){B({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 Xv[t]||this._formats.get(t)||this._archiveFormats?.[t]||null}formatError(e){let t=$v[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)}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);B({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 ${Zv.addOn} — install it with ${Zv.install}`);B({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=A_(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,B({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`,W_(await H_(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{B({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,B({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 oi(r,W_(await H_(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)&&oi(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&&$v[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):Sr().decodeImage?(d=await Dv(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&&iy(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=Rv(new o.GLTFLoader(this._loadingManager),this.renderer),t=(e,t)=>this._reportImageFailure(e,t);return Sr().decodeImage?e.register(e=>kv(e,t)):wr()||e.register(e=>Ov(e,t)),e.register(e=>jv(e)),e}_reportImageFailure(e,t){try{this._issues?.record(Z.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{B({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 Er(()=>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=Gv(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{B({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 Er(()=>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?(re(e),e.parent?.remove(e)):ne(e))}async loadGLBFromArrayBuffer(e,t=`model.glb`){let n=await this.createGLTFLoader();try{B({isLoading:!0,status:`Processing GLB Data...`,progress:5}),await new Promise(e=>setTimeout(e,0));let r=await Er(()=>n.parseAsync(e,``));return this._throwDeferred(),this.releaseTargetModel(),this.targetModel=r.scene,this.animations=r.animations||[],this.sceneMetadata=Gv(r),B({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,B({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 qs(`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*=ny(e,e.width,e.height,i),i.__radianceConverted=!0),(e.isPointLight||e.isSpotLight)&&!i.__candelaConverted&&(e.intensity*=4*Math.PI/ty,i.__candelaConverted=!0),e.isDirectionalLight&&!i.__luxConverted&&(e.intensity/=ty,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*ny(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(Z.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=ey(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={...Xv,...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 iy(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,Yv.info(`environment ${r}×${i} shrunk to ${o}×${s} (memory spill)`)}var ay={addEventListener(){},removeEventListener(){},dispatchEvent(){return!0}},oy=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 sy(e=1,t=1){let n={...ay,defaultView:null},r={...ay,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 oy(r);return r}var cy=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`,uy={DirectionalLight:r.DirectionalLight,PointLight:r.PointLight,SpotLight:r.SpotLight,RectAreaLight:r.RectAreaLight},dy=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:tr(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=uy[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=nr(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}};at(),Pt(),Kn(),ue(),Oe(),F(),rn(),ai(),Z_(),ps(),So(),gc();var fy=({element:e,pbrtEntry:t}={})=>({...e===void 0?{}:{element:e},...t===void 0?{}:{pbrtEntry:t}}),py=new WeakMap,my=3e4,hy=new Set([...Object.values(N),...Object.values(P)]),gy=new Set;async function _y(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 vy=_e(`engine`);function yy(){let e=new Float32Array(16);return new Uint32Array(e.buffer)[3]=wt.TRIANGLE_LEAF,e}function by(e,t){e.lost.then(e=>{t.app&&t.app._handleDeviceLost(e)})}var xy=/swiftshader|llvmpipe|lavapipe|basic render|microsoft basic|warp/i;function Sy(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 Cy=class extends r.EventDispatcher{constructor(e,t={}){super(),this._headless=t.headless===!0||!e,e??=sy();try{py.get(e)?.dispose()}catch(e){vy.warn(`prior canvas owner dispose failed`,e)}if(py.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 nn({strict:t.strict===!0,onIssue:e=>this.dispatchEvent({type:N.ISSUE,issue:e})}),this.color=new _v({issues:this._issues}),Yr(this.color),this.settings=new ov(K,{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 C_,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){vy.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(q.FLOATS_PER_TRIANGLE),0),this.stages.pathTracer.setBVHData(yy()),this.stages.pathTracer.materialData.setMaterialData(new Float32Array(16)),this.stages.pathTracer.setupMaterial(),this.isInitialized=!0,vy.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&&!ti(`storage`)?!1:ni().storage);if(e!==!1){if(e&&typeof e==`object`)this.storage=e;else{if(!this._storageOpener){(this._storageOption!==void 0||ti(`storage`))&&this._issues.warn(Z.CAPABILITY_MISSING,`on-disk storage needs rayzee/addons/storage: setStorageOpener( acquireSharedStorage )`);return}let{storage:e,reason:t,release:n}=await this._storageOpener(ni().cacheNamespace);if(this._disposed){n();return}if(!e){this._issues.warn(Z.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){!hy.has(e)&&!gy.has(e)&&(gy.add(e),vy.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(),le({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,vy.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){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])ne(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){vy.warn(`failed to clear TSL texture singleton listeners`,e)}this.canvas&&py.get(this.canvas)===this&&py.delete(this.canvas),this._gpuDevice&&=(this._gpuDevice.onuncapturederror=null,null),this._deviceLostHolder&&=(this._deviceLostHolder.app=null,null),te(this.renderer),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(q.FLOATS_PER_TRIANGLE),0),this.stages.pathTracer.setBVHData(yy()),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??A_(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,...fy(t)});return}if(tv(e)){let n=Q_(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 U_(n);return{kind:`local-folder`,folder:e,key:W_(e),...n.flat?{flat:!0}:{},...fy(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=H_(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?W_(e):null,...fy(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&&!tv(this._sceneSourceInput)?this._sceneSourceInput:null}get sceneSourceFolder(){return tv(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?vo:0);try{await e(),this._sceneSource=typeof n==`function`?await n():n,this._sceneSourceInput=null,this._emissiveSamplingUserSet=!1,this._clearAppendedModels(),this._modelReplaced(),this._planSpill(),await this.loadSceneData({pendingEnvironment:this._beginSceneMetadataEnvironment()}),this._maybeSpill(),this.pipeline?.eventBus.emit(`pipeline:lightingChanged`),this._dropDisplay(),this.reset(),this.dispatchEvent(t),this._modelAnnounced()}catch(e){throw(!e||e.code!==`LOAD_IN_PROGRESS`)&&this._discardFailedLoad(),e?.code===`ARCHIVE_NEEDS_ELEMENT`?ce():e?.code!==`LOAD_IN_PROGRESS`&&B({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(Z.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 qs(``,{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(Z.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)`),B({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`),B({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&&(B({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()),ce(),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[U.count(e.triangleCount,`tri`),t?U.count(t,`mesh`,`meshes`):null,U.count(e.materialData.materialCount,`material`),n?U.count(n,`map`):null,U.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:go,maxPlacements:_o,...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?vo:0);let t=e?this.meshScene?.environment:null,n=t?.image;return n&&iy(t,vo),t&&t.image!==n&&(t.dispose(),t.needsUpdate=!0),e&&this._memorySpill===`auto`&&vy.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(Z.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(Z.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(Z.STORAGE_WRITE_FAILED,`memory spill failed: ${e.message}`))},my),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(Z.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,W);if(!this.renderer)return this._pendingReservedRenderSize={requestedPx:e,allowLower:t},Math.max(256,Math.min(ke,Math.floor(n)||256));let r=this.renderer.backend?.device?.limits?.maxStorageBufferBindingSize||128*1024*1024,i=ro(this._hostMemoryGB),a=i.gb>=8&&r>=1024*1024*1024?ke:2048,o=Ae(Math.min(n,a));if(o<Math.floor(e)&&this._issues.warn(Z.RENDER_RESERVE_CAPPED,`reserved render size ${U.n(e)}px was capped to ${U.n(o)}px by this device's limits — renders above ${U.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 W}_isRenderSizeSupported(e,t){return e>W||t>W?(this._issues.record(Z.RENDER_SIZE_DECLINED,`render resolution ${e}×${t} exceeds the ${W}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:W}),!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 tr({engine:hc,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:hc,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;if(e===`srgb`){let r=n===`display`?this._displaySource(i):null,s={exposure:this.renderer.toneMappingExposure,toneMapping:this.renderer.toneMapping,saturation:this.settings.get(`saturation`)??1,preserveAlpha:t,gain:this._displayGain()},c=await this._toneMapOnGPU(r?.texture??null,i,a,o,s),l=!c&&s.gain?await s.gain.cpu():null;return{data:c??ws(r?await this._readTexture(r.texture,a,o):await this.renderer.readRenderTargetPixelsAsync(i,0,0,a,o,0),{...s,pixelGain:l&&{fn:l,width:a,height:o}}),width:a,height:o,colorSpace:e,source:r?.source??`accumulation`,toneMappedOn:c?`gpu`:`cpu`}}let{data:s,source:c}=n===`display`?await this._readDisplaySource(i,a,o):{data:await this.renderer.readRenderTargetPixelsAsync(i,0,0,a,o,0),source:`accumulation`};if(e===`linear`)return{data:s,width:a,height:o,colorSpace:e,workingSpace:this.color?.workingSpace??null,source:c};let{rgba:l,colorSpace:u}=this.color.exportPixels(s,e);return{data:l,width:a,height:o,colorSpace:u,source:c}}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 hv(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 tn)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 vy.warn(r),this._issues.warn(Z.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=>vy.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&&mr.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(Z.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(Z.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 this.renderer.readRenderTargetPixelsAsync(e,0,0,t,n,0),source:`accumulation`}}_readbackPass(){return this._textureReadback??=new w_(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}),Yr(this.color),this.renderer&&this.color.attachRenderer(this.renderer)}async loadColorConfig(e={}){await this._leaveColorWorkingSpace();let t=Jo(this.renderer?.toneMapping),n=await this.color.loadConfig(e);return this.color.workingSpaceAdopted&&await this.applyColorWorkingSpace(),(!(t?.source===`ocio`&&Jo(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){vy.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&&Ln(e||this.meshScene)&&(this._sdf.textureCoordinates=!0,t.setTriangleData(this._sdf.triangles,this._sdf.triangleCount,{textureCoordinates:!0}),t.setupMaterial()),this.reset()}async _initRenderer(){if(I(e=>this.dispatchEvent(e)),typeof navigator>`u`||!navigator.gpu)throw Error("WebGPU is not available — outside a browser, install one as navigator.gpu (for Node, the `webgpu` package)");let e=await navigator.gpu.requestAdapter({powerPreference:`high-performance`});if(!e)throw Error(`Failed to get WebGPU adapter`);this.adapterInfo=Sy(e),this.adapterInfo.isSoftware&&(this._issues.warn(Z.ADAPTER_SOFTWARE,`software GPU adapter "${this.adapterInfo.description||this.adapterInfo.vendor}" — renders are correct but orders of magnitude slower than hardware`,{...this.adapterInfo}),vy.warn(`software GPU adapter — check app.adapterInfo.isSoftware. ${this.adapterInfo.description}`));let n=e.limits,r={maxColorAttachmentBytesPerSample:128};for(let e of[`maxBufferSize`,`maxStorageBufferBindingSize`,`maxSampledTexturesPerShaderStage`,`maxStorageTexturesPerShaderStage`,`maxTextureArrayLayers`,`maxTextureDimension2D`,`maxComputeInvocationsPerWorkgroup`,`maxComputeWorkgroupStorageSize`,`maxComputeWorkgroupSizeX`,`maxComputeWorkgroupSizeY`,`maxComputeWorkgroupSizeZ`]){let t=n[e];t!==void 0&&(r[e]=t)}if(r.maxStorageBuffersPerShaderStage=Math.min(n.maxStorageBuffersPerShaderStage,10),this.renderer=new t.WebGPURenderer({canvas:this.canvas,alpha:!0,powerPreference:`high-performance`,requiredLimits:r}),await _y(this.renderer,this._headless),!this.renderer.backend?.isWebGPUBackend)throw Error(`WebGPU backend unavailable — three.js fell back to WebGL2, which cannot run the path tracer's compute kernels. Check GPU process flags and driver support.`);let a=this.renderer.backend?.device;a?.lost&&(this._gpuDevice=a,this._deviceLostHolder={app:this},by(a,this._deviceLostHolder),a.onuncapturederror=e=>vy.error(`WebGPU uncaptured error:`,e.error)),t.RectAreaLightNode.setLTC(i.RectAreaLightTexturesLib.init()),this.renderer.outputColorSpace=t.SRGBColorSpace,this.renderer.toneMapping=fs,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 qc({issues:this._issues,...this._maxSceneBytes===void 0?{}:{maxSceneBytes:this._maxSceneBytes}}),this.assetLoader=new ry(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 x_(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 dy(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()});else if(e.texture){let e=this.meshScene.environment;e&&this.stages.pathTracer&&await this.stages.pathTracer.environment.setEnvironmentMap(e),ce()}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 s_(this.renderer,this.scene,this.camera,{hostMemoryGB:this._hostMemoryGB,sortMaterials:this.settings.get(`wavefrontSortMaterials`)}),this._extraStages=this._createExtraStages(),this.stages.compositor=new c_(this.renderer,{saturation:this.settings.get(`saturation`)??K.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 cy(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(){}},wy=65504,Ty=6e4,Ey=.01,Dy={low:{temporalAlpha:.1,gradientStrength:.8,gradientSigmaScale:2.5,gradientNoiseFloor:.05,atrousIterations:3,phiColor:1,phiNormal:64,phiDepth:.1,phiLuminance:6,maxAccumFrames:16,varianceBoost:.5},medium:{temporalAlpha:.03,gradientStrength:1,gradientSigmaScale:2.5,gradientNoiseFloor:.05,atrousIterations:4,phiColor:.5,phiNormal:128,phiDepth:.05,phiLuminance:4,maxAccumFrames:64,varianceBoost:1},high:{temporalAlpha:0,gradientStrength:1,gradientSigmaScale:2.5,gradientNoiseFloor:.05,atrousIterations:6,phiColor:.3,phiNormal:256,phiDepth:.02,phiLuminance:2,maxAccumFrames:128,varianceBoost:1.5}},Oy=3,ky=.1,Ay={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},jy=[`maxAccumulatedFrameNum`,`maxFastAccumulatedFrameNum`,`maxStabilizedFrameNum`,`historyFixFrameNum`,`prepassBlurRadius`,`maxBlurRadius`,`enableAntiFirefly`],My={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}},Ny=Dy.medium,Py={denoiserStrategy:`none`,filterStrength:1,edgeAtrousIterations:5,edgePhiLuminance:4,edgePhiNormal:64,edgePhiDepth:.1,enableOIDN:!1,oidnQuality:`fast`,continuousDenoise:!1,continuousDenoiseInterval:8,oidnTemporalHistory:!0,enableUpscaler:!1,upscalerScale:2,upscalerQuality:`fast`,upscalerHdr:!0,enableASVGF:!1,asvgfQualityPreset:`medium`,asvgfTemporalAlpha:Ny.temporalAlpha,asvgfAtrousIterations:Ny.atrousIterations,asvgfPhiColor:Ny.phiColor,asvgfPhiNormal:Ny.phiNormal,asvgfPhiDepth:Ny.phiDepth,asvgfPhiLuminance:Ny.phiLuminance,asvgfVarianceBoost:Ny.varianceBoost,asvgfMaxAccumFrames:Ny.maxAccumFrames,asvgfGradientStrength:Ny.gradientStrength,asvgfGradientSigmaScale:Ny.gradientSigmaScale,asvgfGradientNoiseFloor:Ny.gradientNoiseFloor,asvgfDebugMode:0,showAsvgfHeatmap:!1,nrdQualityPreset:`medium`,nrdDebugMode:0};_l(),cu();var Fy=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=Yd(),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(W,W),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(W,W),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&&ip(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=rp(this.pathTracer?.materialData?.linearBuckets);let i={srgbBuckets:rp(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=ir((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=tl(Xd((0,n.vec2)((0,n.float)(o).add(.5).div(s),(0,n.float)(f).add(.5).div(c)),i,a,this.cameraRay)),m=ol.wrap(wf(p,t,e)),h=m.normal.mul(.5).add(.5),g=(0,n.min)(m.dst,(0,n.float)(65504)),_=m.didHit.select((0,n.vec4)(h,g),(0,n.vec4)(0,0,0,(0,n.float)(wy)));(0,n.textureStore)(l,(0,n.uvec2)((0,n.uint)(o),(0,n.uint)(f)),_).toWriteOnly(),d&&(0,n.textureStore)(d,(0,n.uvec2)((0,n.uint)(o),(0,n.uint)(f)),(0,n.uvec4)((0,n.uint)(m.instanceLeaf.add(1)),0,0,0)).toWriteOnly();let v=m.normal.toVar(),y=(0,n.float)(1).toVar();(0,n.If)(m.didHit,()=>{let i=nl.wrap($l(m.materialIndex,r)).toVar(),a=hl.wrap(lp(m.uv,i)).toVar(),o=(0,n.vec4)(0).toVar();(0,n.If)(i.normalMapIndex.greaterThanEqual((0,n.int)(0)),()=>{o.assign(pp(e,m.triangleIndex,m.normal,i.normalTransform,t,m.instanceLeaf))});let s=mp(m.normal,i,a,o).toVar();v.assign(hp(s,i,a)),y.assign(dp(i,a).y.clamp(.05,1))});let b=m.didHit.select((0,n.vec4)(v.mul(.5).add(.5),y),(0,n.vec4)(0,0,0,1));(0,n.textureStore)(u,(0,n.uvec2)((0,n.uint)(o),(0,n.uint)(f)),b).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(W,W);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(W,W);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()}},Iy=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.isFirstFrame=!0,this.frameCount=0,this.cameraWorldMatrix=(0,n.uniform)(new r.Matrix4,`mat4`),this.cameraProjectionMatrixInverse=(0,n.uniform)(new r.Matrix4,`mat4`),this.cameraRay=Yd(),this.prevVP=(0,n.uniform)(new r.Matrix4,`mat4`),this.isFirstFrameU=(0,n.uniform)(1),this.deltaTime=(0,n.uniform)(1/60),this.velocityScale=(0,n.uniform)(1),this.resolutionWidth=(0,n.uniform)(o),this.resolutionHeight=(0,n.uniform)(s),this._normalDepthTexNode=new t.TextureNode,this._screenSpaceStorageTex=new t.StorageTexture(W,W),this._screenSpaceStorageTex.type=r.HalfFloatType,this._screenSpaceStorageTex.format=r.RGBAFormat,this._screenSpaceStorageTex.minFilter=r.NearestFilter,this._screenSpaceStorageTex.magFilter=r.NearestFilter,this._worldSpaceStorageTex=new t.StorageTexture(W,W),this._worldSpaceStorageTex.type=r.HalfFloatType,this._worldSpaceStorageTex.format=r.RGBAFormat,this._worldSpaceStorageTex.minFilter=r.NearestFilter,this._worldSpaceStorageTex.magFilter=r.NearestFilter,this._srcRegion=new r.Box2(new r.Vector2(0,0),new r.Vector2(0,0));let c={type:r.HalfFloatType,format:r.RGBAFormat,minFilter:r.NearestFilter,magFilter:r.NearestFilter,depthBuffer:!1,stencilBuffer:!1};this.screenSpaceTarget=new t.RenderTarget(o,s,c),this.worldSpaceTarget=new t.RenderTarget(o,s,c),this._dispatchX=Math.ceil(o/16),this._dispatchY=Math.ceil(s/16),this._buildScreenSpaceCompute(),this._buildWorldSpaceCompute()}_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=Zd(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])}_buildWorldSpaceCompute(){let e=this._normalDepthTexNode,t=this.cameraWorldMatrix,r=this.cameraProjectionMatrixInverse,i=this.prevVP,a=this.isFirstFrameU,o=this.deltaTime,s=this.velocityScale,c=this.resolutionWidth,l=this.resolutionHeight,u=this._worldSpaceStorageTex;this._worldSpaceComputeNode=(0,n.Fn)(([t,r])=>{let d=(0,n.int)(n.workgroupId.x).mul(16).add((0,n.int)(n.localId.x)),f=(0,n.int)(n.workgroupId.y).mul(16).add((0,n.int)(n.localId.y));(0,n.If)(d.lessThan((0,n.int)(c)).and(f.lessThan((0,n.int)(l))),()=>{let p=(0,n.textureLoad)(e,(0,n.ivec2)(d,f)).w,m=(0,n.vec4)(0,0,0,0).toVar();(0,n.If)(a.lessThan(.5).and(p.lessThan((0,n.float)(6e4))),()=>{let e=(0,n.vec2)((0,n.float)(d).add(.5).div(c),(0,n.float)(f).add(.5).div(l)),a=Zd(e,p,t,r,this.cameraRay),u=i.mul((0,n.vec4)(a,1)),h=u.xy.div(u.w),g=(0,n.vec2)(h.x.mul(.5).add(.5),h.y.mul(-.5).add(.5)),_=g.x.greaterThanEqual(0).and(g.x.lessThanEqual(1)).and(g.y.greaterThanEqual(0)).and(g.y.lessThanEqual(1)),v=e.sub(g),y=(0,n.vec3)(v.x.div(o).mul(s),v.y.div(o).mul(s),0);m.assign(_.select((0,n.vec4)(y,1),(0,n.vec4)(0,0,0,.5)))}),(0,n.textureStore)(u,(0,n.uvec2)((0,n.uint)(d),(0,n.uint)(f)),m).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)}setupEventListeners(){this.on(`pipeline:reset`,()=>{this.reset()})}render(e){if(!this.enabled)return;let t=e.getTexture(`pathtracer:normalDepth`);if(!t)return;this._updateCameraMatrices(),this.isFirstFrameU.value=+!!this.isFirstFrame,this.frameCount++;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.renderer.compute(this._worldSpaceComputeNode),this._srcRegion.max.set(this.screenSpaceTarget.width,this.screenSpaceTarget.height),this.renderer.copyTextureToTexture(this._screenSpaceStorageTex,this.screenSpaceTarget.texture,this._srcRegion),this.renderer.copyTextureToTexture(this._worldSpaceStorageTex,this.worldSpaceTarget.texture,this._srcRegion),e.setTexture(`motionVector:screenSpace`,this.screenSpaceTarget.texture),e.setTexture(`motionVector:worldSpace`,this.worldSpaceTarget.texture),e.setTexture(`motionVector:motion`,this.screenSpaceTarget.texture),this.emit(`motionvector:computed`,{frame:this.frameCount,isFirstFrame:this.isFirstFrame}),this.isFirstFrame=!1}releaseGPUMemory(){this._screenSpaceStorageTex?.dispose(),this._worldSpaceStorageTex?.dispose(),this.reset()}reset(){this.matricesInitialized||(this.isFirstFrame=!0),this.frameCount=0}setSize(e,t){this.screenSpaceTarget.setSize(e,t),this.screenSpaceTarget.texture.needsUpdate=!0,this.worldSpaceTarget.setSize(e,t),this.worldSpaceTarget.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]),this._worldSpaceComputeNode&&(this._worldSpaceComputeNode.dispatchSize=[this._dispatchX,this._dispatchY,1])}setVelocityScale(e){this.velocityScale.value=e}setDeltaTime(e){this.deltaTime.value=e}reallocateReservedStorage(){this._screenSpaceComputeNode?.dispose(),this._worldSpaceComputeNode?.dispose(),this._screenSpaceStorageTex?.dispose(),this._worldSpaceStorageTex?.dispose();let e=()=>{let e=new t.StorageTexture(W,W);return e.type=r.HalfFloatType,e.format=r.RGBAFormat,e.minFilter=r.NearestFilter,e.magFilter=r.NearestFilter,e};this._screenSpaceStorageTex=e(),this._worldSpaceStorageTex=e(),this._buildScreenSpaceCompute(),this._buildWorldSpaceCompute()}dispose(){this._screenSpaceComputeNode?.dispose(),this._worldSpaceComputeNode?.dispose(),this._screenSpaceStorageTex?.dispose(),this._worldSpaceStorageTex?.dispose(),this.screenSpaceTarget?.dispose(),this.worldSpaceTarget?.dispose(),this._normalDepthTexNode?.dispose()}};cu();var Ly=e=>(0,n.select)(e.equal(e),e,(0,n.float)(0)).clamp(0,1e7),Ry=e=>(0,n.vec3)(Ly(e.x),Ly(e.y),Ly(e.z)),zy=class extends j{constructor(e,i={}){super(`ASVGF`,{...i,executionMode:A.PER_CYCLE}),this.renderer=e,this.temporalAlpha=(0,n.uniform)(i.temporalAlpha??Dy.medium.temporalAlpha),this.gradientStrength=(0,n.uniform)(i.gradientStrength??Dy.medium.gradientStrength),this.gradientSigmaScale=(0,n.uniform)(i.gradientSigmaScale??Dy.medium.gradientSigmaScale),this.gradientNoiseFloor=(0,n.uniform)(i.gradientNoiseFloor??Dy.medium.gradientNoiseFloor),this.maxAccumFrames=(0,n.uniform)(i.maxAccumFrames??Dy.medium.maxAccumFrames),this.resW=(0,n.uniform)(i.width||1),this.resH=(0,n.uniform)(i.height||1),this.temporalEnabledU=(0,n.uniform)(1),this.forceResetU=(0,n.uniform)(0),this._colorTexNode=new t.TextureNode,this._albedoTexNode=new t.TextureNode,this._motionTexNode=new t.TextureNode,this._normalDepthTexNode=new t.TextureNode,this._prevNormalDepthTexNode=new t.TextureNode,this._readTemporalTexNode=new t.TextureNode,this._gradientReadTexNode=new t.TextureNode;let a=i.width||1,o=i.height||1;this._temporalTexA=new t.StorageTexture(W,W),this._temporalTexA.type=r.FloatType,this._temporalTexA.format=r.RGBAFormat,this._temporalTexA.minFilter=r.LinearFilter,this._temporalTexA.magFilter=r.LinearFilter,this._temporalTexB=new t.StorageTexture(W,W),this._temporalTexB.type=r.FloatType,this._temporalTexB.format=r.RGBAFormat,this._temporalTexB.minFilter=r.LinearFilter,this._temporalTexB.magFilter=r.LinearFilter,this._outputModulatedTex=new t.StorageTexture(W,W),this._outputModulatedTex.type=r.FloatType,this._outputModulatedTex.format=r.RGBAFormat,this._outputModulatedTex.minFilter=r.LinearFilter,this._outputModulatedTex.magFilter=r.LinearFilter,this._gradientStorageTex=new t.StorageTexture(W,W),this._gradientStorageTex.type=r.HalfFloatType,this._gradientStorageTex.format=r.RGBAFormat,this._gradientStorageTex.minFilter=r.LinearFilter,this._gradientStorageTex.magFilter=r.LinearFilter,this._srcRegion=new r.Box2(new r.Vector2(0,0),new r.Vector2(0,0)),this._demodulatedRT=new t.RenderTarget(a,o,{type:r.FloatType,format:r.RGBAFormat,minFilter:r.LinearFilter,magFilter:r.LinearFilter,depthBuffer:!1,stencilBuffer:!1}),this._outputRT=new t.RenderTarget(a,o,{type:r.FloatType,format:r.RGBAFormat,minFilter:r.LinearFilter,magFilter:r.LinearFilter,depthBuffer:!1,stencilBuffer:!1}),this._gradientRT=new t.RenderTarget(a,o,{type:r.HalfFloatType,format:r.RGBAFormat,minFilter:r.LinearFilter,magFilter:r.LinearFilter,depthBuffer:!1,stencilBuffer:!1}),this.currentMoments=0,this._compiled=!1,this._needsWarmReset=!1,this._dispatchX=Math.ceil(a/8),this._dispatchY=Math.ceil(o/8),this._buildGradientCompute(),this._buildTemporalCompute(),this.showHeatmap=!1,this.debugMode=(0,n.uniform)(0,`int`),this._heatmapStorageTex=new t.StorageTexture(W,W),this._heatmapStorageTex.type=r.FloatType,this._heatmapStorageTex.format=r.RGBAFormat,this._heatmapStorageTex.minFilter=r.NearestFilter,this._heatmapStorageTex.magFilter=r.NearestFilter,this.heatmapTarget=new t.RenderTarget(a,o,{type:r.FloatType,format:r.RGBAFormat,minFilter:r.NearestFilter,magFilter:r.NearestFilter,depthBuffer:!1,stencilBuffer:!1}),this._heatmapRawColorTexNode=new t.TextureNode,this._heatmapColorTexNode=new t.TextureNode,this._heatmapTemporalTexNode=new t.TextureNode,this._heatmapNDTexNode=new t.TextureNode,this._heatmapMotionTexNode=new t.TextureNode,this._heatmapGradientTexNode=new t.TextureNode,this._buildHeatmapCompute()}_buildGradientCompute(){let e=this._colorTexNode,t=this._albedoTexNode,r=this._motionTexNode,i=this._readTemporalTexNode,a=this.gradientNoiseFloor,o=this.gradientSigmaScale,s=this._gradientStorageTex,c=this.resW,l=this.resH,u=(0,n.workgroupArray)(`float`,144),d=(0,n.workgroupArray)(`float`,144);this._gradientNode=(0,n.Fn)(()=>{let f=n.localId.x,p=n.localId.y,m=p.mul(8).add(f),h=(0,n.int)(n.workgroupId.x).mul(8).sub(2).toVar(),g=(0,n.int)(n.workgroupId.y).mul(8).sub(2).toVar(),_=a=>{let o=a.mod((0,n.uint)(12)),s=a.div((0,n.uint)(12)),f=h.add((0,n.int)(o)).clamp((0,n.int)(0),(0,n.int)(c).sub(1)),p=g.add((0,n.int)(s)).clamp((0,n.int)(0),(0,n.int)(l).sub(1)),m=(0,n.textureLoad)(e,(0,n.ivec2)(f,p)).xyz,_=(0,n.textureLoad)(t,(0,n.ivec2)(f,p)).xyz,v=Rl(Ry(m.div((0,n.max)(_,(0,n.vec3)(Ey))))).toVar();u.element(a).assign(v);let y=(0,n.textureLoad)(r,(0,n.ivec2)(f,p)),b=(0,n.float)(f).sub(y.x.mul(c)),x=(0,n.float)(p).sub(y.y.mul(l)),S=(0,n.int)(b.add(.5)).clamp((0,n.int)(0),(0,n.int)(c).sub(1)),C=(0,n.int)(x.add(.5)).clamp((0,n.int)(0),(0,n.int)(l).sub(1)),w=y.w.greaterThan(.5),T=(0,n.textureLoad)(i,(0,n.ivec2)(S,C)).xyz,E=w.select(Rl(T),v);d.element(a).assign(E)};_(m);let v=m.add((0,n.uint)(64));(0,n.If)(v.lessThan((0,n.uint)(144)),()=>{_(v)});let y=m.add((0,n.uint)(128));(0,n.If)(y.lessThan((0,n.uint)(144)),()=>{_(y)}),(0,n.workgroupBarrier)();let b=(0,n.int)(n.workgroupId.x).mul(8).add((0,n.int)(f)),x=(0,n.int)(n.workgroupId.y).mul(8).add((0,n.int)(p));(0,n.If)(b.lessThan((0,n.int)(c)).and(x.lessThan((0,n.int)(l))),()=>{let e=(0,n.float)(0).toVar(),t=(0,n.float)(0).toVar();for(let r=-2;r<=2;r++)for(let i=-2;i<=2;i++){let a=p.add((0,n.uint)(2+r)).mul((0,n.uint)(12)).add(f.add((0,n.uint)(2+i))),o=u.element(a);e.addAssign(o),t.addAssign(o.mul(o))}let m=e.div(25),h=(0,n.sqrt)((0,n.max)(t.div(25).sub(m.mul(m)),(0,n.float)(0))).mul(o).toVar(),g=(0,n.float)(0).toVar();for(let e=-2;e<=2;e++)for(let t=-2;t<=2;t++){let r=p.add((0,n.uint)(2+e)).mul((0,n.uint)(12)).add(f.add((0,n.uint)(2+t))),i=u.element(r),o=d.element(r),s=(0,n.max)((0,n.max)((0,n.abs)(i.sub(o)).sub(h),(0,n.float)(0)).div((0,n.max)((0,n.max)(i,o),(0,n.float)(.001))).sub(a),(0,n.float)(0)).div((0,n.max)((0,n.float)(1).sub(a),(0,n.float)(1e-4)));g.addAssign(s.mul(s))}let _=g.div(25).clamp(0,1).toVar(),v=(0,n.textureLoad)(r,(0,n.ivec2)(b,x)),y=(0,n.int)((0,n.float)(b).sub(v.x.mul(c)).add(.5)).clamp((0,n.int)(0),(0,n.int)(c).sub(1)),S=(0,n.int)((0,n.float)(x).sub(v.y.mul(l)).add(.5)).clamp((0,n.int)(0),(0,n.int)(l).sub(1)),C=v.w.greaterThan(.5).select((0,n.textureLoad)(i,(0,n.ivec2)(y,S)).w,(0,n.float)(0)).div(4).clamp(0,1),w=_.mul(C);(0,n.textureStore)(s,(0,n.uvec2)((0,n.uint)(b),(0,n.uint)(x)),(0,n.vec4)(w,_,h,1)).toWriteOnly()})})().compute([this._dispatchX,this._dispatchY,1],[8,8,1])}_buildTemporalCompute(){this._temporalNodeA=this._buildTemporalForDirection(this._temporalTexA),this._temporalNodeB=this._buildTemporalForDirection(this._temporalTexB)}_buildTemporalForDirection(e){let t=this._colorTexNode,r=this._albedoTexNode,i=this._motionTexNode,a=this._normalDepthTexNode,o=this._prevNormalDepthTexNode,s=this._readTemporalTexNode,c=this._gradientReadTexNode,l=this._outputModulatedTex,u=this.maxAccumFrames,d=this.temporalAlpha,f=this.gradientStrength,p=this.temporalEnabledU,m=this.forceResetU,h=this.resW,g=this.resH;return(0,n.Fn)(()=>{let _=(0,n.int)(n.workgroupId.x).mul(8).add((0,n.int)(n.localId.x)),v=(0,n.int)(n.workgroupId.y).mul(8).add((0,n.int)(n.localId.y));(0,n.If)(_.lessThan((0,n.int)(h)).and(v.lessThan((0,n.int)(g))),()=>{let y=(0,n.ivec2)(_,v),b=(0,n.textureLoad)(t,y),x=b.xyz,S=b.w,C=(0,n.textureLoad)(r,y).xyz,w=(0,n.max)(C,(0,n.vec3)(Ey)),T=Ry(x.div(w)),E=(0,n.vec4)(T,1).toVar(),D=(0,n.vec4)(x,S).toVar();(0,n.If)(p.greaterThan(.5).and(m.lessThan(.5)),()=>{let e=(0,n.textureLoad)(i,y),t=e.w.greaterThan(.5),r=(0,n.float)(_).sub(e.x.mul(h)),l=(0,n.float)(v).sub(e.y.mul(g)),p=r.greaterThanEqual(0).and(r.lessThan((0,n.float)(h))).and(l.greaterThanEqual(0)).and(l.lessThan((0,n.float)(g)));(0,n.If)(t.and(p),()=>{let e=(0,n.textureLoad)(a,y),t=e.xyz.mul(2).sub(1),i=e.w,p=(0,n.int)(r),m=(0,n.int)(l),_=p.add((0,n.int)(1)),v=m.add((0,n.int)(1)),b=r.sub((0,n.float)(p)),x=l.sub((0,n.float)(m)),C=p.clamp((0,n.int)(0),(0,n.int)(h).sub(1)),O=_.clamp((0,n.int)(0),(0,n.int)(h).sub(1)),k=m.clamp((0,n.int)(0),(0,n.int)(g).sub(1)),A=v.clamp((0,n.int)(0),(0,n.int)(g).sub(1)),j=(0,n.float)(1).sub(b).mul((0,n.float)(1).sub(x)),M=b.mul((0,n.float)(1).sub(x)),N=(0,n.float)(1).sub(b).mul(x),P=b.mul(x),F=(e,r,a)=>{let s=(0,n.textureLoad)(o,(0,n.ivec2)(e,r)),c=s.xyz.mul(2).sub(1),l=s.w,u=(0,n.pow)((0,n.dot)(t,c).clamp(0,1),(0,n.float)(16)),d=(0,n.exp)((0,n.abs)(i.sub(l)).div((0,n.max)(i,(0,n.float)(.001))).div((0,n.float)(.05)).negate());return a.mul(u).mul(d)},I=F(C,k,j),L=F(O,k,M),R=F(C,A,N),ee=F(O,A,P),z=I.add(L).add(R).add(ee);(0,n.If)(z.greaterThan((0,n.float)(.01)),()=>{let e=(0,n.textureLoad)(s,(0,n.ivec2)(C,k)),t=(0,n.textureLoad)(s,(0,n.ivec2)(O,k)),r=(0,n.textureLoad)(s,(0,n.ivec2)(C,A)),i=(0,n.textureLoad)(s,(0,n.ivec2)(O,A)),a=(0,n.float)(1).div(z),o=e.xyz.mul(I).add(t.xyz.mul(L)).add(r.xyz.mul(R)).add(i.xyz.mul(ee)).mul(a),l=e.w.mul(I).add(t.w.mul(L)).add(r.w.mul(R)).add(i.w.mul(ee)).mul(a),p=(0,n.textureLoad)(c,y).x.mul(f).clamp(0,1),m=Ry((0,n.mix)(o,T,(0,n.mix)((0,n.max)((0,n.float)(1).div(l.add(1)),d),(0,n.float)(1),p))),h=(0,n.min)(l.add(1),u);E.assign((0,n.vec4)(m,h)),D.assign((0,n.vec4)(m.mul(w),S))})})}),(0,n.textureStore)(e,(0,n.uvec2)((0,n.uint)(_),(0,n.uint)(v)),E).toWriteOnly(),(0,n.textureStore)(l,(0,n.uvec2)((0,n.uint)(_),(0,n.uint)(v)),D).toWriteOnly()})})().compute([this._dispatchX,this._dispatchY,1],[8,8,1])}_buildHeatmapCompute(){let e=this._heatmapRawColorTexNode,t=this._heatmapColorTexNode,r=this._heatmapTemporalTexNode,i=this._heatmapNDTexNode,a=this._heatmapMotionTexNode,o=this._heatmapGradientTexNode,s=this._heatmapStorageTex,c=this.debugMode,l=this.resW,u=this.resH;this._heatmapComputeNode=(0,n.Fn)(()=>{let d=(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)(d.lessThan((0,n.int)(l)).and(f.lessThan((0,n.int)(u))),()=>{let p=(0,n.ivec2)(d,f),m=(0,n.vec4)(0,0,0,1).toVar();(0,n.If)(c.equal((0,n.int)(0)),()=>{let e=(0,n.textureLoad)(t,p).xyz;m.assign((0,n.vec4)(e,1))}).ElseIf(c.equal((0,n.int)(1)),()=>{let t=(0,n.float)(0).toVar(),r=(0,n.float)(0).toVar();for(let i=-1;i<=1;i++)for(let a=-1;a<=1;a++){let o=(0,n.textureLoad)(e,(0,n.ivec2)(d.add(a).clamp((0,n.int)(0),(0,n.int)(l).sub(1)),f.add(i).clamp((0,n.int)(0),(0,n.int)(u).sub(1)))).xyz,s=Rl(o);t.addAssign(s),r.addAssign(s.mul(s))}t.divAssign(9),r.divAssign(9);let i=(0,n.max)(r.sub(t.mul(t)),(0,n.float)(0)).div((0,n.max)(t.mul(t),(0,n.float)(1e-4))).mul(10).clamp(0,1),a=i.sub(.5).mul(4).clamp(0,1),o=i.mul(4).clamp(0,1).sub(i.sub(.75).mul(4).clamp(0,1)),s=(0,n.float)(1).sub(i.sub(.25).mul(4).clamp(0,1));m.assign((0,n.vec4)(a,o,s,1))}).ElseIf(c.equal((0,n.int)(2)),()=>{let e=(0,n.textureLoad)(r,p).w.div(32).clamp(0,1);m.assign((0,n.vec4)((0,n.float)(1).sub(e),e,(0,n.float)(.2),1))}).ElseIf(c.equal((0,n.int)(3)),()=>{let e=(0,n.textureLoad)(a,p),t=(0,n.abs)(e.x).mul(100).clamp(0,1),r=(0,n.abs)(e.y).mul(100).clamp(0,1),i=t.add(r).clamp(0,1);m.assign((0,n.vec4)(t,r,i.mul(.3),1))}).ElseIf(c.equal((0,n.int)(4)),()=>{let e=(0,n.textureLoad)(i,p);m.assign((0,n.vec4)(e.xyz,1))}).Else(()=>{let e=(0,n.textureLoad)(o,p).x.mul(5).clamp(0,1);m.assign((0,n.vec4)(e,e.mul(.5),(0,n.float)(1).sub(e),1))}),(0,n.textureStore)(s,(0,n.uvec2)((0,n.uint)(d),(0,n.uint)(f)),m).toWriteOnly()})})().compute([this._dispatchX,this._dispatchY,1],[8,8,1])}setupEventListeners(){this.on(`pipeline:historyReset`,()=>this.resetTemporalData())}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:prevNormalDepth`)||r,a=e.getTexture(`motionVector:screenSpace`);if(!t)return;let o=t.image;o&&o.width>0&&o.height>0&&(o.width!==this._outputRT.width||o.height!==this._outputRT.height)&&this.setSize(o.width,o.height),this._colorTexNode.value=t,n&&(this._albedoTexNode.value=n),a&&(this._motionTexNode.value=a),r&&(this._normalDepthTexNode.value=r),i&&(this._prevNormalDepthTexNode.value=i);let s=this.currentMoments===0?this._temporalTexB:this._temporalTexA,c=this.currentMoments===0?this._temporalNodeA:this._temporalNodeB,l=this.currentMoments===0?this._temporalTexA:this._temporalTexB;this._compiled||=(this.renderer.compute(this._gradientNode),this.renderer.compute(this._temporalNodeA),this.renderer.compute(this._temporalNodeB),!0),this._readTemporalTexNode.value=s,this._gradientReadTexNode.value=this._gradientStorageTex;let u=this.gradientStrength.value>0||this.showHeatmap;u&&this.renderer.compute(this._gradientNode),this.forceResetU.value=+!!this._needsWarmReset,this.renderer.compute(c),this._needsWarmReset=!1,this._srcRegion.max.set(this.resW.value,this.resH.value),this.renderer.copyTextureToTexture(l,this._demodulatedRT.texture,this._srcRegion),this.renderer.copyTextureToTexture(this._outputModulatedTex,this._outputRT.texture,this._srcRegion),u&&this.renderer.copyTextureToTexture(this._gradientStorageTex,this._gradientRT.texture,this._srcRegion),e.setTexture(`asvgf:demodulated`,this._demodulatedRT.texture),e.setTexture(`asvgf:output`,this._outputRT.texture),e.setTexture(`asvgf:gradient`,this._gradientRT.texture),this.currentMoments=1-this.currentMoments,this.showHeatmap&&(this._heatmapRawColorTexNode.value=t,this._heatmapColorTexNode.value=this._outputModulatedTex,this._heatmapTemporalTexNode.value=l,r&&(this._heatmapNDTexNode.value=r),a&&(this._heatmapMotionTexNode.value=a),this._heatmapGradientTexNode.value=this._gradientStorageTex,this.renderer.compute(this._heatmapComputeNode),this._srcRegion.max.set(this.heatmapTarget.width,this.heatmapTarget.height),this.renderer.copyTextureToTexture(this._heatmapStorageTex,this.heatmapTarget.texture,this._srcRegion))}setHeatmapEnabled(e){this.showHeatmap=e}setTemporalEnabled(e){this.temporalEnabledU.value=+!!e}updateParameters(e){e&&(e.temporalAlpha!==void 0&&(this.temporalAlpha.value=e.temporalAlpha),e.gradientStrength!==void 0&&(this.gradientStrength.value=e.gradientStrength),e.gradientSigmaScale!==void 0&&(this.gradientSigmaScale.value=e.gradientSigmaScale),e.gradientNoiseFloor!==void 0&&(this.gradientNoiseFloor.value=e.gradientNoiseFloor),e.maxAccumFrames!==void 0&&(this.maxAccumFrames.value=e.maxAccumFrames),e.debugMode!==void 0&&(this.debugMode.value=e.debugMode))}resetTemporalData(){this.currentMoments=0,this._needsWarmReset=!0}reallocateReservedStorage(){this._gradientNode?.dispose(),this._temporalNodeA?.dispose(),this._temporalNodeB?.dispose(),this._heatmapComputeNode?.dispose(),this._temporalTexA?.dispose(),this._temporalTexB?.dispose(),this._outputModulatedTex?.dispose(),this._gradientStorageTex?.dispose(),this._heatmapStorageTex?.dispose();let e=(e,n)=>{let i=new t.StorageTexture(W,W);return i.type=e,i.format=r.RGBAFormat,i.minFilter=n,i.magFilter=n,i};this._temporalTexA=e(r.FloatType,r.LinearFilter),this._temporalTexB=e(r.FloatType,r.LinearFilter),this._outputModulatedTex=e(r.FloatType,r.LinearFilter),this._gradientStorageTex=e(r.HalfFloatType,r.LinearFilter),this._heatmapStorageTex=e(r.FloatType,r.NearestFilter),this._buildGradientCompute(),this._buildTemporalCompute(),this._buildHeatmapCompute(),this._compiled=!1,this.currentMoments=0,this._needsWarmReset=!0}setSize(e,t){this._demodulatedRT.setSize(e,t),this._demodulatedRT.texture.needsUpdate=!0,this._outputRT.setSize(e,t),this._outputRT.texture.needsUpdate=!0,this._gradientRT.setSize(e,t),this._gradientRT.texture.needsUpdate=!0,this.heatmapTarget.setSize(e,t),this.heatmapTarget.texture.needsUpdate=!0,this.resW.value=e,this.resH.value=t,this._dispatchX=Math.ceil(e/8),this._dispatchY=Math.ceil(t/8),this._gradientNode.dispatchSize=[this._dispatchX,this._dispatchY,1],this._temporalNodeA.dispatchSize=[this._dispatchX,this._dispatchY,1],this._temporalNodeB.dispatchSize=[this._dispatchX,this._dispatchY,1],this._heatmapComputeNode.dispatchSize=[this._dispatchX,this._dispatchY,1]}reset(){}releaseGPUMemory(){this._temporalTexA?.dispose(),this._temporalTexB?.dispose(),this._outputModulatedTex?.dispose(),this._gradientStorageTex?.dispose(),this._heatmapStorageTex?.dispose(),this.context?.removeTexture(`asvgf:demodulated`),this.context?.removeTexture(`asvgf:output`),this.context?.removeTexture(`asvgf:gradient`),this._demodulatedRT?.texture?.dispose(),this._outputRT?.texture?.dispose(),this._gradientRT?.texture?.dispose(),this.heatmapTarget?.texture?.dispose(),this.resetTemporalData()}dispose(){this._gradientNode?.dispose(),this._temporalNodeA?.dispose(),this._temporalNodeB?.dispose(),this._temporalTexA?.dispose(),this._temporalTexB?.dispose(),this._outputModulatedTex?.dispose(),this._gradientStorageTex?.dispose(),this._demodulatedRT?.dispose(),this._outputRT?.dispose(),this._gradientRT?.dispose(),this._heatmapComputeNode?.dispose(),this._heatmapStorageTex?.dispose(),this.heatmapTarget?.dispose(),this._colorTexNode?.dispose(),this._albedoTexNode?.dispose(),this._motionTexNode?.dispose(),this._normalDepthTexNode?.dispose(),this._prevNormalDepthTexNode?.dispose(),this._readTemporalTexNode?.dispose(),this._gradientReadTexNode?.dispose(),this._heatmapRawColorTexNode?.dispose(),this._heatmapColorTexNode?.dispose(),this._heatmapTemporalTexNode?.dispose(),this._heatmapNDTexNode?.dispose(),this._heatmapMotionTexNode?.dispose(),this._heatmapGradientTexNode?.dispose()}};cu();var By=1e-6,Vy=1.5/255,Hy=.01,Uy=3,Wy=2,Gy=2,Ky=3,qy=2,Jy=38,Yy=.1,Xy=4,Zy=Math.cos(89*Math.PI/180),Qy=.5,$y=16,eb={pre:{radiusScale:1,fractionScale:2},blur:{radiusScale:1,fractionScale:1},post:{radiusScale:2,fractionScale:.5}},tb=.25*Math.SQRT2,nb=[[-1,0,1],[0,1,1],[1,0,1],[0,-1,1],[-tb,tb,.5],[tb,tb,.5],[tb,-tb,.5],[-tb,-tb,.5]],rb=(e,t,r)=>(0,n.smoothstep)(0,1,(0,n.float)(1).sub(e.mul(t).add(r).abs())),ib=(e,t,r)=>{let i=e.mul(t).add(r).abs().mul(-Uy);return(0,n.float)(1).div(i.mul(i).sub(i).add(1))},ab=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)))),ob=(e,t)=>(0,n.float)(1).sub((0,n.exp2)(e.mul(e).mul(-200))).mul((0,n.pow)((0,n.saturate)(e),t)),sb=(e,t)=>(0,n.saturate)(e).mul((0,n.sqrt)(t.div((0,n.float)(1).sub(t).add(By)))),cb=(e,t,r,i)=>{let a=(0,n.max)((0,n.atan)(sb(r,i.mul((0,n.mix)((0,n.saturate)(t),(0,n.float)(1),e)))),(0,n.float)(Vy));return(0,n.float)(1).div(a)},lb=(e,t)=>{let r=(0,n.float)(1).div((0,n.mix)((0,n.float)(Hy),(0,n.float)(1),(0,n.saturate)(e.mul(t))));return(0,n.vec2)(r,e.mul(r).negate())},ub=(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())},db=(e,t)=>{let r=(0,n.float)(1).div(t);return(0,n.vec2)(r,e.mul(r).negate())},fb=(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())},pb=e=>(0,n.vec2)(1).sub((0,n.vec2)(1).sub((0,n.fract)(e.mul(.5)).mul(2)).abs()).min(.99999),mb=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))},gb=(e,t)=>t.add(By).div(e.add(By)),_b=(e,t)=>(0,n.vec4)(e.xyz.mul(gb(e.x,t)),e.w),vb=e=>(0,n.vec4)(mb(hb(e.xyz)),(0,n.saturate)(e.w)),yb=(e,t)=>(0,n.sqrt)(t.sub(e.mul(e)).abs()),bb=(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))),xb=(e,t)=>(0,n.select)(e.equal(0),(0,n.vec4)(0),t);function Sb(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 Cb=class extends j{constructor(e,i={}){super(`NRD`,{...i,executionMode:A.PER_CYCLE}),this.renderer=e,this.pathTracer=i.pathTracer||null,this.settings={...Ay,...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=Yd(),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/$y),this._dispatchY=Math.ceil(o/$y),this._buildKernels()}_allocStorage(){let e=()=>Me(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 Ay&&(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 Zd(e,t,n,r,this.cameraRay)}_viewVector(e,t,r){return(0,n.select)(Jd(this.cameraRay.cameraProjection),r,(0,n.normalize)(t.sub(e)))}_frustumSize(e){return this.minRectDimMulUnproject.mul((0,n.select)(Jd(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)))}_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=Qy,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],[$y,$y,1])}_buildSpatial(e){let t=e===`pre`,{radiusScale:r,fractionScale:i}=eb[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=>{let t=(0,n.textureLoad)(o,e),r=(0,n.textureLoad)(s,e);return(0,n.vec4)(mb(Ml(t.xyz.div((0,n.max)(r.xyz,(0,n.vec3)(Ey))))),jl(r.w,Al).min(1))}:e=>(0,n.textureLoad)(d,e),S=(0,n.Fn)(([o,s])=>{let d=(0,n.int)(n.workgroupId.x).mul($y).add((0,n.int)(n.localId.x)),S=(0,n.int)(n.workgroupId.y).mul($y).add((0,n.int)(n.localId.y));(0,n.If)(d.lessThan((0,n.int)(v)).and(S.lessThan((0,n.int)(y))),()=>{let C=(0,n.ivec2)(d,S),w=(0,n.uvec2)((0,n.uint)(d),(0,n.uint)(S)),T=(0,n.textureLoad)(c,C).w.toVar(),E=T.greaterThanEqual(Ty),D=(0,n.textureLoad)(l,C).toVar(),O=(0,n.normalize)(D.xyz.mul(2).sub(1)).toVar(),k=D.w.clamp(.05,1).toVar(),A=(0,n.float)(Ty).toVar(),j=x(C).toVar();(0,n.If)(E.not(),()=>{let e=this._pixelUv(d,S),f=this._worldPosAt(e,T,o,s).toVar();A.assign(g.mul((0,n.vec4)(f,1)).z.abs()),(0,n.If)(h.greaterThan(0),()=>{let d=(0,n.dot)(O,this._viewVector(f,_,this.viewVector)).abs().toVar(),p=this._frustumSize(A).toVar(),S=b.add(1),w=t?(0,n.max)(b,(0,n.float)(10)):(0,n.textureLoad)(u,C).y.add(b),T=(t?(0,n.float)(1).div(w.add(1)):this._advancedNonLinear(w)).toVar(),E=ob(k,.5).toVar(),D=A.mul(ky).add(3),M=j.w.toVar(),N=(0,n.saturate)(M.mul(D).div(p)),P=(0,n.float)(1).sub(this._handover(S)),F=(t?N.div(S):N.mul(T)).mul(P),I=a.minBlurRadius.mul((0,n.saturate)((0,n.float)(2).sub(w.div((0,n.max)(a.maxAccum,1))))),L=(0,n.max)((0,n.saturate)((0,n.sqrt)((0,n.saturate)(F)).mul(r)).mul(h).mul(E),I.mul(E)).toVar(),R=fb(a.planeDistSensitivity,p,f,O).toVar(),ee=cb(T,a.lobeAngleFraction,k,a.lobeVolumePercent).div(i).toVar(),z=lb(k,a.roughnessFraction.mul(i)).toVar(),te=db(M,T).toVar(),ne=a.minHitDistanceWeight.mul(i).mul(E);t||(ne=ne.mul(T)),ne=ne.toVar();let re=(0,n.vec2)(1);if(!t){let e=g.mul((0,n.vec4)(O,0)).xy;re=(0,n.mix)((0,n.vec2)(1).sub(e.abs()),(0,n.vec2)(1),d),re=re.div((0,n.max)(re.x,re.y))}let ie=re.mul((0,n.vec2)((0,n.float)(1).div(v),(0,n.float)(1).div(y))).mul(L).toVar(),ae=(0,n.float)(1).toVar();for(let t=0;t<nb.length;t++){let r=nb[t],i=e.add(bb(m,(0,n.vec2)(r[0],r[1])).mul(ie)),a=pb(i),u=(0,n.select)(a.x.notEqual(i.x).or(a.y.notEqual(i.y)),(0,n.float)(1),(0,n.float)(Math.exp(-.66*r[2]*r[2]))).toVar(),d=this._uvToCoord(a),f=(0,n.textureLoad)(c,d).w,p=this._worldPosAt(a,f,o,s),h=(0,n.textureLoad)(l,d),g=ab((0,n.dot)(O,(0,n.normalize)(h.xyz.mul(2).sub(1))));u.mulAssign(rb(g,ee,(0,n.float)(0))),u.mulAssign(rb(h.w,z.x,z.y)),u.mulAssign(rb((0,n.dot)(O,p),R.x,R.y)),u.assign((0,n.select)(f.greaterThanEqual(Ty),(0,n.float)(0),u));let _=xb(u,x(d));u.mulAssign(ne.add(ib(_.w,te.x,te.y))),ae.addAssign(u),j.addAssign(_.mul(u))}j.divAssign((0,n.max)(ae,1e-6)),t||j.assign((0,n.vec4)(j.xyz,M))})}),(0,n.textureStore)(f,w,j).toWriteOnly(),e===`post`&&(0,n.textureStore)(p,w,(0,n.vec4)(O,A)).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.camView,p=this.prevCamView,m=this.camPos,h=this.prevCamPos,g=this.resW,_=this.resH,v=this.inputFrames,y=this.resetU,b=(0,n.Fn)(([b,x])=>{let S=(0,n.int)(n.workgroupId.x).mul($y).add((0,n.int)(n.localId.x)),C=(0,n.int)(n.workgroupId.y).mul($y).add((0,n.int)(n.localId.y));(0,n.If)(S.lessThan((0,n.int)(g)).and(C.lessThan((0,n.int)(_))),()=>{let g=(0,n.ivec2)(S,C),_=(0,n.uvec2)((0,n.uint)(S),(0,n.uint)(C)),w=(0,n.textureLoad)(t,g).w,T=(0,n.textureLoad)(a,g).toVar();(0,n.If)(w.greaterThanEqual(Ty),()=>{(0,n.textureStore)(u,_,T).toWriteOnly(),(0,n.textureStore)(d,_,(0,n.vec4)(0)).toWriteOnly(),(0,n.Return)()});let E=e.maxAccum.mul((0,n.float)(1).sub(y)).toVar(),D=e.maxFast.mul((0,n.float)(1).sub(y)).toVar(),O=(0,n.textureLoad)(r,g),k=(0,n.normalize)(O.xyz.mul(2).sub(1)).toVar(),A=O.w.clamp(.05,1).toVar(),j=this._pixelUv(S,C),M=this._worldPosAt(j,w,b,x).toVar(),N=f.mul((0,n.vec4)(M,1)).z.abs().toVar(),P=(0,n.dot)(k,this._viewVector(M,m,this.viewVector)).abs().toVar(),F=this._frustumSize(N).toVar(),I=(0,n.vec3)(0).toVar();I.addAssign(k.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(S.add(i),C.add(e)),o=(0,n.normalize)((0,n.textureLoad)(r,a).xyz.mul(2).sub(1)),s=(0,n.textureLoad)(t,a).w.lessThan(Ty);I.addAssign((0,n.select)(s,o,k).mul(.25))}let L=(0,n.textureLoad)(i,g),R=j.sub(L.xy).toVar(),ee=p.mul((0,n.vec4)(M,1)).z.abs().toVar(),z=this._bilinear(R),te=F.mul((0,n.saturate)(e.disocclusionThreshold.div((0,n.max)(P,.05)))).sub(By).toVar(),ne=(0,n.float)(1).sub(y),re=[],ie=[];for(let e=0;e<4;e++){let t=(0,n.textureLoad)(l,z.taps[e]),r=(0,n.select)((0,n.dot)(t.xyz,I).greaterThan(Zy),(0,n.float)(1),(0,n.float)(0)),i=(0,n.select)(t.w.sub(ee).abs().lessThanEqual(te),(0,n.float)(1),(0,n.float)(0)),a=(0,n.select)(t.w.lessThan(Ty),(0,n.float)(1),(0,n.float)(0));re.push(r.mul(i).mul(a).mul(z.inScreen[e]).mul(ne).toVar()),ie.push((0,n.textureLoad)(c,z.taps[e]).x)}let ae=z.customWeights(re).map(e=>e.toVar()),oe=re[0].add(re[1]).add(re[2]).add(re[3]).greaterThan(3.5).toVar(),se=re[0].add(re[1].mul(2)).add(re[2].mul(4)).add(re[3].mul(8)),ce=this._applyCustomWeights(ie,ae,(0,n.float)(0)).toVar(),B=(0,n.dot)(k,this._viewVector(M,h,this.prevViewVector)).abs().add(.001).div(P.add(.001)).toVar();B.assign((0,n.mix)((0,n.float)(.1),(0,n.float)(1),(0,n.saturate)(B.mul(B))));let le=(0,n.sqrt)((0,n.saturate)(z.filter(re))).mul(B).toVar();ce.assign(ce.mul((0,n.mix)(le,(0,n.float)(1),(0,n.float)(1).div(ce.add(1))))),ce.assign((0,n.min)(ce,E));let ue=vb(this._sampleHistory(e=>(0,n.textureLoad)(o,e),R,z,ae,oe)).toVar(),de=(0,n.max)(this._applyCustomWeights(z.taps.map(e=>(0,n.textureLoad)(s,e).x),ae,(0,n.float)(0)),0).toVar(),fe=v.add(1),pe=this._handover(fe).toVar(),me=ce.mul((0,n.float)(1).sub(pe)),he=fe.div(fe.add(me)).toVar(),ge=(0,n.float)(1).div((0,n.float)(1).add(ob(A,.25).mul(.5).mul(E))),_e=(0,n.vec4)((0,n.mix)(ue.xyz,T.xyz,he),(0,n.mix)(ue.w,T.w,(0,n.max)(he,ge))).toVar(),ve=e.fireflyMinRelativeScale.add((0,n.float)(Jy).div(ce.add(1))).toVar(),V=ce.mul(e.maxBlurRadius).mul(Yy).toVar();V.assign(V.div(V.add(1)).mul((0,n.float)(1).sub(pe)));let ye=(0,n.mix)(_e.x,(0,n.min)(_e.x,ue.x.mul(ve)),V);_e.assign(_b(_e,ye));let be=(0,n.float)(1.2).add((0,n.float)(1).div(ce.add(1)));_e.assign((0,n.vec4)(_e.xyz,(0,n.mix)(_e.w,(0,n.min)(_e.w,ue.w.mul(be)),V))),(0,n.textureStore)(u,_,_e).toWriteOnly();let xe=(0,n.min)(ce,D).mul((0,n.float)(1).sub(pe)),Se=fe.div(fe.add(xe)),H=(0,n.mix)(de,T.x,Se).toVar(),Ce=(0,n.min)(H,ue.x.mul(ve).mul(Xy));H.assign((0,n.mix)(H,Ce,V)),(0,n.textureStore)(d,_,(0,n.vec4)(H,ce,se,(0,n.select)(oe,(0,n.float)(1),(0,n.float)(0)))).toWriteOnly()})});return this._dispatchOf(b)}_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($y).add((0,n.int)(n.localId.x)),h=(0,n.int)(n.workgroupId.y).mul($y).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(Ty),()=>{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=C.w.clamp(.05,1).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(ky).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/Wy).mul(e.historyFixStride).mul((0,n.mix)((0,n.float)(.25).add((0,n.sqrt)(N).mul(.75)),(0,n.float)(1),j))).toVar();(0,n.If)(F.notEqual(0),()=>{let o=cb(j,e.lobeAngleFraction,T,e.lobeVolumePercent).toVar(),s=fb(e.planeDistSensitivity,k,D,w).toVar(),c=db(P,j).toVar(),d=ub(T.mul(T),(0,n.sqrt)(e.roughnessFraction),Hy).toVar(),m=(0,n.float)(1).add(b).toVar();A.mulAssign(m);for(let e=-Wy;e<=Wy;e++)for(let h=-Wy;h<=Wy;h++){if(h===0&&e===0||Math.abs(h)+Math.abs(e)===Wy*2)continue;let g=pb(E.add((0,n.vec2)(h,e).mul(F).mul((0,n.vec2)((0,n.float)(1).div(l),(0,n.float)(1).div(u))))),_=this._uvToCoord(g),v=(0,n.textureLoad)(t,_).w,y=this._worldPosAt(g,v,f,p),b=(0,n.textureLoad)(r,_),x=ib(ab((0,n.dot)((0,n.normalize)(b.xyz.mul(2).sub(1)),w)),o,(0,n.float)(0)).toVar();x.mulAssign(ib(b.w.mul(b.w),d.x,d.y)),x.mulAssign((0,n.float)(1).add((0,n.textureLoad)(a,_).y)),x.mulAssign(rb((0,n.dot)(w,y),s.x,s.y)),x.assign((0,n.select)(v.greaterThanEqual(Ty),(0,n.float)(0),x));let S=xb(x,(0,n.textureLoad)(i,_));x.mulAssign(ib(S.w,c.x,c.y)),m.addAssign(x),A.addAssign(S.mul(x))}A.divAssign((0,n.max)(m,1e-6))});let I=A.x.toVar(),L=(0,n.saturate)(b.div((0,n.max)(e.historyFixFrameNum,By))),R=(0,n.mix)(I,y.x,L).toVar();(0,n.textureStore)(s,_,(0,n.vec4)(R,0,0,0)).toWriteOnly();let ee=R.toVar(),z=R.mul(R).toVar(),te=(0,n.float)(0).toVar(),ne=(0,n.float)(0).toVar(),re=(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(Ty),R,(0,n.textureLoad)(a,o).x);Math.abs(e)<=Gy&&Math.abs(r)<=Gy&&(ee.addAssign(c),z.addAssign(c.mul(c))),i&&(te.addAssign(c),ne.addAssign(c.mul(c)))},ie=e.antiFirefly.greaterThan(.5);for(let e=-Gy;e<=Gy;e++)for(let t=-Gy;t<=Gy;t++)t===0&&e===0||re(t,e,Math.abs(t)>1||Math.abs(e)>1);(0,n.If)(ie,()=>{for(let e=-Ky;e<=Ky;e++)for(let t=-Ky;t<=Ky;t++)Math.abs(t)<=Gy&&Math.abs(e)<=Gy||re(t,e,!0)}),(0,n.If)(ie,()=>{let e=1/((Ky*2+1)**2-9),t=te.mul(e),r=yb(t,ne.mul(e)).mul(qy);I.assign((0,n.mix)(I.clamp(t.sub(r),t.add(r)),I,S))});{let t=1/(Gy*2+1)**2,r=ee.mul(t),i=yb(r,z.mul(t)).mul(e.fastClampSigmaScale),a=I.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);I.assign((0,n.mix)(a,I,s))}(0,n.textureStore)(o,_,_b(A,I)).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($y).add((0,n.int)(n.localId.x)),y=(0,n.int)(n.workgroupId.y).mul($y).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(Ty),()=>{(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.clamp(.05,1),C=this._pixelUv(v,y),w=(0,n.textureLoad)(s,p),T=C.sub(w.xy).toVar(),E=(0,n.textureLoad)(l,p).toVar(),D=E.y.toVar(),O=(0,n.uint)(E.z.add(.5)).toVar(),k=E.w.greaterThan(.5),A=this._bilinear(T),j=[1,2,4,8].map(e=>(0,n.select)(O.bitAnd((0,n.uint)(e)).notEqual((0,n.uint)(0)),(0,n.float)(1),(0,n.float)(0))),M=A.customWeights(j).map(e=>e.toVar()),N=(0,n.sqrt)((0,n.saturate)(A.filter(j))).toVar(),P=(0,n.textureLoad)(c,p).toVar(),F=P.x.toVar(),I=F.toVar(),L=F.mul(F).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(Ty),F,(0,n.textureLoad)(c,r).x);I.addAssign(o),L.addAssign(o.mul(o))}I.divAssign(9),L.divAssign(9);let R=yb(I,L).toVar();(0,n.If)(D.lessThan(t.historyFixFrameNum),()=>{F.assign((0,n.min)(F,I.mul((0,n.float)(1.2).add((0,n.float)(1).div(D.add(1))))))});let ee=(0,n.max)(this._sampleHistory(e=>(0,n.textureLoad)(u,e),T,A,M,k).x,0).toVar(),z=R.mul(t.antilag.x),te=t.antilag.y.mul(4),ne=ee.clamp(I.sub(z),I.add(z)),re=ee.sub(ne).abs().div((0,n.max)(ee,ne).add(By)),ie=(0,n.float)(1).div((0,n.float)(1).add(re.mul(D.mul(N)).div(te))).toVar(),ae=(0,n.min)(D,t.historyFixFrameNum);D.assign((0,n.mix)(ae,D,ie));let oe=h.add(1),se=this._handover(oe),ce=N.mul((0,n.float)(1).sub(this._advancedNonLinear(D.mul((0,n.float)(1).sub(se)).div(oe)))).mul(ie).toVar(),B=(0,n.float)(1).add(ce.mul(6)),le=t.stabilizationStrength.mul((0,n.float)(1).sub(g)),ue=(0,n.mix)(F,ee.clamp(I.sub(R.mul(B)),I.add(R.mul(B))),(0,n.min)(ce,le)).toVar();P.assign(_b(P,ue)),(0,n.textureStore)(e,m,(0,n.vec4)(ue,0,0,0)).toWriteOnly();let de=t.maxAccum.mul((0,n.float)(1).sub(g));(0,n.textureStore)(d,m,(0,n.vec4)((0,n.min)(D.add(1),de),S,0,0)).toWriteOnly();let fe=(0,n.textureLoad)(i,p),pe=(0,n.vec4)(hb(P.xyz).mul((0,n.max)(fe.xyz,(0,n.vec3)(Ey))),x.w).toVar();(0,n.If)(_.equal((0,n.int)(1)),()=>{let e=(0,n.saturate)(D.div((0,n.max)(t.maxAccum,1)));pe.assign((0,n.vec4)((0,n.float)(1).sub(e),e,.2,1))}).ElseIf(_.equal((0,n.int)(2)),()=>{pe.assign((0,n.vec4)((0,n.vec3)(P.w),1))}).ElseIf(_.equal((0,n.int)(3)),()=>{pe.assign((0,n.vec4)((0,n.vec3)(S),1))}).ElseIf(_.equal((0,n.int)(4)),()=>{let e=E.x.div(E.x.add(1));pe.assign((0,n.vec4)((0,n.vec3)(e),1))}).ElseIf(_.equal((0,n.int)(5)),()=>{pe.assign((0,n.vec4)((0,n.vec3)(E.z.div(15)),1))}),(0,n.textureStore)(f,m,pe).toWriteOnly()})})().compute([this._dispatchX,this._dispatchY,1],[$y,$y,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=Sb(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/$y),this._dispatchY=Math.ceil(t/$y);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()}};cu();var wb=e=>(0,n.select)(e.equal(e),e,(0,n.float)(0)).clamp(0,1e7),Tb=(0,n.wgslFn)(`
|
|
918
|
+
`,mv=32,hv=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(mv),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}=sv();this._shaderVersion!==r&&(this._pipelines.clear(),this._bindings=n,this._shaderVersion=r);let i=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:pv(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*fv[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:mv,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?.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})}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*fv[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.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&&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()}}}}));gv(),ps(),er(),rn();var _v=class{constructor({issues:e=null}={}){this._issues=e,this._renderer=null,this._offRegistry=qo(()=>{this._renderer&&ts(this._renderer)})}get hasConfig(){return!1}get workingSpace(){return Kr}get workingSpaceAdopted(){return!1}get inputKey(){return`-`}attachRenderer(e){this._renderer=e;let t=ts(e);return e.outputColorSpace=r.SRGBColorSpace,t}listViews(){return Yo()}get activeView(){return null}setActiveView(e){let t=Jo(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(){qn(null,Kr)}loadConfig(){let e=`colour configs need the OCIO pipeline: renderer.setColorManagement( ColorManagement ), from rayzee/addons/color`;return this._issues?.record(Z.CAPABILITY_MISSING,e,{capability:`color`}),Promise.reject(Error(e))}unloadConfig(){}setWorkingSpace(){}exportPixels(e){return{rgba:e,colorSpace:Kr}}status(){let e=this._renderer?Jo(this._renderer.toneMapping):null;return{config:null,workingSpace:Kr,workingSpaceAdopted:!1,activeTransform:e?{id:e.id,name:e.name,source:e.source}:null,activeView:null,context:null,exportSpace:null,views:Yo(),registryVersion:Ko(),bakeError:e?.error??null}}dispose(){this._offRegistry?.(),this._renderer=null,this._issues=null,Jr()===this&&(qn(null),Yr(null))}};Ar();var vv=[[/\.jpe?g(\?|#|$)/i,`image/jpeg`],[/\.webp(\?|#|$)/i,`image/webp`],[/\.avif(\?|#|$)/i,`image/avif`]];function yv(e){return e.mimeType?e.mimeType:e.uri?.startsWith(`data:`)?e.uri.slice(5,e.uri.indexOf(`;`)):vv.find(([t])=>t.test(e.uri??``))?.[1]??`image/png`}function bv(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 xv({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 Sv(e,t){return Sr().decodeImage(t===`image/png`?bv(e):e,t)}async function Cv(e){let t=await fetch(e);if(!t.ok)throw Error(`HTTP ${t.status}`);return new Uint8Array(await t.arrayBuffer())}function wv(e,t){return t.bufferView===void 0?Cv(e.options.manager.resolveURL(r.LoaderUtils.resolveURL(t.uri,e.options.path))):e.getDependency(`bufferView`,t.bufferView).then(e=>new Uint8Array(e))}var Tv=(e,t)=>!!t&&t!==e.textureLoader&&typeof t.parse==`function`;function Ev(e,t,n){if(e.sourceCache[t]!==void 0)return e.sourceCache[t].then(e=>e.clone());let r=wv(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 Dv(e,t=yv({uri:e})){let n=xv(await Sv(await Cv(e),t));return n.flipY=!0,n}function Ov(e,t=null){return e.loadImageSource=function(e,n){if(Tv(this,n))return Ev(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 kv(e,t=null){return e.loadImageSource=function(e,n){if(Tv(this,n))return Ev(this,e,n);if(this.sourceCache[e]!==void 0)return this.sourceCache[e].then(e=>e.clone());let r=this.json.images[e],i=yv(r),a=r.uri??`bufferView ${r.bufferView}`,o=wv(this,r).then(e=>Sv(e,i)).then(e=>{let t=xv(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 Av=`KHR_materials_diffuse_transmission`;function jv(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:Av,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?.[Av];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)}}}ai();var Mv=`KHR_draco_mesh_compression`,Nv=`KHR_texture_basisu`,Pv=[`EXT_meshopt_compression`,`KHR_meshopt_compression`],Fv=new TextDecoder;function Iv(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 Fv.decode(e);let n=Math.min(t.getUint32(12,!0),e.byteLength-20);return Fv.decode(new Uint8Array(e,20,n))}async function Lv(e,t,n){let{dracoDecoderPath:r,ktx2TranscoderPath:i}=ni(),[a,o,s]=await Promise.all([t.includes(Mv)&&!e.dracoLoader?import(`three/addons/loaders/DRACOLoader.js`):null,t.includes(Nv)&&!e.ktx2Loader?import(`three/addons/loaders/KTX2Loader.js`):null,Pv.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 Rv(e,t){let n=e.parse.bind(e);return e.parse=(r,i,a,o)=>{Lv(e,Iv(r),t).then(()=>n(r,i,a,o),e=>o?.(e))},e}function zv(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 Bv(e){let t=typeof e==`string`?parseFloat(e):e;return Number.isFinite(t)?t:void 0}function Vv(e){let t=zv(e);if(!t)return null;let n=e=>e&&(e.environment!==void 0||e.render!==void 0),r=zv(t.rayzee);return n(r)?r:n(t)?t:null}function Hv(e){let t=zv(e);if(!t)return null;let n=Kv.map(e=>t[e]).find(e=>typeof e==`string`&&e.trim());if(!n)return null;let r=Bv(t.rotation),i=Bv(t.intensity),a={sourceFile:n.trim()};return r!==void 0&&(a.rotation=r),i!==void 0&&(a.intensity=Math.max(0,i)),a}function Uv(e){let t=zv(e);if(!t)return null;let n={};for(let e of qv){let r=Bv(t[e]);r!==void 0&&r>0&&(n[e]=Math.round(r))}return Object.keys(n).length?n:null}function Wv(e){let t=Vv(e);if(!t)return null;let n=Hv(t.environment),r=Uv(t.render);return!n&&!r?null:{...n?{environment:n}:{},...r?{render:r}:{}}}function Gv(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=Wv(e);if(t)return t}return null}var Kv,qv,Jv=g((()=>{Kv=[`sourceFile`,`url`,`file`],qv=[`maxBounces`,`samples`,`width`,`height`]}));mi(),ue(),Ar(),Jv(),rn(),at(),Oe();var Yv=_e(`assets`),Xv={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`}},Zv={addOn:`rayzee/addons/archives`,install:`assetLoader.setArchiveImporter()`},Qv={addOn:`rayzee/addons/formats`,install:`assetLoader.registerFormat()`},$v={zip:Zv,gz:Zv,tgz:Zv,tar:Zv,fbx:Qv,obj:Qv,stl:Qv,ply:Qv,dae:Qv,"3mf":Qv,usd:Qv,usda:Qv,usdc:Qv,usdz:Qv,exr:Qv};function ey(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 ty=683;function ny(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 ry=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??(()=>K.areaLightIntensityScale),this._loadingManager.onError=e=>{this._loadCancelled||this._issues?.record(Z.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 L_(t,{downloads:this.downloads,key:i,policy:a,name:A_(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 P_(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;B({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){B({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 Xv[t]||this._formats.get(t)||this._archiveFormats?.[t]||null}formatError(e){let t=$v[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)}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);B({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 ${Zv.addOn} — install it with ${Zv.install}`);B({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=A_(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,B({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`,W_(await H_(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{B({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,B({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 oi(r,W_(await H_(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)&&oi(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&&$v[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):Sr().decodeImage?(d=await Dv(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&&iy(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=Rv(new o.GLTFLoader(this._loadingManager),this.renderer),t=(e,t)=>this._reportImageFailure(e,t);return Sr().decodeImage?e.register(e=>kv(e,t)):wr()||e.register(e=>Ov(e,t)),e.register(e=>jv(e)),e}_reportImageFailure(e,t){try{this._issues?.record(Z.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{B({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 Er(()=>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=Gv(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{B({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 Er(()=>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?(re(e),e.parent?.remove(e)):ne(e))}async loadGLBFromArrayBuffer(e,t=`model.glb`){let n=await this.createGLTFLoader();try{B({isLoading:!0,status:`Processing GLB Data...`,progress:5}),await new Promise(e=>setTimeout(e,0));let r=await Er(()=>n.parseAsync(e,``));return this._throwDeferred(),this.releaseTargetModel(),this.targetModel=r.scene,this.animations=r.animations||[],this.sceneMetadata=Gv(r),B({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,B({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 qs(`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*=ny(e,e.width,e.height,i),i.__radianceConverted=!0),(e.isPointLight||e.isSpotLight)&&!i.__candelaConverted&&(e.intensity*=4*Math.PI/ty,i.__candelaConverted=!0),e.isDirectionalLight&&!i.__luxConverted&&(e.intensity/=ty,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*ny(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(Z.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=ey(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={...Xv,...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 iy(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,Yv.info(`environment ${r}×${i} shrunk to ${o}×${s} (memory spill)`)}var ay={addEventListener(){},removeEventListener(){},dispatchEvent(){return!0}},oy=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 sy(e=1,t=1){let n={...ay,defaultView:null},r={...ay,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 oy(r);return r}var cy=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`,uy={DirectionalLight:r.DirectionalLight,PointLight:r.PointLight,SpotLight:r.SpotLight,RectAreaLight:r.RectAreaLight},dy=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:tr(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=uy[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=nr(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}};at(),Pt(),Kn(),ue(),Oe(),F(),rn(),ai(),Z_(),ps(),So(),gc();var fy=({element:e,pbrtEntry:t}={})=>({...e===void 0?{}:{element:e},...t===void 0?{}:{pbrtEntry:t}}),py=new WeakMap,my=3e4,hy=new Set([...Object.values(N),...Object.values(P)]),gy=new Set;async function _y(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 vy=_e(`engine`);function yy(){let e=new Float32Array(16);return new Uint32Array(e.buffer)[3]=wt.TRIANGLE_LEAF,e}function by(e,t){e.lost.then(e=>{t.app&&t.app._handleDeviceLost(e)})}var xy=/swiftshader|llvmpipe|lavapipe|basic render|microsoft basic|warp/i;function Sy(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 Cy=class extends r.EventDispatcher{constructor(e,t={}){super(),this._headless=t.headless===!0||!e,e??=sy();try{py.get(e)?.dispose()}catch(e){vy.warn(`prior canvas owner dispose failed`,e)}if(py.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 nn({strict:t.strict===!0,onIssue:e=>this.dispatchEvent({type:N.ISSUE,issue:e})}),this.color=new _v({issues:this._issues}),Yr(this.color),this.settings=new ov(K,{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 C_,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){vy.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(q.FLOATS_PER_TRIANGLE),0),this.stages.pathTracer.setBVHData(yy()),this.stages.pathTracer.materialData.setMaterialData(new Float32Array(16)),this.stages.pathTracer.setupMaterial(),this.isInitialized=!0,vy.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&&!ti(`storage`)?!1:ni().storage);if(e!==!1){if(e&&typeof e==`object`)this.storage=e;else{if(!this._storageOpener){(this._storageOption!==void 0||ti(`storage`))&&this._issues.warn(Z.CAPABILITY_MISSING,`on-disk storage needs rayzee/addons/storage: setStorageOpener( acquireSharedStorage )`);return}let{storage:e,reason:t,release:n}=await this._storageOpener(ni().cacheNamespace);if(this._disposed){n();return}if(!e){this._issues.warn(Z.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){!hy.has(e)&&!gy.has(e)&&(gy.add(e),vy.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(),le({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,vy.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){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])ne(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){vy.warn(`failed to clear TSL texture singleton listeners`,e)}this.canvas&&py.get(this.canvas)===this&&py.delete(this.canvas),this._gpuDevice&&=(this._gpuDevice.onuncapturederror=null,null),this._deviceLostHolder&&=(this._deviceLostHolder.app=null,null),te(this.renderer),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(q.FLOATS_PER_TRIANGLE),0),this.stages.pathTracer.setBVHData(yy()),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??A_(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,...fy(t)});return}if(tv(e)){let n=Q_(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 U_(n);return{kind:`local-folder`,folder:e,key:W_(e),...n.flat?{flat:!0}:{},...fy(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=H_(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?W_(e):null,...fy(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&&!tv(this._sceneSourceInput)?this._sceneSourceInput:null}get sceneSourceFolder(){return tv(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?vo:0);try{await e(),this._sceneSource=typeof n==`function`?await n():n,this._sceneSourceInput=null,this._emissiveSamplingUserSet=!1,this._clearAppendedModels(),this._modelReplaced(),this._planSpill(),await this.loadSceneData({pendingEnvironment:this._beginSceneMetadataEnvironment()}),this._maybeSpill(),this.pipeline?.eventBus.emit(`pipeline:lightingChanged`),this._dropDisplay(),this.reset(),this.dispatchEvent(t),this._modelAnnounced()}catch(e){throw(!e||e.code!==`LOAD_IN_PROGRESS`)&&this._discardFailedLoad(),e?.code===`ARCHIVE_NEEDS_ELEMENT`?ce():e?.code!==`LOAD_IN_PROGRESS`&&B({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(Z.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 qs(``,{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(Z.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)`),B({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`),B({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&&(B({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()),ce(),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[U.count(e.triangleCount,`tri`),t?U.count(t,`mesh`,`meshes`):null,U.count(e.materialData.materialCount,`material`),n?U.count(n,`map`):null,U.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:go,maxPlacements:_o,...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?vo:0);let t=e?this.meshScene?.environment:null,n=t?.image;return n&&iy(t,vo),t&&t.image!==n&&(t.dispose(),t.needsUpdate=!0),e&&this._memorySpill===`auto`&&vy.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(Z.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(Z.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(Z.STORAGE_WRITE_FAILED,`memory spill failed: ${e.message}`))},my),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(Z.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,W);if(!this.renderer)return this._pendingReservedRenderSize={requestedPx:e,allowLower:t},Math.max(256,Math.min(ke,Math.floor(n)||256));let r=this.renderer.backend?.device?.limits?.maxStorageBufferBindingSize||128*1024*1024,i=ro(this._hostMemoryGB),a=i.gb>=8&&r>=1024*1024*1024?ke:2048,o=Ae(Math.min(n,a));if(o<Math.floor(e)&&this._issues.warn(Z.RENDER_RESERVE_CAPPED,`reserved render size ${U.n(e)}px was capped to ${U.n(o)}px by this device's limits — renders above ${U.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 W}_isRenderSizeSupported(e,t){return e>W||t>W?(this._issues.record(Z.RENDER_SIZE_DECLINED,`render resolution ${e}×${t} exceeds the ${W}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:W}),!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 tr({engine:hc,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:hc,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;if(e===`srgb`){let r=n===`display`?this._displaySource(i):null,s={exposure:this.renderer.toneMappingExposure,toneMapping:this.renderer.toneMapping,saturation:this.settings.get(`saturation`)??1,preserveAlpha:t,gain:this._displayGain()},c=await this._toneMapOnGPU(r?.texture??null,i,a,o,s),l=!c&&s.gain?await s.gain.cpu():null;return{data:c??ws(r?await this._readTexture(r.texture,a,o):await this.renderer.readRenderTargetPixelsAsync(i,0,0,a,o,0),{...s,pixelGain:l&&{fn:l,width:a,height:o}}),width:a,height:o,colorSpace:e,source:r?.source??`accumulation`,toneMappedOn:c?`gpu`:`cpu`}}let{data:s,source:c}=n===`display`?await this._readDisplaySource(i,a,o):{data:await this.renderer.readRenderTargetPixelsAsync(i,0,0,a,o,0),source:`accumulation`};if(e===`linear`)return{data:s,width:a,height:o,colorSpace:e,workingSpace:this.color?.workingSpace??null,source:c};let{rgba:l,colorSpace:u}=this.color.exportPixels(s,e);return{data:l,width:a,height:o,colorSpace:u,source:c}}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 hv(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 tn)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 vy.warn(r),this._issues.warn(Z.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=>vy.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&&mr.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(Z.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(Z.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 this.renderer.readRenderTargetPixelsAsync(e,0,0,t,n,0),source:`accumulation`}}_readbackPass(){return this._textureReadback??=new w_(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}),Yr(this.color),this.renderer&&this.color.attachRenderer(this.renderer)}async loadColorConfig(e={}){await this._leaveColorWorkingSpace();let t=Jo(this.renderer?.toneMapping),n=await this.color.loadConfig(e);return this.color.workingSpaceAdopted&&await this.applyColorWorkingSpace(),(!(t?.source===`ocio`&&Jo(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){vy.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&&Ln(e||this.meshScene)&&(this._sdf.textureCoordinates=!0,t.setTriangleData(this._sdf.triangles,this._sdf.triangleCount,{textureCoordinates:!0}),t.setupMaterial()),this.reset()}async _initRenderer(){if(I(e=>this.dispatchEvent(e)),typeof navigator>`u`||!navigator.gpu)throw Error("WebGPU is not available — outside a browser, install one as navigator.gpu (for Node, the `webgpu` package)");let e=await navigator.gpu.requestAdapter({powerPreference:`high-performance`});if(!e)throw Error(`Failed to get WebGPU adapter`);this.adapterInfo=Sy(e),this.adapterInfo.isSoftware&&(this._issues.warn(Z.ADAPTER_SOFTWARE,`software GPU adapter "${this.adapterInfo.description||this.adapterInfo.vendor}" — renders are correct but orders of magnitude slower than hardware`,{...this.adapterInfo}),vy.warn(`software GPU adapter — check app.adapterInfo.isSoftware. ${this.adapterInfo.description}`));let n=e.limits,r={maxColorAttachmentBytesPerSample:128};for(let e of[`maxBufferSize`,`maxStorageBufferBindingSize`,`maxSampledTexturesPerShaderStage`,`maxStorageTexturesPerShaderStage`,`maxTextureArrayLayers`,`maxTextureDimension2D`,`maxComputeInvocationsPerWorkgroup`,`maxComputeWorkgroupStorageSize`,`maxComputeWorkgroupSizeX`,`maxComputeWorkgroupSizeY`,`maxComputeWorkgroupSizeZ`]){let t=n[e];t!==void 0&&(r[e]=t)}if(r.maxStorageBuffersPerShaderStage=Math.min(n.maxStorageBuffersPerShaderStage,10),this.renderer=new t.WebGPURenderer({canvas:this.canvas,alpha:!0,powerPreference:`high-performance`,requiredLimits:r}),await _y(this.renderer,this._headless),!this.renderer.backend?.isWebGPUBackend)throw Error(`WebGPU backend unavailable — three.js fell back to WebGL2, which cannot run the path tracer's compute kernels. Check GPU process flags and driver support.`);let a=this.renderer.backend?.device;a?.lost&&(this._gpuDevice=a,this._deviceLostHolder={app:this},by(a,this._deviceLostHolder),a.onuncapturederror=e=>vy.error(`WebGPU uncaptured error:`,e.error)),t.RectAreaLightNode.setLTC(i.RectAreaLightTexturesLib.init()),this.renderer.outputColorSpace=t.SRGBColorSpace,this.renderer.toneMapping=fs,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 qc({issues:this._issues,...this._maxSceneBytes===void 0?{}:{maxSceneBytes:this._maxSceneBytes}}),this.assetLoader=new ry(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 x_(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 dy(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()});else if(e.texture){let e=this.meshScene.environment;e&&this.stages.pathTracer&&await this.stages.pathTracer.environment.setEnvironmentMap(e),ce()}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 s_(this.renderer,this.scene,this.camera,{hostMemoryGB:this._hostMemoryGB,sortMaterials:this.settings.get(`wavefrontSortMaterials`)}),this._extraStages=this._createExtraStages(),this.stages.compositor=new c_(this.renderer,{saturation:this.settings.get(`saturation`)??K.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 cy(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(){}},wy=65504,Ty=6e4,Ey=.01,Dy={low:{temporalAlpha:.1,gradientStrength:.8,gradientSigmaScale:2.5,gradientNoiseFloor:.05,atrousIterations:3,phiColor:1,phiNormal:64,phiDepth:.1,phiLuminance:6,maxAccumFrames:16,varianceBoost:.5},medium:{temporalAlpha:.03,gradientStrength:1,gradientSigmaScale:2.5,gradientNoiseFloor:.05,atrousIterations:4,phiColor:.5,phiNormal:128,phiDepth:.05,phiLuminance:4,maxAccumFrames:64,varianceBoost:1},high:{temporalAlpha:0,gradientStrength:1,gradientSigmaScale:2.5,gradientNoiseFloor:.05,atrousIterations:6,phiColor:.3,phiNormal:256,phiDepth:.02,phiLuminance:2,maxAccumFrames:128,varianceBoost:1.5}},Oy=3,ky=.1,Ay={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},jy=[`maxAccumulatedFrameNum`,`maxFastAccumulatedFrameNum`,`maxStabilizedFrameNum`,`historyFixFrameNum`,`prepassBlurRadius`,`maxBlurRadius`,`enableAntiFirefly`],My={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}},Ny=Dy.medium,Py={denoiserStrategy:`none`,filterStrength:1,edgeAtrousIterations:5,edgePhiLuminance:4,edgePhiNormal:64,edgePhiDepth:.1,enableOIDN:!1,oidnQuality:`fast`,continuousDenoise:!1,continuousDenoiseInterval:8,oidnTemporalHistory:!0,enableUpscaler:!1,upscalerScale:2,upscalerQuality:`fast`,upscalerHdr:!0,enableASVGF:!1,asvgfQualityPreset:`medium`,asvgfTemporalAlpha:Ny.temporalAlpha,asvgfAtrousIterations:Ny.atrousIterations,asvgfPhiColor:Ny.phiColor,asvgfPhiNormal:Ny.phiNormal,asvgfPhiDepth:Ny.phiDepth,asvgfPhiLuminance:Ny.phiLuminance,asvgfVarianceBoost:Ny.varianceBoost,asvgfMaxAccumFrames:Ny.maxAccumFrames,asvgfGradientStrength:Ny.gradientStrength,asvgfGradientSigmaScale:Ny.gradientSigmaScale,asvgfGradientNoiseFloor:Ny.gradientNoiseFloor,asvgfDebugMode:0,showAsvgfHeatmap:!1,nrdQualityPreset:`medium`,nrdDebugMode:0};_l(),cu();var Fy=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=Yd(),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(W,W),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(W,W),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&&ip(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=rp(this.pathTracer?.materialData?.linearBuckets);let i={srgbBuckets:rp(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=ir((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=tl(Xd((0,n.vec2)((0,n.float)(o).add(.5).div(s),(0,n.float)(f).add(.5).div(c)),i,a,this.cameraRay)),m=ol.wrap(wf(p,t,e)),h=m.normal.mul(.5).add(.5),g=(0,n.min)(m.dst,(0,n.float)(65504)),_=m.didHit.select((0,n.vec4)(h,g),(0,n.vec4)(0,0,0,(0,n.float)(wy)));(0,n.textureStore)(l,(0,n.uvec2)((0,n.uint)(o),(0,n.uint)(f)),_).toWriteOnly(),d&&(0,n.textureStore)(d,(0,n.uvec2)((0,n.uint)(o),(0,n.uint)(f)),(0,n.uvec4)((0,n.uint)(m.instanceLeaf.add(1)),0,0,0)).toWriteOnly();let v=m.normal.toVar(),y=(0,n.float)(1).toVar();(0,n.If)(m.didHit,()=>{let i=nl.wrap($l(m.materialIndex,r)).toVar(),a=hl.wrap(lp(m.uv,i)).toVar(),o=(0,n.vec4)(0).toVar();(0,n.If)(i.normalMapIndex.greaterThanEqual((0,n.int)(0)),()=>{o.assign(pp(e,m.triangleIndex,m.normal,i.normalTransform,t,m.instanceLeaf))});let s=mp(m.normal,i,a,o).toVar();v.assign(hp(s,i,a)),y.assign(dp(i,a).y.clamp(.05,1))});let b=m.didHit.select((0,n.vec4)(v.mul(.5).add(.5),y),(0,n.vec4)(0,0,0,1));(0,n.textureStore)(u,(0,n.uvec2)((0,n.uint)(o),(0,n.uint)(f)),b).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(W,W);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(W,W);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()}},Iy=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.isFirstFrame=!0,this.frameCount=0,this.cameraWorldMatrix=(0,n.uniform)(new r.Matrix4,`mat4`),this.cameraProjectionMatrixInverse=(0,n.uniform)(new r.Matrix4,`mat4`),this.cameraRay=Yd(),this.prevVP=(0,n.uniform)(new r.Matrix4,`mat4`),this.isFirstFrameU=(0,n.uniform)(1),this.deltaTime=(0,n.uniform)(1/60),this.velocityScale=(0,n.uniform)(1),this.resolutionWidth=(0,n.uniform)(o),this.resolutionHeight=(0,n.uniform)(s),this._normalDepthTexNode=new t.TextureNode,this._screenSpaceStorageTex=new t.StorageTexture(W,W),this._screenSpaceStorageTex.type=r.HalfFloatType,this._screenSpaceStorageTex.format=r.RGBAFormat,this._screenSpaceStorageTex.minFilter=r.NearestFilter,this._screenSpaceStorageTex.magFilter=r.NearestFilter,this._worldSpaceStorageTex=new t.StorageTexture(W,W),this._worldSpaceStorageTex.type=r.HalfFloatType,this._worldSpaceStorageTex.format=r.RGBAFormat,this._worldSpaceStorageTex.minFilter=r.NearestFilter,this._worldSpaceStorageTex.magFilter=r.NearestFilter,this._srcRegion=new r.Box2(new r.Vector2(0,0),new r.Vector2(0,0));let c={type:r.HalfFloatType,format:r.RGBAFormat,minFilter:r.NearestFilter,magFilter:r.NearestFilter,depthBuffer:!1,stencilBuffer:!1};this.screenSpaceTarget=new t.RenderTarget(o,s,c),this.worldSpaceTarget=new t.RenderTarget(o,s,c),this._dispatchX=Math.ceil(o/16),this._dispatchY=Math.ceil(s/16),this._buildScreenSpaceCompute(),this._buildWorldSpaceCompute()}_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=Zd(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])}_buildWorldSpaceCompute(){let e=this._normalDepthTexNode,t=this.cameraWorldMatrix,r=this.cameraProjectionMatrixInverse,i=this.prevVP,a=this.isFirstFrameU,o=this.deltaTime,s=this.velocityScale,c=this.resolutionWidth,l=this.resolutionHeight,u=this._worldSpaceStorageTex;this._worldSpaceComputeNode=(0,n.Fn)(([t,r])=>{let d=(0,n.int)(n.workgroupId.x).mul(16).add((0,n.int)(n.localId.x)),f=(0,n.int)(n.workgroupId.y).mul(16).add((0,n.int)(n.localId.y));(0,n.If)(d.lessThan((0,n.int)(c)).and(f.lessThan((0,n.int)(l))),()=>{let p=(0,n.textureLoad)(e,(0,n.ivec2)(d,f)).w,m=(0,n.vec4)(0,0,0,0).toVar();(0,n.If)(a.lessThan(.5).and(p.lessThan((0,n.float)(6e4))),()=>{let e=(0,n.vec2)((0,n.float)(d).add(.5).div(c),(0,n.float)(f).add(.5).div(l)),a=Zd(e,p,t,r,this.cameraRay),u=i.mul((0,n.vec4)(a,1)),h=u.xy.div(u.w),g=(0,n.vec2)(h.x.mul(.5).add(.5),h.y.mul(-.5).add(.5)),_=g.x.greaterThanEqual(0).and(g.x.lessThanEqual(1)).and(g.y.greaterThanEqual(0)).and(g.y.lessThanEqual(1)),v=e.sub(g),y=(0,n.vec3)(v.x.div(o).mul(s),v.y.div(o).mul(s),0);m.assign(_.select((0,n.vec4)(y,1),(0,n.vec4)(0,0,0,.5)))}),(0,n.textureStore)(u,(0,n.uvec2)((0,n.uint)(d),(0,n.uint)(f)),m).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)}setupEventListeners(){this.on(`pipeline:reset`,()=>{this.reset()})}render(e){if(!this.enabled)return;let t=e.getTexture(`pathtracer:normalDepth`);if(!t)return;this._updateCameraMatrices(),this.isFirstFrameU.value=+!!this.isFirstFrame,this.frameCount++;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.renderer.compute(this._worldSpaceComputeNode),this._srcRegion.max.set(this.screenSpaceTarget.width,this.screenSpaceTarget.height),this.renderer.copyTextureToTexture(this._screenSpaceStorageTex,this.screenSpaceTarget.texture,this._srcRegion),this.renderer.copyTextureToTexture(this._worldSpaceStorageTex,this.worldSpaceTarget.texture,this._srcRegion),e.setTexture(`motionVector:screenSpace`,this.screenSpaceTarget.texture),e.setTexture(`motionVector:worldSpace`,this.worldSpaceTarget.texture),e.setTexture(`motionVector:motion`,this.screenSpaceTarget.texture),this.emit(`motionvector:computed`,{frame:this.frameCount,isFirstFrame:this.isFirstFrame}),this.isFirstFrame=!1}releaseGPUMemory(){this._screenSpaceStorageTex?.dispose(),this._worldSpaceStorageTex?.dispose(),this.reset()}reset(){this.matricesInitialized||(this.isFirstFrame=!0),this.frameCount=0}setSize(e,t){this.screenSpaceTarget.setSize(e,t),this.screenSpaceTarget.texture.needsUpdate=!0,this.worldSpaceTarget.setSize(e,t),this.worldSpaceTarget.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]),this._worldSpaceComputeNode&&(this._worldSpaceComputeNode.dispatchSize=[this._dispatchX,this._dispatchY,1])}setVelocityScale(e){this.velocityScale.value=e}setDeltaTime(e){this.deltaTime.value=e}reallocateReservedStorage(){this._screenSpaceComputeNode?.dispose(),this._worldSpaceComputeNode?.dispose(),this._screenSpaceStorageTex?.dispose(),this._worldSpaceStorageTex?.dispose();let e=()=>{let e=new t.StorageTexture(W,W);return e.type=r.HalfFloatType,e.format=r.RGBAFormat,e.minFilter=r.NearestFilter,e.magFilter=r.NearestFilter,e};this._screenSpaceStorageTex=e(),this._worldSpaceStorageTex=e(),this._buildScreenSpaceCompute(),this._buildWorldSpaceCompute()}dispose(){this._screenSpaceComputeNode?.dispose(),this._worldSpaceComputeNode?.dispose(),this._screenSpaceStorageTex?.dispose(),this._worldSpaceStorageTex?.dispose(),this.screenSpaceTarget?.dispose(),this.worldSpaceTarget?.dispose(),this._normalDepthTexNode?.dispose()}};cu();var Ly=e=>(0,n.select)(e.equal(e),e,(0,n.float)(0)).clamp(0,1e7),Ry=e=>(0,n.vec3)(Ly(e.x),Ly(e.y),Ly(e.z)),zy=class extends j{constructor(e,i={}){super(`ASVGF`,{...i,executionMode:A.PER_CYCLE}),this.renderer=e,this.temporalAlpha=(0,n.uniform)(i.temporalAlpha??Dy.medium.temporalAlpha),this.gradientStrength=(0,n.uniform)(i.gradientStrength??Dy.medium.gradientStrength),this.gradientSigmaScale=(0,n.uniform)(i.gradientSigmaScale??Dy.medium.gradientSigmaScale),this.gradientNoiseFloor=(0,n.uniform)(i.gradientNoiseFloor??Dy.medium.gradientNoiseFloor),this.maxAccumFrames=(0,n.uniform)(i.maxAccumFrames??Dy.medium.maxAccumFrames),this.resW=(0,n.uniform)(i.width||1),this.resH=(0,n.uniform)(i.height||1),this.temporalEnabledU=(0,n.uniform)(1),this.forceResetU=(0,n.uniform)(0),this._colorTexNode=new t.TextureNode,this._albedoTexNode=new t.TextureNode,this._motionTexNode=new t.TextureNode,this._normalDepthTexNode=new t.TextureNode,this._prevNormalDepthTexNode=new t.TextureNode,this._readTemporalTexNode=new t.TextureNode,this._gradientReadTexNode=new t.TextureNode;let a=i.width||1,o=i.height||1;this._temporalTexA=new t.StorageTexture(W,W),this._temporalTexA.type=r.FloatType,this._temporalTexA.format=r.RGBAFormat,this._temporalTexA.minFilter=r.LinearFilter,this._temporalTexA.magFilter=r.LinearFilter,this._temporalTexB=new t.StorageTexture(W,W),this._temporalTexB.type=r.FloatType,this._temporalTexB.format=r.RGBAFormat,this._temporalTexB.minFilter=r.LinearFilter,this._temporalTexB.magFilter=r.LinearFilter,this._outputModulatedTex=new t.StorageTexture(W,W),this._outputModulatedTex.type=r.FloatType,this._outputModulatedTex.format=r.RGBAFormat,this._outputModulatedTex.minFilter=r.LinearFilter,this._outputModulatedTex.magFilter=r.LinearFilter,this._gradientStorageTex=new t.StorageTexture(W,W),this._gradientStorageTex.type=r.HalfFloatType,this._gradientStorageTex.format=r.RGBAFormat,this._gradientStorageTex.minFilter=r.LinearFilter,this._gradientStorageTex.magFilter=r.LinearFilter,this._srcRegion=new r.Box2(new r.Vector2(0,0),new r.Vector2(0,0)),this._demodulatedRT=new t.RenderTarget(a,o,{type:r.FloatType,format:r.RGBAFormat,minFilter:r.LinearFilter,magFilter:r.LinearFilter,depthBuffer:!1,stencilBuffer:!1}),this._outputRT=new t.RenderTarget(a,o,{type:r.FloatType,format:r.RGBAFormat,minFilter:r.LinearFilter,magFilter:r.LinearFilter,depthBuffer:!1,stencilBuffer:!1}),this._gradientRT=new t.RenderTarget(a,o,{type:r.HalfFloatType,format:r.RGBAFormat,minFilter:r.LinearFilter,magFilter:r.LinearFilter,depthBuffer:!1,stencilBuffer:!1}),this.currentMoments=0,this._compiled=!1,this._needsWarmReset=!1,this._dispatchX=Math.ceil(a/8),this._dispatchY=Math.ceil(o/8),this._buildGradientCompute(),this._buildTemporalCompute(),this.showHeatmap=!1,this.debugMode=(0,n.uniform)(0,`int`),this._heatmapStorageTex=new t.StorageTexture(W,W),this._heatmapStorageTex.type=r.FloatType,this._heatmapStorageTex.format=r.RGBAFormat,this._heatmapStorageTex.minFilter=r.NearestFilter,this._heatmapStorageTex.magFilter=r.NearestFilter,this.heatmapTarget=new t.RenderTarget(a,o,{type:r.FloatType,format:r.RGBAFormat,minFilter:r.NearestFilter,magFilter:r.NearestFilter,depthBuffer:!1,stencilBuffer:!1}),this._heatmapRawColorTexNode=new t.TextureNode,this._heatmapColorTexNode=new t.TextureNode,this._heatmapTemporalTexNode=new t.TextureNode,this._heatmapNDTexNode=new t.TextureNode,this._heatmapMotionTexNode=new t.TextureNode,this._heatmapGradientTexNode=new t.TextureNode,this._buildHeatmapCompute()}_buildGradientCompute(){let e=this._colorTexNode,t=this._albedoTexNode,r=this._motionTexNode,i=this._readTemporalTexNode,a=this.gradientNoiseFloor,o=this.gradientSigmaScale,s=this._gradientStorageTex,c=this.resW,l=this.resH,u=(0,n.workgroupArray)(`float`,144),d=(0,n.workgroupArray)(`float`,144);this._gradientNode=(0,n.Fn)(()=>{let f=n.localId.x,p=n.localId.y,m=p.mul(8).add(f),h=(0,n.int)(n.workgroupId.x).mul(8).sub(2).toVar(),g=(0,n.int)(n.workgroupId.y).mul(8).sub(2).toVar(),_=a=>{let o=a.mod((0,n.uint)(12)),s=a.div((0,n.uint)(12)),f=h.add((0,n.int)(o)).clamp((0,n.int)(0),(0,n.int)(c).sub(1)),p=g.add((0,n.int)(s)).clamp((0,n.int)(0),(0,n.int)(l).sub(1)),m=(0,n.textureLoad)(e,(0,n.ivec2)(f,p)).xyz,_=(0,n.textureLoad)(t,(0,n.ivec2)(f,p)).xyz,v=Rl(Ry(m.div((0,n.max)(_,(0,n.vec3)(Ey))))).toVar();u.element(a).assign(v);let y=(0,n.textureLoad)(r,(0,n.ivec2)(f,p)),b=(0,n.float)(f).sub(y.x.mul(c)),x=(0,n.float)(p).sub(y.y.mul(l)),S=(0,n.int)(b.add(.5)).clamp((0,n.int)(0),(0,n.int)(c).sub(1)),C=(0,n.int)(x.add(.5)).clamp((0,n.int)(0),(0,n.int)(l).sub(1)),w=y.w.greaterThan(.5),T=(0,n.textureLoad)(i,(0,n.ivec2)(S,C)).xyz,E=w.select(Rl(T),v);d.element(a).assign(E)};_(m);let v=m.add((0,n.uint)(64));(0,n.If)(v.lessThan((0,n.uint)(144)),()=>{_(v)});let y=m.add((0,n.uint)(128));(0,n.If)(y.lessThan((0,n.uint)(144)),()=>{_(y)}),(0,n.workgroupBarrier)();let b=(0,n.int)(n.workgroupId.x).mul(8).add((0,n.int)(f)),x=(0,n.int)(n.workgroupId.y).mul(8).add((0,n.int)(p));(0,n.If)(b.lessThan((0,n.int)(c)).and(x.lessThan((0,n.int)(l))),()=>{let e=(0,n.float)(0).toVar(),t=(0,n.float)(0).toVar();for(let r=-2;r<=2;r++)for(let i=-2;i<=2;i++){let a=p.add((0,n.uint)(2+r)).mul((0,n.uint)(12)).add(f.add((0,n.uint)(2+i))),o=u.element(a);e.addAssign(o),t.addAssign(o.mul(o))}let m=e.div(25),h=(0,n.sqrt)((0,n.max)(t.div(25).sub(m.mul(m)),(0,n.float)(0))).mul(o).toVar(),g=(0,n.float)(0).toVar();for(let e=-2;e<=2;e++)for(let t=-2;t<=2;t++){let r=p.add((0,n.uint)(2+e)).mul((0,n.uint)(12)).add(f.add((0,n.uint)(2+t))),i=u.element(r),o=d.element(r),s=(0,n.max)((0,n.max)((0,n.abs)(i.sub(o)).sub(h),(0,n.float)(0)).div((0,n.max)((0,n.max)(i,o),(0,n.float)(.001))).sub(a),(0,n.float)(0)).div((0,n.max)((0,n.float)(1).sub(a),(0,n.float)(1e-4)));g.addAssign(s.mul(s))}let _=g.div(25).clamp(0,1).toVar(),v=(0,n.textureLoad)(r,(0,n.ivec2)(b,x)),y=(0,n.int)((0,n.float)(b).sub(v.x.mul(c)).add(.5)).clamp((0,n.int)(0),(0,n.int)(c).sub(1)),S=(0,n.int)((0,n.float)(x).sub(v.y.mul(l)).add(.5)).clamp((0,n.int)(0),(0,n.int)(l).sub(1)),C=v.w.greaterThan(.5).select((0,n.textureLoad)(i,(0,n.ivec2)(y,S)).w,(0,n.float)(0)).div(4).clamp(0,1),w=_.mul(C);(0,n.textureStore)(s,(0,n.uvec2)((0,n.uint)(b),(0,n.uint)(x)),(0,n.vec4)(w,_,h,1)).toWriteOnly()})})().compute([this._dispatchX,this._dispatchY,1],[8,8,1])}_buildTemporalCompute(){this._temporalNodeA=this._buildTemporalForDirection(this._temporalTexA),this._temporalNodeB=this._buildTemporalForDirection(this._temporalTexB)}_buildTemporalForDirection(e){let t=this._colorTexNode,r=this._albedoTexNode,i=this._motionTexNode,a=this._normalDepthTexNode,o=this._prevNormalDepthTexNode,s=this._readTemporalTexNode,c=this._gradientReadTexNode,l=this._outputModulatedTex,u=this.maxAccumFrames,d=this.temporalAlpha,f=this.gradientStrength,p=this.temporalEnabledU,m=this.forceResetU,h=this.resW,g=this.resH;return(0,n.Fn)(()=>{let _=(0,n.int)(n.workgroupId.x).mul(8).add((0,n.int)(n.localId.x)),v=(0,n.int)(n.workgroupId.y).mul(8).add((0,n.int)(n.localId.y));(0,n.If)(_.lessThan((0,n.int)(h)).and(v.lessThan((0,n.int)(g))),()=>{let y=(0,n.ivec2)(_,v),b=(0,n.textureLoad)(t,y),x=b.xyz,S=b.w,C=(0,n.textureLoad)(r,y).xyz,w=(0,n.max)(C,(0,n.vec3)(Ey)),T=Ry(x.div(w)),E=(0,n.vec4)(T,1).toVar(),D=(0,n.vec4)(x,S).toVar();(0,n.If)(p.greaterThan(.5).and(m.lessThan(.5)),()=>{let e=(0,n.textureLoad)(i,y),t=e.w.greaterThan(.5),r=(0,n.float)(_).sub(e.x.mul(h)),l=(0,n.float)(v).sub(e.y.mul(g)),p=r.greaterThanEqual(0).and(r.lessThan((0,n.float)(h))).and(l.greaterThanEqual(0)).and(l.lessThan((0,n.float)(g)));(0,n.If)(t.and(p),()=>{let e=(0,n.textureLoad)(a,y),t=e.xyz.mul(2).sub(1),i=e.w,p=(0,n.int)(r),m=(0,n.int)(l),_=p.add((0,n.int)(1)),v=m.add((0,n.int)(1)),b=r.sub((0,n.float)(p)),x=l.sub((0,n.float)(m)),C=p.clamp((0,n.int)(0),(0,n.int)(h).sub(1)),O=_.clamp((0,n.int)(0),(0,n.int)(h).sub(1)),k=m.clamp((0,n.int)(0),(0,n.int)(g).sub(1)),A=v.clamp((0,n.int)(0),(0,n.int)(g).sub(1)),j=(0,n.float)(1).sub(b).mul((0,n.float)(1).sub(x)),M=b.mul((0,n.float)(1).sub(x)),N=(0,n.float)(1).sub(b).mul(x),P=b.mul(x),F=(e,r,a)=>{let s=(0,n.textureLoad)(o,(0,n.ivec2)(e,r)),c=s.xyz.mul(2).sub(1),l=s.w,u=(0,n.pow)((0,n.dot)(t,c).clamp(0,1),(0,n.float)(16)),d=(0,n.exp)((0,n.abs)(i.sub(l)).div((0,n.max)(i,(0,n.float)(.001))).div((0,n.float)(.05)).negate());return a.mul(u).mul(d)},I=F(C,k,j),L=F(O,k,M),R=F(C,A,N),ee=F(O,A,P),z=I.add(L).add(R).add(ee);(0,n.If)(z.greaterThan((0,n.float)(.01)),()=>{let e=(0,n.textureLoad)(s,(0,n.ivec2)(C,k)),t=(0,n.textureLoad)(s,(0,n.ivec2)(O,k)),r=(0,n.textureLoad)(s,(0,n.ivec2)(C,A)),i=(0,n.textureLoad)(s,(0,n.ivec2)(O,A)),a=(0,n.float)(1).div(z),o=e.xyz.mul(I).add(t.xyz.mul(L)).add(r.xyz.mul(R)).add(i.xyz.mul(ee)).mul(a),l=e.w.mul(I).add(t.w.mul(L)).add(r.w.mul(R)).add(i.w.mul(ee)).mul(a),p=(0,n.textureLoad)(c,y).x.mul(f).clamp(0,1),m=Ry((0,n.mix)(o,T,(0,n.mix)((0,n.max)((0,n.float)(1).div(l.add(1)),d),(0,n.float)(1),p))),h=(0,n.min)(l.add(1),u);E.assign((0,n.vec4)(m,h)),D.assign((0,n.vec4)(m.mul(w),S))})})}),(0,n.textureStore)(e,(0,n.uvec2)((0,n.uint)(_),(0,n.uint)(v)),E).toWriteOnly(),(0,n.textureStore)(l,(0,n.uvec2)((0,n.uint)(_),(0,n.uint)(v)),D).toWriteOnly()})})().compute([this._dispatchX,this._dispatchY,1],[8,8,1])}_buildHeatmapCompute(){let e=this._heatmapRawColorTexNode,t=this._heatmapColorTexNode,r=this._heatmapTemporalTexNode,i=this._heatmapNDTexNode,a=this._heatmapMotionTexNode,o=this._heatmapGradientTexNode,s=this._heatmapStorageTex,c=this.debugMode,l=this.resW,u=this.resH;this._heatmapComputeNode=(0,n.Fn)(()=>{let d=(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)(d.lessThan((0,n.int)(l)).and(f.lessThan((0,n.int)(u))),()=>{let p=(0,n.ivec2)(d,f),m=(0,n.vec4)(0,0,0,1).toVar();(0,n.If)(c.equal((0,n.int)(0)),()=>{let e=(0,n.textureLoad)(t,p).xyz;m.assign((0,n.vec4)(e,1))}).ElseIf(c.equal((0,n.int)(1)),()=>{let t=(0,n.float)(0).toVar(),r=(0,n.float)(0).toVar();for(let i=-1;i<=1;i++)for(let a=-1;a<=1;a++){let o=(0,n.textureLoad)(e,(0,n.ivec2)(d.add(a).clamp((0,n.int)(0),(0,n.int)(l).sub(1)),f.add(i).clamp((0,n.int)(0),(0,n.int)(u).sub(1)))).xyz,s=Rl(o);t.addAssign(s),r.addAssign(s.mul(s))}t.divAssign(9),r.divAssign(9);let i=(0,n.max)(r.sub(t.mul(t)),(0,n.float)(0)).div((0,n.max)(t.mul(t),(0,n.float)(1e-4))).mul(10).clamp(0,1),a=i.sub(.5).mul(4).clamp(0,1),o=i.mul(4).clamp(0,1).sub(i.sub(.75).mul(4).clamp(0,1)),s=(0,n.float)(1).sub(i.sub(.25).mul(4).clamp(0,1));m.assign((0,n.vec4)(a,o,s,1))}).ElseIf(c.equal((0,n.int)(2)),()=>{let e=(0,n.textureLoad)(r,p).w.div(32).clamp(0,1);m.assign((0,n.vec4)((0,n.float)(1).sub(e),e,(0,n.float)(.2),1))}).ElseIf(c.equal((0,n.int)(3)),()=>{let e=(0,n.textureLoad)(a,p),t=(0,n.abs)(e.x).mul(100).clamp(0,1),r=(0,n.abs)(e.y).mul(100).clamp(0,1),i=t.add(r).clamp(0,1);m.assign((0,n.vec4)(t,r,i.mul(.3),1))}).ElseIf(c.equal((0,n.int)(4)),()=>{let e=(0,n.textureLoad)(i,p);m.assign((0,n.vec4)(e.xyz,1))}).Else(()=>{let e=(0,n.textureLoad)(o,p).x.mul(5).clamp(0,1);m.assign((0,n.vec4)(e,e.mul(.5),(0,n.float)(1).sub(e),1))}),(0,n.textureStore)(s,(0,n.uvec2)((0,n.uint)(d),(0,n.uint)(f)),m).toWriteOnly()})})().compute([this._dispatchX,this._dispatchY,1],[8,8,1])}setupEventListeners(){this.on(`pipeline:historyReset`,()=>this.resetTemporalData())}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:prevNormalDepth`)||r,a=e.getTexture(`motionVector:screenSpace`);if(!t)return;let o=t.image;o&&o.width>0&&o.height>0&&(o.width!==this._outputRT.width||o.height!==this._outputRT.height)&&this.setSize(o.width,o.height),this._colorTexNode.value=t,n&&(this._albedoTexNode.value=n),a&&(this._motionTexNode.value=a),r&&(this._normalDepthTexNode.value=r),i&&(this._prevNormalDepthTexNode.value=i);let s=this.currentMoments===0?this._temporalTexB:this._temporalTexA,c=this.currentMoments===0?this._temporalNodeA:this._temporalNodeB,l=this.currentMoments===0?this._temporalTexA:this._temporalTexB;this._compiled||=(this.renderer.compute(this._gradientNode),this.renderer.compute(this._temporalNodeA),this.renderer.compute(this._temporalNodeB),!0),this._readTemporalTexNode.value=s,this._gradientReadTexNode.value=this._gradientStorageTex;let u=this.gradientStrength.value>0||this.showHeatmap;u&&this.renderer.compute(this._gradientNode),this.forceResetU.value=+!!this._needsWarmReset,this.renderer.compute(c),this._needsWarmReset=!1,this._srcRegion.max.set(this.resW.value,this.resH.value),this.renderer.copyTextureToTexture(l,this._demodulatedRT.texture,this._srcRegion),this.renderer.copyTextureToTexture(this._outputModulatedTex,this._outputRT.texture,this._srcRegion),u&&this.renderer.copyTextureToTexture(this._gradientStorageTex,this._gradientRT.texture,this._srcRegion),e.setTexture(`asvgf:demodulated`,this._demodulatedRT.texture),e.setTexture(`asvgf:output`,this._outputRT.texture),e.setTexture(`asvgf:gradient`,this._gradientRT.texture),this.currentMoments=1-this.currentMoments,this.showHeatmap&&(this._heatmapRawColorTexNode.value=t,this._heatmapColorTexNode.value=this._outputModulatedTex,this._heatmapTemporalTexNode.value=l,r&&(this._heatmapNDTexNode.value=r),a&&(this._heatmapMotionTexNode.value=a),this._heatmapGradientTexNode.value=this._gradientStorageTex,this.renderer.compute(this._heatmapComputeNode),this._srcRegion.max.set(this.heatmapTarget.width,this.heatmapTarget.height),this.renderer.copyTextureToTexture(this._heatmapStorageTex,this.heatmapTarget.texture,this._srcRegion))}setHeatmapEnabled(e){this.showHeatmap=e}setTemporalEnabled(e){this.temporalEnabledU.value=+!!e}updateParameters(e){e&&(e.temporalAlpha!==void 0&&(this.temporalAlpha.value=e.temporalAlpha),e.gradientStrength!==void 0&&(this.gradientStrength.value=e.gradientStrength),e.gradientSigmaScale!==void 0&&(this.gradientSigmaScale.value=e.gradientSigmaScale),e.gradientNoiseFloor!==void 0&&(this.gradientNoiseFloor.value=e.gradientNoiseFloor),e.maxAccumFrames!==void 0&&(this.maxAccumFrames.value=e.maxAccumFrames),e.debugMode!==void 0&&(this.debugMode.value=e.debugMode))}resetTemporalData(){this.currentMoments=0,this._needsWarmReset=!0}reallocateReservedStorage(){this._gradientNode?.dispose(),this._temporalNodeA?.dispose(),this._temporalNodeB?.dispose(),this._heatmapComputeNode?.dispose(),this._temporalTexA?.dispose(),this._temporalTexB?.dispose(),this._outputModulatedTex?.dispose(),this._gradientStorageTex?.dispose(),this._heatmapStorageTex?.dispose();let e=(e,n)=>{let i=new t.StorageTexture(W,W);return i.type=e,i.format=r.RGBAFormat,i.minFilter=n,i.magFilter=n,i};this._temporalTexA=e(r.FloatType,r.LinearFilter),this._temporalTexB=e(r.FloatType,r.LinearFilter),this._outputModulatedTex=e(r.FloatType,r.LinearFilter),this._gradientStorageTex=e(r.HalfFloatType,r.LinearFilter),this._heatmapStorageTex=e(r.FloatType,r.NearestFilter),this._buildGradientCompute(),this._buildTemporalCompute(),this._buildHeatmapCompute(),this._compiled=!1,this.currentMoments=0,this._needsWarmReset=!0}setSize(e,t){this._demodulatedRT.setSize(e,t),this._demodulatedRT.texture.needsUpdate=!0,this._outputRT.setSize(e,t),this._outputRT.texture.needsUpdate=!0,this._gradientRT.setSize(e,t),this._gradientRT.texture.needsUpdate=!0,this.heatmapTarget.setSize(e,t),this.heatmapTarget.texture.needsUpdate=!0,this.resW.value=e,this.resH.value=t,this._dispatchX=Math.ceil(e/8),this._dispatchY=Math.ceil(t/8),this._gradientNode.dispatchSize=[this._dispatchX,this._dispatchY,1],this._temporalNodeA.dispatchSize=[this._dispatchX,this._dispatchY,1],this._temporalNodeB.dispatchSize=[this._dispatchX,this._dispatchY,1],this._heatmapComputeNode.dispatchSize=[this._dispatchX,this._dispatchY,1]}reset(){}releaseGPUMemory(){this._temporalTexA?.dispose(),this._temporalTexB?.dispose(),this._outputModulatedTex?.dispose(),this._gradientStorageTex?.dispose(),this._heatmapStorageTex?.dispose(),this.context?.removeTexture(`asvgf:demodulated`),this.context?.removeTexture(`asvgf:output`),this.context?.removeTexture(`asvgf:gradient`),this._demodulatedRT?.texture?.dispose(),this._outputRT?.texture?.dispose(),this._gradientRT?.texture?.dispose(),this.heatmapTarget?.texture?.dispose(),this.resetTemporalData()}dispose(){this._gradientNode?.dispose(),this._temporalNodeA?.dispose(),this._temporalNodeB?.dispose(),this._temporalTexA?.dispose(),this._temporalTexB?.dispose(),this._outputModulatedTex?.dispose(),this._gradientStorageTex?.dispose(),this._demodulatedRT?.dispose(),this._outputRT?.dispose(),this._gradientRT?.dispose(),this._heatmapComputeNode?.dispose(),this._heatmapStorageTex?.dispose(),this.heatmapTarget?.dispose(),this._colorTexNode?.dispose(),this._albedoTexNode?.dispose(),this._motionTexNode?.dispose(),this._normalDepthTexNode?.dispose(),this._prevNormalDepthTexNode?.dispose(),this._readTemporalTexNode?.dispose(),this._gradientReadTexNode?.dispose(),this._heatmapRawColorTexNode?.dispose(),this._heatmapColorTexNode?.dispose(),this._heatmapTemporalTexNode?.dispose(),this._heatmapNDTexNode?.dispose(),this._heatmapMotionTexNode?.dispose(),this._heatmapGradientTexNode?.dispose()}};cu();var By=1e-6,Vy=1.5/255,Hy=.01,Uy=3,Wy=2,Gy=2,Ky=3,qy=2,Jy=38,Yy=.1,Xy=4,Zy=Math.cos(89*Math.PI/180),Qy=.5,$y=16,eb={pre:{radiusScale:1,fractionScale:2},blur:{radiusScale:1,fractionScale:1},post:{radiusScale:2,fractionScale:.5}},tb=.25*Math.SQRT2,nb=[[-1,0,1],[0,1,1],[1,0,1],[0,-1,1],[-tb,tb,.5],[tb,tb,.5],[tb,-tb,.5],[-tb,-tb,.5]],rb=(e,t,r)=>(0,n.smoothstep)(0,1,(0,n.float)(1).sub(e.mul(t).add(r).abs())),ib=(e,t,r)=>{let i=e.mul(t).add(r).abs().mul(-Uy);return(0,n.float)(1).div(i.mul(i).sub(i).add(1))},ab=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)))),ob=(e,t)=>(0,n.float)(1).sub((0,n.exp2)(e.mul(e).mul(-200))).mul((0,n.pow)((0,n.saturate)(e),t)),sb=(e,t)=>(0,n.saturate)(e).mul((0,n.sqrt)(t.div((0,n.float)(1).sub(t).add(By)))),cb=(e,t,r,i)=>{let a=(0,n.max)((0,n.atan)(sb(r,i.mul((0,n.mix)((0,n.saturate)(t),(0,n.float)(1),e)))),(0,n.float)(Vy));return(0,n.float)(1).div(a)},lb=(e,t)=>{let r=(0,n.float)(1).div((0,n.mix)((0,n.float)(Hy),(0,n.float)(1),(0,n.saturate)(e.mul(t))));return(0,n.vec2)(r,e.mul(r).negate())},ub=(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())},db=(e,t)=>{let r=(0,n.float)(1).div(t);return(0,n.vec2)(r,e.mul(r).negate())},fb=(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())},pb=e=>(0,n.vec2)(1).sub((0,n.vec2)(1).sub((0,n.fract)(e.mul(.5)).mul(2)).abs()).min(.99999),mb=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))},gb=(e,t)=>t.add(By).div(e.add(By)),_b=(e,t)=>(0,n.vec4)(e.xyz.mul(gb(e.x,t)),e.w),vb=e=>(0,n.vec4)(mb(hb(e.xyz)),(0,n.saturate)(e.w)),yb=(e,t)=>(0,n.sqrt)(t.sub(e.mul(e)).abs()),bb=(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))),xb=(e,t)=>(0,n.select)(e.equal(0),(0,n.vec4)(0),t);function Sb(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 Cb=class extends j{constructor(e,i={}){super(`NRD`,{...i,executionMode:A.PER_CYCLE}),this.renderer=e,this.pathTracer=i.pathTracer||null,this.settings={...Ay,...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=Yd(),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/$y),this._dispatchY=Math.ceil(o/$y),this._buildKernels()}_allocStorage(){let e=()=>Me(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 Ay&&(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 Zd(e,t,n,r,this.cameraRay)}_viewVector(e,t,r){return(0,n.select)(Jd(this.cameraRay.cameraProjection),r,(0,n.normalize)(t.sub(e)))}_frustumSize(e){return this.minRectDimMulUnproject.mul((0,n.select)(Jd(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)))}_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=Qy,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],[$y,$y,1])}_buildSpatial(e){let t=e===`pre`,{radiusScale:r,fractionScale:i}=eb[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=>{let t=(0,n.textureLoad)(o,e),r=(0,n.textureLoad)(s,e);return(0,n.vec4)(mb(Ml(t.xyz.div((0,n.max)(r.xyz,(0,n.vec3)(Ey))))),jl(r.w,Al).min(1))}:e=>(0,n.textureLoad)(d,e),S=(0,n.Fn)(([o,s])=>{let d=(0,n.int)(n.workgroupId.x).mul($y).add((0,n.int)(n.localId.x)),S=(0,n.int)(n.workgroupId.y).mul($y).add((0,n.int)(n.localId.y));(0,n.If)(d.lessThan((0,n.int)(v)).and(S.lessThan((0,n.int)(y))),()=>{let C=(0,n.ivec2)(d,S),w=(0,n.uvec2)((0,n.uint)(d),(0,n.uint)(S)),T=(0,n.textureLoad)(c,C).w.toVar(),E=T.greaterThanEqual(Ty),D=(0,n.textureLoad)(l,C).toVar(),O=(0,n.normalize)(D.xyz.mul(2).sub(1)).toVar(),k=D.w.clamp(.05,1).toVar(),A=(0,n.float)(Ty).toVar(),j=x(C).toVar();(0,n.If)(E.not(),()=>{let e=this._pixelUv(d,S),f=this._worldPosAt(e,T,o,s).toVar();A.assign(g.mul((0,n.vec4)(f,1)).z.abs()),(0,n.If)(h.greaterThan(0),()=>{let d=(0,n.dot)(O,this._viewVector(f,_,this.viewVector)).abs().toVar(),p=this._frustumSize(A).toVar(),S=b.add(1),w=t?(0,n.max)(b,(0,n.float)(10)):(0,n.textureLoad)(u,C).y.add(b),T=(t?(0,n.float)(1).div(w.add(1)):this._advancedNonLinear(w)).toVar(),E=ob(k,.5).toVar(),D=A.mul(ky).add(3),M=j.w.toVar(),N=(0,n.saturate)(M.mul(D).div(p)),P=(0,n.float)(1).sub(this._handover(S)),F=(t?N.div(S):N.mul(T)).mul(P),I=a.minBlurRadius.mul((0,n.saturate)((0,n.float)(2).sub(w.div((0,n.max)(a.maxAccum,1))))),L=(0,n.max)((0,n.saturate)((0,n.sqrt)((0,n.saturate)(F)).mul(r)).mul(h).mul(E),I.mul(E)).toVar(),R=fb(a.planeDistSensitivity,p,f,O).toVar(),ee=cb(T,a.lobeAngleFraction,k,a.lobeVolumePercent).div(i).toVar(),z=lb(k,a.roughnessFraction.mul(i)).toVar(),te=db(M,T).toVar(),ne=a.minHitDistanceWeight.mul(i).mul(E);t||(ne=ne.mul(T)),ne=ne.toVar();let re=(0,n.vec2)(1);if(!t){let e=g.mul((0,n.vec4)(O,0)).xy;re=(0,n.mix)((0,n.vec2)(1).sub(e.abs()),(0,n.vec2)(1),d),re=re.div((0,n.max)(re.x,re.y))}let ie=re.mul((0,n.vec2)((0,n.float)(1).div(v),(0,n.float)(1).div(y))).mul(L).toVar(),ae=(0,n.float)(1).toVar();for(let t=0;t<nb.length;t++){let r=nb[t],i=e.add(bb(m,(0,n.vec2)(r[0],r[1])).mul(ie)),a=pb(i),u=(0,n.select)(a.x.notEqual(i.x).or(a.y.notEqual(i.y)),(0,n.float)(1),(0,n.float)(Math.exp(-.66*r[2]*r[2]))).toVar(),d=this._uvToCoord(a),f=(0,n.textureLoad)(c,d).w,p=this._worldPosAt(a,f,o,s),h=(0,n.textureLoad)(l,d),g=ab((0,n.dot)(O,(0,n.normalize)(h.xyz.mul(2).sub(1))));u.mulAssign(rb(g,ee,(0,n.float)(0))),u.mulAssign(rb(h.w,z.x,z.y)),u.mulAssign(rb((0,n.dot)(O,p),R.x,R.y)),u.assign((0,n.select)(f.greaterThanEqual(Ty),(0,n.float)(0),u));let _=xb(u,x(d));u.mulAssign(ne.add(ib(_.w,te.x,te.y))),ae.addAssign(u),j.addAssign(_.mul(u))}j.divAssign((0,n.max)(ae,1e-6)),t||j.assign((0,n.vec4)(j.xyz,M))})}),(0,n.textureStore)(f,w,j).toWriteOnly(),e===`post`&&(0,n.textureStore)(p,w,(0,n.vec4)(O,A)).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.camView,p=this.prevCamView,m=this.camPos,h=this.prevCamPos,g=this.resW,_=this.resH,v=this.inputFrames,y=this.resetU,b=(0,n.Fn)(([b,x])=>{let S=(0,n.int)(n.workgroupId.x).mul($y).add((0,n.int)(n.localId.x)),C=(0,n.int)(n.workgroupId.y).mul($y).add((0,n.int)(n.localId.y));(0,n.If)(S.lessThan((0,n.int)(g)).and(C.lessThan((0,n.int)(_))),()=>{let g=(0,n.ivec2)(S,C),_=(0,n.uvec2)((0,n.uint)(S),(0,n.uint)(C)),w=(0,n.textureLoad)(t,g).w,T=(0,n.textureLoad)(a,g).toVar();(0,n.If)(w.greaterThanEqual(Ty),()=>{(0,n.textureStore)(u,_,T).toWriteOnly(),(0,n.textureStore)(d,_,(0,n.vec4)(0)).toWriteOnly(),(0,n.Return)()});let E=e.maxAccum.mul((0,n.float)(1).sub(y)).toVar(),D=e.maxFast.mul((0,n.float)(1).sub(y)).toVar(),O=(0,n.textureLoad)(r,g),k=(0,n.normalize)(O.xyz.mul(2).sub(1)).toVar(),A=O.w.clamp(.05,1).toVar(),j=this._pixelUv(S,C),M=this._worldPosAt(j,w,b,x).toVar(),N=f.mul((0,n.vec4)(M,1)).z.abs().toVar(),P=(0,n.dot)(k,this._viewVector(M,m,this.viewVector)).abs().toVar(),F=this._frustumSize(N).toVar(),I=(0,n.vec3)(0).toVar();I.addAssign(k.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(S.add(i),C.add(e)),o=(0,n.normalize)((0,n.textureLoad)(r,a).xyz.mul(2).sub(1)),s=(0,n.textureLoad)(t,a).w.lessThan(Ty);I.addAssign((0,n.select)(s,o,k).mul(.25))}let L=(0,n.textureLoad)(i,g),R=j.sub(L.xy).toVar(),ee=p.mul((0,n.vec4)(M,1)).z.abs().toVar(),z=this._bilinear(R),te=F.mul((0,n.saturate)(e.disocclusionThreshold.div((0,n.max)(P,.05)))).sub(By).toVar(),ne=(0,n.float)(1).sub(y),re=[],ie=[];for(let e=0;e<4;e++){let t=(0,n.textureLoad)(l,z.taps[e]),r=(0,n.select)((0,n.dot)(t.xyz,I).greaterThan(Zy),(0,n.float)(1),(0,n.float)(0)),i=(0,n.select)(t.w.sub(ee).abs().lessThanEqual(te),(0,n.float)(1),(0,n.float)(0)),a=(0,n.select)(t.w.lessThan(Ty),(0,n.float)(1),(0,n.float)(0));re.push(r.mul(i).mul(a).mul(z.inScreen[e]).mul(ne).toVar()),ie.push((0,n.textureLoad)(c,z.taps[e]).x)}let ae=z.customWeights(re).map(e=>e.toVar()),oe=re[0].add(re[1]).add(re[2]).add(re[3]).greaterThan(3.5).toVar(),se=re[0].add(re[1].mul(2)).add(re[2].mul(4)).add(re[3].mul(8)),ce=this._applyCustomWeights(ie,ae,(0,n.float)(0)).toVar(),B=(0,n.dot)(k,this._viewVector(M,h,this.prevViewVector)).abs().add(.001).div(P.add(.001)).toVar();B.assign((0,n.mix)((0,n.float)(.1),(0,n.float)(1),(0,n.saturate)(B.mul(B))));let le=(0,n.sqrt)((0,n.saturate)(z.filter(re))).mul(B).toVar();ce.assign(ce.mul((0,n.mix)(le,(0,n.float)(1),(0,n.float)(1).div(ce.add(1))))),ce.assign((0,n.min)(ce,E));let ue=vb(this._sampleHistory(e=>(0,n.textureLoad)(o,e),R,z,ae,oe)).toVar(),de=(0,n.max)(this._applyCustomWeights(z.taps.map(e=>(0,n.textureLoad)(s,e).x),ae,(0,n.float)(0)),0).toVar(),fe=v.add(1),pe=this._handover(fe).toVar(),me=ce.mul((0,n.float)(1).sub(pe)),he=fe.div(fe.add(me)).toVar(),ge=(0,n.float)(1).div((0,n.float)(1).add(ob(A,.25).mul(.5).mul(E))),_e=(0,n.vec4)((0,n.mix)(ue.xyz,T.xyz,he),(0,n.mix)(ue.w,T.w,(0,n.max)(he,ge))).toVar(),ve=e.fireflyMinRelativeScale.add((0,n.float)(Jy).div(ce.add(1))).toVar(),V=ce.mul(e.maxBlurRadius).mul(Yy).toVar();V.assign(V.div(V.add(1)).mul((0,n.float)(1).sub(pe)));let ye=(0,n.mix)(_e.x,(0,n.min)(_e.x,ue.x.mul(ve)),V);_e.assign(_b(_e,ye));let be=(0,n.float)(1.2).add((0,n.float)(1).div(ce.add(1)));_e.assign((0,n.vec4)(_e.xyz,(0,n.mix)(_e.w,(0,n.min)(_e.w,ue.w.mul(be)),V))),(0,n.textureStore)(u,_,_e).toWriteOnly();let xe=(0,n.min)(ce,D).mul((0,n.float)(1).sub(pe)),Se=fe.div(fe.add(xe)),H=(0,n.mix)(de,T.x,Se).toVar(),Ce=(0,n.min)(H,ue.x.mul(ve).mul(Xy));H.assign((0,n.mix)(H,Ce,V)),(0,n.textureStore)(d,_,(0,n.vec4)(H,ce,se,(0,n.select)(oe,(0,n.float)(1),(0,n.float)(0)))).toWriteOnly()})});return this._dispatchOf(b)}_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($y).add((0,n.int)(n.localId.x)),h=(0,n.int)(n.workgroupId.y).mul($y).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(Ty),()=>{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=C.w.clamp(.05,1).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(ky).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/Wy).mul(e.historyFixStride).mul((0,n.mix)((0,n.float)(.25).add((0,n.sqrt)(N).mul(.75)),(0,n.float)(1),j))).toVar();(0,n.If)(F.notEqual(0),()=>{let o=cb(j,e.lobeAngleFraction,T,e.lobeVolumePercent).toVar(),s=fb(e.planeDistSensitivity,k,D,w).toVar(),c=db(P,j).toVar(),d=ub(T.mul(T),(0,n.sqrt)(e.roughnessFraction),Hy).toVar(),m=(0,n.float)(1).add(b).toVar();A.mulAssign(m);for(let e=-Wy;e<=Wy;e++)for(let h=-Wy;h<=Wy;h++){if(h===0&&e===0||Math.abs(h)+Math.abs(e)===Wy*2)continue;let g=pb(E.add((0,n.vec2)(h,e).mul(F).mul((0,n.vec2)((0,n.float)(1).div(l),(0,n.float)(1).div(u))))),_=this._uvToCoord(g),v=(0,n.textureLoad)(t,_).w,y=this._worldPosAt(g,v,f,p),b=(0,n.textureLoad)(r,_),x=ib(ab((0,n.dot)((0,n.normalize)(b.xyz.mul(2).sub(1)),w)),o,(0,n.float)(0)).toVar();x.mulAssign(ib(b.w.mul(b.w),d.x,d.y)),x.mulAssign((0,n.float)(1).add((0,n.textureLoad)(a,_).y)),x.mulAssign(rb((0,n.dot)(w,y),s.x,s.y)),x.assign((0,n.select)(v.greaterThanEqual(Ty),(0,n.float)(0),x));let S=xb(x,(0,n.textureLoad)(i,_));x.mulAssign(ib(S.w,c.x,c.y)),m.addAssign(x),A.addAssign(S.mul(x))}A.divAssign((0,n.max)(m,1e-6))});let I=A.x.toVar(),L=(0,n.saturate)(b.div((0,n.max)(e.historyFixFrameNum,By))),R=(0,n.mix)(I,y.x,L).toVar();(0,n.textureStore)(s,_,(0,n.vec4)(R,0,0,0)).toWriteOnly();let ee=R.toVar(),z=R.mul(R).toVar(),te=(0,n.float)(0).toVar(),ne=(0,n.float)(0).toVar(),re=(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(Ty),R,(0,n.textureLoad)(a,o).x);Math.abs(e)<=Gy&&Math.abs(r)<=Gy&&(ee.addAssign(c),z.addAssign(c.mul(c))),i&&(te.addAssign(c),ne.addAssign(c.mul(c)))},ie=e.antiFirefly.greaterThan(.5);for(let e=-Gy;e<=Gy;e++)for(let t=-Gy;t<=Gy;t++)t===0&&e===0||re(t,e,Math.abs(t)>1||Math.abs(e)>1);(0,n.If)(ie,()=>{for(let e=-Ky;e<=Ky;e++)for(let t=-Ky;t<=Ky;t++)Math.abs(t)<=Gy&&Math.abs(e)<=Gy||re(t,e,!0)}),(0,n.If)(ie,()=>{let e=1/((Ky*2+1)**2-9),t=te.mul(e),r=yb(t,ne.mul(e)).mul(qy);I.assign((0,n.mix)(I.clamp(t.sub(r),t.add(r)),I,S))});{let t=1/(Gy*2+1)**2,r=ee.mul(t),i=yb(r,z.mul(t)).mul(e.fastClampSigmaScale),a=I.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);I.assign((0,n.mix)(a,I,s))}(0,n.textureStore)(o,_,_b(A,I)).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($y).add((0,n.int)(n.localId.x)),y=(0,n.int)(n.workgroupId.y).mul($y).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(Ty),()=>{(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.clamp(.05,1),C=this._pixelUv(v,y),w=(0,n.textureLoad)(s,p),T=C.sub(w.xy).toVar(),E=(0,n.textureLoad)(l,p).toVar(),D=E.y.toVar(),O=(0,n.uint)(E.z.add(.5)).toVar(),k=E.w.greaterThan(.5),A=this._bilinear(T),j=[1,2,4,8].map(e=>(0,n.select)(O.bitAnd((0,n.uint)(e)).notEqual((0,n.uint)(0)),(0,n.float)(1),(0,n.float)(0))),M=A.customWeights(j).map(e=>e.toVar()),N=(0,n.sqrt)((0,n.saturate)(A.filter(j))).toVar(),P=(0,n.textureLoad)(c,p).toVar(),F=P.x.toVar(),I=F.toVar(),L=F.mul(F).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(Ty),F,(0,n.textureLoad)(c,r).x);I.addAssign(o),L.addAssign(o.mul(o))}I.divAssign(9),L.divAssign(9);let R=yb(I,L).toVar();(0,n.If)(D.lessThan(t.historyFixFrameNum),()=>{F.assign((0,n.min)(F,I.mul((0,n.float)(1.2).add((0,n.float)(1).div(D.add(1))))))});let ee=(0,n.max)(this._sampleHistory(e=>(0,n.textureLoad)(u,e),T,A,M,k).x,0).toVar(),z=R.mul(t.antilag.x),te=t.antilag.y.mul(4),ne=ee.clamp(I.sub(z),I.add(z)),re=ee.sub(ne).abs().div((0,n.max)(ee,ne).add(By)),ie=(0,n.float)(1).div((0,n.float)(1).add(re.mul(D.mul(N)).div(te))).toVar(),ae=(0,n.min)(D,t.historyFixFrameNum);D.assign((0,n.mix)(ae,D,ie));let oe=h.add(1),se=this._handover(oe),ce=N.mul((0,n.float)(1).sub(this._advancedNonLinear(D.mul((0,n.float)(1).sub(se)).div(oe)))).mul(ie).toVar(),B=(0,n.float)(1).add(ce.mul(6)),le=t.stabilizationStrength.mul((0,n.float)(1).sub(g)),ue=(0,n.mix)(F,ee.clamp(I.sub(R.mul(B)),I.add(R.mul(B))),(0,n.min)(ce,le)).toVar();P.assign(_b(P,ue)),(0,n.textureStore)(e,m,(0,n.vec4)(ue,0,0,0)).toWriteOnly();let de=t.maxAccum.mul((0,n.float)(1).sub(g));(0,n.textureStore)(d,m,(0,n.vec4)((0,n.min)(D.add(1),de),S,0,0)).toWriteOnly();let fe=(0,n.textureLoad)(i,p),pe=(0,n.vec4)(hb(P.xyz).mul((0,n.max)(fe.xyz,(0,n.vec3)(Ey))),x.w).toVar();(0,n.If)(_.equal((0,n.int)(1)),()=>{let e=(0,n.saturate)(D.div((0,n.max)(t.maxAccum,1)));pe.assign((0,n.vec4)((0,n.float)(1).sub(e),e,.2,1))}).ElseIf(_.equal((0,n.int)(2)),()=>{pe.assign((0,n.vec4)((0,n.vec3)(P.w),1))}).ElseIf(_.equal((0,n.int)(3)),()=>{pe.assign((0,n.vec4)((0,n.vec3)(S),1))}).ElseIf(_.equal((0,n.int)(4)),()=>{let e=E.x.div(E.x.add(1));pe.assign((0,n.vec4)((0,n.vec3)(e),1))}).ElseIf(_.equal((0,n.int)(5)),()=>{pe.assign((0,n.vec4)((0,n.vec3)(E.z.div(15)),1))}),(0,n.textureStore)(f,m,pe).toWriteOnly()})})().compute([this._dispatchX,this._dispatchY,1],[$y,$y,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=Sb(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/$y),this._dispatchY=Math.ceil(t/$y);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()}};cu();var wb=e=>(0,n.select)(e.equal(e),e,(0,n.float)(0)).clamp(0,1e7),Tb=(0,n.wgslFn)(`
|
|
919
919
|
fn temporalAccumulate(
|
|
920
920
|
lum: f32,
|
|
921
921
|
prevMean: f32,
|
|
@@ -999,7 +999,7 @@ fn rayzee_gain( uv: vec2<f32>, linear: vec3<f32>, exposure: f32 ) -> f32 {
|
|
|
999
999
|
let contrast = select( le[ 2 ].z, le[ 2 ].y, base > le[ 3 ].y );
|
|
1000
1000
|
return exp2( le[ 3 ].y + ( base - le[ 3 ].y ) * contrast + ( y - base ) * le[ 2 ].w - y );
|
|
1001
1001
|
}
|
|
1002
|
-
`,Ox=class extends j{constructor(e,i={}){super(`LocalExposure`,{...i,executionMode:A.ALWAYS}),this.renderer=e,this.highlightContrast=i.highlightContrast??sx.localExposureHighlightContrast,this.shadowContrast=i.shadowContrast??sx.localExposureShadowContrast,this.detailStrength=i.detailStrength??sx.localExposureDetailStrength,this.onChange=null,this._grid=(0,n.attributeArray)(xx*xx*ux,`vec2`),this._blur=(0,n.attributeArray)(Sx*Sx,`float`),this._blurTmp=(0,n.attributeArray)(Sx*Sx,`float`),this._inputNode=new t.TextureNode,this._widthU=(0,n.uniform)(1,`int`),this._heightU=(0,n.uniform)(1,`int`),this._cellsXU=(0,n.uniform)(1,`int`),this._blurWU=(0,n.uniform)(1,`int`),this._blurHU=(0,n.uniform)(1,`int`),this._radiusU=(0,n.uniform)(1),this._logExposureU=(0,n.uniform)(0),this._p=[new r.Vector4,new r.Vector4,new r.Vector4,new r.Vector4].map(e=>(0,n.uniform)(e)),this._params=new Float32Array(16),this._kernels=[this._buildGridKernel(),this._buildBlurSourceKernel(),this._buildBlurKernel(this._blur,this._blurTmp,!0),this._buildBlurKernel(this._blurTmp,this._blur,!1)],this._built=!1,this._restarts=0,this._builtAt={restarts:-1,samples:-1},this._stale=!1,this._paramsBuffer=null,this._disposed=!1}_buildGridKernel(){let e=this._inputNode,t=this._grid,r=this._widthU,i=this._heightU,a=this._cellsXU,o=this._logExposureU,s=(0,n.vec4)(...Cx,0).xyz;return(0,n.Fn)(()=>{let c=n.localId.y.mul((0,n.uint)(16)).add(n.localId.x),l=(0,n.workgroupArray)(`uint`,ux).toAtomic(),u=(0,n.workgroupArray)(`uint`,ux).toAtomic();(0,n.If)(c.lessThan((0,n.uint)(ux)),()=>{(0,n.atomicStore)(l.element(c),(0,n.uint)(0)),(0,n.atomicStore)(u.element(c),(0,n.uint)(0))}),(0,n.workgroupBarrier)();let d=(0,n.int)(n.workgroupId.x).mul((0,n.int)(cx)).add((0,n.int)(n.localId.x).mul((0,n.int)(8))),f=(0,n.int)(n.workgroupId.y).mul((0,n.int)(cx)).add((0,n.int)(n.localId.y).mul((0,n.int)(8)));(0,n.Loop)({start:(0,n.int)(0),end:(0,n.int)(8),type:`int`,condition:`<`,update:2,name:`ty`},({ty:t})=>{(0,n.Loop)({start:(0,n.int)(0),end:(0,n.int)(8),type:`int`,condition:`<`,update:2,name:`tx`},({tx:a})=>{let c=d.add(a),p=f.add(t);(0,n.If)(c.lessThan(r).and(p.lessThan(i)),()=>{let t=(0,n.min)(c.add((0,n.int)(1)),r.sub((0,n.int)(1))),a=(0,n.min)(p.add((0,n.int)(1)),i.sub((0,n.int)(1))),d=(0,n.dot)((0,n.textureLoad)(e,(0,n.ivec2)(c,p)).xyz,s).add((0,n.dot)((0,n.textureLoad)(e,(0,n.ivec2)(t,p)).xyz,s)).add((0,n.dot)((0,n.textureLoad)(e,(0,n.ivec2)(c,a)).xyz,s)).add((0,n.dot)((0,n.textureLoad)(e,(0,n.ivec2)(t,a)).xyz,s)).mul(.25).toVar();(0,n.If)((0,n.floatBitsToUint)(d).bitAnd((0,n.uint)(2139095040)).notEqual((0,n.uint)(2139095040)),()=>{let e=(0,n.log2)((0,n.max)(d,bx)).clamp(px,mx).toVar(),t=e.add(o).sub(dx).div(fx-dx).clamp(0,1).mul(ux-1).toVar(),r=(0,n.uint)((0,n.floor)(t)).min((0,n.uint)(ux-1)),i=r.add((0,n.uint)(1)).min((0,n.uint)(ux-1)),a=t.sub((0,n.floor)(t)),s=(0,n.float)(1).sub(a),c=e.sub(px).mul(hx);(0,n.atomicAdd)(l.element(r),(0,n.uint)(c.mul(s).add(.5))),(0,n.atomicAdd)(u.element(r),(0,n.uint)(s.mul(hx).add(.5))),(0,n.atomicAdd)(l.element(i),(0,n.uint)(c.mul(a).add(.5))),(0,n.atomicAdd)(u.element(i),(0,n.uint)(a.mul(hx).add(.5)))})})})}),(0,n.workgroupBarrier)(),(0,n.If)(c.lessThan((0,n.uint)(ux)),()=>{let e=(0,n.float)((0,n.atomicLoad)(u.element(c))).div(hx),r=(0,n.float)((0,n.atomicLoad)(l.element(c))).div(hx).add(e.mul(px)),i=(0,n.uint)(n.workgroupId.y).mul((0,n.uint)(a)).add((0,n.uint)(n.workgroupId.x));t.element(i.mul((0,n.uint)(ux)).add(c)).assign((0,n.vec2)(r,e).div(lx))})})().compute([1,1,1],[16,16,1])}_buildBlurSourceKernel(){let e=this._inputNode,t=this._blur,r=this._widthU,i=this._heightU,a=this._blurWU,o=(0,n.vec4)(...Cx,0).xyz;return(0,n.Fn)(()=>{let s=n.localId.y.mul((0,n.uint)(8)).add(n.localId.x),c=(0,n.int)(n.workgroupId.x).mul((0,n.int)(gx)),l=(0,n.int)(n.workgroupId.y).mul((0,n.int)(gx)),u=(0,n.float)(0).toVar(),d=(0,n.float)(0).toVar();(0,n.Loop)({start:(0,n.int)(n.localId.y),end:(0,n.int)(gx),type:`int`,condition:`<`,update:8,name:`by`},({by:t})=>{(0,n.Loop)({start:(0,n.int)(n.localId.x),end:(0,n.int)(gx),type:`int`,condition:`<`,update:8,name:`bx`},({bx:a})=>{let s=c.add(a),f=l.add(t);(0,n.If)(s.lessThan(r).and(f.lessThan(i)),()=>{let t=(0,n.dot)((0,n.textureLoad)(e,(0,n.ivec2)(s,f)).xyz,o).toVar(),r=(0,n.floatBitsToUint)(t).bitAnd((0,n.uint)(2139095040)).notEqual((0,n.uint)(2139095040));u.addAssign((0,n.select)(r,t.max(0),(0,n.float)(0))),d.addAssign((0,n.select)(r,(0,n.float)(1),(0,n.float)(0)))})})});let f=(0,n.workgroupArray)(`float`,64),p=(0,n.workgroupArray)(`float`,64);f.element(s).assign(u),p.element(s).assign(d),(0,n.workgroupBarrier)();for(let e=32;e>0;e>>=1)(0,n.If)(s.lessThan((0,n.uint)(e)),()=>{f.element(s).addAssign(f.element(s.add((0,n.uint)(e)))),p.element(s).addAssign(p.element(s.add((0,n.uint)(e))))}),(0,n.workgroupBarrier)();(0,n.If)(s.equal((0,n.uint)(0)),()=>{let e=f.element((0,n.uint)(0)).div((0,n.max)(p.element((0,n.uint)(0)),1));t.element((0,n.uint)((0,n.int)(n.workgroupId.y).mul(a).add((0,n.int)(n.workgroupId.x)))).assign((0,n.log2)((0,n.max)(e,bx)).clamp(px,mx))})})().compute([1,1,1],[8,8,1])}_buildBlurKernel(e,t,r){let i=this._blurWU,a=this._blurHU,o=this._radiusU;return(0,n.Fn)(()=>{let s=(0,n.int)(n.workgroupId.x).mul((0,n.int)(8)).add((0,n.int)(n.localId.x)),c=(0,n.int)(n.workgroupId.y).mul((0,n.int)(8)).add((0,n.int)(n.localId.y));(0,n.If)(s.lessThan(i).and(c.lessThan(a)),()=>{let l=r?i:a,u=r?s:c,d=(0,n.int)(o.ceil()),f=(0,n.float)(0).toVar(),p=(0,n.float)(0).toVar();(0,n.Loop)({start:d.negate(),end:d.add((0,n.int)(1)),type:`int`,condition:`<`,name:`o`},({o:t})=>{let a=(0,n.float)(t).div(o),d=(0,n.exp)(a.mul(a).mul(-16.7)),m=l.mul((0,n.int)(2)),h=u.add(t).mod(m).add(m).mod(m).toVar();(0,n.If)(h.greaterThanEqual(l),()=>{h.assign(m.sub(h).sub((0,n.int)(1)))});let g=r?c.mul(i).add(h):h.mul(i).add(s);f.addAssign(e.element((0,n.uint)(g)).mul(d)),p.addAssign(d)}),t.element((0,n.uint)(c.mul(i).add(s))).assign(f.div(p))})})().compute([1,1,1],[8,8,1])}setupEventListeners(){this.on(`pipeline:reset`,()=>this._restarts++)}render(e){if(!this.enabled)return;let t=e.getState(`pathtracer:samples`)??0,n=this._builtAt;(this._stale||!this._built||n.restarts!==this._restarts||t-n.samples>=wx(t))&&this.build(e)}build(e=this.context){let t=e?.getTexture(`pathtracer:color`),n=t?.image?.width|0,r=t?.image?.height|0;if(!t||n<1||r<1||this._disposed)return!1;this._builtAt.restarts=this._restarts,this._builtAt.samples=e.getState(`pathtracer:samples`)??0,this._stale=!1;let i=Math.min(xx,Math.ceil(n/cx)),a=Math.min(xx,Math.ceil(r/cx)),o=Math.min(Sx,Math.ceil(n/gx)),s=Math.min(Sx,Math.ceil(r/gx)),c=Math.log2(Math.max(this.renderer.toneMappingExposure,1e-6));return this._inputNode.value=t,this._widthU.value=n,this._heightU.value=r,this._cellsXU.value=i,this._blurWU.value=o,this._blurHU.value=s,this._radiusU.value=Math.max(1,vx/100*o),this._logExposureU.value=c,this._kernels[0].dispatchSize=[i,a,1],this._kernels[1].dispatchSize=[o,s,1],this._kernels[2].dispatchSize=this._kernels[3].dispatchSize=[Math.ceil(o/8),Math.ceil(s/8),1],this.renderer.compute(this._kernels),this._params.set([n/cx,r/cx,n/gx,r/gx,i,a,o,s,c],0),this._built=!0,this._writeParams(),!0}_writeParams(){let e=this._params;e[9]=this.highlightContrast,e[10]=this.shadowContrast,e[11]=this.detailStrength,e[12]=_x,e[13]=yx;for(let t=0;t<4;t++)this._p[t].value.fromArray(e,t*4);this.onChange?.()}get wantsBuild(){return this.enabled&&(this._stale||!this._built)}updateParameters(e){for(let t of[`highlightContrast`,`shadowContrast`,`detailStrength`])e[t]!==void 0&&(this[t]=e[t]);this._writeParams()}setEnabled(e){this.enabled!==e&&(this.enabled=e,this._stale=!0,this.onChange?.())}gainNode(e,t){let r=(0,n.storage)(this._grid.value,`vec2`,xx*xx*ux).toReadOnly(),i=(0,n.storage)(this._blur.value,`float`,Sx*Sx).toReadOnly(),[a,o,s,c]=this._p;return(0,n.Fn)(([e,t])=>{let l=(0,n.log2)((0,n.max)((0,n.dot)(e,(0,n.vec4)(...Cx,0).xyz),bx)).min(mx).toVar(),u=(0,n.log2)(n.toneMappingExposure).toVar(),d=(0,n.ivec2)(o.zw),f=t.mul(a.zw).sub(.5).clamp((0,n.vec2)(0),(0,n.vec2)(d.sub((0,n.int)(1)))).toVar(),p=(0,n.ivec2)((0,n.floor)(f)).toVar(),m=p.add((0,n.int)(1)).min(d.sub((0,n.int)(1))).toVar(),h=f.sub((0,n.floor)(f)).toVar(),g=(e,t)=>i.element((0,n.uint)(t.mul(d.x).add(e))),_=(0,n.mix)((0,n.mix)(g(p.x,p.y),g(m.x,p.y),h.x),(0,n.mix)(g(p.x,m.y),g(m.x,m.y),h.x),h.y).toVar(),v=(0,n.ivec2)(o.xy),y=t.mul(a.xy).sub(.5).clamp((0,n.vec2)(0),(0,n.vec2)(v.sub((0,n.int)(1)))).toVar(),b=l.add(s.x).sub(dx).div(fx-dx).clamp(0,1).mul(ux-1).toVar(),x=(0,n.int)((0,n.floor)(y.x)),S=(0,n.int)((0,n.floor)(y.y)),C=(0,n.int)((0,n.floor)(b)),w=y.x.sub((0,n.floor)(y.x)),T=y.y.sub((0,n.floor)(y.y)),E=b.sub((0,n.floor)(b)),D=(0,n.vec2)(0).toVar();for(let e=0;e<8;e++){let t=e&1,i=e>>1&1,a=e>>2,o=(t?w:w.oneMinus()).mul(i?T:T.oneMinus()).mul(a?E:E.oneMinus()),s=x.add((0,n.int)(t)).min(v.x.sub((0,n.int)(1))),c=S.add((0,n.int)(i)).min(v.y.sub((0,n.int)(1))),l=C.add((0,n.int)(a)).min((0,n.int)(ux-1));D.addAssign(r.element((0,n.uint)(c.mul(v.x).add(s).mul((0,n.int)(ux)).add(l))).mul(o))}let O=(0,n.mix)((0,n.select)(D.y.mul(lx).lessThan(.001),_,D.x.div(D.y)),_,c.x).add(u).toVar(),k=l.add(u),A=(0,n.select)(O.greaterThan(c.y),s.y,s.z);return(0,n.exp2)(c.y.add(O.sub(c.y).mul(A)).add(k.sub(O).mul(s.w)).sub(k))})(e,t)}toneGain(){if(!this.enabled||!this._built)return null;let e=this.renderer.backend,t=e.get(this._grid.value)?.buffer,n=e.get(this._blur.value)?.buffer;if(!t||!n)return null;this._paramsBuffer??=e.device.createBuffer({label:`local-exposure-params`,size:64,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),e.device.queue.writeBuffer(this._paramsBuffer,0,this._params);let r=this._params.slice();return{key:`local-exposure`,wgsl:Dx,entries:[{binding:0,resource:{buffer:t}},{binding:1,resource:{buffer:n}},{binding:2,resource:{buffer:this._paramsBuffer}}],cpu:async()=>{let[e,t]=await Promise.all([this.renderer.getArrayBufferAsync(this._grid.value),this.renderer.getArrayBufferAsync(this._blur.value)]),n=new Float32Array(e),i=new Float32Array(t);return(e,t,a,o)=>Ex(r,n,i,e,t,a,o)}}}reset(){}setSize(){}dispose(){this._disposed=!0,this.onChange=null;for(let e of this._kernels)e.dispose();this._inputNode.dispose(),this._paramsBuffer?.destroy(),this._paramsBuffer=null}};F(),at();var kx=new r.Vector3,Ax=new r.Vector3;function jx(e,t){return Ax.subVectors(e,t.position).dot(t.getWorldDirection(kx))}function Mx(e,t,n=!1){return n?e.distance:jx(e.point,t)}var Nx=class extends r.EventDispatcher{constructor({scene:e,camera:t,canvas:n,assetLoader:i,pathTracer:a,floorPlane:o,isGeometryOnDisk:s=null}){super(),this.scene=e,this.isGeometryOnDisk=s,this.camera=t,this.canvas=n,this.assetLoader=i,this.pathTracer=a,this.floorPlane=o,this.raycaster=new r.Raycaster,this.focusMode=!1,this.focusPointIndicator=null,this.afPointPlacementMode=!1,this.handleAFPointClick=this.handleAFPointClick.bind(this),this.selectedObject=null,this.selectMode=!1,this.clickTimeout=null,this.mouseDownPosition=null,this.dragThreshold=5,this.handleFocusClick=this.handleFocusClick.bind(this),this.handleSelectClick=this.handleSelectClick.bind(this),this.handleSelectDoubleClick=this.handleSelectDoubleClick.bind(this),this.handleMouseDown=this.handleMouseDown.bind(this),this.handleMouseUp=this.handleMouseUp.bind(this),this.handleContextMenu=this.handleContextMenu.bind(this),this.handleContextPointerDown=this.handleContextPointerDown.bind(this),this.handleContextPointerUp=this.handleContextPointerUp.bind(this),this.contextPointerDownPosition=null,this.canvas.addEventListener(`pointerdown`,this.handleContextPointerDown),this.canvas.addEventListener(`pointerup`,this.handleContextPointerUp),this.canvas.addEventListener(`contextmenu`,this.handleContextMenu),this._overlayManager=null,this._transformManager=null,this._appDispatch=null,this._orbitControls=null,this._helperScene=null}setDependencies({overlayManager:e,transformManager:t,appDispatch:n,orbitControls:r,helperScene:i}){this._overlayManager=e||null,this._transformManager=t||null,this._appDispatch=n||null,this._orbitControls=r||null,this._helperScene=i||null}select(e){let t=this._overlayManager?.getHelper(`outline`);t&&t.setSelectedObjects(e&&!this.isGeometryOnDisk?.()?[e]:[]),this.selectedObject=e||null,e?this._transformManager?.attach(e):this._transformManager?.detach(),this._appDispatch?.({type:N.OBJECT_SELECTED,object:e||null})}deselect(){this.select(null)}disableMode(){this.disableSelectMode(),this._transformManager?.detach()}on(e,t){return this.addEventListener(e,t),()=>this.removeEventListener(e,t)}toggleFocusMode(){return this.focusMode=!this.focusMode,this.canvas.style.cursor=this.focusMode?`crosshair`:`auto`,this.focusMode?this.canvas.addEventListener(`click`,this.handleFocusClick):this.canvas.removeEventListener(`click`,this.handleFocusClick),this._orbitControls&&(this._orbitControls.enabled=!this.focusMode),this.dispatchEvent({type:`focusModeChanged`,enabled:this.focusMode}),this.focusMode}handleFocusClick(e){let t=this.getMouseCoordinates(e);this.raycaster.setFromCamera(t,this.camera);let n=this._intersectScene();if(n.length>0){let e=n[0],t=this.pathTracer?.cameraProjection?.value===tt.equirectangular,r=Mx(e,this.camera,t);this.showFocusPoint(e.point),this.toggleFocusMode(),this.dispatchEvent({type:`focusChanged`,distance:r/this.assetLoader.getSceneScale(),worldDistance:r})}}showFocusPoint(e){this.focusPointIndicator&&this.scene.remove(this.focusPointIndicator),this.focusPointIndicator=new r.Mesh(new r.SphereGeometry(this.assetLoader.getSceneScale()*.02,16,16),new r.MeshBasicMaterial({color:65280,transparent:!0,opacity:.8,depthTest:!1})),this.focusPointIndicator.position.copy(e),this.scene.add(this.focusPointIndicator),setTimeout(()=>{this.focusPointIndicator&&=(this.scene.remove(this.focusPointIndicator),null)},2e3)}enterAFPointPlacementMode(){this.afPointPlacementMode=!0,this.canvas.style.cursor=`crosshair`,this.canvas.addEventListener(`click`,this.handleAFPointClick)}exitAFPointPlacementMode(){this.afPointPlacementMode=!1,this.canvas.style.cursor=`auto`,this.canvas.removeEventListener(`click`,this.handleAFPointClick)}handleAFPointClick(e){let t=this.canvas.getBoundingClientRect(),n=(e.clientX-t.left)/t.width,r=(e.clientY-t.top)/t.height;this.exitAFPointPlacementMode(),this.dispatchEvent({type:`afPointPlaced`,point:{x:n,y:r}})}toggleSelectMode(){return this.selectMode=!this.selectMode,this.canvas.style.cursor=this.selectMode?`pointer`:`auto`,this.selectMode?(this.canvas.addEventListener(`mousedown`,this.handleMouseDown),this.canvas.addEventListener(`mouseup`,this.handleMouseUp),this.canvas.addEventListener(`click`,this.handleSelectClick),this.canvas.addEventListener(`dblclick`,this.handleSelectDoubleClick)):(this.canvas.removeEventListener(`mousedown`,this.handleMouseDown),this.canvas.removeEventListener(`mouseup`,this.handleMouseUp),this.canvas.removeEventListener(`click`,this.handleSelectClick),this.canvas.removeEventListener(`dblclick`,this.handleSelectDoubleClick),this.clickTimeout&&=(clearTimeout(this.clickTimeout),null),this.mouseDownPosition=null),this.dispatchEvent({type:`selectModeChanged`,enabled:this.selectMode}),this.selectMode}disableSelectMode(){this.selectMode&&(this.selectMode=!1,this.canvas.style.cursor=`auto`,this.canvas.removeEventListener(`mousedown`,this.handleMouseDown),this.canvas.removeEventListener(`mouseup`,this.handleMouseUp),this.canvas.removeEventListener(`click`,this.handleSelectClick),this.canvas.removeEventListener(`dblclick`,this.handleSelectDoubleClick),this.clickTimeout&&=(clearTimeout(this.clickTimeout),null),this.mouseDownPosition=null,this.dispatchEvent({type:`selectModeChanged`,enabled:!1}))}handleMouseDown(e){this.mouseDownPosition={x:e.clientX,y:e.clientY,button:e.button}}wasMouseDragged(e){if(!this.mouseDownPosition)return!1;let t=Math.abs(e.clientX-this.mouseDownPosition.x),n=Math.abs(e.clientY-this.mouseDownPosition.y);return Math.sqrt(t*t+n*n)>this.dragThreshold}handleSelectClick(e){if(this.wasMouseDragged(e)){this.mouseDownPosition=null;return}if(this.mouseDownPosition=null,this.clickTimeout){clearTimeout(this.clickTimeout),this.clickTimeout=null;return}this.clickTimeout=setTimeout(()=>{this.clickTimeout=null;let t=this.getMouseCoordinates(e);this.raycaster.setFromCamera(t,this.camera);let n=this._intersectScene(),r=this.filterValidIntersects(n),i=this._pickLightHelper(),a=null;if(r.length>0&&i?a=r[0].distance<=i.distance?r[0].object:i.light:r.length>0?a=r[0].object:i&&(a=i.light),a){let e=this.selectedObject;e&&e.uuid===a.uuid?this.dispatchEvent({type:`objectDeselected`,object:a,uuid:a.uuid}):this.dispatchEvent({type:`objectSelected`,object:a,uuid:a.uuid})}else this.dispatchEvent({type:`objectDeselected`})},250)}handleSelectDoubleClick(e){if(this.wasMouseDragged(e)){this.mouseDownPosition=null;return}this.mouseDownPosition=null,this.clickTimeout&&=(clearTimeout(this.clickTimeout),null);let t=this.getMouseCoordinates(e);this.raycaster.setFromCamera(t,this.camera);let n=this._intersectScene(),r=this.filterValidIntersects(n);if(r.length>0){let e=r[0].object;this.dispatchEvent({type:`objectDoubleClicked`,object:e,uuid:e.uuid})}}handleMouseUp(){}handleContextPointerDown(e){e.button===2&&(this.contextPointerDownPosition={x:e.clientX,y:e.clientY})}handleContextPointerUp(e){if(e.button!==2)return;if(this.contextPointerDownPosition){let t=Math.abs(e.clientX-this.contextPointerDownPosition.x),n=Math.abs(e.clientY-this.contextPointerDownPosition.y);if(Math.sqrt(t*t+n*n)>this.dragThreshold){this.contextPointerDownPosition=null;return}}else return;this.contextPointerDownPosition=null;let t=this.selectedObject;t&&this.dispatchEvent({type:`contextMenuRequested`,x:e.clientX,y:e.clientY,selectedObject:t})}handleContextMenu(e){e.preventDefault()}getMouseCoordinates(e){let t=this.canvas.getBoundingClientRect();return{x:(e.clientX-t.left)/t.width*2-1,y:-((e.clientY-t.top)/t.height)*2+1}}_intersectScene(){return this.isGeometryOnDisk?.()?[]:this.raycaster.intersectObjects(this.scene.children,!0)}pickSurface(e,t){return this.raycaster.setFromCamera({x:e,y:t},this.camera),this.filterValidIntersects(this._intersectScene())[0]??null}filterValidIntersects(e){return e.filter(e=>{let t=e.object;return t!==this.focusPointIndicator&&t!==this.floorPlane&&!t.name.includes(`Helper`)&&t.type===`Mesh`})}_pickLightHelper(){if(!this._helperScene||this._helperScene.children.length===0)return null;let e=this.raycaster.intersectObjects(this._helperScene.children,!0);for(let t of e){let e=t.object;for(;e;){if(e.light)return{distance:t.distance,light:e.light};e=e.parent}}return null}updateDependencies({scene:e,camera:t,floorPlane:n}){e&&(this.scene=e),t&&(this.camera=t),n&&(this.floorPlane=n)}wireAppEvents(e){this.addEventListener(`objectSelected`,t=>{this.select(t.object),e.refreshFrame(),e.dispatchEvent({type:N.OBJECT_SELECTED,object:t.object,uuid:t.uuid})}),this.addEventListener(`objectDeselected`,t=>{this.select(null),e.refreshFrame(),e.dispatchEvent({type:N.OBJECT_DESELECTED,object:t.object,uuid:t.uuid})}),this.addEventListener(`selectModeChanged`,t=>{e.dispatchEvent({type:N.SELECT_MODE_CHANGED,enabled:t.enabled})}),this.addEventListener(`objectDoubleClicked`,t=>{this.select(t.object),e.refreshFrame(),e.dispatchEvent({type:N.OBJECT_DOUBLE_CLICKED,object:t.object,uuid:t.uuid})}),this.addEventListener(`focusChanged`,t=>{e.settings.set(`focusDistance`,t.worldDistance),e.dispatchEvent({type:N.FOCUS_CHANGED,distance:t.distance})}),this.addEventListener(`afPointPlaced`,t=>{e.dispatchEvent({type:N.AF_POINT_PLACED,point:t.point})})}dispose(){this.canvas.removeEventListener(`click`,this.handleAFPointClick),this.canvas.removeEventListener(`click`,this.handleFocusClick),this.canvas.removeEventListener(`mousedown`,this.handleMouseDown),this.canvas.removeEventListener(`mouseup`,this.handleMouseUp),this.canvas.removeEventListener(`click`,this.handleSelectClick),this.canvas.removeEventListener(`dblclick`,this.handleSelectDoubleClick),this.canvas.removeEventListener(`contextmenu`,this.handleContextMenu),this.canvas.removeEventListener(`pointerdown`,this.handleContextPointerDown),this.canvas.removeEventListener(`pointerup`,this.handleContextPointerUp),this.clickTimeout&&=(clearTimeout(this.clickTimeout),null),this.mouseDownPosition=null,this.contextPointerDownPosition=null,this.focusPointIndicator&&=(this.scene.remove(this.focusPointIndicator),null),this.canvas.style.cursor=`auto`,this.scene=null,this.camera=null,this.canvas=null,this.assetLoader=null,this.pathTracer=null,this.floorPlane=null,this.raycaster=null}},Px=8,Fx=4,Ix=.25,Lx=r.MathUtils.degToRad(89),Rx=.25,zx={KeyD:[1,0,0],ArrowRight:[1,0,0],KeyA:[-1,0,0],ArrowLeft:[-1,0,0],KeyW:[0,1,0],ArrowUp:[0,1,0],KeyS:[0,-1,0],ArrowDown:[0,-1,0],KeyE:[0,0,1],KeyQ:[0,0,-1]},Bx=`input, textarea, select, [contenteditable]:not([contenteditable="false"]), [role=textbox], [role=combobox], [role=listbox], [role=menu], [role=menuitem]`,Vx=e=>e.shiftKey?Fx:e.altKey?Ix:1,Hx={type:`change`},Ux={type:`start`},Wx=new r.Vector3,Gx=new r.Vector3,Kx=new r.Vector3,qx=new r.Vector3,Jx=new r.Quaternion,Yx=class extends r.Controls{constructor(e,t,n){super(e,t),this.orbit=n,this.enabled=!1,this.speed=1/Px,this._held=new Set,this._factor=1,this._lastTime=0,this._drag=null,this._onKeyDown=this._onKeyDown.bind(this),this._onKeyUp=this._onKeyUp.bind(this),this.release=this.release.bind(this),this._onPointerDown=this._onPointerDown.bind(this),this._onPointerMove=this._onPointerMove.bind(this),this._onPointerUp=this._onPointerUp.bind(this),t&&this.connect(t)}get active(){return this.enabled&&this.orbit.enabled}fitSpeed(e){this.speed=(e>0?e:1)/Px}connect(e){super.connect(e);let t=e.ownerDocument;t?.addEventListener(`keydown`,this._onKeyDown),t?.addEventListener(`keyup`,this._onKeyUp),t?.addEventListener(`visibilitychange`,this.release),t?.defaultView?.addEventListener(`blur`,this.release),e.addEventListener(`pointerdown`,this._onPointerDown),e.addEventListener(`pointermove`,this._onPointerMove),e.addEventListener(`pointerup`,this._onPointerUp),e.addEventListener(`pointercancel`,this._onPointerUp)}disconnect(){let e=this.domElement;if(!e)return;let t=e.ownerDocument;t?.removeEventListener(`keydown`,this._onKeyDown),t?.removeEventListener(`keyup`,this._onKeyUp),t?.removeEventListener(`visibilitychange`,this.release),t?.defaultView?.removeEventListener(`blur`,this.release),e.removeEventListener(`pointerdown`,this._onPointerDown),e.removeEventListener(`pointermove`,this._onPointerMove),e.removeEventListener(`pointerup`,this._onPointerUp),e.removeEventListener(`pointercancel`,this._onPointerUp)}dispose(){this.disconnect()}update(e=this._elapsed()){if(!this._held.size||!this.active)return!1;let t=0,n=0,r=0;for(let e of this._held){let[i,a,o]=zx[e];t+=i,n+=a,r+=o}if(!t&&!n&&!r)return!1;let i=this.object;return Gx.set(1,0,0).applyQuaternion(i.quaternion),Wx.crossVectors(i.up,Gx).normalize(),Gx.crossVectors(Wx,i.up),Kx.set(0,0,0).addScaledVector(Gx,t).addScaledVector(Wx,n).addScaledVector(i.up,r).normalize().multiplyScalar(this.speed*this._factor*e),i.position.add(Kx),this.orbit.target.add(Kx),i.updateMatrixWorld(),this.dispatchEvent(Hx),!0}_elapsed(){let e=performance.now(),t=Math.min((e-this._lastTime)/1e3,Rx);return this._lastTime=e,t}_look(e,t){let n=this.object,i=this.orbit.target,a=n.position.distanceTo(i)||1,o=r.MathUtils.degToRad(n.fov)/(this.domElement.clientHeight||1);n.quaternion.premultiply(Jx.setFromAxisAngle(n.up,e*o)),n.getWorldDirection(Wx);let s=Math.asin(r.MathUtils.clamp(Wx.dot(n.up),-1,1)),c=r.MathUtils.clamp(s+t*o,-Lx,Lx);n.quaternion.multiply(Jx.setFromAxisAngle(qx.set(1,0,0),c-s)),n.updateMatrixWorld(),i.copy(n.position).addScaledVector(n.getWorldDirection(Wx),a),this.dispatchEvent(Hx)}_onKeyDown(e){if(!(!this.active||e.defaultPrevented||e.target?.closest?.(Bx))){if(e.metaKey||e.ctrlKey){this.release();return}this._factor=Vx(e),zx[e.code]&&(e.preventDefault(),!this._held.has(e.code)&&(this._held.add(e.code),this._held.size===1&&(this._lastTime=performance.now(),this.dispatchEvent(Ux))))}}_onKeyUp(e){this._factor=Vx(e),this._held.delete(e.code)}release(){this._held.clear(),this._factor=1}_onPointerDown(e){!this.active||e.button!==0||!e.isPrimary||(this._drag={id:e.pointerId,x:e.clientX,y:e.clientY},this.domElement.setPointerCapture?.(e.pointerId))}_onPointerMove(e){let t=this._drag;if(!t||e.pointerId!==t.id)return;let n=e.clientX-t.x,r=e.clientY-t.y;t.x=e.clientX,t.y=e.clientY,this.active&&(n||r)&&this._look(n,r)}_onPointerUp(e){this._drag?.id===e.pointerId&&(this._drag=null,this.domElement.releasePointerCapture?.(e.pointerId))}};F(),at();var Xx={autoFocusMode:`auto`,afScreenPoint:{x:.5,y:.5},afSmoothingFactor:.15},Zx=.05,Qx=10,$x=.5,eS=Object.freeze(new r.Vector3(1,1,1)),tS=e=>e?.isOrthographicCamera?(e.top-e.bottom)/e.zoom:null,nS=class extends r.EventDispatcher{constructor(e){super();let t=e.clientWidth,n=e.clientHeight;this.camera=new cy(60,t/n||1,.01,1e3),this.camera.position.set(0,0,5),this.controls=new u.OrbitControls(this.camera,e),this.controls.screenSpacePanning=!0,this.controls.zoomToCursor=!0,this.controls.saveState(),this._reportedOrthoHeight=null,this._reportOrthoHeight=this._reportOrthoHeight.bind(this),this.controls.addEventListener(`change`,this._reportOrthoHeight),this.walkControls=new Yx(this.camera,e,this.controls),this.interactionManager=null,this.cameras=[this.camera],this.currentCameraIndex=0,this._userCameraCounter=0,this.autoFocusMode=Xx.autoFocusMode,this.afScreenPoint={...Xx.afScreenPoint},this.afSmoothingFactor=Xx.afSmoothingFactor,this._lastValidFocusDistance=null,this._smoothedFocusDistance=null,this._afPointDirty=!1,this._afSuspended=!1,this._afPick=null,this._defaultCameraState=null,this._onResize=null,this._onReset=null,this._getSettings=null,this._applySettings=null}setCameras(e){this.cameras=e,this._userCameraCounter=0,this.resetAutoFocus()}addCameraFromView(e){let t=this.camera,n=t.orthographic?new r.OrthographicCamera(t.left,t.right,t.top,t.bottom,t.near,t.far):new r.PerspectiveCamera(t.fov,t.aspect,t.near,t.far);return n.zoom=t.zoom,n.position.copy(t.position),n.quaternion.copy(t.quaternion),n.scale.copy(t.scale),n.updateMatrixWorld(!0),n.userData.__rayzeeUserCamera=!0,n.userData.__rayzeeEffects=this._captureEffects(),this.controls&&(n.userData.__rayzeeOrbitTarget=this.controls.target.clone()),this._userCameraCounter+=1,n.name=e||`View Camera ${this._userCameraCounter}`,this.cameras.push(n),this.cameras.length-1}removeCamera(e){if(!Number.isInteger(e)||e<=0||e>=this.cameras.length||!this.cameras[e]?.userData?.__rayzeeUserCamera)return!1;let t=this.currentCameraIndex===e;return this.cameras.splice(e,1),t?(this.currentCameraIndex=-1,this.switchCamera(0)):this.currentCameraIndex>e&&--this.currentCameraIndex,!0}getCameraNames(){return!this.cameras||this.cameras.length===0?[`Default Camera`]:this.cameras.map((e,t)=>t===0?`Default Camera`:e.name||`Camera ${t}`)}initCallbacks({onResize:e,onReset:t,getSettings:n,applySettings:r}){this._onResize=e,this._onReset=t,this._getSettings=n,this._applySettings=r}_captureEffects(){let e=this._getSettings;return e?{enableDOF:e(`enableDOF`),focusDistance:e(`focusDistance`),aperture:e(`aperture`),focalLength:e(`focalLength`),apertureScale:e(`apertureScale`),anamorphicRatio:e(`anamorphicRatio`),dofBlur:e(`dofBlur`),autoFocusMode:this.autoFocusMode,afScreenPoint:{...this.afScreenPoint},orthoHeight:this.orthoHeight}:null}_applyEffects(e){e&&(this._applySettings?.({enableDOF:e.enableDOF,focusDistance:e.focusDistance,aperture:e.aperture,focalLength:e.focalLength,apertureScale:e.apertureScale,anamorphicRatio:e.anamorphicRatio,dofBlur:e.dofBlur}),e.autoFocusMode!==void 0&&this.setAutoFocusMode(e.autoFocusMode),e.afScreenPoint&&this.setAFScreenPoint(e.afScreenPoint.x,e.afScreenPoint.y))}switchCamera(e,t,n,r){if(t??=this._getSettings?.(`focusDistance`),n??=this._onResize,r??=this._onReset,!this.cameras||this.cameras.length===0)return;(e<0||e>=this.cameras.length)&&(console.warn(`CameraManager: Invalid camera index ${e}. Using default camera.`),e=0);let i=this.cameras[this.currentCameraIndex];if(i&&(i.userData.__rayzeeEffects=this._captureEffects()),this.currentCameraIndex===0&&e!==0&&(this._defaultCameraState={position:this.camera.position.clone(),quaternion:this.camera.quaternion.clone(),scale:this.camera.scale.clone(),fov:this.camera.fov,near:this.camera.near,far:this.camera.far,target:this.controls?this.controls.target.clone():null}),this.currentCameraIndex=e,e===0&&this._defaultCameraState){let e=this._defaultCameraState;this.camera.position.copy(e.position),this.camera.quaternion.copy(e.quaternion),this.camera.scale.copy(e.scale??eS),this.camera.fov=e.fov,this.camera.near=e.near,this.camera.far=e.far,this.camera.updateProjectionMatrix(),this.camera.updateMatrixWorld(!0),this.controls&&e.target&&(this.controls.target.copy(e.target),this.controls.update())}else this._placeAt(this.cameras[e],t);this.resetAutoFocus();let a=this.cameras[e],o=a?.userData?.__rayzeeEffects;this._showOrthographic(o?o.orthoHeight:tS(a)),this._applyEffects(o),n?.(),r?.(),this.dispatchEvent({type:N.CAMERA_SWITCHED,cameraIndex:e,effects:this._captureEffects(),fov:this.camera.fov,cameraProjection:this._getSettings?.(`cameraProjection`)})}resetView(){let e=this.currentCameraIndex>0?this.cameras[this.currentCameraIndex]:null;if(!e){this.controls.reset();return}this._placeAt(e,this._getSettings?.(`focusDistance`));let t=tS(e);this.camera.orthographic&&this._setView(!0,t?t/2:this.camera.orthoHalfHeight),this._onReset?.()}_placeAt(e,t){if(this.camera.position.copy(e.position),this.camera.quaternion.copy(e.quaternion),this.camera.scale.copy(e.scale),e.isPerspectiveCamera&&(this.camera.fov=e.fov),this.camera.near=e.near,this.camera.far=e.far,this.camera.updateProjectionMatrix(),this.camera.updateMatrixWorld(!0),!this.controls)return;let n=e.userData?.__rayzeeOrbitTarget;if(n)this.controls.target.copy(n);else{let n=new r.Vector3(0,0,-1).applyQuaternion(e.quaternion);this.controls.target.copy(this.camera.position).addScaledVector(n,t||5)}this.controls.update()}_showOrthographic(e){e>0?this._setView(!0,e/2):this._setView(!1);let t=this._getSettings?.(`cameraProjection`),n=e>0?`orthographic`:t===`orthographic`?`perspective`:t;n!==t&&this._applySettings?.({cameraProjection:n})}applyProjection(e){let t=this.camera,n=e===`orthographic`;if(t.orthographic!==n){if(n)this._setView(!0,this._fittedHalfHeight());else{let e=this.controls.target,n=this.orthoHeight/2/Math.tan(r.MathUtils.degToRad(t.fov)/2);t.position.sub(e).setLength(n).add(e),this._setView(!1)}this.controls.update()}}get orthoHeight(){return tS(this.camera)}setOrthoHeight(e){e>0&&(this._setView(this.camera.orthographic,e/2),this._onReset?.())}fitOrthographic(){this.camera.orthographic&&this.setOrthoHeight(2*this._fittedHalfHeight())}_setView(e,t=this.camera.orthoHalfHeight){let n=this.camera;n.orthographic=e,n.orthoHalfHeight=t,n.zoom=1,n.updateProjectionMatrix(),this._reportOrthoHeight()}_fittedHalfHeight(){return this.camera.position.distanceTo(this.controls.target)*Math.tan(r.MathUtils.degToRad(this.camera.fov)/2)}_reportOrthoHeight(){if(!this.camera.orthographic)return;let e=this.orthoHeight;e!==this._reportedOrthoHeight&&(this._reportedOrthoHeight=e,this.dispatchEvent({type:N.ORTHO_HEIGHT_UPDATED,height:e}))}focusOn(e){!e||!this.controls||(this.controls.target.copy(e),this.controls.update(),this._onReset?.())}setNavigationMode(e){let t=e===`walk`;if(this.walkControls.enabled===t)return;let n=this.controls;if(n.enableRotate=n.enablePan=n.enableZoom=!t,this.walkControls.enabled=t,t)return;this.walkControls.release();let i=this.interactionManager?.pickSurface(0,0);if(!i)return;let a=r.MathUtils.clamp(i.distance,n.minDistance,n.maxDistance);n.target.copy(this.camera.position).addScaledVector(this.camera.getWorldDirection(new r.Vector3),a),n.update()}get navigationMode(){return this.walkControls.enabled?`walk`:`orbit`}updateControls(){this.walkControls.update(),this.controls.update()}captureView(){let e=this.camera,t=this.orthoHeight??2*this._fittedHalfHeight();return{position:e.position.clone(),target:this.controls.target.clone(),fov:e.fov,orthoHeight:t}}applyPose(e){let t=this.camera;t.position.copy(e.position),t.lookAt(e.target),this.controls.target.copy(e.target),t.orthographic?this._setView(!0,e.orthoHeight/2):(t.fov=e.fov,t.updateProjectionMatrix()),t.updateMatrixWorld()}serialize(){let e=this.camera,t=this._defaultCameraState;return{current:this.currentCameraIndex,view:{position:e.position.toArray(),quaternion:e.quaternion.toArray(),scale:e.scale.toArray(),fov:e.fov,near:e.near,far:e.far,zoom:e.zoom,orthographic:!!e.orthographic,orthoHalfHeight:e.orthoHalfHeight,target:this.controls.target.toArray()},defaultView:t?{position:t.position.toArray(),quaternion:t.quaternion.toArray(),scale:t.scale.toArray(),fov:t.fov,near:t.near,far:t.far,target:t.target?.toArray()??null}:null,navigationMode:this.navigationMode,autoFocus:{mode:this.autoFocusMode,point:{...this.afScreenPoint}},cameras:this.cameras.map((e,t)=>{let n={index:t,name:e.name??``,effects:tr(e.userData?.__rayzeeEffects)??null};return t===0||!e.userData?.__rayzeeUserCamera?n:{...n,user:!0,orthographic:!!e.isOrthographicCamera,frustum:e.isOrthographicCamera?[e.left,e.right,e.top,e.bottom]:null,fov:e.fov??null,aspect:e.aspect??null,near:e.near,far:e.far,zoom:e.zoom,position:e.position.toArray(),quaternion:e.quaternion.toArray(),scale:e.scale.toArray(),orbitTarget:e.userData.__rayzeeOrbitTarget?.toArray()??null}})}}restore(e){let t=[];if(!e)return{mismatched:t};this.cameras=this.cameras.filter(e=>!e.userData?.__rayzeeUserCamera);let n=new Map;for(let i of e.cameras??[]){if(i.user){let e=i.orthographic?new r.OrthographicCamera(...i.frustum,i.near,i.far):new r.PerspectiveCamera(i.fov,i.aspect,i.near,i.far);e.name=i.name,e.zoom=i.zoom??1,e.position.fromArray(i.position),e.quaternion.fromArray(i.quaternion),e.scale.fromArray(i.scale),e.updateProjectionMatrix(),e.updateMatrixWorld(!0),e.userData.__rayzeeUserCamera=!0,e.userData.__rayzeeEffects=nr(i.effects),i.orbitTarget&&(e.userData.__rayzeeOrbitTarget=new r.Vector3().fromArray(i.orbitTarget)),n.set(i.index,this.cameras.length),this.cameras.push(e);continue}let e=this.cameras[i.index];if(!e||i.index>0&&(e.name??``)!==i.name){t.push(i.name);continue}n.set(i.index,i.index),i.effects&&(e.userData.__rayzeeEffects=nr(i.effects))}this._userCameraCounter=this.cameras.filter(e=>e.userData?.__rayzeeUserCamera).length,this.currentCameraIndex=n.get(e.current)??0;let i=e.defaultView;this._defaultCameraState=i?{position:new r.Vector3().fromArray(i.position),quaternion:new r.Quaternion().fromArray(i.quaternion),scale:new r.Vector3().fromArray(i.scale),fov:i.fov,near:i.near,far:i.far,target:i.target?new r.Vector3().fromArray(i.target):null}:null,e.navigationMode&&this.setNavigationMode(e.navigationMode);let a=e.view;if(a){let e=this.camera;e.position.fromArray(a.position),e.quaternion.fromArray(a.quaternion),e.scale.fromArray(a.scale),e.fov=a.fov,e.near=a.near,e.far=a.far,this._setView(a.orthographic,a.orthoHalfHeight),e.zoom=a.zoom??1,e.updateProjectionMatrix(),e.updateMatrixWorld(!0),this.controls.target.fromArray(a.target),this.controls.update()}return e.autoFocus&&(this.setAutoFocusMode(e.autoFocus.mode),this.setAFScreenPoint(e.autoFocus.point.x,e.autoFocus.point.y)),this.resetAutoFocus(),this._reportOrthoHeight(),this.dispatchEvent({type:N.CAMERA_SWITCHED,cameraIndex:this.currentCameraIndex,effects:this._captureEffects(),fov:this.camera.fov,cameraProjection:this._getSettings?.(`cameraProjection`)}),{mismatched:t}}get active(){return this.camera}getNames(){return this.getCameraNames()}setAutoFocusMode(e){this.autoFocusMode=e,e!==`manual`&&(this._smoothedFocusDistance=null,this._afPointDirty=!0)}resetAutoFocus(){this._lastValidFocusDistance=null,this._smoothedFocusDistance=null,this._afPointDirty=!0}setAFScreenPoint(e,t){this.afScreenPoint={x:e,y:t},this._afPointDirty=!0}enterAFPointPlacementMode(){this.interactionManager&&(this.interactionManager.enterAFPointPlacementMode(),this.controls&&(this.controls.enabled=!1))}exitAFPointPlacementMode(){this.interactionManager&&(this.interactionManager.exitAFPointPlacementMode(),this.controls&&(this.controls.enabled=!0))}updateAutoFocus(e){let t=e||this._afContext;if(!t||!this.interactionManager)return;let{assetLoader:n,currentFocusDistance:r,pathTracer:i,setFocusDistance:a,softReset:o,hardReset:s}=t;if(this.autoFocusMode===`manual`)return;if(!i?.enableDOF?.value||i.cameraProjection?.value===tt.equirectangular){this._afSuspended=!0;return}this._afSuspended&&(this._afSuspended=!1,this._smoothedFocusDistance=null);let c=i;if(c?.isReady&&c.renderMode?.value===1&&c.frameCount>0&&!c.isComplete)return;let l=this._pickFocusPoint(c.resetCount),u;if(l)u=jx(l,this.camera),this._lastValidFocusDistance=u;else if(this._lastValidFocusDistance!==null)u=this._lastValidFocusDistance;else{let e=this.controls?jx(this.controls.target,this.camera):0;u=e>0?e:Qx*(n?.getSceneScale()||1),this._lastValidFocusDistance=u}let d=this._afPointDirty;this._afPointDirty=!1,d||this._smoothedFocusDistance===null||this._smoothedFocusDistance===0||Math.abs(u-this._smoothedFocusDistance)/this._smoothedFocusDistance>$x?this._smoothedFocusDistance=u:this._smoothedFocusDistance+=this.afSmoothingFactor*(u-this._smoothedFocusDistance);let f=r,p=this._smoothedFocusDistance;if(d||f===0||Math.abs(p-f)/Math.max(f,.001)>.001){a(p);let e=n?.getSceneScale()||1;this.dispatchEvent({type:N.AUTO_FOCUS_UPDATED,distance:p/e,worldDistance:p});let t=Math.abs(p-f)/Math.max(f,.001);d?s?.():t>Zx&&o?.()}}_pickFocusPoint(e){let t=this.camera,{x:n,y:i}=this.afScreenPoint,a=this._afPick??={point:new r.Vector3,hit:!1,resetCount:NaN,x:NaN,y:NaN,view:new r.Matrix4,projection:new r.Matrix4};if(this._afPointDirty||e!==a.resetCount||n!==a.x||i!==a.y||!a.view.equals(t.matrixWorld)||!a.projection.equals(t.projectionMatrix)){let r=this.interactionManager.pickSurface(n*2-1,1-i*2);a.hit=!!r,r&&a.point.copy(r.point),a.resetCount=e,a.x=n,a.y=i,a.view.copy(t.matrixWorld),a.projection.copy(t.projectionMatrix)}return a.hit?a.point:null}setInteractionManager(e){this.interactionManager=e}initAutoFocus({assetLoader:e,pathTracer:t,settings:n,softReset:r,hardReset:i}){this._afContext={assetLoader:e,pathTracer:t,setFocusDistance:e=>n.set(`focusDistance`,e,{silent:!0}),softReset:r,hardReset:i},Object.defineProperty(this._afContext,`currentFocusDistance`,{get:()=>n.get(`focusDistance`)})}dispose(){this.walkControls?.dispose(),this.controls?.removeEventListener(`change`,this._reportOrthoHeight),this.controls?.dispose()}},rS=.001,iS=2,aS=(e,t,n,i)=>new e(t,n,i,r.InterpolateSmooth).createInterpolant(),oS=class{constructor(e,t){this._cameraManager=e,this._onChange=t,this.keys=[],this._nextId=1,this._interpolants=null}get animates(){return this.keys.length>1}get duration(){return this.keys.length?this.keys[this.keys.length-1].time:0}addKey(e=this.keys.length?this.duration+iS:0){return this.add(this._cameraManager.captureView(),e)}updateKey(e){this.update(e,this._cameraManager.captureView())}seek(e){let t=this.sample(e);return t&&this._cameraManager.applyPose(t),!!t}add(e,t){let n={id:this._nextId++,time:t,...sS(e)};return this.keys.push(n),this._changed(),n}update(e,t){let n=this.get(e);n&&(Object.assign(n,sS(t)),this._changed())}setTime(e,t){let n=this.get(e);!n||!(t>=0)||(n.time=t,this._changed())}remove(e){let t=this.keys.length;this.keys=this.keys.filter(t=>t.id!==e),this.keys.length!==t&&this._changed()}clear(){this.keys.length&&(this.keys=[],this._changed())}serialize(){return this.keys.map(({time:e,position:t,target:n,fov:r,orthoHeight:i})=>({time:e,position:t.toArray(),target:n.toArray(),fov:r,orthoHeight:i}))}restore(e){this.keys=(e??[]).map(e=>({id:this._nextId++,time:e.time,position:new r.Vector3().fromArray(e.position),target:new r.Vector3().fromArray(e.target),fov:e.fov,orthoHeight:e.orthoHeight})),this._changed()}dispose(){this._cameraManager=this._onChange=null}get(e){return this.keys.find(t=>t.id===e)}sample(e,t={position:new r.Vector3,target:new r.Vector3,fov:0,orthoHeight:0}){if(!this.keys.length)return null;let{position:n,target:i,fov:a,logHeight:o,start:s,end:c}=this._interpolants??=this._build(),l=r.MathUtils.clamp(e,s,c);return t.position.fromArray(n.evaluate(l)),t.target.fromArray(i.evaluate(l)),t.fov=a.evaluate(l)[0],t.orthoHeight=Math.exp(o.evaluate(l)[0]),t}_build(){let e=[];for(let t of this.keys)e.push(e.length?Math.max(t.time,e[e.length-1]+rS):t.time);let t=e[0],n=e[e.length-1],i=this.keys;if(i.length>1){let r=i.length;e.unshift(2*t-e[1]),e.push(2*n-e[r-1]),i=[i[1],...i,i[r-2]]}let a=e=>i.flatMap(t=>e(t).toArray());return{start:t,end:n,position:aS(r.VectorKeyframeTrack,`.position`,e,a(e=>e.position)),target:aS(r.VectorKeyframeTrack,`.target`,e,a(e=>e.target)),fov:aS(r.NumberKeyframeTrack,`.fov`,e,i.map(e=>e.fov)),logHeight:aS(r.NumberKeyframeTrack,`.orthoHeight`,e,i.map(e=>Math.log(e.orthoHeight)))}}_changed(){this.keys.sort((e,t)=>e.time-t.time),this._interpolants=null,this._onChange?.()}};function sS({position:e,target:t,fov:n,orthoHeight:r}){return{position:e.clone(),target:t.clone(),fov:n,orthoHeight:r}}F();var cS=class extends r.EventDispatcher{constructor({cameraManager:e,onReset:t}){super(),this._cameraManager=e,this._onReset=t,this.camera=new oS(e,()=>this._changed(`camera`)),this._playback=null,this._timer=new r.Timer,typeof document<`u`&&this._timer.connect(document)}get duration(){return this.camera.duration}get animates(){return this.camera.animates}seek(e){return this.camera.seek(e)}play(){return this.stop(),new Promise(e=>{let t=this._cameraManager.controls;this._playback={elapsed:0,resolve:e,controlsEnabled:t.enabled},t.enabled=!1,this._timer.reset(),this._changed(),this._onReset?.()})}stop(){let e=this._playback;e&&(this._playback=null,this._cameraManager.controls.enabled=e.controlsEnabled,this._changed(),e.resolve())}get isPlaying(){return!!this._playback}update(){let e=this._playback;if(!e)return;this._timer.update(),e.elapsed+=this._timer.getDelta();let t=r.MathUtils.clamp(e.elapsed,0,this.duration);this.seek(t),t>=this.duration&&this.stop()}serialize(){return{camera:this.camera.serialize()}}restore(e){this.stop(),this.camera.restore(e?.camera)}clear(){this.stop(),this.camera.clear()}dispose(){this.stop(),this._timer.dispose(),this.camera.dispose(),this._cameraManager=this._onReset=null}_changed(e){this.dispatchEvent({type:N.TIMELINE_CHANGED,track:e})}};rn();var lS=class{constructor(e,t={}){this.pathTracer=e,this._onReset=t.onReset||null,this._issues=t.issues??null,this.texture=null,this.entries=[],this._size=256}async loadLibrary(e,{size:t=256}={}){if(!Array.isArray(e)||e.length===0)return[];this._size=t;let n=await Promise.all(e.map(e=>uS(e.url))),i=t,a=t,o=n.length,s=new Uint8Array(i*a*o*4),c=document.createElement(`canvas`);c.width=i,c.height=a;let l=c.getContext(`2d`,{willReadFrequently:!0}),u=performance.now();for(let e=0;e<o;e++){l.clearRect(0,0,i,a),l.drawImage(n[e],0,0,i,a);let t=l.getImageData(0,0,i,a);s.set(t.data,e*i*a*4),performance.now()-u>16&&(await new Promise(e=>setTimeout(e,0)),u=performance.now())}let d=new r.DataArrayTexture(s,i,a,o);d.minFilter=r.LinearFilter,d.magFilter=r.LinearFilter,d.format=r.RGBAFormat,d.type=r.UnsignedByteType,d.generateMipmaps=!1,d.needsUpdate=!0;let f=this.texture;return this.texture=d,this.entries=e.map((e,t)=>({name:e.name,index:t})),this.pathTracer.goboMaps=d,this.pathTracer.shaderBuilder?.updateGoboMaps?.(d),f?.dispose?.(),this.entries}getEntries(){return this.entries.slice()}setLightGobo(e,t,n={}){let{intensity:r=1,inverted:i=!1,scale:a=5}=n,o=this._findGoboLight(e);if(!o)return!1;if(o.userData=o.userData||{},t==null)delete o.userData.gobo;else{let e=this.entries.find(e=>e.name===t);if(!e)return this._issues?.record(Z.ASSET_UNREACHABLE,`no gobo named "${t}" is loaded — the light projects without one`,{name:t,asset:`gobo`}),!1;o.userData.gobo={name:e.name,index:e.index,intensity:dS(r),inverted:!!i,scale:Math.max(1e-4,a)}}return this.pathTracer.updateLights(),this._onReset?.(),!0}setLightGoboInverted(e,t){let n=this._findGoboLight(e);return n?.userData?.gobo?(n.userData.gobo.inverted=!!t,this.pathTracer.updateLights(),this._onReset?.(),!0):!1}setLightGoboScale(e,t){let n=this._findGoboLight(e);return n?.userData?.gobo?(n.userData.gobo.scale=Math.max(1e-4,t),this.pathTracer.updateLights(),this._onReset?.(),!0):!1}getLightGobo(e){return this._findGoboLight(e)?.userData?.gobo||null}setSpotLightGobo(e,t,n=1,r=!1){return this.setLightGobo(e,t,{intensity:n,inverted:r})}setSpotLightGoboInverted(e,t){return this.setLightGoboInverted(e,t)}getSpotLightGobo(e){return this.getLightGobo(e)}dispose(){this.texture?.dispose?.(),this.texture=null,this.entries=[],this.pathTracer=null,this._onReset=null,this._issues=null}_findGoboLight(e){let t=this.pathTracer?.scene?.getObjectByProperty?.(`uuid`,e);return t&&(t.isSpotLight||t.isDirectionalLight)?t:null}_findSpotLight(e){let t=this.pathTracer?.scene?.getObjectByProperty?.(`uuid`,e);return t&&t.isSpotLight?t:null}};async function uS(e){let t=await L_(e);try{return await new Promise((n,r)=>{let i=new Image;i.crossOrigin=`anonymous`,i.onload=()=>n(i),i.onerror=()=>r(Error(`Failed to load gobo image: ${e}`)),i.src=t.url})}finally{t.release()}}function dS(e){return Math.max(0,Math.min(1,e))}function fS(e,t=`ies`){let n=e.search(/TILT\s*=/i);if(n<0)throw Error(`IES (${t}): missing TILT line`);let r=e.indexOf(`
|
|
1002
|
+
`,Ox=class extends j{constructor(e,i={}){super(`LocalExposure`,{...i,executionMode:A.ALWAYS}),this.renderer=e,this.highlightContrast=i.highlightContrast??sx.localExposureHighlightContrast,this.shadowContrast=i.shadowContrast??sx.localExposureShadowContrast,this.detailStrength=i.detailStrength??sx.localExposureDetailStrength,this.onChange=null,this._grid=(0,n.attributeArray)(xx*xx*ux,`vec2`),this._blur=(0,n.attributeArray)(Sx*Sx,`float`),this._blurTmp=(0,n.attributeArray)(Sx*Sx,`float`),this._inputNode=new t.TextureNode,this._widthU=(0,n.uniform)(1,`int`),this._heightU=(0,n.uniform)(1,`int`),this._cellsXU=(0,n.uniform)(1,`int`),this._blurWU=(0,n.uniform)(1,`int`),this._blurHU=(0,n.uniform)(1,`int`),this._radiusU=(0,n.uniform)(1),this._logExposureU=(0,n.uniform)(0),this._p=[new r.Vector4,new r.Vector4,new r.Vector4,new r.Vector4].map(e=>(0,n.uniform)(e)),this._params=new Float32Array(16),this._kernels=[this._buildGridKernel(),this._buildBlurSourceKernel(),this._buildBlurKernel(this._blur,this._blurTmp,!0),this._buildBlurKernel(this._blurTmp,this._blur,!1)],this._built=!1,this._restarts=0,this._builtAt={restarts:-1,samples:-1},this._stale=!1,this._paramsBuffer=null,this._disposed=!1}_buildGridKernel(){let e=this._inputNode,t=this._grid,r=this._widthU,i=this._heightU,a=this._cellsXU,o=this._logExposureU,s=(0,n.vec4)(...Cx,0).xyz;return(0,n.Fn)(()=>{let c=n.localId.y.mul((0,n.uint)(16)).add(n.localId.x),l=(0,n.workgroupArray)(`uint`,ux).toAtomic(),u=(0,n.workgroupArray)(`uint`,ux).toAtomic();(0,n.If)(c.lessThan((0,n.uint)(ux)),()=>{(0,n.atomicStore)(l.element(c),(0,n.uint)(0)),(0,n.atomicStore)(u.element(c),(0,n.uint)(0))}),(0,n.workgroupBarrier)();let d=(0,n.int)(n.workgroupId.x).mul((0,n.int)(cx)).add((0,n.int)(n.localId.x).mul((0,n.int)(8))),f=(0,n.int)(n.workgroupId.y).mul((0,n.int)(cx)).add((0,n.int)(n.localId.y).mul((0,n.int)(8)));(0,n.Loop)({start:(0,n.int)(0),end:(0,n.int)(8),type:`int`,condition:`<`,update:2,name:`ty`},({ty:t})=>{(0,n.Loop)({start:(0,n.int)(0),end:(0,n.int)(8),type:`int`,condition:`<`,update:2,name:`tx`},({tx:a})=>{let c=d.add(a),p=f.add(t);(0,n.If)(c.lessThan(r).and(p.lessThan(i)),()=>{let t=(0,n.min)(c.add((0,n.int)(1)),r.sub((0,n.int)(1))),a=(0,n.min)(p.add((0,n.int)(1)),i.sub((0,n.int)(1))),d=(0,n.dot)((0,n.textureLoad)(e,(0,n.ivec2)(c,p)).xyz,s).add((0,n.dot)((0,n.textureLoad)(e,(0,n.ivec2)(t,p)).xyz,s)).add((0,n.dot)((0,n.textureLoad)(e,(0,n.ivec2)(c,a)).xyz,s)).add((0,n.dot)((0,n.textureLoad)(e,(0,n.ivec2)(t,a)).xyz,s)).mul(.25).toVar();(0,n.If)((0,n.floatBitsToUint)(d).bitAnd((0,n.uint)(2139095040)).notEqual((0,n.uint)(2139095040)),()=>{let e=(0,n.log2)((0,n.max)(d,bx)).clamp(px,mx).toVar(),t=e.add(o).sub(dx).div(fx-dx).clamp(0,1).mul(ux-1).toVar(),r=(0,n.uint)((0,n.floor)(t)).min((0,n.uint)(ux-1)),i=r.add((0,n.uint)(1)).min((0,n.uint)(ux-1)),a=t.sub((0,n.floor)(t)),s=(0,n.float)(1).sub(a),c=e.sub(px).mul(hx);(0,n.atomicAdd)(l.element(r),(0,n.uint)(c.mul(s).add(.5))),(0,n.atomicAdd)(u.element(r),(0,n.uint)(s.mul(hx).add(.5))),(0,n.atomicAdd)(l.element(i),(0,n.uint)(c.mul(a).add(.5))),(0,n.atomicAdd)(u.element(i),(0,n.uint)(a.mul(hx).add(.5)))})})})}),(0,n.workgroupBarrier)(),(0,n.If)(c.lessThan((0,n.uint)(ux)),()=>{let e=(0,n.float)((0,n.atomicLoad)(u.element(c))).div(hx),r=(0,n.float)((0,n.atomicLoad)(l.element(c))).div(hx).add(e.mul(px)),i=(0,n.uint)(n.workgroupId.y).mul((0,n.uint)(a)).add((0,n.uint)(n.workgroupId.x));t.element(i.mul((0,n.uint)(ux)).add(c)).assign((0,n.vec2)(r,e).div(lx))})})().compute([1,1,1],[16,16,1])}_buildBlurSourceKernel(){let e=this._inputNode,t=this._blur,r=this._widthU,i=this._heightU,a=this._blurWU,o=(0,n.vec4)(...Cx,0).xyz;return(0,n.Fn)(()=>{let s=n.localId.y.mul((0,n.uint)(8)).add(n.localId.x),c=(0,n.int)(n.workgroupId.x).mul((0,n.int)(gx)),l=(0,n.int)(n.workgroupId.y).mul((0,n.int)(gx)),u=(0,n.float)(0).toVar(),d=(0,n.float)(0).toVar();(0,n.Loop)({start:(0,n.int)(n.localId.y),end:(0,n.int)(gx),type:`int`,condition:`<`,update:8,name:`by`},({by:t})=>{(0,n.Loop)({start:(0,n.int)(n.localId.x),end:(0,n.int)(gx),type:`int`,condition:`<`,update:8,name:`bx`},({bx:a})=>{let s=c.add(a),f=l.add(t);(0,n.If)(s.lessThan(r).and(f.lessThan(i)),()=>{let t=(0,n.dot)((0,n.textureLoad)(e,(0,n.ivec2)(s,f)).xyz,o).toVar(),r=(0,n.floatBitsToUint)(t).bitAnd((0,n.uint)(2139095040)).notEqual((0,n.uint)(2139095040));u.addAssign((0,n.select)(r,t.max(0),(0,n.float)(0))),d.addAssign((0,n.select)(r,(0,n.float)(1),(0,n.float)(0)))})})});let f=(0,n.workgroupArray)(`float`,64),p=(0,n.workgroupArray)(`float`,64);f.element(s).assign(u),p.element(s).assign(d),(0,n.workgroupBarrier)();for(let e=32;e>0;e>>=1)(0,n.If)(s.lessThan((0,n.uint)(e)),()=>{f.element(s).addAssign(f.element(s.add((0,n.uint)(e)))),p.element(s).addAssign(p.element(s.add((0,n.uint)(e))))}),(0,n.workgroupBarrier)();(0,n.If)(s.equal((0,n.uint)(0)),()=>{let e=f.element((0,n.uint)(0)).div((0,n.max)(p.element((0,n.uint)(0)),1));t.element((0,n.uint)((0,n.int)(n.workgroupId.y).mul(a).add((0,n.int)(n.workgroupId.x)))).assign((0,n.log2)((0,n.max)(e,bx)).clamp(px,mx))})})().compute([1,1,1],[8,8,1])}_buildBlurKernel(e,t,r){let i=this._blurWU,a=this._blurHU,o=this._radiusU;return(0,n.Fn)(()=>{let s=(0,n.int)(n.workgroupId.x).mul((0,n.int)(8)).add((0,n.int)(n.localId.x)),c=(0,n.int)(n.workgroupId.y).mul((0,n.int)(8)).add((0,n.int)(n.localId.y));(0,n.If)(s.lessThan(i).and(c.lessThan(a)),()=>{let l=r?i:a,u=r?s:c,d=(0,n.int)(o.ceil()),f=(0,n.float)(0).toVar(),p=(0,n.float)(0).toVar();(0,n.Loop)({start:d.negate(),end:d.add((0,n.int)(1)),type:`int`,condition:`<`,name:`o`},({o:t})=>{let a=(0,n.float)(t).div(o),d=(0,n.exp)(a.mul(a).mul(-16.7)),m=l.mul((0,n.int)(2)),h=u.add(t).mod(m).add(m).mod(m).toVar();(0,n.If)(h.greaterThanEqual(l),()=>{h.assign(m.sub(h).sub((0,n.int)(1)))});let g=r?c.mul(i).add(h):h.mul(i).add(s);f.addAssign(e.element((0,n.uint)(g)).mul(d)),p.addAssign(d)}),t.element((0,n.uint)(c.mul(i).add(s))).assign(f.div(p))})})().compute([1,1,1],[8,8,1])}setupEventListeners(){this.on(`pipeline:reset`,()=>this._restarts++)}render(e){if(!this.enabled)return;let t=e.getState(`pathtracer:samples`)??0,n=this._builtAt;(this._stale||!this._built||n.restarts!==this._restarts||t-n.samples>=wx(t))&&this.build(e)}build(e=this.context){let t=e?.getTexture(`pathtracer:color`),n=t?.image?.width|0,r=t?.image?.height|0;if(!t||n<1||r<1||this._disposed)return!1;this._builtAt.restarts=this._restarts,this._builtAt.samples=e.getState(`pathtracer:samples`)??0,this._stale=!1;let i=Math.min(xx,Math.ceil(n/cx)),a=Math.min(xx,Math.ceil(r/cx)),o=Math.min(Sx,Math.ceil(n/gx)),s=Math.min(Sx,Math.ceil(r/gx)),c=Math.log2(Math.max(this.renderer.toneMappingExposure,1e-6));return this._inputNode.value=t,this._widthU.value=n,this._heightU.value=r,this._cellsXU.value=i,this._blurWU.value=o,this._blurHU.value=s,this._radiusU.value=Math.max(1,vx/100*o),this._logExposureU.value=c,this._kernels[0].dispatchSize=[i,a,1],this._kernels[1].dispatchSize=[o,s,1],this._kernels[2].dispatchSize=this._kernels[3].dispatchSize=[Math.ceil(o/8),Math.ceil(s/8),1],this.renderer.compute(this._kernels),this._params.set([n/cx,r/cx,n/gx,r/gx,i,a,o,s,c],0),this._built=!0,this._writeParams(),!0}_writeParams(){let e=this._params;e[9]=this.highlightContrast,e[10]=this.shadowContrast,e[11]=this.detailStrength,e[12]=_x,e[13]=yx;for(let t=0;t<4;t++)this._p[t].value.fromArray(e,t*4);this.onChange?.()}get wantsBuild(){return this.enabled&&(this._stale||!this._built)}updateParameters(e){for(let t of[`highlightContrast`,`shadowContrast`,`detailStrength`])e[t]!==void 0&&(this[t]=e[t]);this._writeParams()}setEnabled(e){this.enabled!==e&&(this.enabled=e,this._stale=!0,this.onChange?.())}gainNode(e,t){let r=(0,n.storage)(this._grid.value,`vec2`,xx*xx*ux).toReadOnly(),i=(0,n.storage)(this._blur.value,`float`,Sx*Sx).toReadOnly(),[a,o,s,c]=this._p;return(0,n.Fn)(([e,t])=>{let l=(0,n.log2)((0,n.max)((0,n.dot)(e,(0,n.vec4)(...Cx,0).xyz),bx)).min(mx).toVar(),u=(0,n.log2)(n.toneMappingExposure).toVar(),d=(0,n.ivec2)(o.zw),f=t.mul(a.zw).sub(.5).clamp((0,n.vec2)(0),(0,n.vec2)(d.sub((0,n.int)(1)))).toVar(),p=(0,n.ivec2)((0,n.floor)(f)).toVar(),m=p.add((0,n.int)(1)).min(d.sub((0,n.int)(1))).toVar(),h=f.sub((0,n.floor)(f)).toVar(),g=(e,t)=>i.element((0,n.uint)(t.mul(d.x).add(e))),_=(0,n.mix)((0,n.mix)(g(p.x,p.y),g(m.x,p.y),h.x),(0,n.mix)(g(p.x,m.y),g(m.x,m.y),h.x),h.y).toVar(),v=(0,n.ivec2)(o.xy),y=t.mul(a.xy).sub(.5).clamp((0,n.vec2)(0),(0,n.vec2)(v.sub((0,n.int)(1)))).toVar(),b=l.add(s.x).sub(dx).div(fx-dx).clamp(0,1).mul(ux-1).toVar(),x=(0,n.int)((0,n.floor)(y.x)),S=(0,n.int)((0,n.floor)(y.y)),C=(0,n.int)((0,n.floor)(b)),w=y.x.sub((0,n.floor)(y.x)),T=y.y.sub((0,n.floor)(y.y)),E=b.sub((0,n.floor)(b)),D=(0,n.vec2)(0).toVar();for(let e=0;e<8;e++){let t=e&1,i=e>>1&1,a=e>>2,o=(t?w:w.oneMinus()).mul(i?T:T.oneMinus()).mul(a?E:E.oneMinus()),s=x.add((0,n.int)(t)).min(v.x.sub((0,n.int)(1))),c=S.add((0,n.int)(i)).min(v.y.sub((0,n.int)(1))),l=C.add((0,n.int)(a)).min((0,n.int)(ux-1));D.addAssign(r.element((0,n.uint)(c.mul(v.x).add(s).mul((0,n.int)(ux)).add(l))).mul(o))}let O=(0,n.mix)((0,n.select)(D.y.mul(lx).lessThan(.001),_,D.x.div(D.y)),_,c.x).add(u).toVar(),k=l.add(u),A=(0,n.select)(O.greaterThan(c.y),s.y,s.z);return(0,n.exp2)(c.y.add(O.sub(c.y).mul(A)).add(k.sub(O).mul(s.w)).sub(k))})(e,t)}toneGain(){if(!this.enabled||!this._built)return null;let e=this.renderer.backend,t=e.get(this._grid.value)?.buffer,n=e.get(this._blur.value)?.buffer;if(!t||!n)return null;this._paramsBuffer??=e.device.createBuffer({label:`local-exposure-params`,size:64,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),e.device.queue.writeBuffer(this._paramsBuffer,0,this._params);let r=this._params.slice(),i=()=>Promise.all([this.renderer.getArrayBufferAsync(this._grid.value),this.renderer.getArrayBufferAsync(this._blur.value)]);return{key:`local-exposure`,wgsl:Dx,device:e.device,entries:[{binding:0,resource:{buffer:t}},{binding:1,resource:{buffer:n}},{binding:2,resource:{buffer:this._paramsBuffer}}],cpu:async()=>{let[e,t]=await i(),n=new Float32Array(e),a=new Float32Array(t);return(e,t,i,o)=>Ex(r,n,a,e,t,i,o)},copyTo:async e=>{let[t,n]=await i(),a=[[t,GPUBufferUsage.STORAGE],[n,GPUBufferUsage.STORAGE],[r,GPUBufferUsage.UNIFORM]].map(([t,n])=>{let r=e.createBuffer({label:`local-exposure-copy`,size:t.byteLength,usage:n|GPUBufferUsage.COPY_DST});return e.queue.writeBuffer(r,0,t),r});return{key:`local-exposure`,wgsl:Dx,device:e,entries:a.map((e,t)=>({binding:t,resource:{buffer:e}})),destroy:()=>a.forEach(e=>e.destroy())}}}}reset(){}setSize(){}dispose(){this._disposed=!0,this.onChange=null;for(let e of this._kernels)e.dispose();this._inputNode.dispose(),this._paramsBuffer?.destroy(),this._paramsBuffer=null}};F(),at();var kx=new r.Vector3,Ax=new r.Vector3;function jx(e,t){return Ax.subVectors(e,t.position).dot(t.getWorldDirection(kx))}function Mx(e,t,n=!1){return n?e.distance:jx(e.point,t)}var Nx=class extends r.EventDispatcher{constructor({scene:e,camera:t,canvas:n,assetLoader:i,pathTracer:a,floorPlane:o,isGeometryOnDisk:s=null}){super(),this.scene=e,this.isGeometryOnDisk=s,this.camera=t,this.canvas=n,this.assetLoader=i,this.pathTracer=a,this.floorPlane=o,this.raycaster=new r.Raycaster,this.focusMode=!1,this.focusPointIndicator=null,this.afPointPlacementMode=!1,this.handleAFPointClick=this.handleAFPointClick.bind(this),this.selectedObject=null,this.selectMode=!1,this.clickTimeout=null,this.mouseDownPosition=null,this.dragThreshold=5,this.handleFocusClick=this.handleFocusClick.bind(this),this.handleSelectClick=this.handleSelectClick.bind(this),this.handleSelectDoubleClick=this.handleSelectDoubleClick.bind(this),this.handleMouseDown=this.handleMouseDown.bind(this),this.handleMouseUp=this.handleMouseUp.bind(this),this.handleContextMenu=this.handleContextMenu.bind(this),this.handleContextPointerDown=this.handleContextPointerDown.bind(this),this.handleContextPointerUp=this.handleContextPointerUp.bind(this),this.contextPointerDownPosition=null,this.canvas.addEventListener(`pointerdown`,this.handleContextPointerDown),this.canvas.addEventListener(`pointerup`,this.handleContextPointerUp),this.canvas.addEventListener(`contextmenu`,this.handleContextMenu),this._overlayManager=null,this._transformManager=null,this._appDispatch=null,this._orbitControls=null,this._helperScene=null}setDependencies({overlayManager:e,transformManager:t,appDispatch:n,orbitControls:r,helperScene:i}){this._overlayManager=e||null,this._transformManager=t||null,this._appDispatch=n||null,this._orbitControls=r||null,this._helperScene=i||null}select(e){let t=this._overlayManager?.getHelper(`outline`);t&&t.setSelectedObjects(e&&!this.isGeometryOnDisk?.()?[e]:[]),this.selectedObject=e||null,e?this._transformManager?.attach(e):this._transformManager?.detach(),this._appDispatch?.({type:N.OBJECT_SELECTED,object:e||null})}deselect(){this.select(null)}disableMode(){this.disableSelectMode(),this._transformManager?.detach()}on(e,t){return this.addEventListener(e,t),()=>this.removeEventListener(e,t)}toggleFocusMode(){return this.focusMode=!this.focusMode,this.canvas.style.cursor=this.focusMode?`crosshair`:`auto`,this.focusMode?this.canvas.addEventListener(`click`,this.handleFocusClick):this.canvas.removeEventListener(`click`,this.handleFocusClick),this._orbitControls&&(this._orbitControls.enabled=!this.focusMode),this.dispatchEvent({type:`focusModeChanged`,enabled:this.focusMode}),this.focusMode}handleFocusClick(e){let t=this.getMouseCoordinates(e);this.raycaster.setFromCamera(t,this.camera);let n=this._intersectScene();if(n.length>0){let e=n[0],t=this.pathTracer?.cameraProjection?.value===tt.equirectangular,r=Mx(e,this.camera,t);this.showFocusPoint(e.point),this.toggleFocusMode(),this.dispatchEvent({type:`focusChanged`,distance:r/this.assetLoader.getSceneScale(),worldDistance:r})}}showFocusPoint(e){this.focusPointIndicator&&this.scene.remove(this.focusPointIndicator),this.focusPointIndicator=new r.Mesh(new r.SphereGeometry(this.assetLoader.getSceneScale()*.02,16,16),new r.MeshBasicMaterial({color:65280,transparent:!0,opacity:.8,depthTest:!1})),this.focusPointIndicator.position.copy(e),this.scene.add(this.focusPointIndicator),setTimeout(()=>{this.focusPointIndicator&&=(this.scene.remove(this.focusPointIndicator),null)},2e3)}enterAFPointPlacementMode(){this.afPointPlacementMode=!0,this.canvas.style.cursor=`crosshair`,this.canvas.addEventListener(`click`,this.handleAFPointClick)}exitAFPointPlacementMode(){this.afPointPlacementMode=!1,this.canvas.style.cursor=`auto`,this.canvas.removeEventListener(`click`,this.handleAFPointClick)}handleAFPointClick(e){let t=this.canvas.getBoundingClientRect(),n=(e.clientX-t.left)/t.width,r=(e.clientY-t.top)/t.height;this.exitAFPointPlacementMode(),this.dispatchEvent({type:`afPointPlaced`,point:{x:n,y:r}})}toggleSelectMode(){return this.selectMode=!this.selectMode,this.canvas.style.cursor=this.selectMode?`pointer`:`auto`,this.selectMode?(this.canvas.addEventListener(`mousedown`,this.handleMouseDown),this.canvas.addEventListener(`mouseup`,this.handleMouseUp),this.canvas.addEventListener(`click`,this.handleSelectClick),this.canvas.addEventListener(`dblclick`,this.handleSelectDoubleClick)):(this.canvas.removeEventListener(`mousedown`,this.handleMouseDown),this.canvas.removeEventListener(`mouseup`,this.handleMouseUp),this.canvas.removeEventListener(`click`,this.handleSelectClick),this.canvas.removeEventListener(`dblclick`,this.handleSelectDoubleClick),this.clickTimeout&&=(clearTimeout(this.clickTimeout),null),this.mouseDownPosition=null),this.dispatchEvent({type:`selectModeChanged`,enabled:this.selectMode}),this.selectMode}disableSelectMode(){this.selectMode&&(this.selectMode=!1,this.canvas.style.cursor=`auto`,this.canvas.removeEventListener(`mousedown`,this.handleMouseDown),this.canvas.removeEventListener(`mouseup`,this.handleMouseUp),this.canvas.removeEventListener(`click`,this.handleSelectClick),this.canvas.removeEventListener(`dblclick`,this.handleSelectDoubleClick),this.clickTimeout&&=(clearTimeout(this.clickTimeout),null),this.mouseDownPosition=null,this.dispatchEvent({type:`selectModeChanged`,enabled:!1}))}handleMouseDown(e){this.mouseDownPosition={x:e.clientX,y:e.clientY,button:e.button}}wasMouseDragged(e){if(!this.mouseDownPosition)return!1;let t=Math.abs(e.clientX-this.mouseDownPosition.x),n=Math.abs(e.clientY-this.mouseDownPosition.y);return Math.sqrt(t*t+n*n)>this.dragThreshold}handleSelectClick(e){if(this.wasMouseDragged(e)){this.mouseDownPosition=null;return}if(this.mouseDownPosition=null,this.clickTimeout){clearTimeout(this.clickTimeout),this.clickTimeout=null;return}this.clickTimeout=setTimeout(()=>{this.clickTimeout=null;let t=this.getMouseCoordinates(e);this.raycaster.setFromCamera(t,this.camera);let n=this._intersectScene(),r=this.filterValidIntersects(n),i=this._pickLightHelper(),a=null;if(r.length>0&&i?a=r[0].distance<=i.distance?r[0].object:i.light:r.length>0?a=r[0].object:i&&(a=i.light),a){let e=this.selectedObject;e&&e.uuid===a.uuid?this.dispatchEvent({type:`objectDeselected`,object:a,uuid:a.uuid}):this.dispatchEvent({type:`objectSelected`,object:a,uuid:a.uuid})}else this.dispatchEvent({type:`objectDeselected`})},250)}handleSelectDoubleClick(e){if(this.wasMouseDragged(e)){this.mouseDownPosition=null;return}this.mouseDownPosition=null,this.clickTimeout&&=(clearTimeout(this.clickTimeout),null);let t=this.getMouseCoordinates(e);this.raycaster.setFromCamera(t,this.camera);let n=this._intersectScene(),r=this.filterValidIntersects(n);if(r.length>0){let e=r[0].object;this.dispatchEvent({type:`objectDoubleClicked`,object:e,uuid:e.uuid})}}handleMouseUp(){}handleContextPointerDown(e){e.button===2&&(this.contextPointerDownPosition={x:e.clientX,y:e.clientY})}handleContextPointerUp(e){if(e.button!==2)return;if(this.contextPointerDownPosition){let t=Math.abs(e.clientX-this.contextPointerDownPosition.x),n=Math.abs(e.clientY-this.contextPointerDownPosition.y);if(Math.sqrt(t*t+n*n)>this.dragThreshold){this.contextPointerDownPosition=null;return}}else return;this.contextPointerDownPosition=null;let t=this.selectedObject;t&&this.dispatchEvent({type:`contextMenuRequested`,x:e.clientX,y:e.clientY,selectedObject:t})}handleContextMenu(e){e.preventDefault()}getMouseCoordinates(e){let t=this.canvas.getBoundingClientRect();return{x:(e.clientX-t.left)/t.width*2-1,y:-((e.clientY-t.top)/t.height)*2+1}}_intersectScene(){return this.isGeometryOnDisk?.()?[]:this.raycaster.intersectObjects(this.scene.children,!0)}pickSurface(e,t){return this.raycaster.setFromCamera({x:e,y:t},this.camera),this.filterValidIntersects(this._intersectScene())[0]??null}filterValidIntersects(e){return e.filter(e=>{let t=e.object;return t!==this.focusPointIndicator&&t!==this.floorPlane&&!t.name.includes(`Helper`)&&t.type===`Mesh`})}_pickLightHelper(){if(!this._helperScene||this._helperScene.children.length===0)return null;let e=this.raycaster.intersectObjects(this._helperScene.children,!0);for(let t of e){let e=t.object;for(;e;){if(e.light)return{distance:t.distance,light:e.light};e=e.parent}}return null}updateDependencies({scene:e,camera:t,floorPlane:n}){e&&(this.scene=e),t&&(this.camera=t),n&&(this.floorPlane=n)}wireAppEvents(e){this.addEventListener(`objectSelected`,t=>{this.select(t.object),e.refreshFrame(),e.dispatchEvent({type:N.OBJECT_SELECTED,object:t.object,uuid:t.uuid})}),this.addEventListener(`objectDeselected`,t=>{this.select(null),e.refreshFrame(),e.dispatchEvent({type:N.OBJECT_DESELECTED,object:t.object,uuid:t.uuid})}),this.addEventListener(`selectModeChanged`,t=>{e.dispatchEvent({type:N.SELECT_MODE_CHANGED,enabled:t.enabled})}),this.addEventListener(`objectDoubleClicked`,t=>{this.select(t.object),e.refreshFrame(),e.dispatchEvent({type:N.OBJECT_DOUBLE_CLICKED,object:t.object,uuid:t.uuid})}),this.addEventListener(`focusChanged`,t=>{e.settings.set(`focusDistance`,t.worldDistance),e.dispatchEvent({type:N.FOCUS_CHANGED,distance:t.distance})}),this.addEventListener(`afPointPlaced`,t=>{e.dispatchEvent({type:N.AF_POINT_PLACED,point:t.point})})}dispose(){this.canvas.removeEventListener(`click`,this.handleAFPointClick),this.canvas.removeEventListener(`click`,this.handleFocusClick),this.canvas.removeEventListener(`mousedown`,this.handleMouseDown),this.canvas.removeEventListener(`mouseup`,this.handleMouseUp),this.canvas.removeEventListener(`click`,this.handleSelectClick),this.canvas.removeEventListener(`dblclick`,this.handleSelectDoubleClick),this.canvas.removeEventListener(`contextmenu`,this.handleContextMenu),this.canvas.removeEventListener(`pointerdown`,this.handleContextPointerDown),this.canvas.removeEventListener(`pointerup`,this.handleContextPointerUp),this.clickTimeout&&=(clearTimeout(this.clickTimeout),null),this.mouseDownPosition=null,this.contextPointerDownPosition=null,this.focusPointIndicator&&=(this.scene.remove(this.focusPointIndicator),null),this.canvas.style.cursor=`auto`,this.scene=null,this.camera=null,this.canvas=null,this.assetLoader=null,this.pathTracer=null,this.floorPlane=null,this.raycaster=null}},Px=8,Fx=4,Ix=.25,Lx=r.MathUtils.degToRad(89),Rx=.25,zx={KeyD:[1,0,0],ArrowRight:[1,0,0],KeyA:[-1,0,0],ArrowLeft:[-1,0,0],KeyW:[0,1,0],ArrowUp:[0,1,0],KeyS:[0,-1,0],ArrowDown:[0,-1,0],KeyE:[0,0,1],KeyQ:[0,0,-1]},Bx=`input, textarea, select, [contenteditable]:not([contenteditable="false"]), [role=textbox], [role=combobox], [role=listbox], [role=menu], [role=menuitem]`,Vx=e=>e.shiftKey?Fx:e.altKey?Ix:1,Hx={type:`change`},Ux={type:`start`},Wx=new r.Vector3,Gx=new r.Vector3,Kx=new r.Vector3,qx=new r.Vector3,Jx=new r.Quaternion,Yx=class extends r.Controls{constructor(e,t,n){super(e,t),this.orbit=n,this.enabled=!1,this.speed=1/Px,this._held=new Set,this._factor=1,this._lastTime=0,this._drag=null,this._onKeyDown=this._onKeyDown.bind(this),this._onKeyUp=this._onKeyUp.bind(this),this.release=this.release.bind(this),this._onPointerDown=this._onPointerDown.bind(this),this._onPointerMove=this._onPointerMove.bind(this),this._onPointerUp=this._onPointerUp.bind(this),t&&this.connect(t)}get active(){return this.enabled&&this.orbit.enabled}fitSpeed(e){this.speed=(e>0?e:1)/Px}connect(e){super.connect(e);let t=e.ownerDocument;t?.addEventListener(`keydown`,this._onKeyDown),t?.addEventListener(`keyup`,this._onKeyUp),t?.addEventListener(`visibilitychange`,this.release),t?.defaultView?.addEventListener(`blur`,this.release),e.addEventListener(`pointerdown`,this._onPointerDown),e.addEventListener(`pointermove`,this._onPointerMove),e.addEventListener(`pointerup`,this._onPointerUp),e.addEventListener(`pointercancel`,this._onPointerUp)}disconnect(){let e=this.domElement;if(!e)return;let t=e.ownerDocument;t?.removeEventListener(`keydown`,this._onKeyDown),t?.removeEventListener(`keyup`,this._onKeyUp),t?.removeEventListener(`visibilitychange`,this.release),t?.defaultView?.removeEventListener(`blur`,this.release),e.removeEventListener(`pointerdown`,this._onPointerDown),e.removeEventListener(`pointermove`,this._onPointerMove),e.removeEventListener(`pointerup`,this._onPointerUp),e.removeEventListener(`pointercancel`,this._onPointerUp)}dispose(){this.disconnect()}update(e=this._elapsed()){if(!this._held.size||!this.active)return!1;let t=0,n=0,r=0;for(let e of this._held){let[i,a,o]=zx[e];t+=i,n+=a,r+=o}if(!t&&!n&&!r)return!1;let i=this.object;return Gx.set(1,0,0).applyQuaternion(i.quaternion),Wx.crossVectors(i.up,Gx).normalize(),Gx.crossVectors(Wx,i.up),Kx.set(0,0,0).addScaledVector(Gx,t).addScaledVector(Wx,n).addScaledVector(i.up,r).normalize().multiplyScalar(this.speed*this._factor*e),i.position.add(Kx),this.orbit.target.add(Kx),i.updateMatrixWorld(),this.dispatchEvent(Hx),!0}_elapsed(){let e=performance.now(),t=Math.min((e-this._lastTime)/1e3,Rx);return this._lastTime=e,t}_look(e,t){let n=this.object,i=this.orbit.target,a=n.position.distanceTo(i)||1,o=r.MathUtils.degToRad(n.fov)/(this.domElement.clientHeight||1);n.quaternion.premultiply(Jx.setFromAxisAngle(n.up,e*o)),n.getWorldDirection(Wx);let s=Math.asin(r.MathUtils.clamp(Wx.dot(n.up),-1,1)),c=r.MathUtils.clamp(s+t*o,-Lx,Lx);n.quaternion.multiply(Jx.setFromAxisAngle(qx.set(1,0,0),c-s)),n.updateMatrixWorld(),i.copy(n.position).addScaledVector(n.getWorldDirection(Wx),a),this.dispatchEvent(Hx)}_onKeyDown(e){if(!(!this.active||e.defaultPrevented||e.target?.closest?.(Bx))){if(e.metaKey||e.ctrlKey){this.release();return}this._factor=Vx(e),zx[e.code]&&(e.preventDefault(),!this._held.has(e.code)&&(this._held.add(e.code),this._held.size===1&&(this._lastTime=performance.now(),this.dispatchEvent(Ux))))}}_onKeyUp(e){this._factor=Vx(e),this._held.delete(e.code)}release(){this._held.clear(),this._factor=1}_onPointerDown(e){!this.active||e.button!==0||!e.isPrimary||(this._drag={id:e.pointerId,x:e.clientX,y:e.clientY},this.domElement.setPointerCapture?.(e.pointerId))}_onPointerMove(e){let t=this._drag;if(!t||e.pointerId!==t.id)return;let n=e.clientX-t.x,r=e.clientY-t.y;t.x=e.clientX,t.y=e.clientY,this.active&&(n||r)&&this._look(n,r)}_onPointerUp(e){this._drag?.id===e.pointerId&&(this._drag=null,this.domElement.releasePointerCapture?.(e.pointerId))}};F(),at();var Xx={autoFocusMode:`auto`,afScreenPoint:{x:.5,y:.5},afSmoothingFactor:.15},Zx=.05,Qx=10,$x=.5,eS=Object.freeze(new r.Vector3(1,1,1)),tS=e=>e?.isOrthographicCamera?(e.top-e.bottom)/e.zoom:null,nS=class extends r.EventDispatcher{constructor(e){super();let t=e.clientWidth,n=e.clientHeight;this.camera=new cy(60,t/n||1,.01,1e3),this.camera.position.set(0,0,5),this.controls=new u.OrbitControls(this.camera,e),this.controls.screenSpacePanning=!0,this.controls.zoomToCursor=!0,this.controls.saveState(),this._reportedOrthoHeight=null,this._reportOrthoHeight=this._reportOrthoHeight.bind(this),this.controls.addEventListener(`change`,this._reportOrthoHeight),this.walkControls=new Yx(this.camera,e,this.controls),this.interactionManager=null,this.cameras=[this.camera],this.currentCameraIndex=0,this._userCameraCounter=0,this.autoFocusMode=Xx.autoFocusMode,this.afScreenPoint={...Xx.afScreenPoint},this.afSmoothingFactor=Xx.afSmoothingFactor,this._lastValidFocusDistance=null,this._smoothedFocusDistance=null,this._afPointDirty=!1,this._afSuspended=!1,this._afPick=null,this._defaultCameraState=null,this._onResize=null,this._onReset=null,this._getSettings=null,this._applySettings=null}setCameras(e){this.cameras=e,this._userCameraCounter=0,this.resetAutoFocus()}addCameraFromView(e){let t=this.camera,n=t.orthographic?new r.OrthographicCamera(t.left,t.right,t.top,t.bottom,t.near,t.far):new r.PerspectiveCamera(t.fov,t.aspect,t.near,t.far);return n.zoom=t.zoom,n.position.copy(t.position),n.quaternion.copy(t.quaternion),n.scale.copy(t.scale),n.updateMatrixWorld(!0),n.userData.__rayzeeUserCamera=!0,n.userData.__rayzeeEffects=this._captureEffects(),this.controls&&(n.userData.__rayzeeOrbitTarget=this.controls.target.clone()),this._userCameraCounter+=1,n.name=e||`View Camera ${this._userCameraCounter}`,this.cameras.push(n),this.cameras.length-1}removeCamera(e){if(!Number.isInteger(e)||e<=0||e>=this.cameras.length||!this.cameras[e]?.userData?.__rayzeeUserCamera)return!1;let t=this.currentCameraIndex===e;return this.cameras.splice(e,1),t?(this.currentCameraIndex=-1,this.switchCamera(0)):this.currentCameraIndex>e&&--this.currentCameraIndex,!0}getCameraNames(){return!this.cameras||this.cameras.length===0?[`Default Camera`]:this.cameras.map((e,t)=>t===0?`Default Camera`:e.name||`Camera ${t}`)}initCallbacks({onResize:e,onReset:t,getSettings:n,applySettings:r}){this._onResize=e,this._onReset=t,this._getSettings=n,this._applySettings=r}_captureEffects(){let e=this._getSettings;return e?{enableDOF:e(`enableDOF`),focusDistance:e(`focusDistance`),aperture:e(`aperture`),focalLength:e(`focalLength`),apertureScale:e(`apertureScale`),anamorphicRatio:e(`anamorphicRatio`),dofBlur:e(`dofBlur`),autoFocusMode:this.autoFocusMode,afScreenPoint:{...this.afScreenPoint},orthoHeight:this.orthoHeight}:null}_applyEffects(e){e&&(this._applySettings?.({enableDOF:e.enableDOF,focusDistance:e.focusDistance,aperture:e.aperture,focalLength:e.focalLength,apertureScale:e.apertureScale,anamorphicRatio:e.anamorphicRatio,dofBlur:e.dofBlur}),e.autoFocusMode!==void 0&&this.setAutoFocusMode(e.autoFocusMode),e.afScreenPoint&&this.setAFScreenPoint(e.afScreenPoint.x,e.afScreenPoint.y))}switchCamera(e,t,n,r){if(t??=this._getSettings?.(`focusDistance`),n??=this._onResize,r??=this._onReset,!this.cameras||this.cameras.length===0)return;(e<0||e>=this.cameras.length)&&(console.warn(`CameraManager: Invalid camera index ${e}. Using default camera.`),e=0);let i=this.cameras[this.currentCameraIndex];if(i&&(i.userData.__rayzeeEffects=this._captureEffects()),this.currentCameraIndex===0&&e!==0&&(this._defaultCameraState={position:this.camera.position.clone(),quaternion:this.camera.quaternion.clone(),scale:this.camera.scale.clone(),fov:this.camera.fov,near:this.camera.near,far:this.camera.far,target:this.controls?this.controls.target.clone():null}),this.currentCameraIndex=e,e===0&&this._defaultCameraState){let e=this._defaultCameraState;this.camera.position.copy(e.position),this.camera.quaternion.copy(e.quaternion),this.camera.scale.copy(e.scale??eS),this.camera.fov=e.fov,this.camera.near=e.near,this.camera.far=e.far,this.camera.updateProjectionMatrix(),this.camera.updateMatrixWorld(!0),this.controls&&e.target&&(this.controls.target.copy(e.target),this.controls.update())}else this._placeAt(this.cameras[e],t);this.resetAutoFocus();let a=this.cameras[e],o=a?.userData?.__rayzeeEffects;this._showOrthographic(o?o.orthoHeight:tS(a)),this._applyEffects(o),n?.(),r?.(),this.dispatchEvent({type:N.CAMERA_SWITCHED,cameraIndex:e,effects:this._captureEffects(),fov:this.camera.fov,cameraProjection:this._getSettings?.(`cameraProjection`)})}resetView(){let e=this.currentCameraIndex>0?this.cameras[this.currentCameraIndex]:null;if(!e){this.controls.reset();return}this._placeAt(e,this._getSettings?.(`focusDistance`));let t=tS(e);this.camera.orthographic&&this._setView(!0,t?t/2:this.camera.orthoHalfHeight),this._onReset?.()}_placeAt(e,t){if(this.camera.position.copy(e.position),this.camera.quaternion.copy(e.quaternion),this.camera.scale.copy(e.scale),e.isPerspectiveCamera&&(this.camera.fov=e.fov),this.camera.near=e.near,this.camera.far=e.far,this.camera.updateProjectionMatrix(),this.camera.updateMatrixWorld(!0),!this.controls)return;let n=e.userData?.__rayzeeOrbitTarget;if(n)this.controls.target.copy(n);else{let n=new r.Vector3(0,0,-1).applyQuaternion(e.quaternion);this.controls.target.copy(this.camera.position).addScaledVector(n,t||5)}this.controls.update()}_showOrthographic(e){e>0?this._setView(!0,e/2):this._setView(!1);let t=this._getSettings?.(`cameraProjection`),n=e>0?`orthographic`:t===`orthographic`?`perspective`:t;n!==t&&this._applySettings?.({cameraProjection:n})}applyProjection(e){let t=this.camera,n=e===`orthographic`;if(t.orthographic!==n){if(n)this._setView(!0,this._fittedHalfHeight());else{let e=this.controls.target,n=this.orthoHeight/2/Math.tan(r.MathUtils.degToRad(t.fov)/2);t.position.sub(e).setLength(n).add(e),this._setView(!1)}this.controls.update()}}get orthoHeight(){return tS(this.camera)}setOrthoHeight(e){e>0&&(this._setView(this.camera.orthographic,e/2),this._onReset?.())}fitOrthographic(){this.camera.orthographic&&this.setOrthoHeight(2*this._fittedHalfHeight())}_setView(e,t=this.camera.orthoHalfHeight){let n=this.camera;n.orthographic=e,n.orthoHalfHeight=t,n.zoom=1,n.updateProjectionMatrix(),this._reportOrthoHeight()}_fittedHalfHeight(){return this.camera.position.distanceTo(this.controls.target)*Math.tan(r.MathUtils.degToRad(this.camera.fov)/2)}_reportOrthoHeight(){if(!this.camera.orthographic)return;let e=this.orthoHeight;e!==this._reportedOrthoHeight&&(this._reportedOrthoHeight=e,this.dispatchEvent({type:N.ORTHO_HEIGHT_UPDATED,height:e}))}focusOn(e){!e||!this.controls||(this.controls.target.copy(e),this.controls.update(),this._onReset?.())}setNavigationMode(e){let t=e===`walk`;if(this.walkControls.enabled===t)return;let n=this.controls;if(n.enableRotate=n.enablePan=n.enableZoom=!t,this.walkControls.enabled=t,t)return;this.walkControls.release();let i=this.interactionManager?.pickSurface(0,0);if(!i)return;let a=r.MathUtils.clamp(i.distance,n.minDistance,n.maxDistance);n.target.copy(this.camera.position).addScaledVector(this.camera.getWorldDirection(new r.Vector3),a),n.update()}get navigationMode(){return this.walkControls.enabled?`walk`:`orbit`}updateControls(){this.walkControls.update(),this.controls.update()}captureView(){let e=this.camera,t=this.orthoHeight??2*this._fittedHalfHeight();return{position:e.position.clone(),target:this.controls.target.clone(),fov:e.fov,orthoHeight:t}}applyPose(e){let t=this.camera;t.position.copy(e.position),t.lookAt(e.target),this.controls.target.copy(e.target),t.orthographic?this._setView(!0,e.orthoHeight/2):(t.fov=e.fov,t.updateProjectionMatrix()),t.updateMatrixWorld()}serialize(){let e=this.camera,t=this._defaultCameraState;return{current:this.currentCameraIndex,view:{position:e.position.toArray(),quaternion:e.quaternion.toArray(),scale:e.scale.toArray(),fov:e.fov,near:e.near,far:e.far,zoom:e.zoom,orthographic:!!e.orthographic,orthoHalfHeight:e.orthoHalfHeight,target:this.controls.target.toArray()},defaultView:t?{position:t.position.toArray(),quaternion:t.quaternion.toArray(),scale:t.scale.toArray(),fov:t.fov,near:t.near,far:t.far,target:t.target?.toArray()??null}:null,navigationMode:this.navigationMode,autoFocus:{mode:this.autoFocusMode,point:{...this.afScreenPoint}},cameras:this.cameras.map((e,t)=>{let n={index:t,name:e.name??``,effects:tr(e.userData?.__rayzeeEffects)??null};return t===0||!e.userData?.__rayzeeUserCamera?n:{...n,user:!0,orthographic:!!e.isOrthographicCamera,frustum:e.isOrthographicCamera?[e.left,e.right,e.top,e.bottom]:null,fov:e.fov??null,aspect:e.aspect??null,near:e.near,far:e.far,zoom:e.zoom,position:e.position.toArray(),quaternion:e.quaternion.toArray(),scale:e.scale.toArray(),orbitTarget:e.userData.__rayzeeOrbitTarget?.toArray()??null}})}}restore(e){let t=[];if(!e)return{mismatched:t};this.cameras=this.cameras.filter(e=>!e.userData?.__rayzeeUserCamera);let n=new Map;for(let i of e.cameras??[]){if(i.user){let e=i.orthographic?new r.OrthographicCamera(...i.frustum,i.near,i.far):new r.PerspectiveCamera(i.fov,i.aspect,i.near,i.far);e.name=i.name,e.zoom=i.zoom??1,e.position.fromArray(i.position),e.quaternion.fromArray(i.quaternion),e.scale.fromArray(i.scale),e.updateProjectionMatrix(),e.updateMatrixWorld(!0),e.userData.__rayzeeUserCamera=!0,e.userData.__rayzeeEffects=nr(i.effects),i.orbitTarget&&(e.userData.__rayzeeOrbitTarget=new r.Vector3().fromArray(i.orbitTarget)),n.set(i.index,this.cameras.length),this.cameras.push(e);continue}let e=this.cameras[i.index];if(!e||i.index>0&&(e.name??``)!==i.name){t.push(i.name);continue}n.set(i.index,i.index),i.effects&&(e.userData.__rayzeeEffects=nr(i.effects))}this._userCameraCounter=this.cameras.filter(e=>e.userData?.__rayzeeUserCamera).length,this.currentCameraIndex=n.get(e.current)??0;let i=e.defaultView;this._defaultCameraState=i?{position:new r.Vector3().fromArray(i.position),quaternion:new r.Quaternion().fromArray(i.quaternion),scale:new r.Vector3().fromArray(i.scale),fov:i.fov,near:i.near,far:i.far,target:i.target?new r.Vector3().fromArray(i.target):null}:null,e.navigationMode&&this.setNavigationMode(e.navigationMode);let a=e.view;if(a){let e=this.camera;e.position.fromArray(a.position),e.quaternion.fromArray(a.quaternion),e.scale.fromArray(a.scale),e.fov=a.fov,e.near=a.near,e.far=a.far,this._setView(a.orthographic,a.orthoHalfHeight),e.zoom=a.zoom??1,e.updateProjectionMatrix(),e.updateMatrixWorld(!0),this.controls.target.fromArray(a.target),this.controls.update()}return e.autoFocus&&(this.setAutoFocusMode(e.autoFocus.mode),this.setAFScreenPoint(e.autoFocus.point.x,e.autoFocus.point.y)),this.resetAutoFocus(),this._reportOrthoHeight(),this.dispatchEvent({type:N.CAMERA_SWITCHED,cameraIndex:this.currentCameraIndex,effects:this._captureEffects(),fov:this.camera.fov,cameraProjection:this._getSettings?.(`cameraProjection`)}),{mismatched:t}}get active(){return this.camera}getNames(){return this.getCameraNames()}setAutoFocusMode(e){this.autoFocusMode=e,e!==`manual`&&(this._smoothedFocusDistance=null,this._afPointDirty=!0)}resetAutoFocus(){this._lastValidFocusDistance=null,this._smoothedFocusDistance=null,this._afPointDirty=!0}setAFScreenPoint(e,t){this.afScreenPoint={x:e,y:t},this._afPointDirty=!0}enterAFPointPlacementMode(){this.interactionManager&&(this.interactionManager.enterAFPointPlacementMode(),this.controls&&(this.controls.enabled=!1))}exitAFPointPlacementMode(){this.interactionManager&&(this.interactionManager.exitAFPointPlacementMode(),this.controls&&(this.controls.enabled=!0))}updateAutoFocus(e){let t=e||this._afContext;if(!t||!this.interactionManager)return;let{assetLoader:n,currentFocusDistance:r,pathTracer:i,setFocusDistance:a,softReset:o,hardReset:s}=t;if(this.autoFocusMode===`manual`)return;if(!i?.enableDOF?.value||i.cameraProjection?.value===tt.equirectangular){this._afSuspended=!0;return}this._afSuspended&&(this._afSuspended=!1,this._smoothedFocusDistance=null);let c=i;if(c?.isReady&&c.renderMode?.value===1&&c.frameCount>0&&!c.isComplete)return;let l=this._pickFocusPoint(c.resetCount),u;if(l)u=jx(l,this.camera),this._lastValidFocusDistance=u;else if(this._lastValidFocusDistance!==null)u=this._lastValidFocusDistance;else{let e=this.controls?jx(this.controls.target,this.camera):0;u=e>0?e:Qx*(n?.getSceneScale()||1),this._lastValidFocusDistance=u}let d=this._afPointDirty;this._afPointDirty=!1,d||this._smoothedFocusDistance===null||this._smoothedFocusDistance===0||Math.abs(u-this._smoothedFocusDistance)/this._smoothedFocusDistance>$x?this._smoothedFocusDistance=u:this._smoothedFocusDistance+=this.afSmoothingFactor*(u-this._smoothedFocusDistance);let f=r,p=this._smoothedFocusDistance;if(d||f===0||Math.abs(p-f)/Math.max(f,.001)>.001){a(p);let e=n?.getSceneScale()||1;this.dispatchEvent({type:N.AUTO_FOCUS_UPDATED,distance:p/e,worldDistance:p});let t=Math.abs(p-f)/Math.max(f,.001);d?s?.():t>Zx&&o?.()}}_pickFocusPoint(e){let t=this.camera,{x:n,y:i}=this.afScreenPoint,a=this._afPick??={point:new r.Vector3,hit:!1,resetCount:NaN,x:NaN,y:NaN,view:new r.Matrix4,projection:new r.Matrix4};if(this._afPointDirty||e!==a.resetCount||n!==a.x||i!==a.y||!a.view.equals(t.matrixWorld)||!a.projection.equals(t.projectionMatrix)){let r=this.interactionManager.pickSurface(n*2-1,1-i*2);a.hit=!!r,r&&a.point.copy(r.point),a.resetCount=e,a.x=n,a.y=i,a.view.copy(t.matrixWorld),a.projection.copy(t.projectionMatrix)}return a.hit?a.point:null}setInteractionManager(e){this.interactionManager=e}initAutoFocus({assetLoader:e,pathTracer:t,settings:n,softReset:r,hardReset:i}){this._afContext={assetLoader:e,pathTracer:t,setFocusDistance:e=>n.set(`focusDistance`,e,{silent:!0}),softReset:r,hardReset:i},Object.defineProperty(this._afContext,`currentFocusDistance`,{get:()=>n.get(`focusDistance`)})}dispose(){this.walkControls?.dispose(),this.controls?.removeEventListener(`change`,this._reportOrthoHeight),this.controls?.dispose()}},rS=.001,iS=2,aS=(e,t,n,i)=>new e(t,n,i,r.InterpolateSmooth).createInterpolant(),oS=class{constructor(e,t){this._cameraManager=e,this._onChange=t,this.keys=[],this._nextId=1,this._interpolants=null}get animates(){return this.keys.length>1}get duration(){return this.keys.length?this.keys[this.keys.length-1].time:0}addKey(e=this.keys.length?this.duration+iS:0){return this.add(this._cameraManager.captureView(),e)}updateKey(e){this.update(e,this._cameraManager.captureView())}seek(e){let t=this.sample(e);return t&&this._cameraManager.applyPose(t),!!t}add(e,t){let n={id:this._nextId++,time:t,...sS(e)};return this.keys.push(n),this._changed(),n}update(e,t){let n=this.get(e);n&&(Object.assign(n,sS(t)),this._changed())}setTime(e,t){let n=this.get(e);!n||!(t>=0)||(n.time=t,this._changed())}remove(e){let t=this.keys.length;this.keys=this.keys.filter(t=>t.id!==e),this.keys.length!==t&&this._changed()}clear(){this.keys.length&&(this.keys=[],this._changed())}serialize(){return this.keys.map(({time:e,position:t,target:n,fov:r,orthoHeight:i})=>({time:e,position:t.toArray(),target:n.toArray(),fov:r,orthoHeight:i}))}restore(e){this.keys=(e??[]).map(e=>({id:this._nextId++,time:e.time,position:new r.Vector3().fromArray(e.position),target:new r.Vector3().fromArray(e.target),fov:e.fov,orthoHeight:e.orthoHeight})),this._changed()}dispose(){this._cameraManager=this._onChange=null}get(e){return this.keys.find(t=>t.id===e)}sample(e,t={position:new r.Vector3,target:new r.Vector3,fov:0,orthoHeight:0}){if(!this.keys.length)return null;let{position:n,target:i,fov:a,logHeight:o,start:s,end:c}=this._interpolants??=this._build(),l=r.MathUtils.clamp(e,s,c);return t.position.fromArray(n.evaluate(l)),t.target.fromArray(i.evaluate(l)),t.fov=a.evaluate(l)[0],t.orthoHeight=Math.exp(o.evaluate(l)[0]),t}_build(){let e=[];for(let t of this.keys)e.push(e.length?Math.max(t.time,e[e.length-1]+rS):t.time);let t=e[0],n=e[e.length-1],i=this.keys;if(i.length>1){let r=i.length;e.unshift(2*t-e[1]),e.push(2*n-e[r-1]),i=[i[1],...i,i[r-2]]}let a=e=>i.flatMap(t=>e(t).toArray());return{start:t,end:n,position:aS(r.VectorKeyframeTrack,`.position`,e,a(e=>e.position)),target:aS(r.VectorKeyframeTrack,`.target`,e,a(e=>e.target)),fov:aS(r.NumberKeyframeTrack,`.fov`,e,i.map(e=>e.fov)),logHeight:aS(r.NumberKeyframeTrack,`.orthoHeight`,e,i.map(e=>Math.log(e.orthoHeight)))}}_changed(){this.keys.sort((e,t)=>e.time-t.time),this._interpolants=null,this._onChange?.()}};function sS({position:e,target:t,fov:n,orthoHeight:r}){return{position:e.clone(),target:t.clone(),fov:n,orthoHeight:r}}F();var cS=class extends r.EventDispatcher{constructor({cameraManager:e,onReset:t}){super(),this._cameraManager=e,this._onReset=t,this.camera=new oS(e,()=>this._changed(`camera`)),this._playback=null,this._timer=new r.Timer,typeof document<`u`&&this._timer.connect(document)}get duration(){return this.camera.duration}get animates(){return this.camera.animates}seek(e){return this.camera.seek(e)}play(){return this.stop(),new Promise(e=>{let t=this._cameraManager.controls;this._playback={elapsed:0,resolve:e,controlsEnabled:t.enabled},t.enabled=!1,this._timer.reset(),this._changed(),this._onReset?.()})}stop(){let e=this._playback;e&&(this._playback=null,this._cameraManager.controls.enabled=e.controlsEnabled,this._changed(),e.resolve())}get isPlaying(){return!!this._playback}update(){let e=this._playback;if(!e)return;this._timer.update(),e.elapsed+=this._timer.getDelta();let t=r.MathUtils.clamp(e.elapsed,0,this.duration);this.seek(t),t>=this.duration&&this.stop()}serialize(){return{camera:this.camera.serialize()}}restore(e){this.stop(),this.camera.restore(e?.camera)}clear(){this.stop(),this.camera.clear()}dispose(){this.stop(),this._timer.dispose(),this.camera.dispose(),this._cameraManager=this._onReset=null}_changed(e){this.dispatchEvent({type:N.TIMELINE_CHANGED,track:e})}};rn();var lS=class{constructor(e,t={}){this.pathTracer=e,this._onReset=t.onReset||null,this._issues=t.issues??null,this.texture=null,this.entries=[],this._size=256}async loadLibrary(e,{size:t=256}={}){if(!Array.isArray(e)||e.length===0)return[];this._size=t;let n=await Promise.all(e.map(e=>uS(e.url))),i=t,a=t,o=n.length,s=new Uint8Array(i*a*o*4),c=document.createElement(`canvas`);c.width=i,c.height=a;let l=c.getContext(`2d`,{willReadFrequently:!0}),u=performance.now();for(let e=0;e<o;e++){l.clearRect(0,0,i,a),l.drawImage(n[e],0,0,i,a);let t=l.getImageData(0,0,i,a);s.set(t.data,e*i*a*4),performance.now()-u>16&&(await new Promise(e=>setTimeout(e,0)),u=performance.now())}let d=new r.DataArrayTexture(s,i,a,o);d.minFilter=r.LinearFilter,d.magFilter=r.LinearFilter,d.format=r.RGBAFormat,d.type=r.UnsignedByteType,d.generateMipmaps=!1,d.needsUpdate=!0;let f=this.texture;return this.texture=d,this.entries=e.map((e,t)=>({name:e.name,index:t})),this.pathTracer.goboMaps=d,this.pathTracer.shaderBuilder?.updateGoboMaps?.(d),f?.dispose?.(),this.entries}getEntries(){return this.entries.slice()}setLightGobo(e,t,n={}){let{intensity:r=1,inverted:i=!1,scale:a=5}=n,o=this._findGoboLight(e);if(!o)return!1;if(o.userData=o.userData||{},t==null)delete o.userData.gobo;else{let e=this.entries.find(e=>e.name===t);if(!e)return this._issues?.record(Z.ASSET_UNREACHABLE,`no gobo named "${t}" is loaded — the light projects without one`,{name:t,asset:`gobo`}),!1;o.userData.gobo={name:e.name,index:e.index,intensity:dS(r),inverted:!!i,scale:Math.max(1e-4,a)}}return this.pathTracer.updateLights(),this._onReset?.(),!0}setLightGoboInverted(e,t){let n=this._findGoboLight(e);return n?.userData?.gobo?(n.userData.gobo.inverted=!!t,this.pathTracer.updateLights(),this._onReset?.(),!0):!1}setLightGoboScale(e,t){let n=this._findGoboLight(e);return n?.userData?.gobo?(n.userData.gobo.scale=Math.max(1e-4,t),this.pathTracer.updateLights(),this._onReset?.(),!0):!1}getLightGobo(e){return this._findGoboLight(e)?.userData?.gobo||null}setSpotLightGobo(e,t,n=1,r=!1){return this.setLightGobo(e,t,{intensity:n,inverted:r})}setSpotLightGoboInverted(e,t){return this.setLightGoboInverted(e,t)}getSpotLightGobo(e){return this.getLightGobo(e)}dispose(){this.texture?.dispose?.(),this.texture=null,this.entries=[],this.pathTracer=null,this._onReset=null,this._issues=null}_findGoboLight(e){let t=this.pathTracer?.scene?.getObjectByProperty?.(`uuid`,e);return t&&(t.isSpotLight||t.isDirectionalLight)?t:null}_findSpotLight(e){let t=this.pathTracer?.scene?.getObjectByProperty?.(`uuid`,e);return t&&t.isSpotLight?t:null}};async function uS(e){let t=await L_(e);try{return await new Promise((n,r)=>{let i=new Image;i.crossOrigin=`anonymous`,i.onload=()=>n(i),i.onerror=()=>r(Error(`Failed to load gobo image: ${e}`)),i.src=t.url})}finally{t.release()}}function dS(e){return Math.max(0,Math.min(1,e))}function fS(e,t=`ies`){let n=e.search(/TILT\s*=/i);if(n<0)throw Error(`IES (${t}): missing TILT line`);let r=e.indexOf(`
|
|
1003
1003
|
`,n);if(r<0)throw Error(`IES (${t}): truncated TILT line`);let i=e.slice(n,r).match(/TILT\s*=\s*(\w+)/i),a=i?i[1].toUpperCase():`NONE`,o=e.slice(r);if(a===`INCLUDE`){let e=_S(o),t=2+2*Number(e[1]);o=vS(o,t)}let s=_S(o),c=0,l=()=>Number(s[c++]),u=l(),d=l(),f=l(),p=l(),m=l(),h=l();l(),l(),l(),l();let g=l();if(l(),l(),!Number.isFinite(p)||p<=0)throw Error(`IES (${t}): invalid vertical angle count ${p}`);if(!Number.isFinite(m)||m<=0)throw Error(`IES (${t}): invalid horizontal angle count ${m}`);let _=Array(p);for(let e=0;e<p;e++)_[e]=l();let v=Array(m);for(let e=0;e<m;e++)v[e]=l();let y=Array(p);for(let e=0;e<p;e++)y[e]=new Float32Array(m);let b=f*g,x=0;for(let e=0;e<m;e++)for(let t=0;t<p;t++){let n=l()*b;y[t][e]=n,n>x&&(x=n)}return{verticalAngles:_,horizontalAngles:v,candela:y,maxCandela:x,lumens:d*u,photometricType:h,name:t}}function pS(e,t,n){if(t===0&&n===90){let t=e%180;return t>90?180-t:t}return t===0&&n===180?e>180?360-e:e:t===90&&n===270?e>=90&&e<=270?e:(540-e)%360:e}function mS(e,t,n){let r=new Uint8Array(t*n),{verticalAngles:i,horizontalAngles:a,candela:o,maxCandela:s,photometricType:c}=e;if(s<=0)return r;let l=c===void 0||c===1,u=i[0],d=i[i.length-1],f=a[0],p=a[a.length-1],m=a.length===1||p===f,h=(e,t,n,r)=>{if(m)return bS(o[e][0],o[t][0],n);if(r<f||r>p)return 0;let i=yS(a,r),s=Math.min(i+1,a.length-1),c=a[s]-a[i],l=c>0?(r-a[i])/c:0;return bS(bS(o[e][i],o[e][s],l),bS(o[t][i],o[t][s],l),n)};for(let e=0;e<n;e++){let a=(e+.5)/n,o=l?a*180:u+a*(d-u);if(o<u||o>d)continue;let c=yS(i,o),m=Math.min(c+1,i.length-1),g=i[m]-i[c],_=g>0?(o-i[c])/g:0;for(let n=0;n<t;n++){let i=(n+.5)/t,a=l?pS(i*360,f,p):f+i*(p-f),o=Math.min(1,Math.max(0,h(c,m,_,a)/s));r[e*t+n]=Math.round(o*255)}}return r}function hS(e,t=.1){let{verticalAngles:n,horizontalAngles:r,candela:i,maxCandela:a}=e,o=Math.PI/4;if(a<=0||!n?.length)return o;let s=a*t,c=r.length,l=n[n.length-1],u=!1;for(let e=0;e<n.length;e++){let t=0;for(let n=0;n<c;n++)t+=i[e][n];if(t/=c,t>=s&&(u=!0),u&&t<s){l=n[e];break}}let d=l*Math.PI/180;return Math.min(Math.max(d,5*Math.PI/180),89*Math.PI/180)}function gS(e,t,n=.7){let{verticalAngles:r,horizontalAngles:i,candela:a,maxCandela:o}=e;if(o<=0||!r?.length||t<=0)return 0;let s=o*n,c=i.length,l=0;for(let e=0;e<r.length;e++){let t=0;for(let n=0;n<c;n++)t+=a[e][n];if(t/=c,t>=s)l=r[e];else break}let u=t*180/Math.PI,d=u>0?1-l/u:0;return Math.min(Math.max(d,0),1)}function _S(e){return e.split(/\s+/).filter(e=>e.length>0)}function vS(e,t){let n=/\S+/g,r=0;for(;n.exec(e)!==null;)if(r++,r===t)return e.slice(n.lastIndex);return``}function yS(e,t){if(t<=e[0])return 0;if(t>=e[e.length-1])return e.length-1;let n=0,r=e.length-1;for(;r-n>1;){let i=n+r>>1;e[i]<=t?n=i:r=i}return n}function bS(e,t,n){return e+(t-e)*n}rn();var xS=class{constructor(e,t={}){this.pathTracer=e,this._onReset=t.onReset||null,this._issues=t.issues??null,this.texture=null,this.entries=[],this._gridWidth=128,this._gridHeight=128}async loadLibrary(e,{gridWidth:t=128,gridHeight:n=128}={}){if(!Array.isArray(e)||e.length===0)return[];this._gridWidth=t,this._gridHeight=n;let i=(await Promise.all(e.map(async e=>{try{let{file:r,release:i}=await I_().fetch(e.url),a=fS(await r.text().finally(i),e.name);return{it:e,profile:a,grid:mS(a,t,n)}}catch(t){return this._issues?.warn(Z.ASSET_UNREACHABLE,`IES profile "${e.name}" could not be loaded: ${t.message}`,{url:e.url,asset:`ies`,cause:t.message}),null}}))).filter(e=>e!==null);if(i.length===0)return[];let a=i.length,o=t*n,s=new Uint8Array(o*4*a),c=[];for(let e=0;e<a;e++){let t=i[e].grid,n=e*o*4;for(let e=0;e<o;e++){let r=t[e];s[n+e*4+0]=r,s[n+e*4+1]=r,s[n+e*4+2]=r,s[n+e*4+3]=255}let r=i[e].profile,a=hS(r);c.push({name:i[e].it.name,index:e,maxCandela:r.maxCandela,photometricType:r.photometricType,suggestedAngle:a,suggestedPenumbra:gS(r,a),lumens:r.lumens})}let l=new r.DataArrayTexture(s,t,n,a);l.format=r.RGBAFormat,l.type=r.UnsignedByteType,l.minFilter=r.LinearFilter,l.magFilter=r.LinearFilter,l.generateMipmaps=!1,l.needsUpdate=!0;let u=this.texture;return this.texture=l,this.entries=c,this.pathTracer.iesProfiles=l,this.pathTracer.shaderBuilder?.updateIESProfiles?.(l),u?.dispose?.(),this.entries.map(({name:e,index:t})=>({name:e,index:t}))}getEntries(){return this.entries.slice()}setSpotLightProfile(e,t,n=1,{applyAutoCone:r=!0}={}){let i=this._findSpotLight(e),a={applied:!1,suggestedAngle:null,suggestedPenumbra:null,suggestedDecay:null,fixtureLumens:null};if(!i)return a;i.userData=i.userData||{};let o=null,s=null,c=null,l=null;if(t==null)delete i.userData.ies;else{let e=this.entries.find(e=>e.name===t);if(!e)return this._issues?.record(Z.ASSET_UNREACHABLE,`no IES profile named "${t}" is loaded — the light keeps its plain distribution`,{name:t,asset:`ies`}),a;l=Number.isFinite(e.lumens)?e.lumens:null,i.userData.ies={name:e.name,index:e.index,intensity:SS(n),fixtureLumens:l},r&&(Number.isFinite(e.suggestedAngle)&&(i.angle=e.suggestedAngle,o=e.suggestedAngle),Number.isFinite(e.suggestedPenumbra)&&(i.penumbra=e.suggestedPenumbra,s=e.suggestedPenumbra),i.decay=2,c=2)}return this.pathTracer.updateLights(),this._onReset?.(),{applied:!0,suggestedAngle:o,suggestedPenumbra:s,suggestedDecay:c,fixtureLumens:l}}getSpotLightProfile(e){return this._findSpotLight(e)?.userData?.ies||null}dispose(){this.texture?.dispose?.(),this.texture=null,this.entries=[],this.pathTracer=null,this._onReset=null,this._issues=null}_findSpotLight(e){let t=this.pathTracer?.scene?.getObjectByProperty?.(`uuid`,e);return t&&t.isSpotLight?t:null}};function SS(e){return Math.max(0,Math.min(1,e))}Oe(),ai();var CS=_e(`oidn`),wS=16,TS=null;async function ES(){return TS||=(await import(`oidn-web/dist/oidn.js`)).initUNetFromBuffer,TS}var DS={QUALITY_MODELS:{fast:{model:`rt_hdr_alb_nrm_small`,cleanAux:!1},"fast-clean":{model:`rt_hdr_calb_cnrm_small`,cleanAux:!0},balance:{model:`rt_hdr_calb_cnrm`,cleanAux:!0},high:{model:`rt_hdr_calb_cnrm_large`,cleanAux:!0}},DEFAULT_OPTIONS:{enableOIDN:!0,oidnQuality:`fast`,tileSize:1024}},OS=.18,kS=256,AS=256,jS=`
|
|
1004
1004
|
const WG: u32 = ${kS}u;
|
|
1005
1005
|
const GROUPS: u32 = ${AS}u;
|
|
@@ -1363,7 +1363,7 @@ fn main( @builtin(global_invocation_id) gid: vec3<u32> ) {
|
|
|
1363
1363
|
textureStore( outNormal, p, vec4<f32>( n, an.w ) );
|
|
1364
1364
|
|
|
1365
1365
|
}
|
|
1366
|
-
`,$S=e=>({binding:e,visibility:GPUShaderStage.COMPUTE,texture:{sampleType:`unfilterable-float`}}),eC=e=>({binding:e,visibility:GPUShaderStage.COMPUTE,storageTexture:{access:`write-only`,format:`rgba32float`}}),tC=(e,t)=>({binding:e,visibility:GPUShaderStage.COMPUTE,buffer:{type:t}}),nC=class{constructor(e){this.device=e,this.settings={...VS,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(US),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=tC(0,`uniform`);this._pipelines={select:t(`oidn-history-select`,XS,[n,$S(1),$S(2),tC(3,`storage`),tC(4,`storage`),{binding:5,visibility:GPUShaderStage.COMPUTE,texture:{sampleType:`uint`}},tC(6,`read-only-storage`),tC(7,`read-only-storage`)]),blend:t(`oidn-history-blend`,ZS,[n,...[1,2,3,4,5,6,7].map($S),tC(8,`read-only-storage`),tC(9,`read-only-storage`),eC(10),eC(11),eC(12)]),merge:t(`oidn-history-merge`,QS,[n,...[1,2,3,4,5,6].map($S),eC(7),eC(8),eC(9)])},this._paramsBuffer=e.createBuffer({label:`oidn-history-params`,size:US,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this._growMoved(WS)}_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/HS),Math.ceil(this.height/HS)),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?GS:0)|(i.splitCopies?KS:0)|(e.orthographic?qS: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}},rC='const e=Object.freeze({ADAPTER_SOFTWARE:`adapter.software`,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`,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})}};',iC=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,rC],{type:`text/javascript;charset=utf-8`});function aC(e){let t;try{if(t=iC&&(self.URL||self.webkitURL).createObjectURL(iC),!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(rC),{type:`module`,name:e?.name})}}gv(),ai();var oC={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 sC(){let{upscalerModelBaseUrl:e}=ni(),t={};for(let n in oC){t[n]={};for(let r in oC[n])t[n][r]=e+oC[n][r]}return t}var cC={get QUALITY_PRESETS(){return sC()},TILE_SIZE:512,TILE_OVERLAP:16,SESSION_OPTIONS:{executionProviders:[{name:`webgpu`,preferredLayout:`NCHW`}],graphOptimizationLevel:`all`}},lC=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.enabled=!1,this.hdr=!1,this.scaleFactor=n.scaleFactor||2,this.quality=n.quality||`fast`,this.refreshInput=n.refreshInput||null,this.tileSize=n.tileSize||cC.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 Set,this._upscaledAlpha=null,this._upscaledAlphaWidth=0,this._backupCanvas=null,this._baseWidth=e.width,this._baseHeight=e.height,this._toneMapper=null}async _ensureSession(){let e=cC.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 aC,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}=ni();this._worker.addEventListener(`message`,r),this._worker.postMessage({type:`load`,url:t,sessionOptions:cC.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(){if(!this.enabled||this.state.isUpscaling||this.state.isLoading)return!1;this.dispatchEvent({type:`start`});let e=performance.now(),t=await this.execute();if(t){this.renderer?.resetState?.();let t=performance.now()-e;console.log(`AI Upscaler: ${this.scaleFactor}x upscale completed in ${t.toFixed(1)}ms`)}return t}_revealOutput(){this.output.style.display=`block`,this.input.style.opacity=`0`}async execute(){if(!this.enabled)return!1;this.state.abortController=new AbortController,this.state.isUpscaling=!0,this.hdr&&this.getGPUTextures?this._capturedSource=await this._captureSourceHDR():this._capturedSource=this._captureSource(),this._createBackup(this._capturedSource);let e=this._capturedSource.width*this.scaleFactor,t=this._capturedSource.height*this.scaleFactor;this.output.width=e,this.output.height=t;let n=this.output.getContext(`2d`,{willReadFrequently:!0,alpha:!0});n.imageSmoothingEnabled=!0,n.imageSmoothingQuality=`high`,n.drawImage(this._backupCanvas,0,0,e,t),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=cC.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 hv(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(),{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.add(o),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(!cC.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(){if(this._worker)for(let e of this._pendingWorkerHandlers)this._worker.removeEventListener(`message`,e);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`)}},uC=_({NeuralSuperRes:()=>TC,SR_MAX_INPUT:()=>xC,SR_SCALE:()=>2,presentRGBA8:()=>vC,readDenoisedHalf:()=>mC,releaseDenoisedReader:()=>pC,renderUpscaled:()=>gC});function dC(){if(SC)return SC;let{neuralRuntimeUrl:e,neuralAssetBaseUrl:t}=ni();return t?(globalThis.__NEURAL_ASSET_BASE__=t,SC=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)}),SC):Promise.reject(Error(`No neural model location: set neuralAssetBaseUrl with configureAssets()`))}function fC(e,t,n){if(wC&&(wC.device!==e||wC.width!==t||wC.height!==n)&&pC(),wC)return wC;let r=t*n*8;return wC={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:CC}),entryPoint:`main`}})},wC}function pC(){wC?.storage.destroy(),wC?.map.destroy(),wC=null}async function mC(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=fC(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 hC(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 gC(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 TC.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=hC(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 mC(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&&_C(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 _C(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 vC(e,t,n,r){return _C(e,t,n,r)}var yC,bC,xC,SC,CC,wC,TC,EC=g((()=>{F(),Oe(),gv(),ai(),yC=2,bC=_e(`neural`),xC=2048,SC=null,CC=`
|
|
1366
|
+
`,$S=e=>({binding:e,visibility:GPUShaderStage.COMPUTE,texture:{sampleType:`unfilterable-float`}}),eC=e=>({binding:e,visibility:GPUShaderStage.COMPUTE,storageTexture:{access:`write-only`,format:`rgba32float`}}),tC=(e,t)=>({binding:e,visibility:GPUShaderStage.COMPUTE,buffer:{type:t}}),nC=class{constructor(e){this.device=e,this.settings={...VS,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(US),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=tC(0,`uniform`);this._pipelines={select:t(`oidn-history-select`,XS,[n,$S(1),$S(2),tC(3,`storage`),tC(4,`storage`),{binding:5,visibility:GPUShaderStage.COMPUTE,texture:{sampleType:`uint`}},tC(6,`read-only-storage`),tC(7,`read-only-storage`)]),blend:t(`oidn-history-blend`,ZS,[n,...[1,2,3,4,5,6,7].map($S),tC(8,`read-only-storage`),tC(9,`read-only-storage`),eC(10),eC(11),eC(12)]),merge:t(`oidn-history-merge`,QS,[n,...[1,2,3,4,5,6].map($S),eC(7),eC(8),eC(9)])},this._paramsBuffer=e.createBuffer({label:`oidn-history-params`,size:US,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this._growMoved(WS)}_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/HS),Math.ceil(this.height/HS)),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?GS:0)|(i.splitCopies?KS:0)|(e.orthographic?qS: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}},rC='const e=Object.freeze({ADAPTER_SOFTWARE:`adapter.software`,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`,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})}};',iC=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,rC],{type:`text/javascript;charset=utf-8`});function aC(e){let t;try{if(t=iC&&(self.URL||self.webkitURL).createObjectURL(iC),!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(rC),{type:`module`,name:e?.name})}}gv(),ai();var oC={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 sC(){let{upscalerModelBaseUrl:e}=ni(),t={};for(let n in oC){t[n]={};for(let r in oC[n])t[n][r]=e+oC[n][r]}return t}var cC={get QUALITY_PRESETS(){return sC()},TILE_SIZE:512,TILE_OVERLAP:16,SESSION_OPTIONS:{executionProviders:[{name:`webgpu`,preferredLayout:`NCHW`}],graphOptimizationLevel:`all`}},lC=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.enabled=!1,this.hdr=!1,this.scaleFactor=n.scaleFactor||2,this.quality=n.quality||`fast`,this.refreshInput=n.refreshInput||null,this.tileSize=n.tileSize||cC.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=cC.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 aC,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}=ni();this._worker.addEventListener(`message`,r),this._worker.postMessage({type:`load`,url:t,sessionOptions:cC.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=cC.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 hv(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(),{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(!cC.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`)}},uC=_({NeuralSuperRes:()=>TC,SR_MAX_INPUT:()=>xC,SR_SCALE:()=>2,presentRGBA8:()=>vC,readDenoisedHalf:()=>mC,releaseDenoisedReader:()=>pC,renderUpscaled:()=>gC});function dC(){if(SC)return SC;let{neuralRuntimeUrl:e,neuralAssetBaseUrl:t}=ni();return t?(globalThis.__NEURAL_ASSET_BASE__=t,SC=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)}),SC):Promise.reject(Error(`No neural model location: set neuralAssetBaseUrl with configureAssets()`))}function fC(e,t,n){if(wC&&(wC.device!==e||wC.width!==t||wC.height!==n)&&pC(),wC)return wC;let r=t*n*8;return wC={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:CC}),entryPoint:`main`}})},wC}function pC(){wC?.storage.destroy(),wC?.map.destroy(),wC=null}async function mC(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=fC(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 hC(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 gC(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 TC.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=hC(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 mC(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&&_C(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 _C(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 vC(e,t,n,r){return _C(e,t,n,r)}var yC,bC,xC,SC,CC,wC,TC,EC=g((()=>{F(),Oe(),gv(),ai(),yC=2,bC=_e(`neural`),xC=2048,SC=null,CC=`
|
|
1367
1367
|
@group(0) @binding(0) var src: texture_2d<f32>;
|
|
1368
1368
|
@group(0) @binding(1) var<storage, read_write> dst: array<u32>;
|
|
1369
1369
|
|
|
@@ -1403,7 +1403,7 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
|
|
|
1403
1403
|
dst[a] = pack2x16float(c.rg);
|
|
1404
1404
|
dst[a + 1u] = pack2x16float(vec2<f32>(c.b, 1.0));
|
|
1405
1405
|
}
|
|
1406
|
-
`,RC=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 ${(NC/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 kC()).create(o,t,n,a,OC(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:IC}),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:LC}),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 hv(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){MC.warn(`retouch teardown:`,e)}}}},zC=20}));F(),rn(),Oe(),at();var VC=_e(`neural`),HC=120,UC=2,WC=1,GC=0,KC=300,qC=5,JC=3,YC=3,XC=16,ZC=e=>Math.max(0,1-e/XC),QC=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._finalQuality=Py.oidnQuality,this.finalDenoise=Py.enableOIDN,this.continuousDenoise=Py.continuousDenoise,this.continuousDenoiseInterval=Py.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=Py.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._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(Z.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 BS(this.renderer,{enableOIDN:Py.enableOIDN,oidnQuality:Py.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=>{this.denoiser?.hasOutput&&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(Z.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)}setupUpscaler(){if(!this.upscalerCanvas)return;let e=this._stages.pathTracer;this.upscaler=new lC(this.upscalerCanvas,this.renderer,{scaleFactor:Py.upscalerScale||2,quality:Py.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}),this.upscaler.enabled=Py.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.asvgf?.enabled?`asvgf`:this._stages.nrd?.enabled?`nrd`:this._stages.edgeFilter?.enabled?`edgeaware`:`none`}setDenoiserStrategy(e,t){let n=this._stages;switch(n.asvgf&&(n.asvgf.enabled=!1),n.nrd&&(n.nrd.enabled=!1),n.variance&&(n.variance.enabled=!1),n.bilateralFilter&&(n.bilateralFilter.enabled=!1),n.edgeFilter&&n.edgeFilter.setFilteringEnabled(!1),this._clearDenoiserTextures(),this.setContinuousDenoise(e===`oidn`),e){case`asvgf`:n.asvgf.enabled=!0,n.variance&&(n.variance.enabled=!0),n.bilateralFilter&&(n.bilateralFilter.enabled=!0),n.asvgf.setTemporalEnabled?.(!0),this._applyASVGFPreset(t||`medium`);break;case`nrd`:n.nrd&&(n.nrd.enabled=!0,n.nrd.resetHistory?.(),this._applyNRDPreset(t||`medium`));break;case`edgeaware`:n.variance&&(n.variance.enabled=!0),n.edgeFilter&&n.edgeFilter.setFilteringEnabled(!0);break}this._syncGBufferStages()}setASVGFEnabled(e,t){let n=this._stages;n.asvgf&&(n.asvgf.enabled=e),n.variance&&(n.variance.enabled=e),n.bilateralFilter&&(n.bilateralFilter.enabled=e),e&&(n.nrd&&(n.nrd.enabled=!1),n.asvgf?.setTemporalEnabled?.(!0),this._applyASVGFPreset(t||`medium`)),n.edgeFilter&&n.edgeFilter.setFilteringEnabled(!e),this._syncGBufferStages()}applyASVGFPreset(e){this._applyASVGFPreset(e)}setAutoExposureEnabled(e,t){this._stages.autoExposure?.setEnabled(e,t)}get requiresMotionVectors(){return!!(this._stages.asvgf?.enabled||this._stages.nrd?.enabled)}_syncGBufferStages(){let e=this._stages,t=e.normalDepth,n=e.motionVector,r=this.requiresMotionVectors,i=r||this.historyWanted||!!(e.edgeFilter?.enabled||e.bilateralFilter?.enabled);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.isFirstFrame=!0,n.frameCount=0),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.asvgf,e.nrd,e.variance,e.bilateralFilter,e.edgeFilter,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>KC*JC&&(this._movingHopeless=!0,this._syncGBufferStages());let n=!this._movingHopeless&&(t<2||e<=KC);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<YC||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?GC:this._lastCadenceSamples===0?WC:UC,a=Math.max(this.continuousDenoiseInterval,t.lastDenoiseMs*i);if(r-this._lastCadenceAt<a)return!1;this._lastCadenceAt=r,this._lastCadenceSamples=e,t.lastDenoiseMs>HC&&(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>qC&&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())}setContinuousDenoise(e){this.continuousDenoise=!!e,this._syncOIDNInUse(),this._lastCadenceAt=-1/0,this._resetCadence()}_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}get historyActive(){let e=this._stages.pathTracer;return this.historyWanted&&!this._cadenceSuspended&&!!this._stages.normalDepth?.enabled&&e?.uniforms?.get(`cameraProjection`)?.value!==tt.equirectangular&&!(e?.visMode?.value>0)}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:ZC(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>=XC)return null;let n=this._historyInputs();return n?t.merge(n,e.frameCount,this._historyCameraNow(),{historyScale:ZC(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===tt.orthographic,t}_ensureHistory(){return this._history??=new nC(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){this.neuralRendering=!!e,t&&(this.neuralRenderingSettings={...this.neuralRenderingSettings,...t}),this.neuralRendering||(this._releaseNeuralRetouch(),this._restoreRenderDisplay())}_releaseNeuralRetouch(){this._retouch?.dispose(),this._retouch=null}async _runNeuralPost(e){let t=this.upscaler?.enabled&&this.upscalerBackend===`neural`,n=this.neuralRendering;if(!(!t&&!n)&&!this._neuralPostBusy){if(!this.upscalerCanvas){this._recordNoOverlayCanvas(`neural`);return}if(!this.pipeline?.context?.getTexture(`oidn:output`)){VC.warn(`neural pass skipped: no denoised picture — it needs OIDN`);return}this._neuralPostBusy=!0,this.dispatchEvent({type:N.UPSCALING_START});try{let r=await Promise.resolve().then(()=>(EC(),uC));this._superResModule=r;let i=n?await Promise.resolve().then(()=>(BC(),DC)):null,a=this.denoiser?._outTexSize,o=(a?.width??0)*(a?.height??0),s=n&&o<=i.RETOUCH_MAX_PIXELS;if(n&&!s&&(VC.warn(`Neural rendering skipped: the render is ${(o/1e6).toFixed(1)} MP, above the ${(i.RETOUCH_MAX_PIXELS/1e6).toFixed(1)} MP the pass survives.`+(t?` The upscale still ran.`:``)),this._releaseNeuralRetouch()),!t&&!s)return;let c={exposure:this._getEffectiveExposure(),toneMapping:this._getToneMapping(),saturation:this._getSaturation?.()??1,gain:this._getDisplayGain?.()??null},l=await r.readDenoisedHalf(this.denoiser);t&&(this._neuralUpscaler&&(this._neuralUpscaler.inputWidth!==l.width||this._neuralUpscaler.inputHeight!==l.height)&&this._releaseNeuralUpscaler(),this._neuralUpscaler||=await r.NeuralSuperRes.create({width:l.width,height:l.height}));let u=l;if(s){let e=await i.enhanceFrame({source:u,settings:this.neuralRenderingSettings,instance:this._retouch,exposure:c.exposure,tone:t?null:c});this._retouch=e.instance,u=e}if(t&&(u=await this._neuralUpscaler.upscaleToRGBA8(u,c)),!e()){this.dropDisplay();return}if(r.presentRGBA8(this.upscalerCanvas,u.rgba8,u.width,u.height),!e()){this.dropDisplay();return}this.mainCanvas&&(this.mainCanvas.style.opacity=`0`),this.dispatchEvent({type:N.RESOLUTION_CHANGED,width:u.width,height:u.height})}catch(e){VC.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}onRenderComplete({isStillComplete:e}){this._cleanupCompletionListener();let t=this.finalDenoise?`final`:this.continuousDenoise?`refresh`:null,n=()=>{if(this.denoiser?.removeEventListener(`end`,n),this._pendingStartUpscaler=null,e()){if(t&&this._onDisplayRefresh?.(),this.neuralRendering||this.upscaler?.enabled&&this.upscalerBackend===`neural`){this._runNeuralPost(e);return}this.upscaler?.enabled&&this.upscaler.start()}};if(!t){n();return}let r=()=>{e()&&(this._pendingStartUpscaler=n,this.denoiser.addEventListener(`end`,n),t===`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),r()};this._pendingCloseDenoise=e,this.denoiser.addEventListener(`end`,e)}else r()}abort(e,{keepDisplay:t=!1}={}){this._cleanupCompletionListener(),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(){this._cleanupCompletionListener(),this._releaseNeuralUpscaler(),this._releaseNeuralRetouch(),this._unpublishOutput(),this._releaseHistory(),this.denoiser&&=(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.denoiser.dispose(),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._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}setASVGFParams(e){this._stages.asvgf?.updateParameters(e)}toggleASVGFHeatmap(e){this._stages.asvgf?.setHeatmapEnabled?.(e)}configureASVGFForMode(e){this._stages.asvgf&&(this._stages.asvgf.enabled=e.enabled,this._stages.variance&&(this._stages.variance.enabled=e.enabled),this._stages.bilateralFilter&&(this._stages.bilateralFilter.enabled=e.enabled),e.enabled&&this._stages.asvgf.updateParameters(e),this._syncGBufferStages())}setEdgeAwareParams(e){this._stages.edgeFilter?.updateUniforms(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){this.upscaler?this.upscaler.enabled=e:e&&this._recordNoOverlayCanvas(`upscaler`),e||this._restoreRenderDisplay()}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&&[`asvgf:output`,`asvgf:demodulated`,`asvgf:gradient`,`variance:output`,`bilateralFiltering:output`,`edgeFiltering:output`,`nrd:output`,`oidn:output`].forEach(t=>e.removeTexture(t))}_applyNRDPreset(e){let t=My[e];if(!t)return;let n={};for(let e of jy)n[e]=Ay[e];this._stages.nrd?.updateParameters({...n,...t})}_applyASVGFPreset(e){let t=Dy[e];t&&(this._stages.asvgf?.updateParameters(t),this._stages.bilateralFilter?.updateParameters(t),this._stages.variance&&t.varianceBoost!==void 0&&(this._stages.variance.varianceBoost.value=t.varianceBoost))}},$C=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 tw(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 nw(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}}ue();var rw=4096,iw=class{constructor(){this.canvas=tw(!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=nw(this._sizeSource,rw);!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(){te(this.renderer),this.renderer=null,this.canvas.parentElement?.removeChild(this.canvas)}};Oe(),F();var aw=_e(`overlay`),ow=(e,t)=>e.visible&&e.layer===t&&e.render,sw=class{constructor(e){this.camera=e,this._helpers=new Map,this._hudCanvas=tw(),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 iw().init({device:e,sizeSource:t})}catch(e){aw.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 $C;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)&&(aw.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())ow(t,`scene`)&&t.render(e,this.camera)}_hasVisibleSceneOverlay(){if(this._helperScene?.isDrawing)return!0;for(let e of this._helpers.values())if(ow(e,`scene`))return!0;return!1}refreshHUD(){let e=this._hudCanvas,t=this._hudCtx,n=!1;for(let e of this._helpers.values())if(ow(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?nw(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())ow(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 cw(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 lw=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:cw(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?cw(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 uw=new r.Vector3(0,0,-1),dw=e=>{for(;e.parent;)e=e.parent;return e.isScene?e:null},fw=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)dw(e)||this._moved.delete(e)}get movedObjects(){return[...this._moved].filter(e=>dw(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(uw,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}},pw=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}};gc();var mw=1,hw=e=>typeof e==`string`&&/^https?:\/\//.test(e);function gw(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 _w(e,t){let n=e;for(let e of t)if(n=n?.children[e],!n)return null;return n}function vw(e){return{key:e.assetLoader?.sceneSourceKey??null,name:e.sceneModel?.name??null,meshes:e.sceneMeshes.length,materials:e.stages.pathTracer?.materialData.materialCount??0}}function yw(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 bw(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 xw(e){let t=e.meshScene,n=yw(e),r=[];return t.traverse(e=>{e!==t&&e.visible===!1&&r.push(gw(e,t))}),{v:1,engine:hc,savedAt:Date.now(),scene:vw(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:bw(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:gw(e,t),name:e.name,position:e.position.toArray(),quaternion:e.quaternion.toArray(),scale:e.scale.toArray()})).filter(e=>e.path)}}function Sw(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 Cw(e,t,n,r){if(!t)return;let i=e.environmentManager;if(t.hdri&&t.hdri!==i.hdriSource){let i=hw(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 ww(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 Tw(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=vw(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 Cw(e,t.environment,n,i),await ww(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=yw(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=nr(i);Sw(t,n,a),e.setMaterialProperty(r.index,n,a)}}let r=e.meshScene,a=new Set((t.hidden??[]).map(e=>_w(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=_w(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 Ew=[{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)}}],Dw=_({LampPick:()=>Ow,areaLightDirectPdfW:()=>Lw,directionalConeSolidAngle:()=>Iw,lampCount:()=>kw,lampPickPdf:()=>Pw,lampTypeAt:()=>Aw,pickLamp:()=>Nw,spotConeSolidAngle:()=>Fw});O(),cu();var Ow=x({kind:`int`,index:`int`,pdf:`float`,total:`float`}),kw=e=>e.numDirectional.add(e.numArea).add(e.numPoint).add(e.numSpot),Aw=(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)))),jw=(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)))),Mw=(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=>rh(mm.wrap(bm(e.directional,t)),r,i,(0,n.int)(0))),o(1,e.numArea,a=>{let o=hm.wrap(xm(e.area,a));return(0,n.select)(o.intensity.greaterThan(0),ih(o,t,r,i),(0,n.float)(0))}),o(2,e.numPoint,n=>ah(gm.wrap(Sm(e.point,n)),t,r,i)),o(3,e.numSpot,n=>oh(_m.wrap(Cm(e.spot,n)),t,r,i))};function Nw(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();Mw(e,t,r,i,(t,r,i)=>{u.addAssign(i),(0,n.If)(i.greaterThan(0).and(o((0,n.int)(G+64).add(jw(e,t)).add(r)).mul(u).lessThan(i)),()=>{s.assign(t),c.assign(r),l.assign(i)})});let d=kw(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(Aw(e,t)),c.assign(t.sub(jw(e,s))),f.assign((0,n.float)(1).div((0,n.max)((0,n.float)(d),1)))}),Ow({kind:s,index:c,pdf:f,total:u})}function Pw(e,t,r,i,a,o){let s=(0,n.float)(0).toVar(),c=(0,n.float)(0).toVar();return Mw(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)(kw(e)),1)))}var Fw=e=>(0,n.float)(2*Sl).mul((0,n.max)((0,n.float)(1).sub((0,n.cos)(e.angle)),1e-10)),Iw=e=>(0,n.float)(2*Sl).mul((0,n.max)((0,n.float)(1).sub((0,n.cos)(e.angle.mul(.5))),1e-10)),Lw=(e,t,r,i)=>{let a=Mm(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)))},Rw=_({DIM_CONNECT_PATH:()=>16,DIM_CONNECT_VERTEX:()=>17,DIM_EMIT:()=>zw,LIGHT_PIXEL_ROW_OFFSET:()=>Bw,PASS_TAG_BIT:()=>Uw,SOURCE:()=>cT,SPLAT_MAX:()=>Hw,SPLAT_SCALE:()=>Vw,STRATEGY:()=>rT,STRATEGY_ALONE:()=>8,emitterAreaPdf:()=>oT,emitterSideProbability:()=>aT,facingSide:()=>mT,lampSource:()=>uT,lightEndCosine:()=>hT,lightPathPixel:()=>Kw,mergeEta:()=>$w,mergeRadiusAt:()=>Qw,mergeVmAt:()=>eT,mis:()=>qw,misMergePartial:()=>tT,misOnHit:()=>Jw,misOnScatter:()=>Xw,misOnSpecular:()=>Yw,misPartial:()=>Zw,misWeight:()=>nT,resolveSurfaceMaterial:()=>pT,sourceLampIndex:()=>fT,sourceLampType:()=>dT,sourcePick:()=>lT,strategyWeight:()=>iT,sunEmissionPdf:()=>sT});cu(),_l();var zw=G+2048,Bw=65536,Vw=16384,Hw=4096,Uw=2147483648,Ww=1e30,Gw=e=>(0,n.select)(e.equal(e),e,(0,n.float)(0)).clamp(0,Ww),Kw=(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)(Bw))).add(.5))},qw=e=>e.mul(e),Jw=(e,t,r)=>{let i=(0,n.max)(r,1e-6);e.dVCM.assign(Gw(e.dVCM.mul(qw(t.mul(t).div(i))))),e.dVC.assign(Gw(e.dVC.div(qw(i))))},Yw=(e,t)=>{e.dVC.assign(Gw(e.dVC.mul(qw(t)))),e.dVCM.assign(0)},Xw=(e,t,r,i)=>{let a=(0,n.max)(r,1e-12),o=e.dVC.mul(qw(i)).add(e.dVCM);e.dVC.assign(Gw(qw(t.div(a)).mul(Gw(e.vm?o.add(e.vm):o)))),e.dVCM.assign(Gw(qw((0,n.float)(1).div(a))))},Zw=(e,t,n)=>{let r=t.dVCM.add(t.dVC.mul(qw(n)));return Gw(Gw(qw(e)).mul(Gw(t.vm?r.add(t.vm):r)))},Qw=(e,t)=>(0,n.max)(e.mergeConst.add(e.mergeSlope.mul((0,n.length)(t.sub(e.cameraPosition)))),e.mergeMin),$w=(e,t)=>t.mul(t).mul(Math.PI).mul((0,n.float)(e.lightPaths)),eT=(e,t)=>{let n=$w(e,Qw(e,t)).mul(e.mergeTrust);return n.mul(n)},tT=(e,t,n)=>Gw(Gw(e.dVCM.add(e.dVC.mul(qw(t)))).mul(n)),nT=(e,t)=>(0,n.float)(1).div((0,n.float)(1).add(Gw(e)).add(Gw(t))),rT={ALL:0,HIT:1,NEE:2,CONNECT:3,LIGHT_TRACE:4,MERGE:5},iT=(e,t,r,i=(0,n.float)(1))=>(0,n.select)(e.equal((0,n.uint)(rT.ALL)).or(e.equal((0,n.uint)(t))),r,(0,n.select)(e.equal((0,n.uint)(t+8)),i,(0,n.float)(0))),aT=(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)))),oT=(e,t,r=1)=>(0,n.max)((0,n.dot)(e,kl),0).div((0,n.max)(t,1e-10)).mul(r),sT=(e,t,r)=>e.sunPick.mul(r).div((0,n.max)(t.y,1e-30)),cT={SUN:0,EMITTERS:1,ENVIRONMENT:2,LAMPS:3},lT=(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)))},uT=(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),dT=(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)))),fT=(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 pT(e,t,r,i){let a=nl.wrap($l((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=pl.wrap(yp(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(El,1)),a.sheenRoughness.assign(a.sheenRoughness.clamp(.05,1));let c=op({uv:t,transform:a.albedoTransform}).toVar();(0,n.If)(a.anisotropyMapIndex.greaterThanEqual((0,n.int)(0)),()=>{let e=gp(a,c).toVar();a.anisotropy.assign(e.x),a.anisotropyRotation.assign(e.y)});let l=rl.wrap(_p(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(El).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 mT=(e,t,r)=>(0,n.select)(r.diffuseTransmission.greaterThan(0).and((0,n.dot)(e,t).lessThan(0)),e.negate(),e),hT=(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)),gT=4096,_T=gT+1,vT=Math.ceil(_T*4/256)*64,yT=.2,bT=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()}},xT=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))},ST=(e,t,r)=>{let{u:i,v:a}=bT(t),o=r.sub(e.sceneCenter);return(0,n.vec2)((0,n.dot)(o,i),(0,n.dot)(o,a)).div(e.sceneRadius)},CT=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))},wT=(e,t,r)=>e.guide.greaterThan((0,n.uint)(0)).and(t.load((0,n.ivec2)((0,n.int)(gT),r)).x.greaterThan(0)),TT=(e,t,r,i)=>{let a=ST(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=xT(r).toVar(),l=CT(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(gT/4).div((0,n.max)(o,1e-30));return(0,n.select)(wT(e,t,c),(0,n.mix)(d,s,yT),s)},ET=(e,t,r,i,a)=>{let{u:o,v:s}=bT(r),c=(0,n.vec2)(0).toVar(),l=xT(r).toVar();return(0,n.If)(wT(e,t,l).and(i.lessThan(1-yT)),()=>{let e=i.div(1-yT).toVar(),r=(0,n.int)(0).toVar(),o=(0,n.int)(gT-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))},DT=(e,t,r,i)=>{let a=CT(ST(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)(Ad.GUIDE).add((0,n.uint)(xT(r).mul((0,n.int)(gT)).add(a)))),(0,n.uint)(1))})};function OT({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)(Ad.GUIDE).add(r.mul((0,n.uint)(gT))).toVar(),a=(0,n.float)(0).toVar();(0,n.Loop)({start:(0,n.int)(0),end:(0,n.int)(gT),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)(vT)).toVar(),s=(0,n.float)(0).toVar();(0,n.Loop)({start:(0,n.int)(0),end:(0,n.int)(gT),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)(gT-1)),(0,n.float)(1),s.div(a)),(0,n.float)(0)))}),t.element(o.add((0,n.uint)(gT))).assign(a)})().compute(16,[16])}function kT({counters:e}){return(0,n.Fn)(()=>{(0,n.If)(n.instanceIndex.lessThan((0,n.uint)(jd)),()=>{(0,n.atomicStore)(e.element((0,n.uint)(Ad.GUIDE).add(n.instanceIndex)),(0,n.uint)(0))})})().compute(jd,[256])}cu(),Od();function AT(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)(Ad.ACTIVE_RAY_COUNT)),k),(0,n.atomicStore)(a.element((0,n.uint)(Ad.ENTERING_COUNT)),k)}),(0,n.If)(e.greaterThanEqual(k),()=>{(0,n.Return)()}),i.element(e).assign(e);let A=Kw(e,E).toVar(),j=Le({state:Qe({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(),R=(0,n.int)(0).toVar(),ee=(0,n.float)(1).toVar(),z=(0,n.bool)(!1).toVar(),te=Xe(A,(0,n.int)(0),(0,n.int)(zw+4),j,E,D).toVar(),ne=(0,n.int)(0).toVar(),re=(0,n.int)(T.sourceCount-1).toVar();(0,n.Loop)(ne.lessThan(re),()=>{let e=ne.add(re).div(2).toVar();(0,n.If)(T.sourceCdf.element(e).lessThanEqual(te),()=>{ne.assign(e.add(1))}).Else(()=>{re.assign(e)})});let ie=T.guideTexture,ae=e=>{let t=ET(T,ie,e,Xe(A,(0,n.int)(0),(0,n.int)(zw+7),j,E,D),Ye(A,(0,n.int)(0),(0,n.int)(zw+6),j,E,D)).toVar();return{start:t,pdf:TT(T,ie,e,t)}};(0,n.If)(ne.equal((0,n.int)(cT.SUN)),()=>{let e=fh(p,h,Ye(A,(0,n.int)(0),(0,n.int)(zw+5),j,E,D)).toVar(),t=dh(e,p,m,h).mul(g).toVar(),r=ae(e),i=sT(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(qw((0,n.float)(1).div(h.y.mul(i)))),I.assign(qw((0,n.float)(1).div(i))),z.assign(!0)})}).ElseIf(ne.equal((0,n.int)(cT.EMITTERS)),()=>{let e=Sg(o,u,l,Xe(A,(0,n.int)(0),(0,n.int)(zw),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)),R.assign((0,n.int)(r.w));let a=yg.wrap(bg(L,s,c,R)).toVar(),p=lg(a.v0,a.v1,a.v2,Ye(A,(0,n.int)(0),(0,n.int)(zw+1),j,E,D)).toVar(),m=(0,n.normalize)((0,n.cross)(a.v1.sub(a.v0),a.v2.sub(a.v0))).toVar(),h=xf(Yl(s,L,4).z).toVar(),g=(0,n.select)(h.equal((0,n.int)(1)).or(h.equal((0,n.int)(2)).and(Xe(A,(0,n.int)(0),(0,n.int)(zw+3),j,E,D).lessThan(.5))).toVar(),m.negate(),m).toVar();N.assign(Yf(g,Ye(A,(0,n.int)(0),(0,n.int)(zw+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(bl(p,g)),P.assign(i.xyz.mul(f).mul(Math.PI).div(v)),F.assign(qw((0,n.float)(1).div(y))),I.assign(qw(_.div(y))),ee.assign(_),z.assign(!0)})}).ElseIf(ne.equal((0,n.int)(cT.ENVIRONMENT)),()=>{let e=Hf(v,y,b,Ye(A,(0,n.int)(0),(0,n.int)(zw+5),j,E,D)),t=e.direction.toVar(),r=e.pdf.toVar(),i=Wf({tex:_,samp:(0,n.sampler)(_),direction:t,environmentMatrix:y,environmentIntensity:g,enableEnvironmentLight:(0,n.float)(1)}).xyz.toVar(),a=ae(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(qw(r.div(o))),I.assign(qw((0,n.float)(1).div(o))),L.assign((0,n.int)(-1-cT.ENVIRONMENT)),z.assign(!0)})}).ElseIf(ne.greaterThanEqual((0,n.int)(cT.LAMPS)),()=>{let e=lT(T,ne).toVar(),t=dT(T,ne).toVar(),r=fT(T,ne,t).toVar();L.assign((0,n.int)(-1).sub(ne));let i=(0,n.float)(0).toVar(),a=(0,n.vec3)(0).toVar(),o=Ye(A,(0,n.int)(0),(0,n.int)(zw+2),j,E,D).toVar();(0,n.If)(t.equal((0,n.int)(0)),()=>{let t=mm.wrap(bm(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=Iw(t).toVar();o.assign(Am(o,t.angle.mul(.5),Ye(A,(0,n.int)(0),(0,n.int)(zw+5),j,E,D))),a.divAssign(e),i.divAssign(e)});let s=ae(o);i.mulAssign(s.pdf),M.assign(s.start),N.assign(o.negate())}).ElseIf(t.equal((0,n.int)(1)),()=>{let t=hm.wrap(xm(S,r)),s=t.shape.greaterThan(.5),c=Ye(A,(0,n.int)(0),(0,n.int)(zw+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(Yf(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)),kh(t).mul(Oh(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(qw(d.div((0,n.max)(i,1e-30))))}).ElseIf(t.equal((0,n.int)(2)),()=>{let t=gm.wrap(Sm(C,r));M.assign(t.position),N.assign(Am((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=_m.wrap(Cm(w,r));M.assign(t.position),N.assign(Am(t.direction,t.angle,o));let s=N.negate();a.assign(t.color.mul(t.intensity).mul(Em({coneCosine:(0,n.cos)(t.angle),blend:t.penumbra,angleCosine:(0,n.dot)(N,t.direction)})).mul(Dm(t,s)).mul(km(t,s))),i.assign(e.div(Fw(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(qw((0,n.float)(1).div(i))),z.assign(!0)})}),(0,n.If)(z.not(),()=>{Hu(t,e,N,(0,n.uint)(0)),(0,n.Return)()});let oe=(0,n.max)((0,n.max)((0,n.max)(P.x,P.y),P.z),1e-20).toVar();Vu(t,e,M,(0,n.int)(0),(0,n.int)(0)),Hu(t,e,N,(0,n.uint)(Id.ACTIVE|Id.REDIRECTED|Id.LIGHT_PATH|Id.LIGHT_EMITTED)),Uu(t,e,P.div(oe),(0,n.float)(0)),Wu(t,e,(0,n.vec4)((0,n.vec3)(0),(0,n.float)(1))),gd(t,e,(0,n.uint)(0),(0,n.uint)(O),(0,n.float)(1),(0,n.float)(1),(0,n.float)(1)),td(r,e,j,F,I),fd(r,e,L,R,ee,oe)})}cu(),Od();function jT(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)(Ad.ENTERING_COUNT)))),()=>{(0,n.Return)()});let w=i.element(e).toVar(),T=nd(w);(0,n.If)(ad(r,T).notEqual(_),()=>{(0,n.Return)()});let E=ld(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=Le({state:Qu(r,w).bitXor((0,n.uint)(2654435769))}).toVar(),P=Xe(j,(0,n.int)(0),M.add((0,n.int)(16)),N,l,u).toVar(),F=Xe(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)(ud(r,rd(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 R=(0,n.min)((0,n.int)((0,n.float)(L).mul(F)),L.sub((0,n.int)(1))).toVar(),ee=ld(r,rd(I.add((0,n.uint)(R)))),z={...ee,vm:S?.(ee.position)??null},te=z.position.sub(D.position).toVar(),ne=(0,n.max)((0,n.dot)(te,te),1e-12).toVar(),re=te.div((0,n.sqrt)(ne)).toVar(),ie=(0,n.dot)(re,D.N).toVar(),ae=(0,n.dot)(re,D.facetN).toVar(),oe=(0,n.dot)(re,z.facetN).negate().toVar(),se=ie.greaterThan(0).and(ae.greaterThan(0)).and(oe.greaterThan(0)),ce=ie.lessThan(0).and(ae.lessThan(0)),B=oe.lessThan(0);(0,n.If)((C?ce.or(ie.greaterThan(0).and(ae.greaterThan(0))).and(B.or(oe.greaterThan(0))):se).not(),()=>{(0,n.Return)()});let le=pT(D.materialIndex,D.uv,D.N,c),ue=pT(z.materialIndex,z.uv,z.N,c),de=re.negate();C&&(0,n.If)(ce.and(le.diffuseTransmission.lessThanEqual(0)).or(B.and(ue.diffuseTransmission.lessThanEqual(0))),()=>{(0,n.Return)()});let fe=e=>C?mT(D.N,e,le):D.N,pe=e=>C?mT(z.N,e,ue):z.N,me=pm(D.V,re,D.N,le).toVar(),he=pm(de,z.V,pe(de),ue).toVar(),ge=(C?(0,n.abs)(ie):ie).mul(hT(z.V,z.N,z.facetN,de)).div(ne),_e=Ih(D.V,re,D.N,le),ve=Ih(re,D.V,fe(re),le),V=Ih(z.V,de,z.N,ue),ye=Ih(de,z.V,pe(de),ue),be=Zw(_e.mul(C?(0,n.abs)(oe):oe).div(ne),z,ye),xe=Zw(V.mul(C?(0,n.abs)(ae):ae).div(ne),D,ve),Se=O.add(R).add((0,n.int)(1)),H=iT(v,rT.CONNECT,nT(be,xe),(0,n.float)(1).div((0,n.float)(Se.sub((0,n.int)(1))))),Ce=Xh(D.throughput.mul(me).mul(he).mul(z.throughput).mul(ge.mul(H).mul((0,n.float)(L)).mul(b)),(0,n.float)(Se.sub((0,n.int)(1))),x,(0,n.int)(d)).toVar();(0,n.If)(Rl(Ce).greaterThan(0),()=>{let e=bl(D.position,C?(0,n.select)(ce,D.facetN.negate(),D.facetN):D.facetN).toVar(),r=bl(z.position,C?(0,n.select)(B,z.facetN.negate(),z.facetN):z.facetN).sub(e).toVar(),i=(0,n.length)(r).toVar(),a=th(e,r.div(i),i.mul(xl),Df,o,s,c);(0,n.If)(a.greaterThan(0),()=>{let e=ju(t,w).toVar();Wu(t,w,(0,n.vec4)(e.xyz.add(Ce.mul(a)),e.w))})})})}cu(),Od();var MT=4294967295,NT=1024,PT=Math.log2(1.25),FT=(e,t)=>(0,n.int)((0,n.max)((0,n.floor)((0,n.log2)(t.div(e.mergeMin)).div(PT)),0)),IT=(e,t)=>e.mergeMin.mul((0,n.exp2)((0,n.float)(t.add((0,n.int)(1))).mul(PT))).mul(2).div((0,n.max)((0,n.float)(1).sub(e.mergeSlope),.5)),LT=(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),RT=(e,t)=>{let r=FT(e,Qw(e,t)).toVar();return{shell:r,cell:(0,n.ivec3)((0,n.floor)(t.div(IT(e,r)))).toVar()}};function zT({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)(MT))})})().compute(Math.ceil(t/256)*256,[256])}function BT({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(ud(e,rd(c.sub(l)),o)),()=>{(0,n.Return)()});let u=rd(c),{shell:d,cell:f}=RT(r,od(e,u)),p=LT(d,f,s);cd(e,u,(0,n.atomicFunc)(`atomicExchange`,t.element(p),c))})}function VT(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)(Ad.ENTERING_COUNT)))),()=>{(0,n.Return)()});let v=i.element(e).toVar(),y=nd(v);(0,n.If)(ad(r,y).notEqual(m),()=>{(0,n.Return)()});let b=ld(r,y),x=(0,n.int)(b.extra).toVar(),S=(0,n.int)(l).add((0,n.int)(1)).sub(x).toVar(),C=pT(b.materialIndex,b.uv,b.N,s),w=(0,n.vec3)(0).toVar(),T=Qw(c,b.position).toVar(),E=T.mul(T).toVar(),D=$w(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=FT(c,(0,n.max)(c.mergeConst.add(c.mergeSlope.mul((0,n.max)(A.sub(T),0))),c.mergeMin)).toVar(),M=(0,n.min)(FT(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=IT(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(LT(t,s,_))).toVar(),m=(0,n.int)(0).toVar();(0,n.Loop)(l.notEqual((0,n.uint)(MT)).and(m.lessThan((0,n.int)(NT))),()=>{let e=rd(l),i=od(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=RT(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=ld(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=pm(b.V,t.V,b.N,C),r=tT(t,Ih(b.V,t.V,b.N,C),k),s=p?mT(b.N,t.V,C):b.N,c=tT(b,Ih(t.V,b.V,s,C),k),l=x.add(o),m=iT(g,rT.MERGE,nT(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(Xh(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(sd(r,e)),m.addAssign((0,n.int)(1))})}),(0,n.If)(Rl(w).greaterThan(0),()=>{let e=ju(t,v).toVar();Wu(t,v,(0,n.vec4)(e.xyz.add(w),e.w))})})}cu(),Od();function HT(e){let{hitBufferRO:t,splatBuffer:r,bvhBuffer:i,triangleBuffer:a,materialBuffer:o,lightPaths:s,slotsPerPath:c,lightTag:l,strategyView:u,cameraPosition:d,cameraForward:f,cameraViewMatrix:p,cameraProjectionMatrix:m,pixelArea:h,renderWidth:g,renderHeight:_,globalIlluminationIntensity:v,fireflyThreshold:y,accumFrame:b,frame:x,mergeVm:S=null,diffuseTransmission:C=!0}=e;return(0,n.Fn)(()=>{let e=n.instanceIndex.toVar();(0,n.If)(e.greaterThanEqual(s.mul(c)),()=>{(0,n.Return)()});let w=e.mod(c).toVar(),T=ud(t,rd(e.sub(w)),l);(0,n.If)(w.greaterThanEqual(T),()=>{(0,n.Return)()});let E=ld(t,rd(e)),D={...E,vm:S?.(E.position)??null},O=d.sub(D.position).toVar(),k=(0,n.max)((0,n.dot)(O,O),1e-12).toVar(),A=O.div((0,n.sqrt)(k)).toVar(),j=(0,n.dot)(A,D.facetN).toVar(),M=(0,n.dot)(A,f).negate().toVar(),N=j.lessThan(0),P=C?(0,n.select)(N,D.extra.bitAnd((0,n.uint)(2)),D.extra.bitAnd((0,n.uint)(1))).notEqual((0,n.uint)(0)):D.extra.notEqual((0,n.uint)(0));(0,n.If)((C?j.equal(0):j.lessThanEqual(0)).or(M.lessThanEqual(1e-6)).or(P),()=>{(0,n.Return)()});let F=m.mul(p.mul((0,n.vec4)(D.position,1))).toVar();(0,n.If)(F.w.lessThanEqual(0),()=>{(0,n.Return)()});let I=(0,n.floor)(F.x.div(F.w).mul(.5).add(.5).mul((0,n.float)(g))).toVar(),L=(0,n.floor)((0,n.float)(.5).sub(F.y.div(F.w).mul(.5)).mul((0,n.float)(_))).toVar();(0,n.If)(I.lessThan(0).or(L.lessThan(0)).or(I.greaterThanEqual((0,n.float)(g))).or(L.greaterThanEqual((0,n.float)(_))),()=>{(0,n.Return)()});let R=pT(D.materialIndex,D.uv,D.N,o);C&&(0,n.If)(N.and(R.diffuseTransmission.lessThanEqual(0)),()=>{(0,n.Return)()});let ee=C?mT(D.N,A,R):D.N,z=pm(A,D.V,ee,R).toVar(),te=(0,n.float)(1).div(h.mul(M).mul(M).mul(M)).div(k).toVar(),ne=Zw(te.mul(C?(0,n.abs)(j):j).div((0,n.float)(s)),D,Ih(A,D.V,ee,R)),re=w.add((0,n.uint)(1)),ie=(0,n.float)(1).toVar();(0,n.If)(re.greaterThan((0,n.uint)(1)),()=>{ie.assign(v)});let ae=Xh(D.throughput.mul(z).mul(hT(D.V,D.N,D.facetN,A)).mul(te.div((0,n.float)(s)).mul(iT(u,rT.LIGHT_TRACE,nT(ne,(0,n.float)(0)))).mul(ie)),(0,n.float)(w),y,(0,n.int)(b)).toVar(),oe=bl(D.position,C?(0,n.select)(N,D.facetN.negate(),D.facetN):D.facetN).toVar(),se=d.sub(oe).toVar(),ce=(0,n.length)(se).toVar(),B=th(oe,se.div(ce),ce.mul(xl),Of,i,a,o);(0,n.If)(B.greaterThan(0),()=>{let t=(0,n.min)(Ml(ae.mul(B)),(0,n.vec3)(Hw)).mul(Vw).toVar(),i=(0,n.float)(Le({state:e.bitXor((0,n.uint)(x).mul((0,n.uint)(2654435769)))}).shiftRight((0,n.uint)(8))).mul(1/16777216).toVar(),a=(0,n.uint)(L).mul((0,n.uint)(g)).add((0,n.uint)(I)).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 UT(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=ju(t,o).toVar();Wu(t,o,(0,n.vec4)(e.xyz.add((0,n.vec3)((0,n.float)(l),(0,n.float)(u),(0,n.float)(d)).div(Vw)),e.w))})})})}O(),Od(),at(),Pt();var{PASS_TAG_BIT:WT,STRATEGY:GT,STRATEGY_ALONE:KT,SOURCE:qT,mergeVmAt:JT}=Rw,YT={...Rw,...Dw,guidedDiscPdf:TT,recordEscape:DT},XT=256*1024*1024,ZT=.05,QT=.5,$T=(1<<24)-1,eE=1,tE=.75,nE=.25,rE=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:YT,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(qT.LAMPS),`float`),sourceCount:qT.LAMPS,sourceOffsets:[qT.LAMPS,qT.LAMPS,qT.LAMPS,qT.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)(nE,`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(XT,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)&&(_u(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&&(_u(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,_T,16,r.RedFormat,r.FloatType),this._guideTexture.source.dataReady=!1,this._guideTexture.needsUpdate=!0,this._guideBuildAttr=v(vT*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)(Ad.ACTIVE_ENERGY)))),(0,n.atomicStore)(a.element((0,n.uint)(Ad.ENTERING_COUNT)),e)};if(t.register(`lightSnapshot`,(0,n.Fn)(()=>{C((0,n.atomicLoad)(a.element((0,n.uint)(Ad.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)(Ad.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`,kT({counters:a})),t.register(`guideBuild`,OT({counters:a,out:(0,n.storage)(this._guideBuildAttr,`float`)})),t.register(`lightGenerate`,f(AT({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(jT({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=>JT(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`,zT({head:e,hashSize:this._mergeHeadAttr.count})),t.register(`mergeInsert`,BT({hitBufferRW:i.hitBuffer.rw,head:e,bidirectional:x})().compute([Math.ceil(this._lightCacheSlots/256),1,1],[256,1,1])),t.register(`merge`,f(VT({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(HT({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,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=>JT(x,e):null,diffuseTransmission:b})()).compute([Math.ceil(this._lightCacheSlots/256),1,1],[256,1,1])),t.register(`splatResolve`,UT({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(){_u(this.pt.renderer,this._splatAttr),this._splatAttr=null,_u(this.pt.renderer,this._mergeHeadAttr),this._mergeHeadAttr=null,this._disposeLightGuide()}setBidirectionalStrategy(e=`all`,{alone:t=!1}={}){let n={all:GT.ALL,hit:GT.HIT,nee:GT.NEE,connect:GT.CONNECT,lightTrace:GT.LIGHT_TRACE,merge:GT.MERGE}[e]??GT.ALL;this.uniforms.strategyView.value=n===GT.ALL?n:n+(t?KT:0)}setMergeRadius(e=eE){this._mergeRadiusPixels=Math.max(e,.001)}setMergeTrust(e=nE){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*QT),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%$T+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===tt.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)**((tE-1)/2),i=this.pt.cameraProjection.value,a=this.pt.cameraProjectionMatrix.value.elements,o=0,s=0;i===tt.orthographic?s=r*2/(a[5]*t):o=i===tt.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=qT.LAMPS;[`directional`,`area`,`point`,`spot`].forEach((n,r)=>{e.sourceOffsets[r]=t,t+=this.pt[`${n}LightsBufferNode`].array.length/st[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:st[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*ZT:0;if(o&&s&&(n[qT.ENVIRONMENT]=Math.max(s.radianceIntegral,0)*this.pt.environmentIntensity.value*u),this.pt.emissiveTriangleCount.value>0&&(n[qT.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[qT.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(qT.SUN),e.emitterPick.value=g(qT.EMITTERS),e.envPick.value=g(qT.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]!==wt.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:vT*4,rowsPerImage:16},{texture:r.get(this._guideTexture).texture},[_T,16]),r.device.queue.submit([i.finish()]),e.guide.value=1}_disposeLightGuide(){_u(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,(WT|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 o_)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 iE(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}ai(),Oe();var aE=_e(`ocio`);function oE(e){let t=String(e);/\[OpenColorIO Error\]/.test(t)?aE.error(t):/\[OpenColorIO Warning\]/.test(t)?aE.warn(t):aE.debug(t)}var sE=null,cE=null,lE=null,uE=null,dE=null;async function fE(){let{ocioRuntimeFactory:e,ocioRuntimeUrl:t}=ni();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 pE(){return cE||(sE||=(async()=>{let e=await fE();if(typeof e.createOcioRuntime!=`function`)throw Error(`OCIO module has no createOcioRuntime() — wrong package or version`);let{ocioWasmUrl:t}=ni();return cE=await e.createOcioRuntime({...t?{wasmUrl:t}:{},moduleOptions:{print:oE,printErr:oE}}),cE})().catch(e=>{throw sE=null,e}),await sE)}async function mE(){return(await pE()).ocio.listBuiltinConfigs()}async function hE({builtin:e,text:t,files:n=[],configPath:r=`config.ocio`,id:i}={}){let a=await pE();if(e)lE=a.loadBuiltinConfig(e),uE=e,dE=xE(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`);lE=a.loadConfigPackage({configRelativePath:r,files:e},i?{id:i}:void 0),uE=i??lE.id;let o=e.find(e=>e.relativePath===r);dE=o?new TextDecoder().decode(o.data):null}return bE()}function gE(){lE=null,uE=null,dE=null}function _E(){return lE!==null}function vE(){return lE?cE:null}function yE(){return lE}function bE(){if(!lE)return null;let e=Object.fromEntries(lE.roles.map(e=>[e.name,e.colorSpace]));return{id:uE,name:dE?.match(/^name:\s*(\S.*?)\s*$/m)?.[1]??null,ocioVersion:lE.ocioVersion,version:lE.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:lE.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:lE.displays.slice(),defaultDisplay:lE.defaultDisplay,views:Object.fromEntries(Object.entries(lE.viewsByDisplay).map(([e,t])=>[e,t.map(e=>({name:e.name,transform:e.transform,colorSpace:e.colorSpace,looks:e.looks,description:e.description}))])),defaultViews:{...lE.defaultViewsByDisplay},looks:lE.looks.map(e=>({name:e.name,processSpace:e.processSpace,description:e.description,forward:e.hasForwardTransform,inverse:e.hasInverseTransform})),namedTransforms:lE.namedTransforms.map(e=>e.name),fileRules:lE.fileRules.map(e=>({index:e.index,name:e.name,colorSpace:e.colorSpace,pattern:e.pattern,extension:e.extension,regex:e.regex})),contextVariables:SE()}}function xE(e,t){try{return e.ocio.getBuiltinConfigYaml(t)}catch{return null}}function SE(){if(!dE)return[];let e=new Map,t=dE.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 dE.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 CE(){gE(),cE?.dispose?.(),cE=null,sE=null}var wE=1<<20,TE=new Map,EE=new Map,DE=4096,OE=new Map;function kE(e,t,n){return`${e}\u0000${t}\u0000${n?JSON.stringify(n):``}`}function AE(){for(let e of TE.values())e.dispose?.();TE.clear(),EE.clear(),OE.clear()}function jE(e,t,{context:n=null}={}){if(!vE()||e===t)return null;let r=kE(e,t,n),i=TE.get(r);if(i!==void 0)return i;try{i=FE().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 TE.set(r,i),i}var ME=null,NE=null,PE=!1;function FE(){let e=vE();if(!e)throw Error(`no OCIO config loaded`);if(e.config)return e.config;let t=yE();if(ME&&NE===t.id)return ME;if(PE&&ME?.dispose?.(),!t.id?.startsWith(`ocio://`))throw Error(`OCIO runtime exposes no Config handle for this config`);return ME=e.ocio.createBuiltinConfig(t.id),PE=!0,NE=t.id,ME}function IE(){PE&&ME?.dispose?.(),ME=null,NE=null,PE=!1,AE()}function LE(e,t,n,{context:r=null}={}){let i=vE();if(!i||t===n)return[e[0],e[1],e[2]];let a=`${kE(t,n,r)}\u0000${e[0]},${e[1]},${e[2]}`,o=EE.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 EE.size>=DE&&EE.clear(),EE.set(a,s),s.slice()}function RE(e,t,n,{context:r=null}={}){if(e.length%4!=0)throw Error(`convertPixelsF32 wants 4 floats per pixel`);let i=jE(t,n,{context:r});if(!i)return e;let a=e.length/4;if(a<=wE)return i.applyRGBAF32(e),e;for(let t=0;t<a;t+=wE){let n=Math.min(wE,a-t);i.applyRGBAF32(e.subarray(t*4,(t+n)*4))}return e}var zE=.055;function BE(e){return e<=.04045?e/12.92:((e+zE)/(1+zE))**2.4}function VE(e){return e<=0?0:e<=.0031308?12.92*e:(1+zE)*e**(1/2.4)-zE}var HE=new Float32Array(256);for(let e=0;e<256;e++)HE[e]=BE(e/255);var UE=new Float32Array(256);for(let e=0;e<256;e++)UE[e]=e/255;function WE(e){return e===`srgb`?HE:UE}function GE(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=jE(t,n,{context:r});if(!o)return e;let s=e.length/4,c=WE(i),l=a===`srgb`?JE:YE,u=new Float32Array(Math.min(wE,s)*4);for(let t=0;t<s;t+=wE){let n=Math.min(wE,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 KE=65536,qE=new Uint8Array(KE+1);for(let e=0;e<=KE;e++){let t=e/KE;qE[e]=Math.round(VE(t*t)*255)}function JE(e){return e>0?e>=1?255:qE[Math.sqrt(e)*KE+.5|0]:0}function YE(e){return e>0?e>=1?255:e*255+.5|0:0}function XE(e,t,n=`srgb`){if(!t)return e;let r=WE(n),i=n===`srgb`?JE:YE,[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 ZE(e,t,{context:n=null,tolerance:r=1e-4}={}){if(!vE())return null;if(e===t)return[1,0,0,0,1,0,0,0,1];let i=kE(e,t,n);if(OE.has(i))return OE.get(i);let a=jE(e,t,{context:n});if(!a)return OE.set(i,[1,0,0,0,1,0,0,0,1]),OE.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 OE.set(i,f),f}function QE(e){let t=yE();if(!t)return!1;let n=t.colorSpaces.find(t=>t.name===e||t.aliases?.includes(e));return n?n.isData:!1}function $E(e){let t=yE();return!t||!e?!1:t.colorSpaces.some(t=>t.name===e||t.aliases?.includes(e))}var eD=1e-10;function tD(e,t,n,r){return e<=0?0:2**(n+e/(t-1)*(r-n))}function nD(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 rD({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]=tD(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 iD(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 aD(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 oD=null;function sD(){if(!oD){let e=new Uint16Array(65536);for(let t=0;t<65536;t++)e[t]=t;oD=aD(e)}return oD}function cD(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 lD({data:e,size:t,minEv:n,maxEv:r}){let i=t*t,a=t-1,o=e instanceof Uint16Array,s=o?sD():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=nD(e,t,n,r),u=nD(i,t,n,r),d=nD(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}=cD(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 uD({fnName:e,texName:t,size:n,minEv:r,maxEv:i}){let a=e=>Number.isInteger(e)?`${e}.0`:String(e);return`
|
|
1406
|
+
`,RC=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 ${(NC/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 kC()).create(o,t,n,a,OC(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:IC}),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:LC}),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 hv(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){MC.warn(`retouch teardown:`,e)}}}},zC=20}));F(),rn(),Oe(),at();var VC=_e(`neural`),HC=120,UC=2,WC=1,GC=0,KC=300,qC=5,JC=3,YC=3,XC=16,ZC=e=>Math.max(0,1-e/XC),QC=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=Py.oidnQuality,this.finalDenoise=Py.enableOIDN,this.continuousDenoise=Py.continuousDenoise,this.continuousDenoiseInterval=Py.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=Py.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._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(Z.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 BS(this.renderer,{enableOIDN:Py.enableOIDN,oidnQuality:Py.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=>{this.denoiser?.hasOutput&&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(Z.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)}setupUpscaler(){if(!this.upscalerCanvas)return;let e=this._stages.pathTracer;this.upscaler=new lC(this.upscalerCanvas,this.renderer,{scaleFactor:Py.upscalerScale||2,quality:Py.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}),this.upscaler.enabled=Py.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.asvgf?.enabled?`asvgf`:this._stages.nrd?.enabled?`nrd`:this._stages.edgeFilter?.enabled?`edgeaware`:`none`}setDenoiserStrategy(e,t){let n=this._stages;switch(n.asvgf&&(n.asvgf.enabled=!1),n.nrd&&(n.nrd.enabled=!1),n.variance&&(n.variance.enabled=!1),n.bilateralFilter&&(n.bilateralFilter.enabled=!1),n.edgeFilter&&n.edgeFilter.setFilteringEnabled(!1),this._clearDenoiserTextures(),this.setContinuousDenoise(e===`oidn`),e){case`asvgf`:n.asvgf.enabled=!0,n.variance&&(n.variance.enabled=!0),n.bilateralFilter&&(n.bilateralFilter.enabled=!0),n.asvgf.setTemporalEnabled?.(!0),this._applyASVGFPreset(t||`medium`);break;case`nrd`:n.nrd&&(n.nrd.enabled=!0,n.nrd.resetHistory?.(),this._applyNRDPreset(t||`medium`));break;case`edgeaware`:n.variance&&(n.variance.enabled=!0),n.edgeFilter&&n.edgeFilter.setFilteringEnabled(!0);break}this._syncGBufferStages()}setASVGFEnabled(e,t){let n=this._stages;n.asvgf&&(n.asvgf.enabled=e),n.variance&&(n.variance.enabled=e),n.bilateralFilter&&(n.bilateralFilter.enabled=e),e&&(n.nrd&&(n.nrd.enabled=!1),n.asvgf?.setTemporalEnabled?.(!0),this._applyASVGFPreset(t||`medium`)),n.edgeFilter&&n.edgeFilter.setFilteringEnabled(!e),this._syncGBufferStages()}applyASVGFPreset(e){this._applyASVGFPreset(e)}setAutoExposureEnabled(e,t){this._stages.autoExposure?.setEnabled(e,t)}get requiresMotionVectors(){return!!(this._stages.asvgf?.enabled||this._stages.nrd?.enabled)}_syncGBufferStages(){let e=this._stages,t=e.normalDepth,n=e.motionVector,r=this.requiresMotionVectors,i=r||this.historyWanted||!!(e.edgeFilter?.enabled||e.bilateralFilter?.enabled);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.isFirstFrame=!0,n.frameCount=0),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.asvgf,e.nrd,e.variance,e.bilateralFilter,e.edgeFilter,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>KC*JC&&(this._movingHopeless=!0,this._syncGBufferStages());let n=!this._movingHopeless&&(t<2||e<=KC);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<YC||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?GC:this._lastCadenceSamples===0?WC:UC,a=Math.max(this.continuousDenoiseInterval,t.lastDenoiseMs*i);if(r-this._lastCadenceAt<a)return!1;this._lastCadenceAt=r,this._lastCadenceSamples=e,t.lastDenoiseMs>HC&&(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>qC&&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())}setContinuousDenoise(e){this.continuousDenoise=!!e,this._syncOIDNInUse(),this._lastCadenceAt=-1/0,this._resetCadence()}_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}get historyActive(){let e=this._stages.pathTracer;return this.historyWanted&&!this._cadenceSuspended&&!!this._stages.normalDepth?.enabled&&e?.uniforms?.get(`cameraProjection`)?.value!==tt.equirectangular&&!(e?.visMode?.value>0)}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:ZC(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>=XC)return null;let n=this._historyInputs();return n?t.merge(n,e.frameCount,this._historyCameraNow(),{historyScale:ZC(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===tt.orthographic,t}_ensureHistory(){return this._history??=new nC(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`)){VC.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(()=>(EC(),uC));this._superResModule=i;let a=n?await Promise.resolve().then(()=>(BC(),DC)):null,o=this.denoiser?._outTexSize,s=(o?.width??0)*(o?.height??0),c=n&&s<=a.RETOUCH_MAX_PIXELS;if(n&&!c&&(VC.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){VC.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.finalDenoise?`final`:this.continuousDenoise?`refresh`:null,n=()=>{this.denoiser?.removeEventListener(`end`,n),this._pendingStartUpscaler=null,e()&&(t&&this._onDisplayRefresh?.(),this._runPostPasses(e))};if(!t){n();return}let r=()=>{e()&&(this._pendingStartUpscaler=n,this.denoiser.addEventListener(`end`,n),t===`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),r()};this._pendingCloseDenoise=e,this.denoiser.addEventListener(`end`,e)}else r()}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(){this._cleanupCompletionListener(),this._postIsStillComplete=null,this._releaseNeuralUpscaler(),this._releaseNeuralRetouch(),this._unpublishOutput(),this._releaseHistory(),this.denoiser&&=(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.denoiser.dispose(),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._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}setASVGFParams(e){this._stages.asvgf?.updateParameters(e)}toggleASVGFHeatmap(e){this._stages.asvgf?.setHeatmapEnabled?.(e)}configureASVGFForMode(e){this._stages.asvgf&&(this._stages.asvgf.enabled=e.enabled,this._stages.variance&&(this._stages.variance.enabled=e.enabled),this._stages.bilateralFilter&&(this._stages.bilateralFilter.enabled=e.enabled),e.enabled&&this._stages.asvgf.updateParameters(e),this._syncGBufferStages())}setEdgeAwareParams(e){this._stages.edgeFilter?.updateUniforms(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&&[`asvgf:output`,`asvgf:demodulated`,`asvgf:gradient`,`variance:output`,`bilateralFiltering:output`,`edgeFiltering:output`,`nrd:output`,`oidn:output`].forEach(t=>e.removeTexture(t))}_applyNRDPreset(e){let t=My[e];if(!t)return;let n={};for(let e of jy)n[e]=Ay[e];this._stages.nrd?.updateParameters({...n,...t})}_applyASVGFPreset(e){let t=Dy[e];t&&(this._stages.asvgf?.updateParameters(t),this._stages.bilateralFilter?.updateParameters(t),this._stages.variance&&t.varianceBoost!==void 0&&(this._stages.variance.varianceBoost.value=t.varianceBoost))}},$C=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 tw(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 nw(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}}ue();var rw=4096,iw=class{constructor(){this.canvas=tw(!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=nw(this._sizeSource,rw);!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(){te(this.renderer),this.renderer=null,this.canvas.parentElement?.removeChild(this.canvas)}};Oe(),F();var aw=_e(`overlay`),ow=(e,t)=>e.visible&&e.layer===t&&e.render,sw=class{constructor(e){this.camera=e,this._helpers=new Map,this._hudCanvas=tw(),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 iw().init({device:e,sizeSource:t})}catch(e){aw.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 $C;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)&&(aw.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())ow(t,`scene`)&&t.render(e,this.camera)}_hasVisibleSceneOverlay(){if(this._helperScene?.isDrawing)return!0;for(let e of this._helpers.values())if(ow(e,`scene`))return!0;return!1}refreshHUD(){let e=this._hudCanvas,t=this._hudCtx,n=!1;for(let e of this._helpers.values())if(ow(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?nw(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())ow(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 cw(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 lw=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:cw(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?cw(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 uw=new r.Vector3(0,0,-1),dw=e=>{for(;e.parent;)e=e.parent;return e.isScene?e:null},fw=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)dw(e)||this._moved.delete(e)}get movedObjects(){return[...this._moved].filter(e=>dw(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(uw,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}},pw=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}};gc();var mw=1,hw=e=>typeof e==`string`&&/^https?:\/\//.test(e);function gw(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 _w(e,t){let n=e;for(let e of t)if(n=n?.children[e],!n)return null;return n}function vw(e){return{key:e.assetLoader?.sceneSourceKey??null,name:e.sceneModel?.name??null,meshes:e.sceneMeshes.length,materials:e.stages.pathTracer?.materialData.materialCount??0}}function yw(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 bw(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 xw(e){let t=e.meshScene,n=yw(e),r=[];return t.traverse(e=>{e!==t&&e.visible===!1&&r.push(gw(e,t))}),{v:1,engine:hc,savedAt:Date.now(),scene:vw(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:bw(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:gw(e,t),name:e.name,position:e.position.toArray(),quaternion:e.quaternion.toArray(),scale:e.scale.toArray()})).filter(e=>e.path)}}function Sw(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 Cw(e,t,n,r){if(!t)return;let i=e.environmentManager;if(t.hdri&&t.hdri!==i.hdriSource){let i=hw(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 ww(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 Tw(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=vw(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 Cw(e,t.environment,n,i),await ww(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=yw(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=nr(i);Sw(t,n,a),e.setMaterialProperty(r.index,n,a)}}let r=e.meshScene,a=new Set((t.hidden??[]).map(e=>_w(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=_w(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 Ew=[{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)}}],Dw=_({LampPick:()=>Ow,areaLightDirectPdfW:()=>Lw,directionalConeSolidAngle:()=>Iw,lampCount:()=>kw,lampPickPdf:()=>Pw,lampTypeAt:()=>Aw,pickLamp:()=>Nw,spotConeSolidAngle:()=>Fw});O(),cu();var Ow=x({kind:`int`,index:`int`,pdf:`float`,total:`float`}),kw=e=>e.numDirectional.add(e.numArea).add(e.numPoint).add(e.numSpot),Aw=(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)))),jw=(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)))),Mw=(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=>rh(mm.wrap(bm(e.directional,t)),r,i,(0,n.int)(0))),o(1,e.numArea,a=>{let o=hm.wrap(xm(e.area,a));return(0,n.select)(o.intensity.greaterThan(0),ih(o,t,r,i),(0,n.float)(0))}),o(2,e.numPoint,n=>ah(gm.wrap(Sm(e.point,n)),t,r,i)),o(3,e.numSpot,n=>oh(_m.wrap(Cm(e.spot,n)),t,r,i))};function Nw(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();Mw(e,t,r,i,(t,r,i)=>{u.addAssign(i),(0,n.If)(i.greaterThan(0).and(o((0,n.int)(G+64).add(jw(e,t)).add(r)).mul(u).lessThan(i)),()=>{s.assign(t),c.assign(r),l.assign(i)})});let d=kw(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(Aw(e,t)),c.assign(t.sub(jw(e,s))),f.assign((0,n.float)(1).div((0,n.max)((0,n.float)(d),1)))}),Ow({kind:s,index:c,pdf:f,total:u})}function Pw(e,t,r,i,a,o){let s=(0,n.float)(0).toVar(),c=(0,n.float)(0).toVar();return Mw(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)(kw(e)),1)))}var Fw=e=>(0,n.float)(2*Sl).mul((0,n.max)((0,n.float)(1).sub((0,n.cos)(e.angle)),1e-10)),Iw=e=>(0,n.float)(2*Sl).mul((0,n.max)((0,n.float)(1).sub((0,n.cos)(e.angle.mul(.5))),1e-10)),Lw=(e,t,r,i)=>{let a=Mm(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)))},Rw=_({DIM_CONNECT_PATH:()=>16,DIM_CONNECT_VERTEX:()=>17,DIM_EMIT:()=>zw,LIGHT_PIXEL_ROW_OFFSET:()=>Bw,PASS_TAG_BIT:()=>Uw,SOURCE:()=>cT,SPLAT_MAX:()=>Hw,SPLAT_SCALE:()=>Vw,STRATEGY:()=>rT,STRATEGY_ALONE:()=>8,emitterAreaPdf:()=>oT,emitterSideProbability:()=>aT,facingSide:()=>mT,lampSource:()=>uT,lightEndCosine:()=>hT,lightPathPixel:()=>Kw,mergeEta:()=>$w,mergeRadiusAt:()=>Qw,mergeVmAt:()=>eT,mis:()=>qw,misMergePartial:()=>tT,misOnHit:()=>Jw,misOnScatter:()=>Xw,misOnSpecular:()=>Yw,misPartial:()=>Zw,misWeight:()=>nT,resolveSurfaceMaterial:()=>pT,sourceLampIndex:()=>fT,sourceLampType:()=>dT,sourcePick:()=>lT,strategyWeight:()=>iT,sunEmissionPdf:()=>sT});cu(),_l();var zw=G+2048,Bw=65536,Vw=16384,Hw=4096,Uw=2147483648,Ww=1e30,Gw=e=>(0,n.select)(e.equal(e),e,(0,n.float)(0)).clamp(0,Ww),Kw=(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)(Bw))).add(.5))},qw=e=>e.mul(e),Jw=(e,t,r)=>{let i=(0,n.max)(r,1e-6);e.dVCM.assign(Gw(e.dVCM.mul(qw(t.mul(t).div(i))))),e.dVC.assign(Gw(e.dVC.div(qw(i))))},Yw=(e,t)=>{e.dVC.assign(Gw(e.dVC.mul(qw(t)))),e.dVCM.assign(0)},Xw=(e,t,r,i)=>{let a=(0,n.max)(r,1e-12),o=e.dVC.mul(qw(i)).add(e.dVCM);e.dVC.assign(Gw(qw(t.div(a)).mul(Gw(e.vm?o.add(e.vm):o)))),e.dVCM.assign(Gw(qw((0,n.float)(1).div(a))))},Zw=(e,t,n)=>{let r=t.dVCM.add(t.dVC.mul(qw(n)));return Gw(Gw(qw(e)).mul(Gw(t.vm?r.add(t.vm):r)))},Qw=(e,t)=>(0,n.max)(e.mergeConst.add(e.mergeSlope.mul((0,n.length)(t.sub(e.cameraPosition)))),e.mergeMin),$w=(e,t)=>t.mul(t).mul(Math.PI).mul((0,n.float)(e.lightPaths)),eT=(e,t)=>{let n=$w(e,Qw(e,t)).mul(e.mergeTrust);return n.mul(n)},tT=(e,t,n)=>Gw(Gw(e.dVCM.add(e.dVC.mul(qw(t)))).mul(n)),nT=(e,t)=>(0,n.float)(1).div((0,n.float)(1).add(Gw(e)).add(Gw(t))),rT={ALL:0,HIT:1,NEE:2,CONNECT:3,LIGHT_TRACE:4,MERGE:5},iT=(e,t,r,i=(0,n.float)(1))=>(0,n.select)(e.equal((0,n.uint)(rT.ALL)).or(e.equal((0,n.uint)(t))),r,(0,n.select)(e.equal((0,n.uint)(t+8)),i,(0,n.float)(0))),aT=(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)))),oT=(e,t,r=1)=>(0,n.max)((0,n.dot)(e,kl),0).div((0,n.max)(t,1e-10)).mul(r),sT=(e,t,r)=>e.sunPick.mul(r).div((0,n.max)(t.y,1e-30)),cT={SUN:0,EMITTERS:1,ENVIRONMENT:2,LAMPS:3},lT=(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)))},uT=(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),dT=(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)))),fT=(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 pT(e,t,r,i){let a=nl.wrap($l((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=pl.wrap(yp(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(El,1)),a.sheenRoughness.assign(a.sheenRoughness.clamp(.05,1));let c=op({uv:t,transform:a.albedoTransform}).toVar();(0,n.If)(a.anisotropyMapIndex.greaterThanEqual((0,n.int)(0)),()=>{let e=gp(a,c).toVar();a.anisotropy.assign(e.x),a.anisotropyRotation.assign(e.y)});let l=rl.wrap(_p(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(El).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 mT=(e,t,r)=>(0,n.select)(r.diffuseTransmission.greaterThan(0).and((0,n.dot)(e,t).lessThan(0)),e.negate(),e),hT=(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)),gT=4096,_T=gT+1,vT=Math.ceil(_T*4/256)*64,yT=.2,bT=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()}},xT=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))},ST=(e,t,r)=>{let{u:i,v:a}=bT(t),o=r.sub(e.sceneCenter);return(0,n.vec2)((0,n.dot)(o,i),(0,n.dot)(o,a)).div(e.sceneRadius)},CT=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))},wT=(e,t,r)=>e.guide.greaterThan((0,n.uint)(0)).and(t.load((0,n.ivec2)((0,n.int)(gT),r)).x.greaterThan(0)),TT=(e,t,r,i)=>{let a=ST(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=xT(r).toVar(),l=CT(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(gT/4).div((0,n.max)(o,1e-30));return(0,n.select)(wT(e,t,c),(0,n.mix)(d,s,yT),s)},ET=(e,t,r,i,a)=>{let{u:o,v:s}=bT(r),c=(0,n.vec2)(0).toVar(),l=xT(r).toVar();return(0,n.If)(wT(e,t,l).and(i.lessThan(1-yT)),()=>{let e=i.div(1-yT).toVar(),r=(0,n.int)(0).toVar(),o=(0,n.int)(gT-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))},DT=(e,t,r,i)=>{let a=CT(ST(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)(Ad.GUIDE).add((0,n.uint)(xT(r).mul((0,n.int)(gT)).add(a)))),(0,n.uint)(1))})};function OT({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)(Ad.GUIDE).add(r.mul((0,n.uint)(gT))).toVar(),a=(0,n.float)(0).toVar();(0,n.Loop)({start:(0,n.int)(0),end:(0,n.int)(gT),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)(vT)).toVar(),s=(0,n.float)(0).toVar();(0,n.Loop)({start:(0,n.int)(0),end:(0,n.int)(gT),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)(gT-1)),(0,n.float)(1),s.div(a)),(0,n.float)(0)))}),t.element(o.add((0,n.uint)(gT))).assign(a)})().compute(16,[16])}function kT({counters:e}){return(0,n.Fn)(()=>{(0,n.If)(n.instanceIndex.lessThan((0,n.uint)(jd)),()=>{(0,n.atomicStore)(e.element((0,n.uint)(Ad.GUIDE).add(n.instanceIndex)),(0,n.uint)(0))})})().compute(jd,[256])}cu(),Od();function AT(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)(Ad.ACTIVE_RAY_COUNT)),k),(0,n.atomicStore)(a.element((0,n.uint)(Ad.ENTERING_COUNT)),k)}),(0,n.If)(e.greaterThanEqual(k),()=>{(0,n.Return)()}),i.element(e).assign(e);let A=Kw(e,E).toVar(),j=Le({state:Qe({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(),R=(0,n.int)(0).toVar(),ee=(0,n.float)(1).toVar(),z=(0,n.bool)(!1).toVar(),te=Xe(A,(0,n.int)(0),(0,n.int)(zw+4),j,E,D).toVar(),ne=(0,n.int)(0).toVar(),re=(0,n.int)(T.sourceCount-1).toVar();(0,n.Loop)(ne.lessThan(re),()=>{let e=ne.add(re).div(2).toVar();(0,n.If)(T.sourceCdf.element(e).lessThanEqual(te),()=>{ne.assign(e.add(1))}).Else(()=>{re.assign(e)})});let ie=T.guideTexture,ae=e=>{let t=ET(T,ie,e,Xe(A,(0,n.int)(0),(0,n.int)(zw+7),j,E,D),Ye(A,(0,n.int)(0),(0,n.int)(zw+6),j,E,D)).toVar();return{start:t,pdf:TT(T,ie,e,t)}};(0,n.If)(ne.equal((0,n.int)(cT.SUN)),()=>{let e=fh(p,h,Ye(A,(0,n.int)(0),(0,n.int)(zw+5),j,E,D)).toVar(),t=dh(e,p,m,h).mul(g).toVar(),r=ae(e),i=sT(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(qw((0,n.float)(1).div(h.y.mul(i)))),I.assign(qw((0,n.float)(1).div(i))),z.assign(!0)})}).ElseIf(ne.equal((0,n.int)(cT.EMITTERS)),()=>{let e=Sg(o,u,l,Xe(A,(0,n.int)(0),(0,n.int)(zw),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)),R.assign((0,n.int)(r.w));let a=yg.wrap(bg(L,s,c,R)).toVar(),p=lg(a.v0,a.v1,a.v2,Ye(A,(0,n.int)(0),(0,n.int)(zw+1),j,E,D)).toVar(),m=(0,n.normalize)((0,n.cross)(a.v1.sub(a.v0),a.v2.sub(a.v0))).toVar(),h=xf(Yl(s,L,4).z).toVar(),g=(0,n.select)(h.equal((0,n.int)(1)).or(h.equal((0,n.int)(2)).and(Xe(A,(0,n.int)(0),(0,n.int)(zw+3),j,E,D).lessThan(.5))).toVar(),m.negate(),m).toVar();N.assign(Yf(g,Ye(A,(0,n.int)(0),(0,n.int)(zw+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(bl(p,g)),P.assign(i.xyz.mul(f).mul(Math.PI).div(v)),F.assign(qw((0,n.float)(1).div(y))),I.assign(qw(_.div(y))),ee.assign(_),z.assign(!0)})}).ElseIf(ne.equal((0,n.int)(cT.ENVIRONMENT)),()=>{let e=Hf(v,y,b,Ye(A,(0,n.int)(0),(0,n.int)(zw+5),j,E,D)),t=e.direction.toVar(),r=e.pdf.toVar(),i=Wf({tex:_,samp:(0,n.sampler)(_),direction:t,environmentMatrix:y,environmentIntensity:g,enableEnvironmentLight:(0,n.float)(1)}).xyz.toVar(),a=ae(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(qw(r.div(o))),I.assign(qw((0,n.float)(1).div(o))),L.assign((0,n.int)(-1-cT.ENVIRONMENT)),z.assign(!0)})}).ElseIf(ne.greaterThanEqual((0,n.int)(cT.LAMPS)),()=>{let e=lT(T,ne).toVar(),t=dT(T,ne).toVar(),r=fT(T,ne,t).toVar();L.assign((0,n.int)(-1).sub(ne));let i=(0,n.float)(0).toVar(),a=(0,n.vec3)(0).toVar(),o=Ye(A,(0,n.int)(0),(0,n.int)(zw+2),j,E,D).toVar();(0,n.If)(t.equal((0,n.int)(0)),()=>{let t=mm.wrap(bm(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=Iw(t).toVar();o.assign(Am(o,t.angle.mul(.5),Ye(A,(0,n.int)(0),(0,n.int)(zw+5),j,E,D))),a.divAssign(e),i.divAssign(e)});let s=ae(o);i.mulAssign(s.pdf),M.assign(s.start),N.assign(o.negate())}).ElseIf(t.equal((0,n.int)(1)),()=>{let t=hm.wrap(xm(S,r)),s=t.shape.greaterThan(.5),c=Ye(A,(0,n.int)(0),(0,n.int)(zw+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(Yf(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)),kh(t).mul(Oh(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(qw(d.div((0,n.max)(i,1e-30))))}).ElseIf(t.equal((0,n.int)(2)),()=>{let t=gm.wrap(Sm(C,r));M.assign(t.position),N.assign(Am((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=_m.wrap(Cm(w,r));M.assign(t.position),N.assign(Am(t.direction,t.angle,o));let s=N.negate();a.assign(t.color.mul(t.intensity).mul(Em({coneCosine:(0,n.cos)(t.angle),blend:t.penumbra,angleCosine:(0,n.dot)(N,t.direction)})).mul(Dm(t,s)).mul(km(t,s))),i.assign(e.div(Fw(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(qw((0,n.float)(1).div(i))),z.assign(!0)})}),(0,n.If)(z.not(),()=>{Hu(t,e,N,(0,n.uint)(0)),(0,n.Return)()});let oe=(0,n.max)((0,n.max)((0,n.max)(P.x,P.y),P.z),1e-20).toVar();Vu(t,e,M,(0,n.int)(0),(0,n.int)(0)),Hu(t,e,N,(0,n.uint)(Id.ACTIVE|Id.REDIRECTED|Id.LIGHT_PATH|Id.LIGHT_EMITTED)),Uu(t,e,P.div(oe),(0,n.float)(0)),Wu(t,e,(0,n.vec4)((0,n.vec3)(0),(0,n.float)(1))),gd(t,e,(0,n.uint)(0),(0,n.uint)(O),(0,n.float)(1),(0,n.float)(1),(0,n.float)(1)),td(r,e,j,F,I),fd(r,e,L,R,ee,oe)})}cu(),Od();function jT(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)(Ad.ENTERING_COUNT)))),()=>{(0,n.Return)()});let w=i.element(e).toVar(),T=nd(w);(0,n.If)(ad(r,T).notEqual(_),()=>{(0,n.Return)()});let E=ld(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=Le({state:Qu(r,w).bitXor((0,n.uint)(2654435769))}).toVar(),P=Xe(j,(0,n.int)(0),M.add((0,n.int)(16)),N,l,u).toVar(),F=Xe(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)(ud(r,rd(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 R=(0,n.min)((0,n.int)((0,n.float)(L).mul(F)),L.sub((0,n.int)(1))).toVar(),ee=ld(r,rd(I.add((0,n.uint)(R)))),z={...ee,vm:S?.(ee.position)??null},te=z.position.sub(D.position).toVar(),ne=(0,n.max)((0,n.dot)(te,te),1e-12).toVar(),re=te.div((0,n.sqrt)(ne)).toVar(),ie=(0,n.dot)(re,D.N).toVar(),ae=(0,n.dot)(re,D.facetN).toVar(),oe=(0,n.dot)(re,z.facetN).negate().toVar(),se=ie.greaterThan(0).and(ae.greaterThan(0)).and(oe.greaterThan(0)),ce=ie.lessThan(0).and(ae.lessThan(0)),B=oe.lessThan(0);(0,n.If)((C?ce.or(ie.greaterThan(0).and(ae.greaterThan(0))).and(B.or(oe.greaterThan(0))):se).not(),()=>{(0,n.Return)()});let le=pT(D.materialIndex,D.uv,D.N,c),ue=pT(z.materialIndex,z.uv,z.N,c),de=re.negate();C&&(0,n.If)(ce.and(le.diffuseTransmission.lessThanEqual(0)).or(B.and(ue.diffuseTransmission.lessThanEqual(0))),()=>{(0,n.Return)()});let fe=e=>C?mT(D.N,e,le):D.N,pe=e=>C?mT(z.N,e,ue):z.N,me=pm(D.V,re,D.N,le).toVar(),he=pm(de,z.V,pe(de),ue).toVar(),ge=(C?(0,n.abs)(ie):ie).mul(hT(z.V,z.N,z.facetN,de)).div(ne),_e=Ih(D.V,re,D.N,le),ve=Ih(re,D.V,fe(re),le),V=Ih(z.V,de,z.N,ue),ye=Ih(de,z.V,pe(de),ue),be=Zw(_e.mul(C?(0,n.abs)(oe):oe).div(ne),z,ye),xe=Zw(V.mul(C?(0,n.abs)(ae):ae).div(ne),D,ve),Se=O.add(R).add((0,n.int)(1)),H=iT(v,rT.CONNECT,nT(be,xe),(0,n.float)(1).div((0,n.float)(Se.sub((0,n.int)(1))))),Ce=Xh(D.throughput.mul(me).mul(he).mul(z.throughput).mul(ge.mul(H).mul((0,n.float)(L)).mul(b)),(0,n.float)(Se.sub((0,n.int)(1))),x,(0,n.int)(d)).toVar();(0,n.If)(Rl(Ce).greaterThan(0),()=>{let e=bl(D.position,C?(0,n.select)(ce,D.facetN.negate(),D.facetN):D.facetN).toVar(),r=bl(z.position,C?(0,n.select)(B,z.facetN.negate(),z.facetN):z.facetN).sub(e).toVar(),i=(0,n.length)(r).toVar(),a=th(e,r.div(i),i.mul(xl),Df,o,s,c);(0,n.If)(a.greaterThan(0),()=>{let e=ju(t,w).toVar();Wu(t,w,(0,n.vec4)(e.xyz.add(Ce.mul(a)),e.w))})})})}cu(),Od();var MT=4294967295,NT=1024,PT=Math.log2(1.25),FT=(e,t)=>(0,n.int)((0,n.max)((0,n.floor)((0,n.log2)(t.div(e.mergeMin)).div(PT)),0)),IT=(e,t)=>e.mergeMin.mul((0,n.exp2)((0,n.float)(t.add((0,n.int)(1))).mul(PT))).mul(2).div((0,n.max)((0,n.float)(1).sub(e.mergeSlope),.5)),LT=(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),RT=(e,t)=>{let r=FT(e,Qw(e,t)).toVar();return{shell:r,cell:(0,n.ivec3)((0,n.floor)(t.div(IT(e,r)))).toVar()}};function zT({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)(MT))})})().compute(Math.ceil(t/256)*256,[256])}function BT({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(ud(e,rd(c.sub(l)),o)),()=>{(0,n.Return)()});let u=rd(c),{shell:d,cell:f}=RT(r,od(e,u)),p=LT(d,f,s);cd(e,u,(0,n.atomicFunc)(`atomicExchange`,t.element(p),c))})}function VT(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)(Ad.ENTERING_COUNT)))),()=>{(0,n.Return)()});let v=i.element(e).toVar(),y=nd(v);(0,n.If)(ad(r,y).notEqual(m),()=>{(0,n.Return)()});let b=ld(r,y),x=(0,n.int)(b.extra).toVar(),S=(0,n.int)(l).add((0,n.int)(1)).sub(x).toVar(),C=pT(b.materialIndex,b.uv,b.N,s),w=(0,n.vec3)(0).toVar(),T=Qw(c,b.position).toVar(),E=T.mul(T).toVar(),D=$w(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=FT(c,(0,n.max)(c.mergeConst.add(c.mergeSlope.mul((0,n.max)(A.sub(T),0))),c.mergeMin)).toVar(),M=(0,n.min)(FT(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=IT(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(LT(t,s,_))).toVar(),m=(0,n.int)(0).toVar();(0,n.Loop)(l.notEqual((0,n.uint)(MT)).and(m.lessThan((0,n.int)(NT))),()=>{let e=rd(l),i=od(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=RT(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=ld(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=pm(b.V,t.V,b.N,C),r=tT(t,Ih(b.V,t.V,b.N,C),k),s=p?mT(b.N,t.V,C):b.N,c=tT(b,Ih(t.V,b.V,s,C),k),l=x.add(o),m=iT(g,rT.MERGE,nT(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(Xh(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(sd(r,e)),m.addAssign((0,n.int)(1))})}),(0,n.If)(Rl(w).greaterThan(0),()=>{let e=ju(t,v).toVar();Wu(t,v,(0,n.vec4)(e.xyz.add(w),e.w))})})}cu(),Od();function HT(e){let{hitBufferRO:t,splatBuffer:r,bvhBuffer:i,triangleBuffer:a,materialBuffer:o,lightPaths:s,slotsPerPath:c,lightTag:l,strategyView:u,cameraPosition:d,cameraForward:f,cameraViewMatrix:p,cameraProjectionMatrix:m,pixelArea:h,renderWidth:g,renderHeight:_,globalIlluminationIntensity:v,fireflyThreshold:y,accumFrame:b,frame:x,mergeVm:S=null,diffuseTransmission:C=!0}=e;return(0,n.Fn)(()=>{let e=n.instanceIndex.toVar();(0,n.If)(e.greaterThanEqual(s.mul(c)),()=>{(0,n.Return)()});let w=e.mod(c).toVar(),T=ud(t,rd(e.sub(w)),l);(0,n.If)(w.greaterThanEqual(T),()=>{(0,n.Return)()});let E=ld(t,rd(e)),D={...E,vm:S?.(E.position)??null},O=d.sub(D.position).toVar(),k=(0,n.max)((0,n.dot)(O,O),1e-12).toVar(),A=O.div((0,n.sqrt)(k)).toVar(),j=(0,n.dot)(A,D.facetN).toVar(),M=(0,n.dot)(A,f).negate().toVar(),N=j.lessThan(0),P=C?(0,n.select)(N,D.extra.bitAnd((0,n.uint)(2)),D.extra.bitAnd((0,n.uint)(1))).notEqual((0,n.uint)(0)):D.extra.notEqual((0,n.uint)(0));(0,n.If)((C?j.equal(0):j.lessThanEqual(0)).or(M.lessThanEqual(1e-6)).or(P),()=>{(0,n.Return)()});let F=m.mul(p.mul((0,n.vec4)(D.position,1))).toVar();(0,n.If)(F.w.lessThanEqual(0),()=>{(0,n.Return)()});let I=(0,n.floor)(F.x.div(F.w).mul(.5).add(.5).mul((0,n.float)(g))).toVar(),L=(0,n.floor)((0,n.float)(.5).sub(F.y.div(F.w).mul(.5)).mul((0,n.float)(_))).toVar();(0,n.If)(I.lessThan(0).or(L.lessThan(0)).or(I.greaterThanEqual((0,n.float)(g))).or(L.greaterThanEqual((0,n.float)(_))),()=>{(0,n.Return)()});let R=pT(D.materialIndex,D.uv,D.N,o);C&&(0,n.If)(N.and(R.diffuseTransmission.lessThanEqual(0)),()=>{(0,n.Return)()});let ee=C?mT(D.N,A,R):D.N,z=pm(A,D.V,ee,R).toVar(),te=(0,n.float)(1).div(h.mul(M).mul(M).mul(M)).div(k).toVar(),ne=Zw(te.mul(C?(0,n.abs)(j):j).div((0,n.float)(s)),D,Ih(A,D.V,ee,R)),re=w.add((0,n.uint)(1)),ie=(0,n.float)(1).toVar();(0,n.If)(re.greaterThan((0,n.uint)(1)),()=>{ie.assign(v)});let ae=Xh(D.throughput.mul(z).mul(hT(D.V,D.N,D.facetN,A)).mul(te.div((0,n.float)(s)).mul(iT(u,rT.LIGHT_TRACE,nT(ne,(0,n.float)(0)))).mul(ie)),(0,n.float)(w),y,(0,n.int)(b)).toVar(),oe=bl(D.position,C?(0,n.select)(N,D.facetN.negate(),D.facetN):D.facetN).toVar(),se=d.sub(oe).toVar(),ce=(0,n.length)(se).toVar(),B=th(oe,se.div(ce),ce.mul(xl),Of,i,a,o);(0,n.If)(B.greaterThan(0),()=>{let t=(0,n.min)(Ml(ae.mul(B)),(0,n.vec3)(Hw)).mul(Vw).toVar(),i=(0,n.float)(Le({state:e.bitXor((0,n.uint)(x).mul((0,n.uint)(2654435769)))}).shiftRight((0,n.uint)(8))).mul(1/16777216).toVar(),a=(0,n.uint)(L).mul((0,n.uint)(g)).add((0,n.uint)(I)).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 UT(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=ju(t,o).toVar();Wu(t,o,(0,n.vec4)(e.xyz.add((0,n.vec3)((0,n.float)(l),(0,n.float)(u),(0,n.float)(d)).div(Vw)),e.w))})})})}O(),Od(),at(),Pt();var{PASS_TAG_BIT:WT,STRATEGY:GT,STRATEGY_ALONE:KT,SOURCE:qT,mergeVmAt:JT}=Rw,YT={...Rw,...Dw,guidedDiscPdf:TT,recordEscape:DT},XT=256*1024*1024,ZT=.05,QT=.5,$T=(1<<24)-1,eE=1,tE=.75,nE=.25,rE=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:YT,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(qT.LAMPS),`float`),sourceCount:qT.LAMPS,sourceOffsets:[qT.LAMPS,qT.LAMPS,qT.LAMPS,qT.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)(nE,`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(XT,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)&&(_u(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&&(_u(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,_T,16,r.RedFormat,r.FloatType),this._guideTexture.source.dataReady=!1,this._guideTexture.needsUpdate=!0,this._guideBuildAttr=v(vT*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)(Ad.ACTIVE_ENERGY)))),(0,n.atomicStore)(a.element((0,n.uint)(Ad.ENTERING_COUNT)),e)};if(t.register(`lightSnapshot`,(0,n.Fn)(()=>{C((0,n.atomicLoad)(a.element((0,n.uint)(Ad.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)(Ad.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`,kT({counters:a})),t.register(`guideBuild`,OT({counters:a,out:(0,n.storage)(this._guideBuildAttr,`float`)})),t.register(`lightGenerate`,f(AT({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(jT({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=>JT(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`,zT({head:e,hashSize:this._mergeHeadAttr.count})),t.register(`mergeInsert`,BT({hitBufferRW:i.hitBuffer.rw,head:e,bidirectional:x})().compute([Math.ceil(this._lightCacheSlots/256),1,1],[256,1,1])),t.register(`merge`,f(VT({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(HT({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,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=>JT(x,e):null,diffuseTransmission:b})()).compute([Math.ceil(this._lightCacheSlots/256),1,1],[256,1,1])),t.register(`splatResolve`,UT({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(){_u(this.pt.renderer,this._splatAttr),this._splatAttr=null,_u(this.pt.renderer,this._mergeHeadAttr),this._mergeHeadAttr=null,this._disposeLightGuide()}setBidirectionalStrategy(e=`all`,{alone:t=!1}={}){let n={all:GT.ALL,hit:GT.HIT,nee:GT.NEE,connect:GT.CONNECT,lightTrace:GT.LIGHT_TRACE,merge:GT.MERGE}[e]??GT.ALL;this.uniforms.strategyView.value=n===GT.ALL?n:n+(t?KT:0)}setMergeRadius(e=eE){this._mergeRadiusPixels=Math.max(e,.001)}setMergeTrust(e=nE){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*QT),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%$T+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===tt.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)**((tE-1)/2),i=this.pt.cameraProjection.value,a=this.pt.cameraProjectionMatrix.value.elements,o=0,s=0;i===tt.orthographic?s=r*2/(a[5]*t):o=i===tt.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=qT.LAMPS;[`directional`,`area`,`point`,`spot`].forEach((n,r)=>{e.sourceOffsets[r]=t,t+=this.pt[`${n}LightsBufferNode`].array.length/st[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:st[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*ZT:0;if(o&&s&&(n[qT.ENVIRONMENT]=Math.max(s.radianceIntegral,0)*this.pt.environmentIntensity.value*u),this.pt.emissiveTriangleCount.value>0&&(n[qT.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[qT.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(qT.SUN),e.emitterPick.value=g(qT.EMITTERS),e.envPick.value=g(qT.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]!==wt.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:vT*4,rowsPerImage:16},{texture:r.get(this._guideTexture).texture},[_T,16]),r.device.queue.submit([i.finish()]),e.guide.value=1}_disposeLightGuide(){_u(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,(WT|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 o_)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 iE(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}ai(),Oe();var aE=_e(`ocio`);function oE(e){let t=String(e);/\[OpenColorIO Error\]/.test(t)?aE.error(t):/\[OpenColorIO Warning\]/.test(t)?aE.warn(t):aE.debug(t)}var sE=null,cE=null,lE=null,uE=null,dE=null;async function fE(){let{ocioRuntimeFactory:e,ocioRuntimeUrl:t}=ni();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 pE(){return cE||(sE||=(async()=>{let e=await fE();if(typeof e.createOcioRuntime!=`function`)throw Error(`OCIO module has no createOcioRuntime() — wrong package or version`);let{ocioWasmUrl:t}=ni();return cE=await e.createOcioRuntime({...t?{wasmUrl:t}:{},moduleOptions:{print:oE,printErr:oE}}),cE})().catch(e=>{throw sE=null,e}),await sE)}async function mE(){return(await pE()).ocio.listBuiltinConfigs()}async function hE({builtin:e,text:t,files:n=[],configPath:r=`config.ocio`,id:i}={}){let a=await pE();if(e)lE=a.loadBuiltinConfig(e),uE=e,dE=xE(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`);lE=a.loadConfigPackage({configRelativePath:r,files:e},i?{id:i}:void 0),uE=i??lE.id;let o=e.find(e=>e.relativePath===r);dE=o?new TextDecoder().decode(o.data):null}return bE()}function gE(){lE=null,uE=null,dE=null}function _E(){return lE!==null}function vE(){return lE?cE:null}function yE(){return lE}function bE(){if(!lE)return null;let e=Object.fromEntries(lE.roles.map(e=>[e.name,e.colorSpace]));return{id:uE,name:dE?.match(/^name:\s*(\S.*?)\s*$/m)?.[1]??null,ocioVersion:lE.ocioVersion,version:lE.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:lE.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:lE.displays.slice(),defaultDisplay:lE.defaultDisplay,views:Object.fromEntries(Object.entries(lE.viewsByDisplay).map(([e,t])=>[e,t.map(e=>({name:e.name,transform:e.transform,colorSpace:e.colorSpace,looks:e.looks,description:e.description}))])),defaultViews:{...lE.defaultViewsByDisplay},looks:lE.looks.map(e=>({name:e.name,processSpace:e.processSpace,description:e.description,forward:e.hasForwardTransform,inverse:e.hasInverseTransform})),namedTransforms:lE.namedTransforms.map(e=>e.name),fileRules:lE.fileRules.map(e=>({index:e.index,name:e.name,colorSpace:e.colorSpace,pattern:e.pattern,extension:e.extension,regex:e.regex})),contextVariables:SE()}}function xE(e,t){try{return e.ocio.getBuiltinConfigYaml(t)}catch{return null}}function SE(){if(!dE)return[];let e=new Map,t=dE.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 dE.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 CE(){gE(),cE?.dispose?.(),cE=null,sE=null}var wE=1<<20,TE=new Map,EE=new Map,DE=4096,OE=new Map;function kE(e,t,n){return`${e}\u0000${t}\u0000${n?JSON.stringify(n):``}`}function AE(){for(let e of TE.values())e.dispose?.();TE.clear(),EE.clear(),OE.clear()}function jE(e,t,{context:n=null}={}){if(!vE()||e===t)return null;let r=kE(e,t,n),i=TE.get(r);if(i!==void 0)return i;try{i=FE().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 TE.set(r,i),i}var ME=null,NE=null,PE=!1;function FE(){let e=vE();if(!e)throw Error(`no OCIO config loaded`);if(e.config)return e.config;let t=yE();if(ME&&NE===t.id)return ME;if(PE&&ME?.dispose?.(),!t.id?.startsWith(`ocio://`))throw Error(`OCIO runtime exposes no Config handle for this config`);return ME=e.ocio.createBuiltinConfig(t.id),PE=!0,NE=t.id,ME}function IE(){PE&&ME?.dispose?.(),ME=null,NE=null,PE=!1,AE()}function LE(e,t,n,{context:r=null}={}){let i=vE();if(!i||t===n)return[e[0],e[1],e[2]];let a=`${kE(t,n,r)}\u0000${e[0]},${e[1]},${e[2]}`,o=EE.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 EE.size>=DE&&EE.clear(),EE.set(a,s),s.slice()}function RE(e,t,n,{context:r=null}={}){if(e.length%4!=0)throw Error(`convertPixelsF32 wants 4 floats per pixel`);let i=jE(t,n,{context:r});if(!i)return e;let a=e.length/4;if(a<=wE)return i.applyRGBAF32(e),e;for(let t=0;t<a;t+=wE){let n=Math.min(wE,a-t);i.applyRGBAF32(e.subarray(t*4,(t+n)*4))}return e}var zE=.055;function BE(e){return e<=.04045?e/12.92:((e+zE)/(1+zE))**2.4}function VE(e){return e<=0?0:e<=.0031308?12.92*e:(1+zE)*e**(1/2.4)-zE}var HE=new Float32Array(256);for(let e=0;e<256;e++)HE[e]=BE(e/255);var UE=new Float32Array(256);for(let e=0;e<256;e++)UE[e]=e/255;function WE(e){return e===`srgb`?HE:UE}function GE(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=jE(t,n,{context:r});if(!o)return e;let s=e.length/4,c=WE(i),l=a===`srgb`?JE:YE,u=new Float32Array(Math.min(wE,s)*4);for(let t=0;t<s;t+=wE){let n=Math.min(wE,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 KE=65536,qE=new Uint8Array(KE+1);for(let e=0;e<=KE;e++){let t=e/KE;qE[e]=Math.round(VE(t*t)*255)}function JE(e){return e>0?e>=1?255:qE[Math.sqrt(e)*KE+.5|0]:0}function YE(e){return e>0?e>=1?255:e*255+.5|0:0}function XE(e,t,n=`srgb`){if(!t)return e;let r=WE(n),i=n===`srgb`?JE:YE,[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 ZE(e,t,{context:n=null,tolerance:r=1e-4}={}){if(!vE())return null;if(e===t)return[1,0,0,0,1,0,0,0,1];let i=kE(e,t,n);if(OE.has(i))return OE.get(i);let a=jE(e,t,{context:n});if(!a)return OE.set(i,[1,0,0,0,1,0,0,0,1]),OE.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 OE.set(i,f),f}function QE(e){let t=yE();if(!t)return!1;let n=t.colorSpaces.find(t=>t.name===e||t.aliases?.includes(e));return n?n.isData:!1}function $E(e){let t=yE();return!t||!e?!1:t.colorSpaces.some(t=>t.name===e||t.aliases?.includes(e))}var eD=1e-10;function tD(e,t,n,r){return e<=0?0:2**(n+e/(t-1)*(r-n))}function nD(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 rD({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]=tD(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 iD(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 aD(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 oD=null;function sD(){if(!oD){let e=new Uint16Array(65536);for(let t=0;t<65536;t++)e[t]=t;oD=aD(e)}return oD}function cD(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 lD({data:e,size:t,minEv:n,maxEv:r}){let i=t*t,a=t-1,o=e instanceof Uint16Array,s=o?sD():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=nD(e,t,n,r),u=nD(i,t,n,r),d=nD(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}=cD(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 uD({fnName:e,texName:t,size:n,minEv:r,maxEv:i}){let a=e=>Number.isInteger(e)?`${e}.0`:String(e);return`
|
|
1407
1407
|
fn ${e}_shape( v: vec3<f32> ) -> vec3<f32> {
|
|
1408
1408
|
let ev = log2( max( v, vec3<f32>( 1e-10 ) ) );
|
|
1409
1409
|
let t = ( ev - vec3<f32>( ${a(r)} ) ) / ${a(i-r)};
|