rayzee 7.9.0 → 7.9.2
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/README.md +1 -1
- package/dist/rayzee.es.js +10 -6
- package/dist/rayzee.es.js.map +1 -1
- package/dist/rayzee.umd.js +1 -1
- package/dist/rayzee.umd.js.map +1 -1
- package/package.json +1 -1
- package/src/Stages/NormalDepth.js +5 -2
- package/src/Stages/PathTracer.js +35 -2
package/dist/rayzee.umd.js
CHANGED
|
@@ -666,7 +666,7 @@
|
|
|
666
666
|
let ndcDepth = clipPos.z / clipPos.w * 0.5f + 0.5f;
|
|
667
667
|
return clamp( ndcDepth, 0.0f, 1.0f );
|
|
668
668
|
}
|
|
669
|
-
`),Ls=(0,n.Fn)(([e,t,r,i,a,o,s,c,l,u,d,f,p,m,h,g])=>{let _=(0,n.vec4)(1,0,1,1).toVar(),v=Dt({origin:e,direction:t}),y=jt.wrap(oo(v,r,i).toVar());return(0,n.If)(u.equal((0,n.int)(7)),()=>{let e=(0,n.float)(y.triTests).div(d);_.assign((0,n.select)(e.lessThan(1),(0,n.vec4)((0,n.vec3)(e),1),(0,n.vec4)(1,0,0,1)))}),(0,n.If)(u.equal((0,n.int)(8)),()=>{let e=(0,n.float)(y.boxTests).div(d);_.assign((0,n.select)(e.lessThan(1),(0,n.vec4)((0,n.vec3)(e),1),(0,n.vec4)(1,0,0,1)))}),(0,n.If)(u.equal((0,n.int)(10)),()=>{(0,n.If)(l,()=>{let e=go({tex:o,samp:(0,n.sampler)(o),direction:t,environmentMatrix:s,environmentIntensity:c,enableEnvironmentLight:l}).toVar(),r=(0,n.dot)(e.xyz,Xt).toVar(),i=r,a=(0,n.max)(d.mul(.1),.001),u=r.div(a),m=(0,n.log)(r.add(1e-6)).add(10).div(10),h=(0,n.select)(d.greaterThan(1),u,m).toVar(),g=(0,n.vec3)(0).toVar();(0,n.If)(h.lessThan(.2),()=>{g.assign((0,n.mix)((0,n.vec3)(0,0,0),(0,n.vec3)(0,0,.5),h.mul(5)))}).ElseIf(h.lessThan(.4),()=>{g.assign((0,n.mix)((0,n.vec3)(0,0,.5),(0,n.vec3)(0,0,1),h.sub(.2).mul(5)))}).ElseIf(h.lessThan(.6),()=>{g.assign((0,n.mix)((0,n.vec3)(0,0,1),(0,n.vec3)(0,1,0),h.sub(.4).mul(5)))}).ElseIf(h.lessThan(.8),()=>{g.assign((0,n.mix)((0,n.vec3)(0,1,0),(0,n.vec3)(1,1,0),h.sub(.6).mul(5)))}).ElseIf(h.lessThan(1),()=>{g.assign((0,n.mix)((0,n.vec3)(1,1,0),(0,n.vec3)(1,0,0),h.sub(.8).mul(5)))}).Else(()=>{g.assign((0,n.mix)((0,n.vec3)(1,0,0),(0,n.vec3)(1,1,1),(0,n.min)(h.sub(1),1)))});let v=f.div(p);(0,n.If)(v.x.lessThan(.1).and(v.y.lessThan(.1)),()=>{let e=i.mul(1);g.assign((0,n.vec3)(e))}).ElseIf(v.x.greaterThan(.9).and(v.y.lessThan(.1)),()=>{g.assign(e.xyz.mul(1))}),_.assign((0,n.vec4)(g,1))}).Else(()=>{_.assign((0,n.vec4)(1,0,1,1))})}),(0,n.If)(u.equal((0,n.int)(4)),()=>{(0,n.If)(y.didHit.not(),()=>{_.assign((0,n.vec4)(0,0,0,1))}).Else(()=>{let t=Ot.wrap(pn(y.materialIndex,a)).toVar(),r=Lt.wrap(Tr(t,y.uv,y.normal)).toVar().emissive.toVar(),i=(0,n.length)(r).toVar();(0,n.If)(i.greaterThan(0),()=>{let t=r.div((0,n.max)(i.mul(.1),.001)).toVar(),a=(0,n.length)(e.sub(y.hitPoint)),o=(0,n.clamp)((0,n.float)(1).sub(a.div(10)),0,1),s=(0,n.mix)(t,t.mul((0,n.vec3)(1,.8,.6)),o.mul(.3));_.assign((0,n.vec4)(s,1))}).Else(()=>{_.assign((0,n.vec4)(0,0,.1,1))})})}),(0,n.If)(u.equal((0,n.int)(1)),()=>{(0,n.If)(y.didHit.not(),()=>{_.assign((0,n.vec4)(.5,.5,1,1))}).Else(()=>{let e=Ot.wrap(pn(y.materialIndex,a)).toVar(),t=(0,n.normalize)(Lt.wrap(Tr(e,y.uv,y.normal)).toVar().normal);_.assign((0,n.vec4)(Fs({normal:t}),1))})}),(0,n.If)(u.equal((0,n.int)(2)),()=>{(0,n.If)(y.didHit.not(),()=>{_.assign((0,n.vec4)((0,n.vec3)(1),1))}).Else(()=>{let e=Is({worldPos:y.hitPoint,cameraProjectionMatrix:m,cameraViewMatrix:h});_.assign((0,n.vec4)(Ps({depth:e}),1))})}),(0,n.If)(u.equal((0,n.int)(3)),()=>{(0,n.If)(y.didHit.not(),()=>{_.assign((0,n.vec4)(0,0,0,1))}).Else(()=>{let e=Ot.wrap(pn(y.materialIndex,a)).toVar(),t=Lt.wrap(Tr(e,y.uv,y.normal)).toVar().albedo.rgb;_.assign((0,n.vec4)(t,1))})}),(0,n.If)(u.equal((0,n.int)(5)),()=>{(0,n.If)(y.didHit.not(),()=>{_.assign((0,n.vec4)(0,0,0,1))}).Else(()=>{let e=Ot.wrap(pn(y.materialIndex,a)).toVar(),t=Lt.wrap(Tr(e,y.uv,y.normal)).toVar(),u=t.albedo.rgb,d=(0,n.normalize)(t.normal).toVar(),p=ie({state:ae({seed:(0,n.uint)(f.x).mul((0,n.uint)(1973)).add((0,n.uint)(f.y).mul((0,n.uint)(9277))).add(g.mul((0,n.uint)(26699)))})}).toVar(),m=Ln({N:d,xi:(0,n.vec2)(P(p).toVar(),P(p).toVar())}).toVar(),h=Dt({origin:y.hitPoint.add(d.mul(.001)),direction:m}),v=jt.wrap(oo(h,r,i).toVar()),b=(0,n.vec3)(0).toVar();(0,n.If)(v.didHit.not(),()=>{(0,n.If)(l,()=>{b.assign(go({tex:o,samp:(0,n.sampler)(o),direction:m,environmentMatrix:s,environmentIntensity:c,enableEnvironmentLight:l}).xyz)})}).Else(()=>{let e=Ot.wrap(pn(v.materialIndex,a)).toVar(),t=Lt.wrap(Tr(e,v.uv,v.normal)).toVar();b.assign(t.emissive),(0,n.If)(l,()=>{let e=(0,n.normalize)(t.normal).toVar(),r=go({tex:o,samp:(0,n.sampler)(o),direction:e,environmentMatrix:s,environmentIntensity:c,enableEnvironmentLight:l}).xyz;b.addAssign(t.albedo.rgb.mul(r))})});let x=u.mul(b);_.assign((0,n.vec4)(x,1))})}),(0,n.If)(u.equal((0,n.int)(6)),()=>{(0,n.If)(y.didHit,()=>{let e=y.normal.toVar(),r=(0,n.normalize)(t.sub(e.mul((0,n.dot)(t,e).mul(2)))).toVar(),i=go({tex:o,samp:(0,n.sampler)(o),direction:r,environmentMatrix:s,environmentIntensity:c,enableEnvironmentLight:l}).xyz,a=i.div(i.add(1));_.assign((0,n.vec4)(a,1))}).Else(()=>{let e=go({tex:o,samp:(0,n.sampler)(o),direction:t,environmentMatrix:s,environmentIntensity:c,enableEnvironmentLight:l}).xyz,r=e.div(e.add(1));_.assign((0,n.vec4)(r,1))})}),_});function Rs(e){let{writeColorTex:t,writeNDTex:r,writeAlbedoTex:i,resolution:a,renderWidth:o,renderHeight:s,cameraWorldMatrix:c,cameraProjectionMatrixInverse:l,cameraProjectionMatrix:u,cameraViewMatrix:d,enableDOF:f,focalLength:p,aperture:m,focusDistance:h,sceneScale:g,apertureScale:_,anamorphicRatio:v,bvhBuffer:y,triangleBuffer:b,materialBuffer:x,envTexture:S,environmentMatrix:C,environmentIntensity:w,enableEnvironmentLight:T,visMode:E,debugVisScale:D,frame:O}=e;return(0,n.Fn)(()=>{let e=(0,n.int)(n.workgroupId.x).mul(16).add((0,n.int)(n.localId.x)),k=(0,n.int)(n.workgroupId.y).mul(16).add((0,n.int)(n.localId.y));(0,n.If)(e.lessThan(o).and(k.lessThan(s)),()=>{let o=(0,n.vec2)((0,n.float)(e).add(.5),(0,n.float)(k).add(.5)),s=ie({state:(0,n.uint)(k.mul((0,n.int)(a.x)).add(e)).add((0,n.uint)(1))}).toVar(),A=o.div(a).mul(2).sub(1).toVar();A.y.assign(A.y.negate());let j=Dt.wrap(co(A,s,c,l,f,p,m,h,g,_,v)),M=(0,n.vec4)(1,0,1,1).toVar();(0,n.If)(E.equal((0,n.int)(9)),()=>{let e=he(o,(0,n.int)(0),(0,n.int)(1),s,a,O);M.assign((0,n.vec4)(e,1,1))}).Else(()=>{M.assign(Ls(j.origin,j.direction,y,b,x,S,C,w,T,E,D,o,a,u,d,O))});let N=(0,n.uvec2)((0,n.uint)(e),(0,n.uint)(k));(0,n.textureStore)(t,N,M).toWriteOnly(),(0,n.textureStore)(r,N,(0,n.vec4)(.5,.5,1,1)).toWriteOnly(),(0,n.textureStore)(i,N,(0,n.vec4)(M.xyz,1)).toWriteOnly()})})}function zs({sortGlobalHistogram:e,bins:t=256}){return(0,n.Fn)(()=>{(0,n.If)(n.instanceIndex.lessThan((0,n.uint)(t)),()=>{(0,n.atomicStore)(e.element(n.instanceIndex),(0,n.uint)(0))})})}function Bs({hitBufferRO:e,activeIndicesReadRO:t,sortGlobalHistogram:r,counters:i,bins:a=256}){return(0,n.Fn)(()=>{let o=n.instanceIndex,s=n.localId.x,c=T(`uint`,a);(0,n.If)(s.lessThan((0,n.uint)(a)),()=>{(0,n.atomicStore)(c.element(s),(0,n.uint)(0))}),(0,n.workgroupBarrier)();let l=(0,n.atomicLoad)(i.element((0,n.uint)(Ba.ENTERING_COUNT)));(0,n.If)(o.lessThan(l),()=>{let r=(0,n.uint)(Aa(e,t.element(o))).clamp((0,n.uint)(0),(0,n.uint)(a-1));(0,n.atomicAdd)(c.element(r),(0,n.uint)(1))}),(0,n.workgroupBarrier)(),(0,n.If)(s.lessThan((0,n.uint)(a)),()=>{let e=(0,n.atomicLoad)(c.element(s));(0,n.If)(e.greaterThan((0,n.uint)(0)),()=>{(0,n.atomicAdd)(r.element(s),e)})})})}function Vs({sortGlobalHistogram:e,bins:t=256}){return(0,n.Fn)(()=>{(0,n.If)(n.instanceIndex.equal((0,n.uint)(0)),()=>{let r=(0,n.uint)(0).toVar();(0,n.Loop)({start:(0,n.uint)(0),end:(0,n.uint)(t),type:`uint`},({i:t})=>{let i=e.element(t),a=(0,n.atomicLoad)(i);(0,n.atomicStore)(i,r),r.addAssign(a)})})})}function Hs({hitBufferRO:e,activeIndicesReadRO:t,sortedIndicesRW:r,sortGlobalHistogram:i,counters:a,bins:o=256}){return(0,n.Fn)(()=>{let s=n.instanceIndex,c=(0,n.atomicLoad)(a.element((0,n.uint)(Ba.ENTERING_COUNT)));(0,n.If)(s.lessThan(c),()=>{let a=t.element(s),c=(0,n.uint)(Aa(e,a)).clamp((0,n.uint)(0),(0,n.uint)(o-1)),l=(0,n.atomicAdd)(i.element(c),(0,n.uint)(1));r.element(l).assign(a)})})}var Us=class extends aa{constructor(e,t,r,i={}){super(e,t,r,i),this.name=`PathTracer`,this._packedBuffers=null,this._queueManager=null,this._kernelManager=null,this._gBufferAttr=null,this._wavefrontReady=!1,this._auxGBufferEnabled=!1,this._auxGBufferUniform=(0,n.uniform)(0,`uint`),this._useDynamicDispatch=!0,this._sortMaterials=!1,this._useSubgroupCompact=!1,this._lastBounceCounts=null,this._lastBounceCountsBudget=-1,this._readbackPending=!1,this._readbackEveryNFrames=4,this._readbackFrameCounter=0,this._readbackGeneration=0,this._bounceEarlyExitThreshold=100,this._wfRenderWidth=(0,n.uniform)(1920,`int`),this._wfRenderHeight=(0,n.uniform)(1080,`int`),this._wfMaxRayCount=(0,n.uniform)(0,`uint`),this._wfCurrentBounce=(0,n.uniform)(0,`int`),this.vramTracker=new Ja(this.renderer),this._registerVRAMProviders(),console.log(`PathTracer: initialized (wavefront)`)}_registerVRAMProviders(){let e=this.vramTracker;e.register(`rays`,()=>{let e=this._packedBuffers?._attrs;return e?[e.ray,e.rng,e.hit]:null}),e.register(`queues`,()=>{let e=this._queueManager;return e?[e._countersAttr,e._bounceCountsAttr,e._attrA,e._attrB,e._sortAttr]:null}),e.register(`gbuffer`,()=>this._gBufferAttr?[this._gBufferAttr]:null),e.register(`accum`,()=>{let e=this.storageTextures;return e?[e.writeColor,e.writeNormalDepth,e.writeAlbedo,e.readTarget]:null}),e.register(`geometry`,()=>[this.triangleStorageAttr,this.bvhStorageAttr,this.lightStorageAttr]),e.register(`materials`,()=>{let e=this.materialData;return e?[e.materialStorageAttr,...(e.srgbBuckets||[]).filter(Boolean),...(e.linearBuckets||[]).filter(Boolean)]:null}),e.register(`environment`,()=>{let e=this.environment;return e?[e.environmentTexture,e.envCDFTexture]:null})}setupMaterial(){super.setupMaterial(),this.materialData?.materialCount>0&&(this._kernelManager&&this._kernelManager.dispose(),this._wavefrontReady=!1,this._buildWavefrontKernels())}render(e){if(!this.isReady||!this._wavefrontReady)return;if(this.isComplete||this.frameCount>=this.completionThreshold){this.isComplete||=!0;return}this.performanceMonitor?.start();let t=this.frameCount,n=this.renderMode.value,r=null;n===1&&t===0&&(r=this.maxBounces.value,this.maxBounces.value=1),this._handleResize(),this.manageASVGFForRenderMode(n),e&&e.setState(`tileRenderingComplete`,!0),this.cameraChanged=this._updateCameraUniforms(),this.cameraOptimizer?.updateInteractionMode(this.cameraChanged),this._updateAccumulationUniforms(t,n),this.frame.value=t,this._setWfDispatch();let i=this.storageTextures.getReadTextures();this.shaderBuilder.prevColorTexNode&&(this.shaderBuilder.prevColorTexNode.value=i.color,this.shaderBuilder.prevAlbedoTexNode.value=i.albedo),this._refreshWfTextureNodes();let a=this._kernelManager;if((this.visMode?.value|0)>0&&this.visMode.value!==11){a.dispatch(`debug`),this.storageTextures.copyToReadTargets(this.renderer);let t=this.storageTextures.getReadTextures();e&&this._publishTexturesToContext(e,t),this._emitStateEvents(),this.cameraOptimizer?.isInInteractionMode()||this.frameCount++,r!==null&&(this.maxBounces.value=r),this.performanceMonitor?.end();return}a.dispatch(`resetCounters`),a.dispatch(`generate`),a.dispatch(`initActiveIndices`);let o=this.maxBounces.value,s=o+this.transmissiveBounces.value+this.maxSubsurfaceSteps.value,c=this._wfMaxRayCount.value,l=this._lastBounceCounts,u=l?o<=this._lastBounceCountsBudget?s+1:this._lastBounceCountsBudget:0;for(let e=0;e<=s;e++){this._wfCurrentBounce.value=e;let t=this._useDynamicDispatch;if(t){let t=c;if(e>0){let n=e-1,r;n<u&&l[n]!==void 0?r=l[n]:u>0&&(r=l[u-1]),t=r>0?r:c}let n=Math.min(c,Math.ceil(t*1.5)+1024),r=[Math.ceil(n/256),1,1];a.setDispatchCount(`extend`,r),a.setDispatchCount(`shade`,r),a.setDispatchCount(`globalHist`,r),a.setDispatchCount(`globalScatter`,r),a.setDispatchCount(`compact`,r),a.setDispatchCount(`compactCopyback`,r)}else{a.dispatch(`enterFull`);let e=[Math.ceil(c/256),1,1];a.setDispatchCount(`extend`,e),a.setDispatchCount(`shade`,e),a.setDispatchCount(`compact`,e),a.setDispatchCount(`globalHist`,e),a.setDispatchCount(`globalScatter`,e)}if(a.dispatch(`extend`),this._sortMaterials&&(a.dispatch(`resetGlobalHist`),a.dispatch(`globalHist`),a.dispatch(`globalPrefix`),a.dispatch(`globalScatter`)),a.dispatch(`shade`),a.dispatch(`resetActiveCounter`),a.dispatch(`compact`),t&&a.dispatch(`compactCopyback`),a.dispatch(`snapshotBounceCount`),e<u&&e<s&&l[e]!==void 0&&l[e]<=this._bounceEarlyExitThreshold)break}a.dispatch(`finalWrite`),this._maybeReadbackCounters(),this.storageTextures.copyToReadTargets(this.renderer,this._auxGBufferEnabled);let d=this.storageTextures.getReadTextures();e&&this._publishTexturesToContext(e,d),this._emitStateEvents(),this.cameraOptimizer?.isInInteractionMode()||this.frameCount++,r!==null&&(this.maxBounces.value=r),this.performanceMonitor?.end()}_handleResize(){let e=this.storageTextures.renderWidth,t=this.storageTextures.renderHeight;super._handleResize(),this._rebuildKernelsIfResized(e,t)}setAuxGBufferEnabled(e){e=!!e,this._auxGBufferEnabled!==e&&(this._auxGBufferEnabled=e,this._auxGBufferUniform.value=+!!e,this.reset())}setSize(e,t){let n=this.storageTextures.renderWidth,r=this.storageTextures.renderHeight;super.setSize(e,t),this._rebuildKernelsIfResized(n,r)}_maybeReadbackCounters(){if(this._readbackPending||(this._readbackFrameCounter++,this._readbackFrameCounter<this._readbackEveryNFrames))return;this._readbackFrameCounter=0;let e=this._queueManager?.getBounceCountsAttribute();if(!e)return;this._readbackPending=!0;let t=this._readbackGeneration,n=this.maxBounces.value;this.renderer.getArrayBufferAsync(e).then(e=>{t===this._readbackGeneration&&(this._lastBounceCounts=new Uint32Array(e.slice(0)),this._lastBounceCountsBudget=n),this._readbackPending=!1}).catch(e=>{console.warn(`Wavefront bounceCounts readback failed:`,e),this._readbackPending=!1})}_refreshWfTextureNodes(){let e=this._wfTexNodes;if(!e)return;let t=this.environment?.environmentTexture;t&&e.envTex&&(e.envTex.value=t),this.environment?.envCDFTexture&&e.envCDFTex&&(e.envCDFTex.value=this.environment.envCDFTexture);let n=this.materialData;n&&(mr(e.srgbBuckets,n.srgbBuckets),mr(e.linearBuckets,n.linearBuckets))}_rebuildKernelsIfResized(e,t){let n=this.storageTextures.renderWidth,r=this.storageTextures.renderHeight;if(n===e&&r===t||!(this.materialData?.materialCount>0))return;this._lastBounceCounts=null,this._lastBounceCountsBudget=-1,this._readbackFrameCounter=0,this._readbackGeneration++;let i=ua.requiredCapacity(n*r);!this._packedBuffers||i>this._packedBuffers.capacity?(this._kernelManager&&this._kernelManager.dispose(),this._wavefrontReady=!1,this._buildWavefrontKernels()):this._resizeWavefrontInPlace(n,r)}_resizeWavefrontInPlace(e,t){let n=e*t;this._wfRenderWidth.value=e,this._wfRenderHeight.value=t,this._wfMaxRayCount.value=n,this._kernelManager?.setDispatchCount(`initActiveIndices`,[Math.ceil(n/256),1,1]),this._bounceEarlyExitThreshold!==-1&&(this._bounceEarlyExitThreshold=Math.max(100,Math.floor(n/1e3)))}_buildWavefrontKernels(){let e=this.shaderBuilder.getSceneTextureNodes();if(!e)return;let r=this.storageTextures.renderWidth,i=this.storageTextures.renderHeight,a=r*i;this._bounceEarlyExitThreshold!==-1&&(this._bounceEarlyExitThreshold=Math.max(100,Math.floor(a/1e3))),this._packedBuffers?this._packedBuffers.resize(a):this._packedBuffers=new ua(a,this.renderer);let o=ua.requiredCapacity(a)*1;la(this.renderer,this._gBufferAttr),this._gBufferAttr=new t.StorageInstancedBufferAttribute(new Uint32Array(o*4),4);let s=(0,n.storage)(this._gBufferAttr,`uvec4`),c=(0,n.storage)(this._gBufferAttr,`uvec4`).toReadOnly();this._queueManager?this._queueManager.resize(this._packedBuffers.capacity):this._queueManager=new Ha(this._packedBuffers.capacity,this.renderer),this._kernelManager||=new Xa(this.renderer);let l=this._packedBuffers,u=this._queueManager;this._wfRenderWidth.value=r,this._wfRenderHeight.value=i,this._wfMaxRayCount.value=a;let d=this.shaderBuilder.prevColorTexNode,f=this.shaderBuilder.prevAlbedoTexNode,p=this.storageTextures.getWriteTextures(),m=u.getCounters(),h=(0,n.Fn)(()=>{(0,n.atomicStore)(m.element((0,n.uint)(Ba.ACTIVE_RAY_COUNT)),(0,n.uint)(0))});this._kernelManager.register(`resetCounters`,h().compute([1,1,1],[1,1,1]));let g=(0,n.Fn)(()=>{(0,n.atomicStore)(m.element((0,n.uint)(Ba.ACTIVE_RAY_COUNT)),(0,n.uint)(0))});this._kernelManager.register(`resetActiveCounter`,g().compute([1,1,1],[1,1,1]));let _=u.getBounceCounts(),v=this._wfCurrentBounce,y=(0,n.Fn)(()=>{let e=(0,n.atomicLoad)(m.element((0,n.uint)(Ba.ACTIVE_RAY_COUNT))),t=(0,n.uint)(v).clamp((0,n.uint)(0),(0,n.uint)(u.MAX_BOUNCE_SNAPSHOTS-1));_.element(t).assign(e),(0,n.atomicStore)(m.element((0,n.uint)(Ba.ENTERING_COUNT)),e)});this._kernelManager.register(`snapshotBounceCount`,y().compute([1,1,1],[1,1,1]));let b=u.activeIndices.a,x=(0,n.Fn)(()=>{let e=n.instanceIndex;b.element(e).assign(e),(0,n.If)(e.equal((0,n.uint)(0)),()=>{(0,n.atomicStore)(m.element((0,n.uint)(Ba.ACTIVE_RAY_COUNT)),this._wfMaxRayCount),(0,n.atomicStore)(m.element((0,n.uint)(Ba.ENTERING_COUNT)),this._wfMaxRayCount)})});this._kernelManager.register(`initActiveIndices`,x().compute([Math.ceil(a/256),1,1],[256,1,1]));let S=lo({rayBufferRW:l.rayBuffer.rw,rngBufferRW:l.rngBuffer.rw,gBufferRW:s,resolution:this.resolution,frame:this.frame,cameraWorldMatrix:this.cameraWorldMatrix,cameraProjectionMatrixInverse:this.cameraProjectionMatrixInverse,enableDOF:this.enableDOF,focalLength:this.focalLength,aperture:this.aperture,focusDistance:this.focusDistance,sceneScale:this.sceneScale,apertureScale:this.apertureScale,anamorphicRatio:this.anamorphicRatio,renderWidth:this._wfRenderWidth,renderHeight:this._wfRenderHeight,transmissiveBounces:this.transmissiveBounces,transparentBackground:this.transparentBackground,auxGBufferEnabled:this._auxGBufferUniform});this._kernelManager.register(`generate`,S().compute([Math.ceil(r/16),Math.ceil(i/16),1],[16,16,1]));let C=this.bvhStorageNode,w=this.triangleStorageNode,T=this.materialData.materialStorageNode,E=(0,n.texture)(this.environment.envCDFTexture),D=this.lightStorageNode,O=this.materialData,k=this.environment,A=pr(O.srgbBuckets),j=pr(O.linearBuckets);sr(A,j),kr(A);let M=k.environmentTexture?(0,n.texture)(k.environmentTexture):e.envTex;this._wfTexNodes={envTex:M,envCDFTex:E,srgbBuckets:A,linearBuckets:j},this._sortMaterials=(B.wavefrontSortMaterials??!1)&&(this.materialData?.materialCount??0)>8;let N=uo({bvhBuffer:C,triangleBuffer:w,materialBuffer:T,rayBufferRO:l.rayBuffer.ro,hitBufferRW:l.hitBuffer.rw,activeIndicesRO:u.getActiveReadRO(),counters:m,maxRayCount:this._wfMaxRayCount});if(this._kernelManager.register(`extend`,N().compute([Math.ceil(a/256),1,1],[256,1,1])),this._sortMaterials){let e=u.getSortGlobalHistogram(),t=Math.min(256,this.materialData?.materialCount??256);this._kernelManager.register(`resetGlobalHist`,zs({sortGlobalHistogram:e,bins:t})().compute([1,1,1],[256,1,1])),this._kernelManager.register(`globalHist`,Bs({hitBufferRO:l.hitBuffer.ro,activeIndicesReadRO:u.getActiveReadRO(),sortGlobalHistogram:e,counters:m,bins:t})().compute([Math.ceil(a/256),1,1],[256,1,1])),this._kernelManager.register(`globalPrefix`,Vs({sortGlobalHistogram:e,bins:t})().compute([1,1,1],[1,1,1])),this._kernelManager.register(`globalScatter`,Hs({hitBufferRO:l.hitBuffer.ro,activeIndicesReadRO:u.getActiveReadRO(),sortedIndicesRW:u.getSortedRW(),sortGlobalHistogram:e,counters:m,bins:t})().compute([Math.ceil(a/256),1,1],[256,1,1]))}let ee=ks({gBufferRW:s,envCompensationDelta:this.envCompensationDelta,bvhBuffer:C,triangleBuffer:w,materialBuffer:T,envCDFTexture:E,lightBuffer:D,rayBufferRW:l.rayBuffer.rw,rngBufferRW:l.rngBuffer.rw,hitBufferRO:l.hitBuffer.ro,counters:m,activeIndicesRO:this._sortMaterials?u.getSortedRO():u.getActiveReadRO(),envTexture:M,environmentIntensity:this.environmentIntensity,envMatrix:this.environmentMatrix,enableEnvironmentLight:this.enableEnvironment,useEnvMapIS:this.useEnvMapIS,groundProjectionEnabled:this.groundProjectionEnabled,groundProjectionRadius:this.groundProjectionRadius,groundProjectionHeight:this.groundProjectionHeight,groundProjectionLevel:this.groundProjectionLevel,enableGroundCatcher:this.enableGroundCatcher,groundCatcherHeight:this.groundCatcherHeight,envTotalSum:this.envTotalSum,envResolution:this.envResolution,directionalLightsBuffer:this.directionalLightsBufferNode,numDirectionalLights:this.numDirectionalLights,areaLightsBuffer:this.areaLightsBufferNode,numAreaLights:this.numAreaLights,pointLightsBuffer:this.pointLightsBufferNode,numPointLights:this.numPointLights,spotLightsBuffer:this.spotLightsBufferNode,numSpotLights:this.numSpotLights,maxBounceCount:this.maxBounces,maxSubsurfaceSteps:this.maxSubsurfaceSteps,transparentBackground:this.transparentBackground,backgroundIntensity:this.backgroundIntensity,backgroundColor:this.backgroundColor,backgroundBlurriness:this.backgroundBlurriness,backgroundBlurSamples:this.backgroundBlurSamples,showBackground:this.showBackground,globalIlluminationIntensity:this.globalIlluminationIntensity,cameraProjectionMatrix:this.cameraProjectionMatrix,cameraViewMatrix:this.cameraViewMatrix,fireflyThreshold:this.fireflyThreshold,frame:this.frame,resolution:this.resolution,emissiveTriangleCount:this.emissiveTriangleCount,emissiveVec4Offset:this.emissiveVec4Offset,emissiveTotalPower:this.emissiveTotalPower,emissiveBoost:this.emissiveBoost,totalTriangleCount:this.totalTriangleCount,enableEmissiveTriangleSampling:this.enableEmissiveTriangleSampling,lightBVHNodeCount:this.lightBVHNodeCount,reverseMapVec4Offset:this.reverseMapVec4Offset,currentBounce:this._wfCurrentBounce,maxRayCount:this._wfMaxRayCount,auxGBufferEnabled:this._auxGBufferUniform});this._kernelManager.register(`shade`,ee().compute([Math.ceil(a/256),1,1],[256,1,1]));let te=this._useSubgroupCompact&&(this.renderer.hasFeature?this.renderer.hasFeature(`subgroups`):!1);this._compactIsSubgroup=te;let ne=(te?js:As)({rayBufferRO:l.rayBuffer.ro,activeIndicesReadRO:u.getActiveReadRO(),activeIndicesWriteRW:u.getActiveWrite(),counters:m,currentActiveCount:this._wfMaxRayCount});this._kernelManager.register(`compact`,ne().compute([Math.ceil(a/256),1,1],[256,1,1]));let re=(0,n.Fn)(()=>{(0,n.atomicStore)(m.element((0,n.uint)(Ba.ENTERING_COUNT)),this._wfMaxRayCount)});this._kernelManager.register(`enterFull`,re().compute([1,1,1],[1,1,1]));let ie=u.activeIndicesRO.b,ae=u.activeIndices.a,oe=(0,n.Fn)(()=>{let e=n.instanceIndex;(0,n.If)(e.greaterThanEqual((0,n.atomicLoad)(m.element((0,n.uint)(Ba.ACTIVE_RAY_COUNT)))),()=>{(0,n.Return)()}),ae.element(e).assign(ie.element(e))});this._kernelManager.register(`compactCopyback`,oe().compute([Math.ceil(a/256),1,1],[256,1,1]));let P=Ns({rayBufferRO:l.rayBuffer.ro,gBufferRO:c,writeColorTex:p.color,writeNDTex:p.normalDepth,writeAlbedoTex:p.albedo,resolution:this.resolution,frame:this.frame,enableAccumulation:this.enableAccumulation,hasPreviousAccumulated:this.hasPreviousAccumulated,accumulationAlpha:this.accumulationAlpha,cameraIsMoving:this.cameraIsMoving,transparentBackground:this.transparentBackground,prevAccumTexture:d,prevAlbedoTexture:f,renderWidth:this._wfRenderWidth,renderHeight:this._wfRenderHeight,visMode:this.visMode,auxGBufferEnabled:this._auxGBufferUniform});this._kernelManager.register(`finalWrite`,P().compute([Math.ceil(r/16),Math.ceil(i/16),1],[16,16,1]));let se=Rs({writeColorTex:p.color,writeNDTex:p.normalDepth,writeAlbedoTex:p.albedo,resolution:this.resolution,renderWidth:this._wfRenderWidth,renderHeight:this._wfRenderHeight,cameraWorldMatrix:this.cameraWorldMatrix,cameraProjectionMatrixInverse:this.cameraProjectionMatrixInverse,cameraProjectionMatrix:this.cameraProjectionMatrix,cameraViewMatrix:this.cameraViewMatrix,enableDOF:this.enableDOF,focalLength:this.focalLength,aperture:this.aperture,focusDistance:this.focusDistance,sceneScale:this.sceneScale,apertureScale:this.apertureScale,anamorphicRatio:this.anamorphicRatio,bvhBuffer:C,triangleBuffer:w,materialBuffer:T,envTexture:M,environmentMatrix:this.environmentMatrix,environmentIntensity:this.environmentIntensity,enableEnvironmentLight:this.enableEnvironment,visMode:this.visMode,debugVisScale:this.debugVisScale,frame:this.frame});this._kernelManager.register(`debug`,se().compute([Math.ceil(r/16),Math.ceil(i/16),1],[16,16,1])),this._wavefrontReady=!0,console.log(`PathTracer: all wavefront kernels built (${r}×${i}, ${a} rays)`)}_setWfDispatch(){let e=this._wfRenderWidth.value,t=this._wfRenderHeight.value;this._kernelManager.setDispatchCount(`generate`,[Math.ceil(e/16),Math.ceil(t/16),1]),this._kernelManager.setDispatchCount(`finalWrite`,[Math.ceil(e/16),Math.ceil(t/16),1]),this._kernelManager.setDispatchCount(`debug`,[Math.ceil(e/16),Math.ceil(t/16),1])}dispose(){super.dispose(),this._packedBuffers?.dispose(),this._queueManager?.dispose(),this._kernelManager?.dispose(),this._gBufferAttr?.dispose?.(),this._packedBuffers=null,this._queueManager=null,this._kernelManager=null,this._gBufferAttr=null,this._wavefrontReady=!1}},Ws=class extends ve{constructor(e,i={}){super(`NormalDepth`,{...i,executionMode:_e.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.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(H,H),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(H,H),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._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,this._hasHistory=!1})}_syncStorageBuffers(){let e=this.pathTracer;if(!e)return!1;let t=e.materialData?.materialStorageAttr,r=e.triangleStorageAttr&&e.triangleStorageAttr!==this._lastTriAttr,i=e.bvhStorageAttr&&e.bvhStorageAttr!==this._lastBvhAttr,a=t&&t!==this._lastMatAttr;return(r||i||a)&&(this._computeNode?.dispose?.(),this._computeNode=null,this._computeBuilt=!1,this._triStorageNode=null,this._bvhStorageNode=null,this._matStorageNode=null,this._dirty=!0),e.triangleStorageAttr&&!this._triStorageNode&&(this._triStorageNode=(0,n.storage)(e.triangleStorageAttr,`vec4`,e.triangleStorageAttr.count).toReadOnly()),e.bvhStorageAttr&&!this._bvhStorageNode&&(this._bvhStorageNode=(0,n.storage)(e.bvhStorageAttr,`vec4`,e.bvhStorageAttr.count).toReadOnly()),t&&!this._matStorageNode&&(this._matStorageNode=(0,n.storage)(t,`vec4`,t.count).toReadOnly()),this._linearBuckets&&mr(this._linearBuckets,e.materialData?.linearBuckets),this._lastTriAttr=e.triangleStorageAttr||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=pr(this.pathTracer?.materialData?.linearBuckets),sr(pr(null),this._linearBuckets);let i=this.cameraWorldMatrix,a=this.cameraProjectionMatrixInverse,o=this.resolutionWidth,s=this.resolutionHeight,c=this._outputStorageTex,l=this._shadingStorageTex;this._computeNode=(0,n.Fn)(([i,a])=>{let u=(0,n.int)(n.workgroupId.x).mul(8).add((0,n.int)(n.localId.x)),d=(0,n.int)(n.workgroupId.y).mul(8).add((0,n.int)(n.localId.y));(0,n.If)(u.lessThan((0,n.int)(o)).and(d.lessThan((0,n.int)(s))),()=>{let f=(0,n.vec3)((0,n.float)(u).add(.5).div(o).mul(2).sub(1),(0,n.float)(d).add(.5).div(s).mul(2).sub(1).negate(),1),p=a.mul((0,n.vec4)(f,1)),m=(0,n.normalize)((0,n.mat3)(i[0].xyz,i[1].xyz,i[2].xyz).mul(p.xyz.div(p.w))),h=Dt({origin:(0,n.vec3)(i[3]),direction:m}),g=jt.wrap(oo(h,t,e)),_=g.normal.mul(.5).add(.5),v=g.dst,y=g.didHit.select((0,n.vec4)(_,v),(0,n.vec4)(0,0,0,(0,n.float)(65504)));(0,n.textureStore)(c,(0,n.uvec2)((0,n.uint)(u),(0,n.uint)(d)),y).toWriteOnly();let b=g.normal.toVar();(0,n.If)(g.didHit,()=>{let e=Ot.wrap(pn(g.materialIndex,r)).toVar(),t=zt.wrap(yr(g.uv,e)).toVar(),n=Sr(g.normal,e,t).toVar();b.assign(Cr(n,e,t))});let x=g.didHit.select((0,n.vec4)(b.mul(.5).add(.5),v),(0,n.vec4)(0,0,0,(0,n.float)(65504)));(0,n.textureStore)(l,(0,n.uvec2)((0,n.uint)(u),(0,n.uint)(d)),x).toWriteOnly()})})(i,a).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._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);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._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._dirty=!1}releaseGPUMemory(){this._outputStorageTex?.dispose(),this._shadingStorageTex?.dispose(),this.reset()}reset(){this._dirty=!0,this._hasHistory=!1}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._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}dispose(){this._computeNode?.dispose(),this._outputStorageTex?.dispose(),this._shadingStorageTex?.dispose(),this._shadingRT?.dispose(),this._rtA?.dispose(),this._rtB?.dispose()}},Gs=class extends ve{constructor(e,i,a={}){super(`MotionVector`,{...a,executionMode:_e.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.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(H,H),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(H,H),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=(0,n.vec3)((0,n.float)(c).add(.5).div(a).mul(2).sub(1),(0,n.float)(l).add(.5).div(o).mul(2).sub(1).negate(),1),s=r.mul((0,n.vec4)(e,1)),p=(0,n.normalize)((0,n.mat3)(t[0].xyz,t[1].xyz,t[2].xyz).mul(s.xyz.div(s.w))),m=(0,n.vec3)(t[3]).add(p.mul(u)),h=i.mul((0,n.vec4)(m,1)),g=h.xy.div(h.w),_=(0,n.vec2)(g.x.mul(.5).add(.5),g.y.mul(-.5).add(.5)),v=d.sub(_),y=_.x.greaterThanEqual(0).and(_.x.lessThanEqual(1)).and(_.y.greaterThanEqual(0)).and(_.y.lessThanEqual(1));f.assign(y.select((0,n.vec4)(v,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.vec3)((0,n.float)(d).add(.5).div(c).mul(2).sub(1),(0,n.float)(f).add(.5).div(l).mul(2).sub(1).negate(),1),a=r.mul((0,n.vec4)(e,1)),u=(0,n.normalize)((0,n.mat3)(t[0].xyz,t[1].xyz,t[2].xyz).mul(a.xyz.div(a.w))),h=(0,n.vec3)(t[3]).add(u.mul(p)),g=(0,n.vec2)((0,n.float)(d).add(.5).div(c),(0,n.float)(f).add(.5).div(l)),_=i.mul((0,n.vec4)(h,1)),v=_.xy.div(_.w),y=(0,n.vec2)(v.x.mul(.5).add(.5),v.y.mul(-.5).add(.5)),b=y.x.greaterThanEqual(0).and(y.x.lessThanEqual(1)).and(y.y.greaterThanEqual(0)).and(y.y.lessThanEqual(1)),x=g.sub(y),S=(0,n.vec3)(x.x.div(o).mul(s),x.y.div(o).mul(s),0);m.assign(b.select((0,n.vec4)(S,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)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}dispose(){this._screenSpaceComputeNode?.dispose(),this._worldSpaceComputeNode?.dispose(),this._screenSpaceStorageTex?.dispose(),this._worldSpaceStorageTex?.dispose(),this.screenSpaceTarget?.dispose(),this.worldSpaceTarget?.dispose(),this._normalDepthTexNode?.dispose()}},Ks=e=>(0,n.select)(e.equal(e),e,(0,n.float)(0)).clamp(0,1e7),qs=e=>(0,n.vec3)(Ks(e.x),Ks(e.y),Ks(e.z)),Js=class extends ve{constructor(e,i={}){super(`ASVGF`,{...i,executionMode:_e.PER_CYCLE}),this.renderer=e,this.temporalAlpha=(0,n.uniform)(i.temporalAlpha??0),this.gradientStrength=(0,n.uniform)(i.gradientStrength??0),this.gradientSigmaScale=(0,n.uniform)(i.gradientSigmaScale??2),this.gradientNoiseFloor=(0,n.uniform)(i.gradientNoiseFloor??0),this.maxAccumFrames=(0,n.uniform)(i.maxAccumFrames??32),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(H,H),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(H,H),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(H,H),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(H,H),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(H,H),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=tn(qs(m.div((0,n.max)(_,(0,n.vec3)(V))))).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(tn(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).xyz,x=(0,n.textureLoad)(r,y).xyz,S=(0,n.max)(x,(0,n.vec3)(V)),C=qs(b.div(S)),w=(0,n.vec4)(C,1).toVar(),T=(0,n.vec4)(b,1).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)),E=p.clamp((0,n.int)(0),(0,n.int)(h).sub(1)),D=_.clamp((0,n.int)(0),(0,n.int)(h).sub(1)),O=m.clamp((0,n.int)(0),(0,n.int)(g).sub(1)),k=v.clamp((0,n.int)(0),(0,n.int)(g).sub(1)),A=(0,n.float)(1).sub(b).mul((0,n.float)(1).sub(x)),j=b.mul((0,n.float)(1).sub(x)),M=(0,n.float)(1).sub(b).mul(x),N=b.mul(x),ee=(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)},te=ee(E,O,A),ne=ee(D,O,j),re=ee(E,k,M),ie=ee(D,k,N),ae=te.add(ne).add(re).add(ie);(0,n.If)(ae.greaterThan((0,n.float)(.01)),()=>{let e=(0,n.textureLoad)(s,(0,n.ivec2)(E,O)),t=(0,n.textureLoad)(s,(0,n.ivec2)(D,O)),r=(0,n.textureLoad)(s,(0,n.ivec2)(E,k)),i=(0,n.textureLoad)(s,(0,n.ivec2)(D,k)),a=(0,n.float)(1).div(ae),o=e.xyz.mul(te).add(t.xyz.mul(ne)).add(r.xyz.mul(re)).add(i.xyz.mul(ie)).mul(a),l=e.w.mul(te).add(t.w.mul(ne)).add(r.w.mul(re)).add(i.w.mul(ie)).mul(a),p=(0,n.textureLoad)(c,y).x.mul(f).clamp(0,1),m=qs((0,n.mix)(o,C,(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);w.assign((0,n.vec4)(m,h)),T.assign((0,n.vec4)(m.mul(S),1))})})}),(0,n.textureStore)(e,(0,n.uvec2)((0,n.uint)(_),(0,n.uint)(v)),w).toWriteOnly(),(0,n.textureStore)(l,(0,n.uvec2)((0,n.uint)(_),(0,n.uint)(v)),T).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=tn(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(`asvgf:reset`,()=>this.resetTemporalData()),this.on(`asvgf:setTemporal`,e=>{e&&e.enabled!==void 0&&this.setTemporalEnabled(e.enabled)}),this.on(`asvgf:updateParameters`,e=>this.updateParameters(e))}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}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()}},Ys=e=>(0,n.select)(e.equal(e),e,(0,n.float)(0)).clamp(0,1e7),Xs=(0,n.wgslFn)(`
|
|
669
|
+
`),Ls=(0,n.Fn)(([e,t,r,i,a,o,s,c,l,u,d,f,p,m,h,g])=>{let _=(0,n.vec4)(1,0,1,1).toVar(),v=Dt({origin:e,direction:t}),y=jt.wrap(oo(v,r,i).toVar());return(0,n.If)(u.equal((0,n.int)(7)),()=>{let e=(0,n.float)(y.triTests).div(d);_.assign((0,n.select)(e.lessThan(1),(0,n.vec4)((0,n.vec3)(e),1),(0,n.vec4)(1,0,0,1)))}),(0,n.If)(u.equal((0,n.int)(8)),()=>{let e=(0,n.float)(y.boxTests).div(d);_.assign((0,n.select)(e.lessThan(1),(0,n.vec4)((0,n.vec3)(e),1),(0,n.vec4)(1,0,0,1)))}),(0,n.If)(u.equal((0,n.int)(10)),()=>{(0,n.If)(l,()=>{let e=go({tex:o,samp:(0,n.sampler)(o),direction:t,environmentMatrix:s,environmentIntensity:c,enableEnvironmentLight:l}).toVar(),r=(0,n.dot)(e.xyz,Xt).toVar(),i=r,a=(0,n.max)(d.mul(.1),.001),u=r.div(a),m=(0,n.log)(r.add(1e-6)).add(10).div(10),h=(0,n.select)(d.greaterThan(1),u,m).toVar(),g=(0,n.vec3)(0).toVar();(0,n.If)(h.lessThan(.2),()=>{g.assign((0,n.mix)((0,n.vec3)(0,0,0),(0,n.vec3)(0,0,.5),h.mul(5)))}).ElseIf(h.lessThan(.4),()=>{g.assign((0,n.mix)((0,n.vec3)(0,0,.5),(0,n.vec3)(0,0,1),h.sub(.2).mul(5)))}).ElseIf(h.lessThan(.6),()=>{g.assign((0,n.mix)((0,n.vec3)(0,0,1),(0,n.vec3)(0,1,0),h.sub(.4).mul(5)))}).ElseIf(h.lessThan(.8),()=>{g.assign((0,n.mix)((0,n.vec3)(0,1,0),(0,n.vec3)(1,1,0),h.sub(.6).mul(5)))}).ElseIf(h.lessThan(1),()=>{g.assign((0,n.mix)((0,n.vec3)(1,1,0),(0,n.vec3)(1,0,0),h.sub(.8).mul(5)))}).Else(()=>{g.assign((0,n.mix)((0,n.vec3)(1,0,0),(0,n.vec3)(1,1,1),(0,n.min)(h.sub(1),1)))});let v=f.div(p);(0,n.If)(v.x.lessThan(.1).and(v.y.lessThan(.1)),()=>{let e=i.mul(1);g.assign((0,n.vec3)(e))}).ElseIf(v.x.greaterThan(.9).and(v.y.lessThan(.1)),()=>{g.assign(e.xyz.mul(1))}),_.assign((0,n.vec4)(g,1))}).Else(()=>{_.assign((0,n.vec4)(1,0,1,1))})}),(0,n.If)(u.equal((0,n.int)(4)),()=>{(0,n.If)(y.didHit.not(),()=>{_.assign((0,n.vec4)(0,0,0,1))}).Else(()=>{let t=Ot.wrap(pn(y.materialIndex,a)).toVar(),r=Lt.wrap(Tr(t,y.uv,y.normal)).toVar().emissive.toVar(),i=(0,n.length)(r).toVar();(0,n.If)(i.greaterThan(0),()=>{let t=r.div((0,n.max)(i.mul(.1),.001)).toVar(),a=(0,n.length)(e.sub(y.hitPoint)),o=(0,n.clamp)((0,n.float)(1).sub(a.div(10)),0,1),s=(0,n.mix)(t,t.mul((0,n.vec3)(1,.8,.6)),o.mul(.3));_.assign((0,n.vec4)(s,1))}).Else(()=>{_.assign((0,n.vec4)(0,0,.1,1))})})}),(0,n.If)(u.equal((0,n.int)(1)),()=>{(0,n.If)(y.didHit.not(),()=>{_.assign((0,n.vec4)(.5,.5,1,1))}).Else(()=>{let e=Ot.wrap(pn(y.materialIndex,a)).toVar(),t=(0,n.normalize)(Lt.wrap(Tr(e,y.uv,y.normal)).toVar().normal);_.assign((0,n.vec4)(Fs({normal:t}),1))})}),(0,n.If)(u.equal((0,n.int)(2)),()=>{(0,n.If)(y.didHit.not(),()=>{_.assign((0,n.vec4)((0,n.vec3)(1),1))}).Else(()=>{let e=Is({worldPos:y.hitPoint,cameraProjectionMatrix:m,cameraViewMatrix:h});_.assign((0,n.vec4)(Ps({depth:e}),1))})}),(0,n.If)(u.equal((0,n.int)(3)),()=>{(0,n.If)(y.didHit.not(),()=>{_.assign((0,n.vec4)(0,0,0,1))}).Else(()=>{let e=Ot.wrap(pn(y.materialIndex,a)).toVar(),t=Lt.wrap(Tr(e,y.uv,y.normal)).toVar().albedo.rgb;_.assign((0,n.vec4)(t,1))})}),(0,n.If)(u.equal((0,n.int)(5)),()=>{(0,n.If)(y.didHit.not(),()=>{_.assign((0,n.vec4)(0,0,0,1))}).Else(()=>{let e=Ot.wrap(pn(y.materialIndex,a)).toVar(),t=Lt.wrap(Tr(e,y.uv,y.normal)).toVar(),u=t.albedo.rgb,d=(0,n.normalize)(t.normal).toVar(),p=ie({state:ae({seed:(0,n.uint)(f.x).mul((0,n.uint)(1973)).add((0,n.uint)(f.y).mul((0,n.uint)(9277))).add(g.mul((0,n.uint)(26699)))})}).toVar(),m=Ln({N:d,xi:(0,n.vec2)(P(p).toVar(),P(p).toVar())}).toVar(),h=Dt({origin:y.hitPoint.add(d.mul(.001)),direction:m}),v=jt.wrap(oo(h,r,i).toVar()),b=(0,n.vec3)(0).toVar();(0,n.If)(v.didHit.not(),()=>{(0,n.If)(l,()=>{b.assign(go({tex:o,samp:(0,n.sampler)(o),direction:m,environmentMatrix:s,environmentIntensity:c,enableEnvironmentLight:l}).xyz)})}).Else(()=>{let e=Ot.wrap(pn(v.materialIndex,a)).toVar(),t=Lt.wrap(Tr(e,v.uv,v.normal)).toVar();b.assign(t.emissive),(0,n.If)(l,()=>{let e=(0,n.normalize)(t.normal).toVar(),r=go({tex:o,samp:(0,n.sampler)(o),direction:e,environmentMatrix:s,environmentIntensity:c,enableEnvironmentLight:l}).xyz;b.addAssign(t.albedo.rgb.mul(r))})});let x=u.mul(b);_.assign((0,n.vec4)(x,1))})}),(0,n.If)(u.equal((0,n.int)(6)),()=>{(0,n.If)(y.didHit,()=>{let e=y.normal.toVar(),r=(0,n.normalize)(t.sub(e.mul((0,n.dot)(t,e).mul(2)))).toVar(),i=go({tex:o,samp:(0,n.sampler)(o),direction:r,environmentMatrix:s,environmentIntensity:c,enableEnvironmentLight:l}).xyz,a=i.div(i.add(1));_.assign((0,n.vec4)(a,1))}).Else(()=>{let e=go({tex:o,samp:(0,n.sampler)(o),direction:t,environmentMatrix:s,environmentIntensity:c,enableEnvironmentLight:l}).xyz,r=e.div(e.add(1));_.assign((0,n.vec4)(r,1))})}),_});function Rs(e){let{writeColorTex:t,writeNDTex:r,writeAlbedoTex:i,resolution:a,renderWidth:o,renderHeight:s,cameraWorldMatrix:c,cameraProjectionMatrixInverse:l,cameraProjectionMatrix:u,cameraViewMatrix:d,enableDOF:f,focalLength:p,aperture:m,focusDistance:h,sceneScale:g,apertureScale:_,anamorphicRatio:v,bvhBuffer:y,triangleBuffer:b,materialBuffer:x,envTexture:S,environmentMatrix:C,environmentIntensity:w,enableEnvironmentLight:T,visMode:E,debugVisScale:D,frame:O}=e;return(0,n.Fn)(()=>{let e=(0,n.int)(n.workgroupId.x).mul(16).add((0,n.int)(n.localId.x)),k=(0,n.int)(n.workgroupId.y).mul(16).add((0,n.int)(n.localId.y));(0,n.If)(e.lessThan(o).and(k.lessThan(s)),()=>{let o=(0,n.vec2)((0,n.float)(e).add(.5),(0,n.float)(k).add(.5)),s=ie({state:(0,n.uint)(k.mul((0,n.int)(a.x)).add(e)).add((0,n.uint)(1))}).toVar(),A=o.div(a).mul(2).sub(1).toVar();A.y.assign(A.y.negate());let j=Dt.wrap(co(A,s,c,l,f,p,m,h,g,_,v)),M=(0,n.vec4)(1,0,1,1).toVar();(0,n.If)(E.equal((0,n.int)(9)),()=>{let e=he(o,(0,n.int)(0),(0,n.int)(1),s,a,O);M.assign((0,n.vec4)(e,1,1))}).Else(()=>{M.assign(Ls(j.origin,j.direction,y,b,x,S,C,w,T,E,D,o,a,u,d,O))});let N=(0,n.uvec2)((0,n.uint)(e),(0,n.uint)(k));(0,n.textureStore)(t,N,M).toWriteOnly(),(0,n.textureStore)(r,N,(0,n.vec4)(.5,.5,1,1)).toWriteOnly(),(0,n.textureStore)(i,N,(0,n.vec4)(M.xyz,1)).toWriteOnly()})})}function zs({sortGlobalHistogram:e,bins:t=256}){return(0,n.Fn)(()=>{(0,n.If)(n.instanceIndex.lessThan((0,n.uint)(t)),()=>{(0,n.atomicStore)(e.element(n.instanceIndex),(0,n.uint)(0))})})}function Bs({hitBufferRO:e,activeIndicesReadRO:t,sortGlobalHistogram:r,counters:i,bins:a=256}){return(0,n.Fn)(()=>{let o=n.instanceIndex,s=n.localId.x,c=T(`uint`,a);(0,n.If)(s.lessThan((0,n.uint)(a)),()=>{(0,n.atomicStore)(c.element(s),(0,n.uint)(0))}),(0,n.workgroupBarrier)();let l=(0,n.atomicLoad)(i.element((0,n.uint)(Ba.ENTERING_COUNT)));(0,n.If)(o.lessThan(l),()=>{let r=(0,n.uint)(Aa(e,t.element(o))).clamp((0,n.uint)(0),(0,n.uint)(a-1));(0,n.atomicAdd)(c.element(r),(0,n.uint)(1))}),(0,n.workgroupBarrier)(),(0,n.If)(s.lessThan((0,n.uint)(a)),()=>{let e=(0,n.atomicLoad)(c.element(s));(0,n.If)(e.greaterThan((0,n.uint)(0)),()=>{(0,n.atomicAdd)(r.element(s),e)})})})}function Vs({sortGlobalHistogram:e,bins:t=256}){return(0,n.Fn)(()=>{(0,n.If)(n.instanceIndex.equal((0,n.uint)(0)),()=>{let r=(0,n.uint)(0).toVar();(0,n.Loop)({start:(0,n.uint)(0),end:(0,n.uint)(t),type:`uint`},({i:t})=>{let i=e.element(t),a=(0,n.atomicLoad)(i);(0,n.atomicStore)(i,r),r.addAssign(a)})})})}function Hs({hitBufferRO:e,activeIndicesReadRO:t,sortedIndicesRW:r,sortGlobalHistogram:i,counters:a,bins:o=256}){return(0,n.Fn)(()=>{let s=n.instanceIndex,c=(0,n.atomicLoad)(a.element((0,n.uint)(Ba.ENTERING_COUNT)));(0,n.If)(s.lessThan(c),()=>{let a=t.element(s),c=(0,n.uint)(Aa(e,a)).clamp((0,n.uint)(0),(0,n.uint)(o-1)),l=(0,n.atomicAdd)(i.element(c),(0,n.uint)(1));r.element(l).assign(a)})})}var Us=class extends aa{constructor(e,t,r,i={}){super(e,t,r,i),this.name=`PathTracer`,this._packedBuffers=null,this._queueManager=null,this._kernelManager=null,this._gBufferAttr=null,this._wavefrontReady=!1,this._auxGBufferEnabled=!1,this._auxGBufferUniform=(0,n.uniform)(0,`uint`),this._useDynamicDispatch=!0,this._sortMaterials=!1,this._useSubgroupCompact=!1,this._lastBounceCounts=null,this._lastBounceCountsBudget=-1,this._readbackPending=!1,this._readbackEveryNFrames=4,this._readbackFrameCounter=0,this._readbackGeneration=0,this._curveSizingValid=!1,this._bounceEarlyExitThreshold=100,this._wfRenderWidth=(0,n.uniform)(1920,`int`),this._wfRenderHeight=(0,n.uniform)(1080,`int`),this._wfMaxRayCount=(0,n.uniform)(0,`uint`),this._wfCurrentBounce=(0,n.uniform)(0,`int`),this.vramTracker=new Ja(this.renderer),this._registerVRAMProviders(),console.log(`PathTracer: initialized (wavefront)`)}_registerVRAMProviders(){let e=this.vramTracker;e.register(`rays`,()=>{let e=this._packedBuffers?._attrs;return e?[e.ray,e.rng,e.hit]:null}),e.register(`queues`,()=>{let e=this._queueManager;return e?[e._countersAttr,e._bounceCountsAttr,e._attrA,e._attrB,e._sortAttr]:null}),e.register(`gbuffer`,()=>this._gBufferAttr?[this._gBufferAttr]:null),e.register(`accum`,()=>{let e=this.storageTextures;return e?[e.writeColor,e.writeNormalDepth,e.writeAlbedo,e.readTarget]:null}),e.register(`geometry`,()=>[this.triangleStorageAttr,this.bvhStorageAttr,this.lightStorageAttr]),e.register(`materials`,()=>{let e=this.materialData;return e?[e.materialStorageAttr,...(e.srgbBuckets||[]).filter(Boolean),...(e.linearBuckets||[]).filter(Boolean)]:null}),e.register(`environment`,()=>{let e=this.environment;return e?[e.environmentTexture,e.envCDFTexture]:null})}setupMaterial(){super.setupMaterial(),this.materialData?.materialCount>0&&(this._kernelManager&&this._kernelManager.dispose(),this._wavefrontReady=!1,this._buildWavefrontKernels())}render(e){if(!this.isReady||!this._wavefrontReady)return;if(this.isComplete||this.frameCount>=this.completionThreshold){this.isComplete||=!0;return}this.performanceMonitor?.start();let t=this.frameCount,n=this.renderMode.value,r=null;n===1&&t===0&&(r=this.maxBounces.value,this.maxBounces.value=1),this._handleResize(),this.manageASVGFForRenderMode(n),e&&e.setState(`tileRenderingComplete`,!0),this.cameraChanged=this._updateCameraUniforms(),this.cameraOptimizer?.updateInteractionMode(this.cameraChanged),this.cameraChanged&&(this._curveSizingValid=!1,this._readbackGeneration++),this._updateAccumulationUniforms(t,n),this.frame.value=t,this._setWfDispatch();let i=this.storageTextures.getReadTextures();this.shaderBuilder.prevColorTexNode&&(this.shaderBuilder.prevColorTexNode.value=i.color,this.shaderBuilder.prevAlbedoTexNode.value=i.albedo),this._refreshWfTextureNodes();let a=this._kernelManager;if((this.visMode?.value|0)>0&&this.visMode.value!==11){a.dispatch(`debug`),this.storageTextures.copyToReadTargets(this.renderer);let t=this.storageTextures.getReadTextures();e&&this._publishTexturesToContext(e,t),this._emitStateEvents(),this.cameraOptimizer?.isInInteractionMode()||this.frameCount++,r!==null&&(this.maxBounces.value=r),this.performanceMonitor?.end();return}a.dispatch(`resetCounters`),a.dispatch(`generate`),a.dispatch(`initActiveIndices`);let o=this.maxBounces.value,s=o+this.transmissiveBounces.value+this.maxSubsurfaceSteps.value,c=this._wfMaxRayCount.value,l=this._lastBounceCounts,u=l?o<=this._lastBounceCountsBudget?s+1:this._lastBounceCountsBudget:0;for(let e=0;e<=s;e++){this._wfCurrentBounce.value=e;let t=this._useDynamicDispatch;if(t){let t=c;if(e>0&&this._curveSizingValid){let n=e-1,r;n<u&&l[n]!==void 0?r=l[n]:u>0&&(r=l[u-1]),t=r>0?r:c}let n=Math.min(c,Math.ceil(t*1.5)+1024),r=[Math.ceil(n/256),1,1];a.setDispatchCount(`extend`,r),a.setDispatchCount(`shade`,r),a.setDispatchCount(`globalHist`,r),a.setDispatchCount(`globalScatter`,r),a.setDispatchCount(`compact`,r),a.setDispatchCount(`compactCopyback`,r)}else{a.dispatch(`enterFull`);let e=[Math.ceil(c/256),1,1];a.setDispatchCount(`extend`,e),a.setDispatchCount(`shade`,e),a.setDispatchCount(`compact`,e),a.setDispatchCount(`globalHist`,e),a.setDispatchCount(`globalScatter`,e)}if(a.dispatch(`extend`),this._sortMaterials&&(a.dispatch(`resetGlobalHist`),a.dispatch(`globalHist`),a.dispatch(`globalPrefix`),a.dispatch(`globalScatter`)),a.dispatch(`shade`),a.dispatch(`resetActiveCounter`),a.dispatch(`compact`),t&&a.dispatch(`compactCopyback`),a.dispatch(`snapshotBounceCount`),e<u&&e<s&&l[e]!==void 0&&l[e]<=this._bounceEarlyExitThreshold)break}a.dispatch(`finalWrite`),this._maybeReadbackCounters(),this.storageTextures.copyToReadTargets(this.renderer,this._auxGBufferEnabled);let d=this.storageTextures.getReadTextures();e&&this._publishTexturesToContext(e,d),this._emitStateEvents(),this.cameraOptimizer?.isInInteractionMode()||this.frameCount++,r!==null&&(this.maxBounces.value=r),this.performanceMonitor?.end()}_handleResize(){let e=this.storageTextures.renderWidth,t=this.storageTextures.renderHeight;super._handleResize(),this._rebuildKernelsIfResized(e,t)}setAuxGBufferEnabled(e){e=!!e,this._auxGBufferEnabled!==e&&(this._auxGBufferEnabled=e,this._auxGBufferUniform.value=+!!e,this.reset())}setSize(e,t){let n=this.storageTextures.renderWidth,r=this.storageTextures.renderHeight;super.setSize(e,t),this._rebuildKernelsIfResized(n,r)}_maybeReadbackCounters(){if(this.cameraChanged){this._readbackFrameCounter=this._readbackEveryNFrames;return}if(this._readbackPending||(this._readbackFrameCounter++,this._readbackFrameCounter<this._readbackEveryNFrames))return;this._readbackFrameCounter=0;let e=this._queueManager?.getBounceCountsAttribute();if(!e)return;this._readbackPending=!0;let t=this._readbackGeneration,n=this.maxBounces.value;this.renderer.getArrayBufferAsync(e).then(e=>{t===this._readbackGeneration&&(this._lastBounceCounts=new Uint32Array(e.slice(0)),this._lastBounceCountsBudget=n,this._curveSizingValid=!0),this._readbackPending=!1}).catch(e=>{console.warn(`Wavefront bounceCounts readback failed:`,e),this._readbackPending=!1})}_refreshWfTextureNodes(){let e=this._wfTexNodes;if(!e)return;let t=this.environment?.environmentTexture;t&&e.envTex&&(e.envTex.value=t),this.environment?.envCDFTexture&&e.envCDFTex&&(e.envCDFTex.value=this.environment.envCDFTexture);let n=this.materialData;n&&(mr(e.srgbBuckets,n.srgbBuckets),mr(e.linearBuckets,n.linearBuckets))}_rebuildKernelsIfResized(e,t){let n=this.storageTextures.renderWidth,r=this.storageTextures.renderHeight;if(n===e&&r===t||!(this.materialData?.materialCount>0))return;this._lastBounceCounts=null,this._lastBounceCountsBudget=-1,this._curveSizingValid=!1,this._readbackFrameCounter=0,this._readbackGeneration++;let i=ua.requiredCapacity(n*r);!this._packedBuffers||i>this._packedBuffers.capacity?(this._kernelManager&&this._kernelManager.dispose(),this._wavefrontReady=!1,this._buildWavefrontKernels()):this._resizeWavefrontInPlace(n,r)}_resizeWavefrontInPlace(e,t){let n=e*t;this._wfRenderWidth.value=e,this._wfRenderHeight.value=t,this._wfMaxRayCount.value=n,this._kernelManager?.setDispatchCount(`initActiveIndices`,[Math.ceil(n/256),1,1]),this._bounceEarlyExitThreshold!==-1&&(this._bounceEarlyExitThreshold=Math.max(100,Math.floor(n/1e3)))}_buildWavefrontKernels(){let e=this.shaderBuilder.getSceneTextureNodes();if(!e)return;let r=this.storageTextures.renderWidth,i=this.storageTextures.renderHeight,a=r*i;this._bounceEarlyExitThreshold!==-1&&(this._bounceEarlyExitThreshold=Math.max(100,Math.floor(a/1e3))),this._packedBuffers?this._packedBuffers.resize(a):this._packedBuffers=new ua(a,this.renderer);let o=ua.requiredCapacity(a)*1;la(this.renderer,this._gBufferAttr),this._gBufferAttr=new t.StorageInstancedBufferAttribute(new Uint32Array(o*4),4);let s=(0,n.storage)(this._gBufferAttr,`uvec4`),c=(0,n.storage)(this._gBufferAttr,`uvec4`).toReadOnly();this._queueManager?this._queueManager.resize(this._packedBuffers.capacity):this._queueManager=new Ha(this._packedBuffers.capacity,this.renderer),this._kernelManager||=new Xa(this.renderer);let l=this._packedBuffers,u=this._queueManager;this._wfRenderWidth.value=r,this._wfRenderHeight.value=i,this._wfMaxRayCount.value=a;let d=this.shaderBuilder.prevColorTexNode,f=this.shaderBuilder.prevAlbedoTexNode,p=this.storageTextures.getWriteTextures(),m=u.getCounters(),h=(0,n.Fn)(()=>{(0,n.atomicStore)(m.element((0,n.uint)(Ba.ACTIVE_RAY_COUNT)),(0,n.uint)(0))});this._kernelManager.register(`resetCounters`,h().compute([1,1,1],[1,1,1]));let g=(0,n.Fn)(()=>{(0,n.atomicStore)(m.element((0,n.uint)(Ba.ACTIVE_RAY_COUNT)),(0,n.uint)(0))});this._kernelManager.register(`resetActiveCounter`,g().compute([1,1,1],[1,1,1]));let _=u.getBounceCounts(),v=this._wfCurrentBounce,y=(0,n.Fn)(()=>{let e=(0,n.atomicLoad)(m.element((0,n.uint)(Ba.ACTIVE_RAY_COUNT))),t=(0,n.uint)(v).clamp((0,n.uint)(0),(0,n.uint)(u.MAX_BOUNCE_SNAPSHOTS-1));_.element(t).assign(e),(0,n.atomicStore)(m.element((0,n.uint)(Ba.ENTERING_COUNT)),e)});this._kernelManager.register(`snapshotBounceCount`,y().compute([1,1,1],[1,1,1]));let b=u.activeIndices.a,x=(0,n.Fn)(()=>{let e=n.instanceIndex;b.element(e).assign(e),(0,n.If)(e.equal((0,n.uint)(0)),()=>{(0,n.atomicStore)(m.element((0,n.uint)(Ba.ACTIVE_RAY_COUNT)),this._wfMaxRayCount),(0,n.atomicStore)(m.element((0,n.uint)(Ba.ENTERING_COUNT)),this._wfMaxRayCount)})});this._kernelManager.register(`initActiveIndices`,x().compute([Math.ceil(a/256),1,1],[256,1,1]));let S=lo({rayBufferRW:l.rayBuffer.rw,rngBufferRW:l.rngBuffer.rw,gBufferRW:s,resolution:this.resolution,frame:this.frame,cameraWorldMatrix:this.cameraWorldMatrix,cameraProjectionMatrixInverse:this.cameraProjectionMatrixInverse,enableDOF:this.enableDOF,focalLength:this.focalLength,aperture:this.aperture,focusDistance:this.focusDistance,sceneScale:this.sceneScale,apertureScale:this.apertureScale,anamorphicRatio:this.anamorphicRatio,renderWidth:this._wfRenderWidth,renderHeight:this._wfRenderHeight,transmissiveBounces:this.transmissiveBounces,transparentBackground:this.transparentBackground,auxGBufferEnabled:this._auxGBufferUniform});this._kernelManager.register(`generate`,S().compute([Math.ceil(r/16),Math.ceil(i/16),1],[16,16,1]));let C=this.bvhStorageNode,w=this.triangleStorageNode,T=this.materialData.materialStorageNode,E=(0,n.texture)(this.environment.envCDFTexture),D=this.lightStorageNode,O=this.materialData,k=this.environment,A=pr(O.srgbBuckets),j=pr(O.linearBuckets);sr(A,j),kr(A);let M=k.environmentTexture?(0,n.texture)(k.environmentTexture):e.envTex;this._wfTexNodes={envTex:M,envCDFTex:E,srgbBuckets:A,linearBuckets:j},this._sortMaterials=(B.wavefrontSortMaterials??!1)&&(this.materialData?.materialCount??0)>8;let N=uo({bvhBuffer:C,triangleBuffer:w,materialBuffer:T,rayBufferRO:l.rayBuffer.ro,hitBufferRW:l.hitBuffer.rw,activeIndicesRO:u.getActiveReadRO(),counters:m,maxRayCount:this._wfMaxRayCount});if(this._kernelManager.register(`extend`,N().compute([Math.ceil(a/256),1,1],[256,1,1])),this._sortMaterials){let e=u.getSortGlobalHistogram(),t=Math.min(256,this.materialData?.materialCount??256);this._kernelManager.register(`resetGlobalHist`,zs({sortGlobalHistogram:e,bins:t})().compute([1,1,1],[256,1,1])),this._kernelManager.register(`globalHist`,Bs({hitBufferRO:l.hitBuffer.ro,activeIndicesReadRO:u.getActiveReadRO(),sortGlobalHistogram:e,counters:m,bins:t})().compute([Math.ceil(a/256),1,1],[256,1,1])),this._kernelManager.register(`globalPrefix`,Vs({sortGlobalHistogram:e,bins:t})().compute([1,1,1],[1,1,1])),this._kernelManager.register(`globalScatter`,Hs({hitBufferRO:l.hitBuffer.ro,activeIndicesReadRO:u.getActiveReadRO(),sortedIndicesRW:u.getSortedRW(),sortGlobalHistogram:e,counters:m,bins:t})().compute([Math.ceil(a/256),1,1],[256,1,1]))}let ee=ks({gBufferRW:s,envCompensationDelta:this.envCompensationDelta,bvhBuffer:C,triangleBuffer:w,materialBuffer:T,envCDFTexture:E,lightBuffer:D,rayBufferRW:l.rayBuffer.rw,rngBufferRW:l.rngBuffer.rw,hitBufferRO:l.hitBuffer.ro,counters:m,activeIndicesRO:this._sortMaterials?u.getSortedRO():u.getActiveReadRO(),envTexture:M,environmentIntensity:this.environmentIntensity,envMatrix:this.environmentMatrix,enableEnvironmentLight:this.enableEnvironment,useEnvMapIS:this.useEnvMapIS,groundProjectionEnabled:this.groundProjectionEnabled,groundProjectionRadius:this.groundProjectionRadius,groundProjectionHeight:this.groundProjectionHeight,groundProjectionLevel:this.groundProjectionLevel,enableGroundCatcher:this.enableGroundCatcher,groundCatcherHeight:this.groundCatcherHeight,envTotalSum:this.envTotalSum,envResolution:this.envResolution,directionalLightsBuffer:this.directionalLightsBufferNode,numDirectionalLights:this.numDirectionalLights,areaLightsBuffer:this.areaLightsBufferNode,numAreaLights:this.numAreaLights,pointLightsBuffer:this.pointLightsBufferNode,numPointLights:this.numPointLights,spotLightsBuffer:this.spotLightsBufferNode,numSpotLights:this.numSpotLights,maxBounceCount:this.maxBounces,maxSubsurfaceSteps:this.maxSubsurfaceSteps,transparentBackground:this.transparentBackground,backgroundIntensity:this.backgroundIntensity,backgroundColor:this.backgroundColor,backgroundBlurriness:this.backgroundBlurriness,backgroundBlurSamples:this.backgroundBlurSamples,showBackground:this.showBackground,globalIlluminationIntensity:this.globalIlluminationIntensity,cameraProjectionMatrix:this.cameraProjectionMatrix,cameraViewMatrix:this.cameraViewMatrix,fireflyThreshold:this.fireflyThreshold,frame:this.frame,resolution:this.resolution,emissiveTriangleCount:this.emissiveTriangleCount,emissiveVec4Offset:this.emissiveVec4Offset,emissiveTotalPower:this.emissiveTotalPower,emissiveBoost:this.emissiveBoost,totalTriangleCount:this.totalTriangleCount,enableEmissiveTriangleSampling:this.enableEmissiveTriangleSampling,lightBVHNodeCount:this.lightBVHNodeCount,reverseMapVec4Offset:this.reverseMapVec4Offset,currentBounce:this._wfCurrentBounce,maxRayCount:this._wfMaxRayCount,auxGBufferEnabled:this._auxGBufferUniform});this._kernelManager.register(`shade`,ee().compute([Math.ceil(a/256),1,1],[256,1,1]));let te=this._useSubgroupCompact&&(this.renderer.hasFeature?this.renderer.hasFeature(`subgroups`):!1);this._compactIsSubgroup=te;let ne=(te?js:As)({rayBufferRO:l.rayBuffer.ro,activeIndicesReadRO:u.getActiveReadRO(),activeIndicesWriteRW:u.getActiveWrite(),counters:m,currentActiveCount:this._wfMaxRayCount});this._kernelManager.register(`compact`,ne().compute([Math.ceil(a/256),1,1],[256,1,1]));let re=(0,n.Fn)(()=>{(0,n.atomicStore)(m.element((0,n.uint)(Ba.ENTERING_COUNT)),this._wfMaxRayCount)});this._kernelManager.register(`enterFull`,re().compute([1,1,1],[1,1,1]));let ie=u.activeIndicesRO.b,ae=u.activeIndices.a,oe=(0,n.Fn)(()=>{let e=n.instanceIndex;(0,n.If)(e.greaterThanEqual((0,n.atomicLoad)(m.element((0,n.uint)(Ba.ACTIVE_RAY_COUNT)))),()=>{(0,n.Return)()}),ae.element(e).assign(ie.element(e))});this._kernelManager.register(`compactCopyback`,oe().compute([Math.ceil(a/256),1,1],[256,1,1]));let P=Ns({rayBufferRO:l.rayBuffer.ro,gBufferRO:c,writeColorTex:p.color,writeNDTex:p.normalDepth,writeAlbedoTex:p.albedo,resolution:this.resolution,frame:this.frame,enableAccumulation:this.enableAccumulation,hasPreviousAccumulated:this.hasPreviousAccumulated,accumulationAlpha:this.accumulationAlpha,cameraIsMoving:this.cameraIsMoving,transparentBackground:this.transparentBackground,prevAccumTexture:d,prevAlbedoTexture:f,renderWidth:this._wfRenderWidth,renderHeight:this._wfRenderHeight,visMode:this.visMode,auxGBufferEnabled:this._auxGBufferUniform});this._kernelManager.register(`finalWrite`,P().compute([Math.ceil(r/16),Math.ceil(i/16),1],[16,16,1]));let se=Rs({writeColorTex:p.color,writeNDTex:p.normalDepth,writeAlbedoTex:p.albedo,resolution:this.resolution,renderWidth:this._wfRenderWidth,renderHeight:this._wfRenderHeight,cameraWorldMatrix:this.cameraWorldMatrix,cameraProjectionMatrixInverse:this.cameraProjectionMatrixInverse,cameraProjectionMatrix:this.cameraProjectionMatrix,cameraViewMatrix:this.cameraViewMatrix,enableDOF:this.enableDOF,focalLength:this.focalLength,aperture:this.aperture,focusDistance:this.focusDistance,sceneScale:this.sceneScale,apertureScale:this.apertureScale,anamorphicRatio:this.anamorphicRatio,bvhBuffer:C,triangleBuffer:w,materialBuffer:T,envTexture:M,environmentMatrix:this.environmentMatrix,environmentIntensity:this.environmentIntensity,enableEnvironmentLight:this.enableEnvironment,visMode:this.visMode,debugVisScale:this.debugVisScale,frame:this.frame});this._kernelManager.register(`debug`,se().compute([Math.ceil(r/16),Math.ceil(i/16),1],[16,16,1])),this._wavefrontReady=!0,console.log(`PathTracer: all wavefront kernels built (${r}×${i}, ${a} rays)`)}_setWfDispatch(){let e=this._wfRenderWidth.value,t=this._wfRenderHeight.value;this._kernelManager.setDispatchCount(`generate`,[Math.ceil(e/16),Math.ceil(t/16),1]),this._kernelManager.setDispatchCount(`finalWrite`,[Math.ceil(e/16),Math.ceil(t/16),1]),this._kernelManager.setDispatchCount(`debug`,[Math.ceil(e/16),Math.ceil(t/16),1])}dispose(){super.dispose(),this._packedBuffers?.dispose(),this._queueManager?.dispose(),this._kernelManager?.dispose(),this._gBufferAttr?.dispose?.(),this._packedBuffers=null,this._queueManager=null,this._kernelManager=null,this._gBufferAttr=null,this._wavefrontReady=!1}},Ws=class extends ve{constructor(e,i={}){super(`NormalDepth`,{...i,executionMode:_e.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.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(H,H),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(H,H),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._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,this._hasHistory=!1})}_syncStorageBuffers(){let e=this.pathTracer;if(!e)return!1;let t=e.materialData?.materialStorageAttr,r=e.triangleStorageAttr&&e.triangleStorageAttr!==this._lastTriAttr,i=e.bvhStorageAttr&&e.bvhStorageAttr!==this._lastBvhAttr,a=t&&t!==this._lastMatAttr;return(r||i||a)&&(this._computeNode?.dispose?.(),this._computeNode=null,this._computeBuilt=!1,this._triStorageNode=null,this._bvhStorageNode=null,this._matStorageNode=null,this._dirty=!0),e.triangleStorageAttr&&!this._triStorageNode&&(this._triStorageNode=(0,n.storage)(e.triangleStorageAttr,`vec4`,e.triangleStorageAttr.count).toReadOnly()),e.bvhStorageAttr&&!this._bvhStorageNode&&(this._bvhStorageNode=(0,n.storage)(e.bvhStorageAttr,`vec4`,e.bvhStorageAttr.count).toReadOnly()),t&&!this._matStorageNode&&(this._matStorageNode=(0,n.storage)(t,`vec4`,t.count).toReadOnly()),this._linearBuckets&&mr(this._linearBuckets,e.materialData?.linearBuckets),this._lastTriAttr=e.triangleStorageAttr||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=pr(this.pathTracer?.materialData?.linearBuckets),sr(pr(null),this._linearBuckets);let i=this.cameraWorldMatrix,a=this.cameraProjectionMatrixInverse,o=this.resolutionWidth,s=this.resolutionHeight,c=this._outputStorageTex,l=this._shadingStorageTex;this._computeNode=(0,n.Fn)(([i,a])=>{let u=(0,n.int)(n.workgroupId.x).mul(8).add((0,n.int)(n.localId.x)),d=(0,n.int)(n.workgroupId.y).mul(8).add((0,n.int)(n.localId.y));(0,n.If)(u.lessThan((0,n.int)(o)).and(d.lessThan((0,n.int)(s))),()=>{let f=(0,n.vec3)((0,n.float)(u).add(.5).div(o).mul(2).sub(1),(0,n.float)(d).add(.5).div(s).mul(2).sub(1).negate(),1),p=a.mul((0,n.vec4)(f,1)),m=(0,n.normalize)((0,n.mat3)(i[0].xyz,i[1].xyz,i[2].xyz).mul(p.xyz.div(p.w))),h=Dt({origin:(0,n.vec3)(i[3]),direction:m}),g=jt.wrap(oo(h,t,e)),_=g.normal.mul(.5).add(.5),v=(0,n.min)(g.dst,(0,n.float)(65504)),y=g.didHit.select((0,n.vec4)(_,v),(0,n.vec4)(0,0,0,(0,n.float)(65504)));(0,n.textureStore)(c,(0,n.uvec2)((0,n.uint)(u),(0,n.uint)(d)),y).toWriteOnly();let b=g.normal.toVar();(0,n.If)(g.didHit,()=>{let e=Ot.wrap(pn(g.materialIndex,r)).toVar(),t=zt.wrap(yr(g.uv,e)).toVar(),n=Sr(g.normal,e,t).toVar();b.assign(Cr(n,e,t))});let x=g.didHit.select((0,n.vec4)(b.mul(.5).add(.5),v),(0,n.vec4)(0,0,0,(0,n.float)(65504)));(0,n.textureStore)(l,(0,n.uvec2)((0,n.uint)(u),(0,n.uint)(d)),x).toWriteOnly()})})(i,a).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._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);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._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._dirty=!1}releaseGPUMemory(){this._outputStorageTex?.dispose(),this._shadingStorageTex?.dispose(),this.reset()}reset(){this._dirty=!0,this._hasHistory=!1}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._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}dispose(){this._computeNode?.dispose(),this._outputStorageTex?.dispose(),this._shadingStorageTex?.dispose(),this._shadingRT?.dispose(),this._rtA?.dispose(),this._rtB?.dispose()}},Gs=class extends ve{constructor(e,i,a={}){super(`MotionVector`,{...a,executionMode:_e.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.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(H,H),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(H,H),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=(0,n.vec3)((0,n.float)(c).add(.5).div(a).mul(2).sub(1),(0,n.float)(l).add(.5).div(o).mul(2).sub(1).negate(),1),s=r.mul((0,n.vec4)(e,1)),p=(0,n.normalize)((0,n.mat3)(t[0].xyz,t[1].xyz,t[2].xyz).mul(s.xyz.div(s.w))),m=(0,n.vec3)(t[3]).add(p.mul(u)),h=i.mul((0,n.vec4)(m,1)),g=h.xy.div(h.w),_=(0,n.vec2)(g.x.mul(.5).add(.5),g.y.mul(-.5).add(.5)),v=d.sub(_),y=_.x.greaterThanEqual(0).and(_.x.lessThanEqual(1)).and(_.y.greaterThanEqual(0)).and(_.y.lessThanEqual(1));f.assign(y.select((0,n.vec4)(v,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.vec3)((0,n.float)(d).add(.5).div(c).mul(2).sub(1),(0,n.float)(f).add(.5).div(l).mul(2).sub(1).negate(),1),a=r.mul((0,n.vec4)(e,1)),u=(0,n.normalize)((0,n.mat3)(t[0].xyz,t[1].xyz,t[2].xyz).mul(a.xyz.div(a.w))),h=(0,n.vec3)(t[3]).add(u.mul(p)),g=(0,n.vec2)((0,n.float)(d).add(.5).div(c),(0,n.float)(f).add(.5).div(l)),_=i.mul((0,n.vec4)(h,1)),v=_.xy.div(_.w),y=(0,n.vec2)(v.x.mul(.5).add(.5),v.y.mul(-.5).add(.5)),b=y.x.greaterThanEqual(0).and(y.x.lessThanEqual(1)).and(y.y.greaterThanEqual(0)).and(y.y.lessThanEqual(1)),x=g.sub(y),S=(0,n.vec3)(x.x.div(o).mul(s),x.y.div(o).mul(s),0);m.assign(b.select((0,n.vec4)(S,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)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}dispose(){this._screenSpaceComputeNode?.dispose(),this._worldSpaceComputeNode?.dispose(),this._screenSpaceStorageTex?.dispose(),this._worldSpaceStorageTex?.dispose(),this.screenSpaceTarget?.dispose(),this.worldSpaceTarget?.dispose(),this._normalDepthTexNode?.dispose()}},Ks=e=>(0,n.select)(e.equal(e),e,(0,n.float)(0)).clamp(0,1e7),qs=e=>(0,n.vec3)(Ks(e.x),Ks(e.y),Ks(e.z)),Js=class extends ve{constructor(e,i={}){super(`ASVGF`,{...i,executionMode:_e.PER_CYCLE}),this.renderer=e,this.temporalAlpha=(0,n.uniform)(i.temporalAlpha??0),this.gradientStrength=(0,n.uniform)(i.gradientStrength??0),this.gradientSigmaScale=(0,n.uniform)(i.gradientSigmaScale??2),this.gradientNoiseFloor=(0,n.uniform)(i.gradientNoiseFloor??0),this.maxAccumFrames=(0,n.uniform)(i.maxAccumFrames??32),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(H,H),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(H,H),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(H,H),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(H,H),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(H,H),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=tn(qs(m.div((0,n.max)(_,(0,n.vec3)(V))))).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(tn(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).xyz,x=(0,n.textureLoad)(r,y).xyz,S=(0,n.max)(x,(0,n.vec3)(V)),C=qs(b.div(S)),w=(0,n.vec4)(C,1).toVar(),T=(0,n.vec4)(b,1).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)),E=p.clamp((0,n.int)(0),(0,n.int)(h).sub(1)),D=_.clamp((0,n.int)(0),(0,n.int)(h).sub(1)),O=m.clamp((0,n.int)(0),(0,n.int)(g).sub(1)),k=v.clamp((0,n.int)(0),(0,n.int)(g).sub(1)),A=(0,n.float)(1).sub(b).mul((0,n.float)(1).sub(x)),j=b.mul((0,n.float)(1).sub(x)),M=(0,n.float)(1).sub(b).mul(x),N=b.mul(x),ee=(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)},te=ee(E,O,A),ne=ee(D,O,j),re=ee(E,k,M),ie=ee(D,k,N),ae=te.add(ne).add(re).add(ie);(0,n.If)(ae.greaterThan((0,n.float)(.01)),()=>{let e=(0,n.textureLoad)(s,(0,n.ivec2)(E,O)),t=(0,n.textureLoad)(s,(0,n.ivec2)(D,O)),r=(0,n.textureLoad)(s,(0,n.ivec2)(E,k)),i=(0,n.textureLoad)(s,(0,n.ivec2)(D,k)),a=(0,n.float)(1).div(ae),o=e.xyz.mul(te).add(t.xyz.mul(ne)).add(r.xyz.mul(re)).add(i.xyz.mul(ie)).mul(a),l=e.w.mul(te).add(t.w.mul(ne)).add(r.w.mul(re)).add(i.w.mul(ie)).mul(a),p=(0,n.textureLoad)(c,y).x.mul(f).clamp(0,1),m=qs((0,n.mix)(o,C,(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);w.assign((0,n.vec4)(m,h)),T.assign((0,n.vec4)(m.mul(S),1))})})}),(0,n.textureStore)(e,(0,n.uvec2)((0,n.uint)(_),(0,n.uint)(v)),w).toWriteOnly(),(0,n.textureStore)(l,(0,n.uvec2)((0,n.uint)(_),(0,n.uint)(v)),T).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=tn(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(`asvgf:reset`,()=>this.resetTemporalData()),this.on(`asvgf:setTemporal`,e=>{e&&e.enabled!==void 0&&this.setTemporalEnabled(e.enabled)}),this.on(`asvgf:updateParameters`,e=>this.updateParameters(e))}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}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()}},Ys=e=>(0,n.select)(e.equal(e),e,(0,n.float)(0)).clamp(0,1e7),Xs=(0,n.wgslFn)(`
|
|
670
670
|
fn temporalAccumulate(
|
|
671
671
|
lum: f32,
|
|
672
672
|
prevMean: f32,
|