@hology/webgpu-renderer 0.1.0 → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var e=class{layout;pipeline;constructor(e,t){this.layout=e.createBindGroupLayout({label:t.label?`${t.label}-layout`:void 0,entries:t.bindGroupLayoutEntries});const r=e.createPipelineLayout({label:t.label?`${t.label}-pipeline-layout`:void 0,bindGroupLayouts:[this.layout]});this.pipeline=e.createComputePipeline({label:t.label,layout:r,compute:{module:e.createShaderModule({label:t.label?`${t.label}-module`:void 0,code:t.code}),entryPoint:t.entryPoint??"main"}})}createBindGroup(e,t,r){return e.createBindGroup({label:r,layout:this.layout,entries:t})}};import{Color as t,DirectionalLight as r,Matrix4 as n,Object3D as i,PointLight as a,Scene as s,SpotLight as o,Vector3 as l}from"three";var c=class extends i{constructor(e){super(),this.volume=e}volume;isFogVolumeObject=!0},u=(new n).set(1,0,0,0,0,1,0,0,0,0,.5,.5,0,0,0,1),d=new l,h=new l,p=new l,f=class{constructor(e=new s,r={}){this.scene=e,this.options={froxelPixelSize:Math.max(2,Math.floor(r.froxelPixelSize??8)),depthSlices:Math.max(8,Math.floor(r.depthSlices??64)),integrationSubsteps:r.integrationSubsteps??2,maxDistance:Math.max(1,r.maxDistance??256),targetPrefix:r.targetPrefix??"volumetricFog",maxVolumes:Math.max(1,Math.floor(r.maxVolumes??32)),maxDirectionalLights:Math.min(4,Math.max(1,Math.floor(r.maxDirectionalLights??4))),maxPointLights:Math.min(4,Math.max(0,Math.floor(r.maxPointLights??4))),maxSpotLights:Math.min(4,Math.max(0,Math.floor(r.maxSpotLights??4))),ambientColor:r.ambientColor?.clone()??new t(.03,.035,.045),shadowFilterTaps:r.shadowFilterTaps??4,temporalJitter:r.temporalJitter??!0,spatialJitter:r.spatialJitter??!0,fogDitherStrength:Math.max(0,r.fogDitherStrength??.75),scatteringIntensity:Math.max(0,r.scatteringIntensity??1),blur:!1!==r.blur&&{scale:Math.max(.125,Math.min(1,r.blur?.scale??.5)),radius:Math.max(1,Math.min(12,Math.floor(r.blur?.radius??3))),depthSigma:Math.max(1e-4,r.blur?.depthSigma??.05),spatialSigma:Math.max(.1,r.blur?.spatialSigma??2),depthAwareUpsample:r.blur?.depthAwareUpsample??!0}},this.integratedVolume=`${this.options.targetPrefix}Integrated`,this.columnDepthBounds=`${this.options.targetPrefix}DepthBounds`,this.volumeData=new Float32Array(20*this.options.maxVolumes);const n=this.options.maxDirectionalLights+this.options.maxPointLights+this.options.maxSpotLights;this.lightData=new Float32Array(16*n)}scene;integratedVolume;columnDepthBounds;options;resources=new WeakMap;uniformStorage=new ArrayBuffer(160);uniforms=new Float32Array(this.uniformStorage);uniformIntegers=new Uint32Array(this.uniformStorage);volumeData;lightData;projectionInverse=new n;viewProjectionInverse=new n;explicitVolumes=[];cascadeDirectionalLights=[];compositePass=null;blurPassCache=new Map;frameIndex=0;setScene(e){this.scene=e}setCascadedDirectionalLights(e){this.cascadeDirectionalLights=e}addPasses(e,t){this.explicitVolumes=t.volumes??[],e.createTextureTarget(this.integratedVolume,{dimension:"3d",depthOrArrayLayers:this.options.depthSlices,scale:1/this.options.froxelPixelSize,format:"rgba16float",usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.STORAGE_BINDING}),e.createTextureTarget(this.columnDepthBounds,{scale:1/this.options.froxelPixelSize,format:"rg32float",usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.STORAGE_BINDING}),e.addPass({name:"VolumetricFogFroxelPass",inputs:{sceneDepth:t.depth},outputs:[this.integratedVolume,this.columnDepthBounds],execute:e=>this.executeFroxels(e)});const r=e.createColorTarget(`${this.options.targetPrefix}Composite`,{format:"rgba16float"});return!1!==this.options.blur?this.addBlurredComposite(e,t,r):(this.compositePass&&this.compositePass.matches(t.sceneColor,t.depth,r)||(this.compositePass=new m(t.sceneColor,t.depth,this.integratedVolume,this.columnDepthBounds,r,this.options.maxDistance,this.options.fogDitherStrength)),this.compositePass.setFrameIndex(this.frameIndex),e.addFullscreenPass(this.compositePass),r)}addBlurredComposite(e,t,r){const n=this.options.blur;if(!1===n)return r;const i=e.createColorTarget(`${this.options.targetPrefix}Resolved`,{format:"rgba16float",scale:n.scale}),a=e.createColorTarget(`${this.options.targetPrefix}BlurTemporary`,{format:"rgba16float",scale:n.scale}),s=e.createColorTarget(`${this.options.targetPrefix}Blurred`,{format:"rgba16float",scale:n.scale}),o=`resolve:${t.depth}:${i}`;let l=this.blurPassCache.get(o);l||(l=new g(t.depth,this.integratedVolume,this.columnDepthBounds,i,this.options.maxDistance,this.options.fogDitherStrength),this.blurPassCache.set(o,l)),l.setFrameIndex(this.frameIndex),e.addFullscreenPass(l);for(const[r,o,l]of[[i,a,[1,0]],[a,s,[0,1]]]){const i=`blur:${r}:${o}:${l[0]}:${n.radius}:${n.depthSigma}:${n.spatialSigma}`;let a=this.blurPassCache.get(i);a||(a=new x(r,t.depth,o,l,n),this.blurPassCache.set(i,a)),e.addFullscreenPass(a)}const c=`blurComposite:${t.sceneColor}:${t.depth}:${s}:${r}:${n.depthAwareUpsample}`;let u=this.blurPassCache.get(c);return u||(u=new v(t.sceneColor,t.depth,s,this.integratedVolume,this.columnDepthBounds,r,n.depthAwareUpsample),this.blurPassCache.set(c,u)),e.addFullscreenPass(u),r}dispose(){this.compositePass=null}executeFroxels(e){const t=this.getResources(e.device),r=this.collectSceneData(e.camera),n=Math.max(.01,e.camera.near),i=Math.max(n+.01,Math.min(e.camera.far,this.options.maxDistance)),a=Math.max(1,Math.floor(e.width/this.options.froxelPixelSize)),s=Math.max(1,Math.floor(e.height/this.options.froxelPixelSize));this.viewProjectionInverse.copy(u).multiply(e.camera.projectionMatrix).multiply(e.camera.matrixWorldInverse).invert(),this.uniforms.set(this.viewProjectionInverse.elements,0),this.uniforms.set(e.camera.position.toArray(),16),this.uniforms.set([n],19),this.uniforms.set([a,s,this.options.depthSlices,i],20),this.uniformIntegers.set([r.volumes,r.directional,r.point,r.spot],24),this.uniforms.set([this.options.ambientColor.r,this.options.ambientColor.g,this.options.ambientColor.b,this.options.temporalJitter?this.frameIndex++%1024+1:0],28),e.camera.getWorldDirection(h),this.uniforms.set([h.x,h.y,h.z,Math.max(e.camera.far-n,1e-4)],32),this.uniforms.set([this.options.scatteringIntensity,this.options.spatialJitter?1:0,0,0],36),e.device.queue.writeBuffer(t.uniformBuffer,0,this.uniforms),e.device.queue.writeBuffer(t.volumeBuffer,0,this.volumeData.buffer,this.volumeData.byteOffset,this.volumeData.byteLength),e.device.queue.writeBuffer(t.lightBuffer,0,this.lightData.buffer,this.lightData.byteOffset,this.lightData.byteLength);const o=e.getSceneLightingResources(),l=e.device.createBindGroup({label:"volumetric-fog-bind-group",layout:t.layout,entries:[{binding:0,resource:{buffer:t.uniformBuffer}},{binding:1,resource:{buffer:t.volumeBuffer}},{binding:2,resource:{buffer:t.lightBuffer}},{binding:3,resource:e.getTextureView(this.integratedVolume)},{binding:4,resource:{buffer:o.lightBuffer}},{binding:5,resource:e.comparisonSampler},{binding:6,resource:o.directionalShadowView},{binding:7,resource:o.pointShadowView},{binding:8,resource:o.spotShadowView},{binding:9,resource:e.depthView},{binding:10,resource:e.getTextureView(this.columnDepthBounds)}]}),c=e.encoder.beginComputePass({label:"VolumetricFogFroxelPass"});c.setPipeline(t.pipeline),c.setBindGroup(0,l),c.dispatchWorkgroups(Math.ceil(a/8),Math.ceil(s/8)),c.end()}collectSceneData(e){this.volumeData.fill(0),this.lightData.fill(0);const t=[...this.explicitVolumes],n=[];for(const t of this.cascadeDirectionalLights)t.visible&&t.layers.test(e.layers)&&!n.includes(t)&&n.push(t);const i=[],s=[];this.scene.traverseVisible(l=>{const c=l;c.isFogVolumeObject&&c.volume&&!t.includes(c.volume)?t.push(c.volume):l instanceof r&&l.layers.test(e.layers)&&!n.includes(l)?n.push(l):l instanceof a&&l.layers.test(e.layers)?i.push(l):l instanceof o&&l.layers.test(e.layers)&&s.push(l)});const l=Math.min(t.length,this.options.maxVolumes);for(let e=0;e<l;e++)this.writeVolume(e,t[e]);const c=Math.min(n.length,this.options.maxDirectionalLights),u=Math.min(i.length,this.options.maxPointLights),d=Math.min(s.length,this.options.maxSpotLights);let h=0;for(let e=0;e<c;e++)this.writeDirectional(h++,n[e]);for(let e=0;e<u;e++)this.writePoint(h++,i[e]);for(let e=0;e<d;e++)this.writeSpot(h++,s[e]);return{volumes:l,directional:c,point:u,spot:d}}writeVolume(e,t){const r=20*e;t.object.getWorldPosition(d),t.object.getWorldScale(p),this.volumeData.set([d.x,d.y,d.z,5*Math.max(p.x,p.y,p.z)],r),this.volumeData.set([t.albedo.r,t.albedo.g,t.albedo.b,Math.max(0,t.baseDensity)],r+4),this.volumeData.set([t.heightFalloff,t.heightOffset,t.startDistance??3,-Math.max(-.99,Math.min(.99,t.scatteringDistribution))],r+8),this.volumeData.set([t.emissive.r,t.emissive.g,t.emissive.b,t.ambientIntensity??1],r+12),this.volumeData[r+16]="lightShaft"===t.scatteringMode?1:0}lightColor(e){const t=e.intensity*(e.userData?.volumetricIntensity??1);return[e.color.r*t,e.color.g*t,e.color.b*t]}writeDirectional(e,t){const r=16*e;t.getWorldPosition(d),t.target.getWorldPosition(h),h.sub(d).normalize(),this.lightData.set([h.x,h.y,h.z,0],r),this.lightData.set([...this.lightColor(t),0],r+4)}writePoint(e,t){const r=16*e;t.getWorldPosition(d),this.lightData.set([d.x,d.y,d.z,Math.max(.001,t.distance||this.options.maxDistance)],r),this.lightData.set([...this.lightColor(t),Math.max(0,t.decay)],r+4)}writeSpot(e,t){const r=16*e;t.getWorldPosition(d),t.target.getWorldPosition(h),h.sub(d).normalize(),this.lightData.set([d.x,d.y,d.z,Math.max(.001,t.distance||this.options.maxDistance)],r),this.lightData.set([...this.lightColor(t),Math.max(0,t.decay)],r+4),this.lightData.set([h.x,h.y,h.z,Math.cos(t.angle)],r+8),this.lightData[r+12]=Math.cos(t.angle*(1-t.penumbra))}getResources(e){const t=this.resources.get(e);if(t)return t;const r=e.createBuffer({size:160,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),n=e.createBuffer({size:this.volumeData.byteLength,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST}),i=e.createBuffer({size:this.lightData.byteLength,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST}),a=e.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.COMPUTE,buffer:{type:"uniform"}},{binding:1,visibility:GPUShaderStage.COMPUTE,buffer:{type:"read-only-storage"}},{binding:2,visibility:GPUShaderStage.COMPUTE,buffer:{type:"read-only-storage"}},{binding:3,visibility:GPUShaderStage.COMPUTE,storageTexture:{access:"write-only",format:"rgba16float",viewDimension:"3d"}},{binding:4,visibility:GPUShaderStage.COMPUTE,buffer:{type:"uniform"}},{binding:5,visibility:GPUShaderStage.COMPUTE,sampler:{type:"comparison"}},{binding:6,visibility:GPUShaderStage.COMPUTE,texture:{sampleType:"depth",viewDimension:"2d-array"}},{binding:7,visibility:GPUShaderStage.COMPUTE,texture:{sampleType:"float",viewDimension:"2d-array"}},{binding:8,visibility:GPUShaderStage.COMPUTE,texture:{sampleType:"depth",viewDimension:"2d-array"}},{binding:9,visibility:GPUShaderStage.COMPUTE,texture:{sampleType:"depth",viewDimension:"2d"}},{binding:10,visibility:GPUShaderStage.COMPUTE,storageTexture:{access:"write-only",format:"rg32float",viewDimension:"2d"}}]}),s=e.createShaderModule({label:"volumetric-fog-compute",code:y.replace("__SHADOW_TAPS__",String(this.options.shadowFilterTaps)).replace("__INTEGRATION_SUBSTEPS__",String(this.options.integrationSubsteps))}),o={uniformBuffer:r,volumeBuffer:n,lightBuffer:i,layout:a,pipeline:e.createComputePipeline({layout:e.createPipelineLayout({bindGroupLayouts:[a]}),compute:{module:s,entryPoint:"main"}})};return this.resources.set(e,o),o}},m=class{constructor(e,t,r,n,i,a,s){this.maxDistance=a,this.ditherStrength=s,this.inputs={sceneColor:e,sceneDepth:t,fogVolume:r,fogBounds:n},this.outputs=i}maxDistance;ditherStrength;name="VolumetricFogCompositePass";sampler="linear";uniformBufferSize=80;inputs;inputDimensions={fogVolume:"3d"};outputs;fragmentShader=S;data=new Float32Array(20);inverseProjection=new n;frameIndex=0;setFrameIndex(e){this.frameIndex=e}matches(e,t,r){return this.inputs.sceneColor===e&&this.inputs.sceneDepth===t&&this.outputs===r}updateUniforms=e=>(this.inverseProjection.copy(u).multiply(e.camera.projectionMatrix).invert(),this.data.set(this.inverseProjection.elements,0),this.data.set([Math.max(.01,e.camera.near),Math.min(e.camera.far,this.maxDistance),this.frameIndex>0?this.frameIndex%1024:-1,this.ditherStrength],16),this.data)},g=class{constructor(e,t,r,n,i,a){this.maxDistance=i,this.ditherStrength=a,this.inputs={sceneDepth:e,fogVolume:t,fogBounds:r},this.outputs=n}maxDistance;ditherStrength;name="VolumetricFogResolvePass";sampler="linear";uniformBufferSize=80;inputDimensions={fogVolume:"3d"};inputs;outputs;fragmentShader=C;data=new Float32Array(20);inverseProjection=new n;frameIndex=0;setFrameIndex(e){this.frameIndex=e}updateUniforms=e=>(this.inverseProjection.copy(u).multiply(e.camera.projectionMatrix).invert(),this.data.set(this.inverseProjection.elements,0),this.data.set([Math.max(.01,e.camera.near),Math.min(e.camera.far,this.maxDistance),this.frameIndex>0?this.frameIndex%1024:-1,this.ditherStrength],16),this.data)},x=class{name;sampler="linear";uniformBufferSize=80;inputs;outputs;fragmentShader;data=new Float32Array(20);inverseProjection=new n;constructor(e,t,r,n,i){this.name=n[0]?"VolumetricFogBlurHorizontalPass":"VolumetricFogBlurVerticalPass",this.inputs={fogInput:e,sceneDepth:t},this.outputs=r,this.data.set([n[0],n[1],i.depthSigma,i.spatialSigma],16),this.fragmentShader=`\nconst BLUR_RADIUS:i32=${i.radius};\nfn inverseProjection() -> mat4x4<f32> { return mat4x4<f32>(fullscreenUniforms[0],fullscreenUniforms[1],fullscreenUniforms[2],fullscreenUniforms[3]); }\nfn viewDistance(uv:vec2<f32>)->f32 { let size=vec2<i32>(textureDimensions(sceneDepthTexture));let pixel=clamp(vec2<i32>(uv*vec2<f32>(size)),vec2<i32>(0),size-vec2<i32>(1));let depth=textureLoad(sceneDepthTexture,pixel,0);let clip=vec4<f32>(uv.x*2.0-1.0,1.0-uv.y*2.0,depth,1.0);let view=inverseProjection()*clip;return length(view.xyz/view.w); }\n@fragment fn fsMain(input:FullscreenVertexOutput)->@location(0) vec4<f32>{\n let size=vec2<f32>(textureDimensions(fogInputTexture));let texel=1.0/size;let direction=fullscreenUniforms[4].xy;let depthSigma=fullscreenUniforms[4].z;let spatialSigma=fullscreenUniforms[4].w;\n let centerDepth=viewDistance(input.uv);var sum=vec4<f32>(0.0);var weightSum=0.0;\n for(var i=-BLUR_RADIUS;i<=BLUR_RADIUS;i+=1){let uv=clamp(input.uv+direction*f32(i)*texel,vec2<f32>(0.0),vec2<f32>(1.0));let sampleDepth=viewDistance(uv);let fi=f32(i);let spatial=exp(-0.5*fi*fi/(spatialSigma*spatialSigma));let delta=log(max(sampleDepth,0.0001)/max(centerDepth,0.0001));let depthWeight=exp(-0.5*delta*delta/(depthSigma*depthSigma));let weight=spatial*depthWeight;sum+=textureSampleLevel(fogInputTexture,fullscreenSampler,uv,0.0)*weight;weightSum+=weight;}\n return sum/max(weightSum,0.0001);\n}`}updateUniforms=e=>(this.inverseProjection.copy(u).multiply(e.camera.projectionMatrix).invert(),this.data.set(this.inverseProjection.elements,0),this.data)},v=class{name="VolumetricFogBlurCompositePass";sampler="linear";uniformBufferSize=64;inputs;inputDimensions={fogVolume:"3d"};outputs;fragmentShader;data=new Float32Array(16);inverseProjection=new n;constructor(e,t,r,n,i,a,s){this.inputs=s?{sceneColor:e,sceneDepth:t,fogInput:r,fogVolume:n,fogBounds:i}:{sceneColor:e,fogInput:r},this.outputs=a,this.fragmentShader=s?P:M}updateUniforms=e=>(this.inverseProjection.copy(u).multiply(e.camera.projectionMatrix).invert(),this.data.set(this.inverseProjection.elements),this.data)},w="\nfn rendererSampleIntegratedFog(uv: vec2<f32>, normalizedDepth: f32) -> vec4<f32> {\n let sliceCount = f32(textureDimensions(volumetricFogTexture).z);\n let slicePosition = clamp(normalizedDepth, 0.0, 1.0) * sliceCount;\n let textureZ = clamp((slicePosition - 0.5) / sliceCount, 0.0, 1.0);\n let integrated = textureSampleLevel(volumetricFogTexture, volumetricFogSampler, vec3<f32>(uv, textureZ), 0.0);\n // The volume stores slice endpoints but has no texel for the near-plane\n // identity value. Reconstruct that missing endpoint for the first slice.\n return mix(vec4<f32>(0.0, 0.0, 0.0, 1.0), integrated, min(slicePosition, 1.0));\n}\nfn rendererApplyVolumetricFog(color: vec4<f32>, worldPosition: vec3<f32>) -> vec4<f32> {\n let clip = rendererCamera.viewProj * vec4<f32>(worldPosition, 1.0);\n let uv = clip.xy / clip.w * vec2<f32>(0.5, -0.5) + vec2<f32>(0.5);\n let distance = length(worldPosition - rendererCamera.cameraPosition.xyz);\n let bounds = textureSampleLevel(volumetricFogBoundsTexture, volumetricFogBoundsSampler, uv, 0.0).rg;\n let z = clamp((distance - bounds.x) / max(bounds.y - bounds.x, 0.001), 0.0, 1.0);\n let fog = rendererSampleIntegratedFog(uv, z);\n return vec4<f32>(fog.rgb + color.rgb * fog.a, color.a);\n}";function b(e,t="volumetricFogIntegrated",r=(t.endsWith("Integrated")?`${t.slice(0,-10)}DepthBounds`:"volumetricFogDepthBounds")){return e.graphTextures.volumetricFog={resource:t,dimension:"3d",sampleType:"float",sampler:"filtering",requiresLatePass:!0},e.graphTextures.volumetricFogBounds={resource:r,dimension:"2d",sampleType:"float",sampler:"filtering",requiresLatePass:!0},e.needsUpdate=!0,e}var y="\nstruct FogUniforms { inverseViewProjection: mat4x4<f32>, cameraNear: vec4<f32>, dimensionsFar: vec4<f32>, counts: vec4<u32>, ambient: vec4<f32>, cameraForwardDepthRange: vec4<f32>, scattering: vec4<f32> };\nstruct FogVolume { centerRadius: vec4<f32>, albedoDensity: vec4<f32>, heightStartPhase: vec4<f32>, emissiveAmbient: vec4<f32>, mode: vec4<f32> };\nstruct FogLight { positionRange: vec4<f32>, colorDecay: vec4<f32>, directionCone: vec4<f32>, penumbra: vec4<f32> };\nstruct RendererLightUniforms {\n ambientColor: vec4<f32>, lightCounts: vec4<f32>,\n directionalDirections: array<vec4<f32>,4>, directionalColorIntensities: array<vec4<f32>,4>,\n directionalShadowParams: array<vec4<f32>,4>, directionalShadowParams2: array<vec4<f32>,4>, directionalShadowMatrices: array<mat4x4<f32>,4>,\n pointPositionRanges: array<vec4<f32>,4>, pointColorIntensities: array<vec4<f32>,4>, pointShadowParams: array<vec4<f32>,4>, pointShadowParams2: array<vec4<f32>,4>,\n spotPositionRanges: array<vec4<f32>,4>, spotDirectionCones: array<vec4<f32>,4>, spotColorIntensities: array<vec4<f32>,4>,\n spotShadowParams: array<vec4<f32>,4>, spotShadowParams2: array<vec4<f32>,4>, spotParams: array<vec4<f32>,4>, spotShadowMatrices: array<mat4x4<f32>,4>,\n csmCascadeRanges: array<vec4<f32>,4>, hemisphereSkyColorIntensity: vec4<f32>, hemisphereGroundColorIntensity: vec4<f32>, hemisphereDirection: vec4<f32>\n};\n@group(0) @binding(0) var<uniform> uniforms: FogUniforms;\n@group(0) @binding(1) var<storage, read> volumes: array<FogVolume>;\n@group(0) @binding(2) var<storage, read> lights: array<FogLight>;\n@group(0) @binding(3) var outputFog: texture_storage_3d<rgba16float, write>;\n@group(0) @binding(4) var<uniform> rendererLights: RendererLightUniforms;\n@group(0) @binding(5) var shadowSampler: sampler_comparison;\n@group(0) @binding(6) var directionalShadows: texture_depth_2d_array;\n@group(0) @binding(7) var pointShadows: texture_2d_array<f32>;\n@group(0) @binding(8) var spotShadows: texture_depth_2d_array;\n@group(0) @binding(9) var sceneDepth: texture_depth_2d;\n@group(0) @binding(10) var outputDepthBounds: texture_storage_2d<rg32float, write>;\nconst PI = 3.14159265359;\nconst SHADOW_TAPS = __SHADOW_TAPS__;\nconst INTEGRATION_SUBSTEPS = __INTEGRATION_SUBSTEPS__;\nfn phaseHG(cosTheta: f32, g: f32) -> f32 { let gg = g*g; return (1.0-gg)/(4.0*PI*pow(max(0.001,1.0+gg-2.0*g*cosTheta),1.5)); }\nfn attenuation(distance: f32, range: f32, decay: f32) -> f32 { let window = max(0.0, 1.0-pow(distance/range,4.0)); return window*window / max(1.0, pow(distance, decay)); }\nfn hash12(p:vec2<f32>)->f32 { let p3=fract(vec3<f32>(p.xyx)*0.1031); let q=p3+dot(p3,p3.yzx+33.33); return fract((q.x+q.y)*q.z); }\nfn rotatedOffset(tap:i32, angle:f32)->vec2<f32> {\n let disk=array<vec2<f32>,4>(vec2<f32>(-0.326,-0.406),vec2<f32>(-0.840,0.074),vec2<f32>(-0.696,0.457),vec2<f32>(0.203,0.621));\n let v=disk[tap]; let c=cos(angle); let s=sin(angle); return vec2<f32>(c*v.x-s*v.y,s*v.x+c*v.y);\n}\nfn projectedShadow(matrix: mat4x4<f32>, p: vec3<f32>, layer: i32, bias: f32, intensity: f32, textureKind: u32) -> f32 {\n let clip=matrix*vec4<f32>(p,1.0); if (clip.w<=0.0) { return 1.0; } let ndc=clip.xyz/clip.w;\n if (ndc.x < -1.0 || ndc.x > 1.0 || ndc.y < -1.0 || ndc.y > 1.0 || ndc.z < 0.0 || ndc.z > 1.0) { return 1.0; }\n let uv=ndc.xy*vec2<f32>(0.5,-0.5)+vec2<f32>(0.5); var visibility=0.0;\n // Avoid a world-space random pattern swimming through the camera-relative grid.\n let angle=select(0.0,hash12(p.xz+vec2<f32>(uniforms.ambient.w, f32(layer)))*6.2831853,uniforms.ambient.w>0.0);\n if (textureKind==0u) {\n let dims=vec2<f32>(textureDimensions(directionalShadows)); let radius=max(rendererLights.directionalShadowParams2[u32(layer)].x,0.0);let offset=radius/dims;let depth=ndc.z+bias;\n // Match the surface-lighting path: a weighted hardware-PCF center and\n // four cardinal taps. The former sparse rotated disk made partially\n // shadowed froxels jump between a few discrete visibility values.\n let center=textureSampleCompareLevel(directionalShadows,shadowSampler,uv,layer,depth);\n if(SHADOW_TAPS==1){\n visibility=center;\n }else{\n let left=textureSampleCompareLevel(directionalShadows,shadowSampler,clamp(uv-vec2<f32>(offset.x,0.0),vec2<f32>(0.0),vec2<f32>(1.0)),layer,depth);\n let right=textureSampleCompareLevel(directionalShadows,shadowSampler,clamp(uv+vec2<f32>(offset.x,0.0),vec2<f32>(0.0),vec2<f32>(1.0)),layer,depth);\n let up=textureSampleCompareLevel(directionalShadows,shadowSampler,clamp(uv-vec2<f32>(0.0,offset.y),vec2<f32>(0.0),vec2<f32>(1.0)),layer,depth);\n let down=textureSampleCompareLevel(directionalShadows,shadowSampler,clamp(uv+vec2<f32>(0.0,offset.y),vec2<f32>(0.0),vec2<f32>(1.0)),layer,depth);\n visibility=(center*4.0+left+right+up+down)*0.5;\n }\n } else {\n let dims=vec2<f32>(textureDimensions(spotShadows)); let radius=max(rendererLights.spotShadowParams2[u32(layer)].x,1.0);\n for(var tap=0;tap<SHADOW_TAPS;tap+=1){let suv=clamp(uv+rotatedOffset(tap,angle)*radius/dims,vec2<f32>(0.0),vec2<f32>(1.0));let pixel=vec2<i32>(clamp(suv*dims,vec2<f32>(0.0),dims-1.0));visibility+=select(0.0,1.0,ndc.z-bias<=textureLoad(spotShadows,pixel,layer,0));}\n }\n visibility/=f32(SHADOW_TAPS);\n return mix(1.0,visibility,intensity);\n}\nfn pointShadowUvLayer(direction: vec3<f32>, index: u32) -> vec3<f32> {\n let a=abs(direction); var face=0u; var uv=vec2<f32>(0.0);\n if (a.x>=a.y && a.x>=a.z) { if(direction.x>=0.0){face=0u;uv=vec2<f32>(-direction.z,-direction.y)/a.x;}else{face=1u;uv=vec2<f32>(direction.z,-direction.y)/a.x;} }\n else if(a.y>=a.x && a.y>=a.z){if(direction.y>=0.0){face=2u;uv=vec2<f32>(direction.x,direction.z)/a.y;}else{face=3u;uv=vec2<f32>(direction.x,-direction.z)/a.y;}}\n else{if(direction.z>=0.0){face=4u;uv=vec2<f32>(direction.x,-direction.y)/a.z;}else{face=5u;uv=vec2<f32>(-direction.x,-direction.y)/a.z;}}\n return vec3<f32>(uv*0.5+0.5,f32(index*6u+face));\n}\nfn directionalVisibility(index:u32,p:vec3<f32>)->f32 { let sp=rendererLights.directionalShadowParams[index]; if(sp.y<0.5){return 1.0;} return projectedShadow(rendererLights.directionalShadowMatrices[index],p,i32(index),sp.x,rendererLights.directionalShadowParams2[index].y,0u); }\nfn pointVisibility(index:u32,p:vec3<f32>)->f32 { let sp=rendererLights.pointShadowParams[index]; if(sp.y<0.5){return 1.0;} let delta=p-rendererLights.pointPositionRanges[index].xyz; let range=rendererLights.pointPositionRanges[index].w; let uv=pointShadowUvLayer(delta,index); let dims=vec2<f32>(textureDimensions(pointShadows)); let angle=select(0.0,hash12(p.xy+vec2<f32>(uniforms.ambient.w,f32(index)))*6.2831853,uniforms.ambient.w>0.0); var visible=0.0; for(var tap=0;tap<SHADOW_TAPS;tap+=1){let suv=clamp(uv.xy+rotatedOffset(tap,angle)/dims,vec2<f32>(0.0),vec2<f32>(1.0));let pixel=vec2<i32>(clamp(suv*dims,vec2<f32>(0.0),dims-1.0));let stored=textureLoad(pointShadows,pixel,i32(round(uv.z)),0).r;visible+=select(0.0,1.0,length(delta)/max(range,0.0001)-sp.x<=stored);} visible/=f32(SHADOW_TAPS); return mix(1.0,visible,rendererLights.pointShadowParams2[index].y); }\nfn spotVisibility(index:u32,p:vec3<f32>)->f32 { let sp=rendererLights.spotShadowParams[index]; if(sp.y<0.5){return 1.0;} return projectedShadow(rendererLights.spotShadowMatrices[index],p,i32(index),sp.x,rendererLights.spotShadowParams2[index].y,1u); }\nfn sceneDistanceAt(pixel:vec2<u32>)->f32{\n let size=textureDimensions(sceneDepth);let clamped=min(pixel,size-vec2<u32>(1u));let depth=textureLoad(sceneDepth,vec2<i32>(clamped),0);\n let uv=(vec2<f32>(clamped)+vec2<f32>(0.5))/vec2<f32>(size);let world4=uniforms.inverseViewProjection*vec4<f32>(uv.x*2.0-1.0,1.0-uv.y*2.0,depth,1.0);\n return length(world4.xyz/world4.w-uniforms.cameraNear.xyz);\n}\n@compute @workgroup_size(8,8,1)\nfn main(@builtin(global_invocation_id) id: vec3<u32>) {\n let dims = vec3<u32>(uniforms.dimensionsFar.xyz); if (id.x >= dims.x || id.y >= dims.y) { return; }\n let temporal=select(vec2<f32>(0.5),vec2<f32>(hash12(vec2<f32>(id.xy)+uniforms.ambient.w),hash12(vec2<f32>(id.yx)+uniforms.ambient.w+19.19)),uniforms.ambient.w>0.0);\n let rayJitter=hash12(vec2<f32>(id.xy)+vec2<f32>(uniforms.ambient.w*0.754877,uniforms.ambient.w*0.569841));\n let uv = (vec2<f32>(id.xy)+temporal)/vec2<f32>(dims.xy);\n let farPoint4 = uniforms.inverseViewProjection * vec4<f32>(uv.x*2.0-1.0, 1.0-uv.y*2.0, 1.0, 1.0);\n let camera = uniforms.cameraNear.xyz; let ray = normalize(farPoint4.xyz/farPoint4.w-camera);\n let nearPlane = uniforms.cameraNear.w; let farPlane = uniforms.dimensionsFar.w;\n let depthSize=textureDimensions(sceneDepth);\n let cellMin=id.xy*depthSize/dims.xy;\n let cellEnd=((id.xy+vec2<u32>(1u))*depthSize+dims.xy-vec2<u32>(1u))/dims.xy;\n let cellMax=min(cellEnd-vec2<u32>(1u),depthSize-vec2<u32>(1u));\n let cellCenter=(cellMin+cellMax)/vec2<u32>(2u);var columnFar=max(sceneDistanceAt(cellCenter),max(max(sceneDistanceAt(cellMin),sceneDistanceAt(vec2<u32>(cellMax.x,cellMin.y))),max(sceneDistanceAt(vec2<u32>(cellMin.x,cellMax.y)),sceneDistanceAt(cellMax))));\n columnFar=clamp(columnFar,nearPlane,farPlane);var columnNear=farPlane;\n for(var volumeIndex=0u;volumeIndex<uniforms.counts.x;volumeIndex+=1u){columnNear=min(columnNear,max(volumes[volumeIndex].heightStartPhase.z,nearPlane));}\n columnNear=min(columnNear,columnFar);columnFar=max(columnFar,columnNear+0.001);textureStore(outputDepthBounds,vec2<i32>(id.xy),vec4<f32>(columnNear,columnFar,0.0,0.0));\n var previousDirectionalVisibility=array<f32,4>(1.0,1.0,1.0,1.0);var hasPreviousDirectionalVisibility=false;\n var transmittance = 1.0; var scattering = vec3<f32>(0.0); var previousDistance = columnNear;\n for (var z=0u; z<dims.z; z+=1u) {\n let sliceEnd = mix(columnNear,columnFar,f32(z+1u)/f32(dims.z)); let stepSize = sliceEnd-previousDistance;\n let substepSize=stepSize/f32(INTEGRATION_SUBSTEPS);\n for(var substep=0;substep<INTEGRATION_SUBSTEPS;substep+=1){\n // Share one stratified offset across all intervals on a ray. This turns\n // coherent Z terraces into stationary spatial error that blur can remove.\n let sampleOffset=select(0.5,rayJitter,uniforms.scattering.y>0.5);\n let sampleDistance=previousDistance+(f32(substep)+sampleOffset)*substepSize;\n let p = camera + ray*sampleDistance; var sigma = 0.0; var source = vec3<f32>(0.0);\n // Directional visibility belongs to the integration interval endpoints.\n // Reusing the preceding endpoint gives trapezoidal shadow integration\n // with one new lookup per interval, instead of quantizing a whole slice\n // from a midpoint visibility sample.\n let shadowDistance=previousDistance+(f32(substep)+1.0)*substepSize;\n let shadowP=camera+ray*shadowDistance;\n let csmCount=u32(round(rendererLights.lightCounts.w));let viewDepth=max(dot(shadowP-camera,uniforms.cameraForwardDepthRange.xyz),0.0);let normalizedViewDepth=viewDepth/uniforms.cameraForwardDepthRange.w;\n var filteredDirectionalVisibility=array<f32,4>(1.0,1.0,1.0,1.0);\n for(var d=0u;d<uniforms.counts.y;d+=1u){var cascadeWeight=1.0;if(d<csmCount){let range=rendererLights.csmCascadeRanges[d].xy;let isLast=d+1u==csmCount;cascadeWeight=select(0.0,1.0,normalizedViewDepth>=range.x&&(normalizedViewDepth<range.y||isLast));}let current=directionalVisibility(d,shadowP)*cascadeWeight;filteredDirectionalVisibility[d]=select(current,0.5*(previousDirectionalVisibility[d]+current),hasPreviousDirectionalVisibility);previousDirectionalVisibility[d]=current;}\n hasPreviousDirectionalVisibility=true;\n for (var v=0u; v<uniforms.counts.x; v+=1u) { let volume=volumes[v]; let localDistance=distance(p,volume.centerRadius.xyz);\n if (localDistance < volume.centerRadius.w && sampleDistance >= volume.heightStartPhase.z) {\n var density=volume.albedoDensity.w*exp(-volume.heightStartPhase.x*(p.y-volume.heightStartPhase.y)); density*=1.0-smoothstep(volume.centerRadius.w*0.8,volume.centerRadius.w,localDistance);\n let rendererAmbient=rendererLights.ambientColor.rgb*rendererLights.ambientColor.w;\n let hemisphereAmbient=(rendererLights.hemisphereSkyColorIntensity.rgb*rendererLights.hemisphereSkyColorIntensity.w+rendererLights.hemisphereGroundColorIntensity.rgb*rendererLights.hemisphereGroundColorIntensity.w)*0.5;\n let sceneAmbient=rendererAmbient+hemisphereAmbient;\n let ambient=select(uniforms.ambient.rgb,sceneAmbient,dot(sceneAmbient,sceneAmbient)>0.000001);\n var lighting=ambient*volume.emissiveAmbient.w+volume.emissiveAmbient.rgb; var direct=vec3<f32>(0.0); var li=0u;\n for (var d=0u; d<uniforms.counts.y; d+=1u) {\n let l=lights[li]; li+=1u;\n direct += l.colorDecay.rgb*phaseHG(dot(ray,l.positionRange.xyz),volume.heightStartPhase.w)*filteredDirectionalVisibility[d];\n }\n for (var q=0u; q<uniforms.counts.z; q+=1u) { let l=lights[li]; li+=1u; let delta=l.positionRange.xyz-p; let dist=length(delta); direct += l.colorDecay.rgb*attenuation(dist,l.positionRange.w,l.colorDecay.w)*phaseHG(dot(ray,normalize(delta)),volume.heightStartPhase.w)*pointVisibility(q,p); }\n for (var s=0u; s<uniforms.counts.w; s+=1u) { let l=lights[li]; li+=1u; let delta=l.positionRange.xyz-p; let dist=length(delta); let cd=dot(normalize(-delta),l.directionCone.xyz); let cone=smoothstep(l.directionCone.w,l.penumbra.x,cd); direct += l.colorDecay.rgb*attenuation(dist,l.positionRange.w,l.colorDecay.w)*cone*phaseHG(dot(ray,normalize(delta)),volume.heightStartPhase.w)*spotVisibility(s,p); }\n direct*=uniforms.scattering.x;\n if (volume.mode.x < 0.5) { lighting += direct; } else { lighting = direct; }\n sigma += density; source += lighting*volume.albedoDensity.rgb*density;\n }\n }\n if (sigma > 0.000001) { let extinction=exp(-sigma*substepSize); scattering += transmittance*source*((1.0-extinction)/sigma); transmittance*=extinction; }\n }\n textureStore(outputFog, vec3<i32>(i32(id.x),i32(id.y),i32(z)), vec4<f32>(scattering,transmittance)); previousDistance=sliceEnd;\n }\n}",S="\nfn inverseProjection() -> mat4x4<f32> { return mat4x4<f32>(fullscreenUniforms[0],fullscreenUniforms[1],fullscreenUniforms[2],fullscreenUniforms[3]); }\nfn fogDither(pixel:vec2<f32>,frame:f32)->f32 { let p3=fract(vec3<f32>(pixel.xyx+frame*vec3<f32>(0.754877,0.569841,0.438289))*0.1031); let q=p3+dot(p3,p3.yzx+33.33); return fract((q.x+q.y)*q.z)-0.5; }\nfn sampleIntegratedFog(uv:vec2<f32>,normalizedDepth:f32)->vec4<f32>{\n let slices=f32(textureDimensions(fogVolumeTexture).z);let slicePosition=clamp(normalizedDepth,0.0,1.0)*slices;\n let textureZ=clamp((slicePosition-0.5)/slices,0.0,1.0);let integrated=textureSampleLevel(fogVolumeTexture,fullscreenSampler,vec3<f32>(uv,textureZ),0.0);\n return mix(vec4<f32>(0.0,0.0,0.0,1.0),integrated,min(slicePosition,1.0));\n}\n@fragment fn fsMain(input: FullscreenVertexOutput) -> @location(0) vec4<f32> {\n let pixel=vec2<i32>(input.position.xy); let color=textureLoad(sceneColorTexture,pixel,0); let depth=textureLoad(sceneDepthTexture,pixel,0);\n let clip=vec4<f32>(input.uv.x*2.0-1.0,1.0-input.uv.y*2.0,depth,1.0); let view=inverseProjection()*clip; let distance=length(view.xyz/view.w);\n let bounds=textureSampleLevel(fogBoundsTexture,fullscreenSampler,input.uv,0.0).rg;let z=clamp((distance-bounds.x)/max(bounds.y-bounds.x,0.001),0.0,1.0);\n let frame=fullscreenUniforms[4].z; let ditherStrength=fullscreenUniforms[4].w;\n // Half a slice of stochastic Z movement hides integration-layer contours;\n // the RGB term removes display-quantization bands. Both converge under TAA.\n let sliceCount=f32(textureDimensions(fogVolumeTexture).z); let noise=fogDither(input.position.xy,max(frame,0.0));\n let zJitter=select(0.0,noise/max(sliceCount,1.0),frame>=0.0);\n let fog=sampleIntegratedFog(input.uv,z+zJitter);\n let fogAmount=clamp(1.0-fog.a,0.0,1.0); let dither=vec3<f32>(noise*(ditherStrength/255.0)*fogAmount);\n return vec4<f32>(max(vec3<f32>(0.0),fog.rgb+color.rgb*fog.a+dither),color.a);\n}",C="\nfn inverseProjection() -> mat4x4<f32> { return mat4x4<f32>(fullscreenUniforms[0],fullscreenUniforms[1],fullscreenUniforms[2],fullscreenUniforms[3]); }\nfn fogDither(pixel:vec2<f32>,frame:f32)->f32 { let p3=fract(vec3<f32>(pixel.xyx+frame*vec3<f32>(0.754877,0.569841,0.438289))*0.1031); let q=p3+dot(p3,p3.yzx+33.33); return fract((q.x+q.y)*q.z)-0.5; }\nfn sampleIntegratedFog(uv:vec2<f32>,normalizedDepth:f32)->vec4<f32>{\n let slices=f32(textureDimensions(fogVolumeTexture).z);let slicePosition=clamp(normalizedDepth,0.0,1.0)*slices;\n let textureZ=clamp((slicePosition-0.5)/slices,0.0,1.0);let integrated=textureSampleLevel(fogVolumeTexture,fullscreenSampler,vec3<f32>(uv,textureZ),0.0);\n return mix(vec4<f32>(0.0,0.0,0.0,1.0),integrated,min(slicePosition,1.0));\n}\n@fragment fn fsMain(input: FullscreenVertexOutput) -> @location(0) vec4<f32> {\n let depthSize=vec2<i32>(textureDimensions(sceneDepthTexture)); let depthPixel=clamp(vec2<i32>(input.uv*vec2<f32>(depthSize)),vec2<i32>(0),depthSize-vec2<i32>(1));\n let depth=textureLoad(sceneDepthTexture,depthPixel,0); let clip=vec4<f32>(input.uv.x*2.0-1.0,1.0-input.uv.y*2.0,depth,1.0);\n let view=inverseProjection()*clip; let distance=length(view.xyz/view.w); let nearPlane=fullscreenUniforms[4].x; let farPlane=fullscreenUniforms[4].y;\n let bounds=textureSampleLevel(fogBoundsTexture,fullscreenSampler,input.uv,0.0).rg;let z=clamp((distance-bounds.x)/max(bounds.y-bounds.x,0.001),0.0,1.0); let frame=fullscreenUniforms[4].z; let noise=fogDither(input.position.xy,max(frame,0.0));\n let slices=f32(textureDimensions(fogVolumeTexture).z); let zJitter=select(0.0,noise/max(slices,1.0),frame>=0.0); var fog=sampleIntegratedFog(input.uv,z+zJitter);\n fog=vec4<f32>(max(vec3<f32>(0.0),fog.rgb+vec3<f32>(noise*(fullscreenUniforms[4].w/255.0)*clamp(1.0-fog.a,0.0,1.0))),fog.a); return fog;\n}";var P="\nfn loadDepth(uv:vec2<f32>)->f32{let size=vec2<i32>(textureDimensions(sceneDepthTexture));let pixel=clamp(vec2<i32>(uv*vec2<f32>(size)),vec2<i32>(0),size-vec2<i32>(1));return textureLoad(sceneDepthTexture,pixel,0);}\nfn inverseProjection()->mat4x4<f32>{return mat4x4<f32>(fullscreenUniforms[0],fullscreenUniforms[1],fullscreenUniforms[2],fullscreenUniforms[3]);}\nfn viewDistance(uv:vec2<f32>)->f32{let depth=loadDepth(uv);let clip=vec4<f32>(uv.x*2.0-1.0,1.0-uv.y*2.0,depth,1.0);let view=inverseProjection()*clip;return length(view.xyz/view.w);}\nfn sampleIntegratedFog(uv:vec2<f32>,normalizedDepth:f32)->vec4<f32>{let slices=f32(textureDimensions(fogVolumeTexture).z);let slicePosition=clamp(normalizedDepth,0.0,1.0)*slices;let textureZ=clamp((slicePosition-0.5)/slices,0.0,1.0);let integrated=textureSampleLevel(fogVolumeTexture,fullscreenSampler,vec3<f32>(uv,textureZ),0.0);return mix(vec4<f32>(0.0,0.0,0.0,1.0),integrated,min(slicePosition,1.0));}\n@fragment fn fsMain(input:FullscreenVertexOutput)->@location(0) vec4<f32>{\n let color=textureLoad(sceneColorTexture,vec2<i32>(input.position.xy),0);let fogSize=vec2<f32>(textureDimensions(fogInputTexture));let texel=1.0/fogSize;let grid=input.uv*fogSize-0.5;let base=(floor(grid)+0.5)*texel;\n let candidates=array<vec2<f32>,4>(base,base+vec2<f32>(texel.x,0.0),base+vec2<f32>(0.0,texel.y),base+texel);let centerDistance=max(viewDistance(input.uv),0.0001);var bestUv=clamp(candidates[0],vec2<f32>(0.0),vec2<f32>(1.0));var bestDifference=abs(log(max(viewDistance(bestUv),0.0001)/centerDistance));var maxDifference=bestDifference;\n for(var i=1;i<4;i+=1){let uv=clamp(candidates[i],vec2<f32>(0.0),vec2<f32>(1.0));let difference=abs(log(max(viewDistance(uv),0.0001)/centerDistance));maxDifference=max(maxDifference,difference);if(difference<bestDifference){bestDifference=difference;bestUv=uv;}}\n let blurredUv=select(bestUv,input.uv,maxDifference<0.02);let blurredFog=textureSampleLevel(fogInputTexture,fullscreenSampler,blurredUv,0.0);let bounds=textureSampleLevel(fogBoundsTexture,fullscreenSampler,input.uv,0.0).rg;let z=clamp((centerDistance-bounds.x)/max(bounds.y-bounds.x,0.001),0.0,1.0);let directFog=sampleIntegratedFog(input.uv,z);let fog=select(directFog,blurredFog,bestDifference<0.02);return vec4<f32>(fog.rgb+color.rgb*fog.a,color.a);\n}",M="\n@fragment fn fsMain(input:FullscreenVertexOutput)->@location(0) vec4<f32>{\n let color=textureLoad(sceneColorTexture,vec2<i32>(input.position.xy),0);\n let fog=textureSampleLevel(fogInputTexture,fullscreenSampler,input.uv,0.0);\n return vec4<f32>(fog.rgb+color.rgb*fog.a,color.a);\n}";import{ByteType as B,DepthFormat as D,DepthStencilFormat as T,FloatType as I,HalfFloatType as G,IntType as R,RED_GREEN_RGTC2_Format as L,RED_RGTC1_Format as z,RGBA_ASTC_10x10_Format as U,RGBA_ASTC_10x5_Format as V,RGBA_ASTC_10x6_Format as A,RGBA_ASTC_10x8_Format as F,RGBA_ASTC_12x10_Format as E,RGBA_ASTC_12x12_Format as k,RGBA_ASTC_4x4_Format as O,RGBA_ASTC_5x4_Format as $,RGBA_ASTC_5x5_Format as j,RGBA_ASTC_6x5_Format as N,RGBA_ASTC_6x6_Format as W,RGBA_ASTC_8x5_Format as _,RGBA_ASTC_8x6_Format as q,RGBA_ASTC_8x8_Format as H,RGBA_BPTC_Format as K,RGBA_ETC2_EAC_Format as Z,RGBA_S3TC_DXT1_Format as Y,RGBA_S3TC_DXT3_Format as X,RGBA_S3TC_DXT5_Format as J,RGBAFormat as Q,RGBAIntegerFormat as ee,RGFormat as te,RGIntegerFormat as re,RGB_ETC1_Format as ne,RGB_ETC2_Format as ie,RGB_S3TC_DXT1_Format as ae,RGBFormat as se,RedFormat as oe,RedIntegerFormat as le,ShortType as ce,SIGNED_RED_GREEN_RGTC2_Format as ue,SIGNED_RED_RGTC1_Format as de,SRGBColorSpace as he,UnsignedByteType as pe,UnsignedInt248Type as fe,UnsignedInt5999Type as me,UnsignedIntType as ge,UnsignedShortType as xe}from"three";function ve(e,t){const r=Ce(e),n=function(e,t){const r=e.format,n=e.type,i=e.colorSpace===he;let a=null;if(Pe(e))switch(r){case ae:case Y:a=i?"bc1-rgba-unorm-srgb":"bc1-rgba-unorm";break;case X:a=i?"bc2-rgba-unorm-srgb":"bc2-rgba-unorm";break;case J:a=i?"bc3-rgba-unorm-srgb":"bc3-rgba-unorm";break;case z:a="bc4-r-unorm";break;case de:a="bc4-r-snorm";break;case L:a="bc5-rg-unorm";break;case ue:a="bc5-rg-snorm";break;case K:a=i?"bc7-rgba-unorm-srgb":"bc7-rgba-unorm";break;case ie:case ne:a=i?"etc2-rgb8unorm-srgb":"etc2-rgb8unorm";break;case Z:a=i?"etc2-rgba8unorm-srgb":"etc2-rgba8unorm";break;case O:a=i?"astc-4x4-unorm-srgb":"astc-4x4-unorm";break;case $:a=i?"astc-5x4-unorm-srgb":"astc-5x4-unorm";break;case j:a=i?"astc-5x5-unorm-srgb":"astc-5x5-unorm";break;case N:a=i?"astc-6x5-unorm-srgb":"astc-6x5-unorm";break;case W:a=i?"astc-6x6-unorm-srgb":"astc-6x6-unorm";break;case _:a=i?"astc-8x5-unorm-srgb":"astc-8x5-unorm";break;case q:a=i?"astc-8x6-unorm-srgb":"astc-8x6-unorm";break;case H:a=i?"astc-8x8-unorm-srgb":"astc-8x8-unorm";break;case V:a=i?"astc-10x5-unorm-srgb":"astc-10x5-unorm";break;case A:a=i?"astc-10x6-unorm-srgb":"astc-10x6-unorm";break;case F:a=i?"astc-10x8-unorm-srgb":"astc-10x8-unorm";break;case U:a=i?"astc-10x10-unorm-srgb":"astc-10x10-unorm";break;case E:a=i?"astc-12x10-unorm-srgb":"astc-12x10-unorm";break;case k:a=i?"astc-12x12-unorm-srgb":"astc-12x12-unorm";break;case Q:a=i?"rgba8unorm-srgb":"rgba8unorm"}else switch(r){case Q:switch(n){case B:a="rgba8snorm";break;case ce:a="rgba16sint";break;case xe:a="rgba16uint";break;case ge:a="rgba32uint";break;case R:a="rgba32sint";break;case pe:a=i?"rgba8unorm-srgb":"rgba8unorm";break;case G:a="rgba16float";break;case I:a="rgba32float"}break;case se:switch(n){case me:a="rgb9e5ufloat";break;case 35899:a="rg11b10ufloat"}break;case oe:switch(n){case B:a="r8snorm";break;case ce:a="r16sint";break;case xe:a="r16uint";break;case ge:a="r32uint";break;case R:a="r32sint";break;case pe:a="r8unorm";break;case G:a="r16float";break;case I:a="r32float"}break;case te:switch(n){case B:a="rg8snorm";break;case ce:a="rg16sint";break;case xe:a="rg16uint";break;case ge:a="rg32uint";break;case R:a="rg32sint";break;case pe:a="rg8unorm";break;case G:a="rg16float";break;case I:a="rg32float"}break;case D:switch(n){case xe:a="depth16unorm";break;case ge:a="depth24plus";break;case I:a="depth32float"}break;case T:switch(n){case fe:a="depth24plus-stencil8";break;case I:Me("depth32float-stencil8",t,e,"DepthTexture with DepthStencilFormat + FloatType"),a="depth32float-stencil8"}break;case le:switch(n){case R:a="r32sint";break;case ge:a="r32uint"}break;case re:switch(n){case R:a="rg32sint";break;case ge:a="rg32uint"}break;case ee:switch(n){case R:a="rgba32sint";break;case ge:a="rgba32uint"}}if(!a)throw new Error(`Texture format "${r}" with type "${n}" from "${e.constructor.name}" is not supported by this renderer yet.`);const s=function(e){if(e.startsWith("bc"))return"texture-compression-bc";if(e.startsWith("etc2")||e.startsWith("eac"))return"texture-compression-etc2";if(e.startsWith("astc"))return"texture-compression-astc";return null}(a);s&&Me(s,t,e,`Texture format "${a}"`);return a}(e,t),i=function(e){const t=Se(e);if("cube"===t)return"cube";if("2d-array"===t)return"2d-array";if("3d"===t)return"3d";return"2d"}(e),a=function(e){return"3d"===Se(e)?"3d":"2d"}(e),s=function(e,t,r){if(!0===e.isDepthTexture)return"depth";if(t.endsWith("uint"))return"uint";if(t.endsWith("sint"))return"sint";if(!0===e.isDataTexture||!0===e.isDataArrayTexture||!0===e.isData3DTexture){if(e.type===R)return"sint";if(e.type===ge)return"uint";if(e.type===I&&!Be(r,"float32-filterable")&&("r32float"===t||"rg32float"===t||"rgba32float"===t))return"unfilterable-float"}return"float"}(e,n,t),o=function(e,t){const r=e.compareFunction;if("depth"===t&&null!=r)return"comparison";if("float"===t)return"filtering";return"non-filtering"}(e,s),l=function(e){if(!0===e.isCompressedCubeTexture){const t=e.image;return Math.max(1,t?.[0]?.mipmaps?.length??1)}const t=e.mipmaps;return Math.max(1,t?.length??1)}(e);return{format:n,textureDimension:a,viewDimension:i,sampleType:s,samplerBindingType:o,wgslTextureType:ye(i,s),wgslSamplerType:"comparison"===o?"sampler_comparison":"sampler",width:r.width,height:r.height,depthOrArrayLayers:r.depthOrArrayLayers,mipLevelCount:l,compressed:Pe(e)}}function we(e,t){const r=ve(e,t);return[r.format,r.textureDimension,r.viewDimension,r.sampleType,r.samplerBindingType,r.width,r.height,r.depthOrArrayLayers,r.mipLevelCount].join(":")}function be(e){const t=Ce(e),r=e.compareFunction;return[Se(e),e.format,e.type,e.colorSpace,r??"none",t.depthOrArrayLayers].join(":")}function ye(e,t){if("depth"===t)switch(e){case"2d-array":return"texture_depth_2d_array";case"cube":return"texture_depth_cube";default:return"texture_depth_2d"}const r="uint"===t?"u32":"sint"===t?"i32":"f32";switch(e){case"2d-array":return`texture_2d_array<${r}>`;case"cube":return`texture_cube<${r}>`;case"3d":return`texture_3d<${r}>`;default:return`texture_2d<${r}>`}}function Se(e){return!0===e.isCubeTexture?"cube":!0===e.isArrayTexture||!0===e.isDataArrayTexture||!0===e.isCompressedArrayTexture?"2d-array":!0===e.is3DTexture||!0===e.isData3DTexture?"3d":"2d"}function Ce(e){if(!0===e.isCubeTexture){const t=e.image,r=t?.[0],n=r?.image??r;return{width:n?.width??1,height:n?.height??1,depthOrArrayLayers:6}}const t=e.image;return{width:t?.width??1,height:t?.height??1,depthOrArrayLayers:t?.depth??1}}function Pe(e){return!0===e.isCompressedTexture||!0===e.isCompressedArrayTexture}function Me(e,t,r,n){if(!Be(t,e))throw new Error(`${n} for "${r.name||r.uuid}" requires the WebGPU feature "${e}", which is not enabled on this device.`)}function Be(e,t){return!!e&&(e instanceof Set?e.has(t):"features"in e?e.features.has(t):e.has(t))}import{Color as De,Matrix3 as Te,Matrix4 as Ie,Vector2 as Ge,Vector3 as Re,Vector4 as Le}from"three";var ze=new ArrayBuffer(8),Ue=new Float64Array(ze),Ve=new Uint32Array(ze),Ae={f32:{alignment:4,size:4},i32:{alignment:4,size:4},u32:{alignment:4,size:4},"vec2<f32>":{alignment:8,size:8},"vec3<f32>":{alignment:16,size:12},"vec4<f32>":{alignment:16,size:16},"mat3x3<f32>":{alignment:16,size:48},"mat4x4<f32>":{alignment:16,size:64}};function Fe(e,t){return Math.ceil(e/t)*t}function Ee(e,t){return"number"==typeof e||"boolean"==typeof e?[Number(e)]:Array.isArray(e)?Array.from(e.slice(0,t)):e instanceof De?t>=4?[e.r,e.g,e.b,1]:[e.r,e.g,e.b]:e instanceof Ge?[e.x,e.y]:e instanceof Re?[e.x,e.y,e.z]:e instanceof Le?[e.x,e.y,e.z,e.w]:e instanceof Te||e instanceof Ie?Array.from(e.elements):[]}function ke(e,t,r,n){const i="boolean"==typeof n?n?1:0:Number(n);"i32"!==r?"u32"!==r?e.setFloat32(t,i,!0):e.setUint32(t,i,!0):e.setInt32(t,i,!0)}function Oe(e,t,r,n){const i=Ee(r,n);for(let r=0;r<n;r+=1)e[t+r]=i[r]??0}function $e(e,t,r){const n=r instanceof Te?r.elements:Array.isArray(r)?Array.from(r):Ee(r,9);for(let r=0;r<3;r+=1){const i=3*r,a=t+4*r;e[a+0]=n[i+0]??0,e[a+1]=n[i+1]??0,e[a+2]=n[i+2]??0,e[a+3]=0}}function je(e){let t=0;const r=[];for(const[n,i]of Object.entries(e)){const e=Ae[i.type];t=Fe(t,e.alignment),r.push({name:n,offset:t,type:i.type}),t+=e.size}return{byteLength:Fe(t,16),entries:r}}function Ne(e,t){const r=new ArrayBuffer(t.byteLength),n=new DataView(r),i=new Float32Array(r);for(const r of t.entries){const t=e[r.name],a=r.offset/4;switch(r.type){case"f32":case"i32":case"u32":ke(n,r.offset,r.type,t.value);break;case"vec2<f32>":Oe(i,a,t.value,2);break;case"vec3<f32>":Oe(i,a,t.value,3);break;case"vec4<f32>":Oe(i,a,t.value,4);break;case"mat3x3<f32>":$e(i,a,t.value);break;case"mat4x4<f32>":if(t.value instanceof Ie)i.set(t.value.elements,a);else{const e=Ee(t.value,16);i.set(e,a)}}}return r}function We(e,t){let r=Math.imul(e^t,16777619);return r^=r>>>13,r>>>0}function _e(e,t){return Ue[0]=t,e=We(e,Ve[0]??0),e=We(e,Ve[1]??0)}function qe(e,t,r){const n=Ee(t,r);e=We(e,n.length);for(let t=0;t<n.length;t+=1)e=_e(e,n[t]??0);return e}var He="\nstruct FullscreenVertexOutput {\n @builtin(position) position: vec4<f32>,\n @location(0) uv: vec2<f32>,\n};\n\n@vertex\nfn vsMain(@builtin(vertex_index) vertexIndex: u32) -> FullscreenVertexOutput {\n var output: FullscreenVertexOutput;\n let position = array<vec2<f32>, 3>(\n vec2(-1.0, -3.0),\n vec2(-1.0, 1.0),\n vec2(3.0, 1.0),\n );\n let clip = position[vertexIndex];\n output.position = vec4(clip, 0.0, 1.0);\n output.uv = clip * vec2(0.5, -0.5) + vec2(0.5, 0.5);\n return output;\n}\n",Ke=new WeakMap,Ze=new WeakMap;function Ye(e){return e?"string"==typeof e?[e]:Array.from(e):[]}function Xe(e){return e.replace(/[^A-Za-z0-9_]/g,"_")}var Je=class{constructor(e){this.context=e}context;sceneColor="sceneColor";mainDepth="mainDepth";postProcessColor="postProcessColor";createColorTarget(e,t={}){return this.context.defineColorTarget(e,t),e}createTextureTarget(e,t={}){return this.context.defineTextureTarget(e,t),e}addStandardScenePasses(e=this.sceneColor){this.context.addDirectionalShadowPass(),this.context.addPointShadowPass(),this.context.addSpotShadowPass(),this.context.addDepthPrepass(),this.context.addHiZPasses(),this.context.addVisibilityPass(),this.context.addOpaquePass(e),this.context.addHiZHistoryPass("OpaquePass"),this.context.addSceneTextureCopyPass(e),this.context.addLatePass(e)}addDirectionalShadowPass(){this.context.addDirectionalShadowPass()}addPointShadowPass(){this.context.addPointShadowPass()}addSpotShadowPass(){this.context.addSpotShadowPass()}addDepthPrepass(){this.context.addDepthPrepass()}addHiZPasses(){this.context.addHiZPasses()}addVisibilityPass(){this.context.addVisibilityPass()}addForwardPass(e=this.sceneColor){this.context.addForwardPass(e)}addOpaquePass(e=this.sceneColor){this.context.addOpaquePass(e)}addSceneTextureCopyPass(e=this.sceneColor){this.context.addSceneTextureCopyPass(e)}addLatePass(e=this.sceneColor){this.context.addLatePass(e)}addHiZHistoryPass(e="ForwardPass"){this.context.addHiZHistoryPass(e)}addMaterialPass(e={}){const t={name:e.name,outputs:e.outputs??this.sceneColor,drawStage:e.drawStage,loadColor:e.loadColor,loadDepth:e.loadDepth,objectFilter:e.objectFilter,overrideMaterial:e.overrideMaterial};this.context.addMaterialPass(t)}addPass(e){const t=e.inputs?Object.values(e.inputs):void 0,r=Ye(e.outputs),n={name:e.name,reads:t,writes:r.length>0?r:void 0,dependsOn:e.dependsOn,execute:e.execute};this.context.addCustomPass(n)}addFullscreenPass(e){const t=Ye(e.outputs),r=Object.entries(e.inputs),n=Object.entries(e.textures??{});for(const[t]of n)if(t in e.inputs)throw new Error(`Fullscreen pass "${e.name}" cannot use "${t}" as both an input and an external texture.`);const i=r.map(([,e])=>e===this.mainDepth?"depth":"color");this.addPass({name:e.name,inputs:e.inputs,outputs:t,execute:a=>{const s=t.map(e=>a.getColorFormat(e)),o=n.map(([,e])=>ve(e,a.device)),l=n.map(([,e])=>we(e,a.device)).join("|"),c=r.map(([t])=>e.inputDimensions?.[t]??"2d"),u=`${s.join("|")}:${i.map((e,t)=>`${e}-${c[t]}`).join("|")}:${l}:${e.uniformBufferSize??0}`,d=function(e,t){let r=Ke.get(e);r||(r=new WeakMap,Ke.set(e,r));let n=r.get(t);return n||(n=new Map,r.set(t,n)),n}(e,a.device);let h=d.get(u);if(!h){const t=[He,"@group(0) @binding(0) var fullscreenSampler: sampler;",r.map(([e],t)=>`@group(0) @binding(${t+1}) var ${e}Texture: ${"depth"===i[t]?"texture_depth_2d":"3d"===c[t]?"texture_3d<f32>":"texture_2d<f32>"};`).join("\n"),n.map(([e],t)=>{const n=r.length+1+2*t,i=o[t];return`@group(0) @binding(${n}) var ${e}Sampler: ${i.wgslSamplerType};\n@group(0) @binding(${n+1}) var ${e}Texture: ${i.wgslTextureType};`}).join("\n"),e.uniformBufferSize?`@group(0) @binding(${r.length+1+2*n.length}) var<uniform> fullscreenUniforms: array<vec4<f32>, ${Math.max(1,Math.ceil(e.uniformBufferSize/16))}>;`:"",e.fragmentShader].filter(Boolean).join("\n\n"),l=a.device.createBindGroupLayout({label:`${e.name}-layout`,entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"nearest"===e.sampler?"non-filtering":"filtering"}},...r.map((e,t)=>({binding:t+1,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"depth"===i[t]?"depth":"float",viewDimension:"3d"===c[t]?"3d":"2d"}})),...o.flatMap((e,t)=>{const n=r.length+1+2*t;return[{binding:n,visibility:GPUShaderStage.FRAGMENT,sampler:{type:e.samplerBindingType}},{binding:n+1,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:e.sampleType,viewDimension:e.viewDimension}}]}),...e.uniformBufferSize?[{binding:r.length+1+2*n.length,visibility:GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}}]:[]]}),p=a.device.createPipelineLayout({label:`${e.name}-pipeline-layout`,bindGroupLayouts:[l]});h={bindGroupLayout:l,pipeline:a.device.createRenderPipeline({label:`${e.name}-pipeline`,layout:p,vertex:{module:a.device.createShaderModule({label:`${e.name}-vertex-module`,code:t}),entryPoint:"vsMain"},fragment:{module:a.device.createShaderModule({label:`${e.name}-fragment-module`,code:t}),entryPoint:"fsMain",targets:s.map(e=>({format:e}))},primitive:{topology:"triangle-list"}}),uniformBuffer:e.uniformBufferSize?a.device.createBuffer({label:`${e.name}-uniform-buffer`,size:16*Math.ceil(Math.max(16,e.uniformBufferSize)/16),usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}):null},d.set(u,h)}const{bindGroupLayout:p,pipeline:f,uniformBuffer:m}=h,g=e.updateUniforms?.(a)??null;m&&g&&a.device.queue.writeBuffer(m,0,g.buffer,g.byteOffset,g.byteLength);const x=[{binding:0,resource:"nearest"===e.sampler||"linear"!==e.sampler&&i.includes("depth")?a.nearestClampSampler:a.linearClampSampler},...r.map(([,e],t)=>({binding:t+1,resource:"depth"===i[t]?a.depthView:a.getColorView(e)}))];for(let e=0;e<n.length;e+=1){const t=a.getExternalTexture(n[e][1]),i=r.length+1+2*e;x.push({binding:i,resource:t.sampler},{binding:i+1,resource:t.view})}m&&x.push({binding:r.length+1+2*n.length,resource:{buffer:m}});const v=a.device.createBindGroup({label:`${e.name}-bind-group`,layout:p,entries:x}),w=a.encoder.beginRenderPass({label:e.name,colorAttachments:t.map(e=>({view:a.getColorView(e),clearValue:{r:0,g:0,b:0,a:1},loadOp:"clear",storeOp:"store"}))});w.setPipeline(f),w.setBindGroup(0,v),w.draw(3),w.end()}})}addNodeFullscreenPass(e){const t=Ye(e.outputs),r=Object.entries(function(e){const t={};for(const[r,n]of Object.entries(e.sceneTextures??{}))t[r]="sceneDepth"===n?{resource:"mainDepth",dimension:"depth-2d",sampleType:"depth",sampler:"non-filtering"}:{resource:"sceneColor",dimension:"2d",sampleType:"float",sampler:"filtering"};return{...t,...e.graphTextures}}(e.shader)).map(([t,r])=>[t,null!=e.inputOverrides?.[t]?{...r,resource:e.inputOverrides[t]}:r]),n=Object.entries(e.shader.textures??{}),i=Object.fromEntries(r.map(([e,t])=>[e,t.resource])),a=je(e.shader.uniforms);this.addPass({name:e.name,inputs:i,outputs:t,execute:i=>{const s=t.map(e=>i.getColorFormat(e)),o=r.map(([e,t])=>`${e}:${t.dimension}:${t.sampleType}:${t.sampler??"filtering"}`).join("|"),l=n.map(([,e])=>ve(e,i.device)),c=n.map(([,e])=>we(e,i.device)).join("|"),u=a.entries.map(e=>`${e.name}:${e.type}:${e.offset}`).join("|"),d=`${s.join("|")}:${o}:${c}:${u}`,h=function(e,t){let r=Ze.get(e);r||(r=new WeakMap,Ze.set(e,r));let n=r.get(t);return n||(n=new Map,r.set(t,n)),n}(e.shader,i.device);let p=h.get(d);if(!p){const t=[];for(const[,e]of r){const r=t.length;t.push({binding:r,visibility:GPUShaderStage.FRAGMENT,sampler:{type:e.sampler??("depth-2d"===e.dimension?"non-filtering":"filtering")}},{binding:r+1,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:e.sampleType??("depth-2d"===e.dimension?"depth":"float"),viewDimension:"3d"===e.dimension?"3d":"2d"}})}for(const[e,r]of l.entries()){const e=t.length;t.push({binding:e,visibility:GPUShaderStage.FRAGMENT,sampler:{type:r.samplerBindingType}},{binding:e+1,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:r.sampleType,viewDimension:r.viewDimension}})}const o=2*(r.length+n.length);a.byteLength>0&&t.push({binding:o,visibility:GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}});const c=i.device.createBindGroupLayout({label:`${e.name}-node-layout`,entries:t}),u=i.device.createPipelineLayout({label:`${e.name}-node-pipeline-layout`,bindGroupLayouts:[c]}),f=r.map(([e,t],r)=>{const n=Xe(e);return`@group(0) @binding(${2*r}) var ${n}Sampler: ${"comparison"===t.sampler?"sampler_comparison":"sampler"};\n@group(0) @binding(${2*r+1}) var ${n}Texture: ${"depth-2d"===t.dimension?"texture_depth_2d":"3d"===t.dimension?"texture_3d<f32>":"texture_2d<f32>"};`}).join("\n"),m=n.map(([e],t)=>{const n=2*(r.length+t),i=l[t],a=Xe(e);return`@group(0) @binding(${n}) var ${a}Sampler: ${i.wgslSamplerType};\n@group(0) @binding(${n+1}) var ${a}Texture: ${i.wgslTextureType};`}).join("\n"),g=a.entries.map(e=>` ${Xe(e.name)}: ${e.type},`).join("\n"),x=a.byteLength>0?`struct MaterialUniforms {\n${g}\n};\n@group(0) @binding(${o}) var<uniform> materialUniforms: MaterialUniforms;`:"",v=[He,f,m,x,e.shader.fragmentShader].filter(Boolean).join("\n\n");p={bindGroupLayout:c,pipeline:i.device.createRenderPipeline({label:`${e.name}-node-pipeline`,layout:u,vertex:{module:i.device.createShaderModule({label:`${e.name}-node-vertex-module`,code:v}),entryPoint:"vsMain"},fragment:{module:i.device.createShaderModule({label:`${e.name}-node-fragment-module`,code:v}),entryPoint:"fsMain",targets:s.map(e=>({format:e}))},primitive:{topology:"triangle-list"}}),uniformBuffer:a.byteLength>0?i.device.createBuffer({label:`${e.name}-node-uniforms`,size:a.byteLength,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}):null},h.set(d,p)}const{pipeline:f,bindGroupLayout:m,uniformBuffer:g}=p;e.shader.syncLiveUniforms(e.shader.uniforms),g&&i.device.queue.writeBuffer(g,0,Ne(e.shader.uniforms,a));const x=[];for(const[,e]of r){const t=x.length,r="comparison"===e.sampler?i.comparisonSampler:"non-filtering"===e.sampler||"depth-2d"===e.dimension?i.nearestClampSampler:i.linearClampSampler;x.push({binding:t,resource:r},{binding:t+1,resource:i.getTextureView(e.resource)})}for(const[,e]of n){const t=x.length,r=i.getExternalTexture(e);x.push({binding:t,resource:r.sampler},{binding:t+1,resource:r.view})}g&&x.push({binding:2*(r.length+n.length),resource:{buffer:g}});const v=i.device.createBindGroup({label:`${e.name}-node-bind-group`,layout:m,entries:x}),w=i.encoder.beginRenderPass({label:e.name,colorAttachments:t.map(e=>({view:i.getColorView(e),clearValue:{r:0,g:0,b:0,a:1},loadOp:"clear",storeOp:"store"}))});w.setPipeline(f),w.setBindGroup(0,v),w.draw(3),w.end()}})}present(e=this.sceneColor){this.context.addPresentPass(e)}};import{AdditiveBlending as Qe,BackSide as et,BufferAttribute as tt,BufferGeometry as rt,Color as nt,DoubleSide as it,FrontSide as at,InstancedBufferAttribute as st,MultiplyBlending as ot,Matrix4 as lt,Mesh as ct,OrthographicCamera as ut,PerspectiveCamera as dt,Sphere as ht,SubtractiveBlending as pt,Vector2 as ft,Vector3 as mt,Vector4 as gt,ShaderMaterial as xt}from"three";var vt=/^[A-Za-z_][A-Za-z0-9_]*$/;function wt(e,t={},r={}){const n=function(e){const t=new Map;for(const[r,n]of Object.entries(e))vt.test(r)&&!1!==n&&null!=n&&t.set(r,{name:r,parameters:null,body:bt(n)});return t}(t),i=[],a=[],s=e.split(/\r?\n/),o=r.sourceName??"shader";for(let e=0;e<s.length;e+=1){const t=s[e],r=yt(t),l=Ct(i);if(!r){a.push(l?Mt(t,n):"");continue}const{name:c,rest:u}=r;switch(c){case"define":l&&St(u,n,o,e+1),a.push("");break;case"undef":l&&n.delete(u.trim()),a.push("");break;case"ifdef":{const e=l,t=e&&n.has(u.trim());i.push({parentActive:e,active:t,branchTaken:t,elseSeen:!1}),a.push("");break}case"ifndef":{const e=l,t=e&&!n.has(u.trim());i.push({parentActive:e,active:t,branchTaken:t,elseSeen:!1}),a.push("");break}case"if":{const e=l,t=e&&zt(u,n);i.push({parentActive:e,active:t,branchTaken:t,elseSeen:!1}),a.push("");break}case"elif":{const t=Pt(i,o,e+1,c);if(t.elseSeen)throw new Error(`${o}:${e+1}: #elif after #else`);const r=t.parentActive&&!t.branchTaken&&zt(u,n);t.active=r,t.branchTaken=t.branchTaken||r,a.push("");break}case"else":{const t=Pt(i,o,e+1,c);if(t.elseSeen)throw new Error(`${o}:${e+1}: duplicate #else`);t.active=t.parentActive&&!t.branchTaken,t.branchTaken=!0,t.elseSeen=!0,a.push("");break}case"endif":Pt(i,o,e+1,c),i.pop(),a.push("");break;case"error":if(l)throw new Error(`${o}:${e+1}: ${u.trim()||"#error"}`);a.push("");break;case"warning":case"line":case"version":case"pragma":a.push("");break;default:if(l)throw new Error(`${o}:${e+1}: unsupported preprocessor directive #${c}`);a.push("")}}if(i.length>0)throw new Error(`${o}: unterminated preprocessor conditional`);return a.join("\n")}function bt(e){return"boolean"==typeof e?e?"1":"0":String(e)}function yt(e){const t=/^\s*#\s*([A-Za-z_][A-Za-z0-9_]*)(.*)$/.exec(e);return t?{name:t[1],rest:t[2]??""}:null}function St(e,t,r,n){const i=/^\s*([A-Za-z_][A-Za-z0-9_]*)(.*)$/.exec(e);if(!i)throw new Error(`${r}:${n}: invalid #define`);const a=i[1],s=i[2]??"";if(s.startsWith("(")){const e=Lt(s,0);if(e<0)throw new Error(`${r}:${n}: invalid function-like #define ${a}`);const i=s.slice(1,e).trim(),o=0===i.length?[]:i.split(",").map(e=>e.trim());for(const e of o)if(!vt.test(e))throw new Error(`${r}:${n}: invalid macro parameter "${e}"`);return void t.set(a,{name:a,parameters:o,body:Vt(s.slice(e+1)).trim()||"1"})}t.set(a,{name:a,parameters:null,body:Vt(s).trim()||"1"})}function Ct(e){for(const t of e)if(!t.active)return!1;return!0}function Pt(e,t,r,n){const i=e[e.length-1];if(!i)throw new Error(`${t}:${r}: #${n} without matching #if`);return i}function Mt(e,t){let r=e;for(let e=0;e<8;e+=1){const e=r;if(r=Dt(r,t),r=Bt(r,t),r===e)return r}return r}function Bt(e,t){return e.replace(/\b[A-Za-z_][A-Za-z0-9_]*\b/g,e=>{const r=t.get(e);return r&&null===r.parameters?r.body:e})}function Dt(e,t){let r=e;for(const e of t.values())null!==e.parameters&&(r=Tt(r,e));return r}function Tt(e,t){let r="",n=0;for(;n<e.length;){const i=It(e,t.name,n);if(i<0){r+=e.slice(n);break}let a=i+t.name.length;for(;/\s/.test(e[a]??"");)a+=1;if("("!==e[a]){r+=e.slice(n,i+t.name.length),n=i+t.name.length;continue}const s=Lt(e,a);if(s<0){r+=e.slice(n);break}const o=Rt(e.slice(a+1,s));r+=e.slice(n,i),r+=Gt(t,o),n=s+1}return r}function It(e,t,r){let n=e.indexOf(t,r);for(;n>=0;){const r=n>0?e[n-1]:"",i=e[n+t.length]??"";if(!/[A-Za-z0-9_]/.test(r)&&!/[A-Za-z0-9_]/.test(i))return n;n=e.indexOf(t,n+t.length)}return-1}function Gt(e,t){let r=e.body;const n=e.parameters??[];for(let e=0;e<n.length;e+=1){const i=n[e],a=t[e]?.trim()??"";r=r.replace(new RegExp(`\\b${At(i)}\\b`,"g"),a)}return r}function Rt(e){const t=[];let r=0,n=0;for(let i=0;i<e.length;i+=1){const a=e[i];"("===a?r+=1:")"===a?r-=1:","===a&&0===r&&(t.push(e.slice(n,i)),n=i+1)}return(e.length>0||n>0)&&t.push(e.slice(n)),t}function Lt(e,t){let r=0;for(let n=t;n<e.length;n+=1){const t=e[n];if("("===t)r+=1;else if(")"===t&&(r-=1,0===r))return n}return-1}function zt(e,t){const r=function(e){const t=[];let r=0;for(;r<e.length;){const n=e[r];if(/\s/.test(n)){r+=1;continue}const i=e.slice(r,r+2);if(["&&","||","==","!=","<=",">="].includes(i)){t.push({type:"operator",value:i}),r+=2;continue}if("!<>+-*/%".includes(n)){t.push({type:"operator",value:n}),r+=1;continue}if("("===n||")"===n){t.push({type:"paren",value:n}),r+=1;continue}const a=/^(?:0x[0-9A-Fa-f]+|\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)/.exec(e.slice(r));if(a){t.push({type:"number",value:a[0]}),r+=a[0].length;continue}const s=/^[A-Za-z_][A-Za-z0-9_]*/.exec(e.slice(r));s?(t.push({type:"identifier",value:s[0]}),r+=s[0].length):r+=1}return t}(Vt(e));return 0!==new Ut(r,t).parseExpression()}var Ut=class{constructor(e,t){this.tokens=e,this.macros=t}tokens;macros;cursor=0;parseExpression(){return this.parseLogicalOr()}parseLogicalOr(){let e=this.parseLogicalAnd();for(;this.consumeOperator("||");){const t=this.parseLogicalAnd();e=0!==e||0!==t?1:0}return e}parseLogicalAnd(){let e=this.parseEquality();for(;this.consumeOperator("&&");){const t=this.parseEquality();e=0!==e&&0!==t?1:0}return e}parseEquality(){let e=this.parseComparison();for(;;)if(this.consumeOperator("=="))e=e===this.parseComparison()?1:0;else{if(!this.consumeOperator("!="))return e;e=e!==this.parseComparison()?1:0}}parseComparison(){let e=this.parseAdditive();for(;;)if(this.consumeOperator("<"))e=e<this.parseAdditive()?1:0;else if(this.consumeOperator(">"))e=e>this.parseAdditive()?1:0;else if(this.consumeOperator("<="))e=e<=this.parseAdditive()?1:0;else{if(!this.consumeOperator(">="))return e;e=e>=this.parseAdditive()?1:0}}parseAdditive(){let e=this.parseMultiplicative();for(;;)if(this.consumeOperator("+"))e+=this.parseMultiplicative();else{if(!this.consumeOperator("-"))return e;e-=this.parseMultiplicative()}}parseMultiplicative(){let e=this.parseUnary();for(;;)if(this.consumeOperator("*"))e*=this.parseUnary();else if(this.consumeOperator("/"))e/=this.parseUnary();else{if(!this.consumeOperator("%"))return e;e%=this.parseUnary()}}parseUnary(){return this.consumeOperator("!")?0===this.parseUnary()?1:0:this.consumeOperator("-")?-this.parseUnary():this.consumeOperator("+")?this.parseUnary():this.parsePrimary()}parsePrimary(){const e=this.peek();if(!e)return 0;if("number"===e.type)return this.cursor+=1,e.value.startsWith("0x")?Number.parseInt(e.value,16):Number.parseFloat(e.value);if("identifier"===e.type&&"defined"===e.value){if(this.cursor+=1,this.consumeParen("(")){const e=this.consumeIdentifier();return this.consumeParen(")"),e&&this.macros.has(e)?1:0}const e=this.consumeIdentifier();return e&&this.macros.has(e)?1:0}if("identifier"===e.type)return this.cursor+=1,function(e){if(!e)return 0;const t=e.body.trim();if("true"===t)return 1;if("false"===t)return 0;const r=t.startsWith("0x")?Number.parseInt(t,16):Number.parseFloat(t);return Number.isFinite(r)?r:1}(this.macros.get(e.value));if(this.consumeParen("(")){const e=this.parseExpression();return this.consumeParen(")"),e}return this.cursor+=1,0}consumeIdentifier(){const e=this.peek();return"identifier"!==e?.type?null:(this.cursor+=1,e.value)}consumeOperator(e){const t=this.peek();return"operator"===t?.type&&t.value===e&&(this.cursor+=1,!0)}consumeParen(e){const t=this.peek();return"paren"===t?.type&&t.value===e&&(this.cursor+=1,!0)}peek(){return this.tokens[this.cursor]}};function Vt(e){const t=e.indexOf("//");return t>=0?e.slice(0,t):e}function At(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}import{Material as Ft}from"three";var Et=[{name:"position",shaderLocation:0,format:"float32x3"},{name:"normal",shaderLocation:1,format:"float32x3",defaultValue:[0,0,1]},{name:"uv",shaderLocation:2,format:"float32x2",defaultValue:[0,0]},{name:"color",shaderLocation:3,format:"float32x4",defaultValue:[1,1,1,1]}],kt=class e extends Ft{isWGSLShaderMaterial=!0;vertexShader;fragmentShader;depthVertexShader;depthFragmentShader;pointShadowVertexShader;pointShadowFragmentShader;defines;uniforms;textures;sceneTextures;graphTextures;storageBuffers;vertexAttributes;primitiveTopology;wireframe;uniformLayoutCache=null;programCacheKeyCache=null;textureListCache=null;textureVersionsCache=[];textureVersionHashCache=0;storageBufferBindingListCache=null;storageBufferListCache=null;textureLayoutKeyDeviceCache=null;textureLayoutKeyCache=null;constructor(e){super();const{vertexShader:t,fragmentShader:r,depthVertexShader:n,depthFragmentShader:i,pointShadowVertexShader:a,pointShadowFragmentShader:s,defines:o,uniforms:l,textures:c,sceneTextures:u,graphTextures:d,storageBuffers:h,vertexAttributes:p,primitiveTopology:f,wireframe:m,...g}=e,x=function(e,t){const r={},n={...t};for(const[t,i]of Object.entries(e)){const e=Nt(t,i);"texture"!==e.kind?r[t]=e.uniform:n[t]=e.texture}return{uniforms:r,textures:n}}(l??{},c??{});this.type="WGSLShaderMaterial",this.vertexShader=t,this.fragmentShader=r,this.depthVertexShader=n??null,this.depthFragmentShader=i??null,this.pointShadowVertexShader=a??null,this.pointShadowFragmentShader=s??null,this.defines={...o??{}},this.uniforms=x.uniforms,this.textures=x.textures,this.sceneTextures={...u??{}},this.graphTextures={...d??{}},this.storageBuffers={...h??{}},this.vertexAttributes=$t(p??Et),this.primitiveTopology=f??"triangle-list",this.wireframe=m??!1,this.transparent=g.transparent??!1,this.depthTest=g.depthTest??!0,this.depthWrite=g.depthWrite??!0,this.setValues(g)}getUniformLayout(){return null===this.uniformLayoutCache&&(this.uniformLayoutCache=je(this.uniforms)),this.uniformLayoutCache}setUniform(e,t){const r=Nt(e,t);return"texture"===r.kind?(delete this.uniforms[e],this.textures[e]=r.texture,this.uniformLayoutCache=null,this.invalidateBindingCache(),this.invalidateProgramStructureCache(),this.needsUpdate=!0,this):(delete this.textures[e],this.uniforms[e]=r.uniform,this.uniformLayoutCache=null,this.invalidateBindingCache(),this.invalidateProgramStructureCache(),this.needsUpdate=!0,this)}setDefine(e,t=!0){return this.defines[e]=t,this.invalidateProgramStructureCache(),this.needsUpdate=!0,this}deleteDefine(e){return delete this.defines[e],this.invalidateProgramStructureCache(),this.needsUpdate=!0,this}setTexture(e,t){return delete this.uniforms[e],this.textures[e]=t,this.uniformLayoutCache=null,this.invalidateBindingCache(),this.invalidateProgramStructureCache(),this.needsUpdate=!0,this}setStorageBuffer(e,t){return this.storageBuffers[e]=t,this.invalidateBindingCache(),this.invalidateProgramStructureCache(),this.needsUpdate=!0,this}setVertexAttributes(e){return this.vertexAttributes=$t(e),this.invalidateProgramStructureCache(),this.needsUpdate=!0,this}copy(e){return super.copy(e),this.vertexShader=e.vertexShader,this.fragmentShader=e.fragmentShader,this.depthVertexShader=e.depthVertexShader,this.depthFragmentShader=e.depthFragmentShader,this.pointShadowVertexShader=e.pointShadowVertexShader,this.pointShadowFragmentShader=e.pointShadowFragmentShader,this.defines={...e.defines},this.uniforms=Object.fromEntries(Object.entries(e.uniforms).map(([e,t])=>[e,{type:t.type,value:jt(t.value)}])),this.textures={...e.textures},this.sceneTextures={...e.sceneTextures},this.graphTextures={...e.graphTextures},this.storageBuffers={...e.storageBuffers},this.vertexAttributes=$t(e.vertexAttributes),this.primitiveTopology=e.primitiveTopology,this.wireframe=e.wireframe,this.uniformLayoutCache=null,this.invalidateBindingCache(),this.invalidateProgramStructureCache(),this}clone(){return new e({vertexShader:this.vertexShader,fragmentShader:this.fragmentShader}).copy(this)}customProgramCacheKey(){if(null!==this.programCacheKeyCache)return this.programCacheKeyCache;const e=Object.keys(this.defines).sort((e,t)=>e.localeCompare(t));let t=`vertex:${this.vertexShader};fragment:${this.fragmentShader};depthVertex:${this.depthVertexShader??""};depthFragment:${this.depthFragmentShader??""};pointShadowVertex:${this.pointShadowVertexShader??""};pointShadowFragment:${this.pointShadowFragmentShader??""};`;for(const r of e)t+=`${r}:${String(this.defines[r])};`;for(const e in this.uniforms)t+=`uniform:${e}:${this.uniforms[e].type};`;for(const[e,r]of Object.entries(this.textures))t+=`texture:${e}:${be(r)};`;for(const[e,r]of Object.entries(this.sceneTextures))t+=`sceneTexture:${e}:${r};`;for(const[e,r]of Object.entries(this.getGraphTextureInputs()))t+=`graphTexture:${e}:${r.resource}:${r.dimension}:${r.sampleType??"float"}:${r.sampler??"filtering"}:${Number(r.requiresLatePass??!1)};`;for(const[e,r]of Object.entries(this.storageBuffers))t+=`storage:${e}:${r.type}:${r.visibility??"fragment"};`;for(const e of this.vertexAttributes){const r=e.defaultValue?e.defaultValue.join(","):"";t+=`attribute:${e.name}:${e.shaderLocation}:${e.format}:${e.stepMode??"vertex"}:${r};`}return t+=`topology:${this.primitiveTopology};wireframe:${Number(this.wireframe)};transparent:${Number(this.transparent)};blending:${this.blending};premultipliedAlpha:${Number(this.premultipliedAlpha)};blendSrc:${this.blendSrc};blendDst:${this.blendDst};blendEquation:${this.blendEquation};blendSrcAlpha:${this.blendSrcAlpha};blendDstAlpha:${this.blendDstAlpha};blendEquationAlpha:${this.blendEquationAlpha};depthWrite:${Number(this.depthWrite)};depthTest:${Number(this.depthTest)};side:${String(this.side)};shadowSide:${String(this.shadowSide)};`,this.programCacheKeyCache=t,this.programCacheKeyCache}getTexturesList(){return null===this.textureListCache&&(this.textureListCache=Object.values(this.textures)),this.textureListCache}usesSceneTextures(){return Object.keys(this.sceneTextures).length>0||Object.values(this.graphTextures).some(e=>"sceneColorSnapshot"===e.resource||"sceneDepthSnapshot"===e.resource)}getGraphTextureInputs(){const e={...this.graphTextures};for(const[t,r]of Object.entries(this.sceneTextures))e[t]="sceneDepth"===r?{resource:"sceneDepthSnapshot",dimension:"depth-2d",sampleType:"depth",sampler:"non-filtering",requiresLatePass:!0}:{resource:"sceneColorSnapshot",dimension:"2d",sampleType:"float",sampler:"filtering",requiresLatePass:!0};return e}requiresLatePass(){return Object.values(this.getGraphTextureInputs()).some(e=>!0===e.requiresLatePass)}getUniformValueHash(){return function(e,t){let r=2166136261;for(let n=0;n<t.entries.length;n+=1){const i=t.entries[n],a=e[i.name];if(a)switch(r=We(r,i.offset),i.type){case"f32":case"i32":case"u32":r=_e(r,"boolean"==typeof a.value?a.value?1:0:Number(a.value));break;case"vec2<f32>":r=qe(r,a.value,2);break;case"vec3<f32>":r=qe(r,a.value,3);break;case"vec4<f32>":r=qe(r,a.value,4);break;case"mat3x3<f32>":r=qe(r,a.value,9);break;case"mat4x4<f32>":r=qe(r,a.value,16);break;default:r=We(r,n+17)}else r=We(r,n+1)}return r>>>0}(this.uniforms,this.getUniformLayout())}getTextureVersionsList(){const e=this.getTexturesList(),t=this.textureVersionsCache;t.length=e.length;let r=2166136261;for(let n=0;n<e.length;n+=1){const i=e[n].version;t[n]=i,r=Math.imul((r^i)>>>0,16777619)>>>0}return this.textureVersionHashCache=r,t}getTextureVersionHash(){return this.getTextureVersionsList(),this.textureVersionHashCache}getStorageBufferBindingList(){return null===this.storageBufferBindingListCache&&(this.storageBufferBindingListCache=Object.values(this.storageBuffers)),this.storageBufferBindingListCache}getStorageBufferList(){if(null===this.storageBufferListCache){const e=this.getStorageBufferBindingList();this.storageBufferListCache=e.map(e=>e.buffer)}return this.storageBufferListCache}getTextureLayoutKey(e){return null!==this.textureLayoutKeyCache&&this.textureLayoutKeyDeviceCache===e||(this.textureLayoutKeyDeviceCache=e,this.textureLayoutKeyCache=this.getTexturesList().map(t=>we(t,e)).join("|")),this.textureLayoutKeyCache}invalidateProgramStructureCache(){this.programCacheKeyCache=null}invalidateBindingCache(){this.textureListCache=null,this.textureVersionsCache.length=0,this.textureVersionHashCache=0,this.storageBufferBindingListCache=null,this.storageBufferListCache=null,this.textureLayoutKeyDeviceCache=null,this.textureLayoutKeyCache=null}};function Ot(e){return!0===e.isWGSLShaderMaterial}function $t(e){return e.map(e=>({name:e.name,shaderLocation:e.shaderLocation,format:e.format,stepMode:e.stepMode,defaultValue:e.defaultValue?Array.from(e.defaultValue):void 0}))}function jt(e){return Array.isArray(e)?Array.from(e):"number"==typeof e||"boolean"==typeof e?e:e.clone()}function Nt(e,t){const r=_t(t)?t:null,n=null!==r&&"value"in r?r.value:t;if(function(e){return Wt(e,"isTexture")}(n))return{kind:"texture",texture:n};if(!function(e){return"number"==typeof e||"boolean"==typeof e||Array.isArray(e)||Wt(e,"isColor")||Wt(e,"isVector2")||Wt(e,"isVector3")||Wt(e,"isVector4")||Wt(e,"isMatrix3")||Wt(e,"isMatrix4")}(n))throw new Error(`Unsupported WGSLShaderMaterial uniform "${e}". Use a number, boolean, vector, color, matrix, numeric array, or Texture.`);const i=r?.type,a=function(e){return"f32"===e||"i32"===e||"u32"===e||"vec2<f32>"===e||"vec3<f32>"===e||"vec4<f32>"===e||"mat3x3<f32>"===e||"mat4x4<f32>"===e}(i)?i:function(e,t){if("number"==typeof t)return"f32";if("boolean"==typeof t)return"u32";if(Array.isArray(t)){if(t.length<=1)return"f32";if(2===t.length)return"vec2<f32>";if(3===t.length)return"vec3<f32>";if(4===t.length)return"vec4<f32>";if(9===t.length)return"mat3x3<f32>";if(16===t.length)return"mat4x4<f32>";throw new Error(`Cannot infer WGSL type for uniform "${e}" from an array of length ${t.length}. Provide an explicit type.`)}if(Wt(t,"isColor"))return"vec3<f32>";if(Wt(t,"isVector2"))return"vec2<f32>";if(Wt(t,"isVector3"))return"vec3<f32>";if(Wt(t,"isVector4"))return"vec4<f32>";if(Wt(t,"isMatrix3"))return"mat3x3<f32>";if(Wt(t,"isMatrix4"))return"mat4x4<f32>";throw new Error(`Cannot infer WGSL type for uniform "${e}". Provide an explicit type.`)}(e,n);return{kind:"uniform",uniform:{type:a,value:n}}}function Wt(e,t){return _t(e)&&!0===e[t]}function _t(e){return"object"==typeof e&&null!==e}var qt=class{passes=[];addPass(e){this.passes.push(e)}async executeAsync(e,t){const r=this.resolveExecutionOrder(),n=performance.now();t?.begin?.(r,e);for(let n=0;n<r.length;n+=1){const i=r[n];t?.beforePass?.(i,n,e);const a=performance.now();await(i.prepare?.(e)),i.execute(e),t?.afterPass?.(i,n,performance.now()-a,e)}t?.end?.(r,performance.now()-n,e)}execute(e,t){const r=this.resolveExecutionOrder(),n=performance.now();t?.begin?.(r,e);for(let n=0;n<r.length;n+=1){const i=r[n];t?.beforePass?.(i,n,e);const a=performance.now();i.execute(e),t?.afterPass?.(i,n,performance.now()-a,e)}t?.end?.(r,performance.now()-n,e)}reset(){this.passes.length=0}resolveExecutionOrder(){const e=new Map,t=new Map,r=new Map,n=new Map;for(const n of this.passes)e.set(n.name,n),t.set(n.name,new Set(n.dependsOn??[])),r.set(n.name,new Set);for(const e of this.passes){const r=t.get(e.name);for(const t of e.reads??[]){const i=n.get(t);i&&i!==e.name&&r.add(i)}for(const t of e.writes??[]){const i=n.get(t);i&&i!==e.name&&r.add(i),n.set(t,e.name)}}for(const[e,n]of t)for(const t of n){const n=r.get(t);if(!n)throw new Error(`RenderGraph dependency "${t}" for pass "${e}" is missing.`);n.add(e)}const i=Array.from(t.entries()).filter(([,e])=>0===e.size).map(([e])=>e),a=[];for(;i.length>0;){const n=i.shift();a.push(e.get(n));for(const e of r.get(n)??[]){const r=t.get(e);r.delete(n),0===r.size&&i.push(e)}}if(a.length!==this.passes.length)throw new Error("RenderGraph contains a dependency cycle.");return a}};import{CubeUVReflectionMapping as Ht,HalfFloatType as Kt,LinearFilter as Zt,LinearSRGBColorSpace as Yt,RGBAFormat as Xt,Texture as Jt}from"three";var Qt=[.125,.215,.35,.446,.526,.582],er=20,tr=function(){const e=(1+Math.sqrt(5))/2,t=1/e;return[[-e,t,0],[e,t,0],[-t,0,e],[t,0,e],[0,e,-t],[0,e,t],[-1,1,-1],[1,1,-1],[-1,1,1],[1,1,1]]}(),rr=class{constructor(e,t=20){this.context=e;const{device:r}=e,n=Math.max(1,Math.min(20,Math.floor(t)));this.maxBlurSamples=n,this.equirectBindGroupLayout=r.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}},{binding:1,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"unfilterable-float",viewDimension:"2d"}}]}),this.blurBindGroupLayout=r.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}},{binding:1,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float",viewDimension:"2d"}},{binding:2,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}}]}),this.equirectPipeline=nr(r,this.equirectBindGroupLayout,sr,"pmrem-equirectangular"),this.blurPipeline=nr(r,this.blurBindGroupLayout,or.replaceAll("PMREM_MAX_SAMPLES",String(n)),"pmrem-blur")}context;equirectPipeline;blurPipeline;equirectBindGroupLayout;blurBindGroupLayout;maxBlurSamples;fromEquirectangular(e){const t=this.context.getTextureResource(e);if("2d"!==t.viewDimension)throw new Error("WebGpuPMREMGenerator.fromEquirectangular() requires a 2D equirectangular texture.");const r=2**Math.floor(Math.log2(Math.max(16,Math.floor(t.width/4)))),n=Math.floor(Math.log2(r)),i=function(e){const t=[];for(let r=e;r>=4;r-=1){const n=2**r;t.push({mip:r,size:n,sigma:r===e?0:1/n})}for(let e=0;e<Qt.length;e+=1)t.push({mip:4-e-1,size:16,sigma:Qt[e]});return t}(n),a=3*Math.max(r,112),s=4*r,{device:o}=this.context,l=GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING,c=o.createTexture({label:"pmrem-cubeuv",size:{width:a,height:s},format:"rgba16float",usage:l}),u=o.createTexture({label:"pmrem-cubeuv-ping",size:{width:a,height:s},format:"rgba16float",usage:l}),d=o.createSampler({magFilter:"linear",minFilter:"linear"}),h=o.createCommandEncoder({label:"pmrem-generation"}),p=[],f=ir(o,new Float32Array([t.width,t.height,r,0]));p.push(f);const m=o.createBindGroup({layout:this.equirectBindGroupLayout,entries:[{binding:0,resource:{buffer:f}},{binding:1,resource:t.view}]}),g=h.beginRenderPass({colorAttachments:[{view:c.createView(),loadOp:"clear",storeOp:"store",clearValue:[0,0,0,1]}]});g.setViewport(0,0,3*r,2*r,0,1),g.setScissorRect(0,0,3*r,2*r),g.setPipeline(this.equirectPipeline),g.setBindGroup(0,m),g.draw(36),g.end();for(let e=1;e<i.length;e+=1){const t=i[e-1],r=i[e],o=Math.sqrt(r.sigma*r.sigma-t.sigma*t.sigma),l=tr[(i.length-e-1)%tr.length];this.encodeBlurPass({encoder:h,source:c,target:u,sampler:d,atlasWidth:a,atlasHeight:s,maxMip:n,inputLevel:t,outputLevel:r,sigma:o,poleAxis:l,latitudinal:!0,clear:!0,transientBuffers:p}),this.encodeBlurPass({encoder:h,source:u,target:c,sampler:d,atlasWidth:a,atlasHeight:s,maxMip:n,inputLevel:r,outputLevel:r,sigma:o,poleAxis:l,latitudinal:!1,clear:!1,transientBuffers:p})}o.queue.submit([h.finish()]),o.queue.onSubmittedWorkDone().then(()=>{for(const e of p)e.destroy();u.destroy()});const x=new Jt;return x.image={width:a,height:s},x.name="PMREM.cubeUv",x.mapping=Ht,x.format=Xt,x.type=Kt,x.colorSpace=Yt,x.minFilter=Zt,x.magFilter=Zt,x.generateMipmaps=!1,x.needsUpdate=!0,this.context.registerTextureResource(x,{version:x.version,width:a,height:s,depthOrArrayLayers:1,format:"rgba16float",textureDimension:"2d",viewDimension:"2d",sampleType:"float",samplerBindingType:"filtering",mipLevelCount:1,texture:c,view:c.createView(),sampler:d}),{texture:x,dispose:()=>{c.destroy(),x.dispose()}}}encodeBlurPass(e){const{encoder:t,source:r,target:n,sampler:i,atlasWidth:a,atlasHeight:s,maxMip:o,inputLevel:l,outputLevel:c,sigma:u,poleAxis:d,latitudinal:h,clear:p,transientBuffers:f}=e,m=l.size-1,g=Math.PI/(2*m),x=u/g,v=Math.min(this.maxBlurSamples,1+Math.floor(3*x)),w=function(e,t){const r=new Float32Array(er);let n=0;for(let i=0;i<er;i+=1){const a=i/e,s=Math.exp(-a*a/2);r[i]=s,0===i?n+=s:i<t&&(n+=2*s)}for(let e=0;e<r.length;e+=1)r[e]/=n;return r}(x,v),b=ir(this.context.device,function(e){const t=new ArrayBuffer(144),r=new DataView(t);return r.setFloat32(0,e.atlasWidth,!0),r.setFloat32(4,e.atlasHeight,!0),r.setFloat32(8,e.outputFaceSize,!0),r.setFloat32(12,e.inputMip,!0),r.setFloat32(16,e.dTheta,!0),r.setUint32(20,e.sampleCount,!0),r.setUint32(24,e.latitudinal?1:0,!0),r.setFloat32(28,e.maxMip,!0),r.setFloat32(32,e.poleAxis[0],!0),r.setFloat32(36,e.poleAxis[1],!0),r.setFloat32(40,e.poleAxis[2],!0),new Float32Array(t,48,er).set(e.weights),new Float32Array(t)}({atlasWidth:a,atlasHeight:s,outputFaceSize:c.size,inputMip:l.mip,dTheta:g,sampleCount:v,latitudinal:h,poleAxis:d,weights:w,maxMip:o}));f.push(b);const y=this.context.device.createBindGroup({layout:this.blurBindGroupLayout,entries:[{binding:0,resource:{buffer:b}},{binding:1,resource:r.createView()},{binding:2,resource:i}]}),S=3*c.size*Math.max(0,4-c.mip),C=4*(2**o-c.size),P=t.beginRenderPass({colorAttachments:[{view:n.createView(),loadOp:p?"clear":"load",storeOp:"store",clearValue:[0,0,0,1]}]});P.setViewport(S,C,3*c.size,2*c.size,0,1),P.setScissorRect(S,C,3*c.size,2*c.size),P.setPipeline(this.blurPipeline),P.setBindGroup(0,y),P.draw(36),P.end()}};function nr(e,t,r,n){const i=e.createShaderModule({code:r,label:`${n}-shader`});return i.getCompilationInfo().then(e=>{const t=e.messages.filter(e=>"error"===e.type);t.length>0&&console.error(`[WebGpuPMREMGenerator] ${n} WGSL compilation failed.`,t)}),e.createRenderPipeline({label:n,layout:e.createPipelineLayout({bindGroupLayouts:[t]}),vertex:{module:i,entryPoint:"vs"},fragment:{module:i,entryPoint:"fs",targets:[{format:"rgba16float"}]},primitive:{topology:"triangle-list"}})}function ir(e,t){const r=e.createBuffer({size:t.byteLength,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST});return e.queue.writeBuffer(r,0,t.buffer,t.byteOffset,t.byteLength),r}var ar="\nstruct VertexOutput {\n @builtin(position) position: vec4f,\n @location(0) uv: vec2f,\n @location(1) @interpolate(flat) face: u32,\n};\n\nconst corners = array<vec2f, 6>(\n vec2f(0, 0), vec2f(1, 0), vec2f(1, 1),\n vec2f(0, 0), vec2f(1, 1), vec2f(0, 1),\n);\n\n@vertex\nfn vs(@builtin(vertex_index) index: u32) -> VertexOutput {\n let face = index / 6u;\n let corner = corners[index % 6u];\n var output: VertexOutput;\n output.position = vec4f(\n (corner.x + f32(face % 3u)) / 3.0 * 2.0 - 1.0,\n 1.0 - (corner.y + f32(face / 3u)),\n 0.0,\n 1.0,\n );\n output.uv = corner;\n output.face = face;\n return output;\n}\n\nfn cubeDirection(inputUv: vec2f, face: u32, faceSize: f32) -> vec3f {\n let gutter = 1.0 / (faceSize - 2.0);\n let uv = (inputUv * (1.0 + 2.0 * gutter) - vec2f(gutter)) * 2.0 - 1.0;\n if (face == 0u) { return normalize(vec3f(1.0, uv.y, uv.x)); }\n if (face == 1u) { return normalize(vec3f(-uv.x, 1.0, -uv.y)); }\n if (face == 2u) { return normalize(vec3f(-uv.x, uv.y, 1.0)); }\n if (face == 3u) { return normalize(vec3f(-1.0, uv.y, -uv.x)); }\n if (face == 4u) { return normalize(vec3f(-uv.x, -1.0, uv.y)); }\n return normalize(vec3f(uv.x, uv.y, -1.0));\n}\n",sr=`${ar}\nstruct EquirectParams {\n sourceSize: vec2f,\n faceSize: f32,\n _padding: f32,\n};\n\n@group(0) @binding(0) var<uniform> params: EquirectParams;\n@group(0) @binding(1) var environmentMap: texture_2d<f32>;\n\nfn sampleEquirectangular(direction: vec3f) -> vec3f {\n let uv = vec2f(\n atan2(direction.z, direction.x) / (2.0 * 3.141592653589793) + 0.5,\n asin(clamp(direction.y, -1.0, 1.0)) / 3.141592653589793 + 0.5,\n );\n let pixel = uv * params.sourceSize - vec2f(0.5);\n let base = vec2i(floor(pixel));\n let fraction = fract(pixel);\n let width = i32(params.sourceSize.x);\n let height = i32(params.sourceSize.y);\n let x0 = (base.x % width + width) % width;\n let x1 = (x0 + 1) % width;\n let y0 = clamp(base.y, 0, height - 1);\n let y1 = min(y0 + 1, height - 1);\n let top = mix(\n textureLoad(environmentMap, vec2i(x0, y0), 0).rgb,\n textureLoad(environmentMap, vec2i(x1, y0), 0).rgb,\n fraction.x,\n );\n let bottom = mix(\n textureLoad(environmentMap, vec2i(x0, y1), 0).rgb,\n textureLoad(environmentMap, vec2i(x1, y1), 0).rgb,\n fraction.x,\n );\n return mix(top, bottom, fraction.y);\n}\n\n@fragment\nfn fs(input: VertexOutput) -> @location(0) vec4f {\n let direction = cubeDirection(input.uv, input.face, params.faceSize);\n return vec4f(sampleEquirectangular(direction), 1.0);\n}\n`,or=`${ar}\nstruct BlurParams {\n atlasSize: vec2f,\n outputFaceSize: f32,\n inputMip: f32,\n dTheta: f32,\n samples: u32,\n latitudinal: u32,\n maxMip: f32,\n poleAxis: vec3f,\n _padding: f32,\n weights: array<vec4f, 5>,\n};\n\n@group(0) @binding(0) var<uniform> params: BlurParams;\n@group(0) @binding(1) var environmentMap: texture_2d<f32>;\n@group(0) @binding(2) var environmentSampler: sampler;\n\nfn cubeFace(direction: vec3f) -> f32 {\n let absolute = abs(direction);\n if (absolute.x > absolute.z) {\n if (absolute.x > absolute.y) { return select(3.0, 0.0, direction.x > 0.0); }\n return select(4.0, 1.0, direction.y > 0.0);\n }\n if (absolute.z > absolute.y) { return select(5.0, 2.0, direction.z > 0.0); }\n return select(4.0, 1.0, direction.y > 0.0);\n}\n\nfn cubeUv(direction: vec3f, face: f32) -> vec2f {\n if (face == 0.0) { return 0.5 * (vec2f(direction.z, direction.y) / abs(direction.x) + 1.0); }\n if (face == 1.0) { return 0.5 * (vec2f(-direction.x, -direction.z) / abs(direction.y) + 1.0); }\n if (face == 2.0) { return 0.5 * (vec2f(-direction.x, direction.y) / abs(direction.z) + 1.0); }\n if (face == 3.0) { return 0.5 * (vec2f(-direction.z, direction.y) / abs(direction.x) + 1.0); }\n if (face == 4.0) { return 0.5 * (vec2f(-direction.x, direction.z) / abs(direction.y) + 1.0); }\n return 0.5 * (vec2f(direction.x, direction.y) / abs(direction.z) + 1.0);\n}\n\nfn sampleCubeUv(direction: vec3f) -> vec3f {\n var face = cubeFace(direction);\n let filterOffset = max(4.0 - params.inputMip, 0.0);\n let mip = max(params.inputMip, 4.0);\n let faceSize = exp2(mip);\n var uv = cubeUv(direction, face) * (faceSize - 2.0) + 1.0;\n if (face > 2.0) {\n uv.y += faceSize;\n face -= 3.0;\n }\n uv.x += face * faceSize + filterOffset * 3.0 * 16.0;\n uv.y += 4.0 * (exp2(params.maxMip) - faceSize);\n return textureSampleLevel(environmentMap, environmentSampler, uv / params.atlasSize, 0.0).rgb;\n}\n\nfn weight(index: u32) -> f32 {\n return params.weights[index / 4u][index % 4u];\n}\n\nfn rotatedSample(direction: vec3f, theta: f32, axis: vec3f) -> vec3f {\n let cosine = cos(theta);\n let sampleDirection = direction * cosine\n + cross(axis, direction) * sin(theta)\n + axis * dot(axis, direction) * (1.0 - cosine);\n return sampleCubeUv(sampleDirection);\n}\n\n@fragment\nfn fs(input: VertexOutput) -> @location(0) vec4f {\n let direction = cubeDirection(input.uv, input.face, params.outputFaceSize);\n var axis = select(cross(params.poleAxis, direction), params.poleAxis, params.latitudinal != 0u);\n if (dot(axis, axis) < 0.000001) { axis = vec3f(direction.z, 0.0, -direction.x); }\n axis = normalize(axis);\n var color = weight(0u) * rotatedSample(direction, 0.0, axis);\n for (var index = 1u; index < PMREM_MAX_SAMPLES; index += 1u) {\n if (index >= params.samples) { break; }\n let theta = params.dTheta * f32(index);\n color += weight(index) * rotatedSample(direction, -theta, axis);\n color += weight(index) * rotatedSample(direction, theta, axis);\n }\n return vec4f(color, 1.0);\n}\n`;function lr(e){return e.replace(/[^A-Za-z0-9_]/g,"_")}function cr(e,t){const r=Object.entries(e.uniforms).map(([e,t])=>` ${lr(e)}: ${t.type},`).join("\n"),n=r?`\nstruct MaterialUniforms {\n${r}\n};\n\n@group(1) @binding(0) var<uniform> materialUniforms: MaterialUniforms;\n`:"",i=Object.entries(e.textures).map(([e,r],n)=>{const i=1+2*n,a=lr(e),s=ve(r,t);return[`@group(1) @binding(${i}) var ${a}Sampler: ${s.wgslSamplerType};`,`@group(1) @binding(${i+1}) var ${a}Texture: ${s.wgslTextureType};`].join("\n")}).join("\n"),a=1+2*Object.keys(e.textures).length;return`${n}\n${i}\n${Object.entries(e.storageBuffers).map(([e,t],r)=>{const n=lr(e);return`@group(1) @binding(${a+r}) var<storage, read> ${n}: ${t.type};`}).join("\n")}`}function ur(e){return`\nfn rendererModelMatrix(instanceIndex: u32) -> mat4x4<f32> {\n return rendererInstanceModelMatrix(instanceIndex);\n}\n\nfn rendererNormalMatrix(instanceIndex: u32) -> mat3x3<f32> {\n ${e?"let view = rendererViewMatrix();\n let viewRotation = mat3x3<f32>(view[0].xyz, view[1].xyz, view[2].xyz);\n return viewRotation * rendererInstanceNormalMatrix(instanceIndex);":"return rendererInstanceNormalMatrix(instanceIndex);"}\n}\n\nfn modelMatrix(instanceIndex: u32) -> mat4x4<f32> {\n return rendererModelMatrix(instanceIndex);\n}\n\nfn normalMatrix(instanceIndex: u32) -> mat3x3<f32> {\n return rendererNormalMatrix(instanceIndex);\n}\n${e?`\nfn rendererViewMatrix() -> mat4x4<f32> {\n return ${e}.view;\n}\n\nfn rendererProjectionMatrix() -> mat4x4<f32> {\n return ${e}.projection;\n}\n\nfn rendererModelViewMatrix(instanceIndex: u32) -> mat4x4<f32> {\n return rendererViewMatrix() * rendererModelMatrix(instanceIndex);\n}\n\nfn rendererModelViewProjectionMatrix(instanceIndex: u32) -> mat4x4<f32> {\n return rendererProjectionMatrix() * rendererModelViewMatrix(instanceIndex);\n}\n\nfn rendererCameraPosition() -> vec3<f32> {\n return ${e}.cameraPosition.xyz;\n}\n\nfn rendererCameraNear() -> f32 {\n return ${e}.nearFar.x;\n}\n\nfn rendererCameraFar() -> f32 {\n return ${e}.nearFar.y;\n}\n\n${"rendererCamera"===e?`\nfn rendererFogColor() -> vec3<f32> {\n return ${e}.fogColor.rgb;\n}\n\nfn rendererFogNear() -> f32 {\n return ${e}.fogParams.x;\n}\n\nfn rendererFogFar() -> f32 {\n return ${e}.fogParams.y;\n}\n\nfn rendererFogDensity() -> f32 {\n return ${e}.fogParams.z;\n}\n\nfn rendererFogMode() -> f32 {\n return ${e}.fogParams.w;\n}\n`:""}\n\nfn rendererElapsedTime() -> f32 {\n return ${"rendererCamera"===e?"rendererCamera.viewportAndTime.w":"shadowCamera"===e?"shadowCamera.timeAndPadding.x":null};\n}\n\nfn viewMatrix() -> mat4x4<f32> {\n return rendererViewMatrix();\n}\n\nfn projectionMatrix() -> mat4x4<f32> {\n return rendererProjectionMatrix();\n}\n\nfn modelViewMatrix(instanceIndex: u32) -> mat4x4<f32> {\n return rendererModelViewMatrix(instanceIndex);\n}\n\nfn modelViewProjectionMatrix(instanceIndex: u32) -> mat4x4<f32> {\n return rendererModelViewProjectionMatrix(instanceIndex);\n}\n\nfn cameraPosition() -> vec3<f32> {\n return rendererCameraPosition();\n}\n`:""}`}function dr(e){return e?"\nstruct RendererSkinningUniforms {\n bindMatrix: mat4x4<f32>,\n bindMatrixInverse: mat4x4<f32>,\n};\n\n@group(2) @binding(0) var<storage, read> rendererBoneMatrixColumns: array<vec4<f32>>;\n@group(2) @binding(1) var<uniform> rendererSkinning: RendererSkinningUniforms;\n\nfn rendererBoneMatrix(index: u32) -> mat4x4<f32> {\n let base = index * 4u;\n return mat4x4<f32>(\n rendererBoneMatrixColumns[base + 0u],\n rendererBoneMatrixColumns[base + 1u],\n rendererBoneMatrixColumns[base + 2u],\n rendererBoneMatrixColumns[base + 3u],\n );\n}\n\nfn rendererSkinPosition(position: vec3<f32>, skinIndex: vec4<u32>, skinWeight: vec4<f32>) -> vec3<f32> {\n let boundPosition = rendererSkinning.bindMatrix * vec4(position, 1.0);\n let weightSum = skinWeight.x + skinWeight.y + skinWeight.z + skinWeight.w;\n if (weightSum <= 0.0) {\n return position;\n }\n let skinnedPosition =\n (rendererBoneMatrix(skinIndex.x) * boundPosition) * skinWeight.x +\n (rendererBoneMatrix(skinIndex.y) * boundPosition) * skinWeight.y +\n (rendererBoneMatrix(skinIndex.z) * boundPosition) * skinWeight.z +\n (rendererBoneMatrix(skinIndex.w) * boundPosition) * skinWeight.w;\n let fallbackWeight = max(0.0, 1.0 - weightSum);\n return (rendererSkinning.bindMatrixInverse * (skinnedPosition + boundPosition * fallbackWeight)).xyz;\n}\n\nfn rendererSkinNormal(normal: vec3<f32>, skinIndex: vec4<u32>, skinWeight: vec4<f32>) -> vec3<f32> {\n let boundNormal = rendererSkinning.bindMatrix * vec4(normal, 0.0);\n let weightSum = skinWeight.x + skinWeight.y + skinWeight.z + skinWeight.w;\n if (weightSum <= 0.0) {\n return normalize(normal);\n }\n let skinnedNormal =\n (rendererBoneMatrix(skinIndex.x) * boundNormal) * skinWeight.x +\n (rendererBoneMatrix(skinIndex.y) * boundNormal) * skinWeight.y +\n (rendererBoneMatrix(skinIndex.z) * boundNormal) * skinWeight.z +\n (rendererBoneMatrix(skinIndex.w) * boundNormal) * skinWeight.w;\n let fallbackWeight = max(0.0, 1.0 - weightSum);\n return normalize((rendererSkinning.bindMatrixInverse * (skinnedNormal + boundNormal * fallbackWeight)).xyz);\n}\n":""}function hr(e,t,r="packed",n=!0,i=!1){const a=cr(e,t),s=function(e){return Object.entries(e.getGraphTextureInputs()).map(([e,t],r)=>{const n=lr(e);return`@group(3) @binding(${2*r}) var ${n}Sampler: ${"comparison"===t.sampler?"sampler_comparison":"sampler"};\n@group(3) @binding(${2*r+1}) var ${n}Texture: ${"depth-2d"===t.dimension?"texture_depth_2d":"3d"===t.dimension?"texture_3d<f32>":"texture_2d<f32>"};`}).join("\n")}(e),o="packed-visible"===r,l=n?"\nfn rendererSampleDirectionalShadowForLight(lightIndex: u32, worldPosition: vec3<f32>) -> f32 {\n if (lightIndex >= rendererDirectionalLightCount() || !rendererDirectionalShadowEnabledForLight(lightIndex)) {\n return 1.0;\n }\n\n let matrix = rendererDirectionalShadowMatrixForLight(lightIndex);\n let shadowClip = matrix * vec4(worldPosition, 1.0);\n if (shadowClip.w <= 0.0) {\n return 1.0;\n }\n\n let ndc = shadowClip.xyz / shadowClip.w;\n if (ndc.x < -1.0 || ndc.x > 1.0 || ndc.y < -1.0 || ndc.y > 1.0 || ndc.z < 0.0 || ndc.z > 1.0) {\n return 1.0;\n }\n\n let uv = ndc.xy * vec2(0.5, -0.5) + vec2(0.5, 0.5);\n let dims = vec2<f32>(textureDimensions(rendererDirectionalShadowTexture));\n let texel = 1.0 / max(dims, vec2(1.0, 1.0));\n let radius = max(rendererLights.directionalShadowParams2[lightIndex].x, 0.0);\n // Match Three.js/three-shader-graph semantics: negative bias moves the\n // receiver toward the light and therefore reduces self-shadowing.\n let depth = ndc.z + rendererDirectionalShadowBiasForLight(lightIndex);\n let filterOffset = texel * radius;\n\n // Each comparison-level sample is already a hardware-filtered 2x2 PCF\n // lookup. A weighted center plus four cardinal taps gives a compact tent\n // filter (five lookups rather than nine manual depth loads) and is legal in\n // non-uniform control flow because the explicit level computes no derivatives.\n let center = textureSampleCompareLevel(\n rendererDirectionalShadowTexture,\n rendererShadowSampler,\n uv,\n i32(lightIndex),\n depth\n );\n let left = textureSampleCompareLevel(\n rendererDirectionalShadowTexture,\n rendererShadowSampler,\n clamp(uv - vec2(filterOffset.x, 0.0), vec2(0.0), vec2(1.0)),\n i32(lightIndex),\n depth\n );\n let right = textureSampleCompareLevel(\n rendererDirectionalShadowTexture,\n rendererShadowSampler,\n clamp(uv + vec2(filterOffset.x, 0.0), vec2(0.0), vec2(1.0)),\n i32(lightIndex),\n depth\n );\n let up = textureSampleCompareLevel(\n rendererDirectionalShadowTexture,\n rendererShadowSampler,\n clamp(uv - vec2(0.0, filterOffset.y), vec2(0.0), vec2(1.0)),\n i32(lightIndex),\n depth\n );\n let down = textureSampleCompareLevel(\n rendererDirectionalShadowTexture,\n rendererShadowSampler,\n clamp(uv + vec2(0.0, filterOffset.y), vec2(0.0), vec2(1.0)),\n i32(lightIndex),\n depth\n );\n let shadow = (center * 4.0 + left + right + up + down) * 0.125;\n return mix(1.0, shadow, rendererDirectionalShadowIntensityForLight(lightIndex));\n}\n\nfn rendererSampleDirectionalShadowForLightWithNormal(lightIndex: u32, worldPosition: vec3<f32>, worldNormal: vec3<f32>) -> f32 {\n let params = rendererLights.directionalShadowParams[lightIndex];\n return rendererSampleDirectionalShadowForLight(lightIndex, worldPosition + normalize(worldNormal) * params.w);\n}\n\nfn rendererPointShadowUvLayer(direction: vec3<f32>, pointIndex: u32) -> vec3<f32> {\n let absDir = abs(direction);\n var face = 0u;\n var uv = vec2<f32>(0.0, 0.0);\n if (absDir.x >= absDir.y && absDir.x >= absDir.z) {\n if (direction.x >= 0.0) {\n face = 0u;\n uv = vec2<f32>(-direction.z, -direction.y) / absDir.x;\n } else {\n face = 1u;\n uv = vec2<f32>(direction.z, -direction.y) / absDir.x;\n }\n } else if (absDir.y >= absDir.x && absDir.y >= absDir.z) {\n if (direction.y >= 0.0) {\n face = 2u;\n uv = vec2<f32>(direction.x, direction.z) / absDir.y;\n } else {\n face = 3u;\n uv = vec2<f32>(direction.x, -direction.z) / absDir.y;\n }\n } else {\n if (direction.z >= 0.0) {\n face = 4u;\n uv = vec2<f32>(direction.x, -direction.y) / absDir.z;\n } else {\n face = 5u;\n uv = vec2<f32>(-direction.x, -direction.y) / absDir.z;\n }\n }\n return vec3<f32>(uv * 0.5 + vec2(0.5, 0.5), f32(pointIndex * 6u + face));\n}\n\nfn rendererSamplePointShadowForLight(lightIndex: u32, worldPosition: vec3<f32>) -> f32 {\n if (lightIndex >= rendererPointLightCount() || !rendererPointShadowEnabledForLight(lightIndex)) {\n return 1.0;\n }\n let lightPosition = rendererPointLightPositionForLight(lightIndex);\n let range = rendererPointLightRangeForLight(lightIndex);\n let toFragment = worldPosition - lightPosition;\n let distanceToLight = length(toFragment);\n if (distanceToLight >= range) {\n return 1.0;\n }\n let uvLayer = rendererPointShadowUvLayer(toFragment, lightIndex);\n let dims = vec2<f32>(textureDimensions(rendererPointShadowTexture));\n let sampleUv = clamp(uvLayer.xy, vec2(0.0, 0.0), vec2(1.0, 1.0));\n let pixel = vec2<i32>(clamp(sampleUv * dims, vec2(0.0, 0.0), dims - vec2(1.0, 1.0)));\n let closestDepth = textureLoad(rendererPointShadowTexture, pixel, i32(round(uvLayer.z)), 0).r;\n let currentDepth = clamp(distanceToLight / max(range, 0.0001), 0.0, 1.0) - rendererPointShadowBiasForLight(lightIndex);\n let shadow = select(0.0, 1.0, currentDepth <= closestDepth);\n return mix(1.0, shadow, rendererPointShadowIntensityForLight(lightIndex));\n}\n\nfn rendererSamplePointShadowForLightWithNormal(lightIndex: u32, worldPosition: vec3<f32>, worldNormal: vec3<f32>) -> f32 {\n let params = rendererLights.pointShadowParams[lightIndex];\n let lightDirection = normalize(worldPosition - rendererPointLightPositionForLight(lightIndex));\n return rendererSamplePointShadowForLight(lightIndex, worldPosition + normalize(worldNormal + lightDirection) * params.w);\n}\n\nfn rendererSampleSpotShadowForLight(lightIndex: u32, worldPosition: vec3<f32>) -> f32 {\n if (lightIndex >= rendererSpotLightCount() || !rendererSpotShadowEnabledForLight(lightIndex)) {\n return 1.0;\n }\n let matrix = rendererSpotShadowMatrixForLight(lightIndex);\n let shadowClip = matrix * vec4(worldPosition, 1.0);\n if (shadowClip.w <= 0.0) {\n return 1.0;\n }\n let ndc = shadowClip.xyz / shadowClip.w;\n if (ndc.x < -1.0 || ndc.x > 1.0 || ndc.y < -1.0 || ndc.y > 1.0 || ndc.z < 0.0 || ndc.z > 1.0) {\n return 1.0;\n }\n let uv = ndc.xy * vec2(0.5, -0.5) + vec2(0.5, 0.5);\n let dims = vec2<f32>(textureDimensions(rendererSpotShadowTexture));\n let texel = 1.0 / max(dims, vec2(1.0, 1.0));\n let radius = max(rendererLights.spotShadowParams2[lightIndex].x, 1.0);\n let depth = ndc.z - rendererSpotShadowBiasForLight(lightIndex);\n var sum = 0.0;\n for (var y: i32 = -1; y <= 1; y = y + 1) {\n for (var x: i32 = -1; x <= 1; x = x + 1) {\n let offset = vec2<f32>(f32(x), f32(y)) * texel * radius;\n let sampleUv = clamp(uv + offset, vec2(0.0, 0.0), vec2(1.0, 1.0));\n let pixel = vec2<i32>(clamp(sampleUv * dims, vec2(0.0, 0.0), dims - vec2(1.0, 1.0)));\n let shadowDepth = textureLoad(rendererSpotShadowTexture, pixel, i32(lightIndex), 0);\n sum += select(0.0, 1.0, depth <= shadowDepth);\n }\n }\n return mix(1.0, sum / 9.0, rendererSpotShadowIntensityForLight(lightIndex));\n}\n\nfn rendererSampleSpotShadowForLightWithNormal(lightIndex: u32, worldPosition: vec3<f32>, worldNormal: vec3<f32>) -> f32 {\n let params = rendererLights.spotShadowParams[lightIndex];\n return rendererSampleSpotShadowForLight(lightIndex, worldPosition + normalize(worldNormal) * params.w);\n}\n\nfn rendererSampleDirectionalShadow(worldPosition: vec3<f32>) -> f32 {\n return rendererSampleDirectionalShadowForLight(0u, worldPosition);\n}\n\nfn rendererSampleDirectionalShadowWithNormal(worldPosition: vec3<f32>, worldNormal: vec3<f32>) -> f32 {\n return rendererSampleDirectionalShadowForLightWithNormal(0u, worldPosition, worldNormal);\n}\n\nfn rendererSamplePointShadow(worldPosition: vec3<f32>) -> f32 {\n return rendererSamplePointShadowForLight(0u, worldPosition);\n}\n\nfn rendererSamplePointShadowWithNormal(worldPosition: vec3<f32>, worldNormal: vec3<f32>) -> f32 {\n return rendererSamplePointShadowForLightWithNormal(0u, worldPosition, worldNormal);\n}\n\nfn rendererSampleSpotShadow(worldPosition: vec3<f32>) -> f32 {\n return rendererSampleSpotShadowForLight(0u, worldPosition);\n}\n\nfn rendererSampleSpotShadowWithNormal(worldPosition: vec3<f32>, worldNormal: vec3<f32>) -> f32 {\n return rendererSampleSpotShadowForLightWithNormal(0u, worldPosition, worldNormal);\n}\n":"\nfn rendererSampleDirectionalShadowForLight(lightIndex: u32, worldPosition: vec3<f32>) -> f32 {\n _ = lightIndex;\n _ = worldPosition;\n return 1.0;\n}\n\nfn rendererSampleDirectionalShadowForLightWithNormal(lightIndex: u32, worldPosition: vec3<f32>, worldNormal: vec3<f32>) -> f32 {\n _ = worldNormal;\n return rendererSampleDirectionalShadowForLight(lightIndex, worldPosition);\n}\n\nfn rendererSamplePointShadowForLight(lightIndex: u32, worldPosition: vec3<f32>) -> f32 {\n _ = lightIndex;\n _ = worldPosition;\n return 1.0;\n}\n\nfn rendererSamplePointShadowForLightWithNormal(lightIndex: u32, worldPosition: vec3<f32>, worldNormal: vec3<f32>) -> f32 {\n _ = worldNormal;\n return rendererSamplePointShadowForLight(lightIndex, worldPosition);\n}\n\nfn rendererSampleSpotShadowForLight(lightIndex: u32, worldPosition: vec3<f32>) -> f32 {\n _ = lightIndex;\n _ = worldPosition;\n return 1.0;\n}\n\nfn rendererSampleSpotShadowForLightWithNormal(lightIndex: u32, worldPosition: vec3<f32>, worldNormal: vec3<f32>) -> f32 {\n _ = worldNormal;\n return rendererSampleSpotShadowForLight(lightIndex, worldPosition);\n}\n\nfn rendererSampleDirectionalShadow(worldPosition: vec3<f32>) -> f32 {\n _ = worldPosition;\n return 1.0;\n}\n\nfn rendererSampleDirectionalShadowWithNormal(worldPosition: vec3<f32>, worldNormal: vec3<f32>) -> f32 {\n _ = worldPosition;\n _ = worldNormal;\n return 1.0;\n}\n\nfn rendererSamplePointShadow(worldPosition: vec3<f32>) -> f32 {\n _ = worldPosition;\n return 1.0;\n}\n\nfn rendererSamplePointShadowWithNormal(worldPosition: vec3<f32>, worldNormal: vec3<f32>) -> f32 {\n _ = worldPosition;\n _ = worldNormal;\n return 1.0;\n}\n\nfn rendererSampleSpotShadow(worldPosition: vec3<f32>) -> f32 {\n _ = worldPosition;\n return 1.0;\n}\n\nfn rendererSampleSpotShadowWithNormal(worldPosition: vec3<f32>, worldNormal: vec3<f32>) -> f32 {\n _ = worldPosition;\n _ = worldNormal;\n return 1.0;\n}\n";return`\nstruct RendererCameraUniforms {\n viewProj: mat4x4<f32>,\n cameraPosition: vec4<f32>,\n viewportAndTime: vec4<f32>,\n view: mat4x4<f32>,\n projection: mat4x4<f32>,\n nearFar: vec4<f32>,\n fogColor: vec4<f32>,\n fogParams: vec4<f32>,\n};\n\nstruct RendererLightUniforms {\n ambientColor: vec4<f32>,\n lightCounts: vec4<f32>,\n directionalDirections: array<vec4<f32>, 4>,\n directionalColorIntensities: array<vec4<f32>, 4>,\n directionalShadowParams: array<vec4<f32>, 4>,\n directionalShadowParams2: array<vec4<f32>, 4>,\n directionalShadowMatrices: array<mat4x4<f32>, 4>,\n pointPositionRanges: array<vec4<f32>, 4>,\n pointColorIntensities: array<vec4<f32>, 4>,\n pointShadowParams: array<vec4<f32>, 4>,\n pointShadowParams2: array<vec4<f32>, 4>,\n spotPositionRanges: array<vec4<f32>, 4>,\n spotDirectionCones: array<vec4<f32>, 4>,\n spotColorIntensities: array<vec4<f32>, 4>,\n spotShadowParams: array<vec4<f32>, 4>,\n spotShadowParams2: array<vec4<f32>, 4>,\n spotParams: array<vec4<f32>, 4>,\n spotShadowMatrices: array<mat4x4<f32>, 4>,\n csmCascadeRanges: array<vec4<f32>, 4>,\n hemisphereSkyColorIntensity: vec4<f32>,\n hemisphereGroundColorIntensity: vec4<f32>,\n hemisphereDirection: vec4<f32>,\n};\n\n${"instanced-direct"===r?"\n@group(0) @binding(0) var<uniform> rendererCamera: RendererCameraUniforms;\n@group(0) @binding(1) var<uniform> rendererLights: RendererLightUniforms;\n@group(0) @binding(2) var<storage, read> rendererInstanceMatrices: array<vec4<f32>>;\n@group(0) @binding(3) var<storage, read> rendererInstanceColors: array<vec4<f32>>;\n@group(0) @binding(4) var rendererShadowSampler: sampler_comparison;\n@group(0) @binding(5) var rendererDirectionalShadowTexture: texture_depth_2d_array;\n@group(0) @binding(6) var rendererLinearClampSampler: sampler;\n@group(0) @binding(7) var rendererPointShadowTexture: texture_2d_array<f32>;\n@group(0) @binding(8) var rendererSpotShadowTexture: texture_depth_2d_array;\n\nfn rendererBatchingId(instanceIndex: u32) -> u32 {\n return instanceIndex;\n}\n\nfn rendererInstanceModelMatrix(instanceIndex: u32) -> mat4x4<f32> {\n let base = instanceIndex * 4u;\n return mat4x4<f32>(\n rendererInstanceMatrices[base + 0u],\n rendererInstanceMatrices[base + 1u],\n rendererInstanceMatrices[base + 2u],\n rendererInstanceMatrices[base + 3u]\n );\n}\n\nfn rendererObjectColor(instanceIndex: u32) -> vec4<f32> {\n return rendererInstanceColors[instanceIndex];\n}\n":`\nstruct RendererInstanceData {\n model0: vec4<f32>,\n model1: vec4<f32>,\n model2: vec4<f32>,\n model3: vec4<f32>,\n color: vec4<f32>,\n batching: vec4<f32>,\n};\n\n@group(0) @binding(0) var<uniform> rendererCamera: RendererCameraUniforms;\n@group(0) @binding(1) var<uniform> rendererLights: RendererLightUniforms;\n@group(0) @binding(2) var<storage, read> rendererInstances: array<RendererInstanceData>;\n@group(0) @binding(3) var rendererShadowSampler: sampler_comparison;\n@group(0) @binding(4) var rendererDirectionalShadowTexture: texture_depth_2d_array;\n@group(0) @binding(5) var rendererLinearClampSampler: sampler;\n@group(0) @binding(6) var rendererPointShadowTexture: texture_2d_array<f32>;\n@group(0) @binding(7) var rendererSpotShadowTexture: texture_depth_2d_array;\n${o?"@group(0) @binding(8) var<storage, read> rendererVisibleInstanceIndices: array<u32>;":""}\n\nfn rendererResolveInstanceIndex(instanceIndex: u32) -> u32 {\n ${o?"return rendererVisibleInstanceIndices[instanceIndex];":"return instanceIndex;"}\n}\n\nfn rendererInstanceModelMatrix(instanceIndex: u32) -> mat4x4<f32> {\n let instance = rendererInstances[rendererResolveInstanceIndex(instanceIndex)];\n return mat4x4<f32>(instance.model0, instance.model1, instance.model2, instance.model3);\n}\n\nfn rendererObjectColor(instanceIndex: u32) -> vec4<f32> {\n return rendererInstances[rendererResolveInstanceIndex(instanceIndex)].color;\n}\n\nfn rendererBatchingId(instanceIndex: u32) -> u32 {\n return u32(round(rendererInstances[rendererResolveInstanceIndex(instanceIndex)].batching.x));\n}\n`}\n\nfn rendererInverseMat3(m: mat3x3<f32>) -> mat3x3<f32> {\n let a = m[0];\n let b = m[1];\n let c = m[2];\n let r0 = cross(b, c);\n let r1 = cross(c, a);\n let r2 = cross(a, b);\n let det = dot(r2, c);\n let safeDet = select(det, select(-1e-8, 1e-8, det >= 0.0), abs(det) < 1e-8);\n let invDet = 1.0 / safeDet;\n return transpose(mat3x3<f32>(r0 * invDet, r1 * invDet, r2 * invDet));\n}\n\nfn rendererInstanceNormalMatrix(instanceIndex: u32) -> mat3x3<f32> {\n let model = rendererInstanceModelMatrix(instanceIndex);\n let model3x3 = mat3x3<f32>(model[0].xyz, model[1].xyz, model[2].xyz);\n return transpose(rendererInverseMat3(model3x3));\n}\n\nfn rendererWorldPosition(localPosition: vec3<f32>, instanceIndex: u32) -> vec4<f32> {\n return rendererInstanceModelMatrix(instanceIndex) * vec4(localPosition, 1.0);\n}\n\nfn rendererClipPosition(localPosition: vec3<f32>, instanceIndex: u32) -> vec4<f32> {\n return rendererCamera.viewProj * rendererWorldPosition(localPosition, instanceIndex);\n}\n\nfn rendererWorldNormal(localNormal: vec3<f32>, instanceIndex: u32) -> vec3<f32> {\n return normalize(rendererInstanceNormalMatrix(instanceIndex) * localNormal);\n}\n\n${ur("rendererCamera")}\n\nfn rendererDirectionalLightDirection() -> vec3<f32> {\n return rendererDirectionalLightDirectionForLight(0u);\n}\n\nfn rendererDirectionalLightColor() -> vec3<f32> {\n return rendererDirectionalLightColorForLight(0u);\n}\n\nfn rendererPointLightPosition() -> vec3<f32> {\n return rendererPointLightPositionForLight(0u);\n}\n\nfn rendererPointLightRange() -> f32 {\n return rendererPointLightRangeForLight(0u);\n}\n\nfn rendererPointLightColor() -> vec3<f32> {\n return rendererPointLightColorForLight(0u);\n}\n\nfn rendererAmbientLight() -> vec3<f32> {\n return rendererLights.ambientColor.xyz * rendererLights.ambientColor.w;\n}\n\nfn rendererHemisphereLight(worldNormal: vec3<f32>) -> vec3<f32> {\n let directionLength = length(rendererLights.hemisphereDirection.xyz);\n if (directionLength <= 0.0) {\n return vec3<f32>(0.0);\n }\n let sky = rendererLights.hemisphereSkyColorIntensity;\n let ground = rendererLights.hemisphereGroundColorIntensity;\n let weight = dot(normalize(worldNormal), rendererLights.hemisphereDirection.xyz / directionLength) * 0.5 + 0.5;\n return mix(ground.xyz * ground.w, sky.xyz * sky.w, weight);\n}\n\nfn rendererIndirectDiffuse(worldNormal: vec3<f32>) -> vec3<f32> {\n return rendererAmbientLight() + rendererHemisphereLight(worldNormal);\n}\n\nfn rendererDirectionalLightCount() -> u32 {\n return u32(round(rendererLights.lightCounts.x));\n}\n\nfn rendererPointLightCount() -> u32 {\n return u32(round(rendererLights.lightCounts.y));\n}\n\nfn rendererSpotLightCount() -> u32 {\n return u32(round(rendererLights.lightCounts.z));\n}\n\nfn rendererCsmCascadeCount() -> u32 {\n return u32(round(rendererLights.lightCounts.w));\n}\n\nfn rendererCsmCascadeRangeForLight(lightIndex: u32) -> vec2<f32> {\n return rendererLights.csmCascadeRanges[lightIndex].xy;\n}\n\nfn rendererDirectionalLightDirectionForLight(lightIndex: u32) -> vec3<f32> {\n return normalize(-rendererLights.directionalDirections[lightIndex].xyz);\n}\n\nfn rendererDirectionalLightColorForLight(lightIndex: u32) -> vec3<f32> {\n let value = rendererLights.directionalColorIntensities[lightIndex];\n return value.xyz * value.w;\n}\n\nfn rendererPointLightPositionForLight(lightIndex: u32) -> vec3<f32> {\n return rendererLights.pointPositionRanges[lightIndex].xyz;\n}\n\nfn rendererPointLightRangeForLight(lightIndex: u32) -> f32 {\n return rendererLights.pointPositionRanges[lightIndex].w;\n}\n\nfn rendererPointLightColorForLight(lightIndex: u32) -> vec3<f32> {\n let value = rendererLights.pointColorIntensities[lightIndex];\n return value.xyz * value.w;\n}\n\nfn rendererSpotLightPositionForLight(lightIndex: u32) -> vec3<f32> {\n return rendererLights.spotPositionRanges[lightIndex].xyz;\n}\n\nfn rendererSpotLightRangeForLight(lightIndex: u32) -> f32 {\n return rendererLights.spotPositionRanges[lightIndex].w;\n}\n\nfn rendererSpotLightDirectionForLight(lightIndex: u32) -> vec3<f32> {\n // The packed value points from the light towards its target. Material\n // lighting evaluates the incident direction from the fragment back to the\n // light, matching rendererDirectionalLightDirectionForLight().\n return normalize(-rendererLights.spotDirectionCones[lightIndex].xyz);\n}\n\nfn rendererSpotLightConeCosForLight(lightIndex: u32) -> f32 {\n return rendererLights.spotDirectionCones[lightIndex].w;\n}\n\nfn rendererSpotLightPenumbraCosForLight(lightIndex: u32) -> f32 {\n return rendererLights.spotParams[lightIndex].y;\n}\n\nfn rendererSpotLightDecayForLight(lightIndex: u32) -> f32 {\n return rendererLights.spotParams[lightIndex].z;\n}\n\nfn rendererSpotLightColorForLight(lightIndex: u32) -> vec3<f32> {\n let value = rendererLights.spotColorIntensities[lightIndex];\n return value.xyz * value.w;\n}\n\n// These structs make the renderer's packed light buffer available to generic\n// graph nodes. The graph only depends on the semantic fields; this header can\n// later source them from Forward+ storage buffers without changing materials.\nstruct RendererDirectionalLight {\n direction: vec3<f32>,\n color: vec3<f32>,\n};\n\nfn rendererDirectionalLightForLight(lightIndex: u32) -> RendererDirectionalLight {\n return RendererDirectionalLight(\n rendererDirectionalLightDirectionForLight(lightIndex),\n rendererDirectionalLightColorForLight(lightIndex)\n );\n}\n\n// These records match three-shader-graph's established shadow structs. They\n// intentionally expose metadata only; sampling stays behind the renderer's\n// semantic shadow functions so graph code never depends on the atlas layout.\nstruct RendererDirectionalLightShadow {\n shadowBias: f32,\n shadowNormalBias: f32,\n shadowRadius: f32,\n shadowMapSize: vec2<f32>,\n};\n\nfn rendererDirectionalLightShadowForLight(lightIndex: u32) -> RendererDirectionalLightShadow {\n let params = rendererLights.directionalShadowParams[lightIndex];\n let params2 = rendererLights.directionalShadowParams2[lightIndex];\n return RendererDirectionalLightShadow(\n params.x,\n params.w,\n params2.x,\n vec2<f32>(params.z)\n );\n}\n\nstruct RendererPointLight {\n position: vec3<f32>,\n color: vec3<f32>,\n distance: f32,\n decay: f32,\n};\n\nfn rendererPointLightForLight(lightIndex: u32) -> RendererPointLight {\n return RendererPointLight(\n rendererPointLightPositionForLight(lightIndex),\n rendererPointLightColorForLight(lightIndex),\n rendererPointLightRangeForLight(lightIndex),\n 2.0\n );\n}\n\nstruct RendererPointLightShadow {\n shadowBias: f32,\n shadowNormalBias: f32,\n shadowRadius: f32,\n shadowMapSize: vec2<f32>,\n shadowCameraNear: f32,\n shadowCameraFar: f32,\n};\n\nfn rendererPointLightShadowForLight(lightIndex: u32) -> RendererPointLightShadow {\n let params = rendererLights.pointShadowParams[lightIndex];\n let params2 = rendererLights.pointShadowParams2[lightIndex];\n return RendererPointLightShadow(\n params.x,\n params.w,\n params2.x,\n vec2<f32>(params.z),\n params2.z,\n params2.w\n );\n}\n\nstruct RendererSpotLight {\n position: vec3<f32>,\n direction: vec3<f32>,\n color: vec3<f32>,\n distance: f32,\n decay: f32,\n coneCos: f32,\n penumbraCos: f32,\n};\n\nfn rendererSpotLightForLight(lightIndex: u32) -> RendererSpotLight {\n return RendererSpotLight(\n rendererSpotLightPositionForLight(lightIndex),\n rendererSpotLightDirectionForLight(lightIndex),\n rendererSpotLightColorForLight(lightIndex),\n rendererSpotLightRangeForLight(lightIndex),\n rendererSpotLightDecayForLight(lightIndex),\n rendererSpotLightConeCosForLight(lightIndex),\n rendererSpotLightPenumbraCosForLight(lightIndex)\n );\n}\n\nstruct RendererSpotLightShadow {\n shadowBias: f32,\n shadowNormalBias: f32,\n shadowRadius: f32,\n shadowMapSize: vec2<f32>,\n};\n\nfn rendererSpotLightShadowForLight(lightIndex: u32) -> RendererSpotLightShadow {\n let params = rendererLights.spotShadowParams[lightIndex];\n let params2 = rendererLights.spotShadowParams2[lightIndex];\n return RendererSpotLightShadow(\n params.x,\n params.w,\n params2.x,\n vec2<f32>(params.z)\n );\n}\n\nfn rendererDirectionalShadowMatrixForLight(lightIndex: u32) -> mat4x4<f32> {\n return rendererLights.directionalShadowMatrices[lightIndex];\n}\n\nfn rendererDirectionalShadowMatrix() -> mat4x4<f32> {\n return rendererDirectionalShadowMatrixForLight(0u);\n}\n\nfn rendererDirectionalShadowBias() -> f32 {\n return rendererDirectionalShadowBiasForLight(0u);\n}\n\nfn rendererDirectionalShadowBiasForLight(lightIndex: u32) -> f32 {\n return rendererLights.directionalShadowParams[lightIndex].x;\n}\n\nfn rendererDirectionalShadowEnabled() -> bool {\n return rendererDirectionalShadowEnabledForLight(0u);\n}\n\nfn rendererDirectionalShadowEnabledForLight(lightIndex: u32) -> bool {\n return rendererLights.directionalShadowParams[lightIndex].y >= 0.5;\n}\n\nfn rendererDirectionalShadowIntensityForLight(lightIndex: u32) -> f32 {\n return rendererLights.directionalShadowParams2[lightIndex].y;\n}\n\nfn rendererDirectionalShadowMapSize() -> f32 {\n return rendererLights.directionalShadowParams[0].z;\n}\n\nfn rendererPointShadowBias() -> f32 {\n return rendererPointShadowBiasForLight(0u);\n}\n\nfn rendererPointShadowBiasForLight(lightIndex: u32) -> f32 {\n return rendererLights.pointShadowParams[lightIndex].x;\n}\n\nfn rendererPointShadowEnabled() -> bool {\n return rendererPointShadowEnabledForLight(0u);\n}\n\nfn rendererPointShadowEnabledForLight(lightIndex: u32) -> bool {\n return rendererLights.pointShadowParams[lightIndex].y >= 0.5;\n}\n\nfn rendererPointShadowIntensityForLight(lightIndex: u32) -> f32 {\n return rendererLights.pointShadowParams2[lightIndex].y;\n}\n\nfn rendererSpotShadowMatrixForLight(lightIndex: u32) -> mat4x4<f32> {\n return rendererLights.spotShadowMatrices[lightIndex];\n}\n\nfn rendererSpotShadowBiasForLight(lightIndex: u32) -> f32 {\n return rendererLights.spotShadowParams[lightIndex].x;\n}\n\nfn rendererSpotShadowEnabledForLight(lightIndex: u32) -> bool {\n return rendererLights.spotShadowParams[lightIndex].y >= 0.5;\n}\n\nfn rendererSpotShadowIntensityForLight(lightIndex: u32) -> f32 {\n return rendererLights.spotShadowParams2[lightIndex].y;\n}\n\n${l}\n${dr(i)}\n${a}\n${s}\n`}function pr(e,t,r,n="packed",i=!1){const a="camera"===t?`\nstruct RendererCameraUniforms {\n viewProj: mat4x4<f32>,\n cameraPosition: vec4<f32>,\n viewportAndTime: vec4<f32>,\n view: mat4x4<f32>,\n projection: mat4x4<f32>,\n nearFar: vec4<f32>,\n fogColor: vec4<f32>,\n fogParams: vec4<f32>,\n};\n\n@group(0) @binding(0) var<uniform> rendererCamera: RendererCameraUniforms;\n@group(0) @binding(1) var<uniform> rendererLights: array<vec4<f32>, 11>;\n${"instanced-direct"===n?"@group(0) @binding(2) var<storage, read> rendererInstanceMatrices: array<vec4<f32>>;\n@group(0) @binding(3) var<storage, read> rendererInstanceColors: array<vec4<f32>>;":"@group(0) @binding(2) var<storage, read> rendererInstances: array<RendererInstanceData>;"}\n\nfn rendererClipPosition(localPosition: vec3<f32>, instanceIndex: u32) -> vec4<f32> {\n return rendererCamera.viewProj * rendererWorldPosition(localPosition, instanceIndex);\n}\n`:`\nstruct ShadowCameraUniforms {\n viewProj: mat4x4<f32>,\n lightPositionRange: vec4<f32>,\n view: mat4x4<f32>,\n projection: mat4x4<f32>,\n cameraPosition: vec4<f32>,\n nearFar: vec4<f32>,\n timeAndPadding: vec4<f32>,\n};\n\n@group(0) @binding(0) var<uniform> shadowCamera: ShadowCameraUniforms;\n${"instanced-direct"===n?"@group(0) @binding(1) var<storage, read> rendererInstanceMatrices: array<vec4<f32>>;\n@group(0) @binding(2) var<storage, read> rendererInstanceColors: array<vec4<f32>>;":"@group(0) @binding(1) var<storage, read> rendererInstances: array<RendererInstanceData>;"}\n\nfn rendererClipPosition(localPosition: vec3<f32>, instanceIndex: u32) -> vec4<f32> {\n return shadowCamera.viewProj * rendererWorldPosition(localPosition, instanceIndex);\n}\n`,s=cr(e,r);return`\n${a}\n\n${"instanced-direct"===n?"\nfn rendererInstanceModelMatrix(instanceIndex: u32) -> mat4x4<f32> {\n let base = instanceIndex * 4u;\n return mat4x4<f32>(\n rendererInstanceMatrices[base + 0u],\n rendererInstanceMatrices[base + 1u],\n rendererInstanceMatrices[base + 2u],\n rendererInstanceMatrices[base + 3u]\n );\n}\n\nfn rendererObjectColor(instanceIndex: u32) -> vec4<f32> {\n return rendererInstanceColors[instanceIndex];\n}\n\nfn rendererBatchingId(instanceIndex: u32) -> u32 {\n return instanceIndex;\n}\n":"\nstruct RendererInstanceData {\n model0: vec4<f32>,\n model1: vec4<f32>,\n model2: vec4<f32>,\n model3: vec4<f32>,\n color: vec4<f32>,\n batching: vec4<f32>,\n};\n\nfn rendererInstanceModelMatrix(instanceIndex: u32) -> mat4x4<f32> {\n let instance = rendererInstances[instanceIndex];\n return mat4x4<f32>(instance.model0, instance.model1, instance.model2, instance.model3);\n}\n\nfn rendererObjectColor(instanceIndex: u32) -> vec4<f32> {\n return rendererInstances[instanceIndex].color;\n}\n\nfn rendererBatchingId(instanceIndex: u32) -> u32 {\n return u32(round(rendererInstances[instanceIndex].batching.x));\n}\n"}\n\nfn rendererInverseMat3(m: mat3x3<f32>) -> mat3x3<f32> {\n let a = m[0];\n let b = m[1];\n let c = m[2];\n let r0 = cross(b, c);\n let r1 = cross(c, a);\n let r2 = cross(a, b);\n let det = dot(r2, c);\n let safeDet = select(det, select(-1e-8, 1e-8, det >= 0.0), abs(det) < 1e-8);\n let invDet = 1.0 / safeDet;\n return transpose(mat3x3<f32>(r0 * invDet, r1 * invDet, r2 * invDet));\n}\n\nfn rendererInstanceNormalMatrix(instanceIndex: u32) -> mat3x3<f32> {\n let model = rendererInstanceModelMatrix(instanceIndex);\n let model3x3 = mat3x3<f32>(model[0].xyz, model[1].xyz, model[2].xyz);\n return transpose(rendererInverseMat3(model3x3));\n}\n\nfn rendererWorldPosition(localPosition: vec3<f32>, instanceIndex: u32) -> vec4<f32> {\n return rendererInstanceModelMatrix(instanceIndex) * vec4(localPosition, 1.0);\n}\n\nfn rendererWorldNormal(localNormal: vec3<f32>, instanceIndex: u32) -> vec3<f32> {\n return normalize(rendererInstanceNormalMatrix(instanceIndex) * localNormal);\n}\n\n${ur("camera"===t?"rendererCamera":"shadowCamera")}\n${dr(i)}\n${s}\n`}var fr=class{constructor(e,t,r={}){this.name=e,this.callback=t,this.reads=r.reads,this.writes=r.writes,this.dependsOn=r.dependsOn}name;callback;reads;writes;dependsOn;execute(e){this.callback(e)}};import{AlwaysCompare as mr,BufferAttribute as gr,EqualCompare as xr,GreaterCompare as vr,GreaterEqualCompare as wr,LessCompare as br,LessEqualCompare as yr,MirroredRepeatWrapping as Sr,NearestFilter as Cr,NearestMipmapLinearFilter as Pr,NearestMipmapNearestFilter as Mr,NeverCompare as Br,NotEqualCompare as Dr,Object3D as Tr,RepeatWrapping as Ir,Vector3 as Gr}from"three";import{Matrix4 as Rr,Sphere as Lr,Vector3 as zr}from"three";var Ur=24,Vr=12,Ar=new Float32Array(Ur),Fr=new Float32Array([1,1,1,1]),Er="rgba16float",kr=(new Rr).set(1,0,0,0,0,1,0,0,0,0,.5,.5,0,0,0,1),Or=[new zr(0,-1,0),new zr(0,-1,0),new zr(0,0,1),new zr(0,0,-1),new zr(0,-1,0),new zr(0,-1,0)],$r=[new zr(1,0,0),new zr(-1,0,0),new zr(0,1,0),new zr(0,-1,0),new zr(0,0,1),new zr(0,0,-1)],jr=[{name:"position",shaderLocation:0,format:"float32x3"}],Nr=[{name:"position",shaderLocation:0,format:"float32x3"},{name:"skinIndex",shaderLocation:1,format:"uint32x4"},{name:"skinWeight",shaderLocation:2,format:"float32x4"}],Wr=new Rr,_r=new Rr,qr=(new Rr,new Rr,new Lr),Hr=new zr,Kr=new zr,Zr=new zr,Yr=(new zr,new zr,new zr,new zr,new WeakMap),Xr=1;function Jr(e){return e?"version"in e?e.version:e.data.version:0}function Qr(e){const t=Object.keys(e.attributes).sort().map(t=>{const r=e.getAttribute(t);return[t,Jr(r),r?.itemSize??0,r?.count??0].join(":")}).join("|"),r=e.index?.version??0,n=e.groups.map(e=>`${e.start}:${e.count}:${e.materialIndex??0}`).join("|");return[t,r,e.drawRange.start,e.drawRange.count,n].join(";")}function en(e){switch(e){case"float32":case"uint32":case"sint32":return 1;case"float32x2":case"uint32x2":case"sint32x2":return 2;case"float32x3":case"uint32x3":case"sint32x3":return 3;default:return 4}}function tn(e){return 4*en(e)}function rn(e,t){switch(t){case"uint32":return new Uint32Array(e);case"sint32":return new Int32Array(e);default:return new Float32Array(e)}}function nn(e,t,r,n){switch(r){case"uint32":e[t]=Math.max(0,Math.round(n));break;case"sint32":e[t]=Math.trunc(n);break;default:e[t]=n}}function an(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1)if(e[r]!==t[r])return!1;return!0}function sn(e,t,r,n){const i=Math.max(4,t.byteLength),a=e.createBuffer({label:n,size:4*Math.ceil(i/4),usage:r,mappedAtCreation:!0});return new Uint8Array(a.getMappedRange()).set(new Uint8Array(t.buffer,t.byteOffset,t.byteLength)),a.unmap(),a}function on(e){switch(e){case"vertex":return GPUShaderStage.VERTEX;case"vertex-fragment":return GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT;default:return GPUShaderStage.FRAGMENT}}function ln(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1)if(e[r]!==t[r])return!1;return!0}function cn(e,t){if(!e)return!1;if(e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1)if(e[r]!==t[r])return!1;return!0}function un(e,t,r){try{return e.beginComputePass({timestampWrites:{querySet:t,...r}}).end(),!0}catch{return!1}}function dn(e,t,r,n){const i=new Float32Array(t*r);if(!e){for(let e=0;e<t;e+=1)i.set(n,e*r);return i}for(let a=0;a<t;a+=1){for(let t=0;t<r;t+=1)t<e.itemSize?i[a*r+t]=e.getComponent(a,t):i[a*r+t]=n[t]??0;3===e.itemSize&&4===r&&(i[a*r+3]=n[3]??1)}return i}function hn(e,t,r,n,i=0){const a=en(r),s=(o=r).startsWith("uint32")?"uint32":o.startsWith("sint32")?"sint32":"float32";var o;if(!e)return function(e,t,r,n,i,a){const s=rn(r*n,a);for(let o=0;o<r;o+=1){const r=o*t,l=o*n;for(let o=0;o<n;o+=1)nn(s,l+o,a,e&&o<t?e[r+o]??i[o]??0:i[o]??0)}return s}(void 0,0,t,a,n,s);if(0===i&&e instanceof gr&&!e.normalized&&e.itemSize===a&&e.count===t){const t=e.array;if("float32"===s&&t instanceof Float32Array||"uint32"===s&&t instanceof Uint32Array||"sint32"===s&&t instanceof Int32Array)return t}const l=rn(t*a,s);for(let r=0;r<t;r+=1){const t=r*a,o=r-i,c=o>=0&&o<e.count;for(let r=0;r<a;r+=1){nn(l,t+r,s,c&&r<e.itemSize?e.getComponent(o,r):n[r]??0)}}return l}function pn(e,t,r,n){return Number.isFinite(n)&&n>0?n:t?Math.max(0,(e.index?.count??0)-r):Math.max(0,e.getAttribute("position").count-r)}function fn(e,t){return{start:e.drawRange.start,count:pn(e,t,e.drawRange.start,e.drawRange.count)}}function mn(e){return e===Ir?"repeat":e===Sr?"mirror-repeat":"clamp-to-edge"}function gn(e){return e===Cr||e===Mr||e===Pr?"nearest":"linear"}function xn(e){return e instanceof HTMLCanvasElement||e instanceof HTMLImageElement||e instanceof ImageBitmap||e instanceof OffscreenCanvas||e instanceof HTMLVideoElement?e:null}function vn(e){return e}function wn(e,t,r,n,i,a,s){return e.appendMatrixAndColorValues(t,r,n,i,a,s)}function bn(e,t,r,n,i,a,s){return e.appendMatrixAndColorValues(t.elements,r,n,i,a,s)}function yn(e,t,r){const n=e.elements;for(let e=0;e<16;e+=1)n[e]=t[r+e]??0;return e}function Sn(e){const t=Yr.get(e);if(void 0!==t)return t;const r=Xr+=1;return Yr.set(e,r),r}function Cn(e,t,r,n,i,a){return[Sn(e),Sn(t),r?1:0,n,i,a?Sn(a):0].join(":")}function Pn(e,t,r,n,i,a){let s=2166136261;return s=Tn(s,e),s=Tn(s,t),s=Tn(s,r?1:0),s=Tn(s,n),s=Tn(s,i),s=Tn(s,a),s}function Mn(e,t){return e.renderOrder!==t.renderOrder?e.renderOrder-t.renderOrder:(r=e.sortMaterialId,n=e.sortGeometryId,i=e.indexed,a=e.start,s=e.count,o=e.sortCustomDepthMaterialId,l=t.sortMaterialId,c=t.sortGeometryId,u=t.indexed,d=t.start,h=t.count,p=t.sortCustomDepthMaterialId,r!==l?r-l:n!==c?n-c:i!==u?i?-1:1:a!==d?a-d:s!==h?s-h:o-p);var r,n,i,a,s,o,l,c,u,d,h,p}function Bn(e,t){return e.renderOrder!==t.renderOrder?e.renderOrder-t.renderOrder:0!==e.transparentSortGroup&&e.transparentSortGroup===t.transparentSortGroup&&e.transparentSortOrder!==t.transparentSortOrder?e.transparentSortOrder-t.transparentSortOrder:e.sortDepth!==t.sortDepth?t.sortDepth-e.sortDepth:Mn(e,t)}function Dn(e){for(let t=0;t<e.length;t+=1)if(e[t].hasRenderCallbacks)return!0;return!1}function Tn(e,t){let r=Math.imul((e^t)>>>0,16777619);return r^=r>>>13,r>>>0}function In(e,t){return e.renderOrder===t.renderOrder&&!e.hasRenderCallbacks&&!t.hasRenderCallbacks&&e.castShadow===t.castShadow&&e.receiveShadow===t.receiveShadow&&e.usesBatching===t.usesBatching&&e.sortMaterialId===t.sortMaterialId&&e.sortGeometryId===t.sortGeometryId&&e.indexed===t.indexed&&e.start===t.start&&e.count===t.count&&e.sortCustomDepthMaterialId===t.sortCustomDepthMaterialId}function Gn(e,t){return e.renderOrder===t.renderOrder&&!e.hasRenderCallbacks&&!t.hasRenderCallbacks&&e.castShadow===t.castShadow&&e.receiveShadow===t.receiveShadow&&e.usesBatching===t.usesBatching&&e.sortMaterialId===t.sortMaterialId&&e.sortGeometryId===t.sortGeometryId&&e.indexed===t.indexed&&e.start===t.start&&e.count===t.count&&e.sortCustomDepthMaterialId===t.sortCustomDepthMaterialId}function Rn(e,t){for(let r=0;r<16;r+=1)t[r]=e[r]??0}function Ln(e,t){for(let r=0;r<16;r+=1)if((e[r]??0)!==(t[r]??0))return!1;return!0}function zn(e){return 1===(e[0]??0)&&0===(e[1]??0)&&0===(e[2]??0)&&0===(e[3]??0)&&0===(e[4]??0)&&1===(e[5]??0)&&0===(e[6]??0)&&0===(e[7]??0)&&0===(e[8]??0)&&0===(e[9]??0)&&1===(e[10]??0)&&0===(e[11]??0)&&0===(e[12]??0)&&0===(e[13]??0)&&0===(e[14]??0)&&1===(e[15]??0)}function Un(e,t,r,n){r.x<e.x&&(e.x=r.x),r.y<e.y&&(e.y=r.y),r.z<e.z&&(e.z=r.z),n.x>t.x&&(t.x=n.x),n.y>t.y&&(t.y=n.y),n.z>t.z&&(t.z=n.z)}function Vn(e,t){return t.multiplyMatrices(_r.multiplyMatrices(kr,e.projectionMatrix),e.matrixWorldInverse)}function An(e,t,r,n,i,a){const s=Math.hypot(r,n,i)||1;e[t+0]=r/s,e[t+1]=n/s,e[t+2]=i/s,e[t+3]=a/s}function Fn(e){return null===e.boundingSphere&&e.computeBoundingSphere(),e.boundingSphere?{center:e.boundingSphere.center.clone(),radius:e.boundingSphere.radius}:{center:new Gr,radius:1}}function En(e){const t=e.elements,r=Math.hypot(t[0],t[1],t[2]),n=Math.hypot(t[4],t[5],t[6]),i=Math.hypot(t[8],t[9],t[10]);return Math.max(r,n,i,1e-5)}function kn(e,t,r,n){const i=r.x-n,a=r.y-n,s=r.z-n,o=r.x+n,l=r.y+n,c=r.z+n;i<e.x&&(e.x=i),a<e.y&&(e.y=a),s<e.z&&(e.z=s),o>t.x&&(t.x=o),l>t.y&&(t.y=l),c>t.z&&(t.z=c)}function On(e){return Math.floor(Math.max(0,e.count)/3)*Math.max(0,e.instanceCount)}function $n(e){const t=e??1;if(!Number.isInteger(t)||t<1)throw new Error(`Renderer sampleCount must be a positive integer. Received: ${e}`);return t}function jn(e){const t=e.customDepthMaterial;return t&&Ot(t)?t:null}function Nn(e,t){e.latestFrameProfile=qn(t.profile),(t.pendingGpuRead||t.pendingVisibilityRead)&&Promise.all([t.pendingGpuRead?Wn(t.profile,t.pendingGpuRead):Promise.resolve(),t.pendingVisibilityRead?_n(t.profile,t.pendingVisibilityRead):Promise.resolve()]).then(()=>{const r=qn(t.profile);e.latestFrameProfile=r,e.latestCompletedFrameProfile=r})}async function Wn(e,t){try{await t.readBuffer.mapAsync(GPUMapMode.READ);const r=t.readBuffer.getMappedRange(),n=new BigUint64Array(r.slice(0));let i=0;const a=t.profile.passes.map((e,t)=>{const r=Number(n[2*t]??0n),a=Number(n[2*t+1]??0n),s=Math.max(0,a-r)/1e6;return i+=s,{...e,gpuTimeMs:s}});e.gpuTimeMs=i,e.gpuProfilingReason=null,e.passes=a}catch{e.timestampQueryActive=!1,e.gpuTimeMs=null,e.gpuProfilingReason="timestamp readback failed after submission",e.passes=e.passes.map(e=>({...e,gpuTimeMs:null}))}finally{"mapped"===t.readBuffer.mapState&&t.readBuffer.unmap(),t.querySet.destroy(),t.resolveBuffer.destroy(),t.readBuffer.destroy()}}async function _n(e,t){try{await t.readBuffer.mapAsync(GPUMapMode.READ);const r=new Uint32Array(t.readBuffer.getMappedRange());let n=0,i=0,a=0,s=0;for(const e of t.regions){let t=0;const o=e.byteOffset/Uint32Array.BYTES_PER_ELEMENT;for(let n=0;n<e.drawCount;n+=1)t+=r[o+5*n+1]??0;"dynamic"===e.kind?(n+=e.totalInstances,i+=t):(a+=e.totalInstances,s+=t)}const o=n+a,l=i+s;e.visibility={totalInstances:o,visibleInstances:l,culledInstances:Math.max(0,o-l),dynamicTotalInstances:n,dynamicVisibleInstances:i,staticTotalInstances:a,staticVisibleInstances:s}}catch{e.visibility=null}finally{"mapped"===t.readBuffer.mapState&&t.readBuffer.unmap(),t.readBuffer.destroy()}}function qn(e){return{...e,cpuPhases:{...e.cpuPhases},passes:e.passes.map(e=>({...e})),visibility:e.visibility?{...e.visibility}:null}}function Hn(e){return e.usesBatching}function Kn(e){return!e.wireframe&&e.material.primitiveTopology.startsWith("triangle")}function Zn(e,t){return"pointShadow"===t?null!==e.material.pointShadowVertexShader&&null!==e.material.pointShadowFragmentShader:null!==e.material.depthVertexShader||Hn(e)}function Yn(e,t){if(!this.state.visibilityKernel||!this.state.drawMetadataResource||0===this.state.drawMetadataResource.count)return;const r=e.beginComputePass({label:"renderer-visibility-pass"});r.setPipeline(this.state.visibilityKernel.pipeline),r.setBindGroup(0,t),r.dispatchWorkgroups(Math.ceil(this.state.drawMetadataResource.count/64)),r.end()}function Xn(e,t){if(this.state.staticVisibilityClearKernel&&this.state.staticVisibilityCullKernel&&this.state.staticVisibilityIndirectBuildKernel&&this.getHiZOcclusionCullingActive())for(const r of this.staticDrawSets){if(!r.publicSet.enabled||0===r.drawMetadataResource.count)continue;if("postpass"===t&&r.lastPreVisibilityFrameToken!==this.staticFrameToken)continue;if(!this.state.device)continue;const n="prepass"===t?r.visibilityParamsUpload:r.postVisibilityParamsUpload,i="prepass"===t?r.visibilityParamsBuffer:r.postVisibilityParamsBuffer;n[1]=this.state.hizMipCount,n[3]="prepass"===t?this.state.temporalHiZHistoryValid?3:0:5,this.state.device.queue.writeBuffer(i,0,vn(n),0,4);const a=this.getOrCreateStaticVisibilityBindGroup(r,t);if(!a)continue;if("prepass"!==t||r.visibilityClearBindGroup&&r.visibilityIndirectBuildBindGroup&&r.postVisibilityIndirectBuildBindGroup||(r.visibilityClearBindGroup=this.state.staticVisibilityClearKernel.createBindGroup(this.state.device,[{binding:0,resource:{buffer:r.visibilityParamsBuffer}},{binding:1,resource:{buffer:r.instanceVisibilityResource.visibleCountsBuffer}},{binding:2,resource:{buffer:r.instanceVisibilityResource.postVisibleCountsBuffer}},{binding:3,resource:{buffer:r.instanceVisibilityResource.visibleInstanceMaskBuffer}}],`${r.label}-visibility-clear-bind-group`),r.visibilityIndirectBuildBindGroup=this.state.staticVisibilityIndirectBuildKernel.createBindGroup(this.state.device,[{binding:0,resource:{buffer:r.visibilityParamsBuffer}},{binding:1,resource:{buffer:r.instanceVisibilityResource.visibleCountsBuffer}},{binding:2,resource:{buffer:r.instanceVisibilityResource.postVisibleCountsBuffer}},{binding:3,resource:{buffer:r.drawMetadataResource.indirectBuffer}},{binding:4,resource:{buffer:r.drawMetadataResource.postIndirectBuffer}}],`${r.label}-visibility-indirect-build-bind-group`),r.postVisibilityIndirectBuildBindGroup=this.state.staticVisibilityIndirectBuildKernel.createBindGroup(this.state.device,[{binding:0,resource:{buffer:r.postVisibilityParamsBuffer}},{binding:1,resource:{buffer:r.instanceVisibilityResource.visibleCountsBuffer}},{binding:2,resource:{buffer:r.instanceVisibilityResource.postVisibleCountsBuffer}},{binding:3,resource:{buffer:r.drawMetadataResource.indirectBuffer}},{binding:4,resource:{buffer:r.drawMetadataResource.postIndirectBuffer}}],`${r.label}-post-visibility-indirect-build-bind-group`)),"prepass"===t){const t=e.beginComputePass({label:`${r.label}-temporal-visibility-clear-pass`});t.setPipeline(this.state.staticVisibilityClearKernel.pipeline),t.setBindGroup(0,r.visibilityClearBindGroup),t.dispatchWorkgroups(Math.ceil(Math.max(r.drawMetadataResource.count,r.instanceVisibilityResource.instanceCount)/64)),t.end()}const s=e.beginComputePass({label:`${r.label}-temporal-visibility-${t}-cull-pass`});s.setPipeline(this.state.staticVisibilityCullKernel.pipeline),s.setBindGroup(0,a),s.dispatchWorkgroups(Math.ceil(r.instanceVisibilityResource.instanceCount/64)),s.end();const o=e.beginComputePass({label:`${r.label}-temporal-visibility-${t}-indirect-build-pass`});o.setPipeline(this.state.staticVisibilityIndirectBuildKernel.pipeline),o.setBindGroup(0,"prepass"===t?r.visibilityIndirectBuildBindGroup:r.postVisibilityIndirectBuildBindGroup),o.dispatchWorkgroups(Math.ceil(r.drawMetadataResource.count/64)),o.end(),"prepass"===t?r.lastPreVisibilityFrameToken=this.staticFrameToken:r.lastVisibilityFrameToken=this.staticFrameToken}}function Jn(e,t){if(!(this.state.device&&this.state.staticVisibilityCullKernel&&this.state.hizTexture&&this.state.temporalVisibilityBuffer&&this.state.nearestClampSampler))return null;const r="prepass"===t?e.visibilityBindGroup:e.postVisibilityBindGroup;if(r&&e.visibilityBindGroupHizVersion===this.hizResourceVersion)return r;const n=this.state.staticVisibilityCullKernel.createBindGroup(this.state.device,[{binding:0,resource:{buffer:this.state.temporalVisibilityBuffer}},{binding:1,resource:{buffer:"prepass"===t?e.visibilityParamsBuffer:e.postVisibilityParamsBuffer}},{binding:2,resource:this.state.nearestClampSampler},{binding:3,resource:this.state.hizTexture.createView()},{binding:4,resource:{buffer:e.instanceVisibilityResource.instanceMetadataBuffer}},{binding:5,resource:{buffer:e.drawMetadataResource.metadataBuffer}},{binding:6,resource:{buffer:e.instanceVisibilityResource.visibleCountsBuffer}},{binding:7,resource:{buffer:e.instanceVisibilityResource.visibleInstanceIndicesBuffer}},{binding:8,resource:{buffer:e.instanceVisibilityResource.visibleInstanceMaskBuffer}},{binding:9,resource:{buffer:e.instanceVisibilityResource.postVisibleCountsBuffer}}],`${e.label}-temporal-visibility-${t}-bind-group`);return"prepass"===t?e.visibilityBindGroup=n:e.postVisibilityBindGroup=n,e.visibilityBindGroupHizVersion=this.hizResourceVersion,n}function Qn(e,t,r,n){if(!this.state.shadowDepthPipeline||0===this.state.directionalShadowLayerViews.length)return void this.clearDirectionalShadow(e);let i=!1;for(let t=0;t<r.lights.directionals.length;t+=1){const a=r.lights.directionals[t],s=this.state.directionalShadowLayerViews[t];if(!a.castShadow||!s)continue;i=!0;const o=this.directionalShadowCameras[t];o.left=a.shadowCameraLeft,o.right=a.shadowCameraRight,o.top=a.shadowCameraTop,o.bottom=a.shadowCameraBottom,o.near=a.shadowCameraNear,o.far=a.shadowCameraFar,o.position.copy(a.position),o.lookAt(a.target),o.updateMatrixWorld(!0),o.updateProjectionMatrix();const l=this.getShadowCameraBuffer(t);this.writeShadowCameraBuffer(Vn(o,this.shadowViewProjScratch),0,0,0,1,l,o);const c=this.getSharedShadowBindGroupForCameraBuffer(l),u=e.beginRenderPass({label:`renderer-directional-shadow-pass-${t}`,colorAttachments:[],depthStencilAttachment:{view:s,depthClearValue:1,depthLoadOp:"clear",depthStoreOp:"store"}});u.setPipeline(this.state.shadowDepthPipeline),u.setBindGroup(0,c),this.drawDepthLike(u,r.gpuOpaqueDraws,n,{fallbackPipeline:this.state.shadowDepthPipeline,fallbackPipelineDirect:this.state.shadowDepthPipelineDirect,fallbackSkinnedPipeline:this.state.skinnedShadowDepthPipeline,fallbackBindGroup:c,shadowCameraBuffer:l,passKind:"directionalShadow",customDepthMode:"use"}),this.drawDepthLike(u,r.directOpaqueDraws,n,{fallbackPipeline:this.state.shadowDepthPipeline,fallbackPipelineDirect:this.state.shadowDepthPipelineDirect,fallbackSkinnedPipeline:this.state.skinnedShadowDepthPipeline,fallbackBindGroup:c,shadowCameraBuffer:l,passKind:"directionalShadow",customDepthMode:"use"});for(const e of this.staticDrawSets)e.publicSet.enabled&&0!==e.draws.length&&(this.renderBundleScratch[0]=li.call(this,e,c,l,"directionalShadow",this.state.shadowDepthPipeline,this.state.shadowDepthPipelineDirect),u.executeBundles(this.renderBundleScratch),this.recordStaticDrawStats(e,n));u.end()}i||this.clearDirectionalShadow(e)}function ei(e,t,r,n){if(!r.lights.points.some(e=>e.castShadow))return;if(!this.state.pointShadowPipeline||!this.state.pointShadowFaceViews.length||!this.state.pointShadowDepthFaceViews.length)return void this.clearPointShadow(e);let i=!1;for(let t=0;t<r.lights.points.length;t+=1){const a=r.lights.points[t];if(a.castShadow){i=!0;for(let i=0;i<6;i+=1){const s=6*t+i,o=this.pointShadowCameras[t][i];o.near=a.shadowCameraNear,o.far=a.shadowCameraFar,o.position.copy(a.position),Hr.copy(a.position).add($r[i]),o.up.copy(Or[i]),o.lookAt(Hr),o.updateMatrixWorld(!0),o.updateProjectionMatrix();const l=this.getShadowCameraBuffer(4+s);this.writeShadowCameraBuffer(Vn(o,this.shadowViewProjScratch),a.position.x,a.position.y,a.position.z,a.range,l,o);const c=this.getSharedShadowBindGroupForCameraBuffer(l),u=e.beginRenderPass({label:`renderer-point-shadow-pass-${t}-${i}`,colorAttachments:[{view:this.state.pointShadowFaceViews[s],clearValue:{r:1,g:1,b:1,a:1},loadOp:"clear",storeOp:"store"}],depthStencilAttachment:{view:this.state.pointShadowDepthFaceViews[s],depthClearValue:1,depthLoadOp:"clear",depthStoreOp:"store"}});u.setPipeline(this.state.pointShadowPipeline),u.setBindGroup(0,c),this.drawDepthLike(u,r.gpuOpaqueDraws,n,{fallbackPipeline:this.state.pointShadowPipeline,fallbackPipelineDirect:this.state.pointShadowPipelineDirect,fallbackSkinnedPipeline:this.state.skinnedPointShadowPipeline,fallbackBindGroup:c,shadowCameraBuffer:l,passKind:"pointShadow",customDepthMode:"use"}),this.drawDepthLike(u,r.directOpaqueDraws,n,{fallbackPipeline:this.state.pointShadowPipeline,fallbackPipelineDirect:this.state.pointShadowPipelineDirect,fallbackSkinnedPipeline:this.state.skinnedPointShadowPipeline,fallbackBindGroup:c,shadowCameraBuffer:l,passKind:"pointShadow",customDepthMode:"use"});for(const e of this.staticDrawSets)e.publicSet.enabled&&0!==e.draws.length&&(this.renderBundleScratch[0]=li.call(this,e,c,l,"pointShadow",this.state.pointShadowPipeline,this.state.pointShadowPipelineDirect),u.executeBundles(this.renderBundleScratch),this.recordStaticDrawStats(e,n));u.end()}}}i||this.clearPointShadow(e)}function ti(e,t,r,n){if(!r.lights.spots.some(e=>e.castShadow))return;if(!this.state.shadowDepthPipeline||0===this.state.spotShadowLayerViews.length)return void this.clearSpotShadow(e);let i=!1;for(let t=0;t<r.lights.spots.length;t+=1){const a=r.lights.spots[t],s=this.state.spotShadowLayerViews[t];if(!a.castShadow||!s)continue;i=!0;const o=this.spotShadowCameras[t];o.near=a.shadowCameraNear,o.far=a.shadowCameraFar,o.fov=a.shadowCameraFov,o.aspect=1,o.position.copy(a.position),Hr.copy(a.position).add(a.direction),o.lookAt(Hr),o.updateMatrixWorld(!0),o.updateProjectionMatrix();const l=this.getShadowCameraBuffer(28+t);this.writeShadowCameraBuffer(Vn(o,this.shadowViewProjScratch),0,0,0,1,l,o);const c=this.getSharedShadowBindGroupForCameraBuffer(l),u=e.beginRenderPass({label:`renderer-spot-shadow-pass-${t}`,colorAttachments:[],depthStencilAttachment:{view:s,depthClearValue:1,depthLoadOp:"clear",depthStoreOp:"store"}});u.setPipeline(this.state.shadowDepthPipeline),u.setBindGroup(0,c),this.drawDepthLike(u,r.gpuOpaqueDraws,n,{fallbackPipeline:this.state.shadowDepthPipeline,fallbackPipelineDirect:this.state.shadowDepthPipelineDirect,fallbackSkinnedPipeline:this.state.skinnedShadowDepthPipeline,fallbackBindGroup:c,shadowCameraBuffer:l,passKind:"directionalShadow",customDepthMode:"use"}),this.drawDepthLike(u,r.directOpaqueDraws,n,{fallbackPipeline:this.state.shadowDepthPipeline,fallbackPipelineDirect:this.state.shadowDepthPipelineDirect,fallbackSkinnedPipeline:this.state.skinnedShadowDepthPipeline,fallbackBindGroup:c,shadowCameraBuffer:l,passKind:"directionalShadow",customDepthMode:"use"});for(const e of this.staticDrawSets)e.publicSet.enabled&&0!==e.draws.length&&(this.renderBundleScratch[0]=li.call(this,e,c,l,"directionalShadow",this.state.shadowDepthPipeline,this.state.shadowDepthPipelineDirect),u.executeBundles(this.renderBundleScratch),this.recordStaticDrawStats(e,n));u.end()}i||this.clearSpotShadow(e)}function ri(e,t,r,n){if(!this.state.depthPrepassPipeline||!this.state.mainDepthView)return;const i=e.beginRenderPass({label:"renderer-depth-prepass",colorAttachments:[],depthStencilAttachment:{view:this.state.mainDepthView,depthClearValue:1,depthLoadOp:"clear",depthStoreOp:"store"}});i.setPipeline(this.state.depthPrepassPipeline),i.setBindGroup(0,t),this.executeStaticDepthPrepass(i,t,n),this.drawDepthLike(i,r.gpuOpaqueDraws,n,{fallbackPipeline:this.state.depthPrepassPipeline,fallbackPipelineDirect:this.state.depthPrepassPipelineDirect,fallbackSkinnedPipeline:this.state.skinnedDepthPrepassPipeline,fallbackBindGroup:t,passKind:"prepass",customDepthMode:"skip"}),this.drawDepthLike(i,r.directOpaqueDraws,n,{fallbackPipeline:this.state.depthPrepassPipeline,fallbackPipelineDirect:this.state.depthPrepassPipelineDirect,fallbackSkinnedPipeline:this.state.skinnedDepthPrepassPipeline,fallbackBindGroup:t,passKind:"prepass",customDepthMode:"skip"}),i.end()}function ni(e,t,r){for(const n of this.staticDrawSets){if(!n.publicSet.enabled||0===n.draws.length)continue;if(this.getHiZOcclusionCullingActive()&&n.lastPreVisibilityFrameToken===this.staticFrameToken){const e=this.getOrCreateStaticVisibleDepthSceneBindGroup(n);this.renderBundleScratch[0]=ii.call(this,n,e)}else this.renderBundleScratch[0]=this.getOrCreateStaticDepthPrepassBundle(n,t);e.executeBundles(this.renderBundleScratch),this.recordStaticDrawStats(n,r)}}function ii(e,t,r=e.drawMetadataResource.indirectBuffer,n="prepass"){if(!this.state.device||!this.state.depthPrepassPipelineVisible)throw new Error("Renderer visible depth prepass resources are not initialized.");const i=e.indirectDepthPrepassBundles[n];if(i?.sceneBindGroup===t&&i.indirectBuffer===r)return i.bundle;const a=`${e.label}-static-temporal-depth-${n}-bundle-${e.id}`,s=this.state.device.createRenderBundleEncoder({label:a,colorFormats:[],depthStencilFormat:"depth32float",sampleCount:1});s.setPipeline(this.state.depthPrepassPipelineVisible),s.setBindGroup(0,t);let o=null;for(let t=0;t<e.draws.length;t+=1){const n=e.draws[t];n.customDepthMaterial||Zn(n,"prepass")||Ci(n.material)||!Kn(n)||(o!==n.geometryKey&&(o=n.geometryKey,this.bindGeometryVertexBuffers(s,n.geometry,n.geometryResource,jr,0,1,n.wireframe)),s.drawIndexedIndirect(r,5*t*Uint32Array.BYTES_PER_ELEMENT))}const l=s.finish({label:a});return e.indirectDepthPrepassBundles[n]={sceneBindGroup:t,indirectBuffer:r,bundle:l},l}function ai(e){}function si(e,t){if(!this.state.device||!this.state.depthPrepassPipeline)throw new Error("Renderer is not initialized.");const r=this.resolveSceneBindGroupForDraw(e.draws[0],t);if(e.depthPrepassBundle&&e.depthPrepassBundleSceneBindGroup===r)return e.depthPrepassBundle;const n=oi.call(this,e,"prepass"),i=`${e.label}-static-depth-prepass-bundle-${e.id}`,a=this.state.device.createRenderBundleEncoder({label:i,colorFormats:[],depthStencilFormat:"depth32float",sampleCount:1});a.setBindGroup(0,r);let s=null,o=null,l=null;for(let t=0;t<e.draws.length;t+=1){const r=e.draws[t],i=n[t];if(r.customDepthMaterial||!i&&(Ci(r.material)||!Kn(r)))continue;const c=i?.pipeline??this.state.depthPrepassPipeline;s!==c&&(s=c,o=null,l=null,a.setPipeline(c)),i&&o!==i.bindGroup&&(o=i.bindGroup,a.setBindGroup(1,o)),l!==r.geometryKey&&(l=r.geometryKey,this.bindGeometryVertexBuffers(a,r.geometry,r.geometryResource,i?.vertexAttributes??jr,r.instanceStart,r.instanceCount,r.wireframe)),a.drawIndexed(r.count,r.instanceCount,r.start,0,r.instanceStart)}const c=a.finish({label:i});return e.depthPrepassBundle=c,e.depthPrepassBundleSceneBindGroup=r,c}function oi(e,t){const r=t,n=e.depthMaterialResources.get(r);if(n)return n;const i=e.draws.map(e=>{const r=Zn(e,t);if(e.customDepthMaterial||!r)return null;return this.getDepthPassMaterialResourceForDraw(e.material,t,e)});return e.depthMaterialResources.set(r,i),i}function li(e,t,r,n,i,a){if(!this.state.device)throw new Error("Renderer is not initialized.");const s=this.resolveShadowBindGroupForDraw(e.draws[0],t,r),o=e.shadowBundles.get(s),l=o?.[n];if(l)return l;const c=oi.call(this,e,n),u=`${e.label}-static-${n}-bundle-${e.id}`,d=this.state.device.createRenderBundleEncoder({label:u,colorFormats:"pointShadow"===n?["rgba16float"]:[],depthStencilFormat:"depth32float",sampleCount:1});d.setBindGroup(0,s);let h=null,p=null,f=null;for(let t=0;t<e.draws.length;t+=1){const r=e.draws[t];if(!r.castShadow)continue;const n=c[t],s=n?.pipeline??("instanced-direct"===this.getDrawInstanceAccessMode(r)&&a?a:i);h!==s&&(h=s,p=null,f=null,d.setPipeline(s)),n&&p!==n.bindGroup&&(p=n.bindGroup,d.setBindGroup(1,p)),f!==r.geometryKey&&(f=r.geometryKey,this.bindGeometryVertexBuffers(d,r.geometry,r.geometryResource,n?.vertexAttributes??jr,r.instanceStart,r.instanceCount,r.wireframe)),d.drawIndexed(r.count,r.instanceCount,r.start,0,r.instanceStart)}const m=d.finish({label:u});return e.shadowBundles.set(s,{...o,[n]:m}),m}function ci(e,t=!1){if(!(this.state.device&&this.state.hizTexture&&this.state.mainDepthTexture&&this.state.mainDepthView&&this.state.hizCopyKernel&&this.state.hizReduceKernel))return;let r=this.state.hizCopyBindGroup;r||(r=this.state.hizCopyKernel.createBindGroup(this.state.device,[{binding:0,resource:this.state.mainDepthView},{binding:1,resource:this.state.hizMipViews[0]}],"renderer-hiz-copy-bind-group"),this.state.hizCopyBindGroup=r);const n=e.beginComputePass({label:"renderer-hiz-copy-pass"});n.setPipeline(this.state.hizCopyKernel.pipeline),n.setBindGroup(0,r),n.dispatchWorkgroups(Math.ceil(this.state.width/8),Math.ceil(this.state.height/8)),n.end();for(let t=1;t<this.state.hizMipCount;t+=1){const r=Math.max(1,this.state.width>>t),n=Math.max(1,this.state.height>>t);let i=this.state.hizReduceBindGroups[t];i||(i=this.state.hizReduceKernel.createBindGroup(this.state.device,[{binding:0,resource:this.state.hizMipViews[t-1]},{binding:1,resource:this.state.hizMipViews[t]}],`renderer-hiz-reduce-bind-group-${t}`),this.state.hizReduceBindGroups[t]=i);const a=e.beginComputePass({label:`renderer-hiz-reduce-pass-${t}`});a.setPipeline(this.state.hizReduceKernel.pipeline),a.setBindGroup(0,i),a.dispatchWorkgroups(Math.ceil(r/8),Math.ceil(n/8)),a.end()}t&&this.commitTemporalHiZHistory()}function ui(e,t,r,n,i,a,s=!1,o="all",l=!1,c=this.sampleCount){if(!this.state.mainDepthView)return;const u=c>1,d=u?this.ensureMsaaColorTarget(t):null,h=u?this.ensureMsaaDepthTarget(d.width,d.height):null,p=e.beginRenderPass({label:"renderer-forward-pass",colorAttachments:[{view:d?.view??r,resolveTarget:d?r:void 0,clearValue:{r:this.clearColor[0],g:this.clearColor[1],b:this.clearColor[2],a:this.clearColor[3]},loadOp:l?"load":"clear",storeOp:d?"discard":"store"}],depthStencilAttachment:{view:h?.view??this.state.mainDepthView,depthClearValue:1,depthLoadOp:h||s?"clear":"load",depthStoreOp:h?"discard":"store"}});let f=null,m=null,g=null,x=null,v=null;const w=e=>{e.sourceObject&&e.hasRenderCallbacks&&e.sourceObject.onBeforeRender(this,i.scene,i.camera,e.geometry,e.material,e.geometryGroup);const t=e.geometryResource,r=this.getMaterialResourceForDraw(e,[Er],c),s=this.resolveSceneBindGroupForDraw(e,n);if(f!==r.pipeline&&(f=r.pipeline,g=null,v=null,p.setPipeline(f)),g!==e.geometryKey&&(g=e.geometryKey,this.bindGeometryVertexBuffers(p,e.geometry,t,r.vertexAttributes,e.instanceStart,e.instanceCount,e.wireframe)),x!==s&&(x=s,p.setBindGroup(0,s)),m!==e.material){if(m=e.material,p.setBindGroup(1,r.bindGroup),!r.graphTextureBindGroupLayout)throw new Error("Graph texture layout is missing.");p.setBindGroup(3,this.createGraphTextureBindGroup(e.material,r.graphTextureBindGroupLayout))}r.usesSkinning&&e.skinning&&v!==e.skinning.bindGroup&&(v=e.skinning.bindGroup,p.setBindGroup(2,v)),e.indexed&&(e.wireframe?t.wireframeIndex:t.index)?p.drawIndexed(e.count,e.instanceCount,e.start,0,e.instanceStart):p.draw(e.count,e.instanceCount,e.start,e.instanceStart),this.recordDraw(e,a),e.sourceObject&&e.hasRenderCallbacks&&e.sourceObject.onAfterRender(this,i.scene,i.camera,e.geometry,e.material,e.geometryGroup)};if("late"!==o&&this.executeStaticForwardPass(p,n,a),f=null,m=null,g=null,x=null,v=null,"late"!==o&&this.getHiZOcclusionCullingActive()&&this.state.drawMetadataResource){const e=this.buildIndirectSubmissionStreams(i.gpuOpaqueDraws,n),t=this.renderBundleScratch;t.length=0;for(let r=0;r<e.length;r+=1){const n=e[r];t[0]=this.getOrCreateIndirectForwardBundle(n),p.executeBundles(t),a.drawCallCount+=n.drawCallCount,a.triangleCount+=n.triangleCount}f=null,m=null,g=null,x=null}else if("late"!==o){const e=Dn(i.gpuOpaqueDraws)||i.gpuOpaqueDraws.some(e=>null!==e.skinning)?null:this.getOrCreateDirectForwardBundle(i.gpuOpaqueDraws,n,a);if(e)this.renderBundleScratch[0]=e,p.executeBundles(this.renderBundleScratch);else for(const e of i.gpuOpaqueDraws)w(e)}const b="late"===o||Dn(i.directOpaqueDraws)||i.directOpaqueDraws.some(e=>null!==e.skinning)?null:this.getOrCreateDirectForwardBundle(i.directOpaqueDraws,n,a);if(b)this.renderBundleScratch[0]=b,p.executeBundles(this.renderBundleScratch);else if("late"!==o)for(const e of i.directOpaqueDraws)w(e);if("opaque"!==o)for(const e of i.transparentDraws)w(e);p.end()}function di(e,t,r){for(const n of this.staticDrawSets)if(n.publicSet.enabled&&0!==n.draws.length){if(this.getHiZOcclusionCullingActive()&&n.lastVisibilityFrameToken===this.staticFrameToken){const t=this.getOrCreateStaticVisibleSceneBindGroup(n),i=this.getOrCreateStaticIndirectSubmissionStreams(n,t);for(const t of i)if(this.getMultiDrawIndirectActive()){if(e.setPipeline(t.materialResource.pipeline),this.bindGeometryVertexBuffers(e,t.geometry,t.geometryResource,t.materialResource.vertexAttributes,0,1,t.material.wireframe),e.setBindGroup(0,t.sceneBindGroup),e.setBindGroup(1,t.materialResource.bindGroup),!t.materialResource.graphTextureBindGroupLayout)throw new Error("Graph texture layout is missing.");e.setBindGroup(3,this.createGraphTextureBindGroup(t.material,t.materialResource.graphTextureBindGroupLayout)),e.multiDrawIndexedIndirect(n.drawMetadataResource.indirectBuffer,5*t.indirectStartIndex*Uint32Array.BYTES_PER_ELEMENT,t.indirectCount),r.drawCallCount+=t.drawCallCount,r.triangleCount+=t.triangleCount}else this.renderBundleScratch[0]=this.getOrCreateIndirectForwardBundle(t,n.drawMetadataResource,n.indirectForwardBundleCache,`${n.label}-static-indirect-forward-bundle`),e.executeBundles(this.renderBundleScratch),r.drawCallCount+=t.drawCallCount,r.triangleCount+=t.triangleCount;continue}this.renderBundleScratch[0]=this.getOrCreateStaticDirectForwardBundle(n,t),e.executeBundles(this.renderBundleScratch),this.recordStaticDrawStats(n,r)}}function hi(e,t){if(!this.state.device||!this.state.format)throw new Error("Renderer is not initialized.");const r=this.resolveSceneBindGroupForDraw(e.draws[0],t);if(e.directForwardBundle&&e.directForwardBundleSceneBindGroup===r)return e.directForwardBundle;null==e.draws[0]?.materialResource&&(this.refreshStaticDrawMaterialResources(e.draws),this.syncStaticVisibleMaterialBindingCaches(e));const n=`${e.label}-static-forward-direct-bundle-${e.id}`,i=this.state.device.createRenderBundleEncoder({label:n,colorFormats:[Er],depthStencilFormat:"depth32float",sampleCount:this.sampleCount});let a=null,s=null,o=null;i.setBindGroup(0,r);for(const t of e.draws){const e=t.materialResource??this.getMaterialResource(t.material,this.getDrawInstanceAccessMode(t),t.receiveShadow,void 0,null!==t.skinning,Hn(t));if(a!==e.pipeline&&(a=e.pipeline,o=null,i.setPipeline(a)),o!==t.geometryKey&&(o=t.geometryKey,this.bindGeometryVertexBuffers(i,t.geometry,t.geometryResource,e.vertexAttributes,t.instanceStart,t.instanceCount,t.wireframe)),s!==e.bindGroup){if(s=e.bindGroup,i.setBindGroup(1,s),!e.graphTextureBindGroupLayout)throw new Error("Graph texture layout is missing.");i.setBindGroup(3,this.createGraphTextureBindGroup(t.material,e.graphTextureBindGroupLayout))}i.drawIndexed(t.count,t.instanceCount,t.start,0,t.instanceStart)}const l=i.finish({label:n});return e.directForwardBundle=l,e.directForwardBundleSceneBindGroup=r,l}function pi(e){for(const t of e.visibleMaterialBindings){const r=t.drawIndices[0];t.resource=e.draws[r]?.materialResource??e.visibleDrawMaterialResources[r]??null}}function fi(e){for(const t of e)t.materialResource=this.getMaterialResource(t.material,this.getDrawInstanceAccessMode(t),t.receiveShadow,void 0,null!==t.skinning,Hn(t))}function mi(e,t){t.drawCallCount+=e.drawCallCount,t.triangleCount+=e.triangleCount}function gi(){return this.staticDrawSets.some(e=>e.publicSet.enabled&&e.draws.length>0)}function xi(e,t,r){if(!(this.state.device&&this.state.presentPipeline&&this.state.fullscreenTextureBindGroupLayout&&this.state.linearClampSampler))return;let n=this.state.presentBindGroups.get(t);n||(n=this.state.device.createBindGroup({label:"renderer-present-bind-group",layout:this.state.fullscreenTextureBindGroupLayout,entries:[{binding:0,resource:this.state.linearClampSampler},{binding:1,resource:t}]}),this.state.presentBindGroups.set(t,n));const i=e.beginRenderPass({label:"renderer-present-pass",colorAttachments:[{view:r,clearValue:{r:this.clearColor[0],g:this.clearColor[1],b:this.clearColor[2],a:this.clearColor[3]},loadOp:"clear",storeOp:"store"}]});i.setPipeline(this.state.presentPipeline),i.setBindGroup(0,n),i.draw(3),i.end()}function vi(e){for(let t=0;t<this.state.directionalShadowLayerViews.length;t+=1){e.beginRenderPass({label:`renderer-clear-directional-shadow-${t}`,colorAttachments:[],depthStencilAttachment:{view:this.state.directionalShadowLayerViews[t],depthClearValue:1,depthLoadOp:"clear",depthStoreOp:"store"}}).end()}}function wi(e){for(let t=0;t<this.state.pointShadowFaceViews.length;t+=1){e.beginRenderPass({label:`renderer-clear-point-shadow-${t}`,colorAttachments:[{view:this.state.pointShadowFaceViews[t],clearValue:{r:1,g:1,b:1,a:1},loadOp:"clear",storeOp:"store"}],depthStencilAttachment:{view:this.state.pointShadowDepthFaceViews[t],depthClearValue:1,depthLoadOp:"clear",depthStoreOp:"store"}}).end()}}function bi(e){for(let t=0;t<this.state.spotShadowLayerViews.length;t+=1){e.beginRenderPass({label:`renderer-clear-spot-shadow-${t}`,colorAttachments:[],depthStencilAttachment:{view:this.state.spotShadowLayerViews[t],depthClearValue:1,depthLoadOp:"clear",depthStoreOp:"store"}}).end()}}function yi(e,t,r,n){let i=null,a=null,s=null,o=null,l=null;for(const c of t){if("prepass"!==n.passKind&&!c.castShadow)continue;if("prepass"===n.passKind&&null===c.material.depthVertexShader&&Ci(c.material))continue;if("skip"===n.customDepthMode&&c.customDepthMaterial)continue;const t=Zn(c,n.passKind),u="use"===n.customDepthMode&&c.customDepthMaterial?c.customDepthMaterial:"ignore"!==n.customDepthMode&&t?c.material:null,d=u?this.getDepthPassMaterialResourceForDraw(u,n.passKind,c):null;if(!d&&!Kn(c))continue;const h=null!==c.skinning,p=d?.pipeline??(h&&n.fallbackSkinnedPipeline?n.fallbackSkinnedPipeline:"instanced-direct"===this.getDrawInstanceAccessMode(c)&&n.fallbackPipelineDirect?n.fallbackPipelineDirect:n.fallbackPipeline);a!==p&&(a=p,s=null,o=null,l=null,i=null,e.setPipeline(p));const f="prepass"===n.passKind?this.resolveSceneBindGroupForDraw(c,n.fallbackBindGroup):this.resolveShadowBindGroupForDraw(c,n.fallbackBindGroup,n.shadowCameraBuffer);s!==f&&(s=f,e.setBindGroup(0,f)),d?o!==d.bindGroup&&(o=d.bindGroup,e.setBindGroup(1,d.bindGroup)):o=null,(d?.usesSkinning??h)&&c.skinning&&l!==c.skinning.bindGroup&&(l=c.skinning.bindGroup,e.setBindGroup(2,l));const m=c.geometryResource;i!==c.geometryKey&&(i=c.geometryKey,this.bindGeometryVertexBuffers(e,c.geometry,m,d?.vertexAttributes??(h?Nr:jr),c.instanceStart,c.instanceCount,c.wireframe)),c.indexed&&(c.wireframe?m.wireframeIndex:m.index)?e.drawIndexed(c.count,c.instanceCount,c.start,0,c.instanceStart):e.draw(c.count,c.instanceCount,c.start,c.instanceStart),this.recordDraw(c,r)}}var Si=new WeakMap;function Ci(e){if(e.transparent)return!0;let t=Si.get(e);return null==t&&(t=e.transparent||e.alphaTest>0||/\bdiscard\b/.test(e.fragmentShader),Si.set(e,t)),t}import{Vector3 as Pi}from"three";var Mi=class{data;lengthFloats=0;constructor(e=1024){this.data=new Float32Array(e)}get floatLength(){return this.lengthFloats}get rawData(){return this.data}get byteLength(){return this.lengthFloats*Float32Array.BYTES_PER_ELEMENT}get instanceCount(){return this.lengthFloats/Ur}reset(){this.lengthFloats=0}appendMatrixAndColor(e,t){return this.appendMatrixAndColorValues(e,t[0]??1,t[1]??1,t[2]??1,t[3]??1)}appendMatrixAndColorValues(e,t,r,n,i,a=this.instanceCount){const s=this.instanceCount;this.ensureCapacity(this.lengthFloats+Ur);const o=this.lengthFloats;for(let t=0;t<16;t+=1)this.data[o+t]=e[t]??0;return this.data[o+16]=t,this.data[o+17]=r,this.data[o+18]=n,this.data[o+19]=i,this.data[o+20]=a,this.data[o+21]=0,this.data[o+22]=0,this.data[o+23]=0,this.lengthFloats+=Ur,s}appendRange(e,t,r){if(r<=0)return;const n=t*Ur,i=n+r*Ur;this.ensureCapacity(this.lengthFloats+(i-n)),this.data.set(e.data.subarray(n,i),this.lengthFloats),this.lengthFloats+=i-n}appendBuilder(e){this.appendRange(e,0,e.instanceCount)}beginWriteInstances(e){const t=e*Ur;return this.ensureCapacity(t),this.lengthFloats=t,this.data}toFloat32Array(){return this.data.slice(0,this.lengthFloats)}ensureCapacity(e){if(e<=this.data.length)return;let t=this.data.length;for(;t<e;)t*=2;const r=new Float32Array(t);r.set(this.data.subarray(0,this.lengthFloats),0),this.data=r}},Bi=class{constructor(e,t,r,n,i){this.state=e,this.staticDrawSets=t,this.getGeometryResourceForGeometry=r,this.resolveMaterial=n,this.ensureWireframeIndex=i}state;staticDrawSets;getGeometryResourceForGeometry;resolveMaterial;ensureWireframeIndex;nextStaticDrawSetId=1;activeMaterialSnapshots=null;getGeometryResource(e){return this.getGeometryResourceForGeometry(e)}resolveStaticMaterial(e){const t=this.resolveMaterial(e);if(!t||!this.activeMaterialSnapshots)return t;let r=this.activeMaterialSnapshots.get(t);return r||(r=t.clone(),r.name=t.name?`${t.name} (static snapshot)`:"Static draw-set material snapshot",this.activeMaterialSnapshots.set(t,r)),r}createStaticDrawSet(e,t={}){if(!(this.state.initialized&&this.state.device&&this.state.staticVisibilityClearKernel&&this.state.staticVisibilityCullKernel&&this.state.staticVisibilityIndirectBuildKernel))throw new Error("WebGpuRenderer.initialize() must complete before creating a static draw set.");const r=t.label??`static-draw-set-${this.nextStaticDrawSetId}`,n=t.onUnsupported??"throw",i=[],a=new Mi(4096),s=(e,t)=>{if("skip"!==n)throw new Error(`StaticDrawSet "${r}" does not support ${e.type||"Object3D"} "${e.name||e.uuid}": ${t}.`)};e.updateMatrixWorld(!0);const o=new Map;this.activeMaterialSnapshots=o;try{e.traverseVisible(e=>{e.isSkinnedMesh?s(e,"skinned meshes are dynamic"):e.isBatchedMesh?this.collectStaticBatchedMesh(e,a,i,r,s):e.isInstancedMesh?this.collectStaticInstancedMesh(e,a,i,r,s):e.isMesh&&this.collectStaticMesh(e,a,i,r,s)})}catch(e){for(const e of o.values())e.dispose();throw e}finally{this.activeMaterialSnapshots=null}const{draws:l,instanceData:c}=this.mergeStaticDraws(i,a),u=this.createVisibleMaterialBindings(l),d=Math.max(4,c.byteLength),h=this.state.device.createBuffer({label:`${r}-static-instance-buffer`,size:256*Math.ceil(d/256),usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST});c.floatLength>0?this.state.device.queue.writeBuffer(h,0,c.rawData.buffer,0,c.byteLength):this.state.device.queue.writeBuffer(h,0,Ar,0,Ur);const p={mode:"packed",buffer:h,colorBuffer:null,sceneBindGroup:null,shadowBindGroup:null,shadowBindGroups:new Map,sceneBindGroupVersion:0,shadowBindGroupVersion:0};for(const e of l)e.residentInstanceBinding=p;const f=this.createStaticDrawMetadataResource(r,l),m=this.createStaticInstanceVisibilityResource(r,l,c),g=new Uint32Array([l.length,this.state.hizMipCount,c.instanceCount,0]),x=this.state.device.createBuffer({label:`${r}-visibility-params-buffer`,size:16,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),v=new Uint32Array([l.length,this.state.hizMipCount,c.instanceCount,0]),w=this.state.device.createBuffer({label:`${r}-post-visibility-params-buffer`,size:16,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST});this.state.device.queue.writeBuffer(x,0,g,0,4),this.state.device.queue.writeBuffer(w,0,v,0,4);const b={id:this.nextStaticDrawSetId++,label:r,publicSet:null,ownedMaterials:[...o.values()],draws:l,drawCallCount:l.length,triangleCount:l.reduce((e,t)=>e+Math.floor(Math.max(0,t.count)/3)*Math.max(0,t.instanceCount),0),instanceCount:c.instanceCount,instanceBuffer:h,residentInstanceBinding:p,drawMetadataResource:f,instanceVisibilityResource:m,visibilityParamsBuffer:x,visibilityParamsUpload:g,postVisibilityParamsBuffer:w,postVisibilityParamsUpload:v,visibilityBindGroup:null,postVisibilityBindGroup:null,visibilityClearBindGroup:null,visibilityIndirectBuildBindGroup:null,postVisibilityIndirectBuildBindGroup:null,visibleSceneBindGroup:null,visibleSceneBindGroupVersion:0,visibleDepthSceneBindGroup:null,visibleDepthSceneBindGroupVersion:0,visibleMaterialBindings:u,visibleDrawMaterialResources:new Array(l.length),visibleIndirectSubmissionStreams:null,visibleIndirectStreamsSceneBindGroup:null,visibleIndirectStreamsSampleCount:-1,visibleIndirectStreamsColorFormatsKey:"",visibilityBindGroupHizVersion:0,lastPreVisibilityFrameToken:0,lastVisibilityFrameToken:0,indirectForwardBundleCache:new Map,directForwardBundle:null,directForwardBundleSceneBindGroup:null,depthPrepassBundle:null,depthPrepassBundleSceneBindGroup:null,indirectDepthPrepassBundles:{prepass:null,postpass:null},shadowBundles:new WeakMap,depthMaterialResources:new Map},y={label:r,enabled:!0,get drawCount(){return b.draws.length},get instanceCount(){return b.instanceCount},dispose:()=>{this.disposeStaticDrawSetResource(b)}};return b.publicSet=y,this.staticDrawSets.push(b),y}createVisibleMaterialBindings(e){const t=new Map;for(let r=0;r<e.length;r+=1){const n=e[r],i=`${Sn(n.material)}:${n.receiveShadow?1:0}:${n.usesBatching?1:0}`;let a=t.get(i);a||(a={material:n.material,receiveShadow:n.receiveShadow,usesBatching:n.usesBatching,drawIndices:[],resource:null},t.set(i,a)),a.drawIndices.push(r)}return[...t.values()]}mergeStaticDraws(e,t){e.sort(Mn);const r=[],n=new Mi(Math.max(1024,t.floatLength));for(let i=0;i<e.length;){const a=e[i],s=n.instanceCount;n.appendRange(t,a.instanceStart,a.instanceCount);let o=a.instanceCount,l=a.boundsCenter.x-a.boundsRadius,c=a.boundsCenter.y-a.boundsRadius,u=a.boundsCenter.z-a.boundsRadius,d=a.boundsCenter.x+a.boundsRadius,h=a.boundsCenter.y+a.boundsRadius,p=a.boundsCenter.z+a.boundsRadius,f=i+1;for(;f<e.length&&Gn(a,e[f]);){const r=e[f];n.appendRange(t,r.instanceStart,r.instanceCount),o+=r.instanceCount;const i=r.boundsCenter.x-r.boundsRadius,a=r.boundsCenter.y-r.boundsRadius,s=r.boundsCenter.z-r.boundsRadius,m=r.boundsCenter.x+r.boundsRadius,g=r.boundsCenter.y+r.boundsRadius,x=r.boundsCenter.z+r.boundsRadius;i<l&&(l=i),a<c&&(c=a),s<u&&(u=s),m>d&&(d=m),g>h&&(h=g),x>p&&(p=x),f+=1}const m=.5*(l+d),g=.5*(c+h),x=.5*(u+p),v=d-m,w=h-g,b=p-x;a.instanceStart=s,a.instanceCount=o,a.boundsCenter.set(m,g,x),a.boundsRadius=Math.sqrt(v*v+w*w+b*b),r.push(a),i=f}return{draws:r,instanceData:n}}collectStaticMesh(e,t,r,n,i){if(!(null!==e.geometry.index))return void i(e,"non-indexed geometry cannot use the v1 indirect static path");if(jn(e))return void i(e,"custom depth materials are not supported by StaticDrawSet v1");const a=this.getGeometryResource(e.geometry),s=Fn(e.geometry),o=Hr.copy(s.center).applyMatrix4(e.matrixWorld),l=s.radius*En(e.matrixWorld),c=bn(t,e.matrixWorld,1,1,1,1),u=Array.isArray(e.material)?e.material:null,d=Array.isArray(e.material)?null:e.material;if(e.geometry.groups.length>0){for(const t of e.geometry.groups){const n=u?u[t.materialIndex??0]??u[0]:d,h=this.resolveStaticMaterial(n);if(!h){i(e,"all static mesh materials must be WGSLShaderMaterial");continue}if(h.transparent){i(e,"transparent materials are not supported by StaticDrawSet v1");continue}if(Object.keys(h.getGraphTextureInputs()).length>0){i(e,"scene-texture materials are not supported by StaticDrawSet v1");continue}const p=pn(e.geometry,!0,t.start,t.count);p<=0||r.push(this.createStaticDrawRecord(e.geometry,e.geometry,a,h,!1,t.start,p,c,1,o.x,o.y,o.z,l,s.center,s.radius))}return}const h=d??u?.[0]??null,p=this.resolveStaticMaterial(h);if(!p)return void i(e,"all static mesh materials must be WGSLShaderMaterial");if(p.transparent)return void i(e,"transparent materials are not supported by StaticDrawSet v1");if(Object.keys(p.getGraphTextureInputs()).length>0)return void i(e,"scene-texture materials are not supported by StaticDrawSet v1");const f=fn(e.geometry,!0);f.count<=0||r.push(this.createStaticDrawRecord(e.geometry,e.geometry,a,p,!1,f.start,f.count,c,1,o.x,o.y,o.z,l,s.center,s.radius))}collectStaticInstancedMesh(e,t,r,n,i){const a=this.resolveStaticMaterial(e.material);if(!a)return void i(e,"static instanced meshes must use WGSLShaderMaterial");if(a.transparent)return void i(e,"transparent materials are not supported by StaticDrawSet v1");if(Object.keys(a.getGraphTextureInputs()).length>0)return void i(e,"scene-texture materials are not supported by StaticDrawSet v1");if(jn(e))return void i(e,"custom depth materials are not supported by StaticDrawSet v1");if(null===e.geometry.index)return void i(e,"non-indexed geometry cannot use the v1 indirect static path");const s=fn(e.geometry,!0);if(s.count<=0||e.count<=0)return;const o=Fn(e.geometry),l=Hr.set(1/0,1/0,1/0),c=Kr.set(-1/0,-1/0,-1/0),u=this.getGeometryResource(e.geometry),d=t.instanceCount;for(let r=0;r<e.count;r+=1){e.getMatrixAt(r,Wr),_r.multiplyMatrices(e.matrixWorld,Wr);const n=e.instanceColor?e.instanceColor.getComponent(r,0):1,i=e.instanceColor&&e.instanceColor.itemSize>1?e.instanceColor.getComponent(r,1):1,a=e.instanceColor&&e.instanceColor.itemSize>2?e.instanceColor.getComponent(r,2):1,s=e.instanceColor&&e.instanceColor.itemSize>3?e.instanceColor.getComponent(r,3):1;bn(t,_r,n,i,a,s);kn(l,c,Zr.copy(o.center).applyMatrix4(_r),o.radius*En(_r))}const h=.5*(l.x+c.x),p=.5*(l.y+c.y),f=.5*(l.z+c.z),m=c.x-h,g=c.y-p,x=c.z-f,v=Math.sqrt(m*m+g*g+x*x);r.push(this.createStaticDrawRecord(e.geometry,e.geometry,u,a,!1,s.start,s.count,d,e.count,h,p,f,v,o.center,o.radius))}collectStaticBatchedMesh(e,t,r,n,i){const a=this.resolveStaticMaterial(e.material);if(!a)return void i(e,"static batched meshes must use WGSLShaderMaterial");if(a.transparent)return void i(e,"transparent materials are not supported by StaticDrawSet v1");if(Object.keys(a.getGraphTextureInputs()).length>0)return void i(e,"scene-texture materials are not supported by StaticDrawSet v1");if(jn(e))return void i(e,"custom depth materials are not supported by StaticDrawSet v1");if(null===e.geometry.index)return void i(e,"non-indexed geometry cannot use the v1 indirect static path");const s=e,o=this.getGeometryResource(e.geometry),l=s._geometryCount??0,c=[],u=new Map;for(let t=0;t<l;t+=1){const r=e.getGeometryRangeAt(t);if(!r||r.count<=0)continue;const n=pn(e.geometry,!0,r.start,r.count);if(n<=0)continue;const i=e.getBoundingSphereAt(t,qr),a={geometryId:t,start:r.start,count:n,localBoundsCenter:i?i.center.clone():new Pi,localBoundsRadius:i?.radius??1,instances:[]};u.set(t,a),c.push(a)}const d=s._instanceInfo??s._drawInfo??[],h=s._matricesTexture?.image.data,p=s._colorsTexture?.image.data;for(let t=0;t<d.length;t+=1){const r=d[t];if(!r?.active||!r.visible)continue;const n=u.get(r.geometryIndex);if(!n)continue;h?yn(Wr,h,16*t):e.getMatrixAt(t,Wr),_r.multiplyMatrices(e.matrixWorld,Wr);const i=4*t,a=p?p[i+0]??1:1,s=p?p[i+1]??1:1,o=p?p[i+2]??1:1,l=p?p[i+3]??1:1,c=Zr.copy(n.localBoundsCenter).applyMatrix4(_r),f=n.localBoundsRadius*En(_r);n.instances.push({matrix:new Float32Array(_r.elements),color0:a,color1:s,color2:o,color3:l,batchingId:t,boundsCenter:c.clone(),boundsRadius:f})}for(const n of c){if(0===n.instances.length)continue;const i=Hr.set(1/0,1/0,1/0),s=Kr.set(-1/0,-1/0,-1/0),l=t.instanceCount;for(const e of n.instances)t.appendMatrixAndColorValues(e.matrix,e.color0,e.color1,e.color2,e.color3,e.batchingId),kn(i,s,e.boundsCenter,e.boundsRadius);const c=.5*(i.x+s.x),u=.5*(i.y+s.y),d=.5*(i.z+s.z),h=s.x-c,p=s.y-u,f=s.z-d,m=Math.sqrt(h*h+p*p+f*f);r.push(this.createStaticDrawRecord(e.geometry,e.geometry,o,a,!0,n.start,n.count,l,n.instances.length,c,u,d,m,n.localBoundsCenter,n.localBoundsRadius))}}createStaticDrawRecord(e,t,r,n,i,a,s,o,l,c,u,d,h,p,f){const m=Sn(n),g=n.wireframe&&"triangle-list"===n.primitiveTopology;g&&this.ensureWireframeIndex(e,r);const x=Sn(t);return{geometry:e,geometryKey:g?r.wireframeIndex:t,geometryResource:r,material:n,customDepthMaterial:null,residentInstanceBinding:null,sourceObject:null,usesBatching:i,geometryGroup:null,batchKey:Cn(n,t,!0,a,s,null),batchHash:Pn(m,x,!0,a,s,0),indexed:!0,wireframe:g,start:g?2*a:a,count:g?2*s:s,transparent:!1,renderOrder:0,hasRenderCallbacks:!1,castShadow:!0,receiveShadow:!0,sortMaterialId:m,sortGeometryId:x,sortCustomDepthMaterialId:0,skinning:null,materialResource:null,instanceStart:o,instanceCount:l,boundsCenter:new Pi(c,u,d),boundsRadius:h,sortDepth:0,transparentSortGroup:0,transparentSortOrder:0,staticLocalBoundsCenter:p.clone(),staticLocalBoundsRadius:f}}createStaticDrawMetadataResource(e,t){if(!this.state.device)throw new Error("Renderer is not initialized.");const r=Math.max(1,t.length),n=new Float32Array(r*Vr),i=new Uint32Array(5*r),a=new Uint32Array(5*r);for(let e=0;e<t.length;e+=1){const r=t[e],s=e*Vr;n[s+0]=r.boundsCenter.x,n[s+1]=r.boundsCenter.y,n[s+2]=r.boundsCenter.z,n[s+3]=r.boundsRadius,n[s+4]=r.count,n[s+5]=r.start,n[s+6]=r.instanceStart,n[s+7]=r.instanceCount,n[s+8]=1,n[s+9]=0,n[s+10]=0,n[s+11]=0;const o=5*e;i[o+0]=r.count,i[o+1]=r.instanceCount,i[o+2]=r.start,i[o+3]=0,i[o+4]=r.instanceStart,a[o+0]=r.count,a[o+1]=0,a[o+2]=r.start,a[o+3]=0,a[o+4]=r.instanceStart}const s=this.state.device.createBuffer({label:`${e}-static-draw-metadata-buffer`,size:r*Vr*4,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST}),o=this.state.device.createBuffer({label:`${e}-static-indirect-draw-buffer`,size:5*r*4,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.INDIRECT|GPUBufferUsage.COPY_DST|GPUBufferUsage.COPY_SRC}),l=this.state.device.createBuffer({label:`${e}-static-post-indirect-draw-buffer`,size:5*r*4,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.INDIRECT|GPUBufferUsage.COPY_DST});return this.state.device.queue.writeBuffer(s,0,n,0,n.length),this.state.device.queue.writeBuffer(o,0,i,0,i.length),this.state.device.queue.writeBuffer(l,0,a,0,a.length),{count:t.length,capacity:r,metadataBuffer:s,indirectBuffer:o,postIndirectBuffer:l}}createStaticInstanceVisibilityResource(e,t,r){if(!this.state.device)throw new Error("Renderer is not initialized.");const n=r.instanceCount,i=Math.max(32,32*n),a=new ArrayBuffer(i),s=new Float32Array(a),o=new Uint32Array(a);for(let e=0;e<t.length;e+=1){const n=t[e],i=n.staticLocalBoundsCenter??Fn(n.geometry).center,a=n.staticLocalBoundsRadius??Fn(n.geometry).radius;for(let t=0;t<n.instanceCount;t+=1){const l=n.instanceStart+t,c=l*Ur,u=8*l;Wr.fromArray(r.rawData,c);const d=Hr.copy(i).applyMatrix4(Wr),h=a*En(Wr);s[u+0]=d.x,s[u+1]=d.y,s[u+2]=d.z,s[u+3]=h,o[u+4]=e,o[u+5]=l,o[u+6]=0,o[u+7]=0}}const l=this.state.device.createBuffer({label:`${e}-static-instance-visibility-metadata`,size:256*Math.ceil(i/256),usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST}),c=this.state.device.createBuffer({label:`${e}-static-visible-instance-indices`,size:256*Math.ceil(Math.max(4,4*n)/256),usage:GPUBufferUsage.STORAGE}),u=this.state.device.createBuffer({label:`${e}-static-visible-instance-counts`,size:256*Math.ceil(Math.max(4,4*t.length)/256),usage:GPUBufferUsage.STORAGE}),d=this.state.device.createBuffer({label:`${e}-static-post-visible-instance-counts`,size:256*Math.ceil(Math.max(4,4*t.length)/256),usage:GPUBufferUsage.STORAGE}),h=this.state.device.createBuffer({label:`${e}-static-visible-instance-mask`,size:256*Math.ceil(Math.max(4,4*n)/256),usage:GPUBufferUsage.STORAGE});return n>0&&this.state.device.queue.writeBuffer(l,0,a),{instanceMetadataBuffer:l,visibleInstanceIndicesBuffer:c,visibleCountsBuffer:u,postVisibleCountsBuffer:d,visibleInstanceMaskBuffer:h,instanceCount:n}}disposeStaticDrawSetResource(e){const t=this.staticDrawSets.indexOf(e);if(t<0)return;this.staticDrawSets.splice(t,1);const r=new Set;for(const t of e.draws)t.materialResource&&r.add(t.materialResource);for(const t of e.visibleMaterialBindings)t.resource&&r.add(t.resource);for(const t of e.visibleDrawMaterialResources)t&&r.add(t);for(const t of e.depthMaterialResources.values())for(const e of t)e&&r.add(e);for(const e of r)e.uniformBuffer?.destroy();e.instanceBuffer.destroy(),e.drawMetadataResource.metadataBuffer.destroy(),e.drawMetadataResource.indirectBuffer.destroy(),e.drawMetadataResource.postIndirectBuffer.destroy(),e.instanceVisibilityResource.instanceMetadataBuffer.destroy(),e.instanceVisibilityResource.visibleInstanceIndicesBuffer.destroy(),e.instanceVisibilityResource.visibleCountsBuffer.destroy(),e.instanceVisibilityResource.postVisibleCountsBuffer.destroy(),e.instanceVisibilityResource.visibleInstanceMaskBuffer.destroy(),e.visibilityParamsBuffer.destroy(),e.postVisibilityParamsBuffer.destroy();for(const t of e.ownedMaterials)t.dispose();e.ownedMaterials.length=0,e.residentInstanceBinding.buffer=null,e.residentInstanceBinding.colorBuffer=null,e.residentInstanceBinding.sceneBindGroup=null,e.residentInstanceBinding.shadowBindGroup=null,e.residentInstanceBinding.shadowBindGroups.clear(),e.visibilityBindGroup=null,e.postVisibilityBindGroup=null,e.visibilityClearBindGroup=null,e.visibilityIndirectBuildBindGroup=null,e.postVisibilityIndirectBuildBindGroup=null,e.visibleSceneBindGroup=null,e.visibleDepthSceneBindGroup=null,e.visibleMaterialBindings.length=0,e.visibleDrawMaterialResources.length=0,e.visibleIndirectSubmissionStreams=null,e.visibleIndirectStreamsSceneBindGroup=null,e.visibleIndirectStreamsSampleCount=-1,e.visibleIndirectStreamsColorFormatsKey="",e.indirectForwardBundleCache.clear(),e.directForwardBundle=null,e.directForwardBundleSceneBindGroup=null,e.depthPrepassBundle=null,e.depthPrepassBundleSceneBindGroup=null,e.indirectDepthPrepassBundles.prepass=null,e.indirectDepthPrepassBundles.postpass=null,e.shadowBundles=new WeakMap,e.depthMaterialResources.clear()}},Di=class{constructor(e,t){this.state=e,this.textureCache=t}state;textureCache;skippedExternalTextureWarnings=new WeakSet;destroyTextureResource(e){e?.texture.destroy()}createTextureSampler(e,t){if(!this.state.device)throw new Error("Renderer is not initialized.");const r="non-filtering"===t,n=r?"nearest":gn(e.magFilter),i=r?"nearest":gn(e.minFilter),a=r?"nearest":gn(e.minFilter),s="comparison"===t?function(e){switch(e){case Br:return"never";case br:return"less";case xr:return"equal";case yr:return"less-equal";case vr:return"greater";case Dr:return"not-equal";case wr:return"greater-equal";case mr:return"always";default:return}}(e.compareFunction):void 0,o=r||"linear"!==n||"linear"!==i||"linear"!==a?1:Math.max(1,e.anisotropy);return this.state.device.createSampler({label:`${e.uuid}-sampler`,addressModeU:mn(e.wrapS),addressModeV:mn(e.wrapT),addressModeW:mn(e.wrapR??e.wrapT),magFilter:n,minFilter:i,mipmapFilter:a,maxAnisotropy:o,compare:s})}uploadDataTextureResource(e,t,r){if(!this.state.device)throw new Error("Renderer is not initialized.");const n=function(e){switch(e){case"r8unorm":case"r8snorm":case"r8uint":case"r8sint":return 1;case"r16uint":case"r16sint":case"r16float":case"rg8unorm":case"rg8snorm":case"rg8uint":case"rg8sint":case"depth16unorm":return 2;case"r32uint":case"r32sint":case"r32float":case"rg16uint":case"rg16sint":case"rg16float":case"rgba8unorm":case"rgba8unorm-srgb":case"rgba8snorm":case"rgba8uint":case"rgba8sint":case"bgra8unorm":case"bgra8unorm-srgb":case"rgb9e5ufloat":case"rgb10a2unorm":case"rg11b10ufloat":case"depth32float":return 4;case"rg32uint":case"rg32sint":case"rg32float":case"rgba16uint":case"rgba16sint":case"rgba16float":return 8;case"rgba32uint":case"rgba32sint":case"rgba32float":return 16;default:return null}}(r.format);if(null===n)throw new Error(`Texture format "${r.format}" from "${e.constructor.name}" cannot be uploaded with queue.writeTexture.`);const i=e.mipmaps;if(i&&i.length>0){for(let e=0;e<i.length;e+=1){const a=i[e];if(!a?.data)continue;const s=a.width??Math.max(1,r.width>>e),o=a.height??Math.max(1,r.height>>e),l=a.depth??r.depthOrArrayLayers;this.state.device.queue.writeTexture({texture:t,mipLevel:e},vn(a.data),{bytesPerRow:s*n,rowsPerImage:o},{width:s,height:o,depthOrArrayLayers:l})}return}const a=e.image;a?.data&&this.state.device.queue.writeTexture({texture:t},a.data,{bytesPerRow:r.width*n,rowsPerImage:r.height},{width:r.width,height:r.height,depthOrArrayLayers:r.depthOrArrayLayers})}uploadCompressedTextureResource(e,t,r){if(!this.state.device)throw new Error("Renderer is not initialized.");const n="bc1-rgba-unorm"===(i=r.format)||"bc1-rgba-unorm-srgb"===i?{byteLength:8,width:4,height:4}:"bc2-rgba-unorm"===i||"bc2-rgba-unorm-srgb"===i||"bc3-rgba-unorm"===i||"bc3-rgba-unorm-srgb"===i?{byteLength:16,width:4,height:4}:"bc4-r-unorm"===i||"bc4-r-snorm"===i?{byteLength:8,width:4,height:4}:"bc5-rg-unorm"===i||"bc5-rg-snorm"===i||"bc6h-rgb-ufloat"===i||"bc6h-rgb-float"===i||"bc7-rgba-unorm"===i||"bc7-rgba-unorm-srgb"===i?{byteLength:16,width:4,height:4}:"etc2-rgb8unorm"===i||"etc2-rgb8unorm-srgb"===i||"etc2-rgb8a1unorm"===i||"etc2-rgb8a1unorm-srgb"===i?{byteLength:8,width:4,height:4}:"etc2-rgba8unorm"===i||"etc2-rgba8unorm-srgb"===i?{byteLength:16,width:4,height:4}:"eac-r11unorm"===i||"eac-r11snorm"===i?{byteLength:8,width:4,height:4}:"eac-rg11unorm"===i||"eac-rg11snorm"===i||"astc-4x4-unorm"===i||"astc-4x4-unorm-srgb"===i?{byteLength:16,width:4,height:4}:"astc-5x4-unorm"===i||"astc-5x4-unorm-srgb"===i?{byteLength:16,width:5,height:4}:"astc-5x5-unorm"===i||"astc-5x5-unorm-srgb"===i?{byteLength:16,width:5,height:5}:"astc-6x5-unorm"===i||"astc-6x5-unorm-srgb"===i?{byteLength:16,width:6,height:5}:"astc-6x6-unorm"===i||"astc-6x6-unorm-srgb"===i?{byteLength:16,width:6,height:6}:"astc-8x5-unorm"===i||"astc-8x5-unorm-srgb"===i?{byteLength:16,width:8,height:5}:"astc-8x6-unorm"===i||"astc-8x6-unorm-srgb"===i?{byteLength:16,width:8,height:6}:"astc-8x8-unorm"===i||"astc-8x8-unorm-srgb"===i?{byteLength:16,width:8,height:8}:"astc-10x5-unorm"===i||"astc-10x5-unorm-srgb"===i?{byteLength:16,width:10,height:5}:"astc-10x6-unorm"===i||"astc-10x6-unorm-srgb"===i?{byteLength:16,width:10,height:6}:"astc-10x8-unorm"===i||"astc-10x8-unorm-srgb"===i?{byteLength:16,width:10,height:8}:"astc-10x10-unorm"===i||"astc-10x10-unorm-srgb"===i?{byteLength:16,width:10,height:10}:"astc-12x10-unorm"===i||"astc-12x10-unorm-srgb"===i?{byteLength:16,width:12,height:10}:"astc-12x12-unorm"===i||"astc-12x12-unorm-srgb"===i?{byteLength:16,width:12,height:12}:null;var i;if(!n)throw new Error(`Compressed texture format "${r.format}" is not supported for upload.`);if(!0===e.isCompressedCubeTexture){const i=e.image;for(let e=0;e<i.length;e+=1){const a=i[e]?.mipmaps??[];for(let i=0;i<a.length;i+=1){const s=a[i];if(!s?.data)continue;const o=s.width??Math.max(1,r.width>>i),l=s.height??Math.max(1,r.height>>i),c=Math.max(1,Math.ceil(o/n.width)),u=Math.max(1,Math.ceil(l/n.height));this.state.device.queue.writeTexture({texture:t,mipLevel:i,origin:{x:0,y:0,z:e}},vn(s.data),{bytesPerRow:c*n.byteLength,rowsPerImage:u},{width:c*n.width,height:u*n.height,depthOrArrayLayers:1})}}return}const a=e.mipmaps;for(let e=0;e<a.length;e+=1){const i=a[e];if(!i?.data)continue;const s=i.width??Math.max(1,r.width>>e),o=i.height??Math.max(1,r.height>>e),l=Math.max(1,Math.ceil(s/n.width)),c=Math.max(1,Math.ceil(o/n.height));this.state.device.queue.writeTexture({texture:t,mipLevel:e},vn(i.data),{bytesPerRow:l*n.byteLength,rowsPerImage:c},{width:l*n.width,height:c*n.height,depthOrArrayLayers:r.depthOrArrayLayers})}}uploadExternalTextureResource(e,t,r){if(!this.state.device)throw new Error("Renderer is not initialized.");if(!0===e.isCubeTexture){const n=e.image;if(!Array.isArray(n)||6!==n.length)return void this.warnSkippedExternalTextureUpload(e,r,"CubeTexture must provide exactly six face images.");for(let i=0;i<n.length;i+=1){const a=xn(n[i]);if(!a)return void this.warnSkippedExternalTextureUpload(e,r,`CubeTexture face ${i} is not a copyable image source.`);try{this.state.device.queue.copyExternalImageToTexture({source:a,flipY:e.flipY},{texture:t,origin:{x:0,y:0,z:i}},{width:r.width,height:r.height,depthOrArrayLayers:1})}catch(t){return void this.warnSkippedExternalTextureUpload(e,r,`CubeTexture face ${i} could not be copied: ${Ti(t)}`)}}return}const n=function(e){return xn(e.image)}(e);if(n)try{this.state.device.queue.copyExternalImageToTexture({source:n,flipY:e.flipY},{texture:t},{width:r.width,height:r.height,depthOrArrayLayers:1})}catch(t){this.warnSkippedExternalTextureUpload(e,r,`copyExternalImageToTexture failed: ${Ti(t)}`)}else this.warnSkippedExternalTextureUpload(e,r,"Texture.image is not an HTML image, canvas, video, ImageBitmap, or OffscreenCanvas.")}warnSkippedExternalTextureUpload(e,t,r){if(this.skippedExternalTextureWarnings.has(e))return;this.skippedExternalTextureWarnings.add(e);const n=e.image;console.warn(`[WebGpuRenderer] Skipped upload for texture "${e.name||e.uuid}"; the WebGPU material remains active and samples a zero-cleared fallback texture. ${r}`,{texture:e,textureClass:e.constructor.name,textureName:e.name||void 0,textureUuid:e.uuid,textureFlags:{isRenderTargetTexture:!0===e.isRenderTargetTexture,isVideoTexture:!0===e.isVideoTexture,isCanvasTexture:!0===e.isCanvasTexture,isCubeTexture:!0===e.isCubeTexture},descriptor:t,image:{className:n?.constructor?.name??typeof n,width:n?.width,height:n?.height,depth:n?.depth,src:n?.currentSrc??n?.src,hasData:null!=n?.data,keys:null==n?[]:Object.keys(n).slice(0,16)},userData:e.userData})}uploadTextureResource(e,t,r){!function(e){return!0===e.isCompressedTexture||!0===e.isCompressedArrayTexture}(e)&&!0!==e.isCompressedCubeTexture?!0!==e.isDataTexture&&!0!==e.isDataArrayTexture&&!0!==e.isData3DTexture?this.uploadExternalTextureResource(e,t,r):this.uploadDataTextureResource(e,t,r):this.uploadCompressedTextureResource(e,t,r)}getTextureResource(e){if(!this.state.device)throw new Error("Renderer is not initialized.");const t=this.textureCache.get(e),r=ve(e,this.state.device);if(t&&t.version===e.version&&t.width===r.width&&t.height===r.height&&t.depthOrArrayLayers===r.depthOrArrayLayers&&t.format===r.format&&t.textureDimension===r.textureDimension&&t.viewDimension===r.viewDimension&&t.sampleType===r.sampleType&&t.samplerBindingType===r.samplerBindingType&&t.mipLevelCount===r.mipLevelCount)return t;this.destroyTextureResource(t);const n=this.state.device.createTexture({label:`${e.uuid}-texture`,size:{width:r.width,height:r.height,depthOrArrayLayers:r.depthOrArrayLayers},dimension:r.textureDimension,format:r.format,mipLevelCount:r.mipLevelCount,usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|(r.compressed||"3d"===r.textureDimension?0:GPUTextureUsage.RENDER_ATTACHMENT)});this.uploadTextureResource(e,n,r);const i=this.createTextureSampler(e,r.samplerBindingType),a={version:e.version,width:r.width,height:r.height,depthOrArrayLayers:r.depthOrArrayLayers,format:r.format,textureDimension:r.textureDimension,viewDimension:r.viewDimension,sampleType:r.sampleType,samplerBindingType:r.samplerBindingType,mipLevelCount:r.mipLevelCount,texture:n,view:n.createView("2d"===r.viewDimension?void 0:"2d-array"===r.viewDimension?{dimension:"2d-array",arrayLayerCount:r.depthOrArrayLayers}:{dimension:r.viewDimension}),sampler:i};return this.textureCache.set(e,a),a}};function Ti(e){return e instanceof Error?e.message:String(e)}var Ii="\nstruct ShadowCameraUniforms {\n viewProj: mat4x4<f32>,\n lightPositionRange: vec4<f32>,\n};\n\nstruct RendererInstanceData {\n model0: vec4<f32>,\n model1: vec4<f32>,\n model2: vec4<f32>,\n model3: vec4<f32>,\n color: vec4<f32>,\n batching: vec4<f32>,\n};\n\nstruct PointShadowVertexOutput {\n @builtin(position) position: vec4<f32>,\n @location(0) worldPosition: vec3<f32>,\n};\n\n@group(0) @binding(0) var<uniform> shadowCamera: ShadowCameraUniforms;\n@group(0) @binding(1) var<storage, read> rendererInstances: array<RendererInstanceData>;\n\nfn rendererInstanceModelMatrix(instanceIndex: u32) -> mat4x4<f32> {\n let instance = rendererInstances[instanceIndex];\n return mat4x4<f32>(instance.model0, instance.model1, instance.model2, instance.model3);\n}\n\n@vertex\nfn vsMain(\n @location(0) position: vec3<f32>,\n @builtin(instance_index) instanceIndex: u32\n) -> PointShadowVertexOutput {\n var output: PointShadowVertexOutput;\n let world = rendererInstanceModelMatrix(instanceIndex) * vec4(position, 1.0);\n output.position = shadowCamera.viewProj * world;\n output.worldPosition = world.xyz;\n return output;\n}\n\n@fragment\nfn fsMain(input: PointShadowVertexOutput) -> @location(0) vec4<f32> {\n let distanceToLight = length(input.worldPosition - shadowCamera.lightPositionRange.xyz);\n let normalizedDepth = clamp(distanceToLight / shadowCamera.lightPositionRange.w, 0.0, 1.0);\n return vec4(normalizedDepth, normalizedDepth, normalizedDepth, 1.0);\n}\n",Gi="\nstruct ShadowCameraUniforms {\n viewProj: mat4x4<f32>,\n lightPositionRange: vec4<f32>,\n};\n\nstruct PointShadowVertexOutput {\n @builtin(position) position: vec4<f32>,\n @location(0) worldPosition: vec3<f32>,\n};\n\n@group(0) @binding(0) var<uniform> shadowCamera: ShadowCameraUniforms;\n@group(0) @binding(1) var<storage, read> rendererInstanceMatrices: array<vec4<f32>>;\n\nfn rendererInstanceModelMatrix(instanceIndex: u32) -> mat4x4<f32> {\n let base = instanceIndex * 4u;\n return mat4x4<f32>(\n rendererInstanceMatrices[base + 0u],\n rendererInstanceMatrices[base + 1u],\n rendererInstanceMatrices[base + 2u],\n rendererInstanceMatrices[base + 3u]\n );\n}\n\n@vertex\nfn vsMain(\n @location(0) position: vec3<f32>,\n @builtin(instance_index) instanceIndex: u32\n) -> PointShadowVertexOutput {\n var output: PointShadowVertexOutput;\n let world = rendererInstanceModelMatrix(instanceIndex) * vec4(position, 1.0);\n output.position = shadowCamera.viewProj * world;\n output.worldPosition = world.xyz;\n return output;\n}\n\n@fragment\nfn fsMain(input: PointShadowVertexOutput) -> @location(0) vec4<f32> {\n let distanceToLight = length(input.worldPosition - shadowCamera.lightPositionRange.xyz);\n let normalizedDepth = clamp(distanceToLight / shadowCamera.lightPositionRange.w, 0.0, 1.0);\n return vec4(normalizedDepth, normalizedDepth, normalizedDepth, 1.0);\n}\n",Ri="\nstruct RendererSkinningUniforms {\n bindMatrix: mat4x4<f32>,\n bindMatrixInverse: mat4x4<f32>,\n};\n\n@group(2) @binding(0) var<storage, read> rendererBoneMatrixColumns: array<vec4<f32>>;\n@group(2) @binding(1) var<uniform> rendererSkinning: RendererSkinningUniforms;\n\nfn rendererBoneMatrix(index: u32) -> mat4x4<f32> {\n let base = index * 4u;\n return mat4x4<f32>(\n rendererBoneMatrixColumns[base + 0u],\n rendererBoneMatrixColumns[base + 1u],\n rendererBoneMatrixColumns[base + 2u],\n rendererBoneMatrixColumns[base + 3u],\n );\n}\n\nfn rendererSkinPosition(position: vec3<f32>, skinIndex: vec4<u32>, skinWeight: vec4<f32>) -> vec3<f32> {\n let boundPosition = rendererSkinning.bindMatrix * vec4(position, 1.0);\n let weightSum = skinWeight.x + skinWeight.y + skinWeight.z + skinWeight.w;\n if (weightSum <= 0.0) {\n return position;\n }\n let skinnedPosition =\n (rendererBoneMatrix(skinIndex.x) * boundPosition) * skinWeight.x +\n (rendererBoneMatrix(skinIndex.y) * boundPosition) * skinWeight.y +\n (rendererBoneMatrix(skinIndex.z) * boundPosition) * skinWeight.z +\n (rendererBoneMatrix(skinIndex.w) * boundPosition) * skinWeight.w;\n let fallbackWeight = max(0.0, 1.0 - weightSum);\n return (rendererSkinning.bindMatrixInverse * (skinnedPosition + boundPosition * fallbackWeight)).xyz;\n}\n",Li=`\nstruct RendererCameraUniforms {\n viewProj: mat4x4<f32>,\n cameraPosition: vec4<f32>,\n viewportAndTime: vec4<f32>,\n view: mat4x4<f32>,\n projection: mat4x4<f32>,\n};\n\nstruct RendererInstanceData {\n model0: vec4<f32>,\n model1: vec4<f32>,\n model2: vec4<f32>,\n model3: vec4<f32>,\n color: vec4<f32>,\n batching: vec4<f32>,\n};\n\n@group(0) @binding(0) var<uniform> rendererCamera: RendererCameraUniforms;\n@group(0) @binding(1) var<uniform> rendererLights: array<vec4<f32>, 11>;\n@group(0) @binding(2) var<storage, read> rendererInstances: array<RendererInstanceData>;\n\n${Ri}\n\nfn rendererInstanceModelMatrix(instanceIndex: u32) -> mat4x4<f32> {\n let instance = rendererInstances[instanceIndex];\n return mat4x4<f32>(instance.model0, instance.model1, instance.model2, instance.model3);\n}\n\n@vertex\nfn vsMain(\n @location(0) position: vec3<f32>,\n @location(1) skinIndex: vec4<u32>,\n @location(2) skinWeight: vec4<f32>,\n @builtin(instance_index) instanceIndex: u32,\n) -> @builtin(position) vec4<f32> {\n let world = rendererInstanceModelMatrix(instanceIndex) * vec4(rendererSkinPosition(position, skinIndex, skinWeight), 1.0);\n return rendererCamera.viewProj * world;\n}\n`,zi=`\nstruct ShadowCameraUniforms {\n viewProj: mat4x4<f32>,\n lightPositionRange: vec4<f32>,\n};\n\nstruct RendererInstanceData {\n model0: vec4<f32>,\n model1: vec4<f32>,\n model2: vec4<f32>,\n model3: vec4<f32>,\n color: vec4<f32>,\n batching: vec4<f32>,\n};\n\n@group(0) @binding(0) var<uniform> shadowCamera: ShadowCameraUniforms;\n@group(0) @binding(1) var<storage, read> rendererInstances: array<RendererInstanceData>;\n\n${Ri}\n\nfn rendererInstanceModelMatrix(instanceIndex: u32) -> mat4x4<f32> {\n let instance = rendererInstances[instanceIndex];\n return mat4x4<f32>(instance.model0, instance.model1, instance.model2, instance.model3);\n}\n\n@vertex\nfn vsMain(\n @location(0) position: vec3<f32>,\n @location(1) skinIndex: vec4<u32>,\n @location(2) skinWeight: vec4<f32>,\n @builtin(instance_index) instanceIndex: u32,\n) -> @builtin(position) vec4<f32> {\n let world = rendererInstanceModelMatrix(instanceIndex) * vec4(rendererSkinPosition(position, skinIndex, skinWeight), 1.0);\n return shadowCamera.viewProj * world;\n}\n`,Ui=`\nstruct ShadowCameraUniforms {\n viewProj: mat4x4<f32>,\n lightPositionRange: vec4<f32>,\n};\n\nstruct RendererInstanceData {\n model0: vec4<f32>,\n model1: vec4<f32>,\n model2: vec4<f32>,\n model3: vec4<f32>,\n color: vec4<f32>,\n batching: vec4<f32>,\n};\n\nstruct PointShadowVertexOutput {\n @builtin(position) position: vec4<f32>,\n @location(0) worldPosition: vec3<f32>,\n};\n\n@group(0) @binding(0) var<uniform> shadowCamera: ShadowCameraUniforms;\n@group(0) @binding(1) var<storage, read> rendererInstances: array<RendererInstanceData>;\n\n${Ri}\n\nfn rendererInstanceModelMatrix(instanceIndex: u32) -> mat4x4<f32> {\n let instance = rendererInstances[instanceIndex];\n return mat4x4<f32>(instance.model0, instance.model1, instance.model2, instance.model3);\n}\n\n@vertex\nfn vsMain(\n @location(0) position: vec3<f32>,\n @location(1) skinIndex: vec4<u32>,\n @location(2) skinWeight: vec4<f32>,\n @builtin(instance_index) instanceIndex: u32,\n) -> PointShadowVertexOutput {\n var output: PointShadowVertexOutput;\n let world = rendererInstanceModelMatrix(instanceIndex) * vec4(rendererSkinPosition(position, skinIndex, skinWeight), 1.0);\n output.position = shadowCamera.viewProj * world;\n output.worldPosition = world.xyz;\n return output;\n}\n\n@fragment\nfn fsMain(input: PointShadowVertexOutput) -> @location(0) vec4<f32> {\n let distanceToLight = length(input.worldPosition - shadowCamera.lightPositionRange.xyz);\n let normalizedDepth = clamp(distanceToLight / shadowCamera.lightPositionRange.w, 0.0, 1.0);\n return vec4(normalizedDepth, normalizedDepth, normalizedDepth, 1.0);\n}\n`,Vi="\nstruct FullscreenVertexOutput {\n @builtin(position) position: vec4<f32>,\n @location(0) uv: vec2<f32>,\n};\n\n@group(0) @binding(0) var sourceSampler: sampler;\n@group(0) @binding(1) var sourceTexture: texture_2d<f32>;\n\n@vertex\nfn vsMain(@builtin(vertex_index) vertexIndex: u32) -> FullscreenVertexOutput {\n var output: FullscreenVertexOutput;\n let position = array<vec2<f32>, 3>(\n vec2(-1.0, -3.0),\n vec2(-1.0, 1.0),\n vec2(3.0, 1.0),\n );\n let clip = position[vertexIndex];\n output.position = vec4(clip, 0.0, 1.0);\n output.uv = clip * vec2(0.5, -0.5) + vec2(0.5, 0.5);\n return output;\n}\n\n@fragment\nfn fsMain(input: FullscreenVertexOutput) -> @location(0) vec4<f32> {\n let linearColor = textureSample(sourceTexture, sourceSampler, input.uv);\n let low = linearColor.rgb * 12.92;\n let high = 1.055 * pow(max(linearColor.rgb, vec3<f32>(0.0)), vec3<f32>(1.0 / 2.4)) - 0.055;\n let srgb = select(high, low, linearColor.rgb <= vec3<f32>(0.0031308));\n return vec4<f32>(srgb, linearColor.a);\n}\n";function Ai(e){if(e.transparent)switch(e.blending){case Qe:return{color:{srcFactor:"src-alpha",dstFactor:"one",operation:"add"},alpha:{srcFactor:"one",dstFactor:"one",operation:"add"}};case pt:return{color:{srcFactor:"zero",dstFactor:"one-minus-src",operation:"subtract"},alpha:{srcFactor:"one",dstFactor:"one",operation:"subtract"}};case ot:return{color:{srcFactor:"zero",dstFactor:"src",operation:"add"},alpha:{srcFactor:"zero",dstFactor:"src-alpha",operation:"add"}};default:return{color:{srcFactor:"src-alpha",dstFactor:"one-minus-src-alpha",operation:"add"},alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"}}}}function Fi(e,t,r,n){if(t<0||e[t]!==r)return-1;let i=0;for(let a=t;a<e.length;a+=1)if(e[a]===r&&(i+=1),e[a]===n&&(i-=1,0===i))return a;return-1}function Ei(e,t,r){const n=function(e,t="fsMain"){const r=e.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/.*$/gm,""),n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),i=new RegExp(`@fragment\\s+fn\\s+${n}\\s*\\(`).exec(r);if(!i)return null;const a=r.indexOf("(",i.index),s=Fi(r,a,"(",")");if(s<0)return null;const o=r.indexOf("{",s+1);if(o<0)return null;const l=r.slice(s+1,o),c=/->\s*@location\s*\(\s*(\d+)\s*\)/.exec(l);if(c)return new Set([Number(c[1])]);const u=/->\s*((?:@\w+(?:\s*\([^)]*\))?\s*)*)([A-Za-z_]\w*)/.exec(l);if(!u)return new Set;const d=u[2].replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),h=new RegExp(`\\bstruct\\s+${d}\\s*\\{`).exec(r);if(!h)return null;const p=r.indexOf("{",h.index),f=Fi(r,p,"{","}");if(f<0)return null;const m=new Set,g=/@location\s*\(\s*(\d+)\s*\)/g,x=r.slice(p+1,f);for(const e of x.matchAll(g))m.add(Number(e[1]));return m}(e);return t.map((e,t)=>null===n||n.has(t)?{format:e,blend:r}:{format:e,writeMask:0})}var ki="chromium-experimental-multi-draw-indirect",Oi=[{name:"position",shaderLocation:0,format:"float32x3"},{name:"normal",shaderLocation:1,format:"float32x3",defaultValue:[0,0,1]},{name:"uv",shaderLocation:2,format:"float32x2",defaultValue:[0,0]},{name:"color",shaderLocation:3,format:"float32x4",defaultValue:[1,1,1,1]},{name:"skinIndex",shaderLocation:4,format:"uint32x4"},{name:"skinWeight",shaderLocation:5,format:"float32x4"}];function $i(e){return e.wireframe&&"triangle-list"===e.primitiveTopology?"line-list":e.primitiveTopology}function ji(e,t,r){if(!$i(e).startsWith("triangle"))return"none";if("directionalShadow"===t){if(r&&null===e.shadowSide)return"none";const t=e.shadowSide??(e.side===et?at:e.side===it?it:et);return t===it?"none":t===et?"front":"back"}return e.side===it?"none":e.side===et?"front":"back"}function Ni(e){if(void 0===e)return 1;if(!Number.isFinite(e)||e<=0||e>1)throw new RangeError("renderScale must be a finite number greater than 0 and at most 1.");return e}var Wi=class{canvas;clearColor;powerPreference;shadowMapSize;pointShadowMapSize;fallbackMaterial;materialResolver;toonOutlineMaterialCache=new WeakMap;fallbackSkinnedMaterial;invokeObjectRenderCallbacks;sampleCount;renderScale;hiZOcclusionCullingEnabled;multiDrawIndirectEnabled;dynamicBatchingEnabled;multiDrawIndirectSupported=!1;renderGraphProfilingEnabled;indirectFirstInstanceSupported=!1;timestampQuerySupported=!1;geometryCache=new WeakMap;skinnedGeometryCache=new Map;skinPaletteCache=new WeakMap;skinPaletteResources=new Set;meshExtractionCache=new WeakMap;resolvedMaterialFrameCache=new WeakMap;instancedMeshExtractionCache=new WeakMap;batchedMeshExtractionCache=new WeakMap;materialCache=new WeakMap;skinnedMaterialCache=new WeakMap;materialCacheVisible=new WeakMap;materialCacheDirect=new WeakMap;materialNoReceiveShadowCache=new WeakMap;skinnedMaterialNoReceiveShadowCache=new WeakMap;materialNoReceiveShadowCacheVisible=new WeakMap;materialNoReceiveShadowCacheDirect=new WeakMap;depthPrepassMaterialCache=new WeakMap;directionalShadowMaterialCache=new WeakMap;skinnedDirectionalShadowMaterialCache=new WeakMap;directionalShadowMaterialCacheDirect=new WeakMap;lineMaterialCache=new WeakMap;lineBasicMaterialCache=new WeakMap;lineProxyCache=new WeakMap;spriteProxyCache=new WeakMap;depthMaterialFrameCache=new WeakMap;forwardMaterialFastCache=new WeakMap;forwardMaterialTargetFastCache=new WeakMap;forwardMaterialFrameCache=new WeakMap;depthMaterialFastCache=new WeakMap;sharedForwardPipelineCache=new Map;sharedForwardPipelinePromiseCache=new Map;sharedDepthPipelineCache=new Map;sharedDepthPipelinePromiseCache=new Map;state=function(){return{device:null,context:null,format:null,mainDepthTexture:null,mainDepthView:null,sceneColorTexture:null,sceneColorView:null,sceneColorSnapshotTexture:null,sceneColorSnapshotView:null,sceneDepthSnapshotTexture:null,sceneDepthSnapshotView:null,postProcessColorTexture:null,postProcessColorView:null,cameraBuffer:null,lightBuffer:null,shadowCameraBuffer:null,shadowCameraBufferPool:[],sharedShadowBindGroupByCameraBuffer:new Map,instanceBuffer:null,instanceBufferSize:0,drawMetadataResource:null,sharedSceneBindGroup:null,sharedShadowBindGroup:null,indirectForwardBundleCache:new Map,directForwardBundleCache:new Map,sceneBindGroupLayout:null,directSceneBindGroupLayout:null,visibleSceneBindGroupLayout:null,visibleDepthSceneBindGroupLayout:null,shadowBindGroupLayout:null,directShadowBindGroupLayout:null,emptyBindGroupLayout:null,skinningBindGroupLayout:null,sceneTextureBindGroupLayout:null,sceneTextureBindGroup:null,shadowComparisonSampler:null,linearClampSampler:null,nearestClampSampler:null,fullscreenTextureBindGroupLayout:null,directionalShadowTexture:null,directionalShadowView:null,directionalShadowLayerViews:[],pointShadowTexture:null,pointShadowArrayView:null,pointShadowFaceViews:[],pointShadowDepthTexture:null,pointShadowDepthFaceViews:[],spotShadowTexture:null,spotShadowView:null,spotShadowLayerViews:[],hizTexture:null,hizView:null,hizMipViews:[],hizCopyBindGroup:null,hizReduceBindGroups:[],visibilityBindGroup:null,visibilityBindGroupMetadataResource:null,presentBindGroups:new WeakMap,hizMipCount:1,temporalHiZHistoryValid:!1,temporalVisibilityBuffer:null,visibilityParamsBuffer:null,hizCopyKernel:null,hizReduceKernel:null,visibilityKernel:null,staticVisibilityClearKernel:null,staticVisibilityCullKernel:null,staticVisibilityIndirectBuildKernel:null,depthPrepassPipeline:null,depthPrepassPipelineVisible:null,depthPrepassPipelineDirect:null,skinnedDepthPrepassPipeline:null,shadowDepthPipeline:null,shadowDepthPipelineDirect:null,skinnedShadowDepthPipeline:null,pointShadowPipeline:null,pointShadowPipelineDirect:null,skinnedPointShadowPipeline:null,presentPipeline:null,pixelRatio:1,width:1,height:1,presentationWidth:1,presentationHeight:1,frameTimeSeconds:0,frameIndex:0,directionalShadowTextureSize:1,pointShadowTextureSize:1,spotShadowTextureSize:1,latestFrameProfile:null,latestCompletedFrameProfile:null,residentSceneBindGroupVersion:0,residentShadowBindGroupVersion:0,initialized:!1}}();textureCache=new WeakMap;graphTextureBindGroupCache=new WeakMap;materialGraphTextureReadCache=new WeakMap;defaultInstanceAttributeBuffers=new Map;textureManager=new Di(this.state,this.textureCache);renderGraph=new qt;directionalShadowCameras=Array.from({length:4},()=>new ut(-10,10,10,-10,.1,80));pointShadowCameras=Array.from({length:4},()=>$r.map(()=>new dt(90,1,.1,25)));spotShadowCameras=Array.from({length:4},()=>new dt(60,1,.5,500));colorTargetCache=new Map;msaaColorTargetCache=new Map;msaaDepthTargetCache=new Map;sourceInstanceDataScratch=new Mi(4096);opaqueInstanceDataScratch=new Mi(4096);finalInstanceDataScratch=new Mi(4096);residentInstanceUploadsScratch=[];gpuOpaqueDrawsScratch=[];directOpaqueDrawsScratch=[];stagedOpaqueDrawsScratch=[];residentOpaqueDrawsScratch=[];retiredGeometryResources=[];retiredGeometryBuffers=[];vertexAttributeBufferKeyCache=new WeakMap;standardVertexAttributeCache=new WeakMap;geometryVertexBufferFastCache=new WeakMap;vertexAttributeGroupCache=new WeakMap;vertexAttributeGroupBufferKeyCache=new WeakMap;compileDrawScratch=[];indirectSubmissionStreamsScratch=[];renderBundleScratch=[];directBundleDrawStatsScratch={drawCallCount:0,triangleCount:0};sortedOpaqueBatchesScratch=[];opaqueBatchPool=[];opaqueBatchPoolCount=0;drawCallPool=[];drawCallPoolCount=0;staticDrawSets=[];materialPassStaticBundleCache=new WeakMap;staticDrawSetManager=new Bi(this.state,this.staticDrawSets,e=>this.getGeometryResource(e),e=>this.resolveMaterial(e),(e,t)=>this.ensureWireframeIndex(e,t));staticFrameToken=0;hizResourceVersion=0;graphTextureResourceVersion=0;visibilityParamsUpload=new Uint32Array(4);drawMetadataUpload=new Float32Array(0);indirectDrawUpload=new Uint32Array(0);extractedAmbientScratch=new gt;extractedHemisphereScratch=this.createExtractedHemisphereLightScratch();extractedBoundsMinScratch=new mt;extractedBoundsMaxScratch=new mt;extractedDirectionalLightsScratch=Array.from({length:4},()=>this.createExtractedDirectionalLightScratch());extractedPointLightsScratch=Array.from({length:4},()=>this.createExtractedPointLightScratch());extractedSpotLightsScratch=Array.from({length:4},()=>this.createExtractedSpotLightScratch());activeDirectionalLightsScratch=[];activePointLightsScratch=[];activeSpotLightsScratch=[];resolvedMeshMaterialsScratch=[];extractedLightsScratch={ambient:this.extractedAmbientScratch,hemisphere:null,directionals:this.activeDirectionalLightsScratch,points:this.activePointLightsScratch,spots:this.activeSpotLightsScratch,directional:null,point:null,spot:null};extractedFrameScratch={scene:null,camera:null,gpuOpaqueDraws:this.gpuOpaqueDrawsScratch,directOpaqueDraws:this.directOpaqueDrawsScratch,transparentDraws:[],instanceData:this.finalInstanceDataScratch,residentInstanceUploads:this.residentInstanceUploadsScratch,lights:this.extractedLightsScratch,boundsMin:this.extractedBoundsMinScratch,boundsMax:this.extractedBoundsMaxScratch};cameraUniformScratch=new Float32Array(68);temporalVisibilityUniformScratch=new Float32Array(44);lightUniformScratch=new Float32Array(396);csmCascadeRanges=Array.from({length:4},()=>new ft);csmCascadeCount=0;csmCascadeLights=[];shadowCameraUniformScratch=new Float32Array(64);cameraViewProjScratch=new lt;cameraProjectionScratch=new lt;projectionJitterPixels=new ft;temporalVisibilityCurrentViewProj=new lt;temporalVisibilityPreviousViewProj=new lt;cameraFrustumPlanesScratch=new Float32Array(24);objectTraversalStackScratch=[];isSphereVisibleScratch=(e,t,r,n,i)=>!i||function(e,t,r,n,i){const a=-i;for(let i=0;i<24;i+=4)if(e[i+0]*t+e[i+1]*r+e[i+2]*n+e[i+3]<a)return!1;return!0}(this.cameraFrustumPlanesScratch,e,t,r,n);updateExtractedBoundsFromMatrixScratch=e=>{const t=this.extractedBoundsMinScratch,r=this.extractedBoundsMaxScratch,n=e[12],i=e[13],a=e[14];n<t.x&&(t.x=n),i<t.y&&(t.y=i),a<t.z&&(t.z=a),n>r.x&&(r.x=n),i>r.y&&(r.y=i),a>r.z&&(r.z=a)};transparentSortCameraPositionScratch=new mt;transparentSortCameraForwardScratch=new mt;temporalVisibilityCurrentCameraPosition=new mt;temporalVisibilityPreviousCameraPosition=new mt;shadowViewProjScratch=new lt;extractionVersion=0;graphBuilder=(e,t)=>{t.addDirectionalShadowPass(),t.addPointShadowPass(),t.addSpotShadowPass(),t.addDepthPrepass(),t.addHiZPasses(),t.addVisibilityPass(),t.addForwardPass(),t.addPresentPass()};createExtractedDirectionalLightScratch(){return{sourceLight:null,position:new mt,target:new mt,direction:new mt,color:new mt,intensity:0,castShadow:!1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowIntensity:1,shadowMapSize:this.shadowMapSize,shadowCameraLeft:-5,shadowCameraRight:5,shadowCameraTop:5,shadowCameraBottom:-5,shadowCameraNear:.5,shadowCameraFar:500}}createExtractedHemisphereLightScratch(){return{direction:new mt(0,1,0),skyColor:new mt,groundColor:new mt,intensity:0}}createExtractedPointLightScratch(){return{position:new mt,color:new mt,intensity:0,range:25,castShadow:!1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowIntensity:1,shadowMapSize:this.pointShadowMapSize,shadowCameraNear:.5,shadowCameraFar:500}}createExtractedSpotLightScratch(){return{position:new mt,direction:new mt(0,-1,0),color:new mt,intensity:0,range:500,angle:Math.PI/3,penumbra:0,decay:2,castShadow:!1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowIntensity:1,shadowMapSize:this.shadowMapSize,shadowCameraNear:.5,shadowCameraFar:500,shadowCameraFov:60}}constructor(e){this.canvas=e.canvas,this.clearColor=[...e.clearColor??[.02,.05,.11,1]],this.powerPreference=e.powerPreference,this.shadowMapSize=e.shadowMapSize??2048,this.pointShadowMapSize=e.pointShadowMapSize??1024,this.fallbackMaterial=e.fallbackMaterial??null,this.materialResolver=e.materialResolver,this.fallbackSkinnedMaterial=e.fallbackSkinnedMaterial??new kt({vertexShader:"\nstruct VertexInput {\n @location(0) position: vec3<f32>,\n @location(1) normal: vec3<f32>,\n @location(2) uv: vec2<f32>,\n @location(3) color: vec4<f32>,\n @location(4) skinIndex: vec4<u32>,\n @location(5) skinWeight: vec4<f32>,\n @builtin(instance_index) instanceIndex: u32,\n};\n\nstruct VertexOutput {\n @builtin(position) position: vec4<f32>,\n @location(0) worldNormal: vec3<f32>,\n};\n\n@vertex\nfn vsMain(input: VertexInput) -> VertexOutput {\n var output: VertexOutput;\n let skinnedPosition = rendererSkinPosition(input.position, input.skinIndex, input.skinWeight);\n let skinnedNormal = rendererSkinNormal(input.normal, input.skinIndex, input.skinWeight);\n output.position = rendererClipPosition(skinnedPosition, input.instanceIndex);\n output.worldNormal = rendererWorldNormal(skinnedNormal, input.instanceIndex);\n return output;\n}\n",fragmentShader:"\nstruct VertexOutput {\n @builtin(position) position: vec4<f32>,\n @location(0) worldNormal: vec3<f32>,\n};\n\n@fragment\nfn fsMain(input: VertexOutput) -> @location(0) vec4<f32> {\n let normal = normalize(input.worldNormal);\n let diffuse = max(dot(normal, normalize(rendererDirectionalLightDirection())), 0.0);\n let lighting = rendererIndirectDiffuse(normal) + rendererDirectionalLightColor() * diffuse;\n return vec4<f32>(vec3<f32>(0.72, 0.76, 0.82) * lighting, 1.0);\n}\n",vertexAttributes:Oi}),this.invokeObjectRenderCallbacks=e.invokeObjectRenderCallbacks??!0,this.state.directionalShadowTextureSize=this.shadowMapSize,this.state.pointShadowTextureSize=this.pointShadowMapSize,this.state.spotShadowTextureSize=this.shadowMapSize,this.sampleCount=$n(e.sampleCount),this.renderScale=Ni(e.renderScale),this.hiZOcclusionCullingEnabled=e.hiZOcclusionCulling??!1,this.multiDrawIndirectEnabled=e.multiDrawIndirect??!0,this.dynamicBatchingEnabled=e.dynamicBatching??!0,this.renderGraphProfilingEnabled=e.renderGraphProfiling??!1}resolveMaterial(e){if(!1===e?.visible)return null;if(e&&Ot(e))return e;if(!e)return this.fallbackMaterial;if(!0===e.isLineMaterial)return this.resolveLineMaterial(e);const t=this.resolvedMaterialFrameCache.get(e);if(t?.extractionVersion===this.extractionVersion)return t.material;let r=e.transparent||function(e){if(e.transparent)return!0;if(e instanceof xt)return null!=e.uniforms.hology_depth_map||null!=e.uniforms.hology_scene_map;if(e instanceof kt)return e.requiresLatePass();return!1}(e)?"late":"opaque",n=this.materialResolver?.(e,r);"opaque"===r&&n?.requiresLatePass()&&(r="late",n=this.materialResolver?.(e,r));const i=void 0===n?this.fallbackMaterial:n;return this.resolvedMaterialFrameCache.set(e,{extractionVersion:this.extractionVersion,material:i}),void 0!==n?n:i}resolveLineMaterial(e){let t=this.lineMaterialCache.get(e);t||(t=new kt({vertexShader:"\nstruct VertexInput {\n @location(0) position: vec3<f32>,\n @location(4) instanceStart: vec3<f32>,\n @location(5) instanceEnd: vec3<f32>,\n @builtin(instance_index) instanceIndex: u32,\n};\n\nstruct VertexOutput {\n @builtin(position) position: vec4<f32>,\n @location(0) color: vec4<f32>,\n};\n\n@vertex\nfn vsMain(input: VertexInput) -> VertexOutput {\n var output: VertexOutput;\n let start = rendererCamera.view * rendererWorldPosition(input.instanceStart, input.instanceIndex);\n let end = rendererCamera.view * rendererWorldPosition(input.instanceEnd, input.instanceIndex);\n let clipStart = rendererCamera.projection * start;\n let clipEnd = rendererCamera.projection * end;\n let ndcStart = clipStart.xy / clipStart.w;\n let ndcEnd = clipEnd.xy / clipEnd.w;\n let aspect = rendererCamera.viewportAndTime.x / max(rendererCamera.viewportAndTime.y, 1.0);\n var direction = ndcEnd - ndcStart;\n direction.x *= aspect;\n direction = normalize(select(vec2<f32>(1.0, 0.0), direction, length(direction) > 0.00001));\n var offset = vec2<f32>(direction.y, -direction.x);\n direction.x /= aspect;\n offset.x /= aspect;\n if (input.position.x < 0.0) { offset = -offset; }\n if (input.position.y < 0.0) {\n offset -= direction;\n } else if (input.position.y > 1.0) {\n offset += direction;\n }\n offset *= materialUniforms.linewidth / max(rendererCamera.viewportAndTime.y, 1.0);\n var clip = select(clipEnd, clipStart, input.position.y < 0.5);\n clip.xy += offset * clip.w;\n output.position = clip;\n output.color = vec4<f32>(materialUniforms.color, materialUniforms.opacity);\n return output;\n}\n",fragmentShader:"\nstruct FragmentInput {\n @builtin(position) position: vec4<f32>,\n @location(0) color: vec4<f32>,\n};\n\n@fragment\nfn fsMain(input: FragmentInput) -> @location(0) vec4<f32> {\n return input.color;\n}\n",uniforms:{color:new nt(1,1,1),opacity:1,linewidth:1},vertexAttributes:[{name:"position",shaderLocation:0,format:"float32x3"},{name:"instanceStart",shaderLocation:4,format:"float32x3",stepMode:"instance"},{name:"instanceEnd",shaderLocation:5,format:"float32x3",stepMode:"instance"}],transparent:!0,side:it,depthTest:e.depthTest,depthWrite:e.depthWrite}),this.lineMaterialCache.set(e,t));const r=e,n=r.color;return n&&t.uniforms.color.value.copy(n),t.uniforms.opacity.value=r.opacity??1,t.uniforms.linewidth.value=r.linewidth??1,t.transparent=e.transparent||(r.opacity??1)<1,t.depthTest=e.depthTest,t.depthWrite=e.depthWrite,t}resolveLineBasicMaterial(e,t){let r=this.lineBasicMaterialCache.get(e);r||(r=new Map,this.lineBasicMaterialCache.set(e,r));let n=r.get(t);n||(n=new kt({vertexShader:"\nstruct VertexInput {\n @location(0) position: vec3<f32>,\n @builtin(instance_index) instanceIndex: u32,\n};\nstruct VertexOutput {\n @builtin(position) position: vec4<f32>,\n};\n@vertex\nfn vsMain(input: VertexInput) -> VertexOutput {\n return VertexOutput(rendererClipPosition(input.position, input.instanceIndex));\n}\n",fragmentShader:"\n@fragment\nfn fsMain() -> @location(0) vec4<f32> {\n return vec4<f32>(materialUniforms.color, materialUniforms.opacity);\n}\n",uniforms:{color:new nt(1,1,1),opacity:1},primitiveTopology:t,depthTest:e.depthTest,depthWrite:e.depthWrite}),r.set(t,n));const i=e;return i.color&&n.uniforms.color.value.copy(i.color),n.uniforms.opacity.value=i.opacity??1,n.transparent=e.transparent||(i.opacity??1)<1,n.depthTest=e.depthTest,n.depthWrite=e.depthWrite,n}resolveSkinnedMaterial(e){const t=this.resolveMaterial(e);return null===t?null:function(e){const t=e.vertexAttributes.find(e=>"skinIndex"===e.name),r=e.vertexAttributes.find(e=>"skinWeight"===e.name);return e.vertexShader.includes("USE_SKINNING")||"uint32x4"===t?.format&&"float32x4"===r?.format&&e.vertexShader.includes("rendererSkinPosition(")}(t)?t:this.fallbackSkinnedMaterial}hasRenderCallbacks(e){return null!==e&&this.invokeObjectRenderCallbacks&&function(e){return null!==e&&(e.onBeforeRender!==Tr.prototype.onBeforeRender||e.onAfterRender!==Tr.prototype.onAfterRender)}(e)}async initialize(){if(!("gpu"in navigator))throw new Error("WebGPU is not available in this browser.");const e=await navigator.gpu.requestAdapter({powerPreference:this.powerPreference});if(!e)throw new Error("A WebGPU adapter could not be created.");const t=[];e.features.has("indirect-first-instance")&&t.push("indirect-first-instance"),e.features.has("timestamp-query")&&t.push("timestamp-query"),e.features.has("texture-compression-bc")&&t.push("texture-compression-bc"),e.features.has("texture-compression-etc2")&&t.push("texture-compression-etc2"),e.features.has("texture-compression-astc")&&t.push("texture-compression-astc"),e.features.has("float32-filterable")&&t.push("float32-filterable"),e.features.has(ki)&&t.push(ki);const r=e.limits;if(this.state.device=await e.requestDevice({requiredFeatures:t,requiredLimits:{maxTextureArrayLayers:r.maxTextureArrayLayers,maxBufferSize:r.maxBufferSize,maxStorageBufferBindingSize:r.maxStorageBufferBindingSize}}),this.state.device.addEventListener("uncapturederror",e=>{console.error("Uncaptured WebGPU device error",e)}),this.indirectFirstInstanceSupported=t.includes("indirect-first-instance"),this.timestampQuerySupported=t.includes("timestamp-query"),this.multiDrawIndirectSupported=t.includes(ki),this.state.context=this.canvas.getContext("webgpu"),!this.state.context)throw new Error("The canvas does not provide a WebGPU context.");this.state.format=navigator.gpu.getPreferredCanvasFormat(),this.state.context.configure({device:this.state.device,format:this.state.format,alphaMode:"premultiplied"}),this.state.cameraBuffer=this.state.device.createBuffer({label:"renderer-camera-buffer",size:272,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this.state.temporalVisibilityBuffer=this.state.device.createBuffer({label:"renderer-temporal-visibility-buffer",size:176,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this.state.lightBuffer=this.state.device.createBuffer({label:"renderer-light-buffer",size:1584,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this.state.shadowCameraBuffer=this.state.device.createBuffer({label:"renderer-shadow-camera-buffer",size:256,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this.state.sceneBindGroupLayout=this.state.device.createBindGroupLayout({label:"renderer-scene-layout",entries:[{binding:0,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}},{binding:1,visibility:GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}},{binding:2,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"read-only-storage"}},{binding:3,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"comparison"}},{binding:4,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"depth",viewDimension:"2d-array"}},{binding:5,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}},{binding:6,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float",viewDimension:"2d-array"}},{binding:7,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"depth",viewDimension:"2d-array"}}]}),this.state.directSceneBindGroupLayout=this.state.device.createBindGroupLayout({label:"renderer-direct-scene-layout",entries:[{binding:0,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}},{binding:1,visibility:GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}},{binding:2,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"read-only-storage"}},{binding:3,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"read-only-storage"}},{binding:4,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"comparison"}},{binding:5,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"depth",viewDimension:"2d-array"}},{binding:6,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}},{binding:7,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float",viewDimension:"2d-array"}},{binding:8,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"depth",viewDimension:"2d-array"}}]}),this.state.visibleSceneBindGroupLayout=this.state.device.createBindGroupLayout({label:"renderer-visible-scene-layout",entries:[{binding:0,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}},{binding:1,visibility:GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}},{binding:2,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"read-only-storage"}},{binding:3,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"comparison"}},{binding:4,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"depth",viewDimension:"2d-array"}},{binding:5,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}},{binding:6,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float",viewDimension:"2d-array"}},{binding:7,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"depth",viewDimension:"2d-array"}},{binding:8,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"read-only-storage"}}]}),this.state.visibleDepthSceneBindGroupLayout=this.state.device.createBindGroupLayout({label:"renderer-visible-depth-scene-layout",entries:[{binding:0,visibility:GPUShaderStage.VERTEX,buffer:{type:"uniform"}},{binding:2,visibility:GPUShaderStage.VERTEX,buffer:{type:"read-only-storage"}},{binding:3,visibility:GPUShaderStage.VERTEX,buffer:{type:"read-only-storage"}}]}),this.state.shadowBindGroupLayout=this.state.device.createBindGroupLayout({label:"renderer-shadow-layout",entries:[{binding:0,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}},{binding:1,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"read-only-storage"}}]}),this.state.directShadowBindGroupLayout=this.state.device.createBindGroupLayout({label:"renderer-direct-shadow-layout",entries:[{binding:0,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}},{binding:1,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"read-only-storage"}},{binding:2,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"read-only-storage"}}]}),this.state.emptyBindGroupLayout=this.state.device.createBindGroupLayout({label:"renderer-empty-layout",entries:[]}),this.state.skinningBindGroupLayout=this.state.device.createBindGroupLayout({label:"renderer-skinning-layout",entries:[{binding:0,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"read-only-storage"}},{binding:1,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}}]}),this.state.sceneTextureBindGroupLayout=this.state.device.createBindGroupLayout({label:"renderer-scene-texture-layout",entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}},{binding:1,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float"}},{binding:2,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"non-filtering"}},{binding:3,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"depth"}}]}),this.state.residentSceneBindGroupVersion+=1,this.state.residentShadowBindGroupVersion+=1,this.state.fullscreenTextureBindGroupLayout=this.state.device.createBindGroupLayout({label:"renderer-fullscreen-texture-layout",entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}},{binding:1,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float"}}]}),this.state.shadowComparisonSampler=this.state.device.createSampler({label:"renderer-shadow-comparison-sampler",compare:"less-equal",magFilter:"linear",minFilter:"linear",addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge"}),this.state.linearClampSampler=this.state.device.createSampler({label:"renderer-linear-clamp-sampler",magFilter:"linear",minFilter:"linear",addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge",addressModeW:"clamp-to-edge"}),this.state.nearestClampSampler=this.state.device.createSampler({label:"renderer-nearest-clamp-sampler",magFilter:"nearest",minFilter:"nearest",mipmapFilter:"nearest",addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge",addressModeW:"clamp-to-edge"}),this.state.hizCopyKernel=this.createComputeKernel({label:"renderer-hiz-copy",code:"\n@group(0) @binding(0) var sourceDepth: texture_depth_2d;\n@group(0) @binding(1) var targetMip: texture_storage_2d<r32float, write>;\n\n@compute @workgroup_size(8, 8, 1)\nfn main(@builtin(global_invocation_id) globalId: vec3<u32>) {\n let dims = textureDimensions(targetMip);\n if (globalId.x >= dims.x || globalId.y >= dims.y) {\n return;\n }\n\n let depthValue = textureLoad(sourceDepth, vec2<i32>(globalId.xy), 0);\n textureStore(targetMip, vec2<i32>(globalId.xy), vec4(depthValue, 0.0, 0.0, 1.0));\n}\n",bindGroupLayoutEntries:[{binding:0,visibility:GPUShaderStage.COMPUTE,texture:{sampleType:"depth"}},{binding:1,visibility:GPUShaderStage.COMPUTE,storageTexture:{access:"write-only",format:"r32float"}}]}),this.state.hizReduceKernel=this.createComputeKernel({label:"renderer-hiz-reduce",code:"\n@group(0) @binding(0) var sourceMip: texture_2d<f32>;\n@group(0) @binding(1) var targetMip: texture_storage_2d<r32float, write>;\n\nfn readSource(coord: vec2<i32>, dims: vec2<i32>) -> f32 {\n let clamped = clamp(coord, vec2(0, 0), dims - vec2(1, 1));\n return textureLoad(sourceMip, clamped, 0).r;\n}\n\n@compute @workgroup_size(8, 8, 1)\nfn main(@builtin(global_invocation_id) globalId: vec3<u32>) {\n let outDims = textureDimensions(targetMip);\n if (globalId.x >= outDims.x || globalId.y >= outDims.y) {\n return;\n }\n\n let srcOrigin = vec2<i32>(globalId.xy * 2u);\n let srcDims = vec2<i32>(textureDimensions(sourceMip));\n // This renderer uses conventional depth (near = 0, far = 1). Keep the\n // farthest depth in each footprint so an object is rejected only when the\n // whole footprint is covered by closer geometry. A min reduction would let\n // a single nearby texel occlude an otherwise visible object.\n var reduced = max(\n max(readSource(srcOrigin, srcDims), readSource(srcOrigin + vec2(1, 0), srcDims)),\n max(readSource(srcOrigin + vec2(0, 1), srcDims), readSource(srcOrigin + vec2(1, 1), srcDims))\n );\n\n // WebGPU mip dimensions round down. When a source dimension is odd, fold\n // its otherwise-unrepresented final row/column into the last destination\n // texel so no depth coverage disappears from the hierarchy.\n let hasExtraColumn = (srcDims.x & 1) != 0 && globalId.x + 1u == outDims.x;\n let hasExtraRow = (srcDims.y & 1) != 0 && globalId.y + 1u == outDims.y;\n if (hasExtraColumn) {\n reduced = max(reduced, readSource(srcOrigin + vec2(2, 0), srcDims));\n reduced = max(reduced, readSource(srcOrigin + vec2(2, 1), srcDims));\n }\n if (hasExtraRow) {\n reduced = max(reduced, readSource(srcOrigin + vec2(0, 2), srcDims));\n reduced = max(reduced, readSource(srcOrigin + vec2(1, 2), srcDims));\n }\n if (hasExtraColumn && hasExtraRow) {\n reduced = max(reduced, readSource(srcOrigin + vec2(2, 2), srcDims));\n }\n\n textureStore(targetMip, vec2<i32>(globalId.xy), vec4(reduced, 0.0, 0.0, 1.0));\n}\n",bindGroupLayoutEntries:[{binding:0,visibility:GPUShaderStage.COMPUTE,texture:{sampleType:"unfilterable-float"}},{binding:1,visibility:GPUShaderStage.COMPUTE,storageTexture:{access:"write-only",format:"r32float"}}]}),this.state.visibilityKernel=this.createComputeKernel({label:"renderer-visibility-cull",code:"\nstruct RendererCameraUniforms {\n viewProj: mat4x4<f32>,\n cameraPosition: vec4<f32>,\n viewportAndTime: vec4<f32>,\n};\n\nstruct RendererVisibilityParams {\n drawCount: u32,\n hizMipCount: u32,\n reserved0: u32,\n reserved1: u32,\n};\n\nstruct DrawMetadata {\n centerRadius: vec4<f32>,\n args0: vec4<f32>,\n extra: vec4<f32>,\n};\n\nstruct IndirectIndexedArgs {\n indexCount: u32,\n instanceCount: u32,\n firstIndex: u32,\n baseVertex: i32,\n firstInstance: u32,\n};\n\n@group(0) @binding(0) var<uniform> rendererCamera: RendererCameraUniforms;\n@group(0) @binding(1) var<uniform> visibilityParams: RendererVisibilityParams;\n@group(0) @binding(2) var drawMetaTextureSampler: sampler;\n@group(0) @binding(3) var hizTexture: texture_2d<f32>;\n@group(0) @binding(4) var<storage, read> drawMetadata: array<DrawMetadata>;\n@group(0) @binding(5) var<storage, read_write> indirectArgs: array<IndirectIndexedArgs>;\n\nfn saturate(value: f32) -> f32 {\n return clamp(value, 0.0, 1.0);\n}\n\nfn projectedSphereRadius(\n viewProj: mat4x4<f32>,\n ndc: vec3<f32>,\n clipW: f32,\n radius: f32,\n) -> vec2<f32> {\n // Account for both numerator and perspective-denominator variation over the\n // sphere. Offsetting along world X/Y is not conservative once the camera is\n // rotated because those axes can also change clip W.\n let rowX = vec3(viewProj[0].x, viewProj[1].x, viewProj[2].x);\n let rowY = vec3(viewProj[0].y, viewProj[1].y, viewProj[2].y);\n let rowW = vec3(viewProj[0].w, viewProj[1].w, viewProj[2].w);\n let denominator = max(clipW - radius * length(rowW), 0.0001);\n return radius * vec2(\n length(rowX) + abs(ndc.x) * length(rowW),\n length(rowY) + abs(ndc.y) * length(rowW),\n ) / denominator;\n}\n\nfn spherePlaneRadius(viewProj: mat4x4<f32>, plane: vec4<f32>, radius: f32) -> f32 {\n let worldNormal = vec3(\n dot(viewProj[0], plane),\n dot(viewProj[1], plane),\n dot(viewProj[2], plane),\n );\n return radius * length(worldNormal);\n}\n\nfn isSphereInFrustum(viewProj: mat4x4<f32>, center: vec3<f32>, radius: f32) -> bool {\n let clip = viewProj * vec4(center, 1.0);\n return\n clip.w + clip.x >= -spherePlaneRadius(viewProj, vec4( 1.0, 0.0, 0.0, 1.0), radius) &&\n clip.w - clip.x >= -spherePlaneRadius(viewProj, vec4(-1.0, 0.0, 0.0, 1.0), radius) &&\n clip.w + clip.y >= -spherePlaneRadius(viewProj, vec4( 0.0, 1.0, 0.0, 1.0), radius) &&\n clip.w - clip.y >= -spherePlaneRadius(viewProj, vec4( 0.0, -1.0, 0.0, 1.0), radius) &&\n clip.z >= -spherePlaneRadius(viewProj, vec4(0.0, 0.0, 1.0, 0.0), radius) &&\n clip.w - clip.z >= -spherePlaneRadius(viewProj, vec4(0.0, 0.0, -1.0, 1.0), radius);\n}\n\nfn nearestSphereDepth(viewProj: mat4x4<f32>, clip: vec4<f32>, radius: f32) -> f32 {\n let rowZ = vec3(viewProj[0].z, viewProj[1].z, viewProj[2].z);\n let rowW = vec3(viewProj[0].w, viewProj[1].w, viewProj[2].w);\n let minClipZ = clip.z - radius * length(rowZ);\n let maxClipW = clip.w + radius * length(rowW);\n return max(0.0, minClipZ / max(maxClipW, 0.0001));\n}\n\n@compute @workgroup_size(64, 1, 1)\nfn main(@builtin(global_invocation_id) globalId: vec3<u32>) {\n let drawIndex = globalId.x;\n if (drawIndex >= visibilityParams.drawCount) {\n return;\n }\n\n let drawData = drawMetadata[drawIndex];\n let center = vec4(drawData.centerRadius.xyz, 1.0);\n let radius = drawData.centerRadius.w;\n var visible = isSphereInFrustum(\n rendererCamera.viewProj,\n drawData.centerRadius.xyz,\n radius,\n );\n\n let clip = rendererCamera.viewProj * center;\n let cameraDistance = distance(drawData.centerRadius.xyz, rendererCamera.cameraPosition.xyz);\n // A sphere that intersects the near plane, surrounds the camera, or has a\n // very large projected extent cannot be safely represented by its center.\n // Keep it rather than allowing a false negative to remove large terrain or\n // nearby geometry.\n let clipWRadius = radius * length(vec3(\n rendererCamera.viewProj[0].w,\n rendererCamera.viewProj[1].w,\n rendererCamera.viewProj[2].w,\n ));\n let needsConservativeVisibility =\n clip.w - clipWRadius <= 0.0001 || radius >= cameraDistance * 0.1;\n\n if (!needsConservativeVisibility) {\n let ndc = clip.xyz / clip.w;\n let projectedRadius = projectedSphereRadius(rendererCamera.viewProj, ndc, clip.w, radius);\n let clipRadiusX = projectedRadius.x;\n let clipRadiusY = projectedRadius.y;\n\n if (\n visible &&\n ndc.x - clipRadiusX >= -1.0 && ndc.x + clipRadiusX <= 1.0 &&\n ndc.y - clipRadiusY >= -1.0 && ndc.y + clipRadiusY <= 1.0\n ) {\n let uvCenter = ndc.xy * vec2(0.5, -0.5) + vec2(0.5, 0.5);\n let uvRadius = vec2(clipRadiusX, clipRadiusY) * 0.5;\n let viewport = rendererCamera.viewportAndTime.xy;\n let screenDiameter = max(\n max(clipRadiusX * viewport.x * 0.5, clipRadiusY * viewport.y * 0.5),\n 1.0,\n ) * 2.0;\n let maxMipLevel = max(f32(visibilityParams.hizMipCount) - 1.0, 0.0);\n // Round up from the full diameter. Using floor(log2(radius)) leaves\n // unsampled texels between the corner probes, especially for small\n // objects, and can turn partial coverage into a false occlusion.\n let mipLevel = clamp(ceil(log2(screenDiameter)), 0.0, maxMipLevel);\n // Cover the projected bounds rather than testing only their center. The\n // max-reduced pyramid makes background or a gap at any corner retain the\n // draw, avoiding false occlusion for partially covered objects.\n let hizDepth = max(\n max(\n textureSampleLevel(hizTexture, drawMetaTextureSampler, uvCenter + vec2(-uvRadius.x, -uvRadius.y), mipLevel).r,\n textureSampleLevel(hizTexture, drawMetaTextureSampler, uvCenter + vec2( uvRadius.x, -uvRadius.y), mipLevel).r,\n ),\n max(\n textureSampleLevel(hizTexture, drawMetaTextureSampler, uvCenter + vec2(-uvRadius.x, uvRadius.y), mipLevel).r,\n textureSampleLevel(hizTexture, drawMetaTextureSampler, uvCenter + vec2( uvRadius.x, uvRadius.y), mipLevel).r,\n ),\n );\n let conservativeDepth = nearestSphereDepth(rendererCamera.viewProj, clip, radius);\n visible = conservativeDepth <= hizDepth + 0.0005;\n }\n }\n\n let baseVertex = i32(round(drawData.extra.y));\n indirectArgs[drawIndex].indexCount = u32(round(drawData.args0.x));\n indirectArgs[drawIndex].instanceCount = select(0u, u32(round(drawData.args0.w)), visible);\n indirectArgs[drawIndex].firstIndex = u32(round(drawData.args0.y));\n indirectArgs[drawIndex].baseVertex = baseVertex;\n indirectArgs[drawIndex].firstInstance = u32(round(drawData.args0.z));\n}\n",bindGroupLayoutEntries:[{binding:0,visibility:GPUShaderStage.COMPUTE,buffer:{type:"uniform"}},{binding:1,visibility:GPUShaderStage.COMPUTE,buffer:{type:"uniform"}},{binding:2,visibility:GPUShaderStage.COMPUTE,sampler:{type:"non-filtering"}},{binding:3,visibility:GPUShaderStage.COMPUTE,texture:{sampleType:"unfilterable-float"}},{binding:4,visibility:GPUShaderStage.COMPUTE,buffer:{type:"read-only-storage"}},{binding:5,visibility:GPUShaderStage.COMPUTE,buffer:{type:"storage"}}]}),this.state.staticVisibilityClearKernel=this.createComputeKernel({label:"renderer-static-visibility-clear",code:"\nstruct RendererVisibilityParams {\n drawCount: u32,\n hizMipCount: u32,\n instanceCount: u32,\n flags: u32,\n};\n\n@group(0) @binding(0) var<uniform> visibilityParams: RendererVisibilityParams;\n@group(0) @binding(1) var<storage, read_write> visibleCounts: array<atomic<u32>>;\n@group(0) @binding(2) var<storage, read_write> postVisibleCounts: array<atomic<u32>>;\n@group(0) @binding(3) var<storage, read_write> visibleInstanceMask: array<atomic<u32>>;\n\n@compute @workgroup_size(64, 1, 1)\nfn main(@builtin(global_invocation_id) globalId: vec3<u32>) {\n let index = globalId.x;\n if (index < visibilityParams.drawCount) {\n atomicStore(&visibleCounts[index], 0u);\n atomicStore(&postVisibleCounts[index], 0u);\n }\n if (index < visibilityParams.instanceCount) {\n atomicStore(&visibleInstanceMask[index], 0u);\n }\n}\n",bindGroupLayoutEntries:[{binding:0,visibility:GPUShaderStage.COMPUTE,buffer:{type:"uniform"}},{binding:1,visibility:GPUShaderStage.COMPUTE,buffer:{type:"storage"}},{binding:2,visibility:GPUShaderStage.COMPUTE,buffer:{type:"storage"}},{binding:3,visibility:GPUShaderStage.COMPUTE,buffer:{type:"storage"}}]}),this.state.staticVisibilityCullKernel=this.createComputeKernel({label:"renderer-static-visibility-cull",code:"\nstruct RendererTemporalVisibilityUniforms {\n currentViewProj: mat4x4<f32>,\n previousViewProj: mat4x4<f32>,\n currentCameraPosition: vec4<f32>,\n previousCameraPosition: vec4<f32>,\n viewportAndTime: vec4<f32>,\n};\n\nstruct RendererVisibilityParams {\n drawCount: u32,\n hizMipCount: u32,\n instanceCount: u32,\n flags: u32,\n};\n\nstruct DrawMetadata {\n centerRadius: vec4<f32>,\n args0: vec4<f32>,\n extra: vec4<f32>,\n};\n\nstruct StaticInstanceMetadata {\n centerRadius: vec4<f32>,\n drawAndSourceIndex: vec4<u32>,\n};\n\n@group(0) @binding(0) var<uniform> temporalVisibility: RendererTemporalVisibilityUniforms;\n@group(0) @binding(1) var<uniform> visibilityParams: RendererVisibilityParams;\n@group(0) @binding(2) var hizSampler: sampler;\n@group(0) @binding(3) var hizTexture: texture_2d<f32>;\n@group(0) @binding(4) var<storage, read> instanceMetadata: array<StaticInstanceMetadata>;\n@group(0) @binding(5) var<storage, read> drawMetadata: array<DrawMetadata>;\n@group(0) @binding(6) var<storage, read_write> visibleCounts: array<atomic<u32>>;\n@group(0) @binding(7) var<storage, read_write> visibleInstanceIndices: array<u32>;\n@group(0) @binding(8) var<storage, read_write> visibleInstanceMask: array<atomic<u32>>;\n@group(0) @binding(9) var<storage, read_write> postVisibleCounts: array<atomic<u32>>;\n\nfn spherePlaneRadius(viewProj: mat4x4<f32>, plane: vec4<f32>, radius: f32) -> f32 {\n let worldNormal = vec3(\n dot(viewProj[0], plane),\n dot(viewProj[1], plane),\n dot(viewProj[2], plane),\n );\n return radius * length(worldNormal);\n}\n\nfn projectedSphereRadius(\n viewProj: mat4x4<f32>,\n ndc: vec3<f32>,\n clipW: f32,\n radius: f32,\n) -> vec2<f32> {\n let rowX = vec3(viewProj[0].x, viewProj[1].x, viewProj[2].x);\n let rowY = vec3(viewProj[0].y, viewProj[1].y, viewProj[2].y);\n let rowW = vec3(viewProj[0].w, viewProj[1].w, viewProj[2].w);\n let denominator = max(clipW - radius * length(rowW), 0.0001);\n return radius * vec2(\n length(rowX) + abs(ndc.x) * length(rowW),\n length(rowY) + abs(ndc.y) * length(rowW),\n ) / denominator;\n}\n\nfn nearestSphereDepth(viewProj: mat4x4<f32>, clip: vec4<f32>, radius: f32) -> f32 {\n let rowZ = vec3(viewProj[0].z, viewProj[1].z, viewProj[2].z);\n let rowW = vec3(viewProj[0].w, viewProj[1].w, viewProj[2].w);\n let minClipZ = clip.z - radius * length(rowZ);\n let maxClipW = clip.w + radius * length(rowW);\n return max(0.0, minClipZ / max(maxClipW, 0.0001));\n}\n\nfn isSphereInFrustum(\n viewProj: mat4x4<f32>,\n center: vec3<f32>,\n radius: f32,\n) -> bool {\n let clip = viewProj * vec4(center, 1.0);\n let left = clip.w + clip.x;\n let right = clip.w - clip.x;\n let bottom = clip.w + clip.y;\n let top = clip.w - clip.y;\n let near = clip.z;\n let far = clip.w - clip.z;\n\n return\n left >= -spherePlaneRadius(viewProj, vec4(1.0, 0.0, 0.0, 1.0), radius) &&\n right >= -spherePlaneRadius(viewProj, vec4(-1.0, 0.0, 0.0, 1.0), radius) &&\n bottom >= -spherePlaneRadius(viewProj, vec4(0.0, 1.0, 0.0, 1.0), radius) &&\n top >= -spherePlaneRadius(viewProj, vec4(0.0, -1.0, 0.0, 1.0), radius) &&\n near >= -spherePlaneRadius(viewProj, vec4(0.0, 0.0, 1.0, 0.0), radius) &&\n far >= -spherePlaneRadius(viewProj, vec4(0.0, 0.0, -1.0, 1.0), radius);\n}\n\nfn isSphereNearFrustumBoundary(\n viewProj: mat4x4<f32>,\n center: vec3<f32>,\n radius: f32,\n) -> bool {\n let clip = viewProj * vec4(center, 1.0);\n return\n clip.w + clip.x <= spherePlaneRadius(viewProj, vec4(1.0, 0.0, 0.0, 1.0), radius) ||\n clip.w - clip.x <= spherePlaneRadius(viewProj, vec4(-1.0, 0.0, 0.0, 1.0), radius) ||\n clip.w + clip.y <= spherePlaneRadius(viewProj, vec4(0.0, 1.0, 0.0, 1.0), radius) ||\n clip.w - clip.y <= spherePlaneRadius(viewProj, vec4(0.0, -1.0, 0.0, 1.0), radius) ||\n clip.z <= spherePlaneRadius(viewProj, vec4(0.0, 0.0, 1.0, 0.0), radius) ||\n clip.w - clip.z <= spherePlaneRadius(viewProj, vec4(0.0, 0.0, -1.0, 1.0), radius);\n}\n\nfn isSphereVisible(center: vec3<f32>, radius: f32) -> bool {\n let currentViewProj = temporalVisibility.currentViewProj;\n if (!isSphereInFrustum(currentViewProj, center, radius)) {\n return false;\n }\n\n let clip = currentViewProj * vec4(center, 1.0);\n // Near-plane intersections are deliberately kept. A false negative here would\n // incorrectly remove geometry surrounding the camera.\n if (clip.w <= 0.0001) {\n return true;\n }\n\n if ((visibilityParams.flags & 1u) == 0u) {\n return true;\n }\n\n let usesPreviousHiZ = (visibilityParams.flags & 2u) != 0u;\n var hizViewProj = temporalVisibility.currentViewProj;\n var hizCameraPosition = temporalVisibility.currentCameraPosition.xyz;\n if (usesPreviousHiZ) {\n hizViewProj = temporalVisibility.previousViewProj;\n hizCameraPosition = temporalVisibility.previousCameraPosition.xyz;\n }\n\n let hizClip = hizViewProj * vec4(center, 1.0);\n let hizClipWRadius = radius * length(vec3(\n hizViewProj[0].w,\n hizViewProj[1].w,\n hizViewProj[2].w,\n ));\n if (hizClip.w - hizClipWRadius <= 0.0001) {\n return true;\n }\n let hizNdc = hizClip.xyz / hizClip.w;\n let hizProjectedRadius = projectedSphereRadius(\n hizViewProj,\n hizNdc,\n hizClip.w,\n radius,\n );\n let hizClipRadiusX = hizProjectedRadius.x;\n let hizClipRadiusY = hizProjectedRadius.y;\n let hizClipRadiusZ = radius / max(distance(center, hizCameraPosition), 0.001);\n\n // Samples close to the viewport boundary cannot cover the whole projected\n // sphere. This also retains newly revealed regions during camera motion.\n if (\n isSphereNearFrustumBoundary(hizViewProj, center, radius) ||\n hizNdc.x - hizClipRadiusX < -1.0 || hizNdc.x + hizClipRadiusX > 1.0 ||\n hizNdc.y - hizClipRadiusY < -1.0 || hizNdc.y + hizClipRadiusY > 1.0 ||\n hizNdc.z < -hizClipRadiusZ || hizNdc.z > 1.0 + hizClipRadiusZ\n ) {\n return true;\n }\n\n let viewport = temporalVisibility.viewportAndTime.xy;\n let screenDiameter = max(\n max(hizClipRadiusX * viewport.x * 0.5, hizClipRadiusY * viewport.y * 0.5),\n 1.0,\n ) * 2.0;\n let maxMipLevel = max(f32(visibilityParams.hizMipCount) - 1.0, 0.0);\n let mipLevel = clamp(ceil(log2(screenDiameter)), 0.0, maxMipLevel);\n let uvCenter = hizNdc.xy * vec2(0.5, -0.5) + vec2(0.5, 0.5);\n let uvRadius = vec2(hizClipRadiusX, hizClipRadiusY) * 0.5;\n let hizDepth = max(\n max(\n textureSampleLevel(hizTexture, hizSampler, uvCenter + vec2(-uvRadius.x, -uvRadius.y), mipLevel).r,\n textureSampleLevel(hizTexture, hizSampler, uvCenter + vec2( uvRadius.x, -uvRadius.y), mipLevel).r,\n ),\n max(\n textureSampleLevel(hizTexture, hizSampler, uvCenter + vec2(-uvRadius.x, uvRadius.y), mipLevel).r,\n textureSampleLevel(hizTexture, hizSampler, uvCenter + vec2( uvRadius.x, uvRadius.y), mipLevel).r,\n ),\n );\n let conservativeNearestDepth = nearestSphereDepth(hizViewProj, hizClip, radius);\n return conservativeNearestDepth <= hizDepth + 0.001;\n}\n\n@compute @workgroup_size(64, 1, 1)\nfn main(@builtin(global_invocation_id) globalId: vec3<u32>) {\n let instanceIndex = globalId.x;\n if (instanceIndex >= visibilityParams.instanceCount) {\n return;\n }\n\n let instance = instanceMetadata[instanceIndex];\n if ((visibilityParams.flags & 4u) != 0u && atomicLoad(&visibleInstanceMask[instanceIndex]) != 0u) {\n return;\n }\n let drawIndex = instance.drawAndSourceIndex.x;\n if (drawIndex >= visibilityParams.drawCount || !isSphereVisible(instance.centerRadius.xyz, instance.centerRadius.w)) {\n return;\n }\n\n let isPostpass = (visibilityParams.flags & 4u) != 0u;\n if (!isPostpass) {\n atomicStore(&visibleInstanceMask[instanceIndex], 1u);\n }\n let firstInstance = u32(round(drawMetadata[drawIndex].args0.z));\n if (isPostpass) {\n let primaryVisibleCount = atomicLoad(&visibleCounts[drawIndex]);\n let postVisibleIndex = atomicAdd(&postVisibleCounts[drawIndex], 1u);\n visibleInstanceIndices[firstInstance + primaryVisibleCount + postVisibleIndex] = instance.drawAndSourceIndex.y;\n } else {\n let visibleIndex = atomicAdd(&visibleCounts[drawIndex], 1u);\n visibleInstanceIndices[firstInstance + visibleIndex] = instance.drawAndSourceIndex.y;\n }\n}\n",bindGroupLayoutEntries:[{binding:0,visibility:GPUShaderStage.COMPUTE,buffer:{type:"uniform"}},{binding:1,visibility:GPUShaderStage.COMPUTE,buffer:{type:"uniform"}},{binding:2,visibility:GPUShaderStage.COMPUTE,sampler:{type:"non-filtering"}},{binding:3,visibility:GPUShaderStage.COMPUTE,texture:{sampleType:"unfilterable-float"}},{binding:4,visibility:GPUShaderStage.COMPUTE,buffer:{type:"read-only-storage"}},{binding:5,visibility:GPUShaderStage.COMPUTE,buffer:{type:"read-only-storage"}},{binding:6,visibility:GPUShaderStage.COMPUTE,buffer:{type:"storage"}},{binding:7,visibility:GPUShaderStage.COMPUTE,buffer:{type:"storage"}},{binding:8,visibility:GPUShaderStage.COMPUTE,buffer:{type:"storage"}},{binding:9,visibility:GPUShaderStage.COMPUTE,buffer:{type:"storage"}}]}),this.state.staticVisibilityIndirectBuildKernel=this.createComputeKernel({label:"renderer-static-visibility-indirect-build",code:"\nstruct RendererVisibilityParams {\n drawCount: u32,\n hizMipCount: u32,\n instanceCount: u32,\n flags: u32,\n};\n\nstruct IndirectIndexedArgs {\n indexCount: u32,\n instanceCount: u32,\n firstIndex: u32,\n baseVertex: i32,\n firstInstance: u32,\n};\n\n@group(0) @binding(0) var<uniform> visibilityParams: RendererVisibilityParams;\n@group(0) @binding(1) var<storage, read_write> visibleCounts: array<atomic<u32>>;\n@group(0) @binding(2) var<storage, read_write> postVisibleCounts: array<atomic<u32>>;\n@group(0) @binding(3) var<storage, read_write> indirectArgs: array<IndirectIndexedArgs>;\n@group(0) @binding(4) var<storage, read_write> postIndirectArgs: array<IndirectIndexedArgs>;\n\n@compute @workgroup_size(64, 1, 1)\nfn main(@builtin(global_invocation_id) globalId: vec3<u32>) {\n let drawIndex = globalId.x;\n if (drawIndex >= visibilityParams.drawCount) {\n return;\n }\n\n let primaryVisibleCount = atomicLoad(&visibleCounts[drawIndex]);\n let postVisibleCount = atomicLoad(&postVisibleCounts[drawIndex]);\n indirectArgs[drawIndex].instanceCount = primaryVisibleCount + postVisibleCount;\n if ((visibilityParams.flags & 4u) != 0u) {\n postIndirectArgs[drawIndex].instanceCount = postVisibleCount;\n postIndirectArgs[drawIndex].firstInstance = indirectArgs[drawIndex].firstInstance + primaryVisibleCount;\n }\n}\n",bindGroupLayoutEntries:[{binding:0,visibility:GPUShaderStage.COMPUTE,buffer:{type:"uniform"}},{binding:1,visibility:GPUShaderStage.COMPUTE,buffer:{type:"storage"}},{binding:2,visibility:GPUShaderStage.COMPUTE,buffer:{type:"storage"}},{binding:3,visibility:GPUShaderStage.COMPUTE,buffer:{type:"storage"}},{binding:4,visibility:GPUShaderStage.COMPUTE,buffer:{type:"storage"}}]}),this.state.visibilityParamsBuffer=this.state.device.createBuffer({label:"renderer-visibility-params-buffer",size:16,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this.createStaticPipelines(),this.setSize(this.canvas.clientWidth||this.canvas.width||1,this.canvas.clientHeight||this.canvas.height||1),this.state.initialized=!0}createComputeKernel(t){if(!this.state.device)throw new Error("WebGpuRenderer.initialize() must complete before creating compute kernels.");return new e(this.state.device,t)}setRenderGraphBuilder(e){this.graphBuilder=e}setCascadedShadowRanges(e,t=[]){this.csmCascadeCount=Math.min(e.length,4),this.csmCascadeLights=t.slice(0,this.csmCascadeCount);for(let t=0;t<this.csmCascadeCount;t+=1)this.csmCascadeRanges[t].set(e[t].x,e[t].y);for(let e=this.csmCascadeCount;e<4;e+=1)this.csmCascadeRanges[e].set(0,0)}setRenderGraphProfilingEnabled(e){this.renderGraphProfilingEnabled=e}getRenderGraphProfilingEnabled(){return this.renderGraphProfilingEnabled}getTimestampQuerySupported(){return this.timestampQuerySupported}getSampleCount(){return this.sampleCount}setSampleCount(e){const t=$n(e);t!==this.sampleCount&&(this.sampleCount=t,this.destroyMsaaResources(),this.clearIndirectBundleCache(),this.clearStaticDrawSetBundleCaches())}setRenderScale(e){const t=Ni(e);if(t===this.renderScale)return;this.renderScale=t;const r=this.state.pixelRatio;this.setSize(this.state.presentationWidth/r,this.state.presentationHeight/r,r)}getRenderScale(){return this.renderScale}setProjectionJitter(e,t){if(!Number.isFinite(e)||!Number.isFinite(t))throw new RangeError("Projection jitter must contain finite pixel offsets.");this.projectionJitterPixels.set(e,t)}clearProjectionJitter(){this.projectionJitterPixels.set(0,0)}getLastFrameProfile(){const e=this.state.latestFrameProfile?.timestampQueryActive&&null===this.state.latestFrameProfile.gpuTimeMs&&this.state.latestCompletedFrameProfile?this.state.latestCompletedFrameProfile:this.state.latestFrameProfile;return e?{...e,cpuPhases:{...e.cpuPhases},passes:e.passes.map(e=>({...e})),visibility:e.visibility?{...e.visibility}:null}:null}setHiZOcclusionCullingEnabled(e){this.hiZOcclusionCullingEnabled!==e&&(this.state.temporalHiZHistoryValid=!1),this.hiZOcclusionCullingEnabled=e}getHiZOcclusionCullingEnabled(){return this.hiZOcclusionCullingEnabled}getHiZOcclusionCullingActive(){return this.hiZOcclusionCullingEnabled&&this.indirectFirstInstanceSupported}setMultiDrawIndirectEnabled(e){this.multiDrawIndirectEnabled=e}getMultiDrawIndirectEnabled(){return this.multiDrawIndirectEnabled}setDynamicBatchingEnabled(e){this.dynamicBatchingEnabled=e}getDynamicBatchingEnabled(){return this.dynamicBatchingEnabled}getMultiDrawIndirectSupported(){return this.multiDrawIndirectSupported}getMultiDrawIndirectActive(){return this.multiDrawIndirectEnabled&&this.multiDrawIndirectSupported&&this.getHiZOcclusionCullingActive()}setSize(e,t,r=window.devicePixelRatio||1){if(this.state.pixelRatio=r,this.state.presentationWidth=Math.max(1,Math.floor(e*r)),this.state.presentationHeight=Math.max(1,Math.floor(t*r)),this.state.width=Math.max(1,Math.floor(this.state.presentationWidth*this.renderScale)),this.state.height=Math.max(1,Math.floor(this.state.presentationHeight*this.renderScale)),this.canvas.width=this.state.presentationWidth,this.canvas.height=this.state.presentationHeight,this.canvas.style.width=`${Math.max(1,Math.floor(e))}px`,this.canvas.style.height=`${Math.max(1,Math.floor(t))}px`,this.state.device){for(const[e,t]of this.colorTargetCache){const r="presentation"===t.resolution?this.state.presentationWidth:this.state.width,n="presentation"===t.resolution?this.state.presentationHeight:this.state.height,i=Math.max(1,Math.floor(r*t.scale)),a=Math.max(1,Math.floor(n*t.scale));t.width===i&&t.height===a||(t.texture.destroy(),this.colorTargetCache.delete(e))}this.destroyMsaaResources(),this.state.mainDepthTexture?.destroy(),this.state.mainDepthTexture=this.state.device.createTexture({label:"renderer-main-depth",size:{width:this.state.width,height:this.state.height},format:"depth32float",usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_SRC}),this.state.mainDepthView=this.state.mainDepthTexture.createView(),this.state.hizCopyBindGroup=null,this.state.sceneColorTexture?.destroy(),this.state.sceneColorTexture=this.state.device.createTexture({label:"renderer-scene-color",size:{width:this.state.width,height:this.state.height},format:Er,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_SRC}),this.state.sceneColorView=this.state.sceneColorTexture.createView(),this.state.sceneColorSnapshotTexture?.destroy(),this.state.sceneColorSnapshotTexture=this.state.device.createTexture({label:"renderer-scene-color-snapshot",size:{width:this.state.width,height:this.state.height},format:Er,usage:GPUTextureUsage.COPY_DST|GPUTextureUsage.TEXTURE_BINDING}),this.state.sceneColorSnapshotView=this.state.sceneColorSnapshotTexture.createView(),this.state.sceneDepthSnapshotTexture?.destroy(),this.state.sceneDepthSnapshotTexture=this.state.device.createTexture({label:"renderer-scene-depth-snapshot",size:{width:this.state.width,height:this.state.height},format:"depth32float",usage:GPUTextureUsage.COPY_DST|GPUTextureUsage.TEXTURE_BINDING}),this.state.sceneDepthSnapshotView=this.state.sceneDepthSnapshotTexture.createView(),this.state.postProcessColorTexture?.destroy(),this.state.postProcessColorTexture=this.state.device.createTexture({label:"renderer-post-process-color",size:{width:this.state.width,height:this.state.height},format:Er,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_SRC}),this.state.postProcessColorView=this.state.postProcessColorTexture.createView(),this.state.sceneTextureBindGroupLayout&&this.state.linearClampSampler&&this.state.nearestClampSampler&&(this.state.sceneTextureBindGroup=this.state.device.createBindGroup({label:"renderer-scene-texture-bind-group",layout:this.state.sceneTextureBindGroupLayout,entries:[{binding:0,resource:this.state.linearClampSampler},{binding:1,resource:this.state.sceneColorSnapshotView},{binding:2,resource:this.state.nearestClampSampler},{binding:3,resource:this.state.sceneDepthSnapshotView}]})),this.state.hizTexture?.destroy(),this.state.hizMipCount=Math.max(1,Math.floor(Math.log2(Math.max(this.state.width,this.state.height)))+1),this.state.hizTexture=this.state.device.createTexture({label:"renderer-hiz-pyramid",size:{width:this.state.width,height:this.state.height},format:"r32float",mipLevelCount:this.state.hizMipCount,usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.STORAGE_BINDING}),this.state.hizView=this.state.hizTexture.createView(),this.state.hizMipViews=[],this.state.hizCopyBindGroup=null,this.state.hizReduceBindGroups=[],this.state.visibilityBindGroup=null,this.state.visibilityBindGroupMetadataResource=null;for(let e=0;e<this.state.hizMipCount;e+=1)this.state.hizMipViews.push(this.state.hizTexture.createView({baseMipLevel:e,mipLevelCount:1}));this.hizResourceVersion+=1,this.graphTextureResourceVersion+=1,this.state.temporalHiZHistoryValid=!1;for(const e of this.staticDrawSets)e.visibilityBindGroup=null,e.postVisibilityBindGroup=null,e.visibilityBindGroupHizVersion=0;this.recreateShadowResources()}}setClearColor(e){this.clearColor[0]=e[0],this.clearColor[1]=e[1],this.clearColor[2]=e[2],this.clearColor[3]=e[3]}render(e,t,r=.001*performance.now()){this.renderFrame(e,t,r,!1)}async renderAsync(e,t,r=.001*performance.now()){await this.renderFrame(e,t,r,!0)}compile(e,t){this.prepareSceneForCompilation(e,t,!1)}async compileAsync(e,t){this.state.initialized||await this.initialize(),await this.prepareSceneForCompilation(e,t,!0)}createPMREMGenerator(e=20){if(!this.state.device)throw new Error("WebGpuRenderer.initialize() must complete before creating a PMREM generator.");return new rr({device:this.state.device,getTextureResource:e=>this.getTextureResource(e),registerTextureResource:(e,t)=>this.textureCache.set(e,t)},e)}initTexture(e){this.textureManager.getTextureResource(e)}createStaticDrawSet(e,t={}){return this.staticDrawSetManager.createStaticDrawSet(e,t)}disposeStaticDrawSetResource(e){this.staticDrawSetManager.disposeStaticDrawSetResource(e)}renderFrame(e,t,r,n){if(!(this.state.initialized&&this.state.device&&this.state.context&&this.state.mainDepthView&&this.state.sceneColorView&&this.state.postProcessColorView&&this.state.cameraBuffer&&this.state.lightBuffer&&this.state.shadowCameraBuffer&&this.state.sceneBindGroupLayout&&this.state.shadowBindGroupLayout&&this.state.shadowComparisonSampler&&this.state.linearClampSampler&&this.state.nearestClampSampler&&this.state.visibilityParamsBuffer&&this.state.directionalShadowView&&this.state.pointShadowArrayView&&this.state.spotShadowView&&this.state.hizCopyKernel&&this.state.hizReduceKernel&&this.state.visibilityKernel&&this.state.presentPipeline))throw new Error("WebGpuRenderer.initialize() must complete before render().");this.state.frameTimeSeconds=r,this.staticFrameToken+=1,e.matrixWorldAutoUpdate&&e.updateMatrixWorld(),null===t.parent&&t.matrixWorldAutoUpdate&&t.updateMatrixWorld();const i=performance.now(),a=this.extractScene(e,t);this.ensureShadowTextureSizes(a);const s=performance.now()-i,o={drawCallCount:0,triangleCount:0},l=performance.now();this.uploadInstanceData(a.instanceData),this.uploadResidentInstanceData(a.residentInstanceUploads);const c=this.getHiZOcclusionCullingActive();this.uploadDrawMetadata(c?a.gpuOpaqueDraws:[]),this.updateCameraUniforms(t,e),this.updateTemporalVisibilityUniforms(t),this.updateLightUniforms(a);const u=performance.now()-l,d=this.state.device.createCommandEncoder({label:"renderer-command-encoder"}),h=this.state.context.getCurrentTexture().createView(),p=this.getSharedSceneBindGroup(),f=this.getSharedShadowBindGroup();let m=null;const g=this.state.drawMetadataResource;c&&g&&g.count>0&&this.state.hizView&&(this.state.visibilityBindGroup&&this.state.visibilityBindGroupMetadataResource===g||(this.state.visibilityBindGroup=this.state.visibilityKernel.createBindGroup(this.state.device,[{binding:0,resource:{buffer:this.state.cameraBuffer}},{binding:1,resource:{buffer:this.state.visibilityParamsBuffer}},{binding:2,resource:this.state.nearestClampSampler},{binding:3,resource:this.state.hizView},{binding:4,resource:{buffer:g.metadataBuffer}},{binding:5,resource:{buffer:g.indirectBuffer}}],"renderer-visibility-bind-group"),this.state.visibilityBindGroupMetadataResource=g),m=this.state.visibilityBindGroup),this.renderGraph.reset();const x=this.createGraphBuilderContext(this.renderGraph,d,p,f,m,h,a,o);this.graphBuilder(this.renderGraph,x);const v={device:this.state.device,encoder:d},w=function(e,t,r,n,i){if(!t.renderGraphProfilingEnabled||!e.device)return null;const a={frameIndex:e.frameIndex+=1,cpuTimeMs:0,gpuTimeMs:null,drawCallCount:n.drawCallCount,triangleCount:n.triangleCount,cpuPhases:{extractSceneMs:i.extractSceneMs,uploadMs:i.uploadMs,renderGraphMs:0},passes:[],timestampQuerySupported:t.timestampQuerySupported,timestampQueryActive:t.timestampQuerySupported,gpuProfilingReason:null,hiZOcclusionCullingEnabled:t.hiZOcclusionCullingEnabled,hiZOcclusionCullingActive:r,visibility:null};let s=null;const o={begin:(e,r)=>{if(a.passes=e.map(e=>({name:e.name,cpuTimeMs:0,gpuTimeMs:null})),!t.timestampQuerySupported)return a.timestampQueryActive=!1,void(a.gpuProfilingReason="timestamp-query is not supported by this adapter/device");if(0===e.length)return a.timestampQueryActive=!1,void(a.gpuProfilingReason="no render graph passes were recorded");const n=2*e.length,i=Math.max(8,8*n),o=r.device.createQuerySet({label:`renderer-frame-profile-${a.frameIndex}`,type:"timestamp",count:n}),l=r.device.createBuffer({label:`renderer-frame-profile-resolve-${a.frameIndex}`,size:i,usage:GPUBufferUsage.QUERY_RESOLVE|GPUBufferUsage.COPY_SRC}),c=r.device.createBuffer({label:`renderer-frame-profile-read-${a.frameIndex}`,size:i,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});s={profile:a,querySet:o,resolveBuffer:l,readBuffer:c,queryCount:n}},beforePass:(e,t,r)=>{s&&(un(r.encoder,s.querySet,{endOfPassWriteIndex:2*t})||(a.timestampQueryActive=!1,a.gpuProfilingReason="timestampWrites marker pass is not available on this browser/runtime",s.querySet.destroy(),s.resolveBuffer.destroy(),s.readBuffer.destroy(),s=null))},afterPass:(e,t,r,n)=>{a.passes[t].cpuTimeMs=r,s&&(un(n.encoder,s.querySet,{beginningOfPassWriteIndex:2*t+1})||(a.timestampQueryActive=!1,a.gpuProfilingReason="timestampWrites marker pass is not available on this browser/runtime",s.querySet.destroy(),s.resolveBuffer.destroy(),s.readBuffer.destroy(),s=null))},end:(t,r,i)=>{if(a.cpuPhases.renderGraphMs=r,a.cpuTimeMs=a.cpuPhases.extractSceneMs+a.cpuPhases.uploadMs+a.cpuPhases.renderGraphMs,a.drawCallCount=n.drawCallCount,a.triangleCount=n.triangleCount,!s){const t=qn(a);return e.latestFrameProfile=t,void(e.latestCompletedFrameProfile=t)}i.encoder.resolveQuerySet(s.querySet,0,s.queryCount,s.resolveBuffer,0),i.encoder.copyBufferToBuffer(s.resolveBuffer,0,s.readBuffer,0,8*s.queryCount),e.latestFrameProfile=qn(a)}};return{profile:a,observer:o,pendingVisibilityRead:null,get pendingGpuRead(){return s},set pendingGpuRead(e){s=e}}}(this.state,{renderGraphProfilingEnabled:this.renderGraphProfilingEnabled,timestampQuerySupported:this.timestampQuerySupported,hiZOcclusionCullingEnabled:this.hiZOcclusionCullingEnabled},c,o,{extractSceneMs:s,uploadMs:u}),b=()=>{if(!w||!c)return;const e=[];g&&g.count>0&&e.push({buffer:g.indirectBuffer,drawCount:g.count,totalInstances:a.gpuOpaqueDraws.reduce((e,t)=>e+Math.max(0,t.instanceCount),0),kind:"dynamic"});for(const t of this.staticDrawSets)t.publicSet.enabled&&t.lastVisibilityFrameToken===this.staticFrameToken&&e.push({buffer:t.drawMetadataResource.indirectBuffer,drawCount:t.drawMetadataResource.count,totalInstances:t.instanceCount,kind:"static"});!function(e,t,r,n){const i=n.filter(e=>e.drawCount>0);if(0===i.length)return void(e.profile.visibility={totalInstances:0,visibleInstances:0,culledInstances:0,dynamicTotalInstances:0,dynamicVisibleInstances:0,staticTotalInstances:0,staticVisibleInstances:0});let a=0;const s=i.map(e=>{const t={byteOffset:a,drawCount:e.drawCount,totalInstances:e.totalInstances,kind:e.kind};return a+=5*e.drawCount*Uint32Array.BYTES_PER_ELEMENT,t}),o=t.createBuffer({label:`renderer-visibility-profile-read-${e.profile.frameIndex}`,size:Math.max(4,a),usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});for(let e=0;e<i.length;e+=1){const t=i[e];r.copyBufferToBuffer(t.buffer,0,o,s[e].byteOffset,5*t.drawCount*Uint32Array.BYTES_PER_ELEMENT)}e.pendingVisibilityRead={readBuffer:o,regions:s}}(w,this.state.device,d,e)};if(n)return this.renderGraph.executeAsync(v,w?.observer).then(()=>{b(),this.state.device.queue.submit([d.finish()]),this.releaseRetiredGeometryResourcesAfterSubmit(),w&&Nn(this.state,w)});this.renderGraph.execute(v,w?.observer),b(),this.state.device.queue.submit([d.finish()]),this.releaseRetiredGeometryResourcesAfterSubmit(),w&&Nn(this.state,w)}destroy(){this.clearIndirectBundleCache();for(const e of this.staticDrawSets.slice())this.disposeStaticDrawSetResource(e);this.sharedForwardPipelineCache.clear(),this.sharedForwardPipelinePromiseCache.clear(),this.sharedDepthPipelineCache.clear(),this.sharedDepthPipelinePromiseCache.clear();for(const e of this.skinnedGeometryCache.values())e.skinning.bindUniformBuffer.destroy();this.skinnedGeometryCache.clear();for(const e of this.skinPaletteResources)e.matrixBuffer.destroy();this.skinPaletteResources.clear();for(const e of this.retiredGeometryResources)this.destroyGeometryResource(e);this.retiredGeometryResources.length=0;for(const e of this.colorTargetCache.values())e.texture.destroy();this.colorTargetCache.clear(),this.destroyMsaaResources(),this.state.mainDepthTexture?.destroy(),this.state.sceneColorTexture?.destroy(),this.state.sceneColorSnapshotTexture?.destroy(),this.state.sceneDepthSnapshotTexture?.destroy(),this.state.postProcessColorTexture?.destroy(),this.state.directionalShadowTexture?.destroy(),this.state.pointShadowTexture?.destroy(),this.state.pointShadowDepthTexture?.destroy(),this.state.spotShadowTexture?.destroy(),this.state.hizTexture?.destroy(),this.state.cameraBuffer?.destroy(),this.state.temporalVisibilityBuffer?.destroy(),this.state.lightBuffer?.destroy(),this.state.shadowCameraBuffer?.destroy();for(const e of this.state.shadowCameraBufferPool)e.destroy();this.state.shadowCameraBufferPool.length=0,this.state.sharedShadowBindGroupByCameraBuffer.clear(),this.state.instanceBuffer?.destroy();for(const e of this.defaultInstanceAttributeBuffers.values())for(const t of e.values())t.destroy();this.defaultInstanceAttributeBuffers.clear(),this.state.visibilityParamsBuffer?.destroy(),this.state.drawMetadataResource?.metadataBuffer.destroy(),this.state.drawMetadataResource?.indirectBuffer.destroy(),this.state.drawMetadataResource?.postIndirectBuffer.destroy(),this.state.initialized=!1,this.state.device?.destroy(),this.state.device=null}createStaticPipelines(){if(!(this.state.device&&this.state.sceneBindGroupLayout&&this.state.directSceneBindGroupLayout&&this.state.visibleDepthSceneBindGroupLayout&&this.state.shadowBindGroupLayout&&this.state.directShadowBindGroupLayout&&this.state.emptyBindGroupLayout&&this.state.skinningBindGroupLayout&&this.state.fullscreenTextureBindGroupLayout&&this.state.format))return;const e=this.state.device.createPipelineLayout({label:"renderer-depth-prepass-layout",bindGroupLayouts:[this.state.sceneBindGroupLayout]});this.state.depthPrepassPipeline=this.state.device.createRenderPipeline({label:"renderer-depth-prepass-pipeline",layout:e,vertex:{module:this.state.device.createShaderModule({label:"renderer-depth-prepass-module",code:"\nstruct RendererCameraUniforms {\n viewProj: mat4x4<f32>,\n cameraPosition: vec4<f32>,\n viewportAndTime: vec4<f32>,\n};\n\nstruct RendererInstanceData {\n model0: vec4<f32>,\n model1: vec4<f32>,\n model2: vec4<f32>,\n model3: vec4<f32>,\n color: vec4<f32>,\n batching: vec4<f32>,\n};\n\n@group(0) @binding(0) var<uniform> rendererCamera: RendererCameraUniforms;\n@group(0) @binding(1) var<uniform> rendererLights: array<vec4<f32>, 11>;\n@group(0) @binding(2) var<storage, read> rendererInstances: array<RendererInstanceData>;\n\nfn rendererInstanceModelMatrix(instanceIndex: u32) -> mat4x4<f32> {\n let instance = rendererInstances[instanceIndex];\n return mat4x4<f32>(instance.model0, instance.model1, instance.model2, instance.model3);\n}\n\n@vertex\nfn vsMain(\n @location(0) position: vec3<f32>,\n @builtin(instance_index) instanceIndex: u32\n) -> @builtin(position) vec4<f32> {\n let world = rendererInstanceModelMatrix(instanceIndex) * vec4(position, 1.0);\n return rendererCamera.viewProj * world;\n}\n"}),entryPoint:"vsMain",buffers:[{arrayStride:12,attributes:[{shaderLocation:0,offset:0,format:"float32x3"}]}]},primitive:{topology:"triangle-list",cullMode:"back",frontFace:"ccw"},depthStencil:{format:"depth32float",depthWriteEnabled:!0,depthCompare:"less"}});const t=this.state.device.createPipelineLayout({label:"renderer-depth-prepass-visible-layout",bindGroupLayouts:[this.state.visibleDepthSceneBindGroupLayout]});this.state.depthPrepassPipelineVisible=this.state.device.createRenderPipeline({label:"renderer-depth-prepass-visible-pipeline",layout:t,vertex:{module:this.state.device.createShaderModule({label:"renderer-depth-prepass-visible-module",code:"\nstruct RendererCameraUniforms {\n viewProj: mat4x4<f32>,\n cameraPosition: vec4<f32>,\n viewportAndTime: vec4<f32>,\n};\n\nstruct RendererInstanceData {\n model0: vec4<f32>,\n model1: vec4<f32>,\n model2: vec4<f32>,\n model3: vec4<f32>,\n color: vec4<f32>,\n batching: vec4<f32>,\n};\n\n@group(0) @binding(0) var<uniform> rendererCamera: RendererCameraUniforms;\n@group(0) @binding(2) var<storage, read> rendererInstances: array<RendererInstanceData>;\n@group(0) @binding(3) var<storage, read> rendererVisibleInstanceIndices: array<u32>;\n\nfn rendererInstanceModelMatrix(instanceIndex: u32) -> mat4x4<f32> {\n let instance = rendererInstances[rendererVisibleInstanceIndices[instanceIndex]];\n return mat4x4<f32>(instance.model0, instance.model1, instance.model2, instance.model3);\n}\n\n@vertex\nfn vsMain(\n @location(0) position: vec3<f32>,\n @builtin(instance_index) instanceIndex: u32\n) -> @builtin(position) vec4<f32> {\n let world = rendererInstanceModelMatrix(instanceIndex) * vec4(position, 1.0);\n return rendererCamera.viewProj * world;\n}\n"}),entryPoint:"vsMain",buffers:[{arrayStride:12,attributes:[{shaderLocation:0,offset:0,format:"float32x3"}]}]},primitive:{topology:"triangle-list",cullMode:"back",frontFace:"ccw"},depthStencil:{format:"depth32float",depthWriteEnabled:!0,depthCompare:"less"}});const r=this.state.device.createPipelineLayout({label:"renderer-depth-prepass-direct-layout",bindGroupLayouts:[this.state.directSceneBindGroupLayout]});this.state.depthPrepassPipelineDirect=this.state.device.createRenderPipeline({label:"renderer-depth-prepass-direct-pipeline",layout:r,vertex:{module:this.state.device.createShaderModule({label:"renderer-depth-prepass-direct-module",code:"\nstruct RendererCameraUniforms {\n viewProj: mat4x4<f32>,\n cameraPosition: vec4<f32>,\n viewportAndTime: vec4<f32>,\n};\n\n@group(0) @binding(0) var<uniform> rendererCamera: RendererCameraUniforms;\n@group(0) @binding(1) var<uniform> rendererLights: array<vec4<f32>, 11>;\n@group(0) @binding(2) var<storage, read> rendererInstanceMatrices: array<vec4<f32>>;\n\nfn rendererInstanceModelMatrix(instanceIndex: u32) -> mat4x4<f32> {\n let base = instanceIndex * 4u;\n return mat4x4<f32>(\n rendererInstanceMatrices[base + 0u],\n rendererInstanceMatrices[base + 1u],\n rendererInstanceMatrices[base + 2u],\n rendererInstanceMatrices[base + 3u]\n );\n}\n\n@vertex\nfn vsMain(\n @location(0) position: vec3<f32>,\n @builtin(instance_index) instanceIndex: u32\n) -> @builtin(position) vec4<f32> {\n let world = rendererInstanceModelMatrix(instanceIndex) * vec4(position, 1.0);\n return rendererCamera.viewProj * world;\n}\n"}),entryPoint:"vsMain",buffers:[{arrayStride:12,attributes:[{shaderLocation:0,offset:0,format:"float32x3"}]}]},primitive:{topology:"triangle-list",cullMode:"back",frontFace:"ccw"},depthStencil:{format:"depth32float",depthWriteEnabled:!0,depthCompare:"less"}});const n=this.state.device.createPipelineLayout({label:"renderer-skinned-depth-prepass-layout",bindGroupLayouts:[this.state.sceneBindGroupLayout,this.state.emptyBindGroupLayout,this.state.skinningBindGroupLayout]});this.state.skinnedDepthPrepassPipeline=this.state.device.createRenderPipeline({label:"renderer-skinned-depth-prepass-pipeline",layout:n,vertex:{module:this.state.device.createShaderModule({label:"renderer-skinned-depth-prepass-module",code:Li}),entryPoint:"vsMain",buffers:this.createVertexBufferLayouts(Nr)},primitive:{topology:"triangle-list",cullMode:"back",frontFace:"ccw"},depthStencil:{format:"depth32float",depthWriteEnabled:!0,depthCompare:"less"}});const i=this.state.device.createPipelineLayout({label:"renderer-shadow-layout",bindGroupLayouts:[this.state.shadowBindGroupLayout]}),a=this.state.device.createPipelineLayout({label:"renderer-direct-shadow-pipeline-layout",bindGroupLayouts:[this.state.directShadowBindGroupLayout]});this.state.shadowDepthPipeline=this.state.device.createRenderPipeline({label:"renderer-directional-shadow-pipeline",layout:i,vertex:{module:this.state.device.createShaderModule({label:"renderer-directional-shadow-module",code:"\nstruct ShadowCameraUniforms {\n viewProj: mat4x4<f32>,\n lightPositionRange: vec4<f32>,\n};\n\nstruct RendererInstanceData {\n model0: vec4<f32>,\n model1: vec4<f32>,\n model2: vec4<f32>,\n model3: vec4<f32>,\n color: vec4<f32>,\n batching: vec4<f32>,\n};\n\n@group(0) @binding(0) var<uniform> shadowCamera: ShadowCameraUniforms;\n@group(0) @binding(1) var<storage, read> rendererInstances: array<RendererInstanceData>;\n\nfn rendererInstanceModelMatrix(instanceIndex: u32) -> mat4x4<f32> {\n let instance = rendererInstances[instanceIndex];\n return mat4x4<f32>(instance.model0, instance.model1, instance.model2, instance.model3);\n}\n\n@vertex\nfn vsMain(\n @location(0) position: vec3<f32>,\n @builtin(instance_index) instanceIndex: u32\n) -> @builtin(position) vec4<f32> {\n let world = rendererInstanceModelMatrix(instanceIndex) * vec4(position, 1.0);\n return shadowCamera.viewProj * world;\n}\n"}),entryPoint:"vsMain",buffers:[{arrayStride:12,attributes:[{shaderLocation:0,offset:0,format:"float32x3"}]}]},primitive:{topology:"triangle-list",cullMode:"front",frontFace:"ccw"},depthStencil:{format:"depth32float",depthWriteEnabled:!0,depthCompare:"less",depthBias:1,depthBiasSlopeScale:2,depthBiasClamp:0}}),this.state.shadowDepthPipelineDirect=this.state.device.createRenderPipeline({label:"renderer-directional-shadow-direct-pipeline",layout:a,vertex:{module:this.state.device.createShaderModule({label:"renderer-directional-shadow-direct-module",code:"\nstruct ShadowCameraUniforms {\n viewProj: mat4x4<f32>,\n lightPositionRange: vec4<f32>,\n};\n\n@group(0) @binding(0) var<uniform> shadowCamera: ShadowCameraUniforms;\n@group(0) @binding(1) var<storage, read> rendererInstanceMatrices: array<vec4<f32>>;\n\nfn rendererInstanceModelMatrix(instanceIndex: u32) -> mat4x4<f32> {\n let base = instanceIndex * 4u;\n return mat4x4<f32>(\n rendererInstanceMatrices[base + 0u],\n rendererInstanceMatrices[base + 1u],\n rendererInstanceMatrices[base + 2u],\n rendererInstanceMatrices[base + 3u]\n );\n}\n\n@vertex\nfn vsMain(\n @location(0) position: vec3<f32>,\n @builtin(instance_index) instanceIndex: u32\n) -> @builtin(position) vec4<f32> {\n let world = rendererInstanceModelMatrix(instanceIndex) * vec4(position, 1.0);\n return shadowCamera.viewProj * world;\n}\n"}),entryPoint:"vsMain",buffers:[{arrayStride:12,attributes:[{shaderLocation:0,offset:0,format:"float32x3"}]}]},primitive:{topology:"triangle-list",cullMode:"front",frontFace:"ccw"},depthStencil:{format:"depth32float",depthWriteEnabled:!0,depthCompare:"less",depthBias:1,depthBiasSlopeScale:2,depthBiasClamp:0}});const s=this.state.device.createPipelineLayout({label:"renderer-skinned-shadow-layout",bindGroupLayouts:[this.state.shadowBindGroupLayout,this.state.emptyBindGroupLayout,this.state.skinningBindGroupLayout]});this.state.skinnedShadowDepthPipeline=this.state.device.createRenderPipeline({label:"renderer-skinned-directional-shadow-pipeline",layout:s,vertex:{module:this.state.device.createShaderModule({label:"renderer-skinned-directional-shadow-module",code:zi}),entryPoint:"vsMain",buffers:this.createVertexBufferLayouts(Nr)},primitive:{topology:"triangle-list",cullMode:"front",frontFace:"ccw"},depthStencil:{format:"depth32float",depthWriteEnabled:!0,depthCompare:"less",depthBias:1,depthBiasSlopeScale:2,depthBiasClamp:0}}),this.state.pointShadowPipeline=this.state.device.createRenderPipeline({label:"renderer-point-shadow-pipeline",layout:i,vertex:{module:this.state.device.createShaderModule({label:"renderer-point-shadow-module",code:Ii}),entryPoint:"vsMain",buffers:[{arrayStride:12,attributes:[{shaderLocation:0,offset:0,format:"float32x3"}]}]},fragment:{module:this.state.device.createShaderModule({label:"renderer-point-shadow-fragment-module",code:Ii}),entryPoint:"fsMain",targets:[{format:"rgba16float"}]},primitive:{topology:"triangle-list",cullMode:"back",frontFace:"ccw"},depthStencil:{format:"depth32float",depthWriteEnabled:!0,depthCompare:"less"}}),this.state.pointShadowPipelineDirect=this.state.device.createRenderPipeline({label:"renderer-point-shadow-direct-pipeline",layout:a,vertex:{module:this.state.device.createShaderModule({label:"renderer-point-shadow-direct-module",code:Gi}),entryPoint:"vsMain",buffers:[{arrayStride:12,attributes:[{shaderLocation:0,offset:0,format:"float32x3"}]}]},fragment:{module:this.state.device.createShaderModule({label:"renderer-point-shadow-direct-fragment-module",code:Gi}),entryPoint:"fsMain",targets:[{format:"rgba16float"}]},primitive:{topology:"triangle-list",cullMode:"back",frontFace:"ccw"},depthStencil:{format:"depth32float",depthWriteEnabled:!0,depthCompare:"less"}}),this.state.skinnedPointShadowPipeline=this.state.device.createRenderPipeline({label:"renderer-skinned-point-shadow-pipeline",layout:s,vertex:{module:this.state.device.createShaderModule({label:"renderer-skinned-point-shadow-module",code:Ui}),entryPoint:"vsMain",buffers:this.createVertexBufferLayouts(Nr)},fragment:{module:this.state.device.createShaderModule({label:"renderer-skinned-point-shadow-fragment-module",code:Ui}),entryPoint:"fsMain",targets:[{format:"rgba16float"}]},primitive:{topology:"triangle-list",cullMode:"back",frontFace:"ccw"},depthStencil:{format:"depth32float",depthWriteEnabled:!0,depthCompare:"less"}});const o=this.state.device.createPipelineLayout({label:"renderer-present-layout",bindGroupLayouts:[this.state.fullscreenTextureBindGroupLayout]});this.state.presentPipeline=this.state.device.createRenderPipeline({label:"renderer-present-pipeline",layout:o,vertex:{module:this.state.device.createShaderModule({label:"renderer-present-module",code:Vi}),entryPoint:"vsMain"},fragment:{module:this.state.device.createShaderModule({label:"renderer-present-fragment-module",code:Vi}),entryPoint:"fsMain",targets:[{format:this.state.format}]},primitive:{topology:"triangle-list"}})}recreateShadowResources(){if(this.state.device){this.state.residentSceneBindGroupVersion+=1,this.state.sharedSceneBindGroup=null,this.clearIndirectBundleCache(),this.clearStaticDrawSetBundleCaches(),this.state.directionalShadowTexture?.destroy(),this.state.directionalShadowTexture=this.state.device.createTexture({label:"renderer-directional-shadow-texture",size:{width:this.state.directionalShadowTextureSize,height:this.state.directionalShadowTextureSize,depthOrArrayLayers:4},format:"depth32float",dimension:"2d",usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_SRC}),this.state.directionalShadowView=this.state.directionalShadowTexture.createView({dimension:"2d-array"}),this.state.directionalShadowLayerViews=[];for(let e=0;e<4;e+=1)this.state.directionalShadowLayerViews.push(this.state.directionalShadowTexture.createView({dimension:"2d",baseArrayLayer:e,arrayLayerCount:1}));this.state.pointShadowTexture?.destroy(),this.state.pointShadowTexture=this.state.device.createTexture({label:"renderer-point-shadow-texture",size:{width:this.state.pointShadowTextureSize,height:this.state.pointShadowTextureSize,depthOrArrayLayers:24},format:"rgba16float",dimension:"2d",usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING}),this.state.pointShadowArrayView=this.state.pointShadowTexture.createView({dimension:"2d-array"}),this.state.pointShadowFaceViews=[];for(let e=0;e<24;e+=1)this.state.pointShadowFaceViews.push(this.state.pointShadowTexture.createView({dimension:"2d",baseArrayLayer:e,arrayLayerCount:1}));this.state.pointShadowDepthTexture?.destroy(),this.state.pointShadowDepthTexture=this.state.device.createTexture({label:"renderer-point-shadow-depth-texture",size:{width:this.state.pointShadowTextureSize,height:this.state.pointShadowTextureSize,depthOrArrayLayers:24},format:"depth32float",dimension:"2d",usage:GPUTextureUsage.RENDER_ATTACHMENT}),this.state.pointShadowDepthFaceViews=[];for(let e=0;e<24;e+=1)this.state.pointShadowDepthFaceViews.push(this.state.pointShadowDepthTexture.createView({dimension:"2d",baseArrayLayer:e,arrayLayerCount:1}));this.state.spotShadowTexture?.destroy(),this.state.spotShadowTexture=this.state.device.createTexture({label:"renderer-spot-shadow-texture",size:{width:this.state.spotShadowTextureSize,height:this.state.spotShadowTextureSize,depthOrArrayLayers:4},format:"depth32float",dimension:"2d",usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING}),this.state.spotShadowView=this.state.spotShadowTexture.createView({dimension:"2d-array"}),this.state.spotShadowLayerViews=[];for(let e=0;e<4;e+=1)this.state.spotShadowLayerViews.push(this.state.spotShadowTexture.createView({dimension:"2d",baseArrayLayer:e,arrayLayerCount:1}))}}ensureShadowTextureSizes(e){const t=Math.max(this.shadowMapSize,...e.lights.directionals.map(e=>Math.ceil(e.shadowMapSize))),r=Math.max(this.pointShadowMapSize,...e.lights.points.map(e=>Math.ceil(e.shadowMapSize))),n=Math.max(this.shadowMapSize,...e.lights.spots.map(e=>Math.ceil(e.shadowMapSize)));t===this.state.directionalShadowTextureSize&&r===this.state.pointShadowTextureSize&&n===this.state.spotShadowTextureSize||(this.state.directionalShadowTextureSize=t,this.state.pointShadowTextureSize=r,this.state.spotShadowTextureSize=n,this.recreateShadowResources())}ensureColorTarget(e,t={}){if(!this.state.device||!this.state.format)throw new Error("Renderer is not initialized.");if("sceneColor"===e||"postProcessColor"===e)throw new Error(`Color target "${e}" is reserved by the renderer.`);const r=t.scale??1,n=t.resolution??"render",i=t.format??Er,a="presentation"===n?this.state.presentationWidth:this.state.width,s="presentation"===n?this.state.presentationHeight:this.state.height,o=Math.max(1,Math.floor(a*r)),l=Math.max(1,Math.floor(s*r)),c=this.colorTargetCache.get(e);if(c&&c.format===i&&c.width===o&&c.height===l&&c.scale===r&&c.resolution===n)return c;c?.texture.destroy();const u=this.state.device.createTexture({label:`renderer-color-target-${e}`,size:{width:o,height:l},format:i,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_SRC}),d={name:e,format:i,width:o,height:l,scale:r,resolution:n,texture:u,view:u.createView()};return this.colorTargetCache.set(e,d),this.graphTextureResourceVersion+=1,d}ensureMsaaColorTarget(e){if(!this.state.device)throw new Error("Renderer is not initialized.");const t=this.getColorTargetDimensions(e),r=this.getColorTargetFormat(e),n=this.msaaColorTargetCache.get(e);if(n&&n.format===r&&n.width===t.width&&n.height===t.height&&1===n.scale)return n;n?.texture.destroy();const i=this.state.device.createTexture({label:`renderer-msaa-color-target-${e}`,size:{width:t.width,height:t.height},sampleCount:this.sampleCount,format:r,usage:GPUTextureUsage.RENDER_ATTACHMENT}),a={name:e,format:r,width:t.width,height:t.height,scale:1,texture:i,view:i.createView()};return this.msaaColorTargetCache.set(e,a),a}ensureMsaaDepthTarget(e,t){if(!this.state.device)throw new Error("Renderer is not initialized.");const r=`${e}x${t}`,n=this.msaaDepthTargetCache.get(r);if(n&&n.width===e&&n.height===t&&n.sampleCount===this.sampleCount)return n;n?.texture.destroy();const i=this.state.device.createTexture({label:`renderer-msaa-depth-${r}`,size:{width:e,height:t},sampleCount:this.sampleCount,format:"depth32float",usage:GPUTextureUsage.RENDER_ATTACHMENT}),a={width:e,height:t,sampleCount:this.sampleCount,texture:i,view:i.createView()};return this.msaaDepthTargetCache.set(r,a),a}destroyMsaaResources(){for(const e of this.msaaColorTargetCache.values())e.texture.destroy();this.msaaColorTargetCache.clear();for(const e of this.msaaDepthTargetCache.values())e.texture.destroy();this.msaaDepthTargetCache.clear()}getColorTargetView(e){if("sceneColor"===e){if(!this.state.sceneColorView)throw new Error("Scene color target is not available.");return this.state.sceneColorView}if("postProcessColor"===e){if(!this.state.postProcessColorView)throw new Error("Post-process color target is not available.");return this.state.postProcessColorView}const t=this.colorTargetCache.get(e);if(!t)throw new Error(`Color target "${e}" has not been defined.`);return t.view}ensureTextureTarget(e,t={}){if("2d"===(t.dimension??"2d")&&null==t.usage)return this.ensureColorTarget(e,t);if(!this.state.device)throw new Error("Renderer is not initialized.");const r=t.scale??1,n=t.resolution??"render",i="presentation"===n?this.state.presentationWidth:this.state.width,a="presentation"===n?this.state.presentationHeight:this.state.height,s=Math.max(1,Math.floor(i*r)),o=Math.max(1,Math.floor(a*r)),l=Math.max(1,t.depthOrArrayLayers??1),c=t.format??Er,u=this.colorTargetCache.get(e),d=t.dimension??"2d",h=t.usage??GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.STORAGE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.COPY_SRC;if(u&&u.format===c&&u.width===s&&u.height===o&&u.resolution===n&&u.dimension===d&&u.depthOrArrayLayers===l&&u.usage===h)return u;u?.texture.destroy();const p=this.state.device.createTexture({label:`renderer-texture-target-${e}`,size:{width:s,height:o,depthOrArrayLayers:l},dimension:d,format:c,usage:h}),f={name:e,format:c,width:s,height:o,scale:r,resolution:n,dimension:d,depthOrArrayLayers:l,usage:h,texture:p,view:p.createView({dimension:d})};return this.colorTargetCache.set(e,f),this.graphTextureResourceVersion+=1,f}getColorTargetTexture(e){if("sceneColor"===e){if(!this.state.sceneColorTexture)throw new Error("Scene color target is not available.");return this.state.sceneColorTexture}if("postProcessColor"===e){if(!this.state.postProcessColorTexture)throw new Error("Post-process color target is not available.");return this.state.postProcessColorTexture}const t=this.colorTargetCache.get(e);if(!t)throw new Error(`Color target "${e}" has not been defined.`);return t.texture}getColorTargetDimensions(e){if("sceneColor"===e||"postProcessColor"===e)return{width:this.state.width,height:this.state.height};const t=this.colorTargetCache.get(e);if(!t)throw new Error(`Color target "${e}" has not been defined.`);return{width:t.width,height:t.height}}getColorTargetFormat(e){if(!this.state.format)throw new Error("Renderer is not initialized.");if("sceneColor"===e||"postProcessColor"===e)return Er;const t=this.colorTargetCache.get(e);if(!t)throw new Error(`Color target "${e}" has not been defined.`);return t.format}getMaterialGraphTextureReads(e){const t=this.materialGraphTextureReadCache.get(e);if(t?.materialVersion===e.version)return t.resources;const r=e.getGraphTextureInputs(),n=[];for(const e in r){const t=r[e].resource;n.includes(t)||n.push(t)}return this.materialGraphTextureReadCache.set(e,{materialVersion:e.version,resources:n}),n}createGraphBuilderContext(e,t,r,n,i,a,s,o,l){let c=!1,u=!1;const d=e=>{const t=new Set;for(let r=0;r<e.length;r+=1){const n=this.getMaterialGraphTextureReads(e[r].material);for(let e=0;e<n.length;e+=1)t.add(n[e])}return Array.from(t)},h={device:this.state.device,encoder:t,camera:s.camera,sceneColorView:this.state.sceneColorView,postProcessColorView:this.state.postProcessColorView,presentationColorView:a,depthView:this.state.mainDepthView,colorFormat:Er,width:this.state.width,height:this.state.height,presentationWidth:this.state.presentationWidth,presentationHeight:this.state.presentationHeight,linearClampSampler:this.state.linearClampSampler,nearestClampSampler:this.state.nearestClampSampler,comparisonSampler:this.state.shadowComparisonSampler,getColorView:e=>this.getColorTargetView(e),getTextureView:e=>this.getGraphTextureView(e),getExternalTexture:e=>{const t=this.textureManager.getTextureResource(e);return{view:t.view,sampler:t.sampler}},getColorFormat:e=>this.getColorTargetFormat(e),getShadowMapDebugInfo:()=>({directional:{view:this.state.directionalShadowView,size:this.state.directionalShadowTextureSize,layerCount:4,activeLightCount:s.lights.directionals.length,activeLayerCount:s.lights.directionals.length},point:{view:this.state.pointShadowArrayView,size:this.state.pointShadowTextureSize,layerCount:24,activeLightCount:s.lights.points.length,activeLayerCount:6*s.lights.points.length},spot:{view:this.state.spotShadowView,size:this.state.spotShadowTextureSize,layerCount:4,activeLightCount:s.lights.spots.length,activeLayerCount:s.lights.spots.length}}),getSceneLightingResources:()=>{if(!(this.state.lightBuffer&&this.state.directionalShadowView&&this.state.pointShadowArrayView&&this.state.spotShadowView))throw new Error("Renderer scene lighting resources are not initialized.");return{lightBuffer:this.state.lightBuffer,directionalShadowView:this.state.directionalShadowView,pointShadowView:this.state.pointShadowArrayView,spotShadowView:this.state.spotShadowView}}};return{addDirectionalShadowPass:()=>{e.addPass(new fr("DirectionalShadowPass",()=>{this.executeDirectionalShadowPass(t,n,s,o)},{writes:["directionalShadow"]}))},addPointShadowPass:()=>{s.lights.points.some(e=>e.castShadow)&&e.addPass(new fr("PointShadowPass",()=>{this.executePointShadowPass(t,n,s,o)},{writes:["pointShadow"]}))},addSpotShadowPass:()=>{s.lights.spots.some(e=>e.castShadow)&&e.addPass(new fr("SpotShadowPass",()=>{this.executeSpotShadowPass(t,n,s,o)},{writes:["spotShadow"]}))},addDepthPrepass:()=>{c=!0,this.getHiZOcclusionCullingActive()&&this.hasEnabledStaticDrawSets()&&e.addPass(new fr("TemporalStaticVisibilityPrepass",()=>{this.executeStaticVisibilityPasses(t,"prepass")},{reads:["hiz"],writes:["staticIndirectArgs"]})),e.addPass(new fr("DepthPrepass",()=>{this.executeDepthPrepass(t,r,s,o)},{writes:["mainDepth"]}))},addHiZPasses:()=>{this.getHiZOcclusionCullingActive()&&e.addPass(new fr("HiZPasses",()=>{this.executeHiZPasses(t)},{reads:["mainDepth"],writes:["hiz"]}))},addVisibilityPass:()=>{this.getHiZOcclusionCullingActive()&&(i||this.hasEnabledStaticDrawSets())&&(e.addPass(new fr("VisibilityPass",()=>{i&&this.executeVisibilityPass(t,i),this.executeStaticVisibilityPasses(t,"postpass")},{reads:["hiz"],writes:["indirectArgs","staticIndirectArgs"]})),this.hasEnabledStaticDrawSets()&&e.addPass(new fr("TemporalStaticDepthResolvePass",()=>{this.executeStaticTemporalDepthResolvePass(t)},{reads:["staticIndirectArgs"],writes:["mainDepth"]})))},defineColorTarget:(e,t={})=>{this.ensureColorTarget(e,t)},defineTextureTarget:(e,t={})=>{this.ensureTextureTarget(e,t)},addForwardPass:(n="sceneColor")=>{const i=!c,a=[...s.gpuOpaqueDraws,...s.directOpaqueDraws,...s.transparentDraws],h=d(a);if(l?.push({draws:a,colorTargetFormats:[this.getColorTargetFormat(n)],sampleCount:this.sampleCount}),h.includes("mainDepth")){if(!c)throw new Error("Materials that sample mainDepth require a depth prepass.");e.addPass(new fr("ForwardDepthSnapshotPass",()=>{this.state.mainDepthTexture&&this.state.sceneDepthSnapshotTexture&&t.copyTextureToTexture({texture:this.state.mainDepthTexture},{texture:this.state.sceneDepthSnapshotTexture},{width:this.state.width,height:this.state.height})},{reads:["mainDepth"],writes:["sceneDepthSnapshot"]})),u=!0}e.addPass(new fr("ForwardPass",()=>{this.executeForwardPass(t,n,this.getColorTargetView(n),r,s,o,i)},{reads:["directionalShadow","pointShadow","spotShadow","mainDepth","indirectArgs",...h.map(e=>"mainDepth"===e?"sceneDepthSnapshot":e)],writes:[n]})),this.getHiZOcclusionCullingActive()&&this.hasEnabledStaticDrawSets()&&e.addPass(new fr("TemporalHiZHistoryPass",()=>{this.executeHiZPasses(t,!0)},{reads:["mainDepth"],writes:["hiz"],dependsOn:["ForwardPass"]}))},addOpaquePass:(n="sceneColor")=>{const i=!c,a=[...s.gpuOpaqueDraws,...s.directOpaqueDraws],h=d(a);if(l?.push({draws:a,colorTargetFormats:[this.getColorTargetFormat(n)],sampleCount:this.sampleCount}),h.includes("mainDepth")){if(!c)throw new Error("Materials that sample mainDepth require a depth prepass.");e.addPass(new fr("OpaqueDepthSnapshotPass",()=>{this.state.mainDepthTexture&&this.state.sceneDepthSnapshotTexture&&t.copyTextureToTexture({texture:this.state.mainDepthTexture},{texture:this.state.sceneDepthSnapshotTexture},{width:this.state.width,height:this.state.height})},{reads:["mainDepth"],writes:["sceneDepthSnapshot"]})),u=!0}e.addPass(new fr("OpaquePass",()=>{this.executeForwardPass(t,n,this.getColorTargetView(n),r,s,o,i,"opaque")},{reads:["directionalShadow","pointShadow","spotShadow","mainDepth","indirectArgs",...h.map(e=>"mainDepth"===e?"sceneDepthSnapshot":e)],writes:[n]}))},addSceneTextureCopyPass:(r="sceneColor")=>{if(!(s.transparentDraws.some(e=>e.material.usesSceneTextures())||d(s.transparentDraws).includes("mainDepth")))return;const n=this.getColorTargetDimensions(r);if(n.width!==this.state.width||n.height!==this.state.height||this.getColorTargetFormat(r)!==Er)throw new Error("Scene texture snapshots currently require a full-resolution rgba16float source.");e.addPass(new fr("SceneTextureCopyPass",()=>{this.state.sceneColorSnapshotTexture&&this.state.sceneDepthSnapshotTexture&&this.state.mainDepthTexture&&(t.copyTextureToTexture({texture:this.getColorTargetTexture(r)},{texture:this.state.sceneColorSnapshotTexture},{width:this.state.width,height:this.state.height}),t.copyTextureToTexture({texture:this.state.mainDepthTexture},{texture:this.state.sceneDepthSnapshotTexture},{width:this.state.width,height:this.state.height}))},{reads:[r,"mainDepth"],writes:["sceneColorSnapshot","sceneDepthSnapshot"]})),u=!0},addLatePass:(n="sceneColor")=>{if(0===s.transparentDraws.length)return;l?.push({draws:s.transparentDraws,colorTargetFormats:[this.getColorTargetFormat(n)],sampleCount:1});const i=[n,"mainDepth",...d(s.transparentDraws)];s.transparentDraws.some(e=>e.material.usesSceneTextures())&&i.push("sceneColorSnapshot","sceneDepthSnapshot"),e.addPass(new fr("LatePass",()=>{this.executeForwardPass(t,n,this.getColorTargetView(n),r,s,o,!1,"late",!0,1)},{reads:i,writes:[n,"mainDepth"]}))},addHiZHistoryPass:(r="ForwardPass")=>{if(!this.getHiZOcclusionCullingActive()||!this.hasEnabledStaticDrawSets())return;const n="LatePass"===r&&0===s.transparentDraws.length?"OpaquePass":r;e.addPass(new fr("TemporalHiZHistoryPass",()=>{this.executeHiZPasses(t,!0)},{reads:["mainDepth"],writes:["hiz"],dependsOn:[n]}))},addMaterialPass:(n={})=>{const i="string"==typeof n.outputs?[n.outputs]:Array.from(n.outputs??["sceneColor"]),a=n.drawStage??"all",c="opaque"===a?[...s.gpuOpaqueDraws,...s.directOpaqueDraws]:"late"===a?s.transparentDraws:[...s.gpuOpaqueDraws,...s.directOpaqueDraws,...s.transparentDraws],u=n.objectFilter?c.filter(e=>n.objectFilter(e.sourceObject)||!0===e.sourceRanges?.some(e=>n.objectFilter(e.sourceObject))):c,d=e=>"function"==typeof n.overrideMaterial?n.overrideMaterial(e.material,null!==e.skinning):n.overrideMaterial,h=n.overrideMaterial?u.map(e=>({...e,material:d(e)})):u;l?.push({draws:h,colorTargetFormats:i.map(e=>this.getColorTargetFormat(e)),sampleCount:this.sampleCount}),e.addPass(new fr(n.name??"MaterialPass",()=>{this.executeMaterialPass(t,i,r,s,o,n)},{reads:["directionalShadow","pointShadow","spotShadow",...n.loadDepth?["mainDepth"]:[],...n.loadColor?i:[]],writes:this.sampleCount>1?i:[...i,"mainDepth"]}))},addCustomPass:t=>{e.addPass(new fr(t.name,()=>{t.execute(h)},{reads:t.reads,writes:t.writes,dependsOn:t.dependsOn}))},addPresentPass:(r="sceneColor")=>{e.addPass(new fr("PresentPass",()=>{const e=this.getColorTargetView(r);this.executePresentPass(t,e,a)},{reads:[r],writes:["mainColor"]}))}}}transparentDraws=[];opaqueBatches=new Map;acquireDrawCall(){const e=this.drawCallPoolCount;this.drawCallPoolCount+=1;let t=this.drawCallPool[e];return t||(t={geometry:null,geometryKey:{},geometryResource:null,material:null,customDepthMaterial:null,residentInstanceBinding:null,sourceObject:null,usesBatching:!1,geometryGroup:null,batchKey:"",batchHash:0,indexed:!1,wireframe:!1,start:0,count:0,transparent:!1,renderOrder:0,hasRenderCallbacks:!1,castShadow:!0,receiveShadow:!0,sortMaterialId:0,sortGeometryId:0,sortCustomDepthMaterialId:0,skinning:null,materialResource:null,instanceStart:0,instanceCount:0,boundsCenter:new mt,boundsRadius:0,sortDepth:0,transparentSortGroup:0,transparentSortOrder:0},this.drawCallPool[e]=t),t}acquireOpaqueBatchBuilder(){const e=this.opaqueBatchPoolCount;this.opaqueBatchPoolCount+=1;let t=this.opaqueBatchPool[e];return t||(t={template:null,totalInstanceCount:0,rangePairCount:0,firstInstanceStart:0,firstInstanceCount:0,sourceRanges:[],boundsMin:new mt,boundsMax:new mt},this.opaqueBatchPool[e]=t),t}populateDrawCall(e,t,r,n,i,a,s,o){const l=t.wireframe;l&&this.ensureWireframeIndex(t.geometry,t.geometryResource);const c=t.sourceObject?Boolean(t.sourceObject.receiveShadow):t.receiveShadow;return this.shouldInvalidateDrawMaterialResource(e,t.material,c,t.usesBatching,null)&&(e.materialResource=null),e.geometry=t.geometry,e.geometryKey=l?t.geometryResource.wireframeIndex:t.geometryKey,e.geometryResource=t.geometryResource,e.material=t.material,e.customDepthMaterial=t.customDepthMaterial,e.residentInstanceBinding=t.residentInstanceBinding,e.sourceObject=t.sourceObject,e.usesBatching=t.usesBatching,e.geometryGroup=t.geometryGroup,e.batchKey=t.batchKey,e.batchHash=t.batchHash,e.indexed=l||t.indexed,e.wireframe=l,e.start=l?2*t.start:t.start,e.count=l?2*t.count:t.count,e.transparent=t.transparent,e.renderOrder=t.sourceObject?.renderOrder??t.renderOrder,e.hasRenderCallbacks=this.hasRenderCallbacks(t.sourceObject),e.castShadow=t.sourceObject?Boolean(t.sourceObject.castShadow):t.castShadow,e.receiveShadow=c,e.sortMaterialId=t.sortMaterialId,e.sortGeometryId=t.sortGeometryId,e.sortCustomDepthMaterialId=t.sortCustomDepthMaterialId,e.skinning=null,e.instanceStart=r,e.instanceCount=n,e.boundsCenter.set(i,a,s),e.boundsRadius=o,e.sortDepth=0,e.transparentSortGroup=0,e.transparentSortOrder=0,e.sourceRanges=void 0,e}populateDynamicDrawCall(e,t,r,n,i,a,s,o,l,c,u,d,h,p,f,m,g,x,v,w,b,y,S,C,P,M,B,D,T=null){const I=!0===o?.isBatchedMesh,G=i.wireframe&&"triangle-list"===i.primitiveTopology;return G&&this.ensureWireframeIndex(t,n),this.shouldInvalidateDrawMaterialResource(e,i,v,I,T)&&(e.materialResource=null),e.geometry=t,e.geometryKey=G?n.wireframeIndex:r,e.geometryResource=n,e.material=i,e.customDepthMaterial=a,e.residentInstanceBinding=s,e.sourceObject=o,e.usesBatching=I,e.geometryGroup=l,e.batchKey=c,e.batchHash=u,e.indexed=G||d,e.wireframe=G,e.start=G?2*h:h,e.count=G?2*p:p,e.transparent=f,e.renderOrder=m,e.hasRenderCallbacks=g,e.castShadow=x,e.receiveShadow=v,e.sortMaterialId=w,e.sortGeometryId=b,e.sortCustomDepthMaterialId=y,e.skinning=T,e.instanceStart=S,e.instanceCount=C,e.boundsCenter.set(P,M,B),e.boundsRadius=D,e.sortDepth=0,e.transparentSortGroup=0,e.transparentSortOrder=0,e.sourceRanges=void 0,e}pushOpaqueDrawTemplate(e,t,r,n,i,a,s){const o=e.batchHash,l=this.opaqueBatches.get(o);let c=null;if(l)if(Array.isArray(l))for(let t=0;t<l.length;t+=1){const r=l[t];if(In(r.template,e)){c=r;break}}else In(l.template,e)&&(c=l);if(c){if(c.totalInstanceCount+=r,1===c.rangePairCount){const e=c.sourceRanges;e.length=4,e[0]=c.firstInstanceStart,e[1]=c.firstInstanceCount,e[2]=t,e[3]=r}else{const e=c.sourceRanges,n=2*c.rangePairCount;e[n]=t,e[n+1]=r}c.rangePairCount+=1;const e=c.boundsMin,o=c.boundsMax,l=n-s,u=i-s,d=a-s,h=n+s,p=i+s,f=a+s;return l<e.x&&(e.x=l),u<e.y&&(e.y=u),d<e.z&&(e.z=d),h>o.x&&(o.x=h),p>o.y&&(o.y=p),void(f>o.z&&(o.z=f))}const u=this.acquireOpaqueBatchBuilder();u.template=e,u.totalInstanceCount=r,u.rangePairCount=1,u.firstInstanceStart=t,u.firstInstanceCount=r,u.sourceRanges.length=0,u.boundsMin.set(n-s,i-s,a-s),u.boundsMax.set(n+s,i+s,a+s),l?Array.isArray(l)?l.push(u):this.opaqueBatches.set(o,[l,u]):this.opaqueBatches.set(o,u)}pushDraw(e){e.transparent?this.transparentDraws.push(e):e.skinning||e.hasRenderCallbacks&&e.residentInstanceBinding?this.directOpaqueDrawsScratch.push(e):e.residentInstanceBinding?this.residentOpaqueDrawsScratch.push(e):this.stagedOpaqueDrawsScratch.push(e)}getToonOutlineParameters(e){if(!e||!e.visible||!0===e.wireframe||!e.depthTest)return null;const t=e.userData?.outlineParameters;return t&&!1!==t.visible?t:null}getToonOutlineMaterial(e,t){const r=this.getToonOutlineParameters(e);if(!r)return null;let n=this.toonOutlineMaterialCache.get(e);if(!n){const t=t=>new kt({vertexShader:t?"\nstruct VertexInput {\n @location(0) position: vec3<f32>,\n @location(1) normal: vec3<f32>,\n @location(4) skinIndex: vec4<u32>,\n @location(5) skinWeight: vec4<f32>,\n @builtin(instance_index) instanceIndex: u32,\n};\n\nstruct VertexOutput {\n @builtin(position) position: vec4<f32>,\n};\n\n@vertex\nfn vsMain(input: VertexInput) -> VertexOutput {\n let localPosition = rendererSkinPosition(input.position, input.skinIndex, input.skinWeight);\n let localNormal = rendererSkinNormal(input.normal, input.skinIndex, input.skinWeight);\n let worldPosition = rendererWorldPosition(localPosition, input.instanceIndex);\n let viewPosition = rendererCamera.view * worldPosition;\n let worldNormal = rendererWorldNormal(localNormal, input.instanceIndex);\n let viewNormal = normalize((rendererCamera.view * vec4(worldNormal, 0.0)).xyz);\n let distanceScale = sqrt(max(length(viewPosition.xyz), 0.0001)) * 0.5;\n let displaced = viewPosition.xyz + viewNormal * materialUniforms.outlineThickness * distanceScale;\n return VertexOutput(rendererCamera.projection * vec4(displaced, 1.0));\n}\n":"\nstruct VertexInput {\n @location(0) position: vec3<f32>,\n @location(1) normal: vec3<f32>,\n @builtin(instance_index) instanceIndex: u32,\n};\n\nstruct VertexOutput {\n @builtin(position) position: vec4<f32>,\n};\n\n@vertex\nfn vsMain(input: VertexInput) -> VertexOutput {\n let worldPosition = rendererWorldPosition(input.position, input.instanceIndex);\n let viewPosition = rendererCamera.view * worldPosition;\n let worldNormal = rendererWorldNormal(input.normal, input.instanceIndex);\n let viewNormal = normalize((rendererCamera.view * vec4(worldNormal, 0.0)).xyz);\n let distanceScale = sqrt(max(length(viewPosition.xyz), 0.0001)) * 0.5;\n let displaced = viewPosition.xyz + viewNormal * materialUniforms.outlineThickness * distanceScale;\n return VertexOutput(rendererCamera.projection * vec4(displaced, 1.0));\n}\n",fragmentShader:"\n@fragment\nfn fsMain() -> @location(0) vec4<f32> {\n return vec4(materialUniforms.outlineColor, materialUniforms.outlineAlpha);\n}\n",vertexAttributes:t?Oi:[{name:"position",shaderLocation:0,format:"float32x3"},{name:"normal",shaderLocation:1,format:"float32x3",defaultValue:[0,0,1]}],uniforms:{outlineThickness:r.thickness??.003,outlineColor:(new nt).fromArray(r.color??[0,0,0]),outlineAlpha:r.alpha??e.opacity},side:et,depthTest:!0,depthWrite:!0,transparent:!0});n={regular:t(!1),skinned:t(!0)},this.toonOutlineMaterialCache.set(e,n)}const i=t?n.skinned:n.regular;return i.uniforms.outlineThickness.value=r.thickness??.003,i.uniforms.outlineColor.value.fromArray(r.color??[0,0,0]),i.uniforms.outlineAlpha.value=r.alpha??e.opacity,i}pushToonOutlineDraw(e,t){const r=t?this.getToonOutlineMaterial(t,null!==e.skinning):null;if(!r||e.usesBatching)return;const n=this.populateDynamicDrawCall(this.acquireDrawCall(),e.geometry,e.geometryKey,e.geometryResource,r,null,e.residentInstanceBinding,e.sourceObject,e.geometryGroup,`toon-outline:${e.batchKey}`,Pn(Sn(r),Sn(e.geometryKey),e.indexed,e.start,e.count,0),e.indexed,e.start,e.count,!0,e.renderOrder,!1,!1,!1,Sn(r),e.sortGeometryId,0,e.instanceStart,e.instanceCount,e.boundsCenter.x,e.boundsCenter.y,e.boundsCenter.z,e.boundsRadius,e.skinning);this.transparentDraws.push(n)}updateTransparentDrawSortDepths(e,t,r){for(let n=0;n<e.length;n+=1){const i=e[n];0===i.transparentSortGroup&&(i.sortDepth=(i.boundsCenter.x-t.x)*r.x+(i.boundsCenter.y-t.y)*r.y+(i.boundsCenter.z-t.z)*r.z)}}extractScene(e,t){this.extractionVersion+=1,this.drawCallPoolCount=0,this.opaqueBatchPoolCount=0;this.opaqueBatches.clear();const r=this.transparentDraws;r.length=0;const n=this.residentInstanceUploadsScratch;n.length=0;const i=this.sourceInstanceDataScratch;i.reset();const a=this.gpuOpaqueDrawsScratch;a.length=0;const s=this.directOpaqueDrawsScratch;s.length=0;const o=this.stagedOpaqueDrawsScratch;o.length=0;const l=this.residentOpaqueDrawsScratch;l.length=0;const c=this.opaqueInstanceDataScratch;c.reset();const u=this.finalInstanceDataScratch;u.reset();const d=this.extractedAmbientScratch;d.set(0,0,0,0);let h=null;const p=this.activeDirectionalLightsScratch,f=this.activePointLightsScratch,m=this.activeSpotLightsScratch;p.length=0,f.length=0,m.length=0;const g=this.extractedBoundsMinScratch;g.set(1/0,1/0,1/0);const x=this.extractedBoundsMaxScratch;x.set(-1/0,-1/0,-1/0),function(e,t){const r=e.elements,n=r[0],i=r[1],a=r[2],s=r[3],o=r[4],l=r[5],c=r[6],u=r[7],d=r[8],h=r[9],p=r[10],f=r[11],m=r[12],g=r[13],x=r[14],v=r[15];An(t,0,s-n,u-o,f-d,v-m),An(t,4,s+n,u+o,f+d,v+m),An(t,8,s+i,u+l,f+h,v+g),An(t,12,s-i,u-l,f-h,v-g),An(t,16,s-a,u-c,f-p,v-x),An(t,20,a,c,p,x)}(Vn(t,this.cameraViewProjScratch),this.cameraFrustumPlanesScratch);const v=this.transparentSortCameraPositionScratch,w=this.transparentSortCameraForwardScratch;t.getWorldPosition(v),t.getWorldDirection(w);const b=this.isSphereVisibleScratch,y=this.updateExtractedBoundsFromMatrixScratch,S=this.objectTraversalStackScratch;S.length=0,S.push(e);for(let e=this.csmCascadeLights.length-1;e>=0;e-=1)S.push(this.csmCascadeLights[e]);for(;S.length>0;){const e=S.pop();if(!e.visible)continue;const r=0!==(e.layers.mask&t.layers.mask);if(e.isAmbientLight){if(r){const t=e;d.x+=t.color.r*t.intensity,d.y+=t.color.g*t.intensity,d.z+=t.color.b*t.intensity,d.w=1}}else if(e.isHemisphereLight){if(r&&null==h){const t=e,r=this.extractedHemisphereScratch;Hr.setFromMatrixPosition(t.matrixWorld),r.direction.copy(Hr),r.direction.lengthSq()<=1e-10?r.direction.set(0,1,0):r.direction.normalize(),r.skyColor.set(t.color.r,t.color.g,t.color.b),r.groundColor.set(t.groundColor.r,t.groundColor.g,t.groundColor.b),r.intensity=t.intensity,h=r}}else if(e.isDirectionalLight){if(r&&p.length<4&&!this.hasExtractedDirectionalLight(p,e)){const t=e,r=t.shadow,n=r.camera,i=this.extractedDirectionalLightsScratch[p.length];i.sourceLight=t,t.target.matrixWorldAutoUpdate&&t.target.updateMatrixWorld(!0),Hr.setFromMatrixPosition(t.matrixWorld),Kr.setFromMatrixPosition(t.target.matrixWorld),i.position.copy(Hr),i.target.copy(Kr),i.direction.copy(Kr).sub(Hr).normalize(),i.color.set(t.color.r,t.color.g,t.color.b),i.intensity=t.intensity,i.castShadow=t.castShadow,i.shadowBias=r.bias,i.shadowNormalBias=r.normalBias,i.shadowRadius=r.radius,i.shadowIntensity=r.intensity,i.shadowMapSize=Math.max(1,r.mapSize.width,r.mapSize.height),i.shadowCameraLeft=n.left,i.shadowCameraRight=n.right,i.shadowCameraTop=n.top,i.shadowCameraBottom=n.bottom,i.shadowCameraNear=n.near,i.shadowCameraFar=n.far,p.push(i)}}else if(e.isPointLight){if(r&&f.length<4){const t=e,r=t.shadow,n=r.camera,i=this.extractedPointLightsScratch[f.length];Hr.setFromMatrixPosition(t.matrixWorld),i.position.copy(Hr),i.color.set(t.color.r,t.color.g,t.color.b),i.intensity=t.intensity,i.range=t.distance>0?t.distance:Math.max(n.far,25),i.castShadow=t.castShadow,i.shadowBias=r.bias,i.shadowNormalBias=r.normalBias,i.shadowRadius=r.radius,i.shadowIntensity=r.intensity,i.shadowMapSize=Math.max(1,r.mapSize.width,r.mapSize.height),i.shadowCameraNear=n.near,i.shadowCameraFar=t.distance>0?t.distance:n.far,f.push(i)}}else if(e.isSpotLight){if(r&&m.length<4){const t=e,r=t.shadow,n=r.camera,i=this.extractedSpotLightsScratch[m.length];t.target.matrixWorldAutoUpdate&&t.target.updateMatrixWorld(!0),Hr.setFromMatrixPosition(t.matrixWorld),Kr.setFromMatrixPosition(t.target.matrixWorld),i.position.copy(Hr),i.direction.copy(Kr).sub(Hr).normalize(),i.color.set(t.color.r,t.color.g,t.color.b),i.intensity=t.intensity,i.range=t.distance>0?t.distance:n.far,i.angle=t.angle,i.penumbra=t.penumbra,i.decay=t.decay,i.castShadow=t.castShadow,i.shadowBias=r.bias,i.shadowNormalBias=r.normalBias,i.shadowRadius=r.radius,i.shadowIntensity=r.intensity,i.shadowMapSize=Math.max(1,r.mapSize.width,r.mapSize.height),i.shadowCameraNear=n.near,i.shadowCameraFar=t.distance>0?t.distance:n.far,i.shadowCameraFov=n.fov,m.push(i)}}else r&&e.isBatchedMesh?this.collectBatchedMesh(e,i,y,b,t,v,w):r&&e.isInstancedMesh?this.collectInstancedMesh(e,i,y,b):r&&e.isSkinnedMesh?this.collectSkinnedMesh(e,i,y,b):r&&e.isLine?this.collectLine(e,i,y,b):r&&e.isSprite?this.collectSprite(e,i,y,b):r&&e.isMesh&&this.collectMesh(e,i,y,b);const n=e.children;for(let e=n.length-1;e>=0;e-=1)S.push(n[e])}if(this.csmCascadeLights.length>0){const e=new Map;for(let t=0;t<this.csmCascadeLights.length;t+=1)e.set(this.csmCascadeLights[t],t);p.sort((t,r)=>((null==t.sourceLight?void 0:e.get(t.sourceLight))??4)-((null==r.sourceLight?void 0:e.get(r.sourceLight))??4))}const C=s.length;this.updateTransparentDrawSortDepths(r,v,w),r.sort(Bn),Number.isFinite(g.x)||(g.set(-6,-6,-6),x.set(6,6,6)),o.sort(Mn);for(let e=0;e<o.length;){const t=o[e],r=c.instanceCount;c.appendRange(i,t.instanceStart,t.instanceCount);let n,l=t.instanceCount,u=t.boundsCenter.x-t.boundsRadius,d=t.boundsCenter.y-t.boundsRadius,h=t.boundsCenter.z-t.boundsRadius,p=t.boundsCenter.x+t.boundsRadius,f=t.boundsCenter.y+t.boundsRadius,m=t.boundsCenter.z+t.boundsRadius,g=e+1;for(;this.dynamicBatchingEnabled&&g<o.length&&Gn(t,o[g]);){const e=o[g];c.appendRange(i,e.instanceStart,e.instanceCount),n??=[{sourceObject:t.sourceObject,instanceStart:r,instanceCount:t.instanceCount}],n.push({sourceObject:e.sourceObject,instanceStart:r+l,instanceCount:e.instanceCount}),l+=e.instanceCount;const a=e.boundsCenter.x-e.boundsRadius,s=e.boundsCenter.y-e.boundsRadius,x=e.boundsCenter.z-e.boundsRadius,v=e.boundsCenter.x+e.boundsRadius,w=e.boundsCenter.y+e.boundsRadius,b=e.boundsCenter.z+e.boundsRadius;a<u&&(u=a),s<d&&(d=s),x<h&&(h=x),v>p&&(p=v),w>f&&(f=w),b>m&&(m=b),g+=1}const x=.5*(u+p),v=.5*(d+f),w=.5*(h+m),b=p-x,y=f-v,S=m-w;t.instanceStart=r,t.instanceCount=l,t.sourceRanges=n,t.boundsCenter.set(x,v,w),t.boundsRadius=Math.sqrt(b*b+y*y+S*S),t.indexed&&!t.hasRenderCallbacks?a.push(t):s.push(t),e=g}l.sort(Mn);for(let e=0;e<l.length;e+=1){const t=l[e];t.indexed&&!t.hasRenderCallbacks?a.push(t):s.push(t)}u.appendBuilder(c);for(let e=0;e<C;e+=1){const t=s[e];if(t.residentInstanceBinding)continue;const r=u.instanceCount;u.appendRange(i,t.instanceStart,t.instanceCount),t.instanceStart=r}a.sort(Mn),s.sort(Mn);for(let e=0;e<r.length;e+=1){const t=r[e];if(t.residentInstanceBinding)continue;const n=u.instanceCount;u.appendRange(i,t.instanceStart,t.instanceCount),t.instanceStart=n}const P=this.extractedLightsScratch;P.hemisphere=h,P.directional=p[0]??null,P.point=f[0]??null,P.spot=m[0]??null;const M=this.extractedFrameScratch;return M.scene=e,M.camera=t,M.transparentDraws=r,M.instanceData=u,M.residentInstanceUploads=n,M}collectLine(e,t,r,n){if(Array.isArray(e.material)||!e.geometry.getAttribute("position"))return;const i=e.geometry,a=e.material;if(!1===a.visible)return;if((!0===a.isLineBasicMaterial||!0===a.isMeshBasicMaterial)&&!0!==a.isLineMaterial){const s=e.isLineSegments?"line-list":"line-strip",o=this.resolveLineBasicMaterial(a,s),l=`${Qr(i)}:${s}`;let c=this.lineProxyCache.get(e);c&&c.signature===l||(c={signature:l,mesh:new ct(i,o)},this.lineProxyCache.set(e,c));const u=c.mesh;return u.material=o,u.matrixWorld.copy(e.matrixWorld),u.frustumCulled=e.frustumCulled,u.renderOrder=e.renderOrder,u.castShadow=!1,u.receiveShadow=!1,u.onBeforeRender=(...t)=>e.onBeforeRender(...t),void this.collectMesh(u,t,r,n)}const s=Qr(i);let o=this.lineProxyCache.get(e);if(!o||o.signature!==s){const t=i.getAttribute("position"),r=i.index,n=r?.count??t.count,a=Math.max(0,Math.min(n,i.drawRange.start)),l=Number.isFinite(i.drawRange.count)?i.drawRange.count:n-a,c=Math.max(a,Math.min(n,a+l)),u=e.isLineSegments?2:1,d=[],h=[],p=e=>r?r.getX(e):e;for(let e=a;e+1<c;e+=u){const r=p(e),n=p(e+1);d.push(t.getX(r),t.getY(r),t.getZ(r)),h.push(t.getX(n),t.getY(n),t.getZ(n))}const f=new rt;f.setIndex([0,2,1,2,3,1,2,4,3,4,5,3,4,6,5,6,7,5]),f.setAttribute("position",new tt(new Float32Array([-1,2,0,1,2,0,-1,1,0,1,1,0,-1,0,0,1,0,0,-1,-1,0,1,-1,0]),3)),f.setAttribute("instanceStart",new st(new Float32Array(d),3)),f.setAttribute("instanceEnd",new st(new Float32Array(h),3)),f.instanceCount=d.length/3;const m=Fn(i);f.boundingSphere=new ht(m.center.clone(),m.radius),o={signature:s,mesh:new ct(f,e.material)},this.lineProxyCache.set(e,o)}const l=o.mesh;l.matrixWorld.copy(e.matrixWorld),l.frustumCulled=e.frustumCulled,l.renderOrder=e.renderOrder,l.castShadow=e.castShadow??!1,l.receiveShadow=e.receiveShadow??!1,l.onBeforeRender=(...t)=>e.onBeforeRender(...t),this.collectMesh(l,t,r,n)}collectSprite(e,t,r,n){let i=this.spriteProxyCache.get(e);if(!i){const t=e.geometry.clone();i={mesh:new ct(t,e.material),centerX:Number.NaN,centerY:Number.NaN},this.spriteProxyCache.set(e,i)}if(i.centerX!==e.center.x||i.centerY!==e.center.y){const t=i.mesh.geometry.getAttribute("position"),r=e.geometry.getAttribute("position");for(let n=0;n<t.count;n+=1)t.setXYZ(n,r.getX(n)+.5-e.center.x,r.getY(n)+.5-e.center.y,r.getZ(n));t.needsUpdate=!0,i.mesh.geometry.computeBoundingSphere(),i.centerX=e.center.x,i.centerY=e.center.y}const a=i.mesh;a.material=e.material,a.matrixWorld.copy(e.matrixWorld),a.frustumCulled=e.frustumCulled,a.renderOrder=e.renderOrder,a.castShadow=e.castShadow,a.receiveShadow=e.receiveShadow,a.onBeforeRender=(...t)=>e.onBeforeRender(...t),a.onAfterRender=(...t)=>e.onAfterRender(...t),this.collectMesh(a,t,r,n)}hasExtractedDirectionalLight(e,t){for(let r=0;r<e.length;r+=1)if(e[r].sourceLight===t)return!0;return!1}collectMesh(e,t,r,n){const i=e.geometry;if(void 0===i.attributes.position)return;const a=e.material,s=Array.isArray(a);if(!s&&!1===a.visible||s&&a.every(e=>!1===e.visible))return;const o=this.resolvedMeshMaterialsScratch;o.length=0;let l=null;if(s)for(let e=0;e<a.length;e+=1)o[e]=this.resolveMaterial(a[e]);else{if(!a.visible)return;l=this.resolveMaterial(a)}const c=jn(e),u=this.meshExtractionCache.get(e),d=u&&u.customDepthMaterial===c&&u.geometryResource.lastValidatedExtractionVersion===this.extractionVersion&&(!s&&u.material===a&&u.resolvedMaterial===l||s&&null!==u.materials&&null!==u.resolvedMaterials&&an(u.materials,a)&&ln(u.resolvedMaterials,o))?u:this.getMeshExtractionCacheEntry(e,a,l,o,c,this.getGeometryResource(i)),h=d.templates.length;if(0===h)return;const p=e.matrixWorld.elements,f=d.localBoundsCenter,m=f.x,g=f.y,x=f.z,v=p[0]*m+p[4]*g+p[8]*x+p[12],w=p[1]*m+p[5]*g+p[9]*x+p[13],b=p[2]*m+p[6]*g+p[10]*x+p[14],y=p[0]*p[0]+p[1]*p[1]+p[2]*p[2],S=p[4]*p[4]+p[5]*p[5]+p[6]*p[6],C=p[8]*p[8]+p[9]*p[9]+p[10]*p[10],P=d.localBoundsRadius*Math.sqrt(Math.max(y,S,C,1e-10));if(!n(v,w,b,P,e.frustumCulled))return;const M=function(e){const t=e.attributes;let r=!1,n=1/0;for(const e in t){const i=t[e];!0!==i.isInstancedBufferAttribute&&!0!==i.data?.isInstancedInterleavedBuffer||(r=!0,i.count<n&&(n=i.count))}if(!r)return 1;const i=e.instanceCount;return Number.isFinite(i)?Math.max(0,Math.floor(i)):Math.max(0,n)}(i);let B=0;for(let e=0;e<M;e+=1){const r=wn(t,p,1,1,1,1);0===e&&(B=r)}r(p);for(let e=0;e<h;e+=1){const t=d.templates[e],r=this.populateDrawCall(this.acquireDrawCall(),t,B,M,v,w,b,P);t.transparent?this.transparentDraws.push(r):this.pushDraw(r);const n=s?a[t.geometryGroup?.materialIndex??0]:a;this.pushToonOutlineDraw(r,n)}}prepareSceneForCompilation(e,t,r){if(!(this.state.initialized&&this.state.device&&this.state.context&&this.state.mainDepthView&&this.state.sceneColorView&&this.state.postProcessColorView&&this.state.cameraBuffer&&this.state.lightBuffer&&this.state.shadowCameraBuffer&&this.state.sceneBindGroupLayout&&this.state.shadowBindGroupLayout&&this.state.shadowComparisonSampler&&this.state.linearClampSampler&&this.state.nearestClampSampler&&this.state.visibilityParamsBuffer&&this.state.directionalShadowView&&this.state.pointShadowArrayView&&this.state.spotShadowView&&this.state.hizCopyKernel&&this.state.hizReduceKernel&&this.state.visibilityKernel&&this.state.presentPipeline))throw new Error("WebGpuRenderer.initialize() must complete before compile().");e.matrixWorldAutoUpdate&&e.updateMatrixWorld(),null===t.parent&&t.matrixWorldAutoUpdate&&t.updateMatrixWorld();const n=this.extractScene(e,t);this.ensureShadowTextureSizes(n),this.uploadInstanceData(n.instanceData),this.uploadResidentInstanceData(n.residentInstanceUploads),this.uploadDrawMetadata(this.getHiZOcclusionCullingActive()?n.gpuOpaqueDraws:[]),this.updateCameraUniforms(t,e),this.updateLightUniforms(n);const i=this.compileDrawScratch;if(i.length=0,i.push(...n.gpuOpaqueDraws,...n.directOpaqueDraws,...n.transparentDraws),r){const e=[];this.renderGraph.reset();const t=this.state.device.createCommandEncoder({label:"renderer-graph-compilation-encoder"}),r=this.createGraphBuilderContext(this.renderGraph,t,this.getSharedSceneBindGroup(),this.getSharedShadowBindGroup(),null,this.state.sceneColorView,n,{drawCallCount:0,triangleCount:0},e);return this.graphBuilder(this.renderGraph,r),Promise.all([...e.map(e=>this.compileDrawMaterialsAsync(e.draws,e.colorTargetFormats,e.sampleCount)),...e.map(e=>this.compileStaticDrawMaterialsAsync(e.colorTargetFormats,e.sampleCount))]).then(async()=>{await(this.state.device?.queue.onSubmittedWorkDone())})}this.compileDrawMaterials(i)}collectInstancedMesh(e,t,r,n){if(void 0===e.geometry?.getAttribute("position"))return;const i=e.material;if(!1===i.visible)return;const a=this.instancedMeshExtractionCache.get(e),s=!0===e.userData.webGpuCacheMaterial&&a?.sourceMaterial===i&&a.sourceMaterialVersion===i.version&&a.material!==this.fallbackMaterial?a.material:this.resolveMaterial(i);if(!s)return;const o=jn(e),l=this.getGeometryResource(e.geometry),c=this.getInstancedMeshExtractionCacheEntry(e,s,o,l),u=e.instanceMatrix.array,d=e.instanceMatrix.version,h=e.instanceColor?.array,p=e.instanceColor?.itemSize??0,f=e.instanceColor?.version??-1,m=c.cacheValid&&c.cachedCount===e.count&&c.cachedInstanceMatrixVersion===d&&c.cachedInstanceColorVersion===f&&Ln(c.cachedMatrixWorld,e.matrixWorld.elements),g=zn(e.matrixWorld.elements),x=g&&!e.frustumCulled;if(!m){const t=c.cachedInstanceMatrixVersion!==d||c.cachedCount!==e.count,r=c.cachedInstanceColorVersion!==f||c.cachedCount!==e.count;if(x){const n=e.matrixWorld.elements,i=n[12]??0,a=n[13]??0,s=n[14]??0;c.cachedDrawBoundsCenter.set(i,a,s),c.cachedDrawBoundsRadius=0,c.cachedBoundsMin.set(i,a,s),c.cachedBoundsMax.set(i,a,s),c.cachedInstanceMatrixVersion=d,c.cachedInstanceColorVersion=f,c.cachedCount=e.count,c.cachedDefaultColorData=null,Rn(e.matrixWorld.elements,c.cachedMatrixWorld),c.residentBufferDirty||=t,c.residentColorBufferDirty||=r,c.cacheValid=!0}else{const t=c.cachedInstanceData.beginWriteInstances(e.count),r=c.cachedBoundsMin,n=c.cachedBoundsMax;r.set(1/0,1/0,1/0),n.set(-1/0,-1/0,-1/0);const i=c.localBoundsCenter,a=c.localBoundsRadius,s=e.matrixWorld.elements,o=zn(s),l=i.x,m=i.y,g=i.z,x=s[0],v=s[4],w=s[8],b=s[12],y=s[1],S=s[5],C=s[9],P=s[13],M=s[2],B=s[6],D=s[10],T=s[14],I=s[3],G=s[7],R=s[11],L=s[15];for(let i=0;i<e.count;i+=1){const e=16*i,s=i*Ur,c=u[e+0]??0,d=u[e+1]??0,f=u[e+2]??0,z=u[e+3]??0,U=u[e+4]??0,V=u[e+5]??0,A=u[e+6]??0,F=u[e+7]??0,E=u[e+8]??0,k=u[e+9]??0,O=u[e+10]??0,$=u[e+11]??0,j=u[e+12]??0,N=u[e+13]??0,W=u[e+14]??0,_=u[e+15]??0;let q,H,K,Z,Y,X,J,Q,ee,te,re,ne,ie,ae,se,oe;o?(q=c,H=d,K=f,Z=z,Y=U,X=V,J=A,Q=F,ee=E,te=k,re=O,ne=$,ie=j,ae=N,se=W,oe=_):(q=x*c+v*d+w*f+b*z,Y=x*U+v*V+w*A+b*F,ee=x*E+v*k+w*O+b*$,ie=x*j+v*N+w*W+b*_,H=y*c+S*d+C*f+P*z,X=y*U+S*V+C*A+P*F,te=y*E+S*k+C*O+P*$,ae=y*j+S*N+C*W+P*_,K=M*c+B*d+D*f+T*z,J=M*U+B*V+D*A+T*F,re=M*E+B*k+D*O+T*$,se=M*j+B*N+D*W+T*_,Z=I*c+G*d+R*f+L*z,Q=I*U+G*V+R*A+L*F,ne=I*E+G*k+R*O+L*$,oe=I*j+G*N+R*W+L*_),t[s+0]=q,t[s+1]=H,t[s+2]=K,t[s+3]=Z,t[s+4]=Y,t[s+5]=X,t[s+6]=J,t[s+7]=Q,t[s+8]=ee,t[s+9]=te,t[s+10]=re,t[s+11]=ne,t[s+12]=ie,t[s+13]=ae,t[s+14]=se,t[s+15]=oe;const le=i*p;t[s+16]=h?h[le+0]??1:1,t[s+17]=h?h[le+1]??1:1,t[s+18]=h?h[le+2]??1:1,t[s+19]=h&&p>=4?h[le+3]??1:1,t[s+20]=i,t[s+21]=0,t[s+22]=0,t[s+23]=0;const ce=q*l+Y*m+ee*g+ie,ue=H*l+X*m+te*g+ae,de=K*l+J*m+re*g+se,he=Math.sqrt(q*q+H*H+K*K),pe=Math.sqrt(Y*Y+X*X+J*J),fe=Math.sqrt(ee*ee+te*te+re*re),me=a*Math.max(he,pe,fe,1e-5);kn(r,n,Hr.set(ce,ue,de),me)}c.cachedDrawBoundsCenter.copy(r).add(n).multiplyScalar(.5);const z=n.x-c.cachedDrawBoundsCenter.x,U=n.y-c.cachedDrawBoundsCenter.y,V=n.z-c.cachedDrawBoundsCenter.z;c.cachedDrawBoundsRadius=Math.sqrt(z*z+U*U+V*V),c.cachedInstanceMatrixVersion=d,c.cachedInstanceColorVersion=f,c.cachedCount=e.count,c.cachedDefaultColorData=null,Rn(e.matrixWorld.elements,c.cachedMatrixWorld),c.residentBufferDirty=!0,c.residentColorBufferDirty=!0,c.cacheValid=!0}}if(!n(c.cachedDrawBoundsCenter.x,c.cachedDrawBoundsCenter.y,c.cachedDrawBoundsCenter.z,c.cachedDrawBoundsRadius,e.frustumCulled))return;c.residentInstanceBinding&&c.residentInstanceBinding.mode!==(g?"instanced-direct":"packed")&&(c.residentInstanceBinding.mode=g?"instanced-direct":"packed",c.residentInstanceBinding.sceneBindGroup=null,c.residentInstanceBinding.shadowBindGroup=null,c.residentInstanceBinding.shadowBindGroups.clear(),c.residentInstanceBinding.sceneBindGroupVersion=0,c.residentInstanceBinding.shadowBindGroupVersion=0,c.residentBufferDirty=!0,c.residentColorBufferDirty=!0),(c.residentBufferDirty||c.residentColorBufferDirty||!c.residentInstanceBinding)&&this.residentInstanceUploadsScratch.push(c),Un(this.extractedBoundsMinScratch,this.extractedBoundsMaxScratch,c.cachedBoundsMin,c.cachedBoundsMax);const v=this.populateDynamicDrawCall(this.acquireDrawCall(),e.geometry,e.geometry,l,s,o,c.residentInstanceBinding,e,null,c.batchKey,c.batchHash,c.indexed,c.drawRangeStart,c.drawRangeCount,s.transparent||s.requiresLatePass(),e.renderOrder,this.hasRenderCallbacks(e),e.castShadow,e.receiveShadow,c.sortMaterialId,c.sortGeometryId,c.sortCustomDepthMaterialId,0,e.count,c.cachedDrawBoundsCenter.x,c.cachedDrawBoundsCenter.y,c.cachedDrawBoundsCenter.z,c.cachedDrawBoundsRadius);x&&!v.transparent?this.directOpaqueDrawsScratch.push(v):this.pushDraw(v)}collectSkinnedMesh(e,t,r,n){if(void 0===e.geometry?.getAttribute("position"))return;const i=e.boundingSphere;if(e.frustumCulled&&null!==i){const t=i.center,r=e.matrixWorld.elements;if(!n(r[0]*t.x+r[4]*t.y+r[8]*t.z+r[12],r[1]*t.x+r[5]*t.y+r[9]*t.z+r[13],r[2]*t.x+r[6]*t.y+r[10]*t.z+r[14],i.radius*En(e.matrixWorld),!0))return}const a=Array.isArray(e.material)?e.material:[e.material],s=jn(e),o=null!==e.geometry.index,l=this.getSkinnedGeometryResource(e);this.refreshSkinningPalette(l.skinning.palette),this.refreshSkinningBindMatrices(e,l.skinning),this.updateSkinnedBounds(e,l);const c=Hr.copy(l.localBoundsCenter).applyMatrix4(e.matrixWorld),u=l.localBoundsRadius*En(e.matrixWorld);if(!n(c.x,c.y,c.z,u,e.frustumCulled))return;this.uploadSkinningResources(l.skinning);const d=bn(t,e.matrixWorld,1,1,1,1);if(r(e.matrixWorld.elements),e.geometry.groups.length>0&&a.length>0){for(const t of e.geometry.groups){const r=a[t.materialIndex??0]??a[0],n=this.resolveSkinnedMaterial(r);if(!n)continue;const i=Cn(n,e,o,t.start,pn(e.geometry,o,t.start,t.count),s),h=this.populateDynamicDrawCall(this.acquireDrawCall(),e.geometry,e,l.resource,n,s,null,e,t,i,Pn(Sn(n),Sn(e),o,t.start,pn(e.geometry,o,t.start,t.count),s?Sn(s):0),o,t.start,pn(e.geometry,o,t.start,t.count),n.transparent,e.renderOrder,this.hasRenderCallbacks(e),e.castShadow,e.receiveShadow,Sn(n),Sn(e),s?Sn(s):0,d,1,c.x,c.y,c.z,u,l.skinning);this.pushDraw(h),this.pushToonOutlineDraw(h,r)}return}const h=this.resolveSkinnedMaterial(a[0]);if(!h)return;const p=fn(e.geometry,o),f=Cn(h,e,o,p.start,p.count,s),m=this.populateDynamicDrawCall(this.acquireDrawCall(),e.geometry,e,l.resource,h,s,null,e,null,f,Pn(Sn(h),Sn(e),o,p.start,p.count,s?Sn(s):0),o,p.start,p.count,h.transparent,e.renderOrder,this.hasRenderCallbacks(e),e.castShadow,e.receiveShadow,Sn(h),Sn(e),s?Sn(s):0,d,1,c.x,c.y,c.z,u,l.skinning);this.pushDraw(m),this.pushToonOutlineDraw(m,a[0])}collectBatchedMesh(e,t,r,n,i,a,s){if(void 0===e.geometry?.getAttribute("position"))return;const o=this.resolveMaterial(e.material);if(!o)return;const l=jn(e),c=(e.geometry.index,this.getGeometryResource(e.geometry)),u=e,d=u._instanceInfo??u._drawInfo??[],h=d.length,p=u._matricesTexture?.image.data,f=u._colorsTexture?.image.data,m=this.getBatchedMeshExtractionCacheEntry(e,o,l,c,u),g=e.matrixWorld.elements,x=u._matricesTexture?.version??0,v=u._colorsTexture?.version??-1;if(m.cacheValid&&!o.transparent&&m.cachedMatricesVersion===x&&m.cachedColorsVersion===v&&m.cachedInstanceInfoLength===d.length&&m.cachedGeometryCount===(u._geometryCount??0)&&Ln(m.cachedMatrixWorld,g)&&this.batchedGeometryIdsMatchSnapshot(m.geometryIdsSnapshot,d)){let t=!1;for(let r=0;r<m.cachedDraws.length;r+=1){const i=m.cachedDraws[r];n(i.boundsCenter.x,i.boundsCenter.y,i.boundsCenter.z,i.boundsRadius,e.frustumCulled)&&(t=!0,this.pushDraw(this.populateDynamicDrawCall(this.acquireDrawCall(),i.template.geometry,i.template.geometryKey,i.template.geometryResource,i.template.material,i.template.customDepthMaterial,m.residentInstanceBinding,i.template.sourceObject,i.template.geometryGroup,i.template.batchKey,i.template.batchHash,i.template.indexed,i.template.start,i.template.count,i.template.transparent,i.template.sourceObject?.renderOrder??i.template.renderOrder,this.hasRenderCallbacks(i.template.sourceObject),i.template.sourceObject?Boolean(i.template.sourceObject.castShadow):i.template.castShadow,i.template.sourceObject?Boolean(i.template.sourceObject.receiveShadow):i.template.receiveShadow,i.template.sortMaterialId,i.template.sortGeometryId,i.template.sortCustomDepthMaterialId,i.instanceStart,i.instanceCount,i.boundsCenter.x,i.boundsCenter.y,i.boundsCenter.z,i.boundsRadius)))}if(!t)return;return!m.residentBufferDirty&&m.residentInstanceBinding||this.residentInstanceUploadsScratch.push(m),void Un(this.extractedBoundsMinScratch,this.extractedBoundsMaxScratch,m.cachedBoundsMin,m.cachedBoundsMax)}if(o.transparent){const o=[],l=!e.sortObjects||null!==e.customSort;for(let i=0;i<h;i+=1){const c=d[i];if(!c?.active||!c.visible)continue;const u=m.templates[c.geometryIndex];if(!u)continue;p?Wr.fromArray(p,16*i):e.getMatrixAt(i,Wr),_r.multiplyMatrices(e.matrixWorld,Wr);const h=u.localBoundsCenter,g=_r.elements,x=g[0]*h.x+g[4]*h.y+g[8]*h.z+g[12],v=g[1]*h.x+g[5]*h.y+g[9]*h.z+g[13],w=g[2]*h.x+g[6]*h.y+g[10]*h.z+g[14],b=Math.sqrt(g[0]*g[0]+g[1]*g[1]+g[2]*g[2]),y=Math.sqrt(g[4]*g[4]+g[5]*g[5]+g[6]*g[6]),S=Math.sqrt(g[8]*g[8]+g[9]*g[9]+g[10]*g[10]),C=u.localBoundsRadius*Math.max(b,y,S,1e-5);if(!n(x,v,w,C,e.frustumCulled&&e.perObjectFrustumCulled))continue;const P=f?f[4*i+0]??1:1,M=f?f[4*i+1]??1:1,B=f?f[4*i+2]??1:1,D=f?f[4*i+3]??1:1,T=bn(t,_r,P,M,B,D,i);r(_r.elements);const I=this.populateDrawCall(this.acquireDrawCall(),u,T,1,x,v,w,C),G=(x-a.x)*s.x+(v-a.y)*s.y+(w-a.z)*s.z;l?o.push({start:u.start,count:u.count,z:G,index:i,draw:I}):(I.sortDepth=G,this.transparentDraws.push(I))}if(l&&o.length>0){e.sortObjects&&e.customSort?e.customSort.call(e,o,i):e.sortObjects&&o.sort((e,t)=>t.z-e.z);let t=0;for(let e=0;e<o.length;e+=1)t+=o[e].z;t/=o.length;const r=Sn(e);for(let e=0;e<o.length;e+=1){const n=o[e].draw;n.sortDepth=t,n.transparentSortGroup=r,n.transparentSortOrder=e,this.transparentDraws.push(n)}}return}const w=m.activeGroups;for(let e=0;e<w.length;e+=1){const t=w[e];t.activeInFrame=!1,t.activeCount=0}w.length=0;const b=m.cachedBoundsMin,y=m.cachedBoundsMax;b.set(1/0,1/0,1/0),y.set(-1/0,-1/0,-1/0),m.geometryIdsSnapshot.length!==d.length&&(m.geometryIdsSnapshot=new Int32Array(d.length));let S=0;for(let e=0;e<h;e+=1){const t=d[e];if(!t?.active||!t.visible){m.geometryIdsSnapshot[e]=-1;continue}const r=m.groups[t.geometryIndex];r?(m.geometryIdsSnapshot[e]=t.geometryIndex,r.activeInFrame||(r.activeInFrame=!0,r.activeCount=0,r.boundsMin.set(1/0,1/0,1/0),r.boundsMax.set(-1/0,-1/0,-1/0),w.push(r)),r.activeCount+=1,S+=1):m.geometryIdsSnapshot[e]=-1}const C=m.cachedInstanceData.beginWriteInstances(S);let P=0;for(let e=0;e<w.length;e+=1){const t=w[e];t.instanceStart=P,t.writeOffset=P*Ur,P+=t.activeCount}const M=zn(g),B=g[0],D=g[4],T=g[8],I=g[12],G=g[1],R=g[5],L=g[9],z=g[13],U=g[2],V=g[6],A=g[10],F=g[14],E=g[3],k=g[7],O=g[11],$=g[15];for(let t=0;t<h;t+=1){const r=m.geometryIdsSnapshot[t]??-1;if(r<0)continue;const n=m.groups[r];if(!n)continue;let i,a,s,o,l,c,u,d,h,g,x,v,w,S,P,j,N,W,_,q,H,K,Z,Y,X,J,Q,ee,te,re,ne,ie;if(p){const e=16*t;i=p[e+0]??0,a=p[e+1]??0,s=p[e+2]??0,o=p[e+3]??0,l=p[e+4]??0,c=p[e+5]??0,u=p[e+6]??0,d=p[e+7]??0,h=p[e+8]??0,g=p[e+9]??0,x=p[e+10]??0,v=p[e+11]??0,w=p[e+12]??0,S=p[e+13]??0,P=p[e+14]??0,j=p[e+15]??0}else{e.getMatrixAt(t,Wr);const r=Wr.elements;i=r[0]??0,a=r[1]??0,s=r[2]??0,o=r[3]??0,l=r[4]??0,c=r[5]??0,u=r[6]??0,d=r[7]??0,h=r[8]??0,g=r[9]??0,x=r[10]??0,v=r[11]??0,w=r[12]??0,S=r[13]??0,P=r[14]??0,j=r[15]??0}M?(N=i,W=a,_=s,q=o,H=l,K=c,Z=u,Y=d,X=h,J=g,Q=x,ee=v,te=w,re=S,ne=P,ie=j):(N=B*i+D*a+T*s+I*o,H=B*l+D*c+T*u+I*d,X=B*h+D*g+T*x+I*v,te=B*w+D*S+T*P+I*j,W=G*i+R*a+L*s+z*o,K=G*l+R*c+L*u+z*d,J=G*h+R*g+L*x+z*v,re=G*w+R*S+L*P+z*j,_=U*i+V*a+A*s+F*o,Z=U*l+V*c+A*u+F*d,Q=U*h+V*g+A*x+F*v,ne=U*w+V*S+A*P+F*j,q=E*i+k*a+O*s+$*o,Y=E*l+k*c+O*u+$*d,ee=E*h+k*g+O*x+$*v,ie=E*w+k*S+O*P+$*j);const ae=f?f[4*t+0]??1:1,se=f?f[4*t+1]??1:1,oe=f?f[4*t+2]??1:1,le=f?f[4*t+3]??1:1,ce=n.writeOffset;C[ce+0]=N,C[ce+1]=W,C[ce+2]=_,C[ce+3]=q,C[ce+4]=H,C[ce+5]=K,C[ce+6]=Z,C[ce+7]=Y,C[ce+8]=X,C[ce+9]=J,C[ce+10]=Q,C[ce+11]=ee,C[ce+12]=te,C[ce+13]=re,C[ce+14]=ne,C[ce+15]=ie,C[ce+16]=ae,C[ce+17]=se,C[ce+18]=oe,C[ce+19]=le,C[ce+20]=t,C[ce+21]=0,C[ce+22]=0,C[ce+23]=0,n.writeOffset+=Ur;const ue=n.template.localBoundsCenter,de=N*ue.x+H*ue.y+X*ue.z+te,he=W*ue.x+K*ue.y+J*ue.z+re,pe=_*ue.x+Z*ue.y+Q*ue.z+ne,fe=Math.sqrt(N*N+W*W+_*_),me=Math.sqrt(H*H+K*K+Z*Z),ge=Math.sqrt(X*X+J*J+Q*Q),xe=n.template.localBoundsRadius*Math.max(fe,me,ge,1e-5),ve=de-xe,we=he-xe,be=pe-xe,ye=de+xe,Se=he+xe,Ce=pe+xe;ve<n.boundsMin.x&&(n.boundsMin.x=ve),we<n.boundsMin.y&&(n.boundsMin.y=we),be<n.boundsMin.z&&(n.boundsMin.z=be),ye>n.boundsMax.x&&(n.boundsMax.x=ye),Se>n.boundsMax.y&&(n.boundsMax.y=Se),Ce>n.boundsMax.z&&(n.boundsMax.z=Ce),ve<b.x&&(b.x=ve),we<b.y&&(b.y=we),be<b.z&&(b.z=be),ye>y.x&&(y.x=ye),Se>y.y&&(y.y=Se),Ce>y.z&&(y.z=Ce)}const j=m.cachedDraws;let N=0;for(let e=0;e<w.length;e+=1){const t=w[e],r=.5*(t.boundsMin.x+t.boundsMax.x),n=.5*(t.boundsMin.y+t.boundsMax.y),i=.5*(t.boundsMin.z+t.boundsMax.z),a=t.boundsMax.x-r,s=t.boundsMax.y-n,o=t.boundsMax.z-i,l=Math.sqrt(a*a+s*s+o*o);let c=j[N];c||(c={template:t.template,instanceStart:0,instanceCount:0,boundsCenter:new mt,boundsRadius:0},j[N]=c),c.template=t.template,c.instanceStart=t.instanceStart,c.instanceCount=t.activeCount,c.boundsCenter.set(r,n,i),c.boundsRadius=l,N+=1}j.length=N,m.cachedMatricesVersion=x,m.cachedColorsVersion=v,m.cachedInstanceInfoLength=d.length,m.cachedGeometryCount=u._geometryCount??0,Rn(g,m.cachedMatrixWorld),m.residentBufferDirty=!0,m.cacheValid=!0;let W=!1;for(let t=0;t<j.length;t+=1){const r=j[t];n(r.boundsCenter.x,r.boundsCenter.y,r.boundsCenter.z,r.boundsRadius,e.frustumCulled)&&(W=!0,this.pushDraw(this.populateDynamicDrawCall(this.acquireDrawCall(),r.template.geometry,r.template.geometryKey,r.template.geometryResource,r.template.material,r.template.customDepthMaterial,m.residentInstanceBinding,r.template.sourceObject,r.template.geometryGroup,r.template.batchKey,r.template.batchHash,r.template.indexed,r.template.start,r.template.count,r.template.transparent,r.template.sourceObject?.renderOrder??r.template.renderOrder,this.hasRenderCallbacks(r.template.sourceObject),r.template.sourceObject?Boolean(r.template.sourceObject.castShadow):r.template.castShadow,r.template.sourceObject?Boolean(r.template.sourceObject.receiveShadow):r.template.receiveShadow,r.template.sortMaterialId,r.template.sortGeometryId,r.template.sortCustomDepthMaterialId,r.instanceStart,r.instanceCount,r.boundsCenter.x,r.boundsCenter.y,r.boundsCenter.z,r.boundsRadius)))}W&&(this.residentInstanceUploadsScratch.push(m),Un(this.extractedBoundsMinScratch,this.extractedBoundsMaxScratch,b,y))}uploadInstanceData(e){if(!this.state.device)return;const t=Math.max(4,e.byteLength);(!this.state.instanceBuffer||t>this.state.instanceBufferSize)&&(this.state.instanceBuffer?.destroy(),this.state.instanceBufferSize=256*Math.ceil(t/256),this.state.instanceBuffer=this.state.device.createBuffer({label:"renderer-instance-buffer",size:this.state.instanceBufferSize,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST}),this.state.sharedSceneBindGroup=null,this.state.sharedShadowBindGroup=null,this.state.sharedShadowBindGroupByCameraBuffer.clear(),this.clearIndirectBundleCache()),e.floatLength>0?this.state.device.queue.writeBuffer(this.state.instanceBuffer,0,e.rawData.buffer,0,e.byteLength):this.state.device.queue.writeBuffer(this.state.instanceBuffer,0,Ar,0,Ur)}uploadResidentInstanceData(e){if(this.state.device)for(let t=0;t<e.length;t+=1){const r=e[t],n=r.residentInstanceBinding;if(!n)continue;if("instanced-direct"===n.mode){const e=r,t=e.sourceMesh,i=t.instanceMatrix.array,a=Math.max(4,16*t.count*Float32Array.BYTES_PER_ELEMENT),s=Math.max(t.count,1),o=Math.max(16,4*s*Float32Array.BYTES_PER_ELEMENT);if((!n.buffer||a>r.residentBufferSize)&&(n.buffer?.destroy(),r.residentBufferSize=256*Math.ceil(a/256),n.buffer=this.state.device.createBuffer({label:"renderer-instanced-mesh-matrix-buffer",size:r.residentBufferSize,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST}),n.sceneBindGroup=null,n.shadowBindGroup=null,n.shadowBindGroups.clear(),n.sceneBindGroupVersion=0,n.shadowBindGroupVersion=0,r.residentBufferDirty=!0),(!n.colorBuffer||o>r.residentColorBufferSize)&&(n.colorBuffer?.destroy(),r.residentColorBufferSize=256*Math.ceil(o/256),n.colorBuffer=this.state.device.createBuffer({label:"renderer-instanced-mesh-color-buffer",size:r.residentColorBufferSize,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST}),n.sceneBindGroup=null,n.shadowBindGroup=null,n.shadowBindGroups.clear(),n.sceneBindGroupVersion=0,n.shadowBindGroupVersion=0,r.residentColorBufferDirty=!0),r.residentBufferDirty&&n.buffer&&(t.count>0?this.state.device.queue.writeBuffer(n.buffer,0,vn(i),0,16*t.count):this.state.device.queue.writeBuffer(n.buffer,0,Fr,0,4),r.residentBufferDirty=!1),r.residentColorBufferDirty&&n.colorBuffer){if(t.instanceColor&&4===t.instanceColor.itemSize&&t.instanceColor.array instanceof Float32Array)this.state.device.queue.writeBuffer(n.colorBuffer,0,vn(t.instanceColor.array),0,4*s);else{let r=e.cachedDefaultColorData;r&&r.length===4*s||(r=new Float32Array(4*s),e.cachedDefaultColorData=r);for(let e=0;e<s;e+=1){const n=4*e;t.instanceColor?(r[n+0]=t.instanceColor.getComponent(e,0),r[n+1]=t.instanceColor.itemSize>1?t.instanceColor.getComponent(e,1):1,r[n+2]=t.instanceColor.itemSize>2?t.instanceColor.getComponent(e,2):1,r[n+3]=t.instanceColor.itemSize>3?t.instanceColor.getComponent(e,3):1):(r[n+0]=1,r[n+1]=1,r[n+2]=1,r[n+3]=1)}this.state.device.queue.writeBuffer(n.colorBuffer,0,vn(r),0,r.length)}r.residentColorBufferDirty=!1}continue}const i=Math.max(4,r.cachedInstanceData.byteLength);if((!n.buffer||i>r.residentBufferSize)&&(n.buffer?.destroy(),r.residentBufferSize=256*Math.ceil(i/256),n.buffer=this.state.device.createBuffer({label:"renderer-instanced-mesh-buffer",size:r.residentBufferSize,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST}),n.sceneBindGroup=null,n.shadowBindGroup=null,n.shadowBindGroups.clear(),n.sceneBindGroupVersion=0,n.shadowBindGroupVersion=0,r.residentBufferDirty=!0),r.residentBufferDirty){if(!n.buffer)continue;r.cachedInstanceData.floatLength>0?this.state.device.queue.writeBuffer(n.buffer,0,r.cachedInstanceData.rawData.buffer,0,r.cachedInstanceData.byteLength):this.state.device.queue.writeBuffer(n.buffer,0,Ar,0,Ur),r.residentBufferDirty=!1}}}clearIndirectBundleCache(){this.state.indirectForwardBundleCache.clear(),this.state.directForwardBundleCache.clear()}clearStaticDrawSetBundleCaches(){this.materialPassStaticBundleCache=new WeakMap;for(const e of this.staticDrawSets){for(const t of e.visibleIndirectSubmissionStreams??[])t.forwardBundle=null;e.indirectForwardBundleCache.clear(),e.directForwardBundle=null,e.directForwardBundleSceneBindGroup=null,e.depthPrepassBundle=null,e.depthPrepassBundleSceneBindGroup=null,e.indirectDepthPrepassBundles.prepass=null,e.indirectDepthPrepassBundles.postpass=null,e.shadowBundles=new WeakMap,e.depthMaterialResources.clear()}}getViewport(e){return e.set(0,0,this.state.width,this.state.height)}getSharedSceneBindGroup(){if(!(this.state.device&&this.state.sceneBindGroupLayout&&this.state.cameraBuffer&&this.state.lightBuffer&&this.state.instanceBuffer&&this.state.shadowComparisonSampler&&this.state.directionalShadowView&&this.state.linearClampSampler&&this.state.pointShadowArrayView&&this.state.spotShadowView))throw new Error("Renderer scene bind group resources are not initialized.");return this.state.sharedSceneBindGroup||(this.state.sharedSceneBindGroup=this.state.device.createBindGroup({label:"renderer-scene-bind-group",layout:this.state.sceneBindGroupLayout,entries:[{binding:0,resource:{buffer:this.state.cameraBuffer}},{binding:1,resource:{buffer:this.state.lightBuffer}},{binding:2,resource:{buffer:this.state.instanceBuffer}},{binding:3,resource:this.state.shadowComparisonSampler},{binding:4,resource:this.state.directionalShadowView},{binding:5,resource:this.state.linearClampSampler},{binding:6,resource:this.state.pointShadowArrayView},{binding:7,resource:this.state.spotShadowView}]})),this.state.sharedSceneBindGroup}getSharedShadowBindGroup(){if(!(this.state.device&&this.state.shadowBindGroupLayout&&this.state.shadowCameraBuffer&&this.state.instanceBuffer))throw new Error("Renderer shadow bind group resources are not initialized.");return this.state.sharedShadowBindGroup||(this.state.sharedShadowBindGroup=this.state.device.createBindGroup({label:"renderer-shadow-bind-group",layout:this.state.shadowBindGroupLayout,entries:[{binding:0,resource:{buffer:this.state.shadowCameraBuffer}},{binding:1,resource:{buffer:this.state.instanceBuffer}}]})),this.state.sharedShadowBindGroup}getShadowCameraBuffer(e){if(!this.state.device)throw new Error("Renderer is not initialized.");for(;this.state.shadowCameraBufferPool.length<=e;)this.state.shadowCameraBufferPool.push(this.state.device.createBuffer({label:`renderer-shadow-camera-buffer-${this.state.shadowCameraBufferPool.length}`,size:256,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}));return this.state.shadowCameraBufferPool[e]}getSharedShadowBindGroupForCameraBuffer(e){if(!(this.state.device&&this.state.sceneBindGroupLayout&&this.state.directSceneBindGroupLayout&&this.state.shadowBindGroupLayout&&this.state.instanceBuffer))throw new Error("Renderer shadow bind group resources are not initialized.");const t=this.state.sharedShadowBindGroupByCameraBuffer.get(e);if(t)return t;const r=this.state.device.createBindGroup({label:"renderer-shadow-bind-group-per-camera",layout:this.state.shadowBindGroupLayout,entries:[{binding:0,resource:{buffer:e}},{binding:1,resource:{buffer:this.state.instanceBuffer}}]});return this.state.sharedShadowBindGroupByCameraBuffer.set(e,r),r}buildIndirectSubmissionStreams(e,t,r,n){const i=this.indirectSubmissionStreamsScratch;i.length=0;let a=null;for(let s=0;s<e.length;s+=1){const o=e[s],l=n?.[s]??(r?this.getMaterialResource(o.material,r,o.receiveShadow,void 0,null!==o.skinning,this.drawUsesBatching(o)):this.getMaterialResourceForDraw(o)),c=r?t:this.resolveSceneBindGroupForDraw(o,t),u=[Sn(l.pipeline),Sn(l.bindGroup),Sn(c),Sn(o.geometryKey)].join(":"),d=On(o);a&&a.key===u&&a.indirectStartIndex+a.indirectCount===s?(a.indirectCount+=1,a.drawCallCount+=1,a.triangleCount+=d):(a={key:u,material:o.material,materialResource:l,sceneBindGroup:c,geometry:o.geometry,geometryKey:o.geometryKey,geometryResource:o.geometryResource,indirectStartIndex:s,indirectCount:1,drawCallCount:1,triangleCount:d,forwardBundle:null},i.push(a))}return i}getOrCreateStaticIndirectSubmissionStreams(e,t,r=[Er]){const n=r.join("|"),i=null!==e.visibleIndirectSubmissionStreams&&e.visibleIndirectStreamsSceneBindGroup===t&&e.visibleIndirectStreamsSampleCount===this.sampleCount&&e.visibleIndirectStreamsColorFormatsKey===n;if(i)return e.visibleIndirectSubmissionStreams;let a=!i;for(const t of e.visibleMaterialBindings){const n=this.getMaterialResource(t.material,"packed-visible",t.receiveShadow,r,!1,t.usesBatching),i=t.resource;t.resource=n,i!==n&&(a=!0);for(const r of t.drawIndices)e.visibleDrawMaterialResources[r]!==n&&(a=!0),e.visibleDrawMaterialResources[r]=n}return!a&&e.visibleIndirectSubmissionStreams||(e.visibleIndirectSubmissionStreams=this.buildIndirectSubmissionStreams(e.draws,t,"packed-visible",e.visibleDrawMaterialResources).slice(),e.visibleIndirectStreamsSceneBindGroup=t,e.visibleIndirectStreamsSampleCount=this.sampleCount,e.visibleIndirectStreamsColorFormatsKey=n,e.indirectForwardBundleCache.clear()),e.visibleIndirectSubmissionStreams}getOrCreateIndirectForwardBundle(e,t=this.state.drawMetadataResource,r=this.state.indirectForwardBundleCache,n="renderer-indirect-forward-bundle",i=[Er]){if(!this.state.device||!this.state.format)throw new Error("Renderer is not initialized.");if(!t)throw new Error("Indirect draw metadata is not available.");if(e.forwardBundle)return e.forwardBundle;const a=[e.key,Sn(e.geometryResource.position),e.geometryResource.index?Sn(e.geometryResource.index):"no-index",Sn(t.indirectBuffer),e.indirectStartIndex,e.indirectCount,`samples=${this.sampleCount}`,`formats=${i.join("|")}`].join(":"),s=r.get(a);if(s)return e.forwardBundle=s,s;const o=this.state.device.createRenderBundleEncoder({label:`${n}-${a}`,colorFormats:i,depthStencilFormat:"depth32float",sampleCount:this.sampleCount});if(o.setPipeline(e.materialResource.pipeline),this.bindGeometryVertexBuffers(o,e.geometry,e.geometryResource,e.materialResource.vertexAttributes,0,1,e.material.wireframe),o.setBindGroup(0,e.sceneBindGroup),o.setBindGroup(1,e.materialResource.bindGroup),!e.materialResource.graphTextureBindGroupLayout)throw new Error("Graph texture layout is missing.");o.setBindGroup(3,this.createGraphTextureBindGroup(e.material,e.materialResource.graphTextureBindGroupLayout));for(let r=0;r<e.indirectCount;r+=1)o.drawIndexedIndirect(t.indirectBuffer,20*(e.indirectStartIndex+r));const l=o.finish({label:`${n}-${a}`});return r.set(a,l),e.forwardBundle=l,l}getDirectForwardBundleKey(e,t,r){let n=2166136261;n=Tn(n,e.length),n=Tn(n,this.sampleCount),n=Tn(n,Sn(t));for(let i=0;i<e.length;i+=1){const a=e[i],s=this.getMaterialResourceForDraw(a,r),o=this.resolveSceneBindGroupForDraw(a,t);n=Tn(n,Sn(a.material)),n=Tn(n,a.receiveShadow?1:0),n=Tn(n,a.material.version??0),n=Tn(n,Sn(s.pipeline)),n=Tn(n,Sn(s.bindGroup)),n=Tn(n,Sn(o)),n=Tn(n,Sn(a.geometryKey)),n=Tn(n,Sn(a.geometryResource.position)),n=Tn(n,Sn(a.geometryResource.normal)),n=Tn(n,Sn(a.geometryResource.uv)),n=Tn(n,Sn(a.geometryResource.color)),n=Tn(n,a.geometryResource.index?Sn(a.geometryResource.index):0);for(const e of a.geometryResource.extraAttributeBuffers.values())n=Tn(n,Sn(e));n=Tn(n,a.indexed?1:0),n=Tn(n,a.start),n=Tn(n,a.count),n=Tn(n,a.instanceStart),n=Tn(n,a.instanceCount);const l=a.material.getTexturesList();n=Tn(n,l.length);for(let e=0;e<l.length;e+=1){const t=l[e];n=Tn(n,Sn(t)),n=Tn(n,t.version)}}return`forward-direct:${n}:${e.length}:samples=${this.sampleCount}:formats=${r.join("|")}`}getOrCreateDirectForwardBundle(e,t,r,n=[Er]){if(!this.state.device||!this.state.format||0===e.length)return null;const i=this.getDirectForwardBundleKey(e,t,n),a=this.state.directForwardBundleCache.get(i);if(a){for(let t=0;t<e.length;t+=1){const n=e[t];n.materialResource&&this.updateMaterialUniformBuffer(n.material,n.materialResource),this.recordDraw(n,r)}return a}const s=this.state.device.createRenderBundleEncoder({label:`renderer-direct-forward-bundle-${i}`,colorFormats:n,depthStencilFormat:"depth32float",sampleCount:this.sampleCount});let o=null,l=null,c=null,u=null;for(let i=0;i<e.length;i+=1){const a=e[i],d=a.geometryResource,h=this.getMaterialResourceForDraw(a,n),p=this.resolveSceneBindGroupForDraw(a,t);if(o!==h.pipeline&&(o=h.pipeline,c=null,s.setPipeline(o)),c!==a.geometryKey&&(c=a.geometryKey,this.bindGeometryVertexBuffers(s,a.geometry,d,h.vertexAttributes,a.instanceStart,a.instanceCount,a.wireframe)),u!==p&&(u=p,s.setBindGroup(0,p)),l!==a.material){if(l=a.material,s.setBindGroup(1,h.bindGroup),!h.graphTextureBindGroupLayout)throw new Error("Graph texture layout is missing.");s.setBindGroup(3,this.createGraphTextureBindGroup(a.material,h.graphTextureBindGroupLayout))}a.indexed&&(a.wireframe?d.wireframeIndex:d.index)?s.drawIndexed(a.count,a.instanceCount,a.start,0,a.instanceStart):s.draw(a.count,a.instanceCount,a.start,a.instanceStart),this.recordDraw(a,r)}const d=s.finish({label:`renderer-direct-forward-bundle-${i}`});return this.state.directForwardBundleCache.set(i,d),d}getOrCreateStaticMaterialBundle(e,t,r,n){const i=`${Sn(t)}:${this.sampleCount}:${n.join("|")}`,a=this.materialPassStaticBundleCache.get(e)?.get(i);if(a)return this.recordStaticDrawStats(e,r),a;const s=this.getOrCreateDirectForwardBundle(e.draws,t,r,n);if(!s)return null;let o=this.materialPassStaticBundleCache.get(e);return o||(o=new Map,this.materialPassStaticBundleCache.set(e,o)),o.set(i,s),s}resolveSceneBindGroupForDraw(e,t){if(!(e.residentInstanceBinding&&this.state.device&&this.state.sceneBindGroupLayout&&this.state.directSceneBindGroupLayout&&this.state.cameraBuffer&&this.state.lightBuffer&&this.state.shadowComparisonSampler&&this.state.directionalShadowView&&this.state.linearClampSampler&&this.state.pointShadowArrayView&&this.state.spotShadowView&&e.residentInstanceBinding.buffer))return t;const r=e.residentInstanceBinding,n=r.buffer,i=r.colorBuffer??r.buffer;return n&&i?(r.sceneBindGroup&&r.sceneBindGroupVersion===this.state.residentSceneBindGroupVersion||(r.sceneBindGroup=this.state.device.createBindGroup("instanced-direct"===r.mode?{label:"renderer-resident-direct-scene-bind-group",layout:this.state.directSceneBindGroupLayout,entries:[{binding:0,resource:{buffer:this.state.cameraBuffer}},{binding:1,resource:{buffer:this.state.lightBuffer}},{binding:2,resource:{buffer:n}},{binding:3,resource:{buffer:i}},{binding:4,resource:this.state.shadowComparisonSampler},{binding:5,resource:this.state.directionalShadowView},{binding:6,resource:this.state.linearClampSampler},{binding:7,resource:this.state.pointShadowArrayView},{binding:8,resource:this.state.spotShadowView}]}:{label:"renderer-resident-scene-bind-group",layout:this.state.sceneBindGroupLayout,entries:[{binding:0,resource:{buffer:this.state.cameraBuffer}},{binding:1,resource:{buffer:this.state.lightBuffer}},{binding:2,resource:{buffer:n}},{binding:3,resource:this.state.shadowComparisonSampler},{binding:4,resource:this.state.directionalShadowView},{binding:5,resource:this.state.linearClampSampler},{binding:6,resource:this.state.pointShadowArrayView},{binding:7,resource:this.state.spotShadowView}]}),r.sceneBindGroupVersion=this.state.residentSceneBindGroupVersion),r.sceneBindGroup):t}resolveShadowBindGroupForDraw(e,t,r=this.state.shadowCameraBuffer){if(!(e.residentInstanceBinding&&this.state.device&&this.state.shadowBindGroupLayout&&this.state.directShadowBindGroupLayout&&r&&e.residentInstanceBinding.buffer))return t;const n=e.residentInstanceBinding,i=n.buffer,a=n.colorBuffer??n.buffer;if(!i||!a)return t;if(n.shadowBindGroupVersion!==this.state.residentShadowBindGroupVersion&&(n.shadowBindGroup=null,n.shadowBindGroups.clear(),n.shadowBindGroupVersion=this.state.residentShadowBindGroupVersion),r===this.state.shadowCameraBuffer&&n.shadowBindGroup)return n.shadowBindGroup;const s=n.shadowBindGroups.get(r);if(s)return s;const o=this.state.device.createBindGroup("instanced-direct"===n.mode?{label:"renderer-resident-direct-shadow-bind-group",layout:this.state.directShadowBindGroupLayout,entries:[{binding:0,resource:{buffer:r}},{binding:1,resource:{buffer:i}},{binding:2,resource:{buffer:a}}]}:{label:"renderer-resident-shadow-bind-group",layout:this.state.shadowBindGroupLayout,entries:[{binding:0,resource:{buffer:r}},{binding:1,resource:{buffer:i}}]});return n.shadowBindGroups.set(r,o),r===this.state.shadowCameraBuffer&&(n.shadowBindGroup=o),o}uploadDrawMetadata(e){if(!this.state.device||!this.state.visibilityParamsBuffer)return;if(0===e.length)return this.visibilityParamsUpload[0]=0,this.visibilityParamsUpload[1]=this.state.hizMipCount,this.visibilityParamsUpload[2]=0,this.visibilityParamsUpload[3]=0,this.state.device.queue.writeBuffer(this.state.visibilityParamsBuffer,0,this.visibilityParamsUpload,0,4),void(this.state.drawMetadataResource&&(this.state.drawMetadataResource.count=0));const t=e.length*Vr;this.drawMetadataUpload.length<t&&(this.drawMetadataUpload=new Float32Array(Math.max(t,2*this.drawMetadataUpload.length,768)));const r=5*e.length;this.indirectDrawUpload.length<r&&(this.indirectDrawUpload=new Uint32Array(Math.max(r,2*this.indirectDrawUpload.length,320)));const n=this.drawMetadataUpload,i=this.indirectDrawUpload;for(let t=0;t<e.length;t+=1){const r=e[t],a=t*Vr;n[a+0]=r.boundsCenter.x,n[a+1]=r.boundsCenter.y,n[a+2]=r.boundsCenter.z,n[a+3]=r.boundsRadius,n[a+4]=r.count,n[a+5]=r.start,n[a+6]=r.instanceStart,n[a+7]=r.instanceCount,n[a+8]=1,n[a+9]=0,n[a+10]=0,n[a+11]=0;const s=5*t;i[s+0]=r.count,i[s+1]=r.instanceCount,i[s+2]=r.start,i[s+3]=0,i[s+4]=r.instanceStart}const a=e.length;if(!(this.state.drawMetadataResource&&this.state.drawMetadataResource.capacity>=a)){this.state.drawMetadataResource?.metadataBuffer.destroy(),this.state.drawMetadataResource?.indirectBuffer.destroy(),this.state.drawMetadataResource?.postIndirectBuffer.destroy();const t=Math.max(64,1<<Math.ceil(Math.log2(a)));this.state.drawMetadataResource={count:e.length,capacity:t,metadataBuffer:this.state.device.createBuffer({label:"renderer-draw-metadata-buffer",size:t*Vr*4,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST}),indirectBuffer:this.state.device.createBuffer({label:"renderer-indirect-draw-buffer",size:5*t*4,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.INDIRECT|GPUBufferUsage.COPY_DST|GPUBufferUsage.COPY_SRC}),postIndirectBuffer:this.state.device.createBuffer({label:"renderer-post-indirect-draw-buffer",size:5*t*4,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.INDIRECT|GPUBufferUsage.COPY_DST})},this.state.visibilityBindGroup=null,this.state.visibilityBindGroupMetadataResource=null,this.clearIndirectBundleCache()}this.state.drawMetadataResource.count=e.length,this.state.device.queue.writeBuffer(this.state.drawMetadataResource.metadataBuffer,0,n,0,t),this.state.device.queue.writeBuffer(this.state.drawMetadataResource.indirectBuffer,0,i,0,r),this.visibilityParamsUpload[0]=e.length,this.visibilityParamsUpload[1]=this.state.hizMipCount,this.visibilityParamsUpload[2]=0,this.visibilityParamsUpload[3]=0,this.state.device.queue.writeBuffer(this.state.visibilityParamsBuffer,0,this.visibilityParamsUpload,0,4)}recordDraw(e,t){t.drawCallCount+=1,t.triangleCount+=On(e)}executeVisibilityPass(e,t){Yn.call(this,e,t)}executeStaticVisibilityPasses(e,t){Xn.call(this,e,t)}getOrCreateStaticVisibilityBindGroup(e,t){return Jn.call(this,e,t)}executeDirectionalShadowPass(e,t,r,n){Qn.call(this,e,t,r,n)}executePointShadowPass(e,t,r,n){ei.call(this,e,t,r,n)}executeSpotShadowPass(e,t,r,n){ti.call(this,e,t,r,n)}executeDepthPrepass(e,t,r,n){ri.call(this,e,t,r,n)}executeStaticDepthPrepass(e,t,r){ni.call(this,e,t,r)}executeStaticTemporalDepthResolvePass(e){ai.call(this,e)}getOrCreateStaticDepthPrepassBundle(e,t){return si.call(this,e,t)}executeHiZPasses(e,t=!1){ci.call(this,e,t)}getOrCreateStaticVisibleSceneBindGroup(e){if(!(this.state.device&&this.state.visibleSceneBindGroupLayout&&this.state.cameraBuffer&&this.state.lightBuffer&&this.state.shadowComparisonSampler&&this.state.directionalShadowView&&this.state.linearClampSampler&&this.state.pointShadowArrayView&&this.state.spotShadowView))throw new Error("Renderer visible scene bind group resources are not initialized.");return e.visibleSceneBindGroup&&e.visibleSceneBindGroupVersion===this.state.residentSceneBindGroupVersion||(e.visibleSceneBindGroup=this.state.device.createBindGroup({label:`${e.label}-static-visible-scene-bind-group`,layout:this.state.visibleSceneBindGroupLayout,entries:[{binding:0,resource:{buffer:this.state.cameraBuffer}},{binding:1,resource:{buffer:this.state.lightBuffer}},{binding:2,resource:{buffer:e.instanceBuffer}},{binding:3,resource:this.state.shadowComparisonSampler},{binding:4,resource:this.state.directionalShadowView},{binding:5,resource:this.state.linearClampSampler},{binding:6,resource:this.state.pointShadowArrayView},{binding:7,resource:this.state.spotShadowView},{binding:8,resource:{buffer:e.instanceVisibilityResource.visibleInstanceIndicesBuffer}}]}),e.visibleSceneBindGroupVersion=this.state.residentSceneBindGroupVersion),e.visibleSceneBindGroup}getOrCreateStaticVisibleDepthSceneBindGroup(e){if(!this.state.device||!this.state.visibleDepthSceneBindGroupLayout||!this.state.cameraBuffer)throw new Error("Renderer visible depth scene bind group resources are not initialized.");return e.visibleDepthSceneBindGroup&&e.visibleDepthSceneBindGroupVersion===this.state.residentSceneBindGroupVersion||(e.visibleDepthSceneBindGroup=this.state.device.createBindGroup({label:`${e.label}-static-visible-depth-scene-bind-group`,layout:this.state.visibleDepthSceneBindGroupLayout,entries:[{binding:0,resource:{buffer:this.state.cameraBuffer}},{binding:2,resource:{buffer:e.instanceBuffer}},{binding:3,resource:{buffer:e.instanceVisibilityResource.visibleInstanceIndicesBuffer}}]}),e.visibleDepthSceneBindGroupVersion=this.state.residentSceneBindGroupVersion),e.visibleDepthSceneBindGroup}executeMaterialPass(e,t,r,n,i,a={}){if(!this.state.mainDepthView||0===t.length)return;const s=t.map(e=>this.getColorTargetFormat(e)),o=t.map(e=>this.getColorTargetView(e)),l=this.sampleCount>1,c=l?t.map(e=>this.ensureMsaaColorTarget(e)):[],u=this.getColorTargetDimensions(t[0]),d=l?this.ensureMsaaDepthTarget(u.width,u.height):null,h=e.beginRenderPass({label:"renderer-material-pass",colorAttachments:t.map((e,t)=>({view:c[t]?.view??o[t],resolveTarget:c[t]?o[t]:void 0,clearValue:1===t?{r:.5,g:.5,b:1,a:1}:{r:this.clearColor[0],g:this.clearColor[1],b:this.clearColor[2],a:this.clearColor[3]},loadOp:a.loadColor?"load":"clear",storeOp:c[t]?"discard":"store"})),depthStencilAttachment:{view:d?.view??this.state.mainDepthView,depthClearValue:1,depthLoadOp:d?"clear":a.loadDepth?"load":"clear",depthStoreOp:d?"discard":"store"}});let p=null,f=null,m=null,g=null,x=null;const v=e=>{e.sourceObject&&e.hasRenderCallbacks&&e.sourceObject.onBeforeRender(this,n.scene,n.camera,e.geometry,e.material,e.geometryGroup);const t=e.geometryResource;let a=e.material;const o=this.getMaterialResourceForDraw(e,s),l=this.resolveSceneBindGroupForDraw(e,r);if(p!==o.pipeline&&(p=o.pipeline,m=null,x=null,h.setPipeline(p)),m!==e.geometryKey&&(m=e.geometryKey,this.bindGeometryVertexBuffers(h,e.geometry,t,o.vertexAttributes,e.instanceStart,e.instanceCount,e.wireframe)),g!==l&&(g=l,h.setBindGroup(0,l)),f!==a){if(f=a,h.setBindGroup(1,o.bindGroup),!o.graphTextureBindGroupLayout)throw new Error("Graph texture layout is missing.");h.setBindGroup(3,this.createGraphTextureBindGroup(a,o.graphTextureBindGroupLayout))}o.usesSkinning&&e.skinning&&x!==e.skinning.bindGroup&&(x=e.skinning.bindGroup,h.setBindGroup(2,x)),e.indexed&&(e.wireframe?t.wireframeIndex:t.index)?h.drawIndexed(e.count,e.instanceCount,e.start,0,e.instanceStart):h.draw(e.count,e.instanceCount,e.start,e.instanceStart),this.recordDraw(e,i),e.sourceObject&&e.hasRenderCallbacks&&e.sourceObject.onAfterRender(this,n.scene,n.camera,e.geometry,e.material,e.geometryGroup)},w=a.drawStage??"all";if(a.objectFilter||a.overrideMaterial){const e=e=>{if(a.objectFilter){const t=e.sourceRanges?.filter(e=>a.objectFilter(e.sourceObject));if(null!=t&&t.length>0){const r="function"==typeof a.overrideMaterial?a.overrideMaterial(e.material,null!==e.skinning):a.overrideMaterial;for(const n of t)v({...e,sourceObject:n.sourceObject,instanceStart:n.instanceStart,instanceCount:n.instanceCount,material:r??e.material,sourceRanges:void 0});return}if(!a.objectFilter(e.sourceObject))return}const t="function"==typeof a.overrideMaterial?a.overrideMaterial(e.material,null!==e.skinning):a.overrideMaterial;v(t?{...e,material:t}:e)};if("late"!==w){for(const t of this.staticDrawSets)if(t.publicSet.enabled)for(const r of t.draws)e(r);for(const t of n.gpuOpaqueDraws)e(t);for(const t of n.directOpaqueDraws)e(t)}if("opaque"!==w)for(const t of n.transparentDraws)e(t);return void h.end()}if("late"!==w){for(const e of this.staticDrawSets){if(!e.publicSet.enabled||0===e.draws.length)continue;if(this.getHiZOcclusionCullingActive()&&e.lastVisibilityFrameToken===this.staticFrameToken){const t=this.getOrCreateStaticVisibleSceneBindGroup(e),r=this.getOrCreateStaticIndirectSubmissionStreams(e,t,s);for(const t of r){if(this.getMultiDrawIndirectActive()){if(h.setPipeline(t.materialResource.pipeline),this.bindGeometryVertexBuffers(h,t.geometry,t.geometryResource,t.materialResource.vertexAttributes,0,1,t.material.wireframe),h.setBindGroup(0,t.sceneBindGroup),h.setBindGroup(1,t.materialResource.bindGroup),!t.materialResource.graphTextureBindGroupLayout)throw new Error("Graph texture layout is missing.");h.setBindGroup(3,this.createGraphTextureBindGroup(t.material,t.materialResource.graphTextureBindGroupLayout)),h.multiDrawIndexedIndirect(e.drawMetadataResource.indirectBuffer,5*t.indirectStartIndex*Uint32Array.BYTES_PER_ELEMENT,t.indirectCount)}else this.renderBundleScratch[0]=this.getOrCreateIndirectForwardBundle(t,e.drawMetadataResource,e.indirectForwardBundleCache,`${e.label}-static-indirect-material-bundle`,s),h.executeBundles(this.renderBundleScratch);i.drawCallCount+=t.drawCallCount,i.triangleCount+=t.triangleCount}continue}const t=this.getOrCreateStaticMaterialBundle(e,r,i,s);t&&(this.renderBundleScratch[0]=t,h.executeBundles(this.renderBundleScratch))}if(this.getHiZOcclusionCullingActive()&&this.state.drawMetadataResource){const e=n.gpuOpaqueDraws.map(e=>this.getMaterialResourceForDraw(e,s)),t=this.buildIndirectSubmissionStreams(n.gpuOpaqueDraws,r,void 0,e);for(const e of t)this.renderBundleScratch[0]=this.getOrCreateIndirectForwardBundle(e,this.state.drawMetadataResource,this.state.indirectForwardBundleCache,"renderer-indirect-material-bundle",s),h.executeBundles(this.renderBundleScratch),i.drawCallCount+=e.drawCallCount,i.triangleCount+=e.triangleCount}else{const e=Dn(n.gpuOpaqueDraws)||n.gpuOpaqueDraws.some(e=>null!==e.skinning)?null:this.getOrCreateDirectForwardBundle(n.gpuOpaqueDraws,r,i,s);if(e)this.renderBundleScratch[0]=e,h.executeBundles(this.renderBundleScratch);else for(const e of n.gpuOpaqueDraws)v(e)}const e=Dn(n.directOpaqueDraws)||n.directOpaqueDraws.some(e=>null!==e.skinning)?null:this.getOrCreateDirectForwardBundle(n.directOpaqueDraws,r,i,s);if(e)this.renderBundleScratch[0]=e,h.executeBundles(this.renderBundleScratch);else for(const e of n.directOpaqueDraws)v(e)}if("opaque"!==w)for(const e of n.transparentDraws)v(e);h.end()}executeForwardPass(e,t,r,n,i,a,s=!1,o="all",l=!1,c=this.sampleCount){ui.call(this,e,t,r,n,i,a,s,o,l,c)}executeStaticForwardPass(e,t,r){di.call(this,e,t,r)}getOrCreateStaticDirectForwardBundle(e,t){return hi.call(this,e,t)}refreshStaticDrawMaterialResources(e){fi.call(this,e)}syncStaticVisibleMaterialBindingCaches(e){pi.call(this,e)}recordStaticDrawStats(e,t){mi.call(this,e,t)}hasEnabledStaticDrawSets(){return gi.call(this)}executePresentPass(e,t,r){xi.call(this,e,t,r)}clearDirectionalShadow(e){vi.call(this,e)}clearPointShadow(e){wi.call(this,e)}clearSpotShadow(e){bi.call(this,e)}drawDepthLike(e,t,r,n){yi.call(this,e,t,r,n)}getGeometryResource(e){if(!this.state.device)throw new Error("Renderer is not initialized.");const t=this.geometryCache.get(e);if(t&&t.lastValidatedExtractionVersion===this.extractionVersion)return t;if(t&&function(e,t){if(t.indexVersion!==(e.index?.version??0)||t.drawRangeStart!==e.drawRange.start||t.drawRangeCount!==e.drawRange.count)return!1;if(t.groups.length!==e.groups.length)return!1;for(let r=0;r<t.groups.length;r+=1){const n=t.groups[r],i=e.groups[r];if(n.start!==i?.start||n.count!==i?.count||n.materialIndex!==(i?.materialIndex??0))return!1}for(let r=0;r<t.attributes.length;r+=1){const n=t.attributes[r],i=e.getAttribute(n.name);if(i?Jr(i)!==n.version||i.itemSize!==n.itemSize||i.count!==n.count:0!==n.version||0!==n.itemSize||0!==n.count)return!1}return!0}(e,t))return t.lastValidatedExtractionVersion=this.extractionVersion,t;t&&(this.clearIndirectBundleCache(),this.retireGeometryResource(t));const r=e.getAttribute("position");if(!r)throw new Error("BufferGeometry is missing the required position attribute.");const n=r.count,i=dn(r,n,3,[0,0,0]),a=dn(e.getAttribute("normal"),n,3,[0,0,1]),s=dn(e.getAttribute("uv"),n,2,[0,0]),o=dn(e.getAttribute("color"),n,4,[1,1,1,1]);let l=null,c=null;if(e.index){const t=e.index.array,r=t instanceof Uint32Array?t:new Uint16Array(t);c=t instanceof Uint32Array?"uint32":"uint16",l=sn(this.state.device,r,GPUBufferUsage.INDEX,`${e.uuid}-index`)}const u={signature:Qr(e),indexVersion:e.index?.version??0,drawRangeStart:e.drawRange.start,drawRangeCount:e.drawRange.count,vertexCount:n,attributes:["position","normal","uv","color"].map(t=>{const r=e.getAttribute(t);return{name:t,version:Jr(r),itemSize:r?.itemSize??0,count:r?.count??0}}),lastValidatedExtractionVersion:this.extractionVersion,groups:e.groups.map(e=>({start:e.start,count:e.count,materialIndex:e.materialIndex??0})),...this.createGeometryBuffers(e.uuid,i,a,s,o,e.index?.array),extraAttributeBuffers:new Map,extraAttributeBufferVersions:new Map,wireframeIndex:null,wireframeIndexFormat:null};return this.geometryCache.set(e,u),u}getSkinnedGeometryResource(e){if(!this.state.device)throw new Error("Renderer is not initialized.");const t=e.geometry.getAttribute("skinIndex"),r=e.geometry.getAttribute("skinWeight"),n=e.geometry.getAttribute("position");if(!t||!r||!n)throw new Error("SkinnedMesh requires position, skinIndex, and skinWeight attributes.");if(0===e.skeleton.bones.length)throw new Error("SkinnedMesh requires a skeleton with at least one bone.");const i=function(e){return[Qr(e.geometry),Jr(e.geometry.getAttribute("skinIndex")),Jr(e.geometry.getAttribute("skinWeight")),e.skeleton.bones.length].join(";")}(e);let a=this.skinnedGeometryCache.get(e);if(!a||a.sourceSignature!==i||a.skinning.palette.skeleton!==e.skeleton){a&&a.skinning.bindUniformBuffer.destroy();const s=this.getSkinningPalette(e.skeleton),o=this.state.device.createBuffer({label:`${e.uuid}-skinning-bind-matrices`,size:32*Float32Array.BYTES_PER_ELEMENT,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),l=new Float32Array(32);l.set(e.bindMatrix.elements,0),l.set(e.bindMatrixInverse.elements,16);const c={bindGroup:this.state.device.createBindGroup({label:`${e.uuid}-skinning-bind-group`,layout:this.state.skinningBindGroupLayout,entries:[{binding:0,resource:{buffer:s.matrixBuffer}},{binding:1,resource:{buffer:o}}]}),bindUniformBuffer:o,bindMatrices:l,palette:s,bindUniformDirty:!0},u={sourceSignature:i,resource:this.getGeometryResource(e.geometry),skinning:c,boneBounds:this.createSkinningBoneBounds(e,n,t,r),localBoundsMin:new mt,localBoundsMax:new mt,localBoundsCenter:new mt,localBoundsRadius:1};a=u,this.skinnedGeometryCache.set(e,u)}if(!a)throw new Error("Skinned geometry cache entry could not be created.");return a}getSkinningPalette(e){const t=this.skinPaletteCache.get(e);if(t)return t;if(!this.state.device||0===e.bones.length)throw new Error("A non-empty skeleton is required to create a GPU skinning palette.");const r=16*e.bones.length,n={skeleton:e,matrixBuffer:this.state.device.createBuffer({label:"renderer-skinning-bone-palette",size:r*Float32Array.BYTES_PER_ELEMENT,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST}),dirty:!0,lastRefreshExtractionVersion:-1};return this.skinPaletteCache.set(e,n),this.skinPaletteResources.add(n),n}refreshSkinningPalette(e){if(e.lastRefreshExtractionVersion===this.extractionVersion)return;e.lastRefreshExtractionVersion=this.extractionVersion;const{skeleton:t}=e;t.update(),e.dirty=!0}refreshSkinningBindMatrices(e,t){const r=t.bindMatrices;let n=!1;for(let t=0;t<16;t+=1){const i=e.bindMatrix.elements[t],a=e.bindMatrixInverse.elements[t];r[t]===i&&r[t+16]===a||(n=!0),r[t]=i,r[t+16]=a}t.bindUniformDirty||=n}uploadSkinningResources(e){if(this.state.device){if(e.palette.dirty){const t=e.palette.skeleton.boneMatrices;this.state.device.queue.writeBuffer(e.palette.matrixBuffer,0,t.buffer,t.byteOffset,16*e.palette.skeleton.bones.length*Float32Array.BYTES_PER_ELEMENT),e.palette.dirty=!1}e.bindUniformDirty&&(this.state.device.queue.writeBuffer(e.bindUniformBuffer,0,e.bindMatrices.buffer,e.bindMatrices.byteOffset,e.bindMatrices.byteLength),e.bindUniformDirty=!1)}}createSkinningBoneBounds(e,t,r,n){const i=Array.from({length:e.skeleton.bones.length},()=>new mt(1/0,1/0,1/0)),a=Array.from({length:e.skeleton.bones.length},()=>new mt(-1/0,-1/0,-1/0));for(let e=0;e<t.count;e+=1){Hr.set(t.getX(e),t.getY(e),t.getZ(e));for(let t=0;t<4;t+=1){if(n.getComponent(e,t)<=0)continue;const s=Math.round(r.getComponent(e,t)),o=i[s],l=a[s];o&&l&&(o.min(Hr),l.max(Hr))}}return i.map((e,t)=>{if(!Number.isFinite(e.x))return null;const r=a[t],n=e.clone().add(r).multiplyScalar(.5);return{center:n,radius:r.distanceTo(n)}})}updateSkinnedBounds(e,t){const r=t.localBoundsMin,n=t.localBoundsMax,i=Fn(e.geometry);r.set(i.center.x-i.radius,i.center.y-i.radius,i.center.z-i.radius),n.set(i.center.x+i.radius,i.center.y+i.radius,i.center.z+i.radius);for(let i=0;i<t.boneBounds.length;i+=1){const a=t.boneBounds[i];if(!a)continue;Wr.fromArray(t.skinning.palette.skeleton.boneMatrices,16*i),_r.multiplyMatrices(e.bindMatrixInverse,Wr).multiply(e.bindMatrix),Hr.copy(a.center).applyMatrix4(_r);const s=a.radius*En(_r);r.min(Kr.copy(Hr).addScalar(-s)),n.max(Kr.copy(Hr).addScalar(s))}t.localBoundsCenter.copy(r).add(n).multiplyScalar(.5),t.localBoundsRadius=n.distanceTo(t.localBoundsCenter)}createGeometryBuffers(e,t,r,n,i,a,s=GPUBufferUsage.VERTEX,o=GPUBufferUsage.VERTEX){if(!this.state.device)throw new Error("Renderer is not initialized.");let l=null,c=null;if(a){const t=a instanceof Uint32Array?a:new Uint16Array(a);c=a instanceof Uint32Array?"uint32":"uint16",l=sn(this.state.device,t,GPUBufferUsage.INDEX,`${e}-index`)}return{position:sn(this.state.device,t,s,`${e}-position`),normal:sn(this.state.device,r,o,`${e}-normal`),uv:sn(this.state.device,n,GPUBufferUsage.VERTEX,`${e}-uv`),color:sn(this.state.device,i,GPUBufferUsage.VERTEX,`${e}-color`),index:l,indexFormat:c}}createVertexBufferLayouts(e){return this.getVertexAttributeGroups(e).map(e=>{let t=0;const r=e.map(e=>{const r={shaderLocation:e.shaderLocation,offset:t,format:e.format};return t+=tn(e.format),r});return{arrayStride:t,stepMode:e[0].stepMode??"vertex",attributes:r}})}getVertexAttributeGroups(e){const t=this.vertexAttributeGroupCache.get(e);if(t)return t;const r=this.state.device?.limits.maxVertexBuffers??8;if(e.length<=r){const t=e.map(e=>[e]);return this.vertexAttributeGroupCache.set(e,t),t}let n=e.length-r;const i=[],a=new Set;for(const t of["vertex","instance"]){if(0===n)break;const r=e.filter(e=>(e.stepMode??"vertex")===t),s=Math.min(r.length,n+1);if(s<2)continue;const o=r.slice(0,s);i.push(o);for(const e of o)a.add(e);n-=s-1}if(n>0)throw new Error(`Vertex attributes cannot be packed into the device's ${r} vertex-buffer slots.`);const s=[];for(const t of e){if(!a.has(t)){s.push([t]);continue}const e=i.find(e=>e[0]===t);e&&s.push(e)}return this.vertexAttributeGroupCache.set(e,s),s}getGeometryAttributeBufferKey(e){const t=this.vertexAttributeBufferKeyCache.get(e);if(void 0!==t)return t;const r=function(e){const t=e.defaultValue?Array.from(e.defaultValue).join(","):"";return`${e.name}:${e.format}:${e.stepMode??"vertex"}:${t}`}(e);return this.vertexAttributeBufferKeyCache.set(e,r),r}getGeometryAttributeGroupBufferKey(e){const t=this.vertexAttributeGroupBufferKeyCache.get(e);if(void 0!==t)return t;const r=e.map(e=>this.getGeometryAttributeBufferKey(e)).join("|");return this.vertexAttributeGroupBufferKeyCache.set(e,r),r}getMaterialVertexAttributes(e,t){const r=e.vertexAttributes.slice();if(!t)return r;const n=[{name:"skinIndex",shaderLocation:4,format:"uint32x4"},{name:"skinWeight",shaderLocation:5,format:"float32x4"}];for(const e of n){const t=r.find(t=>t.name===e.name);if(t){if(t.shaderLocation!==e.shaderLocation||t.format!==e.format)throw new Error(`Skinned material attribute "${e.name}" must use ${e.format} at location ${e.shaderLocation}.`);continue}const n=r.find(t=>t.shaderLocation===e.shaderLocation);if(n)throw new Error(`Skinned material requires location ${e.shaderLocation} for "${e.name}", but it is used by "${n.name}".`);r.push(e)}return r}getGeometryVertexBuffer(e,t,r,n=0,i=1){if(!this.state.device)throw new Error("Renderer is not initialized.");let a=this.standardVertexAttributeCache.get(r);if(void 0===a&&(a="position"===r.name&&"float32x3"===r.format?"position":"normal"!==r.name||"float32x3"!==r.format||void 0!==r.defaultValue&&!cn(r.defaultValue,[0,0,1])?"uv"!==r.name||"float32x2"!==r.format||void 0!==r.defaultValue&&!cn(r.defaultValue,[0,0])?"color"!==r.name||"float32x4"!==r.format||void 0!==r.defaultValue&&!cn(r.defaultValue,[1,1,1,1])?null:"color":"uv":"normal",this.standardVertexAttributeCache.set(r,a)),a)return t[a];const s=e.getAttribute(r.name),o="instance"===r.stepMode,l=o?Math.max(0,Math.trunc(n)):0;if(o&&!s)return this.getDefaultInstanceAttributeBuffer(r,l+Math.max(1,i));const c=Jr(s),u=this.geometryVertexBufferFastCache.get(t),d=u?.get(r),h=d?.get(l);if(h&&h.source===s&&h.version===c&&h.itemSize===(s?.itemSize??0)&&h.count===(s?.count??0))return h.buffer;const p=`${this.getGeometryAttributeBufferKey(r)}${o?`:instance-start=${l}`:""}`,f=s?`${c}:${s.itemSize}:${s.count}`:"default",m=t.extraAttributeBuffers.get(p);if(m&&t.extraAttributeBufferVersions.get(p)===f)return this.cacheGeometryVertexBufferFast(t,r,l,s,c,m),m;if(!s&&!r.defaultValue)throw new Error(`Geometry "${e.uuid}" is missing required vertex attribute "${r.name}".`);const g=hn(s,o?l+Math.max(1,s?.count??1,i):t.vertexCount,r.format,r.defaultValue??[],o?l:0);if(m&&m.size>=Math.max(4,g.byteLength))return this.state.device.queue.writeBuffer(m,0,g.buffer,g.byteOffset,g.byteLength),t.extraAttributeBufferVersions.set(p,f),this.cacheGeometryVertexBufferFast(t,r,l,s,c,m),m;const x=sn(this.state.device,g,GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST,`${e.uuid}-${r.name}-${r.format}`);return m&&(this.clearIndirectBundleCache(),this.retiredGeometryBuffers.push(m)),t.extraAttributeBuffers.set(p,x),t.extraAttributeBufferVersions.set(p,f),this.cacheGeometryVertexBufferFast(t,r,l,s,c,x),x}cacheGeometryVertexBufferFast(e,t,r,n,i,a){let s=this.geometryVertexBufferFastCache.get(e);s||(s=new WeakMap,this.geometryVertexBufferFastCache.set(e,s));let o=s.get(t);o||(o=new Map,s.set(t,o));const l=n;o.set(r,{source:n,version:i,itemSize:l?.itemSize??0,count:l?.count??0,buffer:a})}getInterleavedGeometryVertexBuffer(e,t,r,n,i){if(!this.state.device)throw new Error("Renderer is not initialized.");const a=r[0].stepMode??"vertex",s=Math.max(0,Math.trunc(n)),o="instance"===a?s+Math.max(1,i,...r.map(t=>e.getAttribute(t.name)?.count??1)):t.vertexCount,l=`interleaved:${this.getGeometryAttributeGroupBufferKey(r)}:instance-start=${"instance"===a?s:0}`,c=r.map(t=>{const r=e.getAttribute(t.name);return r?`${Jr(r)}:${r.itemSize}:${r.count}`:"default"}).join("|"),u=t.extraAttributeBuffers.get(l);if(u&&t.extraAttributeBufferVersions.get(l)===c)return u;const d=[];let h=0;for(const e of r)d.push(h),h+=tn(e.format);const p=new Uint8Array(o*h);for(let t=0;t<r.length;t+=1){const n=r[t],i=hn(e.getAttribute(n.name),o,n.format,n.defaultValue??[],"instance"===a?s:0),l=new Uint8Array(i.buffer,i.byteOffset,i.byteLength),c=tn(n.format);for(let e=0;e<o;e+=1)p.set(l.subarray(e*c,(e+1)*c),e*h+d[t])}if(u&&u.size>=Math.max(4,p.byteLength))return this.state.device.queue.writeBuffer(u,0,p.buffer,p.byteOffset,p.byteLength),t.extraAttributeBufferVersions.set(l,c),u;const f=sn(this.state.device,p,GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST,`${e.uuid}-interleaved-${a}`);return u&&(this.clearIndirectBundleCache(),this.retiredGeometryBuffers.push(u)),t.extraAttributeBuffers.set(l,f),t.extraAttributeBufferVersions.set(l,c),f}ensureWireframeIndex(e,t){if(t.wireframeIndex)return;if(!this.state.device)throw new Error("Renderer is not initialized.");const r=e.index?.array,n=r?.length??t.vertexCount,i=Math.floor(n/3),a=t.vertexCount>65535,s=a?new Uint32Array(6*i):new Uint16Array(6*i);for(let e=0;e<i;e+=1){const t=3*e,n=6*e,i=r?r[t]:t,a=r?r[t+1]:t+1,o=r?r[t+2]:t+2;s[n]=i,s[n+1]=a,s[n+2]=a,s[n+3]=o,s[n+4]=o,s[n+5]=i}t.wireframeIndexFormat=a?"uint32":"uint16",t.wireframeIndex=sn(this.state.device,s,GPUBufferUsage.INDEX,`${e.uuid}-wireframe-index`)}bindGeometryVertexBuffers(e,t,r,n,i=0,a=1,s=!1){const o=this.getVertexAttributeGroups(n);for(let n=0;n<o.length;n+=1){const s=o[n];e.setVertexBuffer(n,1===s.length?this.getGeometryVertexBuffer(t,r,s[0],i,a):this.getInterleavedGeometryVertexBuffer(t,r,s,i,a))}s&&r.wireframeIndex&&r.wireframeIndexFormat?e.setIndexBuffer(r.wireframeIndex,r.wireframeIndexFormat):r.index&&r.indexFormat&&e.setIndexBuffer(r.index,r.indexFormat)}getDefaultInstanceAttributeBuffer(e,t){if(!this.state.device)throw new Error("Renderer is not initialized.");const r=Math.max(1,t,Math.ceil(this.state.instanceBufferSize/(Float32Array.BYTES_PER_ELEMENT*Ur))),n=2**Math.ceil(Math.log2(r)),i=`${e.format}:${(e.defaultValue??[]).join(",")}`;let a=this.defaultInstanceAttributeBuffers.get(i);a||(a=new Map,this.defaultInstanceAttributeBuffers.set(i,a));const s=a.get(n);if(s)return s;const o=sn(this.state.device,hn(void 0,n,e.format,e.defaultValue??[]),GPUBufferUsage.VERTEX,`renderer-default-instance-${e.format}`);return a.set(n,o),o}getMeshExtractionCacheEntry(e,t,r,n,i,a){const s=this.meshExtractionCache.get(e),o=Array.isArray(t)?t:null,l=Array.isArray(t)?null:t;if(s&&s.geometryResource===a&&s.customDepthMaterial===i&&(null!==l&&s.material===l&&s.resolvedMaterial===r||null!==o&&null!==s.materials&&null!==s.resolvedMaterials&&an(s.materials,o)&&ln(s.resolvedMaterials,n)))return s;const c=null!==e.geometry.index,u=Fn(e.geometry),d=[];if(e.geometry.groups.length>0)for(const t of e.geometry.groups){const s=o?n[t.materialIndex??0]??n[0]:r;if(!s)continue;const l=pn(e.geometry,c,t.start,t.count),u=Cn(s,e.geometry,c,t.start,l,i),h=Sn(s),p=Sn(e.geometry),f=i?Sn(i):0;d.push({geometry:e.geometry,geometryKey:e.geometry,geometryResource:a,material:s,customDepthMaterial:i,residentInstanceBinding:null,sourceObject:e,usesBatching:!1,geometryGroup:t,batchKey:u,batchHash:Pn(h,p,c,t.start,l,f),indexed:c,wireframe:s.wireframe&&"triangle-list"===s.primitiveTopology,start:t.start,count:l,transparent:s.transparent||s.requiresLatePass(),renderOrder:e.renderOrder,hasRenderCallbacks:this.hasRenderCallbacks(e),castShadow:e.castShadow,receiveShadow:e.receiveShadow,sortMaterialId:h,sortGeometryId:p,sortCustomDepthMaterialId:f})}else{const t=r??n?.[0]??null;if(t){const r=fn(e.geometry,c),n=Cn(t,e.geometry,c,r.start,r.count,i),s=Sn(t),o=Sn(e.geometry),l=i?Sn(i):0;d.push({geometry:e.geometry,geometryKey:e.geometry,geometryResource:a,material:t,customDepthMaterial:i,residentInstanceBinding:null,sourceObject:e,usesBatching:!1,geometryGroup:null,batchKey:n,batchHash:Pn(s,o,c,r.start,r.count,l),indexed:c,wireframe:t.wireframe&&"triangle-list"===t.primitiveTopology,start:r.start,count:r.count,transparent:t.transparent||t.requiresLatePass(),renderOrder:e.renderOrder,hasRenderCallbacks:this.hasRenderCallbacks(e),castShadow:e.castShadow,receiveShadow:e.receiveShadow,sortMaterialId:s,sortGeometryId:o,sortCustomDepthMaterialId:l})}}const h={geometryResource:a,material:l,materials:o?o.slice():null,resolvedMaterial:r,resolvedMaterials:o?n.slice():null,customDepthMaterial:i,indexed:c,templates:d,localBoundsCenter:u.center.clone(),localBoundsRadius:u.radius};return this.meshExtractionCache.set(e,h),h}getInstancedMeshExtractionCacheEntry(e,t,r,n){const i=null!==e.geometry.index,a=fn(e.geometry,i),s=Fn(e.geometry),o=this.instancedMeshExtractionCache.get(e);if(o&&o.geometryResource===n&&o.material===t&&o.customDepthMaterial===r&&o.indexed===i&&o.drawRangeStart===a.start&&o.drawRangeCount===a.count)return o.sourceMaterial=e.material,o.sourceMaterialVersion=e.material.version,o;o?.residentInstanceBinding?.buffer?.destroy(),o?.residentInstanceBinding?.colorBuffer?.destroy();const l=Sn(t),c=Sn(e.geometry),u=r?Sn(r):0,d={geometryResource:n,sourceMesh:e,sourceMaterial:e.material,sourceMaterialVersion:e.material.version,material:t,customDepthMaterial:r,indexed:i,drawRangeStart:a.start,drawRangeCount:a.count,batchKey:Cn(t,e,i,a.start,a.count,r),batchHash:Pn(l,c,i,a.start,a.count,u),sortMaterialId:l,sortGeometryId:c,sortCustomDepthMaterialId:u,localBoundsCenter:s.center.clone(),localBoundsRadius:s.radius,cachedInstanceData:new Mi(1024),cachedBoundsMin:new mt,cachedBoundsMax:new mt,cachedDrawBoundsCenter:new mt,cachedDrawBoundsRadius:0,cachedMatrixWorld:new Float64Array(16),cachedInstanceMatrixVersion:-1,cachedInstanceColorVersion:-1,cachedCount:0,cachedDefaultColorData:null,residentInstanceBinding:{mode:"packed",buffer:null,colorBuffer:null,sceneBindGroup:null,shadowBindGroup:null,shadowBindGroups:new Map,sceneBindGroupVersion:0,shadowBindGroupVersion:0},residentBufferSize:0,residentColorBufferSize:0,residentBufferDirty:!1,residentColorBufferDirty:!1,cacheValid:!1};return this.instancedMeshExtractionCache.set(e,d),d}getBatchedMeshExtractionCacheEntry(e,t,r,n,i){const a=i._geometryCount??0,s=this.batchedMeshExtractionCache.get(e);if(s&&s.geometryResource===n&&s.material===t&&s.customDepthMaterial===r&&s.indexed===(null!==e.geometry.index)&&s.cachedGeometryCount===a)return s;s?.residentInstanceBinding?.buffer?.destroy(),s?.residentInstanceBinding?.colorBuffer?.destroy();const o=null!==e.geometry.index,l=new Array(a).fill(null),c=new Array(a).fill(null);for(let i=0;i<a;i+=1){const a=e.getGeometryRangeAt(i);if(!a||a.count<=0)continue;const s=pn(e.geometry,o,a.start,a.count),u=Cn(t,e.geometry,o,a.start,s,r),d=Sn(t),h=Sn(e.geometry),p=r?Sn(r):0,f=e.getBoundingSphereAt(i,qr),m={geometry:e.geometry,geometryKey:e.geometry,geometryResource:n,material:t,customDepthMaterial:r,residentInstanceBinding:null,sourceObject:e,usesBatching:!0,geometryGroup:null,batchKey:u,batchHash:Pn(d,h,o,a.start,s,p),indexed:o,wireframe:t.wireframe&&"triangle-list"===t.primitiveTopology,start:a.start,count:s,transparent:t.transparent||t.requiresLatePass(),renderOrder:e.renderOrder,hasRenderCallbacks:this.hasRenderCallbacks(e),castShadow:e.castShadow,receiveShadow:e.receiveShadow,sortMaterialId:d,sortGeometryId:h,sortCustomDepthMaterialId:p,geometryId:i,localBoundsCenter:f?f.center.clone():new mt,localBoundsRadius:f?.radius??1};l[i]=m,c[i]={template:m,boundsMin:new mt,boundsMax:new mt,activeInFrame:!1,activeCount:0,instanceStart:0,writeOffset:0}}const u={geometryResource:n,material:t,customDepthMaterial:r,indexed:o,templates:l,groups:c,activeGroups:[],cachedInstanceData:new Mi(1024),cachedDraws:[],cachedBoundsMin:new mt,cachedBoundsMax:new mt,cachedMatrixWorld:new Float64Array(16),geometryIdsSnapshot:new Int32Array(0),cachedMatricesVersion:-1,cachedColorsVersion:-1,cachedGeometryCount:a,cachedInstanceInfoLength:0,residentInstanceBinding:{mode:"packed",buffer:null,colorBuffer:null,sceneBindGroup:null,shadowBindGroup:null,shadowBindGroups:new Map,sceneBindGroupVersion:0,shadowBindGroupVersion:0},residentBufferSize:0,residentColorBufferSize:0,residentBufferDirty:!1,residentColorBufferDirty:!1,cacheValid:!1};return this.batchedMeshExtractionCache.set(e,u),u}batchedGeometryIdsMatchSnapshot(e,t){if(e.length!==t.length)return!1;for(let r=0;r<t.length;r+=1){const n=t[r];if((e[r]??-1)!==(n?.active&&n.visible?n.geometryIndex:-1))return!1}return!0}destroyGeometryResource(e){e.position.destroy(),e.normal.destroy(),e.uv.destroy(),e.color.destroy();for(const t of e.extraAttributeBuffers.values())t.destroy();e.extraAttributeBuffers.clear(),e.extraAttributeBufferVersions.clear(),e.index?.destroy(),e.wireframeIndex?.destroy()}retireGeometryResource(e){this.retiredGeometryResources.push(e)}releaseRetiredGeometryResourcesAfterSubmit(){const e=this.retiredGeometryResources.splice(0),t=this.retiredGeometryBuffers.splice(0);if(0!==e.length||0!==t.length)if(this.state.device)this.state.device.queue.onSubmittedWorkDone().then(()=>{for(const t of e)this.destroyGeometryResource(t);for(const e of t)e.destroy()},()=>{for(const t of e)this.destroyGeometryResource(t);for(const e of t)e.destroy()});else{for(const t of e)this.destroyGeometryResource(t);for(const e of t)e.destroy()}}destroyTextureResource(e){this.textureManager.destroyTextureResource(e)}createTextureSampler(e,t){return this.textureManager.createTextureSampler(e,t)}uploadDataTextureResource(e,t,r){this.textureManager.uploadDataTextureResource(e,t,r)}uploadCompressedTextureResource(e,t,r){this.textureManager.uploadCompressedTextureResource(e,t,r)}uploadExternalTextureResource(e,t,r){this.textureManager.uploadExternalTextureResource(e,t,r)}uploadTextureResource(e,t,r){this.textureManager.uploadTextureResource(e,t,r)}getTextureResource(e){return this.textureManager.getTextureResource(e)}updateMaterialUniformBuffer(e,t){if(!this.state.device||!t.uniformBuffer||0===Object.keys(e.uniforms).length)return;const r=e.getUniformLayout(),n=e.getUniformValueHash();if(t.uniformValueHash===n)return;const i=Ne(e.uniforms,r);!t.uniformBuffer||i.byteLength>t.uniformBuffer.size||(t.uniformValueHash=n,this.state.device.queue.writeBuffer(t.uniformBuffer,0,i))}materialResourceMatches(e,t,r,n=this.sampleCount){if(e.key!==r)return!1;if(e.materialVersion===t.version&&e.textureVersionHash===t.getTextureVersionHash()&&e.rendererSampleCount===n&&e.uniformBufferSize===t.getUniformLayout().byteLength)return!0;const i=ln(e.textures,t.getTexturesList())&&cn(e.textureVersions,t.getTextureVersionsList())&&ln(e.storageBuffers,t.getStorageBufferList())&&e.rendererSampleCount===n&&e.uniformBufferSize===t.getUniformLayout().byteLength;return i&&(e.materialVersion=t.version,e.textureVersionHash=t.getTextureVersionHash()),i}destroyMaterialResource(e){e?.uniformBuffer?.destroy()}createMaterialBindGroupData(e,t,r){if(!this.state.device)throw new Error("Renderer is not initialized.");const n=[],i=[],a=Array.from(e.getTexturesList()),s=Array.from(e.getTextureVersionsList()),o=e.getStorageBufferBindingList();let l=null;if(Object.keys(e.uniforms).length>0){const r=Ne(e.uniforms,e.getUniformLayout());l=this.state.device.createBuffer({label:`${t}-uniforms`,size:r.byteLength,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this.state.device.queue.writeBuffer(l,0,r),n.push({binding:0,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}}),i.push({binding:0,resource:{buffer:l}})}for(const[e,t]of a.entries()){const a=1+2*e,s=this.getTextureResource(t);n.push({binding:a,visibility:r,sampler:{type:s.samplerBindingType}},{binding:a+1,visibility:r,texture:{sampleType:s.sampleType,viewDimension:s.viewDimension}}),i.push({binding:a,resource:s.sampler},{binding:a+1,resource:s.view})}const c=1+2*a.length,u=Array.from(e.getStorageBufferList());for(const[e,t]of o.entries()){const r=c+e;n.push({binding:r,visibility:on(t.visibility),buffer:{type:"read-only-storage"}}),i.push({binding:r,resource:{buffer:t.buffer}})}return{bindGroupLayoutEntries:n,bindGroupEntries:i,uniformBuffer:l,textures:a,textureVersions:s,storageBuffers:u}}createGraphTextureBindGroupLayout(e){if(!this.state.device)throw new Error("Renderer is not initialized.");const t=[];return Object.values(e.getGraphTextureInputs()).forEach((e,r)=>{t.push({binding:2*r,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,sampler:{type:e.sampler??("depth-2d"===e.dimension?"non-filtering":"filtering")}},{binding:2*r+1,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,texture:{sampleType:e.sampleType??("depth-2d"===e.dimension?"depth":"float"),viewDimension:"3d"===e.dimension?"3d":"2d"}})}),this.state.device.createBindGroupLayout({label:`${e.uuid}-graph-textures-layout`,entries:t})}createGraphTextureBindGroup(e,t){if(!(this.state.device&&this.state.linearClampSampler&&this.state.nearestClampSampler&&this.state.shadowComparisonSampler))throw new Error("Renderer graph texture bindings are not initialized.");let r=this.graphTextureBindGroupCache.get(e);const n=r?.get(t);if(n&&n.materialVersion===e.version&&n.resourceVersion===this.graphTextureResourceVersion)return n.bindGroup;const i=[];Object.values(e.getGraphTextureInputs()).forEach((e,t)=>{const r="comparison"===e.sampler?this.state.shadowComparisonSampler:"non-filtering"===e.sampler||"depth-2d"===e.dimension?this.state.nearestClampSampler:this.state.linearClampSampler,n="mainDepth"===e.resource?this.state.sceneDepthSnapshotView:this.getGraphTextureView(e.resource);i.push({binding:2*t,resource:r},{binding:2*t+1,resource:n})});const a=this.state.device.createBindGroup({label:`${e.uuid}-graph-textures`,layout:t,entries:i});return r||(r=new WeakMap,this.graphTextureBindGroupCache.set(e,r)),r.set(t,{materialVersion:e.version,resourceVersion:this.graphTextureResourceVersion,bindGroup:a}),a}getGraphTextureView(e){return"mainDepth"===e?this.state.mainDepthView:"sceneColorSnapshot"===e?this.state.sceneColorSnapshotView:"sceneDepthSnapshot"===e?this.state.sceneDepthSnapshotView:this.getColorTargetView(e)}compileDrawMaterials(e){const t=new Set;for(const r of e){const e=this.getDrawInstanceAccessMode(r),n=null!==r.skinning,i=this.drawUsesBatching(r),a=`${r.material.uuid}:${e}:receiveShadow=${r.receiveShadow?1:0}:skinning=${n?1:0}:batching=${i?1:0}`;t.has(a)||(r.materialResource=this.getMaterialResource(r.material,e,r.receiveShadow,void 0,n,i),t.add(a))}}async compileDrawMaterialsAsync(e,t=[Er],r=this.sampleCount){const n=new Set,i=new Set,a=[];for(const s of e){const e=this.getDrawInstanceAccessMode(s),o=null!==s.skinning,l=this.drawUsesBatching(s),c=`${s.material.uuid}:${e}:receiveShadow=${s.receiveShadow?1:0}:skinning=${o?1:0}:batching=${l?1:0}`;if(n.has(c)||(a.push(this.getMaterialResourceAsync(s.material,e,s.receiveShadow,t,o,l,r).then(e=>(s.materialResource=e,e))),n.add(c)),s.customDepthMaterial){const t=`${s.customDepthMaterial.uuid}:${e}:skinning=${o?1:0}`;i.has(t)||(a.push(this.getDepthPassMaterialResourceAsyncForDraw(s.customDepthMaterial,"directionalShadow",s)),i.add(t))}if(null!==s.material.depthVertexShader||l){const t=null!==s.material.depthVertexShader?["prepass","directionalShadow","pointShadow"]:["prepass","directionalShadow"];for(const r of t){const t=`${s.material.uuid}:${r}:${e}:skinning=${o?1:0}:batching=${l?1:0}`;i.has(t)||(a.push(this.getDepthPassMaterialResourceAsyncForDraw(s.material,r,s)),i.add(t))}}}await Promise.all(a)}async compileStaticDrawMaterialsAsync(e,t=this.sampleCount){const r=[],n=new Set;for(const i of this.staticDrawSets)if(i.publicSet.enabled){r.push(this.compileDrawMaterialsAsync(i.draws,e,t));for(const a of i.visibleMaterialBindings){const i=`${a.material.uuid}:receiveShadow=${a.receiveShadow?1:0}:batching=${a.usesBatching?1:0}`;n.has(i)||(n.add(i),r.push(this.getMaterialResourceAsync(a.material,"packed-visible",a.receiveShadow,e,!1,a.usesBatching,t)))}}await Promise.all(r)}getDepthPassMaterialKey(e,t,r,n,i){if(!this.state.device)throw new Error("Renderer is not initialized.");return`${e.customProgramCacheKey()}:${t}:instance=${r}:skinning=${n?1:0}:batching=${i?1:0}:textures=${e.getTextureLayoutKey(this.state.device)}`}getForwardMaterialKey(e,t,r,n,i,a,s=this.sampleCount){return`${e.customProgramCacheKey()}:instance=${t}:receiveShadow=${r?1:0}:skinning=${i?1:0}:batching=${a?1:0}:textures=${e.getTextureLayoutKey(this.state.device)}:samples=${s}:targets=${n.join("|")}`}getInstanceAccessModeIndex(e){return"packed"===e?0:"packed-visible"===e?1:2}getForwardMaterialFastCacheIndex(e,t,r,n){return this.getInstanceAccessModeIndex(e)|(t?4:0)|(r?8:0)|(n?16:0)}getDepthMaterialFastCacheIndex(e,t,r,n){return("prepass"===e?0:"directionalShadow"===e?1:2)+3*this.getInstanceAccessModeIndex(t)+(r?9:0)+(n?18:0)}fastMaterialResourceMatches(e,t,r=this.sampleCount){return e.materialVersion===t.version&&e.textureVersionHash===t.getTextureVersionHash()&&e.rendererSampleCount===r}setForwardMaterialFastCache(e,t,r){let n=this.forwardMaterialFastCache.get(e);n||(n=[],this.forwardMaterialFastCache.set(e,n)),n[t]=r}getForwardMaterialTargetFastCacheKey(e,t){return`${t}:${e.join("|")}`}setForwardMaterialTargetFastCache(e,t,r){let n=this.forwardMaterialTargetFastCache.get(e);n||(n=new Map,this.forwardMaterialTargetFastCache.set(e,n)),n.set(t,r)}setForwardMaterialFrameCache(e,t,r){let n=this.forwardMaterialFrameCache.get(e);n||(n=[],this.forwardMaterialFrameCache.set(e,n)),n[t]={extractionVersion:this.extractionVersion,resource:r}}setDepthMaterialFastCache(e,t,r){let n=this.depthMaterialFastCache.get(e);n||(n=[],this.depthMaterialFastCache.set(e,n)),n[t]=r}getDrawInstanceAccessMode(e){return"instanced-direct"===e.residentInstanceBinding?.mode?"instanced-direct":"packed"}drawUsesBatching(e){return e.usesBatching}buildMaterialShaderCode(e,t,r,n,i=!1,a=!1){return wt(`${t}\n${r}`,this.createMaterialPreprocessorDefines(e,n,i,a),{sourceName:n})}createMaterialPreprocessorDefines(e,t,r=!1,n=!1){const i={HIGH_PRECISION:!0,WEBGPU_RENDERER:!0,WGSL_SHADER_MATERIAL:!0,USE_BATCHING:n,USE_COLOR:!0,USE_COLOR_ALPHA:!0,NUM_DIR_LIGHTS:4,NUM_POINT_LIGHTS:4,NUM_SPOT_LIGHTS:4,NUM_DIR_LIGHT_SHADOWS:4,NUM_POINT_LIGHT_SHADOWS:4,NUM_SPOT_LIGHT_SHADOWS:4,NUM_CLIPPING_PLANES:0,UNION_CLIPPING_PLANES:0,USE_SKINNING:r,...this.createTexturePreprocessorDefines(e)};return e.side===it?i.DOUBLE_SIDED=!0:e.side===et&&(i.FLIP_SIDED=!0),!t.includes("receiveShadow=1")&&t.includes("receiveShadow=0")||(i.USE_SHADOWMAP=!0,i.SHADOWMAP_TYPE_PCF=!0),{...i,...e.defines,USE_BATCHING:n}}createTexturePreprocessorDefines(e){const t={},r={map:"USE_MAP",matcap:"USE_MATCAP",lightMap:"USE_LIGHTMAP",aoMap:"USE_AOMAP",bumpMap:"USE_BUMPMAP",normalMap:"USE_NORMALMAP",displacementMap:"USE_DISPLACEMENTMAP",emissiveMap:"USE_EMISSIVEMAP",anisotropyMap:"USE_ANISOTROPYMAP",clearcoatMap:"USE_CLEARCOATMAP",clearcoatRoughnessMap:"USE_CLEARCOAT_ROUGHNESSMAP",clearcoatNormalMap:"USE_CLEARCOAT_NORMALMAP",iridescenceMap:"USE_IRIDESCENCEMAP",iridescenceThicknessMap:"USE_IRIDESCENCE_THICKNESSMAP",specularMap:"USE_SPECULARMAP",specularColorMap:"USE_SPECULAR_COLORMAP",specularIntensityMap:"USE_SPECULAR_INTENSITYMAP",roughnessMap:"USE_ROUGHNESSMAP",metalnessMap:"USE_METALNESSMAP",alphaMap:"USE_ALPHAMAP",sheenColorMap:"USE_SHEEN_COLORMAP",sheenRoughnessMap:"USE_SHEEN_ROUGHNESSMAP",transmissionMap:"USE_TRANSMISSIONMAP",thicknessMap:"USE_THICKNESSMAP"};for(const[n,i]of Object.entries(r))e.textures[n]&&(t[i]=!0);return t}shouldInvalidateDrawMaterialResource(e,t,r,n,i){return!!e.materialResource&&(e.material!==t||e.receiveShadow!==r||e.usesBatching!==n||e.skinning!==i)}cachedDrawMaterialResourceMatches(e,t,r,n=this.sampleCount){const i=this.getDrawInstanceAccessMode(e),a=null!==e.skinning,s=this.drawUsesBatching(e),o=1===r.length&&r[0]===Er?Er:r.join("|");return t.instanceAccessMode===i&&t.receiveShadow===e.receiveShadow&&t.useBatching===s&&t.usesSkinning===a&&t.rendererSampleCount===n&&t.colorTargetFormatsKey===o&&(t.materialVersion===e.material.version&&t.textureVersionHash===e.material.getTextureVersionHash()||this.materialResourceMatches(t,e.material,t.key,n))}getMaterialResourceForDraw(e,t=[Er],r=this.sampleCount){const n=e.materialResource;if(n&&this.cachedDrawMaterialResourceMatches(e,n,t,r))return this.updateMaterialUniformBuffer(e.material,n),n;const i=this.getDrawInstanceAccessMode(e),a=null!==e.skinning,s=this.drawUsesBatching(e),o=this.getMaterialResource(e.material,i,e.receiveShadow,t,a,s,r);return e.materialResource=o,o}getMaterialResourceAsyncForDraw(e){return this.getMaterialResourceAsync(e.material,this.getDrawInstanceAccessMode(e),e.receiveShadow,void 0,null!==e.skinning,this.drawUsesBatching(e))}resolveForwardMaterialResources(e){for(let t=0;t<e.length;t+=1){const r=e[t];r.materialResource=this.getMaterialResource(r.material,this.getDrawInstanceAccessMode(r),r.receiveShadow,void 0,null!==r.skinning,this.drawUsesBatching(r))}}getDepthPassMaterialResourceForDraw(e,t,r){return this.getDepthPassMaterialResource(e,t,this.getDrawInstanceAccessMode(r),null!==r.skinning,this.drawUsesBatching(r))}getDepthPassMaterialResourceAsyncForDraw(e,t,r){return this.getDepthPassMaterialResourceAsync(e,t,this.getDrawInstanceAccessMode(r),null!==r.skinning,this.drawUsesBatching(r))}getOrCreateSharedDepthPipeline(e,t,r,n,i,a,s){if(!(this.state.device&&this.state.shadowBindGroupLayout&&this.state.directShadowBindGroupLayout&&this.state.skinningBindGroupLayout))throw new Error("Renderer is not initialized.");const o=this.sharedDepthPipelineCache.get(e);if(o)return o;const l=this.state.device.createBindGroupLayout({label:`${e}-shared-depth-material-layout`,entries:i}),c="prepass"===r?"instanced-direct"===n?this.state.directSceneBindGroupLayout:this.state.sceneBindGroupLayout:"instanced-direct"===n?this.state.directShadowBindGroupLayout:this.state.shadowBindGroupLayout,u=this.state.device.createPipelineLayout({label:`${e}-shared-depth-pipeline-layout`,bindGroupLayouts:[c,l,...a?[this.state.skinningBindGroupLayout]:[]]}),d=pr(t,"prepass"===r?"camera":"shadow",this.state.device,n,a),h=this.buildMaterialShaderCode(t,d,"pointShadow"===r?t.pointShadowVertexShader??t.vertexShader:t.depthVertexShader??t.vertexShader,`${e}-shared-depth-vertex`,a,s),p="pointShadow"===r?t.pointShadowFragmentShader:t.depthFragmentShader,f=p?this.buildMaterialShaderCode(t,d,p,`${e}-shared-depth-fragment`,a,s):null,m={bindGroupLayout:l,pipeline:this.state.device.createRenderPipeline({label:`${e}-shared-depth-pipeline`,layout:u,vertex:{module:this.state.device.createShaderModule({label:`${e}-shared-depth-vertex`,code:h}),entryPoint:"vsMain",buffers:this.createVertexBufferLayouts(this.getMaterialVertexAttributes(t,a))},...f?{fragment:{module:this.state.device.createShaderModule({label:`${e}-shared-depth-fragment`,code:f}),entryPoint:"fsMain",targets:"pointShadow"===r?[{format:"rgba16float"}]:[]}}:{},primitive:{topology:$i(t),cullMode:ji(t,r,s),frontFace:"ccw"},depthStencil:{format:"depth32float",depthWriteEnabled:!0,depthCompare:"less",..."directionalShadow"===r?{depthBias:1,depthBiasSlopeScale:2,depthBiasClamp:0}:{}}})};return this.sharedDepthPipelineCache.set(e,m),m}async getOrCreateSharedDepthPipelineAsync(e,t,r,n,i,a,s){if(!(this.state.device&&this.state.sceneBindGroupLayout&&this.state.directSceneBindGroupLayout&&this.state.shadowBindGroupLayout&&this.state.directShadowBindGroupLayout&&this.state.skinningBindGroupLayout))throw new Error("Renderer is not initialized.");const o=this.sharedDepthPipelineCache.get(e);if(o)return o;const l=this.sharedDepthPipelinePromiseCache.get(e);if(l)return l;const c=(async()=>{const o=this.state.device.createBindGroupLayout({label:`${e}-shared-depth-material-layout`,entries:i}),l="prepass"===r?"instanced-direct"===n?this.state.directSceneBindGroupLayout:this.state.sceneBindGroupLayout:"instanced-direct"===n?this.state.directShadowBindGroupLayout:this.state.shadowBindGroupLayout,c=this.state.device.createPipelineLayout({label:`${e}-shared-depth-pipeline-layout`,bindGroupLayouts:[l,o,...a?[this.state.skinningBindGroupLayout]:[]]}),u=pr(t,"prepass"===r?"camera":"shadow",this.state.device,n,a),d=this.buildMaterialShaderCode(t,u,"pointShadow"===r?t.pointShadowVertexShader??t.vertexShader:t.depthVertexShader??t.vertexShader,`${e}-shared-depth-vertex`,a,s),h="pointShadow"===r?t.pointShadowFragmentShader:t.depthFragmentShader,p=h?this.buildMaterialShaderCode(t,u,h,`${e}-shared-depth-fragment`,a,s):null,f={bindGroupLayout:o,pipeline:await this.state.device.createRenderPipelineAsync({label:`${e}-shared-depth-pipeline`,layout:c,vertex:{module:this.state.device.createShaderModule({label:`${e}-shared-depth-vertex`,code:d}),entryPoint:"vsMain",buffers:this.createVertexBufferLayouts(this.getMaterialVertexAttributes(t,a))},...p?{fragment:{module:this.state.device.createShaderModule({label:`${e}-shared-depth-fragment`,code:p}),entryPoint:"fsMain",targets:"pointShadow"===r?[{format:"rgba16float"}]:[]}}:{},primitive:{topology:$i(t),cullMode:ji(t,r,s),frontFace:"ccw"},depthStencil:{format:"depth32float",depthWriteEnabled:!0,depthCompare:"less",..."directionalShadow"===r?{depthBias:1,depthBiasSlopeScale:2,depthBiasClamp:0}:{}}})};return this.sharedDepthPipelineCache.set(e,f),this.sharedDepthPipelinePromiseCache.delete(e),f})();return this.sharedDepthPipelinePromiseCache.set(e,c),c}getOrCreateSharedForwardPipeline(e,t,r,n,i,a,s,o,l=this.sampleCount){if(!(this.state.device&&this.state.format&&this.state.sceneBindGroupLayout&&this.state.visibleSceneBindGroupLayout&&this.state.directSceneBindGroupLayout&&this.state.skinningBindGroupLayout&&this.state.emptyBindGroupLayout))throw new Error("Renderer is not initialized.");const c=this.sharedForwardPipelineCache.get(e);if(c)return c;const u=this.state.device.createBindGroupLayout({label:`${e}-shared-forward-material-layout`,entries:n}),d=this.createGraphTextureBindGroupLayout(t),h=this.state.device.createPipelineLayout({label:`${e}-shared-forward-pipeline-layout`,bindGroupLayouts:["instanced-direct"===r?this.state.directSceneBindGroupLayout:"packed-visible"===r?this.state.visibleSceneBindGroupLayout:this.state.sceneBindGroupLayout,u,s?this.state.skinningBindGroupLayout:this.state.emptyBindGroupLayout,d]}),p=hr(t,this.state.device,r,i,s),f=this.buildMaterialShaderCode(t,p,t.vertexShader,`${e}-shared-forward-vertex`,s,o),m=this.buildMaterialShaderCode(t,p,t.fragmentShader,`${e}-shared-forward-fragment`,s,o),g={bindGroupLayout:u,graphTextureBindGroupLayout:d,pipeline:this.state.device.createRenderPipeline({label:`${e}-shared-forward-pipeline`,layout:h,vertex:{module:this.state.device.createShaderModule({label:`${e}-shared-forward-vertex`,code:f}),entryPoint:"vsMain",buffers:this.createVertexBufferLayouts(this.getMaterialVertexAttributes(t,s))},fragment:{module:this.state.device.createShaderModule({label:`${e}-shared-forward-fragment`,code:m}),entryPoint:"fsMain",targets:Ei(m,a,Ai(t))},primitive:{topology:$i(t),cullMode:$i(t).startsWith("triangle")&&t.side!==it?t.side===et?"front":"back":"none",frontFace:"ccw"},multisample:{count:l},depthStencil:{format:"depth32float",depthWriteEnabled:t.depthWrite,depthCompare:t.depthTest?"less-equal":"always"}})};return this.sharedForwardPipelineCache.set(e,g),g}async getOrCreateSharedForwardPipelineAsync(e,t,r,n,i,a,s,o,l=this.sampleCount){if(!(this.state.device&&this.state.format&&this.state.sceneBindGroupLayout&&this.state.visibleSceneBindGroupLayout&&this.state.directSceneBindGroupLayout&&this.state.skinningBindGroupLayout&&this.state.emptyBindGroupLayout))throw new Error("Renderer is not initialized.");const c=this.sharedForwardPipelineCache.get(e);if(c)return c;const u=this.sharedForwardPipelinePromiseCache.get(e);if(u)return u;const d=(async()=>{const c=this.state.device.createBindGroupLayout({label:`${e}-shared-forward-material-layout`,entries:n}),u=this.createGraphTextureBindGroupLayout(t),d=this.state.device.createPipelineLayout({label:`${e}-shared-forward-pipeline-layout`,bindGroupLayouts:["instanced-direct"===r?this.state.directSceneBindGroupLayout:"packed-visible"===r?this.state.visibleSceneBindGroupLayout:this.state.sceneBindGroupLayout,c,s?this.state.skinningBindGroupLayout:this.state.emptyBindGroupLayout,u]}),h=hr(t,this.state.device,r,i,s),p=this.buildMaterialShaderCode(t,h,t.vertexShader,`${e}-shared-forward-vertex`,s,o),f=this.buildMaterialShaderCode(t,h,t.fragmentShader,`${e}-shared-forward-fragment`,s,o),m={bindGroupLayout:c,graphTextureBindGroupLayout:u,pipeline:await this.state.device.createRenderPipelineAsync({label:`${e}-shared-forward-pipeline`,layout:d,vertex:{module:this.state.device.createShaderModule({label:`${e}-shared-forward-vertex`,code:p}),entryPoint:"vsMain",buffers:this.createVertexBufferLayouts(this.getMaterialVertexAttributes(t,s))},fragment:{module:this.state.device.createShaderModule({label:`${e}-shared-forward-fragment`,code:f}),entryPoint:"fsMain",targets:Ei(f,a,Ai(t))},primitive:{topology:$i(t),cullMode:$i(t).startsWith("triangle")&&t.side!==it?t.side===et?"front":"back":"none",frontFace:"ccw"},multisample:{count:l},depthStencil:{format:"depth32float",depthWriteEnabled:t.depthWrite,depthCompare:t.depthTest?"less-equal":"always"}})};return this.sharedForwardPipelineCache.set(e,m),this.sharedForwardPipelinePromiseCache.delete(e),m})();return this.sharedForwardPipelinePromiseCache.set(e,d),d}getDepthPassMaterialResource(e,t,r,n,i){if(!(this.state.device&&this.state.shadowBindGroupLayout&&this.state.directShadowBindGroupLayout&&this.state.skinningBindGroupLayout))throw new Error("Renderer is not initialized.");if("prepass"===t&&null===e.depthVertexShader&&!i||"pointShadow"===t&&(null===e.pointShadowVertexShader||null===e.pointShadowFragmentShader))return null;const a=this.getDepthMaterialFastCacheIndex(t,r,n,i),s=this.depthMaterialFastCache.get(e)?.[a];if(s&&this.fastMaterialResourceMatches(s,e))return this.updateMaterialUniformBuffer(e,s),s;const o=`${t}:${r}:${n?1:0}:${i?1:0}`,l=this.depthMaterialFrameCache.get(e),c=l?.get(o);if(c?.extractionVersion===this.extractionVersion)return c.resource;const u="prepass"===t?this.depthPrepassMaterialCache:n?this.skinnedDirectionalShadowMaterialCache:"instanced-direct"===r?this.directionalShadowMaterialCacheDirect:this.directionalShadowMaterialCache,d=this.getDepthPassMaterialKey(e,t,r,n,i),h=u.get(e),p=h?.get(d);if(p&&this.materialResourceMatches(p,e,d))return this.setDepthMaterialFastCache(e,a,p),this.updateMaterialUniformBuffer(e,p),this.setDepthMaterialFrameCache(e,o,p),p;this.destroyMaterialResource(p),h&&h.delete(d);const{bindGroupLayoutEntries:f,bindGroupEntries:m,uniformBuffer:g,textures:x,textureVersions:v,storageBuffers:w}=this.createMaterialBindGroupData(e,`${e.uuid}-${t}-${r}-material`,GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT),b=this.getOrCreateSharedDepthPipeline(d,e,t,r,f,n,i),y=this.state.device.createBindGroup({label:`${e.uuid}-${t}-${r}-material-bind-group`,layout:b.bindGroupLayout,entries:m}),S={key:d,materialVersion:e.version,textureVersionHash:e.getTextureVersionHash(),rendererSampleCount:this.sampleCount,instanceAccessMode:r,receiveShadow:!0,useBatching:i,colorTargetFormatsKey:"",pipeline:b.pipeline,graphTextureBindGroupLayout:b.graphTextureBindGroupLayout,bindGroup:y,uniformBuffer:g,uniformBufferSize:g?.size??0,uniformValueHash:e.getUniformValueHash(),textures:x,textureVersions:v,storageBuffers:w,vertexAttributes:this.getMaterialVertexAttributes(e,n),usesSkinning:n};let C=u.get(e);return C||(C=new Map,u.set(e,C)),C.set(d,S),this.setDepthMaterialFastCache(e,a,S),this.setDepthMaterialFrameCache(e,o,S),S}setDepthMaterialFrameCache(e,t,r){let n=this.depthMaterialFrameCache.get(e);n||(n=new Map,this.depthMaterialFrameCache.set(e,n)),n.set(t,{extractionVersion:this.extractionVersion,resource:r})}async getDepthPassMaterialResourceAsync(e,t,r,n,i){if(!(this.state.device&&this.state.sceneBindGroupLayout&&this.state.directSceneBindGroupLayout&&this.state.shadowBindGroupLayout&&this.state.directShadowBindGroupLayout&&this.state.skinningBindGroupLayout))throw new Error("Renderer is not initialized.");if("prepass"===t&&null===e.depthVertexShader&&!i||"pointShadow"===t&&(null===e.pointShadowVertexShader||null===e.pointShadowFragmentShader))return null;const a=this.getDepthMaterialFastCacheIndex(t,r,n,i),s=this.depthMaterialFastCache.get(e)?.[a];if(s&&this.fastMaterialResourceMatches(s,e))return this.updateMaterialUniformBuffer(e,s),s;const o="prepass"===t?this.depthPrepassMaterialCache:n?this.skinnedDirectionalShadowMaterialCache:"instanced-direct"===r?this.directionalShadowMaterialCacheDirect:this.directionalShadowMaterialCache,l=this.getDepthPassMaterialKey(e,t,r,n,i),c=o.get(e),u=c?.get(l);if(u&&this.materialResourceMatches(u,e,l))return this.setDepthMaterialFastCache(e,a,u),this.updateMaterialUniformBuffer(e,u),u;this.destroyMaterialResource(u),c&&c.delete(l);const{bindGroupLayoutEntries:d,bindGroupEntries:h,uniformBuffer:p,textures:f,textureVersions:m,storageBuffers:g}=this.createMaterialBindGroupData(e,`${e.uuid}-${t}-${r}-material`,GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT),x=await this.getOrCreateSharedDepthPipelineAsync(l,e,t,r,d,n,i),v=this.state.device.createBindGroup({label:`${e.uuid}-${t}-${r}-material-bind-group`,layout:x.bindGroupLayout,entries:h}),w={key:l,materialVersion:e.version,textureVersionHash:e.getTextureVersionHash(),rendererSampleCount:this.sampleCount,instanceAccessMode:r,receiveShadow:!0,useBatching:i,colorTargetFormatsKey:"",pipeline:x.pipeline,graphTextureBindGroupLayout:x.graphTextureBindGroupLayout,bindGroup:v,uniformBuffer:p,uniformBufferSize:p?.size??0,uniformValueHash:e.getUniformValueHash(),textures:f,textureVersions:m,storageBuffers:g,vertexAttributes:this.getMaterialVertexAttributes(e,n),usesSkinning:n};let b=o.get(e);return b||(b=new Map,o.set(e,b)),b.set(l,w),this.setDepthMaterialFastCache(e,a,w),w}getMaterialResource(e,t,r=!0,n,i=!1,a=!1,s=this.sampleCount){if(!(this.state.device&&this.state.format&&this.state.sceneBindGroupLayout&&this.state.visibleSceneBindGroupLayout&&this.state.directSceneBindGroupLayout))throw new Error("Renderer is not initialized.");const o=i?r?this.skinnedMaterialCache:this.skinnedMaterialNoReceiveShadowCache:r?"instanced-direct"===t?this.materialCacheDirect:"packed-visible"===t?this.materialCacheVisible:this.materialCache:"instanced-direct"===t?this.materialNoReceiveShadowCacheDirect:"packed-visible"===t?this.materialNoReceiveShadowCacheVisible:this.materialNoReceiveShadowCache,l=n??[Er],c=void 0===n||1===n.length&&n[0]===Er,u=this.getForwardMaterialFastCacheIndex(t,r,i,a),d=c?null:this.getForwardMaterialTargetFastCacheKey(l,u);if(c){const t=this.forwardMaterialFrameCache.get(e)?.[u];if(t?.extractionVersion===this.extractionVersion&&t.resource.rendererSampleCount===s)return t.resource;const r=this.forwardMaterialFastCache.get(e)?.[u];if(r&&this.fastMaterialResourceMatches(r,e,s))return this.updateMaterialUniformBuffer(e,r),this.setForwardMaterialFrameCache(e,u,r),r}else{const t=this.forwardMaterialTargetFastCache.get(e)?.get(d);if(t&&this.fastMaterialResourceMatches(t,e,s))return this.updateMaterialUniformBuffer(e,t),t}const h=this.getForwardMaterialKey(e,t,r,l,i,a,s),p=o.get(e),f=p?.get(h);if(f&&this.materialResourceMatches(f,e,h,s))return c?(this.setForwardMaterialFastCache(e,u,f),this.setForwardMaterialFrameCache(e,u,f)):this.setForwardMaterialTargetFastCache(e,d,f),this.updateMaterialUniformBuffer(e,f),f;this.destroyMaterialResource(f),p&&p.delete(h);const{bindGroupLayoutEntries:m,bindGroupEntries:g,uniformBuffer:x,textures:v,textureVersions:w,storageBuffers:b}=this.createMaterialBindGroupData(e,`${e.uuid}-${t}-material`,GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT),y=this.getOrCreateSharedForwardPipeline(h,e,t,m,r,l,i,a,s),S=this.state.device.createBindGroup({label:`${e.uuid}-${t}-material-bind-group`,layout:y.bindGroupLayout,entries:g}),C={key:h,materialVersion:e.version,textureVersionHash:e.getTextureVersionHash(),rendererSampleCount:s,instanceAccessMode:t,receiveShadow:r,useBatching:a,colorTargetFormatsKey:l.join("|"),pipeline:y.pipeline,graphTextureBindGroupLayout:y.graphTextureBindGroupLayout,bindGroup:S,uniformBuffer:x,uniformBufferSize:x?.size??0,uniformValueHash:e.getUniformValueHash(),textures:v,textureVersions:w,storageBuffers:b,vertexAttributes:this.getMaterialVertexAttributes(e,i),usesSkinning:i};let P=o.get(e);return P||(P=new Map,o.set(e,P)),P.set(h,C),c?(this.setForwardMaterialFastCache(e,u,C),this.setForwardMaterialFrameCache(e,u,C)):this.setForwardMaterialTargetFastCache(e,d,C),C}async getMaterialResourceAsync(e,t,r=!0,n,i=!1,a=!1,s=this.sampleCount){if(!(this.state.device&&this.state.format&&this.state.sceneBindGroupLayout&&this.state.visibleSceneBindGroupLayout&&this.state.directSceneBindGroupLayout))throw new Error("Renderer is not initialized.");const o=i?r?this.skinnedMaterialCache:this.skinnedMaterialNoReceiveShadowCache:r?"instanced-direct"===t?this.materialCacheDirect:"packed-visible"===t?this.materialCacheVisible:this.materialCache:"instanced-direct"===t?this.materialNoReceiveShadowCacheDirect:"packed-visible"===t?this.materialNoReceiveShadowCacheVisible:this.materialNoReceiveShadowCache,l=n??[Er],c=void 0===n||1===n.length&&n[0]===Er,u=this.getForwardMaterialFastCacheIndex(t,r,i,a);if(c){const t=this.forwardMaterialFrameCache.get(e)?.[u];if(t?.extractionVersion===this.extractionVersion&&t.resource.rendererSampleCount===s)return t.resource;const r=this.forwardMaterialFastCache.get(e)?.[u];if(r&&this.fastMaterialResourceMatches(r,e,s))return this.updateMaterialUniformBuffer(e,r),this.setForwardMaterialFrameCache(e,u,r),r}const d=this.getForwardMaterialKey(e,t,r,l,i,a,s),h=o.get(e),p=h?.get(d);if(p&&this.materialResourceMatches(p,e,d,s))return c&&(this.setForwardMaterialFastCache(e,u,p),this.setForwardMaterialFrameCache(e,u,p)),this.updateMaterialUniformBuffer(e,p),p;this.destroyMaterialResource(p),h&&h.delete(d);const{bindGroupLayoutEntries:f,bindGroupEntries:m,uniformBuffer:g,textures:x,textureVersions:v,storageBuffers:w}=this.createMaterialBindGroupData(e,`${e.uuid}-${t}-material`,GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT),b=await this.getOrCreateSharedForwardPipelineAsync(d,e,t,f,r,l,i,a,s),y=this.state.device.createBindGroup({label:`${e.uuid}-${t}-material-bind-group`,layout:b.bindGroupLayout,entries:m}),S={key:d,materialVersion:e.version,textureVersionHash:e.getTextureVersionHash(),rendererSampleCount:s,instanceAccessMode:t,receiveShadow:r,useBatching:a,colorTargetFormatsKey:l.join("|"),pipeline:b.pipeline,graphTextureBindGroupLayout:b.graphTextureBindGroupLayout,bindGroup:y,uniformBuffer:g,uniformBufferSize:g?.size??0,uniformValueHash:e.getUniformValueHash(),textures:x,textureVersions:v,storageBuffers:w,vertexAttributes:this.getMaterialVertexAttributes(e,i),usesSkinning:i};let C=o.get(e);return C||(C=new Map,o.set(e,C)),C.set(d,S),c&&(this.setForwardMaterialFastCache(e,u,S),this.setForwardMaterialFrameCache(e,u,S)),S}updateCameraUniforms(e,t){if(!this.state.device||!this.state.cameraBuffer)return;const r=this.cameraProjectionScratch.copy(e.projectionMatrix);r.elements[8]-=2*this.projectionJitterPixels.x/this.state.width,r.elements[9]-=2*this.projectionJitterPixels.y/this.state.height;const n=this.cameraViewProjScratch.copy(kr).multiply(r).multiply(e.matrixWorldInverse);e.getWorldPosition(Hr);const i=this.cameraUniformScratch;i.set(n.elements,0),i[16]=Hr.x,i[17]=Hr.y,i[18]=Hr.z,i[19]=1,i[20]=this.state.width,i[21]=this.state.height,i[22]=this.state.pixelRatio,i[23]=this.state.frameTimeSeconds,i.set(e.matrixWorldInverse.elements,24),i.set(_r.multiplyMatrices(kr,r).elements,40),i[56]=e.near,i[57]=e.far,i[58]=1/Math.max(e.far-e.near,1e-4),i[59]=0;const a=t.fog;null!=a?(i[60]=a.color.r,i[61]=a.color.g,i[62]=a.color.b,i[63]=1,"density"in a?(i[64]=0,i[65]=0,i[66]=a.density,i[67]=1):(i[64]=a.near,i[65]=a.far,i[66]=0,i[67]=0)):(i.fill(0,60,68),i[67]=-1),this.state.device.queue.writeBuffer(this.state.cameraBuffer,0,i,0,68)}updateTemporalVisibilityUniforms(e){if(!this.state.device||!this.state.temporalVisibilityBuffer)return;const t=Vn(e,this.temporalVisibilityCurrentViewProj);e.getWorldPosition(this.temporalVisibilityCurrentCameraPosition);const r=this.temporalVisibilityUniformScratch;r.set(t.elements,0),r.set((this.state.temporalHiZHistoryValid?this.temporalVisibilityPreviousViewProj:t).elements,16),r[32]=this.temporalVisibilityCurrentCameraPosition.x,r[33]=this.temporalVisibilityCurrentCameraPosition.y,r[34]=this.temporalVisibilityCurrentCameraPosition.z,r[35]=1;const n=this.state.temporalHiZHistoryValid?this.temporalVisibilityPreviousCameraPosition:this.temporalVisibilityCurrentCameraPosition;r[36]=n.x,r[37]=n.y,r[38]=n.z,r[39]=1,r[40]=this.state.width,r[41]=this.state.height,r[42]=this.state.pixelRatio,r[43]=this.state.frameTimeSeconds,this.state.device.queue.writeBuffer(this.state.temporalVisibilityBuffer,0,r,0,44)}commitTemporalHiZHistory(){this.temporalVisibilityPreviousViewProj.copy(this.temporalVisibilityCurrentViewProj),this.temporalVisibilityPreviousCameraPosition.copy(this.temporalVisibilityCurrentCameraPosition),this.state.temporalHiZHistoryValid=!0}updateLightUniforms(e){if(!this.state.device||!this.state.lightBuffer)return;const t=this.lightUniformScratch;t.fill(0),t[0]=e.lights.ambient.x,t[1]=e.lights.ambient.y,t[2]=e.lights.ambient.z,t[3]=e.lights.ambient.w,t[4]=e.lights.directionals.length,t[5]=e.lights.points.length,t[6]=e.lights.spots.length,t[7]=Math.min(this.csmCascadeCount,e.lights.directionals.length);for(let e=0;e<this.csmCascadeCount;e+=1){const r=this.csmCascadeRanges[e],n=360+4*e;t[n+0]=r.x,t[n+1]=r.y}const r=e.lights.hemisphere;null!=r&&(t[376]=r.skyColor.x,t[377]=r.skyColor.y,t[378]=r.skyColor.z,t[379]=r.intensity,t[380]=r.groundColor.x,t[381]=r.groundColor.y,t[382]=r.groundColor.z,t[383]=r.intensity,t[384]=r.direction.x,t[385]=r.direction.y,t[386]=r.direction.z,t[387]=1);for(let r=0;r<e.lights.directionals.length;r+=1){const n=e.lights.directionals[r],i=this.directionalShadowCameras[r];i.left=n.shadowCameraLeft,i.right=n.shadowCameraRight,i.top=n.shadowCameraTop,i.bottom=n.shadowCameraBottom,i.near=n.shadowCameraNear,i.far=n.shadowCameraFar,i.position.copy(n.position),i.lookAt(n.target),i.updateMatrixWorld(!0),i.updateProjectionMatrix();const a=8+4*r;t[a+0]=n.direction.x,t[a+1]=n.direction.y,t[a+2]=n.direction.z,t[a+3]=1;const s=24+4*r;t[s+0]=n.color.x,t[s+1]=n.color.y,t[s+2]=n.color.z,t[s+3]=n.intensity;const o=40+4*r;t[o+0]=n.shadowBias,t[o+1]=n.castShadow?1:0,t[o+2]=this.state.directionalShadowTextureSize,t[o+3]=n.shadowNormalBias;const l=56+4*r;t[l+0]=n.shadowRadius,t[l+1]=n.shadowIntensity,t.set(Vn(i,this.shadowViewProjScratch).elements,72+16*r)}for(let r=0;r<e.lights.points.length;r+=1){const n=e.lights.points[r],i=136+4*r;t[i+0]=n.position.x,t[i+1]=n.position.y,t[i+2]=n.position.z,t[i+3]=n.range;const a=152+4*r;t[a+0]=n.color.x,t[a+1]=n.color.y,t[a+2]=n.color.z,t[a+3]=n.intensity;const s=168+4*r;t[s+0]=n.shadowBias,t[s+1]=n.castShadow?1:0,t[s+2]=this.state.pointShadowTextureSize,t[s+3]=n.shadowNormalBias;const o=184+4*r;t[o+0]=n.shadowRadius,t[o+1]=n.shadowIntensity,t[o+2]=n.shadowCameraNear,t[o+3]=n.shadowCameraFar}for(let r=0;r<e.lights.spots.length;r+=1){const n=e.lights.spots[r],i=this.spotShadowCameras[r];i.near=n.shadowCameraNear,i.far=n.shadowCameraFar,i.fov=n.shadowCameraFov,i.aspect=1,i.position.copy(n.position),Kr.copy(n.position).add(n.direction),i.lookAt(Kr),i.updateMatrixWorld(!0),i.updateProjectionMatrix();const a=200+4*r;t[a+0]=n.position.x,t[a+1]=n.position.y,t[a+2]=n.position.z,t[a+3]=n.range;const s=216+4*r;t[s+0]=n.direction.x,t[s+1]=n.direction.y,t[s+2]=n.direction.z,t[s+3]=Math.cos(n.angle);const o=232+4*r;t[o+0]=n.color.x,t[o+1]=n.color.y,t[o+2]=n.color.z,t[o+3]=n.intensity;const l=248+4*r;t[l+0]=n.shadowBias,t[l+1]=n.castShadow?1:0,t[l+2]=this.state.spotShadowTextureSize,t[l+3]=n.shadowNormalBias;const c=264+4*r;t[c+0]=n.shadowRadius,t[c+1]=n.shadowIntensity;const u=280+4*r;t[u+0]=n.range,t[u+1]=Math.cos(n.angle*(1-n.penumbra)),t[u+2]=n.decay,t.set(Vn(i,this.shadowViewProjScratch).elements,296+16*r)}this.state.device.queue.writeBuffer(this.state.lightBuffer,0,t,0,396)}writeShadowCameraBuffer(e,t,r,n,i,a=this.state.shadowCameraBuffer,s){if(!this.state.device||!a)return;const o=this.shadowCameraUniformScratch;o.set(e.elements,0),o[16]=t,o[17]=r,o[18]=n,o[19]=i,o[60]=this.state.frameTimeSeconds,o[61]=0,o[62]=0,o[63]=0,s&&(o.set(s.matrixWorldInverse.elements,20),o.set(s.projectionMatrix.elements,36),o[52]=s.position.x,o[53]=s.position.y,o[54]=s.position.z,o[55]=1,o[56]=s.near,o[57]=s.far,o[58]=0,o[59]=0),this.state.device.queue.writeBuffer(a,0,o,0,64)}};import{DataTexture as _i,Matrix4 as qi,RepeatWrapping as Hi}from"three";var Ki=class{options;noiseTexture=function(){const e=new Array(25).fill(0);let t=Math.floor(2.5),r=4;for(let n=1;n<=25;){-1===t&&5===r?(t=0,r=3):(5===r&&(r=0),t<0&&(t=4));const i=5*t+r;0===e[i]?(e[i]=n++,t-=1,r+=1):(t+=1,r-=2)}const n=new Uint8Array(100);for(let t=0;t<e.length;t+=1){const r=2*Math.PI*e[t]/e.length;n[4*t]=Math.round(255*(.5*Math.cos(r)+.5)),n[4*t+1]=Math.round(255*(.5*Math.sin(r)+.5)),n[4*t+2]=127,n[4*t+3]=255}const i=new _i(n,5,5);return i.wrapS=Hi,i.wrapT=Hi,i.needsUpdate=!0,i}();gtaoPasses=new Map;denoisePasses=new Map;compositePasses=new Map;constructor(e={}){this.options={radius:Math.max(.001,e.radius??.25),resolutionScale:Qi(e.resolutionScale??1,.25,1),thickness:Math.max(.001,e.thickness??1),distanceExponent:Math.max(.01,e.distanceExponent??1),distanceFalloff:Qi(e.distanceFalloff??1,0,1),directions:ea(e.directions??3,1,8),steps:ea(e.steps??6,1,16),normalSpace:e.normalSpace??"world",targetPrefix:e.targetPrefix??"gtao",denoise:!1!==e.denoise&&{radius:Math.max(1,e.denoise?.radius??8),depthPhi:Math.max(1e-4,e.denoise?.depthPhi??2),normalPhi:Math.max(1e-4,e.denoise?.normalPhi??3),lumaPhi:Math.max(1e-4,e.denoise?.lumaPhi??10)}}}addPasses(e,t){const r=e.createColorTarget(`${this.options.targetPrefix}Raw`,{format:"r16float",scale:this.options.resolutionScale}),n=`${t.depth}:${t.normal}:${r}`;let i=this.gtaoPasses.get(n);if(i||(i=new Zi(t.depth,t.normal,r,this.noiseTexture,this.options),this.gtaoPasses.set(n,i)),e.addFullscreenPass(i),!1===this.options.denoise)return r;const a=e.createColorTarget(`${this.options.targetPrefix}Denoised`,{format:"r16float",scale:this.options.resolutionScale}),s=`${r}:${t.depth}:${t.normal}:${a}`;let o=this.denoisePasses.get(s);return o||(o=new Yi(r,t.depth,t.normal,a,this.options.normalSpace,this.options.denoise),this.denoisePasses.set(s,o)),e.addFullscreenPass(o),a}addCompositePass(e,t,r,n={}){const i=n.output??e.createColorTarget(`${this.options.targetPrefix}Composite`,{format:"rgba16float"}),a=Math.max(0,n.intensity??.6),s=Math.max(1e-4,n.power??1),o=`${t}:${r}:${i}:${a}:${s}`;let l=this.compositePasses.get(o);return l||(l=new Xi(t,r,i,a,s),this.compositePasses.set(o,l)),e.addFullscreenPass(l),i}dispose(){this.noiseTexture.dispose()}},Zi=class{constructor(e,t,r,n,i){this.options=i,this.inputs={sceneDepth:e,sceneNormal:t},this.outputs=r,this.textures={gtaoNoise:n},this.fragmentShader=function(e){const t="world"===e.normalSpace?"normalize(viewRotation() * decodedNormal)":"decodedNormal";return`\nconst PI = 3.14159265359;\nconst DIRECTIONS: i32 = ${e.directions};\nconst STEPS: i32 = ${e.steps};\n\nfn projectionMatrix() -> mat4x4<f32> {\n return mat4x4<f32>(fullscreenUniforms[0], fullscreenUniforms[1], fullscreenUniforms[2], fullscreenUniforms[3]);\n}\nfn inverseProjectionMatrix() -> mat4x4<f32> {\n return mat4x4<f32>(fullscreenUniforms[4], fullscreenUniforms[5], fullscreenUniforms[6], fullscreenUniforms[7]);\n}\nfn viewRotation() -> mat3x3<f32> {\n return mat3x3<f32>(fullscreenUniforms[8].xyz, fullscreenUniforms[9].xyz, fullscreenUniforms[10].xyz);\n}\nfn getViewPosition(uv: vec2<f32>, depth: f32) -> vec3<f32> {\n let clip = vec4<f32>(uv.x * 2.0 - 1.0, 1.0 - uv.y * 2.0, depth, 1.0);\n let view = inverseProjectionMatrix() * clip;\n return view.xyz / view.w;\n}\nfn projectViewPosition(position: vec3<f32>) -> vec2<f32> {\n let clip = projectionMatrix() * vec4<f32>(position, 1.0);\n let ndc = clip.xy / clip.w;\n return vec2<f32>(ndc.x * 0.5 + 0.5, 0.5 - ndc.y * 0.5);\n}\nfn loadDepth(uv: vec2<f32>, size: vec2<i32>) -> f32 {\n let pixel = clamp(vec2<i32>(uv * vec2<f32>(size)), vec2<i32>(0), size - vec2<i32>(1));\n return textureLoad(sceneDepthTexture, pixel, 0);\n}\n\n@fragment\nfn fsMain(input: FullscreenVertexOutput) -> @location(0) vec4<f32> {\n let depthSize = vec2<i32>(textureDimensions(sceneDepthTexture));\n let pixel = clamp(vec2<i32>(input.uv * vec2<f32>(depthSize)), vec2<i32>(0), depthSize - vec2<i32>(1));\n let depth = textureLoad(sceneDepthTexture, pixel, 0);\n if (depth >= 1.0) { return vec4<f32>(1.0); }\n\n let viewPosition = getViewPosition(input.uv, depth);\n let decodedNormal = normalize(textureLoad(sceneNormalTexture, pixel, 0).rgb * 2.0 - vec3<f32>(1.0));\n let viewNormal = ${t};\n let viewDirection = normalize(-viewPosition);\n let radius = fullscreenUniforms[12].x;\n let thickness = fullscreenUniforms[12].y;\n let distanceExponent = fullscreenUniforms[12].z;\n let distanceFalloff = fullscreenUniforms[12].w;\n let noiseSize = vec2<f32>(textureDimensions(gtaoNoiseTexture));\n let noiseUv = input.uv * vec2<f32>(depthSize) / noiseSize;\n let noiseTexel = textureSampleLevel(gtaoNoiseTexture, gtaoNoiseSampler, noiseUv, 0.0);\n let tangent = normalize(vec3<f32>(noiseTexel.xy * 2.0 - vec2<f32>(1.0), 0.0));\n let bitangent = vec3<f32>(-tangent.y, tangent.x, 0.0);\n var ao = 0.0;\n\n for (var i = 0; i < DIRECTIONS; i += 1) {\n let angle = (f32(i) / f32(DIRECTIONS)) * PI;\n let sampleDirection = normalize(tangent * cos(angle) + bitangent * sin(angle));\n let sliceBitangent = normalize(cross(sampleDirection, viewDirection));\n let sliceTangent = cross(sliceBitangent, viewDirection);\n let normalInSlice = normalize(viewNormal - sliceBitangent * dot(viewNormal, sliceBitangent));\n let tangentToNormal = cross(normalInSlice, sliceBitangent);\n var cosHorizons = vec2<f32>(dot(viewDirection, tangentToNormal), dot(viewDirection, -tangentToNormal));\n for (var j = 0; j < STEPS; j += 1) {\n let distance = radius * pow(f32(j + 1) / f32(STEPS), distanceExponent);\n for (var side = 0; side < 2; side += 1) {\n let sign = select(-1.0, 1.0, side == 0);\n let sampleUv = projectViewPosition(viewPosition + sampleDirection * distance * sign);\n if (all(sampleUv >= vec2<f32>(0.0)) && all(sampleUv <= vec2<f32>(1.0))) {\n let sampleDepth = loadDepth(sampleUv, depthSize);\n if (sampleDepth < 1.0) {\n let viewDelta = getViewPosition(sampleUv, sampleDepth) - viewPosition;\n if (abs(viewDelta.z) < thickness) {\n let horizon = dot(viewDirection, normalize(viewDelta));\n let update = max(0.0, (horizon - cosHorizons[side]) * mix(1.0, 2.0 / f32(j + 2), distanceFalloff));\n cosHorizons[side] += update;\n }\n }\n }\n }\n }\n let sinHorizons = sqrt(max(vec2<f32>(0.0), vec2<f32>(1.0) - cosHorizons * cosHorizons));\n let nx = dot(normalInSlice, sliceTangent);\n let ny = dot(normalInSlice, viewDirection);\n let nxb = 0.5 * (acos(cosHorizons.y) - acos(cosHorizons.x) + sinHorizons.x * cosHorizons.x - sinHorizons.y * cosHorizons.y);\n let nyb = 0.5 * (2.0 - cosHorizons.x * cosHorizons.x - cosHorizons.y * cosHorizons.y);\n ao += nx * nxb + ny * nyb;\n }\n return vec4<f32>(vec3<f32>(clamp(ao / f32(DIRECTIONS), 0.0, 1.0)), 1.0);\n}\n`}(i)}options;name="GTAOPass";sampler="nearest";uniformBufferSize=208;inputs;outputs;textures;fragmentShader;uniforms=new Float32Array(this.uniformBufferSize/4);webGpuProjection=new qi;webGpuProjectionInverse=new qi;updateUniforms=e=>(this.webGpuProjection.copy(Ji).multiply(e.camera.projectionMatrix),this.webGpuProjectionInverse.copy(this.webGpuProjection).invert(),this.uniforms.set(this.webGpuProjection.elements,0),this.uniforms.set(this.webGpuProjectionInverse.elements,16),this.uniforms.set(e.camera.matrixWorldInverse.elements,32),this.uniforms.set([this.options.radius,this.options.thickness,this.options.distanceExponent,this.options.distanceFalloff],48),this.uniforms)},Yi=class{constructor(e,t,r,n,i,a){this.options=a,this.inputs={aoInput:e,sceneDepth:t,sceneNormal:r},this.outputs=n,this.fragmentShader=function(e){const t="world"===e?"normalize(viewRotation() * decoded)":"decoded";return`\nconst PI = 3.14159265359;\nconst MAGIC_SQUARE: array<u32, 25> = array<u32, 25>(9u, 3u, 22u, 16u, 15u, 2u, 21u, 20u, 14u, 8u, 25u, 19u, 13u, 7u, 1u, 18u, 12u, 6u, 5u, 24u, 11u, 10u, 4u, 23u, 17u);\nconst POISSON_DISK: array<vec3<f32>, 16> = array<vec3<f32>, 16>(\n vec3<f32>(1.0, 0.0, 0.0), vec3<f32>(0.707106781, 0.707106781, 0.066666667), vec3<f32>(0.0, 1.0, 0.133333333), vec3<f32>(-0.707106781, 0.707106781, 0.2),\n vec3<f32>(-1.0, 0.0, 0.266666667), vec3<f32>(-0.707106781, -0.707106781, 0.333333333), vec3<f32>(0.0, -1.0, 0.4), vec3<f32>(0.707106781, -0.707106781, 0.466666667),\n vec3<f32>(1.0, 0.0, 0.533333333), vec3<f32>(0.707106781, 0.707106781, 0.6), vec3<f32>(0.0, 1.0, 0.666666667), vec3<f32>(-0.707106781, 0.707106781, 0.733333333),\n vec3<f32>(-1.0, 0.0, 0.8), vec3<f32>(-0.707106781, -0.707106781, 0.866666667), vec3<f32>(0.0, -1.0, 0.933333333), vec3<f32>(0.707106781, -0.707106781, 1.0));\nfn inverseProjectionMatrix() -> mat4x4<f32> { return mat4x4<f32>(fullscreenUniforms[0], fullscreenUniforms[1], fullscreenUniforms[2], fullscreenUniforms[3]); }\nfn viewRotation() -> mat3x3<f32> { return mat3x3<f32>(fullscreenUniforms[4].xyz, fullscreenUniforms[5].xyz, fullscreenUniforms[6].xyz); }\nfn viewPosition(pixel: vec2<i32>, depth: f32, size: vec2<i32>) -> vec3<f32> {\n let uv = (vec2<f32>(pixel) + vec2<f32>(0.5)) / vec2<f32>(size);\n let view = inverseProjectionMatrix() * vec4<f32>(uv.x * 2.0 - 1.0, 1.0 - uv.y * 2.0, depth, 1.0);\n return view.xyz / view.w;\n}\nfn viewNormal(pixel: vec2<i32>) -> vec3<f32> {\n let decoded = normalize(textureLoad(sceneNormalTexture, pixel, 0).rgb * 2.0 - vec3<f32>(1.0));\n return ${t};\n}\nfn magicSquareAngle(pixel: vec2<i32>) -> f32 { return f32(MAGIC_SQUARE[u32((pixel.y % 5) * 5 + pixel.x % 5)]) * (2.0 * PI / 25.0); }\n@fragment\nfn fsMain(input: FullscreenVertexOutput) -> @location(0) vec4<f32> {\n let aoSize = vec2<i32>(textureDimensions(aoInputTexture));\n let depthSize = vec2<i32>(textureDimensions(sceneDepthTexture));\n let pixel = clamp(vec2<i32>(input.position.xy), vec2<i32>(0), aoSize - vec2<i32>(1));\n let depthPixel = clamp(vec2<i32>(input.uv * vec2<f32>(depthSize)), vec2<i32>(0), depthSize - vec2<i32>(1));\n let depth = textureLoad(sceneDepthTexture, depthPixel, 0);\n if (depth >= 1.0) { return vec4<f32>(1.0); }\n let center = textureLoad(aoInputTexture, pixel, 0).r;\n let normal = viewNormal(depthPixel);\n let position = viewPosition(depthPixel, depth, depthSize);\n let radius = fullscreenUniforms[8].x;\n let depthPhi = fullscreenUniforms[8].y;\n let normalPhi = fullscreenUniforms[8].z;\n let lumaPhi = fullscreenUniforms[8].w;\n let angle = magicSquareAngle(pixel);\n let rotation = mat2x2<f32>(vec2<f32>(cos(angle), sin(angle)), vec2<f32>(-sin(angle), cos(angle)));\n var denoised = center;\n var totalWeight = 1.0;\n for (var i = 0; i < 16; i += 1) {\n let sample = POISSON_DISK[i];\n let samplePixel = vec2<i32>(round(vec2<f32>(pixel) + rotation * sample.xy * (1.0 + sample.z * (radius - 1.0))));\n if (all(samplePixel >= vec2<i32>(0)) && all(samplePixel < aoSize)) {\n let sampleUv = (vec2<f32>(samplePixel) + vec2<f32>(0.5)) / vec2<f32>(aoSize);\n let sampleDepthPixel = clamp(vec2<i32>(sampleUv * vec2<f32>(depthSize)), vec2<i32>(0), depthSize - vec2<i32>(1));\n let sampleDepth = textureLoad(sceneDepthTexture, sampleDepthPixel, 0);\n if (sampleDepth < 1.0) {\n let neighbor = textureLoad(aoInputTexture, samplePixel, 0).r;\n let sampleNormal = viewNormal(sampleDepthPixel);\n let samplePosition = viewPosition(sampleDepthPixel, sampleDepth, depthSize);\n let normalSimilarity = pow(max(dot(normal, sampleNormal), 0.0), normalPhi);\n let lumaSimilarity = max(1.0 - abs(neighbor - center) / lumaPhi, 0.0);\n let depthSimilarity = max(1.0 - abs(dot(position - samplePosition, normal)) / depthPhi, 0.0);\n let weight = normalSimilarity * lumaSimilarity * depthSimilarity;\n denoised += neighbor * weight;\n totalWeight += weight;\n }\n }\n }\n return vec4<f32>(vec3<f32>(denoised / totalWeight), 1.0);\n}\n`}(i)}options;name="GTAODenoisePass";sampler="nearest";uniformBufferSize=144;inputs;outputs;fragmentShader;uniforms=new Float32Array(this.uniformBufferSize/4);webGpuProjectionInverse=new qi;updateUniforms=e=>(this.webGpuProjectionInverse.copy(Ji).multiply(e.camera.projectionMatrix).invert(),this.uniforms.set(this.webGpuProjectionInverse.elements,0),this.uniforms.set(e.camera.matrixWorldInverse.elements,16),this.uniforms.set([this.options.radius,this.options.depthPhi,this.options.normalPhi,this.options.lumaPhi],32),this.uniforms)},Xi=class{name="GTAOCompositePass";sampler="nearest";uniformBufferSize=16;inputs;outputs;uniforms;constructor(e,t,r,n,i){this.inputs={sceneColor:e,ambientOcclusion:t},this.outputs=r,this.uniforms=new Float32Array([n,i,0,0])}updateUniforms=()=>this.uniforms;fragmentShader="\n@fragment\nfn fsMain(input: FullscreenVertexOutput) -> @location(0) vec4<f32> {\n let color = textureLoad(sceneColorTexture, vec2<i32>(input.position.xy), 0);\n let aoSize = vec2<i32>(textureDimensions(ambientOcclusionTexture));\n let aoPixel = clamp(vec2<i32>(input.uv * vec2<f32>(aoSize)), vec2<i32>(0), aoSize - vec2<i32>(1));\n let ao = textureLoad(ambientOcclusionTexture, aoPixel, 0).r;\n let visibility = select(1.0, mix(1.0, pow(clamp(ao, 0.0, 1.0), fullscreenUniforms[0].y), fullscreenUniforms[0].x), color.a < 0.2);\n return vec4<f32>(color.rgb * visibility, 1.0);\n}\n"},Ji=(new qi).set(1,0,0,0,0,1,0,0,0,0,.5,.5,0,0,0,1);function Qi(e,t,r){return Math.min(r,Math.max(t,e))}function ea(e,t,r){return Math.floor(Qi(e,t,r))}import{Matrix4 as ta}from"three";var ra=class{options;passes=new Map;constructor(e={}){var t,r,n;this.options={resolutionScale:oa(e.resolutionScale??.5,.25,1),maxDistance:Math.max(.01,e.maxDistance??50),thickness:Math.max(.001,e.thickness??.15),intensity:Math.max(0,e.intensity??.65),distanceAttenuation:e.distanceAttenuation??!0,maxRoughness:oa(e.maxRoughness??.8,.01,1),steps:(t=e.steps??2048,r=8,n=2048,Math.round(oa(t,r,n))),pixelStride:oa(e.pixelStride??1,1,4),normalSpace:e.normalSpace??"world",blur:e.blur??!0,blurRadius:oa(e.blurRadius??6,1,12),targetPrefix:e.targetPrefix??"ssr"}}addPasses(e,t){const r=e.createColorTarget(`${this.options.targetPrefix}Raw`,{format:"rgba16float",scale:this.options.resolutionScale}),n=`trace:${t.sceneColor}:${t.depth}:${t.normalRoughness}:${r}`;let i=this.passes.get(n);i||(i=new na(t,r,this.options),this.passes.set(n,i)),e.addFullscreenPass(i);let a=r;if(this.options.blur)for(let r=0;r<2;r++){const n=e.createColorTarget(`${this.options.targetPrefix}Blur${r}`,{format:"rgba16float",scale:this.options.resolutionScale}),i=`blur:${a}:${t.depth}:${t.normalRoughness}:${n}:${r}:${this.options.blurRadius}`;let s=this.passes.get(i);s||(s=new ia(a,t.depth,t.normalRoughness,n,r,this.options.blurRadius),this.passes.set(i,s)),e.addFullscreenPass(s),a=n}const s=e.createColorTarget(`${this.options.targetPrefix}Composite`,{format:"rgba16float"}),o=`composite:${t.sceneColor}:${a}:${s}`;let l=this.passes.get(o);return l||(l=new aa(t.sceneColor,a,s,this.options.intensity),this.passes.set(o,l)),e.addFullscreenPass(l),s}},na=class{constructor(e,t,r){this.options=r,this.inputs={sceneColor:e.sceneColor,sceneDepth:e.depth,normalRoughness:e.normalRoughness},this.outputs=t,this.fragmentShader=function(e){const t="world"===e.normalSpace?"normalize(viewRotation() * encodedNormal)":"encodedNormal",r=e.distanceAttenuation?"pow(clamp(1.0 - hitDistance / maxDistance, 0.0, 1.0), 2.0)":"1.0";return`\nconst STEPS: i32 = ${e.steps};\nfn projectionMatrix() -> mat4x4<f32> { return mat4x4<f32>(fullscreenUniforms[0], fullscreenUniforms[1], fullscreenUniforms[2], fullscreenUniforms[3]); }\nfn inverseProjectionMatrix() -> mat4x4<f32> { return mat4x4<f32>(fullscreenUniforms[4], fullscreenUniforms[5], fullscreenUniforms[6], fullscreenUniforms[7]); }\nfn viewRotation() -> mat3x3<f32> { return mat3x3<f32>(fullscreenUniforms[8].xyz, fullscreenUniforms[9].xyz, fullscreenUniforms[10].xyz); }\nfn viewPosition(uv: vec2<f32>, depth: f32) -> vec3<f32> {\n let p = inverseProjectionMatrix() * vec4<f32>(uv.x * 2.0 - 1.0, 1.0 - uv.y * 2.0, depth, 1.0);\n return p.xyz / p.w;\n}\nfn projectUv(position: vec3<f32>) -> vec2<f32> {\n let p = projectionMatrix() * vec4<f32>(position, 1.0);\n return vec2<f32>(p.x / p.w * 0.5 + 0.5, 0.5 - p.y / p.w * 0.5);\n}\nfn depthAt(uv: vec2<f32>) -> f32 {\n let size = vec2<i32>(textureDimensions(sceneDepthTexture));\n return textureLoad(sceneDepthTexture, clamp(vec2<i32>(uv * vec2<f32>(size)), vec2<i32>(0), size - vec2<i32>(1)), 0);\n}\nfn viewZFromDepth(depth: f32) -> f32 {\n let projection = projectionMatrix();\n return (projection[3].z - depth * projection[3].w)\n / (depth * projection[2].w - projection[2].z);\n}\nfn pointToLineDistanceSquared(point: vec3<f32>, start: vec3<f32>, end: vec3<f32>) -> f32 {\n let line = end - start;\n let perpendicular = cross(point - start, point - end);\n return dot(perpendicular, perpendicular) / max(dot(line, line), 0.0000001);\n}\nfn pointPlaneDistance(point: vec3<f32>, planePoint: vec3<f32>, planeNormal: vec3<f32>) -> f32 {\n return dot(point - planePoint, planeNormal);\n}\n@fragment\nfn fsMain(input: FullscreenVertexOutput) -> @location(0) vec4<f32> {\n let depth = depthAt(input.uv);\n if (depth >= 1.0) { return vec4<f32>(0.0); }\n let normalSize = vec2<i32>(textureDimensions(normalRoughnessTexture));\n let normalPixel = clamp(vec2<i32>(input.uv * vec2<f32>(normalSize)), vec2<i32>(0), normalSize - vec2<i32>(1));\n let material = textureLoad(normalRoughnessTexture, normalPixel, 0);\n let encodedNormal = normalize(material.rgb * 2.0 - vec3<f32>(1.0));\n let normal = ${t};\n let roughness = clamp(material.a, 0.0, 1.0);\n let maxRoughness = fullscreenUniforms[12].z;\n let reflectivity = 1.0 - roughness;\n if (roughness >= maxRoughness || reflectivity <= 0.0) { return vec4<f32>(0.0); }\n let origin = viewPosition(input.uv, depth);\n let incident = normalize(origin);\n let direction = normalize(reflect(incident, normal));\n let maxDistance = fullscreenUniforms[12].x;\n let thickness = fullscreenUniforms[12].y;\n let pixelStride = fullscreenUniforms[12].w;\n let near = fullscreenUniforms[13].x;\n let resolutionScale = fullscreenUniforms[13].z;\n let perspective = fullscreenUniforms[13].w > 0.5;\n let incidence = max(dot(-incident, normal), 0.001);\n let rayLength = maxDistance / incidence;\n var endpoint = origin + direction * rayLength;\n if (perspective && endpoint.z > -near && direction.z > 0.0) {\n endpoint = origin + direction * ((-near - origin.z) / direction.z);\n }\n let traceSize = vec2<f32>(textureDimensions(sceneDepthTexture)) * resolutionScale;\n let startPixel = input.position.xy;\n let endPixel = projectUv(endpoint) * traceSize;\n let pixelDelta = endPixel - startPixel;\n let totalSteps = max(abs(pixelDelta.x), abs(pixelDelta.y));\n if (totalSteps < 1.0) { return vec4<f32>(0.0); }\n let pixelStep = pixelDelta / totalSteps;\n let reciprocalOriginZ = 1.0 / origin.z;\n for (var i = 1; i <= STEPS; i += 1) {\n let traversedPixels = f32(i) * pixelStride;\n if (traversedPixels >= totalSteps) { break; }\n let samplePixel = startPixel + traversedPixels * pixelStep;\n if (any(samplePixel < vec2<f32>(0.0)) || any(samplePixel >= traceSize)) { break; }\n let sampleUv = samplePixel / traceSize;\n let sampleDepth = depthAt(sampleUv);\n if (sampleDepth < 1.0) {\n let progress = traversedPixels / totalSteps;\n let rayZ = select(\n mix(origin.z, endpoint.z, progress),\n 1.0 / mix(reciprocalOriginZ, 1.0 / endpoint.z, progress),\n perspective,\n );\n let sceneZ = viewZFromDepth(sampleDepth);\n if (rayZ <= sceneZ) {\n let scene = viewPosition(sampleUv, sampleDepth);\n let neighborUv = sampleUv + vec2<f32>(1.0 / traceSize.x, 0.0);\n let neighbor = viewPosition(neighborUv, sampleDepth);\n let minimumThickness = abs(neighbor.x - scene.x) * 3.0;\n let hitThickness = max(minimumThickness, thickness);\n if (pointToLineDistanceSquared(scene, origin, endpoint) <= hitThickness * hitThickness) {\n let hitPixel = clamp(vec2<i32>(sampleUv * vec2<f32>(normalSize)), vec2<i32>(0), normalSize - vec2<i32>(1));\n let hitEncodedNormal = normalize(textureLoad(normalRoughnessTexture, hitPixel, 0).rgb * 2.0 - vec3<f32>(1.0));\n let hitNormal = ${t.replace("encodedNormal","hitEncodedNormal")};\n if (dot(direction, hitNormal) < 0.0) {\n let hitDistance = pointPlaneDistance(scene, origin, normal);\n if (hitDistance > maxDistance) { break; }\n let distanceFade = ${r};\n let fresnel = (dot(incident, direction) + 1.0) * 0.5;\n let reflected = textureSampleLevel(sceneColorTexture, fullscreenSampler, sampleUv, 0.0).rgb;\n return vec4<f32>(reflected, reflectivity * distanceFade * fresnel);\n }\n }\n }\n }\n }\n return vec4<f32>(0.0);\n}`}(r)}options;name="SSRTracePass";sampler="linear";uniformBufferSize=224;inputs;outputs;fragmentShader;uniforms=new Float32Array(56);projection=new ta;inverseProjection=new ta;updateUniforms=e=>(this.projection.copy(sa).multiply(e.camera.projectionMatrix),this.inverseProjection.copy(this.projection).invert(),this.uniforms.set(this.projection.elements,0),this.uniforms.set(this.inverseProjection.elements,16),this.uniforms.set(e.camera.matrixWorldInverse.elements,32),this.uniforms.set([this.options.maxDistance,this.options.thickness,this.options.maxRoughness,this.options.pixelStride],48),this.uniforms.set([e.camera.near,e.camera.far,this.options.resolutionScale,"isPerspectiveCamera"in e.camera&&e.camera.isPerspectiveCamera?1:0],52),this.uniforms)},ia=class{name;sampler="linear";uniformBufferSize=16;inputs;outputs;uniforms;constructor(e,t,r,n,i,a){this.name=0===i?"SSRBlurHorizontalPass":"SSRBlurVerticalPass",this.inputs={reflection:e,sceneDepth:t,normalRoughness:r},this.outputs=n,this.uniforms=new Float32Array([0===i?1:0,1===i?1:0,a,0])}updateUniforms=()=>this.uniforms;fragmentShader="\nconst MIN_BLUR = 0.02; // Helps reducing artifacts\n@fragment\nfn fsMain(input: FullscreenVertexOutput) -> @location(0) vec4<f32> {\n let reflectionSize = vec2<i32>(textureDimensions(reflectionTexture));\n let depthSize = vec2<i32>(textureDimensions(sceneDepthTexture));\n let p = clamp(vec2<i32>(input.position.xy), vec2<i32>(0), reflectionSize - vec2<i32>(1));\n let fullP = clamp(vec2<i32>(input.uv * vec2<f32>(depthSize)), vec2<i32>(0), depthSize - vec2<i32>(1));\n let centerDepth = textureLoad(sceneDepthTexture, fullP, 0);\n let centerMaterial = textureLoad(normalRoughnessTexture, fullP, 0);\n let centerNormal = normalize(centerMaterial.rgb * 2.0 - vec3<f32>(1.0));\n let blurAmount = smoothstep(0.03, 0.75, centerMaterial.a);\n // A tiny base radius antialiases trace silhouettes on perfect mirrors. The\n // outer Gaussian tap reaches blurRadius pixels on a fully rough receiver.\n let radiusPixels = mix(0.75, fullscreenUniforms[0].z, max(MIN_BLUR, blurAmount));\n let axis = fullscreenUniforms[0].xy;\n let tapSpacing = radiusPixels / 4.0;\n var premultiplied = vec3<f32>(0.0);\n var alphaSum = 0.0;\n var weightSum = 0.0;\n for (var i = -4; i <= 4; i += 1) {\n let fi = f32(i);\n let sampleUv = clamp(\n input.uv + axis * fi * tapSpacing / vec2<f32>(reflectionSize),\n vec2<f32>(0.0),\n vec2<f32>(1.0),\n );\n let sampleFullP = clamp(vec2<i32>(sampleUv * vec2<f32>(depthSize)), vec2<i32>(0), depthSize - vec2<i32>(1));\n let sampleDepth = textureLoad(sceneDepthTexture, sampleFullP, 0);\n let sampleNormal = normalize(textureLoad(normalRoughnessTexture, sampleFullP, 0).rgb * 2.0 - vec3<f32>(1.0));\n let geometryWeight = select(\n exp(-abs(sampleDepth - centerDepth) * 350.0) * pow(max(dot(centerNormal, sampleNormal), 0.0), 16.0),\n 1.0,\n i == 0,\n );\n let reflected = textureSampleLevel(reflectionTexture, fullscreenSampler, sampleUv, 0.0);\n let gaussianWeight = exp(-0.5 * fi * fi / 4.0);\n let weight = geometryWeight * gaussianWeight;\n premultiplied += reflected.rgb * reflected.a * weight;\n alphaSum += reflected.a * weight;\n weightSum += weight;\n }\n let alpha = alphaSum / max(weightSum, 0.0001);\n let color = select(vec3<f32>(0.0), premultiplied / max(alphaSum, 0.0001), alphaSum > 0.0001);\n return vec4<f32>(color, alpha);\n}"},aa=class{name="SSRCompositePass";sampler="linear";uniformBufferSize=16;inputs;outputs;uniforms;constructor(e,t,r,n){this.inputs={sceneColor:e,reflection:t},this.outputs=r,this.uniforms=new Float32Array([n,0,0,0])}updateUniforms=()=>this.uniforms;fragmentShader="\n@fragment\nfn fsMain(input: FullscreenVertexOutput) -> @location(0) vec4<f32> {\n let color = textureLoad(sceneColorTexture, vec2<i32>(input.position.xy), 0);\n let reflection = textureSampleLevel(reflectionTexture, fullscreenSampler, input.uv, 0.0);\n let reflectionWeight = clamp(reflection.a * fullscreenUniforms[0].x, 0.0, 1.0);\n return vec4<f32>(mix(color.rgb, reflection.rgb, reflectionWeight), color.a);\n}"};var sa=(new ta).set(1,0,0,0,0,1,0,0,0,0,.5,.5,0,0,0,1);function oa(e,t,r){return Math.min(r,Math.max(t,e))}import{Matrix4 as la,Vector2 as ca}from"three";var ua=(new la).set(1,0,0,0,0,1,0,0,0,0,.5,.5,0,0,0,1),da=class{renderScale;sampleCount;minCurrentWeight;motionWeightScale;depthThreshold;relativeDepthThreshold;targetPrefix;writeIndex=0;historyValid=!1;frameIndex=0;renderWidth=1;renderHeight=1;outputWidth=1;outputHeight=1;jitter=new ca;unjitteredProjection=new la;previousJitterUv=new ca;currentJitterUv=new ca;previousViewProjection=new la;resolvePasses=new Map;constructor(e={}){this.renderScale=fa(e.renderScale??1,.25,1),this.sampleCount=Math.max(1,Math.floor(e.sampleCount??32)),this.minCurrentWeight=fa(e.minCurrentWeight??.06,0,1),this.motionWeightScale=Math.max(.001,e.motionWeightScale??24),this.depthThreshold=Math.max(0,e.depthThreshold??.001),this.relativeDepthThreshold=Math.max(0,e.relativeDepthThreshold??.002),this.targetPrefix=e.targetPrefix??"taa"}prepareCamera(e,t,r){this.setSize(t,r),e.updateProjectionMatrix(),this.unjitteredProjection.copy(e.projectionMatrix),this.jitter.set(pa(this.frameIndex%this.sampleCount+1,2)-.5,pa(this.frameIndex%this.sampleCount+1,3)-.5),this.currentJitterUv.set(this.jitter.x/this.renderWidth,-this.jitter.y/this.renderHeight),e.projectionMatrix.elements[8]-=2*this.jitter.x/this.renderWidth,e.projectionMatrix.elements[9]-=2*this.jitter.y/this.renderHeight,e.projectionMatrixInverse?.copy(e.projectionMatrix).invert()}finishCamera(e){e.projectionMatrix.copy(this.unjitteredProjection),e.projectionMatrixInverse?.copy(e.projectionMatrix).invert()}addPass(e,t,r=e.mainDepth){const n=e.createColorTarget(`${this.targetPrefix}HistoryColorA`,{format:"rgba16float",resolution:"presentation"}),i=e.createColorTarget(`${this.targetPrefix}HistoryColorB`,{format:"rgba16float",resolution:"presentation"}),a=e.createColorTarget(`${this.targetPrefix}HistoryDepthA`,{format:"r32float",resolution:"presentation"}),s=e.createColorTarget(`${this.targetPrefix}HistoryDepthB`,{format:"r32float",resolution:"presentation"}),o=0===this.writeIndex?i:n,l=0===this.writeIndex?n:i,c=0===this.writeIndex?s:a,u=0===this.writeIndex?a:s,d=`${t}:${r}:${o}:${c}:${l}:${u}`;let h=this.resolvePasses.get(d);return h||(h=new ha(t,r,o,c,l,u,this),this.resolvePasses.set(d,h)),e.addFullscreenPass(h),this.writeIndex=1-this.writeIndex,this.frameIndex+=1,l}reset(){this.frameIndex=0,this.writeIndex=0,this.historyValid=!1,this.previousViewProjection.identity(),this.currentJitterUv.set(0,0),this.previousJitterUv.set(0,0)}setSize(e,t){const r=Math.max(1,Math.floor(e)),n=Math.max(1,Math.floor(t));r===this.outputWidth&&n===this.outputHeight||(this.outputWidth=r,this.outputHeight=n,this.renderWidth=Math.max(1,Math.floor(r*this.renderScale)),this.renderHeight=Math.max(1,Math.floor(n*this.renderScale)),this.reset())}updateResolveUniforms(e,t,r,n){t.copy(ua).multiply(n.camera.projectionMatrix).multiply(n.camera.matrixWorldInverse),r.copy(t).invert(),e.set(r.elements,0),e.set((this.historyValid?this.previousViewProjection:t).elements,16),e.set([n.presentationWidth,n.presentationHeight,this.historyValid?1:0,0],32),e.set([this.currentJitterUv.x,this.currentJitterUv.y,this.previousJitterUv.x,this.previousJitterUv.y],36),e.set([this.minCurrentWeight,this.motionWeightScale,this.depthThreshold,this.relativeDepthThreshold],40),this.previousViewProjection.copy(t),this.previousJitterUv.copy(this.currentJitterUv),this.historyValid=!0}},ha=class{constructor(e,t,r,n,i,a,s){this.state=s,this.inputs={currentColor:e,currentDepth:t,historyColor:r,historyDepth:n},this.outputs=[i,a]}state;name="TemporalAAResolvePass";sampler="nearest";uniformBufferSize=176;inputs;outputs;uniforms=new Float32Array(this.uniformBufferSize/4);currentViewProjection=new la;currentViewProjectionInverse=new la;updateUniforms=e=>(this.state.updateResolveUniforms(this.uniforms,this.currentViewProjection,this.currentViewProjectionInverse,e),this.uniforms);fragmentShader="\nstruct TAAOutput {\n @location(0) color: vec4<f32>,\n @location(1) depth: vec4<f32>,\n};\n\nfn currentViewProjectionInverse() -> mat4x4<f32> {\n return mat4x4<f32>(fullscreenUniforms[0], fullscreenUniforms[1], fullscreenUniforms[2], fullscreenUniforms[3]);\n}\n\nfn previousViewProjection() -> mat4x4<f32> {\n return mat4x4<f32>(fullscreenUniforms[4], fullscreenUniforms[5], fullscreenUniforms[6], fullscreenUniforms[7]);\n}\n\nfn loadCurrentDepth(pixel: vec2<i32>, size: vec2<i32>) -> f32 {\n return textureLoad(currentDepthTexture, clamp(pixel, vec2<i32>(0), size - vec2<i32>(1)), 0);\n}\n\nfn loadCurrentColor(pixel: vec2<i32>, size: vec2<i32>) -> vec3<f32> {\n return textureLoad(currentColorTexture, clamp(pixel, vec2<i32>(0), size - vec2<i32>(1)), 0).rgb;\n}\n\nfn sampleCurrentColorBilinear(uv: vec2<f32>) -> vec3<f32> {\n let size = vec2<i32>(textureDimensions(currentColorTexture));\n let position = uv * vec2<f32>(size) - 0.5;\n let base = vec2<i32>(floor(position));\n let fraction = fract(position);\n let c00 = loadCurrentColor(base, size);\n let c10 = loadCurrentColor(base + vec2<i32>(1, 0), size);\n let c01 = loadCurrentColor(base + vec2<i32>(0, 1), size);\n let c11 = loadCurrentColor(base + vec2<i32>(1, 1), size);\n return mix(mix(c00, c10, fraction.x), mix(c01, c11, fraction.x), fraction.y);\n}\n\nfn sampleHistoryColorBilinear(uv: vec2<f32>) -> vec3<f32> {\n let size = vec2<i32>(textureDimensions(historyColorTexture));\n let position = uv * vec2<f32>(size) - 0.5;\n let base = vec2<i32>(floor(position));\n let fraction = fract(position);\n let maximum = size - vec2<i32>(1);\n let c00 = textureLoad(historyColorTexture, clamp(base, vec2<i32>(0), maximum), 0).rgb;\n let c10 = textureLoad(historyColorTexture, clamp(base + vec2<i32>(1, 0), vec2<i32>(0), maximum), 0).rgb;\n let c01 = textureLoad(historyColorTexture, clamp(base + vec2<i32>(0, 1), vec2<i32>(0), maximum), 0).rgb;\n let c11 = textureLoad(historyColorTexture, clamp(base + vec2<i32>(1, 1), vec2<i32>(0), maximum), 0).rgb;\n return mix(mix(c00, c10, fraction.x), mix(c01, c11, fraction.x), fraction.y);\n}\n\nfn sampleHistoryDepthNearest(uv: vec2<f32>) -> f32 {\n let size = vec2<i32>(textureDimensions(historyDepthTexture));\n let pixel = clamp(vec2<i32>(uv * vec2<f32>(size)), vec2<i32>(0), size - vec2<i32>(1));\n return textureLoad(historyDepthTexture, pixel, 0).r;\n}\n\nfn historyUvFor(currentUv: vec2<f32>, depth: f32) -> vec2<f32> {\n let clip = vec4<f32>(currentUv.x * 2.0 - 1.0, 1.0 - currentUv.y * 2.0, depth, 1.0);\n let worldH = currentViewProjectionInverse() * clip;\n let world = worldH / worldH.w;\n let previousClip = previousViewProjection() * world;\n let previousNdc = previousClip.xy / previousClip.w;\n let previousRasterUv = vec2<f32>(previousNdc.x * 0.5 + 0.5, 0.5 - previousNdc.y * 0.5);\n return previousRasterUv - fullscreenUniforms[9].zw;\n}\n\n@fragment\nfn fsMain(input: FullscreenVertexOutput) -> TAAOutput {\n let renderSize = vec2<i32>(textureDimensions(currentDepthTexture));\n let outputSize = vec2<i32>(fullscreenUniforms[8].xy);\n let centerPixel = clamp(vec2<i32>(input.position.xy), vec2<i32>(0), outputSize - vec2<i32>(1));\n let centerUv = (vec2<f32>(centerPixel) + 0.5) / vec2<f32>(outputSize);\n let currentJitterUv = fullscreenUniforms[9].xy;\n let currentSampleUv = centerUv + currentJitterUv;\n let currentSamplePixel = clamp(vec2<i32>(currentSampleUv * vec2<f32>(renderSize)), vec2<i32>(0), renderSize - vec2<i32>(1));\n let centerDepth = loadCurrentDepth(currentSamplePixel, renderSize);\n\n var closestDepth = centerDepth;\n var closestPixel = currentSamplePixel;\n var mean = vec3<f32>(0.0);\n var meanSquared = vec3<f32>(0.0);\n for (var y = -1; y <= 1; y += 1) {\n for (var x = -1; x <= 1; x += 1) {\n let samplePixel = clamp(currentSamplePixel + vec2<i32>(x, y), vec2<i32>(0), renderSize - vec2<i32>(1));\n let sampleDepth = loadCurrentDepth(samplePixel, renderSize);\n if (sampleDepth < closestDepth) {\n closestDepth = sampleDepth;\n closestPixel = samplePixel;\n }\n let sampleColor = sampleCurrentColorBilinear(currentSampleUv + vec2<f32>(f32(x), f32(y)) / vec2<f32>(renderSize));\n mean += sampleColor;\n meanSquared += sampleColor * sampleColor;\n }\n }\n mean /= 9.0;\n let sigma = sqrt(max(meanSquared / 9.0 - mean * mean, vec3<f32>(0.0)));\n\n let currentColor = sampleCurrentColorBilinear(currentSampleUv);\n let closestUv = (vec2<f32>(closestPixel) + 0.5) / vec2<f32>(renderSize);\n let closestHistoryUv = historyUvFor(closestUv, closestDepth);\n let closestOutputUv = closestUv - currentJitterUv;\n let historyUv = centerUv - (closestOutputUv - closestHistoryUv);\n let validUv = all(historyUv >= vec2<f32>(0.0)) && all(historyUv <= vec2<f32>(1.0));\n let historyWasValid = fullscreenUniforms[8].z > 0.5;\n\n var validHistory = historyWasValid && validUv && centerDepth < 1.0;\n var historyColor = currentColor;\n if (validHistory) {\n historyColor = sampleHistoryColorBilinear(historyUv);\n let previousDepth = sampleHistoryDepthNearest(historyUv);\n let expectedPreviousDepth = previousViewProjection() *\n (currentViewProjectionInverse() * vec4<f32>(currentSampleUv.x * 2.0 - 1.0, 1.0 - currentSampleUv.y * 2.0, centerDepth, 1.0));\n let expectedDepth = expectedPreviousDepth.z / expectedPreviousDepth.w;\n let depthThreshold = fullscreenUniforms[10].z;\n let relativeDepthThreshold = fullscreenUniforms[10].w;\n validHistory = abs(previousDepth - expectedDepth) < max(depthThreshold, abs(expectedDepth) * relativeDepthThreshold);\n }\n\n let clippedHistory = clamp(historyColor, mean - sigma, mean + sigma);\n let motionPixels = length((centerUv - historyUv) * vec2<f32>(outputSize));\n let minCurrentWeight = fullscreenUniforms[10].x;\n let currentWeight = clamp(minCurrentWeight + motionPixels / fullscreenUniforms[10].y, minCurrentWeight, 1.0);\n let resolved = select(currentColor, mix(clippedHistory, currentColor, currentWeight), validHistory);\n\n var output: TAAOutput;\n output.color = vec4<f32>(resolved, 1.0);\n output.depth = vec4<f32>(centerDepth, 0.0, 0.0, 1.0);\n return output;\n}\n"};function pa(e,t){let r=1,n=0;for(;e>0;)r/=t,n+=r*(e%t),e=Math.floor(e/t);return n}function fa(e,t,r){return Math.min(r,Math.max(t,e))}var ma=class{contrastThreshold;relativeThreshold;subpixelBlending;targetPrefix;passes=new Map;constructor(e={}){this.contrastThreshold=Math.max(0,e.contrastThreshold??.0312),this.relativeThreshold=Math.max(0,e.relativeThreshold??.063),this.subpixelBlending=xa(e.subpixelBlending??.75,0,1),this.targetPrefix=e.targetPrefix??"fxaa"}addPass(e,t,r={}){const n=r.output??e.createColorTarget(`${this.targetPrefix}Color`,{format:"rgba16float",resolution:"presentation"}),i=`${t}:${n}`;let a=this.passes.get(i);return a||(a=new ga(t,n,this),this.passes.set(i,a)),e.addFullscreenPass(a),n}},ga=class{constructor(e,t,r){this.state=r,this.inputs={source:e},this.outputs=t}state;name="FXAAPass";sampler="linear";uniformBufferSize=16;inputs;outputs;uniforms=new Float32Array(4);updateUniforms=()=>(this.uniforms.set([Math.max(0,this.state.contrastThreshold),Math.max(0,this.state.relativeThreshold),xa(this.state.subpixelBlending,0,1),0]),this.uniforms);fragmentShader="\nconst EDGE_STEP_COUNT: i32 = 6;\nconst EDGE_GUESS: f32 = 8.0;\nconst EDGE_STEPS = array<f32, 6>(1.0, 1.5, 2.0, 2.0, 2.0, 4.0);\n\nstruct LuminanceData {\n m: f32,\n n: f32,\n e: f32,\n s: f32,\n w: f32,\n ne: f32,\n nw: f32,\n se: f32,\n sw: f32,\n highest: f32,\n lowest: f32,\n contrast: f32,\n};\n\nstruct EdgeData {\n isHorizontal: bool,\n pixelStep: f32,\n oppositeLuminance: f32,\n gradient: f32,\n};\n\nfn sampleColor(uv: vec2<f32>) -> vec4<f32> {\n return textureSampleLevel(sourceTexture, fullscreenSampler, uv, 0.0);\n}\n\nfn sampleLuminance(uv: vec2<f32>) -> f32 {\n // The renderer's intermediate buffers are linear. FXAA thresholds are tuned\n // for perceptual luminance, so sqrt is a cheap gamma approximation here.\n return sqrt(max(dot(sampleColor(uv).rgb, vec3<f32>(0.299, 0.587, 0.114)), 0.0));\n}\n\nfn offsetLuminance(uv: vec2<f32>, texel: vec2<f32>, offset: vec2<f32>) -> f32 {\n return sampleLuminance(uv + texel * offset);\n}\n\nfn sampleNeighborhood(uv: vec2<f32>, texel: vec2<f32>) -> LuminanceData {\n var l: LuminanceData;\n l.m = sampleLuminance(uv);\n l.n = offsetLuminance(uv, texel, vec2<f32>(0.0, -1.0));\n l.e = offsetLuminance(uv, texel, vec2<f32>(1.0, 0.0));\n l.s = offsetLuminance(uv, texel, vec2<f32>(0.0, 1.0));\n l.w = offsetLuminance(uv, texel, vec2<f32>(-1.0, 0.0));\n l.ne = offsetLuminance(uv, texel, vec2<f32>(1.0, -1.0));\n l.nw = offsetLuminance(uv, texel, vec2<f32>(-1.0, -1.0));\n l.se = offsetLuminance(uv, texel, vec2<f32>(1.0, 1.0));\n l.sw = offsetLuminance(uv, texel, vec2<f32>(-1.0, 1.0));\n l.highest = max(max(max(max(l.n, l.e), l.s), l.w), l.m);\n l.lowest = min(min(min(min(l.n, l.e), l.s), l.w), l.m);\n l.contrast = l.highest - l.lowest;\n return l;\n}\n\nfn pixelBlendFactor(l: LuminanceData) -> f32 {\n var filterAmount = 2.0 * (l.n + l.e + l.s + l.w);\n filterAmount += l.ne + l.nw + l.se + l.sw;\n filterAmount = abs(filterAmount / 12.0 - l.m);\n filterAmount = clamp(filterAmount / max(l.contrast, 1e-5), 0.0, 1.0);\n let blend = smoothstep(0.0, 1.0, filterAmount);\n return blend * blend * fullscreenUniforms[0].z;\n}\n\nfn determineEdge(texel: vec2<f32>, l: LuminanceData) -> EdgeData {\n let horizontal =\n abs(l.n + l.s - 2.0 * l.m) * 2.0 +\n abs(l.ne + l.se - 2.0 * l.e) +\n abs(l.nw + l.sw - 2.0 * l.w);\n let vertical =\n abs(l.e + l.w - 2.0 * l.m) * 2.0 +\n abs(l.ne + l.nw - 2.0 * l.n) +\n abs(l.se + l.sw - 2.0 * l.s);\n\n var edge: EdgeData;\n edge.isHorizontal = horizontal >= vertical;\n let positiveLuminance = select(l.e, l.n, edge.isHorizontal);\n let negativeLuminance = select(l.w, l.s, edge.isHorizontal);\n let positiveGradient = abs(positiveLuminance - l.m);\n let negativeGradient = abs(negativeLuminance - l.m);\n edge.pixelStep = select(texel.x, texel.y, edge.isHorizontal);\n if (positiveGradient < negativeGradient) {\n edge.pixelStep = -edge.pixelStep;\n edge.oppositeLuminance = negativeLuminance;\n edge.gradient = negativeGradient;\n } else {\n edge.oppositeLuminance = positiveLuminance;\n edge.gradient = positiveGradient;\n }\n return edge;\n}\n\nfn edgeBlendFactor(uv: vec2<f32>, texel: vec2<f32>, l: LuminanceData, edge: EdgeData) -> f32 {\n var edgeUv = uv;\n var edgeStep: vec2<f32>;\n if (edge.isHorizontal) {\n edgeUv.y += edge.pixelStep * 0.5;\n edgeStep = vec2<f32>(texel.x, 0.0);\n } else {\n edgeUv.x += edge.pixelStep * 0.5;\n edgeStep = vec2<f32>(0.0, texel.y);\n }\n\n let edgeLuminance = (l.m + edge.oppositeLuminance) * 0.5;\n let gradientThreshold = edge.gradient * 0.25;\n var positiveUv = edgeUv + edgeStep * EDGE_STEPS[0];\n var positiveDelta = sampleLuminance(positiveUv) - edgeLuminance;\n var positiveAtEnd = abs(positiveDelta) >= gradientThreshold;\n for (var i = 1; i < EDGE_STEP_COUNT; i += 1) {\n if (!positiveAtEnd) {\n positiveUv += edgeStep * EDGE_STEPS[i];\n positiveDelta = sampleLuminance(positiveUv) - edgeLuminance;\n positiveAtEnd = abs(positiveDelta) >= gradientThreshold;\n }\n }\n if (!positiveAtEnd) {\n positiveUv += edgeStep * EDGE_GUESS;\n }\n\n var negativeUv = edgeUv - edgeStep * EDGE_STEPS[0];\n var negativeDelta = sampleLuminance(negativeUv) - edgeLuminance;\n var negativeAtEnd = abs(negativeDelta) >= gradientThreshold;\n for (var i = 1; i < EDGE_STEP_COUNT; i += 1) {\n if (!negativeAtEnd) {\n negativeUv -= edgeStep * EDGE_STEPS[i];\n negativeDelta = sampleLuminance(negativeUv) - edgeLuminance;\n negativeAtEnd = abs(negativeDelta) >= gradientThreshold;\n }\n }\n if (!negativeAtEnd) {\n negativeUv -= edgeStep * EDGE_GUESS;\n }\n\n let positiveDistance = select(positiveUv.y - uv.y, positiveUv.x - uv.x, edge.isHorizontal);\n let negativeDistance = select(uv.y - negativeUv.y, uv.x - negativeUv.x, edge.isHorizontal);\n var shortestDistance = negativeDistance;\n var deltaSign = negativeDelta >= 0.0;\n if (positiveDistance <= negativeDistance) {\n shortestDistance = positiveDistance;\n deltaSign = positiveDelta >= 0.0;\n }\n if (deltaSign == (l.m - edgeLuminance >= 0.0)) {\n return 0.0;\n }\n return 0.5 - shortestDistance / max(positiveDistance + negativeDistance, 1e-5);\n}\n\n@fragment\nfn fsMain(input: FullscreenVertexOutput) -> @location(0) vec4<f32> {\n let texel = 1.0 / vec2<f32>(textureDimensions(sourceTexture));\n let luminance = sampleNeighborhood(input.uv, texel);\n let threshold = max(fullscreenUniforms[0].x, fullscreenUniforms[0].y * luminance.highest);\n if (luminance.contrast < threshold) {\n return sampleColor(input.uv);\n }\n\n let edge = determineEdge(texel, luminance);\n let blend = max(pixelBlendFactor(luminance), edgeBlendFactor(input.uv, texel, luminance, edge));\n var sampleUv = input.uv;\n if (edge.isHorizontal) {\n sampleUv.y += edge.pixelStep * blend;\n } else {\n sampleUv.x += edge.pixelStep * blend;\n }\n return sampleColor(sampleUv);\n}\n"};function xa(e,t,r){return Math.min(r,Math.max(t,e))}var va=class{strength;threshold;knee;radius;levels;targetPrefix;passes=new Map;constructor(e={}){var t,r,n;this.strength=Math.max(0,e.strength??.9),this.threshold=Math.max(0,e.threshold??1),this.knee=Math.max(1e-4,e.knee??.1),this.radius=Sa(e.radius??.2,0,1),this.levels=(t=e.levels??5,r=1,n=5,Math.floor(Sa(t,r,n))),this.targetPrefix=e.targetPrefix??"bloom"}addPass(e,t,r={}){const n=[];let i=t;for(let t=0;t<this.levels;t+=1){const r=1/2**(t+1),a=e.createColorTarget(`${this.targetPrefix}Horizontal${t}`,{format:"rgba16float",scale:r}),s=e.createColorTarget(`${this.targetPrefix}Vertical${t}`,{format:"rgba16float",scale:r}),o=i,l=`h:${t}:${o}:${a}`;let c=this.passes.get(l);c||(c=0===t?new wa(o,a,this):new ba(`BloomDownsampleHorizontal${t}`,o,a,!0,t),this.passes.set(l,c)),e.addFullscreenPass(c);const u=`v:${t}:${a}:${s}`;let d=this.passes.get(u);d||(d=new ba(`BloomVertical${t}`,a,s,!1,t),this.passes.set(u,d)),e.addFullscreenPass(d),n.push(s),i=s}const a=r.output??e.createColorTarget(`${this.targetPrefix}Color`,{format:"rgba16float"}),s=Object.fromEntries(n.map((e,t)=>[`blur${t}`,e])),o=`composite:${t}:${n.join(":")}:${a}`;let l=this.passes.get(o);return l||(l=new ya(t,s,a,this,this.levels),this.passes.set(o,l)),e.addFullscreenPass(l),a}},wa=class{constructor(e,t,r){this.state=r,this.inputs={source:e},this.outputs=t}state;name="BloomThresholdHorizontal";sampler="linear";uniformBufferSize=16;inputs;outputs;uniforms=new Float32Array(4);updateUniforms=()=>(this.uniforms.set([this.state.threshold,this.state.knee,0,0]),this.uniforms);fragmentShader="\nfn bright(color: vec3<f32>) -> vec3<f32> {\n let brightness = dot(color, vec3<f32>(0.2126, 0.7152, 0.0722));\n let threshold = fullscreenUniforms[0].x;\n let knee = fullscreenUniforms[0].y;\n let soft = clamp(brightness - threshold + knee, 0.0, 2.0 * knee);\n let contribution = max(brightness - threshold, soft * soft / (4.0 * knee));\n return color * contribution / max(brightness, 0.0001);\n}\n\n@fragment\nfn fsMain(input: FullscreenVertexOutput) -> @location(0) vec4<f32> {\n let texel = 1.0 / vec2<f32>(textureDimensions(sourceTexture));\n let center = bright(textureSample(sourceTexture, fullscreenSampler, input.uv).rgb) * 0.227027;\n let a = bright(textureSample(sourceTexture, fullscreenSampler, input.uv + vec2<f32>(1.384615 * texel.x, 0.0)).rgb);\n let b = bright(textureSample(sourceTexture, fullscreenSampler, input.uv - vec2<f32>(1.384615 * texel.x, 0.0)).rgb);\n let c = bright(textureSample(sourceTexture, fullscreenSampler, input.uv + vec2<f32>(3.230769 * texel.x, 0.0)).rgb);\n let d = bright(textureSample(sourceTexture, fullscreenSampler, input.uv - vec2<f32>(3.230769 * texel.x, 0.0)).rgb);\n return vec4<f32>(center + (a + b) * 0.316216 + (c + d) * 0.070270, 1.0);\n}"},ba=class{constructor(e,t,r,n,i){this.name=e,this.inputs={source:t},this.outputs=r;const a=n?"vec2<f32>(texel.x, 0.0)":"vec2<f32>(0.0, texel.y)",s=(1+.35*i).toFixed(2);this.fragmentShader=`\n@fragment\nfn fsMain(input: FullscreenVertexOutput) -> @location(0) vec4<f32> {\n let texel = 1.0 / vec2<f32>(textureDimensions(sourceTexture));\n let axis = ${a} * ${s};\n var color = textureSample(sourceTexture, fullscreenSampler, input.uv).rgb * 0.227027;\n color += textureSample(sourceTexture, fullscreenSampler, input.uv + axis * 1.384615).rgb * 0.316216;\n color += textureSample(sourceTexture, fullscreenSampler, input.uv - axis * 1.384615).rgb * 0.316216;\n color += textureSample(sourceTexture, fullscreenSampler, input.uv + axis * 3.230769).rgb * 0.070270;\n color += textureSample(sourceTexture, fullscreenSampler, input.uv - axis * 3.230769).rgb * 0.070270;\n return vec4<f32>(color, 1.0);\n}`}name;sampler="linear";inputs;outputs;fragmentShader},ya=class{constructor(e,t,r,n,i){this.state=n,this.inputs={source:e,...t},this.outputs=r;const a=[1,.8,.6,.4,.2],s=Array.from({length:i},(e,t)=>`bloom += textureSample(blur${t}Texture, fullscreenSampler, input.uv).rgb * mix(${a[t].toFixed(1)}, ${(1.2-a[t]).toFixed(1)}, radius);`).join("\n ");this.fragmentShader=`\n@fragment\nfn fsMain(input: FullscreenVertexOutput) -> @location(0) vec4<f32> {\n let scene = textureSample(sourceTexture, fullscreenSampler, input.uv);\n let radius = fullscreenUniforms[0].y;\n var bloom = vec3<f32>(0.0);\n ${s}\n return vec4<f32>(scene.rgb + bloom * fullscreenUniforms[0].x, scene.a);\n}`}state;name="BloomComposite";sampler="linear";uniformBufferSize=32;inputs;outputs;uniforms=new Float32Array(8);updateUniforms=()=>(this.uniforms.set([this.state.strength,Sa(this.state.radius,0,1),0,0]),this.uniforms);fragmentShader};function Sa(e,t,r){return Math.min(r,Math.max(t,e))}var Ca=[1,1,1],Pa=[0,0,0],Ma=class{options;passes=new Map;targetPrefix;constructor(e={}){this.options=e,this.targetPrefix=e.targetPrefix??"colorGrading"}addPass(e,t){const r=e.createColorTarget(`${this.targetPrefix}Color`,{format:"rgba16float"}),n=`${t}:${r}`;let i=this.passes.get(n);return i||(i=new Ba(t,r,this.options),this.passes.set(n,i)),e.addFullscreenPass(i),r}},Ba=class{constructor(e,t,r){this.state=r,this.inputs={source:e},this.outputs=t}state;name="ColorGrading";sampler="linear";uniformBufferSize=384;inputs;outputs;uniforms=new Float32Array(this.uniformBufferSize/4);updateUniforms=()=>{const e=[],t=(t,r)=>e.push(...t??r,0),r=e=>{t(e?.saturation,Ca),t(e?.contrast,Ca),t(e?.gamma,Ca),t(e?.gain,Ca),t(e?.offset,Pa)};return t(this.state.whiteBalance,Ca),t(this.state.tint,Ca),r(this.state),r(this.state.shadows),r(this.state.midtones),r(this.state.highlights),e.push(this.state.exposure??1,{none:0,linear:1,reinhard:2,cineon:3,aces:4,agx:5,neutral:6}[this.state.toneMapping??"none"],Math.max(0,this.state.vignetteIntensity??0),Math.min(1,Math.max(0,this.state.tintIntensity??0)),this.state.shadowsMax??.09,this.state.highlightsMin??.5,!1===this.state.enabled?0:1,0),this.uniforms.fill(0),this.uniforms.set(e),this.uniforms};fragmentShader="\nfn grade(color: vec3<f32>, s: vec3<f32>, c: vec3<f32>, g: vec3<f32>, gain: vec3<f32>, offset: vec3<f32>) -> vec3<f32> {\n let luma = dot(color, vec3<f32>(0.2126, 0.7152, 0.0722));\n var result = mix(vec3<f32>(luma), color, s);\n result = (result - vec3<f32>(0.18)) * c + vec3<f32>(0.18);\n result = pow(max(result, vec3<f32>(0.0)), vec3<f32>(1.0) / max(g, vec3<f32>(0.0001)));\n return max(result * gain + offset, vec3<f32>(0.0));\n}\nfn aces(x: vec3<f32>) -> vec3<f32> { return clamp((x * (2.51*x + vec3<f32>(0.03))) / (x * (2.43*x + vec3<f32>(0.59)) + vec3<f32>(0.14)), vec3<f32>(0.0), vec3<f32>(1.0)); }\nfn tonemap(x: vec3<f32>, mode: i32) -> vec3<f32> {\n if (mode == 1) { return clamp(x, vec3<f32>(0.0), vec3<f32>(1.0)); }\n if (mode == 2) { return x / (vec3<f32>(1.0) + x); }\n if (mode == 3) { let y=max(vec3<f32>(0.0),x-vec3<f32>(0.004)); return pow((y*(6.2*y+vec3<f32>(0.5)))/(y*(6.2*y+vec3<f32>(1.7))+vec3<f32>(0.06)),vec3<f32>(2.2)); }\n if (mode == 4) { return aces(x); }\n if (mode == 5) { return clamp((x * (x + vec3<f32>(0.0245786)) - vec3<f32>(0.000090537)) / (x * (0.983729*x + vec3<f32>(0.432951)) + vec3<f32>(0.238081)), vec3<f32>(0.0), vec3<f32>(1.0)); }\n if (mode == 6) { return clamp(x / (max(max(x.r,x.g),x.b) + 1.0), vec3<f32>(0.0), vec3<f32>(1.0)); }\n return x;\n}\n@fragment\nfn fsMain(input: FullscreenVertexOutput) -> @location(0) vec4<f32> {\n let source = textureSample(sourceTexture, fullscreenSampler, input.uv);\n if (fullscreenUniforms[23].z < 0.5) { return source; }\n var color = source.rgb * fullscreenUniforms[0].xyz;\n color = mix(color, color * fullscreenUniforms[1].xyz, fullscreenUniforms[22].w);\n let lum = clamp(dot(color, vec3<f32>(0.2126,0.7152,0.0722)), 0.0, 1.0);\n let shadowLimit = clamp(fullscreenUniforms[23].x, 0.0, 0.98);\n let highlightLimit = clamp(max(fullscreenUniforms[23].y, shadowLimit + 0.02), 0.02, 1.0);\n let sw = 1.0 - smoothstep(shadowLimit, min(1.0, shadowLimit + 0.05), lum);\n let hw = smoothstep(max(0.0, highlightLimit - 0.05), highlightLimit, lum);\n let mw = clamp(1.0-sw-hw, 0.0, 1.0);\n var s=fullscreenUniforms[2].xyz; var c=fullscreenUniforms[3].xyz; var g=fullscreenUniforms[4].xyz; var gn=fullscreenUniforms[5].xyz; var o=fullscreenUniforms[6].xyz;\n s*=mix(vec3<f32>(1),fullscreenUniforms[7].xyz,sw)*mix(vec3<f32>(1),fullscreenUniforms[12].xyz,mw)*mix(vec3<f32>(1),fullscreenUniforms[17].xyz,hw);\n c*=mix(vec3<f32>(1),fullscreenUniforms[8].xyz,sw)*mix(vec3<f32>(1),fullscreenUniforms[13].xyz,mw)*mix(vec3<f32>(1),fullscreenUniforms[18].xyz,hw);\n g*=mix(vec3<f32>(1),fullscreenUniforms[9].xyz,sw)*mix(vec3<f32>(1),fullscreenUniforms[14].xyz,mw)*mix(vec3<f32>(1),fullscreenUniforms[19].xyz,hw);\n gn*=mix(vec3<f32>(1),fullscreenUniforms[10].xyz,sw)*mix(vec3<f32>(1),fullscreenUniforms[15].xyz,mw)*mix(vec3<f32>(1),fullscreenUniforms[20].xyz,hw);\n o+=fullscreenUniforms[11].xyz*sw+fullscreenUniforms[16].xyz*mw+fullscreenUniforms[21].xyz*hw;\n color=grade(color,s,c,g,gn,o);\n color=tonemap(color*fullscreenUniforms[22].x,i32(fullscreenUniforms[22].y));\n let d=distance(input.uv,vec2<f32>(0.5));\n color*=smoothstep(0.8,0.1598,d*(fullscreenUniforms[22].z+0.2));\n return vec4<f32>(color,source.a);\n}"};import{Matrix4 as Da}from"three";var Ta=class{options;passes=new Map;targetPrefix;constructor(e={}){this.options=e,this.targetPrefix=e.targetPrefix??"depthOfField"}addPass(e,t,r){const n=e.createColorTarget(`${this.targetPrefix}Color`,{format:"rgba16float"}),i=`${t}:${r}:${n}`;let a=this.passes.get(i);return a||(a=new Ia(t,r,n,this.options),this.passes.set(i,a)),e.addFullscreenPass(a),n}},Ia=class{constructor(e,t,r,n){this.state=n,this.inputs={source:e,sceneDepth:t},this.outputs=r}state;name="DepthOfField";sampler="linear";uniformBufferSize=80;inputs;outputs;uniforms=new Float32Array(20);inverseProjection=new Da;updateUniforms=e=>(this.inverseProjection.copy(Ga).multiply(e.camera.projectionMatrix).invert(),this.uniforms.set(this.inverseProjection.elements,0),this.uniforms.set([this.state.focus??10,this.state.aperture??2e-4,this.state.maxBlur??.01,!1===this.state.enabled?0:1],16),this.uniforms);fragmentShader="\nfn viewDistance(uv:vec2<f32>,depth:f32)->f32 { let clip=vec4<f32>(uv*vec2<f32>(2,-2)+vec2<f32>(-1,1),depth,1); let view=mat4x4<f32>(fullscreenUniforms[0],fullscreenUniforms[1],fullscreenUniforms[2],fullscreenUniforms[3])*clip; return abs(view.z/view.w); }\n@fragment fn fsMain(input:FullscreenVertexOutput)->@location(0) vec4<f32>{\n let center=textureSample(sourceTexture,fullscreenSampler,input.uv); if(fullscreenUniforms[4].w<0.5){return center;}\n let px=vec2<f32>(1)/vec2<f32>(textureDimensions(sourceTexture)); let depth=textureLoad(sceneDepthTexture,vec2<i32>(input.position.xy),0);\n let blur=clamp(abs(viewDistance(input.uv,depth)-fullscreenUniforms[4].x)*fullscreenUniforms[4].y,0,fullscreenUniforms[4].z);\n var color=center.rgb*0.2; color+=textureSample(sourceTexture,fullscreenSampler,input.uv+vec2<f32>( blur,0)*px*400).rgb*0.1; color+=textureSample(sourceTexture,fullscreenSampler,input.uv-vec2<f32>( blur,0)*px*400).rgb*0.1;\n color+=textureSample(sourceTexture,fullscreenSampler,input.uv+vec2<f32>(0, blur)*px*400).rgb*0.1; color+=textureSample(sourceTexture,fullscreenSampler,input.uv-vec2<f32>(0, blur)*px*400).rgb*0.1;\n color+=textureSample(sourceTexture,fullscreenSampler,input.uv+vec2<f32>( blur, blur)*px*280).rgb*0.1; color+=textureSample(sourceTexture,fullscreenSampler,input.uv+vec2<f32>(-blur, blur)*px*280).rgb*0.1; color+=textureSample(sourceTexture,fullscreenSampler,input.uv+vec2<f32>( blur,-blur)*px*280).rgb*0.1; color+=textureSample(sourceTexture,fullscreenSampler,input.uv-vec2<f32>( blur, blur)*px*280).rgb*0.1;\n return vec4<f32>(color,center.a); }"},Ga=(new Da).set(1,0,0,0,0,1,0,0,0,0,.5,.5,0,0,0,1),Ra=class{enabled;visibleEdgeColor;edgeStrength;edgeThickness;selectedObjects=new Set;selectedInstances=[];targetPrefix;maskMaterial;skinnedMaskMaterial;instanceMaskMaterials=new Map;passes=new Map;constructor(e={}){this.enabled=e.enabled??!0,this.visibleEdgeColor=[...e.visibleEdgeColor??[1,1,1]],this.edgeStrength=Math.max(0,e.edgeStrength??5),this.edgeThickness=Math.max(0,e.edgeThickness??1.5),this.targetPrefix=e.targetPrefix??"outline",this.maskMaterial=La(!1),this.skinnedMaskMaterial=La(!0)}setSelectedObjects(e){this.selectedObjects.clear();for(const t of e)this.selectedObjects.add(t)}setSelectedInstances(e){this.selectedInstances.length=0;for(const t of e)Number.isInteger(t.instanceIndex)&&t.instanceIndex>=0&&this.selectedInstances.push(t)}addPass(e,t){if(!this.enabled||0===this.selectedObjects.size&&0===this.selectedInstances.length)return t;const r=e.createColorTarget(`${this.targetPrefix}Mask`,{format:"rgba8unorm"}),n=this.selectedObjects;e.addMaterialPass({name:"OutlineMask",outputs:r,loadDepth:!0,objectFilter:e=>null!==e&&function(e,t){for(let r=e;null!==r;r=r.parent)if(t.has(r))return!0;return!1}(e,n),overrideMaterial:(e,t)=>t?this.skinnedMaskMaterial:this.maskMaterial});for(let t=0;t<this.selectedInstances.length;t+=1){const n=this.selectedInstances[t];let i=this.instanceMaskMaterials.get(n.instanceIndex);i||(i=[La(!1,n.instanceIndex),La(!0,n.instanceIndex)],this.instanceMaskMaterials.set(n.instanceIndex,i)),e.addMaterialPass({name:`OutlineInstanceMask${t}-${n.instanceIndex}`,outputs:r,loadColor:!0,loadDepth:!0,objectFilter:e=>e===n.object,overrideMaterial:(e,t)=>t?i[1]:i[0]})}const i=e.createColorTarget(`${this.targetPrefix}Color`,{format:"rgba16float"}),a=`${t}:${r}:${i}`;let s=this.passes.get(a);return s||(s=new za(t,r,i,this),this.passes.set(a,s)),e.addFullscreenPass(s),i}dispose(){this.maskMaterial.dispose(),this.skinnedMaskMaterial.dispose();for(const e of this.instanceMaskMaterials.values())e[0].dispose(),e[1].dispose();this.instanceMaskMaterials.clear(),this.passes.clear()}};function La(e,t=-1){return new kt({vertexShader:`\nstruct VertexInput {\n @location(0) position: vec3<f32>,${e?"\n @location(4) skinIndex: vec4<u32>,\n @location(5) skinWeight: vec4<f32>,":""}\n @builtin(instance_index) instanceIndex: u32,\n};\nstruct VertexOutput {\n @builtin(position) position: vec4<f32>,\n @interpolate(flat) @location(0) batchingId: u32,\n};\n@vertex fn vsMain(input: VertexInput) -> VertexOutput {\n return VertexOutput(\n rendererClipPosition(${e?"rendererSkinPosition(input.position, input.skinIndex, input.skinWeight)":"input.position"}, input.instanceIndex),\n rendererBatchingId(input.instanceIndex)\n );\n}`,fragmentShader:"\nstruct VertexOutput {\n @builtin(position) position: vec4<f32>,\n @interpolate(flat) @location(0) batchingId: u32,\n};\n@fragment fn fsMain(input: VertexOutput) -> @location(0) vec4<f32> {\n if (materialUniforms.selectedInstance >= 0.0 &&\n input.batchingId != u32(materialUniforms.selectedInstance)) { discard; }\n return vec4(1.0);\n}",uniforms:{selectedInstance:t},depthWrite:!1,depthTest:!0})}var za=class{constructor(e,t,r,n){this.state=n,this.inputs={source:e,mask:t},this.outputs=r}state;name="OutlineComposite";sampler="linear";uniformBufferSize=32;inputs;outputs;uniforms=new Float32Array(8);updateUniforms=()=>(this.uniforms.set([this.state.visibleEdgeColor[0],this.state.visibleEdgeColor[1],this.state.visibleEdgeColor[2],this.state.edgeStrength,this.state.edgeThickness,0,0,0]),this.uniforms);fragmentShader="\n@fragment fn fsMain(input: FullscreenVertexOutput) -> @location(0) vec4<f32> {\n let scene = textureSample(sourceTexture, fullscreenSampler, input.uv);\n let texel = 1.0 / vec2<f32>(textureDimensions(maskTexture));\n let radius = max(fullscreenUniforms[1].x, 0.5);\n let center = textureSample(maskTexture, fullscreenSampler, input.uv).r;\n var around = 0.0;\n around = max(around, textureSample(maskTexture, fullscreenSampler, input.uv + vec2(texel.x * radius, 0.0)).r);\n around = max(around, textureSample(maskTexture, fullscreenSampler, input.uv - vec2(texel.x * radius, 0.0)).r);\n around = max(around, textureSample(maskTexture, fullscreenSampler, input.uv + vec2(0.0, texel.y * radius)).r);\n around = max(around, textureSample(maskTexture, fullscreenSampler, input.uv - vec2(0.0, texel.y * radius)).r);\n around = max(around, textureSample(maskTexture, fullscreenSampler, input.uv + texel * radius).r);\n around = max(around, textureSample(maskTexture, fullscreenSampler, input.uv - texel * radius).r);\n let edge = clamp(around - center, 0.0, 1.0);\n let color = fullscreenUniforms[0].rgb * fullscreenUniforms[0].a;\n return vec4(scene.rgb + color * edge, scene.a);\n}"};import{AmbientLight as Ua,BackSide as Va,Bone as Aa,BatchedMesh as Fa,BoxGeometry as Ea,BufferAttribute as ka,BufferGeometry as Oa,CanvasTexture as $a,Color as ja,CompressedArrayTexture as Na,CompressedArrayTexture as Wa,CompressedCubeTexture as _a,CompressedTexture as qa,CubeTexture as Ha,Data3DTexture as Ka,DataArrayTexture as Za,DataTexture as Ya,DepthTexture as Xa,DirectionalLight as Ja,DoubleSide as Qa,FrontSide as es,Group as ts,HemisphereLight as rs,InstancedMesh as ns,MathUtils as is,Matrix4 as as,Mesh as ss,Object3D as os,OrthographicCamera as ls,PerspectiveCamera as cs,PlaneGeometry as us,PointLight as ds,RepeatWrapping as hs,Scene as ps,Skeleton as fs,SkinnedMesh as ms,SphereGeometry as gs,SpotLight as xs,Texture as vs,Vector2 as ws,Vector3 as bs,Vector4 as ys}from"three";export{Ua as AmbientLight,Va as BackSide,Fa as BatchedMesh,va as BloomEffect,Aa as Bone,Ea as BoxGeometry,ka as BufferAttribute,Oa as BufferGeometry,$a as CanvasTexture,ja as Color,Ma as ColorGradingEffect,Na as CompressedArrayTexture,_a as CompressedCubeTexture,qa as CompressedTexture,Wa as CompressedTextureArray,e as ComputeKernel,Ha as CubeTexture,Et as DEFAULT_WGSL_VERTEX_ATTRIBUTES,Ka as Data3DTexture,Za as DataArrayTexture,Ya as DataTexture,Ta as DepthOfFieldEffect,Xa as DepthTexture,Ja as DirectionalLight,Qa as DoubleSide,ma as FXAAEffect,Je as FrameGraphBuilder,es as FrontSide,Ki as GTAOEffect,ts as Group,rs as HemisphereLight,ns as InstancedMesh,is as MathUtils,as as Matrix4,ss as Mesh,os as Object3D,ls as OrthographicCamera,Ra as OutlineEffect,cs as PerspectiveCamera,us as PlaneGeometry,ds as PointLight,qt as RenderGraph,hs as RepeatWrapping,ra as SSREffect,ps as Scene,fs as Skeleton,ms as SkinnedMesh,gs as SphereGeometry,xs as SpotLight,da as TemporalAAEffect,vs as Texture,w as VOLUMETRIC_FOG_MATERIAL_WGSL,ws as Vector2,bs as Vector3,ys as Vector4,f as VolumetricFogEffect,c as VolumetricFogVolumeObject,kt as WGSLShaderMaterial,rr as WebGpuPMREMGenerator,Wi as WebGpuRenderer,b as configureVolumetricFogMaterial};
|
|
1
|
+
var e=class{layout;pipeline;constructor(e,t){this.layout=e.createBindGroupLayout({label:t.label?`${t.label}-layout`:void 0,entries:t.bindGroupLayoutEntries});const r=e.createPipelineLayout({label:t.label?`${t.label}-pipeline-layout`:void 0,bindGroupLayouts:[this.layout]});this.pipeline=e.createComputePipeline({label:t.label,layout:r,compute:{module:e.createShaderModule({label:t.label?`${t.label}-module`:void 0,code:t.code}),entryPoint:t.entryPoint??"main"}})}createBindGroup(e,t,r){return e.createBindGroup({label:r,layout:this.layout,entries:t})}};import{Color as t,DirectionalLight as r,Matrix4 as n,Object3D as i,PointLight as a,Scene as s,SpotLight as o,Vector3 as l}from"three";var c=class extends i{constructor(e){super(),this.volume=e}volume;isFogVolumeObject=!0},u=(new n).set(1,0,0,0,0,1,0,0,0,0,.5,.5,0,0,0,1),d=new l,h=new l,p=new l,f=class{constructor(e=new s,r={}){this.scene=e,this.options={froxelPixelSize:Math.max(2,Math.floor(r.froxelPixelSize??8)),depthSlices:Math.max(8,Math.floor(r.depthSlices??64)),integrationSubsteps:r.integrationSubsteps??2,maxDistance:Math.max(1,r.maxDistance??256),targetPrefix:r.targetPrefix??"volumetricFog",maxVolumes:Math.max(1,Math.floor(r.maxVolumes??32)),maxDirectionalLights:Math.min(4,Math.max(1,Math.floor(r.maxDirectionalLights??4))),maxPointLights:Math.min(4,Math.max(0,Math.floor(r.maxPointLights??4))),maxSpotLights:Math.min(4,Math.max(0,Math.floor(r.maxSpotLights??4))),ambientColor:r.ambientColor?.clone()??new t(.03,.035,.045),shadowFilterTaps:r.shadowFilterTaps??4,temporalJitter:r.temporalJitter??!0,spatialJitter:r.spatialJitter??!0,fogDitherStrength:Math.max(0,r.fogDitherStrength??.75),scatteringIntensity:Math.max(0,r.scatteringIntensity??1),blur:!1!==r.blur&&{scale:Math.max(.125,Math.min(1,r.blur?.scale??.5)),radius:Math.max(1,Math.min(12,Math.floor(r.blur?.radius??3))),depthSigma:Math.max(1e-4,r.blur?.depthSigma??.05),spatialSigma:Math.max(.1,r.blur?.spatialSigma??2),depthAwareUpsample:r.blur?.depthAwareUpsample??!0}},this.integratedVolume=`${this.options.targetPrefix}Integrated`,this.columnDepthBounds=`${this.options.targetPrefix}DepthBounds`,this.volumeData=new Float32Array(20*this.options.maxVolumes);const n=this.options.maxDirectionalLights+this.options.maxPointLights+this.options.maxSpotLights;this.lightData=new Float32Array(16*n)}scene;integratedVolume;columnDepthBounds;options;resources=new WeakMap;uniformStorage=new ArrayBuffer(160);uniforms=new Float32Array(this.uniformStorage);uniformIntegers=new Uint32Array(this.uniformStorage);volumeData;lightData;projectionInverse=new n;viewProjectionInverse=new n;explicitVolumes=[];cascadeDirectionalLights=[];compositePass=null;blurPassCache=new Map;frameIndex=0;setScene(e){this.scene=e}setCascadedDirectionalLights(e){this.cascadeDirectionalLights=e}addPasses(e,t){this.explicitVolumes=t.volumes??[],e.createTextureTarget(this.integratedVolume,{dimension:"3d",depthOrArrayLayers:this.options.depthSlices,scale:1/this.options.froxelPixelSize,format:"rgba16float",usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.STORAGE_BINDING}),e.createTextureTarget(this.columnDepthBounds,{scale:1/this.options.froxelPixelSize,format:"rg32float",usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.STORAGE_BINDING}),e.addPass({name:"VolumetricFogFroxelPass",inputs:{sceneDepth:t.depth},outputs:[this.integratedVolume,this.columnDepthBounds],execute:e=>this.executeFroxels(e)});const r=e.createColorTarget(`${this.options.targetPrefix}Composite`,{format:"rgba16float"});return!1!==this.options.blur?this.addBlurredComposite(e,t,r):(this.compositePass&&this.compositePass.matches(t.sceneColor,t.depth,r)||(this.compositePass=new m(t.sceneColor,t.depth,this.integratedVolume,this.columnDepthBounds,r,this.options.maxDistance,this.options.fogDitherStrength)),this.compositePass.setFrameIndex(this.frameIndex),e.addFullscreenPass(this.compositePass),r)}addBlurredComposite(e,t,r){const n=this.options.blur;if(!1===n)return r;const i=e.createColorTarget(`${this.options.targetPrefix}Resolved`,{format:"rgba16float",scale:n.scale}),a=e.createColorTarget(`${this.options.targetPrefix}BlurTemporary`,{format:"rgba16float",scale:n.scale}),s=e.createColorTarget(`${this.options.targetPrefix}Blurred`,{format:"rgba16float",scale:n.scale}),o=`resolve:${t.depth}:${i}`;let l=this.blurPassCache.get(o);l||(l=new g(t.depth,this.integratedVolume,this.columnDepthBounds,i,this.options.maxDistance,this.options.fogDitherStrength),this.blurPassCache.set(o,l)),l.setFrameIndex(this.frameIndex),e.addFullscreenPass(l);for(const[r,o,l]of[[i,a,[1,0]],[a,s,[0,1]]]){const i=`blur:${r}:${o}:${l[0]}:${n.radius}:${n.depthSigma}:${n.spatialSigma}`;let a=this.blurPassCache.get(i);a||(a=new x(r,t.depth,o,l,n),this.blurPassCache.set(i,a)),e.addFullscreenPass(a)}const c=`blurComposite:${t.sceneColor}:${t.depth}:${s}:${r}:${n.depthAwareUpsample}`;let u=this.blurPassCache.get(c);return u||(u=new v(t.sceneColor,t.depth,s,this.integratedVolume,this.columnDepthBounds,r,n.depthAwareUpsample),this.blurPassCache.set(c,u)),e.addFullscreenPass(u),r}dispose(){this.compositePass=null}executeFroxels(e){const t=this.getResources(e.device),r=this.collectSceneData(e.camera),n=Math.max(.01,e.camera.near),i=Math.max(n+.01,Math.min(e.camera.far,this.options.maxDistance)),a=Math.max(1,Math.floor(e.width/this.options.froxelPixelSize)),s=Math.max(1,Math.floor(e.height/this.options.froxelPixelSize));this.viewProjectionInverse.copy(u).multiply(e.camera.projectionMatrix).multiply(e.camera.matrixWorldInverse).invert(),this.uniforms.set(this.viewProjectionInverse.elements,0),this.uniforms.set(e.camera.position.toArray(),16),this.uniforms.set([n],19),this.uniforms.set([a,s,this.options.depthSlices,i],20),this.uniformIntegers.set([r.volumes,r.directional,r.point,r.spot],24),this.uniforms.set([this.options.ambientColor.r,this.options.ambientColor.g,this.options.ambientColor.b,this.options.temporalJitter?this.frameIndex++%1024+1:0],28),e.camera.getWorldDirection(h),this.uniforms.set([h.x,h.y,h.z,Math.max(e.camera.far-n,1e-4)],32),this.uniforms.set([this.options.scatteringIntensity,this.options.spatialJitter?1:0,0,0],36),e.device.queue.writeBuffer(t.uniformBuffer,0,this.uniforms),e.device.queue.writeBuffer(t.volumeBuffer,0,this.volumeData.buffer,this.volumeData.byteOffset,this.volumeData.byteLength),e.device.queue.writeBuffer(t.lightBuffer,0,this.lightData.buffer,this.lightData.byteOffset,this.lightData.byteLength);const o=e.getSceneLightingResources(),l=e.device.createBindGroup({label:"volumetric-fog-bind-group",layout:t.layout,entries:[{binding:0,resource:{buffer:t.uniformBuffer}},{binding:1,resource:{buffer:t.volumeBuffer}},{binding:2,resource:{buffer:t.lightBuffer}},{binding:3,resource:e.getTextureView(this.integratedVolume)},{binding:4,resource:{buffer:o.lightBuffer}},{binding:5,resource:e.comparisonSampler},{binding:6,resource:o.directionalShadowView},{binding:7,resource:o.pointShadowView},{binding:8,resource:o.spotShadowView},{binding:9,resource:e.depthView},{binding:10,resource:e.getTextureView(this.columnDepthBounds)}]}),c=e.encoder.beginComputePass({label:"VolumetricFogFroxelPass"});c.setPipeline(t.pipeline),c.setBindGroup(0,l),c.dispatchWorkgroups(Math.ceil(a/8),Math.ceil(s/8)),c.end()}collectSceneData(e){this.volumeData.fill(0),this.lightData.fill(0);const t=[...this.explicitVolumes],n=[];for(const t of this.cascadeDirectionalLights)t.visible&&t.layers.test(e.layers)&&!n.includes(t)&&n.push(t);const i=[],s=[];this.scene.traverseVisible(l=>{const c=l;c.isFogVolumeObject&&c.volume&&!t.includes(c.volume)?t.push(c.volume):l instanceof r&&l.layers.test(e.layers)&&!n.includes(l)?n.push(l):l instanceof a&&l.layers.test(e.layers)?i.push(l):l instanceof o&&l.layers.test(e.layers)&&s.push(l)});const l=Math.min(t.length,this.options.maxVolumes);for(let e=0;e<l;e++)this.writeVolume(e,t[e]);const c=Math.min(n.length,this.options.maxDirectionalLights),u=Math.min(i.length,this.options.maxPointLights),d=Math.min(s.length,this.options.maxSpotLights);let h=0;for(let e=0;e<c;e++)this.writeDirectional(h++,n[e]);for(let e=0;e<u;e++)this.writePoint(h++,i[e]);for(let e=0;e<d;e++)this.writeSpot(h++,s[e]);return{volumes:l,directional:c,point:u,spot:d}}writeVolume(e,t){const r=20*e;t.object.getWorldPosition(d),t.object.getWorldScale(p),this.volumeData.set([d.x,d.y,d.z,5*Math.max(p.x,p.y,p.z)],r),this.volumeData.set([t.albedo.r,t.albedo.g,t.albedo.b,Math.max(0,t.baseDensity)],r+4),this.volumeData.set([t.heightFalloff,t.heightOffset,t.startDistance??3,-Math.max(-.99,Math.min(.99,t.scatteringDistribution))],r+8),this.volumeData.set([t.emissive.r,t.emissive.g,t.emissive.b,t.ambientIntensity??1],r+12),this.volumeData[r+16]="lightShaft"===t.scatteringMode?1:0}lightColor(e){const t=e.intensity*(e.userData?.volumetricIntensity??1);return[e.color.r*t,e.color.g*t,e.color.b*t]}writeDirectional(e,t){const r=16*e;t.getWorldPosition(d),t.target.getWorldPosition(h),h.sub(d).normalize(),this.lightData.set([h.x,h.y,h.z,0],r),this.lightData.set([...this.lightColor(t),0],r+4)}writePoint(e,t){const r=16*e;t.getWorldPosition(d),this.lightData.set([d.x,d.y,d.z,Math.max(.001,t.distance||this.options.maxDistance)],r),this.lightData.set([...this.lightColor(t),Math.max(0,t.decay)],r+4)}writeSpot(e,t){const r=16*e;t.getWorldPosition(d),t.target.getWorldPosition(h),h.sub(d).normalize(),this.lightData.set([d.x,d.y,d.z,Math.max(.001,t.distance||this.options.maxDistance)],r),this.lightData.set([...this.lightColor(t),Math.max(0,t.decay)],r+4),this.lightData.set([h.x,h.y,h.z,Math.cos(t.angle)],r+8),this.lightData[r+12]=Math.cos(t.angle*(1-t.penumbra))}getResources(e){const t=this.resources.get(e);if(t)return t;const r=e.createBuffer({size:160,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),n=e.createBuffer({size:this.volumeData.byteLength,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST}),i=e.createBuffer({size:this.lightData.byteLength,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST}),a=e.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.COMPUTE,buffer:{type:"uniform"}},{binding:1,visibility:GPUShaderStage.COMPUTE,buffer:{type:"read-only-storage"}},{binding:2,visibility:GPUShaderStage.COMPUTE,buffer:{type:"read-only-storage"}},{binding:3,visibility:GPUShaderStage.COMPUTE,storageTexture:{access:"write-only",format:"rgba16float",viewDimension:"3d"}},{binding:4,visibility:GPUShaderStage.COMPUTE,buffer:{type:"uniform"}},{binding:5,visibility:GPUShaderStage.COMPUTE,sampler:{type:"comparison"}},{binding:6,visibility:GPUShaderStage.COMPUTE,texture:{sampleType:"depth",viewDimension:"2d-array"}},{binding:7,visibility:GPUShaderStage.COMPUTE,texture:{sampleType:"float",viewDimension:"2d-array"}},{binding:8,visibility:GPUShaderStage.COMPUTE,texture:{sampleType:"depth",viewDimension:"2d-array"}},{binding:9,visibility:GPUShaderStage.COMPUTE,texture:{sampleType:"depth",viewDimension:"2d"}},{binding:10,visibility:GPUShaderStage.COMPUTE,storageTexture:{access:"write-only",format:"rg32float",viewDimension:"2d"}}]}),s=e.createShaderModule({label:"volumetric-fog-compute",code:y.replace("__SHADOW_TAPS__",String(this.options.shadowFilterTaps)).replace("__INTEGRATION_SUBSTEPS__",String(this.options.integrationSubsteps))}),o={uniformBuffer:r,volumeBuffer:n,lightBuffer:i,layout:a,pipeline:e.createComputePipeline({layout:e.createPipelineLayout({bindGroupLayouts:[a]}),compute:{module:s,entryPoint:"main"}})};return this.resources.set(e,o),o}},m=class{constructor(e,t,r,n,i,a,s){this.maxDistance=a,this.ditherStrength=s,this.inputs={sceneColor:e,sceneDepth:t,fogVolume:r,fogBounds:n},this.outputs=i}maxDistance;ditherStrength;name="VolumetricFogCompositePass";sampler="linear";uniformBufferSize=80;inputs;inputDimensions={fogVolume:"3d"};outputs;fragmentShader=S;data=new Float32Array(20);inverseProjection=new n;frameIndex=0;setFrameIndex(e){this.frameIndex=e}matches(e,t,r){return this.inputs.sceneColor===e&&this.inputs.sceneDepth===t&&this.outputs===r}updateUniforms=e=>(this.inverseProjection.copy(u).multiply(e.camera.projectionMatrix).invert(),this.data.set(this.inverseProjection.elements,0),this.data.set([Math.max(.01,e.camera.near),Math.min(e.camera.far,this.maxDistance),this.frameIndex>0?this.frameIndex%1024:-1,this.ditherStrength],16),this.data)},g=class{constructor(e,t,r,n,i,a){this.maxDistance=i,this.ditherStrength=a,this.inputs={sceneDepth:e,fogVolume:t,fogBounds:r},this.outputs=n}maxDistance;ditherStrength;name="VolumetricFogResolvePass";sampler="linear";uniformBufferSize=80;inputDimensions={fogVolume:"3d"};inputs;outputs;fragmentShader=C;data=new Float32Array(20);inverseProjection=new n;frameIndex=0;setFrameIndex(e){this.frameIndex=e}updateUniforms=e=>(this.inverseProjection.copy(u).multiply(e.camera.projectionMatrix).invert(),this.data.set(this.inverseProjection.elements,0),this.data.set([Math.max(.01,e.camera.near),Math.min(e.camera.far,this.maxDistance),this.frameIndex>0?this.frameIndex%1024:-1,this.ditherStrength],16),this.data)},x=class{name;sampler="linear";uniformBufferSize=80;inputs;outputs;fragmentShader;data=new Float32Array(20);inverseProjection=new n;constructor(e,t,r,n,i){this.name=n[0]?"VolumetricFogBlurHorizontalPass":"VolumetricFogBlurVerticalPass",this.inputs={fogInput:e,sceneDepth:t},this.outputs=r,this.data.set([n[0],n[1],i.depthSigma,i.spatialSigma],16),this.fragmentShader=`\nconst BLUR_RADIUS:i32=${i.radius};\nfn inverseProjection() -> mat4x4<f32> { return mat4x4<f32>(fullscreenUniforms[0],fullscreenUniforms[1],fullscreenUniforms[2],fullscreenUniforms[3]); }\nfn viewDistance(uv:vec2<f32>)->f32 { let size=vec2<i32>(textureDimensions(sceneDepthTexture));let pixel=clamp(vec2<i32>(uv*vec2<f32>(size)),vec2<i32>(0),size-vec2<i32>(1));let depth=textureLoad(sceneDepthTexture,pixel,0);let clip=vec4<f32>(uv.x*2.0-1.0,1.0-uv.y*2.0,depth,1.0);let view=inverseProjection()*clip;return length(view.xyz/view.w); }\n@fragment fn fsMain(input:FullscreenVertexOutput)->@location(0) vec4<f32>{\n let size=vec2<f32>(textureDimensions(fogInputTexture));let texel=1.0/size;let direction=fullscreenUniforms[4].xy;let depthSigma=fullscreenUniforms[4].z;let spatialSigma=fullscreenUniforms[4].w;\n let centerDepth=viewDistance(input.uv);var sum=vec4<f32>(0.0);var weightSum=0.0;\n for(var i=-BLUR_RADIUS;i<=BLUR_RADIUS;i+=1){let uv=clamp(input.uv+direction*f32(i)*texel,vec2<f32>(0.0),vec2<f32>(1.0));let sampleDepth=viewDistance(uv);let fi=f32(i);let spatial=exp(-0.5*fi*fi/(spatialSigma*spatialSigma));let delta=log(max(sampleDepth,0.0001)/max(centerDepth,0.0001));let depthWeight=exp(-0.5*delta*delta/(depthSigma*depthSigma));let weight=spatial*depthWeight;sum+=textureSampleLevel(fogInputTexture,fullscreenSampler,uv,0.0)*weight;weightSum+=weight;}\n return sum/max(weightSum,0.0001);\n}`}updateUniforms=e=>(this.inverseProjection.copy(u).multiply(e.camera.projectionMatrix).invert(),this.data.set(this.inverseProjection.elements,0),this.data)},v=class{name="VolumetricFogBlurCompositePass";sampler="linear";uniformBufferSize=64;inputs;inputDimensions={fogVolume:"3d"};outputs;fragmentShader;data=new Float32Array(16);inverseProjection=new n;constructor(e,t,r,n,i,a,s){this.inputs=s?{sceneColor:e,sceneDepth:t,fogInput:r,fogVolume:n,fogBounds:i}:{sceneColor:e,fogInput:r},this.outputs=a,this.fragmentShader=s?P:M}updateUniforms=e=>(this.inverseProjection.copy(u).multiply(e.camera.projectionMatrix).invert(),this.data.set(this.inverseProjection.elements),this.data)},w="\nfn rendererSampleIntegratedFog(uv: vec2<f32>, normalizedDepth: f32) -> vec4<f32> {\n let sliceCount = f32(textureDimensions(volumetricFogTexture).z);\n let slicePosition = clamp(normalizedDepth, 0.0, 1.0) * sliceCount;\n let textureZ = clamp((slicePosition - 0.5) / sliceCount, 0.0, 1.0);\n let integrated = textureSampleLevel(volumetricFogTexture, volumetricFogSampler, vec3<f32>(uv, textureZ), 0.0);\n // The volume stores slice endpoints but has no texel for the near-plane\n // identity value. Reconstruct that missing endpoint for the first slice.\n return mix(vec4<f32>(0.0, 0.0, 0.0, 1.0), integrated, min(slicePosition, 1.0));\n}\nfn rendererApplyVolumetricFog(color: vec4<f32>, worldPosition: vec3<f32>) -> vec4<f32> {\n let clip = rendererCamera.viewProj * vec4<f32>(worldPosition, 1.0);\n let uv = clip.xy / clip.w * vec2<f32>(0.5, -0.5) + vec2<f32>(0.5);\n let distance = length(worldPosition - rendererCamera.cameraPosition.xyz);\n let bounds = textureSampleLevel(volumetricFogBoundsTexture, volumetricFogBoundsSampler, uv, 0.0).rg;\n let z = clamp((distance - bounds.x) / max(bounds.y - bounds.x, 0.001), 0.0, 1.0);\n let fog = rendererSampleIntegratedFog(uv, z);\n return vec4<f32>(fog.rgb + color.rgb * fog.a, color.a);\n}";function b(e,t="volumetricFogIntegrated",r=(t.endsWith("Integrated")?`${t.slice(0,-10)}DepthBounds`:"volumetricFogDepthBounds")){return e.graphTextures.volumetricFog={resource:t,dimension:"3d",sampleType:"float",sampler:"filtering",requiresLatePass:!0},e.graphTextures.volumetricFogBounds={resource:r,dimension:"2d",sampleType:"float",sampler:"filtering",requiresLatePass:!0},e.needsUpdate=!0,e}var y="\nstruct FogUniforms { inverseViewProjection: mat4x4<f32>, cameraNear: vec4<f32>, dimensionsFar: vec4<f32>, counts: vec4<u32>, ambient: vec4<f32>, cameraForwardDepthRange: vec4<f32>, scattering: vec4<f32> };\nstruct FogVolume { centerRadius: vec4<f32>, albedoDensity: vec4<f32>, heightStartPhase: vec4<f32>, emissiveAmbient: vec4<f32>, mode: vec4<f32> };\nstruct FogLight { positionRange: vec4<f32>, colorDecay: vec4<f32>, directionCone: vec4<f32>, penumbra: vec4<f32> };\nstruct RendererLightUniforms {\n ambientColor: vec4<f32>, lightCounts: vec4<f32>,\n directionalDirections: array<vec4<f32>,4>, directionalColorIntensities: array<vec4<f32>,4>,\n directionalShadowParams: array<vec4<f32>,4>, directionalShadowParams2: array<vec4<f32>,4>, directionalShadowMatrices: array<mat4x4<f32>,4>,\n pointPositionRanges: array<vec4<f32>,4>, pointColorIntensities: array<vec4<f32>,4>, pointShadowParams: array<vec4<f32>,4>, pointShadowParams2: array<vec4<f32>,4>,\n spotPositionRanges: array<vec4<f32>,4>, spotDirectionCones: array<vec4<f32>,4>, spotColorIntensities: array<vec4<f32>,4>,\n spotShadowParams: array<vec4<f32>,4>, spotShadowParams2: array<vec4<f32>,4>, spotParams: array<vec4<f32>,4>, spotShadowMatrices: array<mat4x4<f32>,4>,\n csmCascadeRanges: array<vec4<f32>,4>, hemisphereSkyColorIntensity: vec4<f32>, hemisphereGroundColorIntensity: vec4<f32>, hemisphereDirection: vec4<f32>\n};\n@group(0) @binding(0) var<uniform> uniforms: FogUniforms;\n@group(0) @binding(1) var<storage, read> volumes: array<FogVolume>;\n@group(0) @binding(2) var<storage, read> lights: array<FogLight>;\n@group(0) @binding(3) var outputFog: texture_storage_3d<rgba16float, write>;\n@group(0) @binding(4) var<uniform> rendererLights: RendererLightUniforms;\n@group(0) @binding(5) var shadowSampler: sampler_comparison;\n@group(0) @binding(6) var directionalShadows: texture_depth_2d_array;\n@group(0) @binding(7) var pointShadows: texture_2d_array<f32>;\n@group(0) @binding(8) var spotShadows: texture_depth_2d_array;\n@group(0) @binding(9) var sceneDepth: texture_depth_2d;\n@group(0) @binding(10) var outputDepthBounds: texture_storage_2d<rg32float, write>;\nconst PI = 3.14159265359;\nconst SHADOW_TAPS = __SHADOW_TAPS__;\nconst INTEGRATION_SUBSTEPS = __INTEGRATION_SUBSTEPS__;\nfn phaseHG(cosTheta: f32, g: f32) -> f32 { let gg = g*g; return (1.0-gg)/(4.0*PI*pow(max(0.001,1.0+gg-2.0*g*cosTheta),1.5)); }\nfn attenuation(distance: f32, range: f32, decay: f32) -> f32 { let window = max(0.0, 1.0-pow(distance/range,4.0)); return window*window / max(1.0, pow(distance, decay)); }\nfn hash12(p:vec2<f32>)->f32 { let p3=fract(vec3<f32>(p.xyx)*0.1031); let q=p3+dot(p3,p3.yzx+33.33); return fract((q.x+q.y)*q.z); }\nfn rotatedOffset(tap:i32, angle:f32)->vec2<f32> {\n let disk=array<vec2<f32>,4>(vec2<f32>(-0.326,-0.406),vec2<f32>(-0.840,0.074),vec2<f32>(-0.696,0.457),vec2<f32>(0.203,0.621));\n let v=disk[tap]; let c=cos(angle); let s=sin(angle); return vec2<f32>(c*v.x-s*v.y,s*v.x+c*v.y);\n}\nfn projectedShadow(matrix: mat4x4<f32>, p: vec3<f32>, layer: i32, bias: f32, intensity: f32, textureKind: u32) -> f32 {\n let clip=matrix*vec4<f32>(p,1.0); if (clip.w<=0.0) { return 1.0; } let ndc=clip.xyz/clip.w;\n if (ndc.x < -1.0 || ndc.x > 1.0 || ndc.y < -1.0 || ndc.y > 1.0 || ndc.z < 0.0 || ndc.z > 1.0) { return 1.0; }\n let uv=ndc.xy*vec2<f32>(0.5,-0.5)+vec2<f32>(0.5); var visibility=0.0;\n // Avoid a world-space random pattern swimming through the camera-relative grid.\n let angle=select(0.0,hash12(p.xz+vec2<f32>(uniforms.ambient.w, f32(layer)))*6.2831853,uniforms.ambient.w>0.0);\n if (textureKind==0u) {\n let dims=vec2<f32>(textureDimensions(directionalShadows)); let radius=max(rendererLights.directionalShadowParams2[u32(layer)].x,0.0);let offset=radius/dims;let depth=ndc.z+bias;\n // Match the surface-lighting path: a weighted hardware-PCF center and\n // four cardinal taps. The former sparse rotated disk made partially\n // shadowed froxels jump between a few discrete visibility values.\n let center=textureSampleCompareLevel(directionalShadows,shadowSampler,uv,layer,depth);\n if(SHADOW_TAPS==1){\n visibility=center;\n }else{\n let left=textureSampleCompareLevel(directionalShadows,shadowSampler,clamp(uv-vec2<f32>(offset.x,0.0),vec2<f32>(0.0),vec2<f32>(1.0)),layer,depth);\n let right=textureSampleCompareLevel(directionalShadows,shadowSampler,clamp(uv+vec2<f32>(offset.x,0.0),vec2<f32>(0.0),vec2<f32>(1.0)),layer,depth);\n let up=textureSampleCompareLevel(directionalShadows,shadowSampler,clamp(uv-vec2<f32>(0.0,offset.y),vec2<f32>(0.0),vec2<f32>(1.0)),layer,depth);\n let down=textureSampleCompareLevel(directionalShadows,shadowSampler,clamp(uv+vec2<f32>(0.0,offset.y),vec2<f32>(0.0),vec2<f32>(1.0)),layer,depth);\n visibility=(center*4.0+left+right+up+down)*0.5;\n }\n } else {\n let dims=vec2<f32>(textureDimensions(spotShadows)); let radius=max(rendererLights.spotShadowParams2[u32(layer)].x,1.0);\n for(var tap=0;tap<SHADOW_TAPS;tap+=1){let suv=clamp(uv+rotatedOffset(tap,angle)*radius/dims,vec2<f32>(0.0),vec2<f32>(1.0));let pixel=vec2<i32>(clamp(suv*dims,vec2<f32>(0.0),dims-1.0));visibility+=select(0.0,1.0,ndc.z-bias<=textureLoad(spotShadows,pixel,layer,0));}\n }\n visibility/=f32(SHADOW_TAPS);\n return mix(1.0,visibility,intensity);\n}\nfn pointShadowUvLayer(direction: vec3<f32>, index: u32) -> vec3<f32> {\n let a=abs(direction); var face=0u; var uv=vec2<f32>(0.0);\n if (a.x>=a.y && a.x>=a.z) { if(direction.x>=0.0){face=0u;uv=vec2<f32>(-direction.z,-direction.y)/a.x;}else{face=1u;uv=vec2<f32>(direction.z,-direction.y)/a.x;} }\n else if(a.y>=a.x && a.y>=a.z){if(direction.y>=0.0){face=2u;uv=vec2<f32>(direction.x,direction.z)/a.y;}else{face=3u;uv=vec2<f32>(direction.x,-direction.z)/a.y;}}\n else{if(direction.z>=0.0){face=4u;uv=vec2<f32>(direction.x,-direction.y)/a.z;}else{face=5u;uv=vec2<f32>(-direction.x,-direction.y)/a.z;}}\n return vec3<f32>(uv*0.5+0.5,f32(index*6u+face));\n}\nfn directionalVisibility(index:u32,p:vec3<f32>)->f32 { let sp=rendererLights.directionalShadowParams[index]; if(sp.y<0.5){return 1.0;} return projectedShadow(rendererLights.directionalShadowMatrices[index],p,i32(index),sp.x,rendererLights.directionalShadowParams2[index].y,0u); }\nfn pointVisibility(index:u32,p:vec3<f32>)->f32 { let sp=rendererLights.pointShadowParams[index]; if(sp.y<0.5){return 1.0;} let delta=p-rendererLights.pointPositionRanges[index].xyz; let range=rendererLights.pointPositionRanges[index].w; let uv=pointShadowUvLayer(delta,index); let dims=vec2<f32>(textureDimensions(pointShadows)); let angle=select(0.0,hash12(p.xy+vec2<f32>(uniforms.ambient.w,f32(index)))*6.2831853,uniforms.ambient.w>0.0); var visible=0.0; for(var tap=0;tap<SHADOW_TAPS;tap+=1){let suv=clamp(uv.xy+rotatedOffset(tap,angle)/dims,vec2<f32>(0.0),vec2<f32>(1.0));let pixel=vec2<i32>(clamp(suv*dims,vec2<f32>(0.0),dims-1.0));let stored=textureLoad(pointShadows,pixel,i32(round(uv.z)),0).r;visible+=select(0.0,1.0,length(delta)/max(range,0.0001)-sp.x<=stored);} visible/=f32(SHADOW_TAPS); return mix(1.0,visible,rendererLights.pointShadowParams2[index].y); }\nfn spotVisibility(index:u32,p:vec3<f32>)->f32 { let sp=rendererLights.spotShadowParams[index]; if(sp.y<0.5){return 1.0;} return projectedShadow(rendererLights.spotShadowMatrices[index],p,i32(index),sp.x,rendererLights.spotShadowParams2[index].y,1u); }\nfn sceneDistanceAt(pixel:vec2<u32>)->f32{\n let size=textureDimensions(sceneDepth);let clamped=min(pixel,size-vec2<u32>(1u));let depth=textureLoad(sceneDepth,vec2<i32>(clamped),0);\n let uv=(vec2<f32>(clamped)+vec2<f32>(0.5))/vec2<f32>(size);let world4=uniforms.inverseViewProjection*vec4<f32>(uv.x*2.0-1.0,1.0-uv.y*2.0,depth,1.0);\n return length(world4.xyz/world4.w-uniforms.cameraNear.xyz);\n}\n@compute @workgroup_size(8,8,1)\nfn main(@builtin(global_invocation_id) id: vec3<u32>) {\n let dims = vec3<u32>(uniforms.dimensionsFar.xyz); if (id.x >= dims.x || id.y >= dims.y) { return; }\n let temporal=select(vec2<f32>(0.5),vec2<f32>(hash12(vec2<f32>(id.xy)+uniforms.ambient.w),hash12(vec2<f32>(id.yx)+uniforms.ambient.w+19.19)),uniforms.ambient.w>0.0);\n let rayJitter=hash12(vec2<f32>(id.xy)+vec2<f32>(uniforms.ambient.w*0.754877,uniforms.ambient.w*0.569841));\n let uv = (vec2<f32>(id.xy)+temporal)/vec2<f32>(dims.xy);\n let farPoint4 = uniforms.inverseViewProjection * vec4<f32>(uv.x*2.0-1.0, 1.0-uv.y*2.0, 1.0, 1.0);\n let camera = uniforms.cameraNear.xyz; let ray = normalize(farPoint4.xyz/farPoint4.w-camera);\n let nearPlane = uniforms.cameraNear.w; let farPlane = uniforms.dimensionsFar.w;\n let depthSize=textureDimensions(sceneDepth);\n let cellMin=id.xy*depthSize/dims.xy;\n let cellEnd=((id.xy+vec2<u32>(1u))*depthSize+dims.xy-vec2<u32>(1u))/dims.xy;\n let cellMax=min(cellEnd-vec2<u32>(1u),depthSize-vec2<u32>(1u));\n let cellCenter=(cellMin+cellMax)/vec2<u32>(2u);var columnFar=max(sceneDistanceAt(cellCenter),max(max(sceneDistanceAt(cellMin),sceneDistanceAt(vec2<u32>(cellMax.x,cellMin.y))),max(sceneDistanceAt(vec2<u32>(cellMin.x,cellMax.y)),sceneDistanceAt(cellMax))));\n columnFar=clamp(columnFar,nearPlane,farPlane);var columnNear=farPlane;\n for(var volumeIndex=0u;volumeIndex<uniforms.counts.x;volumeIndex+=1u){columnNear=min(columnNear,max(volumes[volumeIndex].heightStartPhase.z,nearPlane));}\n columnNear=min(columnNear,columnFar);columnFar=max(columnFar,columnNear+0.001);textureStore(outputDepthBounds,vec2<i32>(id.xy),vec4<f32>(columnNear,columnFar,0.0,0.0));\n var previousDirectionalVisibility=array<f32,4>(1.0,1.0,1.0,1.0);var hasPreviousDirectionalVisibility=false;\n var transmittance = 1.0; var scattering = vec3<f32>(0.0); var previousDistance = columnNear;\n for (var z=0u; z<dims.z; z+=1u) {\n let sliceEnd = mix(columnNear,columnFar,f32(z+1u)/f32(dims.z)); let stepSize = sliceEnd-previousDistance;\n let substepSize=stepSize/f32(INTEGRATION_SUBSTEPS);\n for(var substep=0;substep<INTEGRATION_SUBSTEPS;substep+=1){\n // Share one stratified offset across all intervals on a ray. This turns\n // coherent Z terraces into stationary spatial error that blur can remove.\n let sampleOffset=select(0.5,rayJitter,uniforms.scattering.y>0.5);\n let sampleDistance=previousDistance+(f32(substep)+sampleOffset)*substepSize;\n let p = camera + ray*sampleDistance; var sigma = 0.0; var source = vec3<f32>(0.0);\n // Directional visibility belongs to the integration interval endpoints.\n // Reusing the preceding endpoint gives trapezoidal shadow integration\n // with one new lookup per interval, instead of quantizing a whole slice\n // from a midpoint visibility sample.\n let shadowDistance=previousDistance+(f32(substep)+1.0)*substepSize;\n let shadowP=camera+ray*shadowDistance;\n let csmCount=u32(round(rendererLights.lightCounts.w));let viewDepth=max(dot(shadowP-camera,uniforms.cameraForwardDepthRange.xyz),0.0);let normalizedViewDepth=viewDepth/uniforms.cameraForwardDepthRange.w;\n var filteredDirectionalVisibility=array<f32,4>(1.0,1.0,1.0,1.0);\n for(var d=0u;d<uniforms.counts.y;d+=1u){var cascadeWeight=1.0;if(d<csmCount){let range=rendererLights.csmCascadeRanges[d].xy;let isLast=d+1u==csmCount;cascadeWeight=select(0.0,1.0,normalizedViewDepth>=range.x&&(normalizedViewDepth<range.y||isLast));}let current=directionalVisibility(d,shadowP)*cascadeWeight;filteredDirectionalVisibility[d]=select(current,0.5*(previousDirectionalVisibility[d]+current),hasPreviousDirectionalVisibility);previousDirectionalVisibility[d]=current;}\n hasPreviousDirectionalVisibility=true;\n for (var v=0u; v<uniforms.counts.x; v+=1u) { let volume=volumes[v]; let localDistance=distance(p,volume.centerRadius.xyz);\n if (localDistance < volume.centerRadius.w && sampleDistance >= volume.heightStartPhase.z) {\n var density=volume.albedoDensity.w*exp(-volume.heightStartPhase.x*(p.y-volume.heightStartPhase.y)); density*=1.0-smoothstep(volume.centerRadius.w*0.8,volume.centerRadius.w,localDistance);\n let rendererAmbient=rendererLights.ambientColor.rgb*rendererLights.ambientColor.w;\n let hemisphereAmbient=(rendererLights.hemisphereSkyColorIntensity.rgb*rendererLights.hemisphereSkyColorIntensity.w+rendererLights.hemisphereGroundColorIntensity.rgb*rendererLights.hemisphereGroundColorIntensity.w)*0.5;\n let sceneAmbient=rendererAmbient+hemisphereAmbient;\n let ambient=select(uniforms.ambient.rgb,sceneAmbient,dot(sceneAmbient,sceneAmbient)>0.000001);\n var lighting=ambient*volume.emissiveAmbient.w+volume.emissiveAmbient.rgb; var direct=vec3<f32>(0.0); var li=0u;\n for (var d=0u; d<uniforms.counts.y; d+=1u) {\n let l=lights[li]; li+=1u;\n direct += l.colorDecay.rgb*phaseHG(dot(ray,l.positionRange.xyz),volume.heightStartPhase.w)*filteredDirectionalVisibility[d];\n }\n for (var q=0u; q<uniforms.counts.z; q+=1u) { let l=lights[li]; li+=1u; let delta=l.positionRange.xyz-p; let dist=length(delta); direct += l.colorDecay.rgb*attenuation(dist,l.positionRange.w,l.colorDecay.w)*phaseHG(dot(ray,normalize(delta)),volume.heightStartPhase.w)*pointVisibility(q,p); }\n for (var s=0u; s<uniforms.counts.w; s+=1u) { let l=lights[li]; li+=1u; let delta=l.positionRange.xyz-p; let dist=length(delta); let cd=dot(normalize(-delta),l.directionCone.xyz); let cone=smoothstep(l.directionCone.w,l.penumbra.x,cd); direct += l.colorDecay.rgb*attenuation(dist,l.positionRange.w,l.colorDecay.w)*cone*phaseHG(dot(ray,normalize(delta)),volume.heightStartPhase.w)*spotVisibility(s,p); }\n direct*=uniforms.scattering.x;\n if (volume.mode.x < 0.5) { lighting += direct; } else { lighting = direct; }\n sigma += density; source += lighting*volume.albedoDensity.rgb*density;\n }\n }\n if (sigma > 0.000001) { let extinction=exp(-sigma*substepSize); scattering += transmittance*source*((1.0-extinction)/sigma); transmittance*=extinction; }\n }\n textureStore(outputFog, vec3<i32>(i32(id.x),i32(id.y),i32(z)), vec4<f32>(scattering,transmittance)); previousDistance=sliceEnd;\n }\n}",S="\nfn inverseProjection() -> mat4x4<f32> { return mat4x4<f32>(fullscreenUniforms[0],fullscreenUniforms[1],fullscreenUniforms[2],fullscreenUniforms[3]); }\nfn fogDither(pixel:vec2<f32>,frame:f32)->f32 { let p3=fract(vec3<f32>(pixel.xyx+frame*vec3<f32>(0.754877,0.569841,0.438289))*0.1031); let q=p3+dot(p3,p3.yzx+33.33); return fract((q.x+q.y)*q.z)-0.5; }\nfn sampleIntegratedFog(uv:vec2<f32>,normalizedDepth:f32)->vec4<f32>{\n let slices=f32(textureDimensions(fogVolumeTexture).z);let slicePosition=clamp(normalizedDepth,0.0,1.0)*slices;\n let textureZ=clamp((slicePosition-0.5)/slices,0.0,1.0);let integrated=textureSampleLevel(fogVolumeTexture,fullscreenSampler,vec3<f32>(uv,textureZ),0.0);\n return mix(vec4<f32>(0.0,0.0,0.0,1.0),integrated,min(slicePosition,1.0));\n}\n@fragment fn fsMain(input: FullscreenVertexOutput) -> @location(0) vec4<f32> {\n let pixel=vec2<i32>(input.position.xy); let color=textureLoad(sceneColorTexture,pixel,0); let depth=textureLoad(sceneDepthTexture,pixel,0);\n let clip=vec4<f32>(input.uv.x*2.0-1.0,1.0-input.uv.y*2.0,depth,1.0); let view=inverseProjection()*clip; let distance=length(view.xyz/view.w);\n let bounds=textureSampleLevel(fogBoundsTexture,fullscreenSampler,input.uv,0.0).rg;let z=clamp((distance-bounds.x)/max(bounds.y-bounds.x,0.001),0.0,1.0);\n let frame=fullscreenUniforms[4].z; let ditherStrength=fullscreenUniforms[4].w;\n // Half a slice of stochastic Z movement hides integration-layer contours;\n // the RGB term removes display-quantization bands. Both converge under TAA.\n let sliceCount=f32(textureDimensions(fogVolumeTexture).z); let noise=fogDither(input.position.xy,max(frame,0.0));\n let zJitter=select(0.0,noise/max(sliceCount,1.0),frame>=0.0);\n let fog=sampleIntegratedFog(input.uv,z+zJitter);\n let fogAmount=clamp(1.0-fog.a,0.0,1.0); let dither=vec3<f32>(noise*(ditherStrength/255.0)*fogAmount);\n return vec4<f32>(max(vec3<f32>(0.0),fog.rgb+color.rgb*fog.a+dither),color.a);\n}",C="\nfn inverseProjection() -> mat4x4<f32> { return mat4x4<f32>(fullscreenUniforms[0],fullscreenUniforms[1],fullscreenUniforms[2],fullscreenUniforms[3]); }\nfn fogDither(pixel:vec2<f32>,frame:f32)->f32 { let p3=fract(vec3<f32>(pixel.xyx+frame*vec3<f32>(0.754877,0.569841,0.438289))*0.1031); let q=p3+dot(p3,p3.yzx+33.33); return fract((q.x+q.y)*q.z)-0.5; }\nfn sampleIntegratedFog(uv:vec2<f32>,normalizedDepth:f32)->vec4<f32>{\n let slices=f32(textureDimensions(fogVolumeTexture).z);let slicePosition=clamp(normalizedDepth,0.0,1.0)*slices;\n let textureZ=clamp((slicePosition-0.5)/slices,0.0,1.0);let integrated=textureSampleLevel(fogVolumeTexture,fullscreenSampler,vec3<f32>(uv,textureZ),0.0);\n return mix(vec4<f32>(0.0,0.0,0.0,1.0),integrated,min(slicePosition,1.0));\n}\n@fragment fn fsMain(input: FullscreenVertexOutput) -> @location(0) vec4<f32> {\n let depthSize=vec2<i32>(textureDimensions(sceneDepthTexture)); let depthPixel=clamp(vec2<i32>(input.uv*vec2<f32>(depthSize)),vec2<i32>(0),depthSize-vec2<i32>(1));\n let depth=textureLoad(sceneDepthTexture,depthPixel,0); let clip=vec4<f32>(input.uv.x*2.0-1.0,1.0-input.uv.y*2.0,depth,1.0);\n let view=inverseProjection()*clip; let distance=length(view.xyz/view.w); let nearPlane=fullscreenUniforms[4].x; let farPlane=fullscreenUniforms[4].y;\n let bounds=textureSampleLevel(fogBoundsTexture,fullscreenSampler,input.uv,0.0).rg;let z=clamp((distance-bounds.x)/max(bounds.y-bounds.x,0.001),0.0,1.0); let frame=fullscreenUniforms[4].z; let noise=fogDither(input.position.xy,max(frame,0.0));\n let slices=f32(textureDimensions(fogVolumeTexture).z); let zJitter=select(0.0,noise/max(slices,1.0),frame>=0.0); var fog=sampleIntegratedFog(input.uv,z+zJitter);\n fog=vec4<f32>(max(vec3<f32>(0.0),fog.rgb+vec3<f32>(noise*(fullscreenUniforms[4].w/255.0)*clamp(1.0-fog.a,0.0,1.0))),fog.a); return fog;\n}";var P="\nfn loadDepth(uv:vec2<f32>)->f32{let size=vec2<i32>(textureDimensions(sceneDepthTexture));let pixel=clamp(vec2<i32>(uv*vec2<f32>(size)),vec2<i32>(0),size-vec2<i32>(1));return textureLoad(sceneDepthTexture,pixel,0);}\nfn inverseProjection()->mat4x4<f32>{return mat4x4<f32>(fullscreenUniforms[0],fullscreenUniforms[1],fullscreenUniforms[2],fullscreenUniforms[3]);}\nfn viewDistance(uv:vec2<f32>)->f32{let depth=loadDepth(uv);let clip=vec4<f32>(uv.x*2.0-1.0,1.0-uv.y*2.0,depth,1.0);let view=inverseProjection()*clip;return length(view.xyz/view.w);}\nfn sampleIntegratedFog(uv:vec2<f32>,normalizedDepth:f32)->vec4<f32>{let slices=f32(textureDimensions(fogVolumeTexture).z);let slicePosition=clamp(normalizedDepth,0.0,1.0)*slices;let textureZ=clamp((slicePosition-0.5)/slices,0.0,1.0);let integrated=textureSampleLevel(fogVolumeTexture,fullscreenSampler,vec3<f32>(uv,textureZ),0.0);return mix(vec4<f32>(0.0,0.0,0.0,1.0),integrated,min(slicePosition,1.0));}\n@fragment fn fsMain(input:FullscreenVertexOutput)->@location(0) vec4<f32>{\n let color=textureLoad(sceneColorTexture,vec2<i32>(input.position.xy),0);let fogSize=vec2<f32>(textureDimensions(fogInputTexture));let texel=1.0/fogSize;let grid=input.uv*fogSize-0.5;let base=(floor(grid)+0.5)*texel;\n let candidates=array<vec2<f32>,4>(base,base+vec2<f32>(texel.x,0.0),base+vec2<f32>(0.0,texel.y),base+texel);let centerDistance=max(viewDistance(input.uv),0.0001);var bestUv=clamp(candidates[0],vec2<f32>(0.0),vec2<f32>(1.0));var bestDifference=abs(log(max(viewDistance(bestUv),0.0001)/centerDistance));var maxDifference=bestDifference;\n for(var i=1;i<4;i+=1){let uv=clamp(candidates[i],vec2<f32>(0.0),vec2<f32>(1.0));let difference=abs(log(max(viewDistance(uv),0.0001)/centerDistance));maxDifference=max(maxDifference,difference);if(difference<bestDifference){bestDifference=difference;bestUv=uv;}}\n let blurredUv=select(bestUv,input.uv,maxDifference<0.02);let blurredFog=textureSampleLevel(fogInputTexture,fullscreenSampler,blurredUv,0.0);let bounds=textureSampleLevel(fogBoundsTexture,fullscreenSampler,input.uv,0.0).rg;let z=clamp((centerDistance-bounds.x)/max(bounds.y-bounds.x,0.001),0.0,1.0);let directFog=sampleIntegratedFog(input.uv,z);let fog=select(directFog,blurredFog,bestDifference<0.02);return vec4<f32>(fog.rgb+color.rgb*fog.a,color.a);\n}",M="\n@fragment fn fsMain(input:FullscreenVertexOutput)->@location(0) vec4<f32>{\n let color=textureLoad(sceneColorTexture,vec2<i32>(input.position.xy),0);\n let fog=textureSampleLevel(fogInputTexture,fullscreenSampler,input.uv,0.0);\n return vec4<f32>(fog.rgb+color.rgb*fog.a,color.a);\n}";import{ByteType as B,DepthFormat as D,DepthStencilFormat as T,FloatType as I,HalfFloatType as G,IntType as R,RED_GREEN_RGTC2_Format as L,RED_RGTC1_Format as z,RGBA_ASTC_10x10_Format as U,RGBA_ASTC_10x5_Format as V,RGBA_ASTC_10x6_Format as A,RGBA_ASTC_10x8_Format as F,RGBA_ASTC_12x10_Format as E,RGBA_ASTC_12x12_Format as k,RGBA_ASTC_4x4_Format as O,RGBA_ASTC_5x4_Format as $,RGBA_ASTC_5x5_Format as j,RGBA_ASTC_6x5_Format as N,RGBA_ASTC_6x6_Format as W,RGBA_ASTC_8x5_Format as _,RGBA_ASTC_8x6_Format as q,RGBA_ASTC_8x8_Format as H,RGBA_BPTC_Format as K,RGBA_ETC2_EAC_Format as Z,RGBA_S3TC_DXT1_Format as Y,RGBA_S3TC_DXT3_Format as X,RGBA_S3TC_DXT5_Format as J,RGBAFormat as Q,RGBAIntegerFormat as ee,RGFormat as te,RGIntegerFormat as re,RGB_ETC1_Format as ne,RGB_ETC2_Format as ie,RGB_S3TC_DXT1_Format as ae,RGBFormat as se,RedFormat as oe,RedIntegerFormat as le,ShortType as ce,SIGNED_RED_GREEN_RGTC2_Format as ue,SIGNED_RED_RGTC1_Format as de,SRGBColorSpace as he,UnsignedByteType as pe,UnsignedInt248Type as fe,UnsignedInt5999Type as me,UnsignedIntType as ge,UnsignedShortType as xe}from"three";function ve(e,t){const r=Ce(e),n=function(e,t){const r=e.format,n=e.type,i=e.colorSpace===he;let a=null;if(Pe(e))switch(r){case ae:case Y:a=i?"bc1-rgba-unorm-srgb":"bc1-rgba-unorm";break;case X:a=i?"bc2-rgba-unorm-srgb":"bc2-rgba-unorm";break;case J:a=i?"bc3-rgba-unorm-srgb":"bc3-rgba-unorm";break;case z:a="bc4-r-unorm";break;case de:a="bc4-r-snorm";break;case L:a="bc5-rg-unorm";break;case ue:a="bc5-rg-snorm";break;case K:a=i?"bc7-rgba-unorm-srgb":"bc7-rgba-unorm";break;case ie:case ne:a=i?"etc2-rgb8unorm-srgb":"etc2-rgb8unorm";break;case Z:a=i?"etc2-rgba8unorm-srgb":"etc2-rgba8unorm";break;case O:a=i?"astc-4x4-unorm-srgb":"astc-4x4-unorm";break;case $:a=i?"astc-5x4-unorm-srgb":"astc-5x4-unorm";break;case j:a=i?"astc-5x5-unorm-srgb":"astc-5x5-unorm";break;case N:a=i?"astc-6x5-unorm-srgb":"astc-6x5-unorm";break;case W:a=i?"astc-6x6-unorm-srgb":"astc-6x6-unorm";break;case _:a=i?"astc-8x5-unorm-srgb":"astc-8x5-unorm";break;case q:a=i?"astc-8x6-unorm-srgb":"astc-8x6-unorm";break;case H:a=i?"astc-8x8-unorm-srgb":"astc-8x8-unorm";break;case V:a=i?"astc-10x5-unorm-srgb":"astc-10x5-unorm";break;case A:a=i?"astc-10x6-unorm-srgb":"astc-10x6-unorm";break;case F:a=i?"astc-10x8-unorm-srgb":"astc-10x8-unorm";break;case U:a=i?"astc-10x10-unorm-srgb":"astc-10x10-unorm";break;case E:a=i?"astc-12x10-unorm-srgb":"astc-12x10-unorm";break;case k:a=i?"astc-12x12-unorm-srgb":"astc-12x12-unorm";break;case Q:a=i?"rgba8unorm-srgb":"rgba8unorm"}else switch(r){case Q:switch(n){case B:a="rgba8snorm";break;case ce:a="rgba16sint";break;case xe:a="rgba16uint";break;case ge:a="rgba32uint";break;case R:a="rgba32sint";break;case pe:a=i?"rgba8unorm-srgb":"rgba8unorm";break;case G:a="rgba16float";break;case I:a="rgba32float"}break;case se:switch(n){case me:a="rgb9e5ufloat";break;case 35899:a="rg11b10ufloat"}break;case oe:switch(n){case B:a="r8snorm";break;case ce:a="r16sint";break;case xe:a="r16uint";break;case ge:a="r32uint";break;case R:a="r32sint";break;case pe:a="r8unorm";break;case G:a="r16float";break;case I:a="r32float"}break;case te:switch(n){case B:a="rg8snorm";break;case ce:a="rg16sint";break;case xe:a="rg16uint";break;case ge:a="rg32uint";break;case R:a="rg32sint";break;case pe:a="rg8unorm";break;case G:a="rg16float";break;case I:a="rg32float"}break;case D:switch(n){case xe:a="depth16unorm";break;case ge:a="depth24plus";break;case I:a="depth32float"}break;case T:switch(n){case fe:a="depth24plus-stencil8";break;case I:Me("depth32float-stencil8",t,e,"DepthTexture with DepthStencilFormat + FloatType"),a="depth32float-stencil8"}break;case le:switch(n){case R:a="r32sint";break;case ge:a="r32uint"}break;case re:switch(n){case R:a="rg32sint";break;case ge:a="rg32uint"}break;case ee:switch(n){case R:a="rgba32sint";break;case ge:a="rgba32uint"}}if(!a)throw new Error(`Texture format "${r}" with type "${n}" from "${e.constructor.name}" is not supported by this renderer yet.`);const s=function(e){if(e.startsWith("bc"))return"texture-compression-bc";if(e.startsWith("etc2")||e.startsWith("eac"))return"texture-compression-etc2";if(e.startsWith("astc"))return"texture-compression-astc";return null}(a);s&&Me(s,t,e,`Texture format "${a}"`);return a}(e,t),i=function(e){const t=Se(e);if("cube"===t)return"cube";if("2d-array"===t)return"2d-array";if("3d"===t)return"3d";return"2d"}(e),a=function(e){return"3d"===Se(e)?"3d":"2d"}(e),s=function(e,t,r){if(!0===e.isDepthTexture)return"depth";if(t.endsWith("uint"))return"uint";if(t.endsWith("sint"))return"sint";if(!0===e.isDataTexture||!0===e.isDataArrayTexture||!0===e.isData3DTexture){if(e.type===R)return"sint";if(e.type===ge)return"uint";if(e.type===I&&!Be(r,"float32-filterable")&&("r32float"===t||"rg32float"===t||"rgba32float"===t))return"unfilterable-float"}return"float"}(e,n,t),o=function(e,t){const r=e.compareFunction;if("depth"===t&&null!=r)return"comparison";if("float"===t)return"filtering";return"non-filtering"}(e,s),l=function(e){if(!0===e.isCompressedCubeTexture){const t=e.image;return Math.max(1,t?.[0]?.mipmaps?.length??1)}const t=e.mipmaps;return Math.max(1,t?.length??1)}(e);return{format:n,textureDimension:a,viewDimension:i,sampleType:s,samplerBindingType:o,wgslTextureType:ye(i,s),wgslSamplerType:"comparison"===o?"sampler_comparison":"sampler",width:r.width,height:r.height,depthOrArrayLayers:r.depthOrArrayLayers,mipLevelCount:l,compressed:Pe(e)}}function we(e,t){const r=ve(e,t);return[r.format,r.textureDimension,r.viewDimension,r.sampleType,r.samplerBindingType,r.width,r.height,r.depthOrArrayLayers,r.mipLevelCount].join(":")}function be(e){const t=Ce(e),r=e.compareFunction;return[Se(e),e.format,e.type,e.colorSpace,r??"none",t.depthOrArrayLayers].join(":")}function ye(e,t){if("depth"===t)switch(e){case"2d-array":return"texture_depth_2d_array";case"cube":return"texture_depth_cube";default:return"texture_depth_2d"}const r="uint"===t?"u32":"sint"===t?"i32":"f32";switch(e){case"2d-array":return`texture_2d_array<${r}>`;case"cube":return`texture_cube<${r}>`;case"3d":return`texture_3d<${r}>`;default:return`texture_2d<${r}>`}}function Se(e){return!0===e.isCubeTexture?"cube":!0===e.isArrayTexture||!0===e.isDataArrayTexture||!0===e.isCompressedArrayTexture?"2d-array":!0===e.is3DTexture||!0===e.isData3DTexture?"3d":"2d"}function Ce(e){if(!0===e.isCubeTexture){const t=e.image,r=t?.[0],n=r?.image??r;return{width:n?.width??1,height:n?.height??1,depthOrArrayLayers:6}}const t=e.image;return{width:t?.width??1,height:t?.height??1,depthOrArrayLayers:t?.depth??1}}function Pe(e){return!0===e.isCompressedTexture||!0===e.isCompressedArrayTexture}function Me(e,t,r,n){if(!Be(t,e))throw new Error(`${n} for "${r.name||r.uuid}" requires the WebGPU feature "${e}", which is not enabled on this device.`)}function Be(e,t){return!!e&&(e instanceof Set?e.has(t):"features"in e?e.features.has(t):e.has(t))}import{Color as De,Matrix3 as Te,Matrix4 as Ie,Vector2 as Ge,Vector3 as Re,Vector4 as Le}from"three";var ze=new ArrayBuffer(8),Ue=new Float64Array(ze),Ve=new Uint32Array(ze),Ae={f32:{alignment:4,size:4},i32:{alignment:4,size:4},u32:{alignment:4,size:4},"vec2<f32>":{alignment:8,size:8},"vec3<f32>":{alignment:16,size:12},"vec4<f32>":{alignment:16,size:16},"mat3x3<f32>":{alignment:16,size:48},"mat4x4<f32>":{alignment:16,size:64}};function Fe(e,t){return Math.ceil(e/t)*t}function Ee(e,t){return"number"==typeof e||"boolean"==typeof e?[Number(e)]:Array.isArray(e)?Array.from(e.slice(0,t)):e instanceof De?t>=4?[e.r,e.g,e.b,1]:[e.r,e.g,e.b]:e instanceof Ge?[e.x,e.y]:e instanceof Re?[e.x,e.y,e.z]:e instanceof Le?[e.x,e.y,e.z,e.w]:e instanceof Te||e instanceof Ie?Array.from(e.elements):[]}function ke(e,t,r,n){const i="boolean"==typeof n?n?1:0:Number(n);"i32"!==r?"u32"!==r?e.setFloat32(t,i,!0):e.setUint32(t,i,!0):e.setInt32(t,i,!0)}function Oe(e,t,r,n){const i=Ee(r,n);for(let r=0;r<n;r+=1)e[t+r]=i[r]??0}function $e(e,t,r){const n=r instanceof Te?r.elements:Array.isArray(r)?Array.from(r):Ee(r,9);for(let r=0;r<3;r+=1){const i=3*r,a=t+4*r;e[a+0]=n[i+0]??0,e[a+1]=n[i+1]??0,e[a+2]=n[i+2]??0,e[a+3]=0}}function je(e){let t=0;const r=[];for(const[n,i]of Object.entries(e)){const e=Ae[i.type];t=Fe(t,e.alignment),r.push({name:n,offset:t,type:i.type}),t+=e.size}return{byteLength:Fe(t,16),entries:r}}function Ne(e,t){const r=new ArrayBuffer(t.byteLength),n=new DataView(r),i=new Float32Array(r);for(const r of t.entries){const t=e[r.name],a=r.offset/4;switch(r.type){case"f32":case"i32":case"u32":ke(n,r.offset,r.type,t.value);break;case"vec2<f32>":Oe(i,a,t.value,2);break;case"vec3<f32>":Oe(i,a,t.value,3);break;case"vec4<f32>":Oe(i,a,t.value,4);break;case"mat3x3<f32>":$e(i,a,t.value);break;case"mat4x4<f32>":if(t.value instanceof Ie)i.set(t.value.elements,a);else{const e=Ee(t.value,16);i.set(e,a)}}}return r}function We(e,t){let r=Math.imul(e^t,16777619);return r^=r>>>13,r>>>0}function _e(e,t){return Ue[0]=t,e=We(e,Ve[0]??0),e=We(e,Ve[1]??0)}function qe(e,t,r){const n=Ee(t,r);e=We(e,n.length);for(let t=0;t<n.length;t+=1)e=_e(e,n[t]??0);return e}var He="\nstruct FullscreenVertexOutput {\n @builtin(position) position: vec4<f32>,\n @location(0) uv: vec2<f32>,\n};\n\n@vertex\nfn vsMain(@builtin(vertex_index) vertexIndex: u32) -> FullscreenVertexOutput {\n var output: FullscreenVertexOutput;\n let position = array<vec2<f32>, 3>(\n vec2(-1.0, -3.0),\n vec2(-1.0, 1.0),\n vec2(3.0, 1.0),\n );\n let clip = position[vertexIndex];\n output.position = vec4(clip, 0.0, 1.0);\n output.uv = clip * vec2(0.5, -0.5) + vec2(0.5, 0.5);\n return output;\n}\n",Ke=new WeakMap,Ze=new WeakMap;function Ye(e){return e?"string"==typeof e?[e]:Array.from(e):[]}function Xe(e){return e.replace(/[^A-Za-z0-9_]/g,"_")}var Je=class{constructor(e){this.context=e}context;sceneColor="sceneColor";mainDepth="mainDepth";postProcessColor="postProcessColor";createColorTarget(e,t={}){return this.context.defineColorTarget(e,t),e}createTextureTarget(e,t={}){return this.context.defineTextureTarget(e,t),e}addStandardScenePasses(e=this.sceneColor){this.context.addDirectionalShadowPass(),this.context.addPointShadowPass(),this.context.addSpotShadowPass(),this.context.addDepthPrepass(),this.context.addHiZPasses(),this.context.addVisibilityPass(),this.context.addOpaquePass(e),this.context.addHiZHistoryPass("OpaquePass"),this.context.addSceneTextureCopyPass(e),this.context.addLatePass(e)}addDirectionalShadowPass(){this.context.addDirectionalShadowPass()}addPointShadowPass(){this.context.addPointShadowPass()}addSpotShadowPass(){this.context.addSpotShadowPass()}addDepthPrepass(){this.context.addDepthPrepass()}addHiZPasses(){this.context.addHiZPasses()}addVisibilityPass(){this.context.addVisibilityPass()}addForwardPass(e=this.sceneColor){this.context.addForwardPass(e)}addOpaquePass(e=this.sceneColor){this.context.addOpaquePass(e)}addSceneTextureCopyPass(e=this.sceneColor){this.context.addSceneTextureCopyPass(e)}addLatePass(e=this.sceneColor){this.context.addLatePass(e)}addHiZHistoryPass(e="ForwardPass"){this.context.addHiZHistoryPass(e)}addMaterialPass(e={}){const t={name:e.name,outputs:e.outputs??this.sceneColor,drawStage:e.drawStage,loadColor:e.loadColor,loadDepth:e.loadDepth,objectFilter:e.objectFilter,overrideMaterial:e.overrideMaterial};this.context.addMaterialPass(t)}addPass(e){const t=e.inputs?Object.values(e.inputs):void 0,r=Ye(e.outputs),n={name:e.name,reads:t,writes:r.length>0?r:void 0,dependsOn:e.dependsOn,execute:e.execute};this.context.addCustomPass(n)}addFullscreenPass(e){const t=Ye(e.outputs),r=Object.entries(e.inputs),n=Object.entries(e.textures??{});for(const[t]of n)if(t in e.inputs)throw new Error(`Fullscreen pass "${e.name}" cannot use "${t}" as both an input and an external texture.`);const i=r.map(([,e])=>e===this.mainDepth?"depth":"color");this.addPass({name:e.name,inputs:e.inputs,outputs:t,execute:a=>{const s=t.map(e=>a.getColorFormat(e)),o=n.map(([,e])=>ve(e,a.device)),l=n.map(([,e])=>we(e,a.device)).join("|"),c=r.map(([t])=>e.inputDimensions?.[t]??"2d"),u=`${s.join("|")}:${i.map((e,t)=>`${e}-${c[t]}`).join("|")}:${l}:${e.uniformBufferSize??0}`,d=function(e,t){let r=Ke.get(e);r||(r=new WeakMap,Ke.set(e,r));let n=r.get(t);return n||(n=new Map,r.set(t,n)),n}(e,a.device);let h=d.get(u);if(!h){const t=[He,"@group(0) @binding(0) var fullscreenSampler: sampler;",r.map(([e],t)=>`@group(0) @binding(${t+1}) var ${e}Texture: ${"depth"===i[t]?"texture_depth_2d":"3d"===c[t]?"texture_3d<f32>":"texture_2d<f32>"};`).join("\n"),n.map(([e],t)=>{const n=r.length+1+2*t,i=o[t];return`@group(0) @binding(${n}) var ${e}Sampler: ${i.wgslSamplerType};\n@group(0) @binding(${n+1}) var ${e}Texture: ${i.wgslTextureType};`}).join("\n"),e.uniformBufferSize?`@group(0) @binding(${r.length+1+2*n.length}) var<uniform> fullscreenUniforms: array<vec4<f32>, ${Math.max(1,Math.ceil(e.uniformBufferSize/16))}>;`:"",e.fragmentShader].filter(Boolean).join("\n\n"),l=a.device.createBindGroupLayout({label:`${e.name}-layout`,entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"nearest"===e.sampler?"non-filtering":"filtering"}},...r.map((e,t)=>({binding:t+1,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"depth"===i[t]?"depth":"float",viewDimension:"3d"===c[t]?"3d":"2d"}})),...o.flatMap((e,t)=>{const n=r.length+1+2*t;return[{binding:n,visibility:GPUShaderStage.FRAGMENT,sampler:{type:e.samplerBindingType}},{binding:n+1,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:e.sampleType,viewDimension:e.viewDimension}}]}),...e.uniformBufferSize?[{binding:r.length+1+2*n.length,visibility:GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}}]:[]]}),p=a.device.createPipelineLayout({label:`${e.name}-pipeline-layout`,bindGroupLayouts:[l]});h={bindGroupLayout:l,pipeline:a.device.createRenderPipeline({label:`${e.name}-pipeline`,layout:p,vertex:{module:a.device.createShaderModule({label:`${e.name}-vertex-module`,code:t}),entryPoint:"vsMain"},fragment:{module:a.device.createShaderModule({label:`${e.name}-fragment-module`,code:t}),entryPoint:"fsMain",targets:s.map(e=>({format:e}))},primitive:{topology:"triangle-list"}}),uniformBuffer:e.uniformBufferSize?a.device.createBuffer({label:`${e.name}-uniform-buffer`,size:16*Math.ceil(Math.max(16,e.uniformBufferSize)/16),usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}):null},d.set(u,h)}const{bindGroupLayout:p,pipeline:f,uniformBuffer:m}=h,g=e.updateUniforms?.(a)??null;m&&g&&a.device.queue.writeBuffer(m,0,g.buffer,g.byteOffset,g.byteLength);const x=[{binding:0,resource:"nearest"===e.sampler||"linear"!==e.sampler&&i.includes("depth")?a.nearestClampSampler:a.linearClampSampler},...r.map(([,e],t)=>({binding:t+1,resource:"depth"===i[t]?a.depthView:a.getColorView(e)}))];for(let e=0;e<n.length;e+=1){const t=a.getExternalTexture(n[e][1]),i=r.length+1+2*e;x.push({binding:i,resource:t.sampler},{binding:i+1,resource:t.view})}m&&x.push({binding:r.length+1+2*n.length,resource:{buffer:m}});const v=a.device.createBindGroup({label:`${e.name}-bind-group`,layout:p,entries:x}),w=a.encoder.beginRenderPass({label:e.name,colorAttachments:t.map(e=>({view:a.getColorView(e),clearValue:{r:0,g:0,b:0,a:1},loadOp:"clear",storeOp:"store"}))});w.setPipeline(f),w.setBindGroup(0,v),w.draw(3),w.end()}})}addNodeFullscreenPass(e){const t=Ye(e.outputs),r=Object.entries(function(e){const t={};for(const[r,n]of Object.entries(e.sceneTextures??{}))t[r]="sceneDepth"===n?{resource:"mainDepth",dimension:"depth-2d",sampleType:"depth",sampler:"non-filtering"}:{resource:"sceneColor",dimension:"2d",sampleType:"float",sampler:"filtering"};return{...t,...e.graphTextures}}(e.shader)).map(([t,r])=>[t,null!=e.inputOverrides?.[t]?{...r,resource:e.inputOverrides[t]}:r]),n=Object.entries(e.shader.textures??{}),i=Object.fromEntries(r.map(([e,t])=>[e,t.resource])),a=je(e.shader.uniforms);this.addPass({name:e.name,inputs:i,outputs:t,execute:i=>{const s=t.map(e=>i.getColorFormat(e)),o=r.map(([e,t])=>`${e}:${t.dimension}:${t.sampleType}:${t.sampler??"filtering"}`).join("|"),l=n.map(([,e])=>ve(e,i.device)),c=n.map(([,e])=>we(e,i.device)).join("|"),u=a.entries.map(e=>`${e.name}:${e.type}:${e.offset}`).join("|"),d=`${s.join("|")}:${o}:${c}:${u}`,h=function(e,t){let r=Ze.get(e);r||(r=new WeakMap,Ze.set(e,r));let n=r.get(t);return n||(n=new Map,r.set(t,n)),n}(e.shader,i.device);let p=h.get(d);if(!p){const t=[];for(const[,e]of r){const r=t.length;t.push({binding:r,visibility:GPUShaderStage.FRAGMENT,sampler:{type:e.sampler??("depth-2d"===e.dimension?"non-filtering":"filtering")}},{binding:r+1,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:e.sampleType??("depth-2d"===e.dimension?"depth":"float"),viewDimension:"3d"===e.dimension?"3d":"2d"}})}for(const[e,r]of l.entries()){const e=t.length;t.push({binding:e,visibility:GPUShaderStage.FRAGMENT,sampler:{type:r.samplerBindingType}},{binding:e+1,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:r.sampleType,viewDimension:r.viewDimension}})}const o=2*(r.length+n.length);a.byteLength>0&&t.push({binding:o,visibility:GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}});const c=i.device.createBindGroupLayout({label:`${e.name}-node-layout`,entries:t}),u=i.device.createPipelineLayout({label:`${e.name}-node-pipeline-layout`,bindGroupLayouts:[c]}),f=r.map(([e,t],r)=>{const n=Xe(e);return`@group(0) @binding(${2*r}) var ${n}Sampler: ${"comparison"===t.sampler?"sampler_comparison":"sampler"};\n@group(0) @binding(${2*r+1}) var ${n}Texture: ${"depth-2d"===t.dimension?"texture_depth_2d":"3d"===t.dimension?"texture_3d<f32>":"texture_2d<f32>"};`}).join("\n"),m=n.map(([e],t)=>{const n=2*(r.length+t),i=l[t],a=Xe(e);return`@group(0) @binding(${n}) var ${a}Sampler: ${i.wgslSamplerType};\n@group(0) @binding(${n+1}) var ${a}Texture: ${i.wgslTextureType};`}).join("\n"),g=a.entries.map(e=>` ${Xe(e.name)}: ${e.type},`).join("\n"),x=a.byteLength>0?`struct MaterialUniforms {\n${g}\n};\n@group(0) @binding(${o}) var<uniform> materialUniforms: MaterialUniforms;`:"",v=[He,f,m,x,e.shader.fragmentShader].filter(Boolean).join("\n\n");p={bindGroupLayout:c,pipeline:i.device.createRenderPipeline({label:`${e.name}-node-pipeline`,layout:u,vertex:{module:i.device.createShaderModule({label:`${e.name}-node-vertex-module`,code:v}),entryPoint:"vsMain"},fragment:{module:i.device.createShaderModule({label:`${e.name}-node-fragment-module`,code:v}),entryPoint:"fsMain",targets:s.map(e=>({format:e}))},primitive:{topology:"triangle-list"}}),uniformBuffer:a.byteLength>0?i.device.createBuffer({label:`${e.name}-node-uniforms`,size:a.byteLength,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}):null},h.set(d,p)}const{pipeline:f,bindGroupLayout:m,uniformBuffer:g}=p;e.shader.syncLiveUniforms(e.shader.uniforms),g&&i.device.queue.writeBuffer(g,0,Ne(e.shader.uniforms,a));const x=[];for(const[,e]of r){const t=x.length,r="comparison"===e.sampler?i.comparisonSampler:"non-filtering"===e.sampler||"depth-2d"===e.dimension?i.nearestClampSampler:i.linearClampSampler;x.push({binding:t,resource:r},{binding:t+1,resource:i.getTextureView(e.resource)})}for(const[,e]of n){const t=x.length,r=i.getExternalTexture(e);x.push({binding:t,resource:r.sampler},{binding:t+1,resource:r.view})}g&&x.push({binding:2*(r.length+n.length),resource:{buffer:g}});const v=i.device.createBindGroup({label:`${e.name}-node-bind-group`,layout:m,entries:x}),w=i.encoder.beginRenderPass({label:e.name,colorAttachments:t.map(e=>({view:i.getColorView(e),clearValue:{r:0,g:0,b:0,a:1},loadOp:"clear",storeOp:"store"}))});w.setPipeline(f),w.setBindGroup(0,v),w.draw(3),w.end()}})}present(e=this.sceneColor){this.context.addPresentPass(e)}};import{AdditiveBlending as Qe,BackSide as et,BufferAttribute as tt,BufferGeometry as rt,Color as nt,DoubleSide as it,FrontSide as at,InstancedBufferAttribute as st,MultiplyBlending as ot,Matrix4 as lt,Mesh as ct,OrthographicCamera as ut,PerspectiveCamera as dt,Sphere as ht,SubtractiveBlending as pt,Vector2 as ft,Vector3 as mt,Vector4 as gt,ShaderMaterial as xt}from"three";var vt=/^[A-Za-z_][A-Za-z0-9_]*$/;function wt(e,t={},r={}){const n=function(e){const t=new Map;for(const[r,n]of Object.entries(e))vt.test(r)&&!1!==n&&null!=n&&t.set(r,{name:r,parameters:null,body:bt(n)});return t}(t),i=[],a=[],s=e.split(/\r?\n/),o=r.sourceName??"shader";for(let e=0;e<s.length;e+=1){const t=s[e],r=yt(t),l=Ct(i);if(!r){a.push(l?Mt(t,n):"");continue}const{name:c,rest:u}=r;switch(c){case"define":l&&St(u,n,o,e+1),a.push("");break;case"undef":l&&n.delete(u.trim()),a.push("");break;case"ifdef":{const e=l,t=e&&n.has(u.trim());i.push({parentActive:e,active:t,branchTaken:t,elseSeen:!1}),a.push("");break}case"ifndef":{const e=l,t=e&&!n.has(u.trim());i.push({parentActive:e,active:t,branchTaken:t,elseSeen:!1}),a.push("");break}case"if":{const e=l,t=e&&zt(u,n);i.push({parentActive:e,active:t,branchTaken:t,elseSeen:!1}),a.push("");break}case"elif":{const t=Pt(i,o,e+1,c);if(t.elseSeen)throw new Error(`${o}:${e+1}: #elif after #else`);const r=t.parentActive&&!t.branchTaken&&zt(u,n);t.active=r,t.branchTaken=t.branchTaken||r,a.push("");break}case"else":{const t=Pt(i,o,e+1,c);if(t.elseSeen)throw new Error(`${o}:${e+1}: duplicate #else`);t.active=t.parentActive&&!t.branchTaken,t.branchTaken=!0,t.elseSeen=!0,a.push("");break}case"endif":Pt(i,o,e+1,c),i.pop(),a.push("");break;case"error":if(l)throw new Error(`${o}:${e+1}: ${u.trim()||"#error"}`);a.push("");break;case"warning":case"line":case"version":case"pragma":a.push("");break;default:if(l)throw new Error(`${o}:${e+1}: unsupported preprocessor directive #${c}`);a.push("")}}if(i.length>0)throw new Error(`${o}: unterminated preprocessor conditional`);return a.join("\n")}function bt(e){return"boolean"==typeof e?e?"1":"0":String(e)}function yt(e){const t=/^\s*#\s*([A-Za-z_][A-Za-z0-9_]*)(.*)$/.exec(e);return t?{name:t[1],rest:t[2]??""}:null}function St(e,t,r,n){const i=/^\s*([A-Za-z_][A-Za-z0-9_]*)(.*)$/.exec(e);if(!i)throw new Error(`${r}:${n}: invalid #define`);const a=i[1],s=i[2]??"";if(s.startsWith("(")){const e=Lt(s,0);if(e<0)throw new Error(`${r}:${n}: invalid function-like #define ${a}`);const i=s.slice(1,e).trim(),o=0===i.length?[]:i.split(",").map(e=>e.trim());for(const e of o)if(!vt.test(e))throw new Error(`${r}:${n}: invalid macro parameter "${e}"`);return void t.set(a,{name:a,parameters:o,body:Vt(s.slice(e+1)).trim()||"1"})}t.set(a,{name:a,parameters:null,body:Vt(s).trim()||"1"})}function Ct(e){for(const t of e)if(!t.active)return!1;return!0}function Pt(e,t,r,n){const i=e[e.length-1];if(!i)throw new Error(`${t}:${r}: #${n} without matching #if`);return i}function Mt(e,t){let r=e;for(let e=0;e<8;e+=1){const e=r;if(r=Dt(r,t),r=Bt(r,t),r===e)return r}return r}function Bt(e,t){return e.replace(/\b[A-Za-z_][A-Za-z0-9_]*\b/g,e=>{const r=t.get(e);return r&&null===r.parameters?r.body:e})}function Dt(e,t){let r=e;for(const e of t.values())null!==e.parameters&&(r=Tt(r,e));return r}function Tt(e,t){let r="",n=0;for(;n<e.length;){const i=It(e,t.name,n);if(i<0){r+=e.slice(n);break}let a=i+t.name.length;for(;/\s/.test(e[a]??"");)a+=1;if("("!==e[a]){r+=e.slice(n,i+t.name.length),n=i+t.name.length;continue}const s=Lt(e,a);if(s<0){r+=e.slice(n);break}const o=Rt(e.slice(a+1,s));r+=e.slice(n,i),r+=Gt(t,o),n=s+1}return r}function It(e,t,r){let n=e.indexOf(t,r);for(;n>=0;){const r=n>0?e[n-1]:"",i=e[n+t.length]??"";if(!/[A-Za-z0-9_]/.test(r)&&!/[A-Za-z0-9_]/.test(i))return n;n=e.indexOf(t,n+t.length)}return-1}function Gt(e,t){let r=e.body;const n=e.parameters??[];for(let e=0;e<n.length;e+=1){const i=n[e],a=t[e]?.trim()??"";r=r.replace(new RegExp(`\\b${At(i)}\\b`,"g"),a)}return r}function Rt(e){const t=[];let r=0,n=0;for(let i=0;i<e.length;i+=1){const a=e[i];"("===a?r+=1:")"===a?r-=1:","===a&&0===r&&(t.push(e.slice(n,i)),n=i+1)}return(e.length>0||n>0)&&t.push(e.slice(n)),t}function Lt(e,t){let r=0;for(let n=t;n<e.length;n+=1){const t=e[n];if("("===t)r+=1;else if(")"===t&&(r-=1,0===r))return n}return-1}function zt(e,t){const r=function(e){const t=[];let r=0;for(;r<e.length;){const n=e[r];if(/\s/.test(n)){r+=1;continue}const i=e.slice(r,r+2);if(["&&","||","==","!=","<=",">="].includes(i)){t.push({type:"operator",value:i}),r+=2;continue}if("!<>+-*/%".includes(n)){t.push({type:"operator",value:n}),r+=1;continue}if("("===n||")"===n){t.push({type:"paren",value:n}),r+=1;continue}const a=/^(?:0x[0-9A-Fa-f]+|\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)/.exec(e.slice(r));if(a){t.push({type:"number",value:a[0]}),r+=a[0].length;continue}const s=/^[A-Za-z_][A-Za-z0-9_]*/.exec(e.slice(r));s?(t.push({type:"identifier",value:s[0]}),r+=s[0].length):r+=1}return t}(Vt(e));return 0!==new Ut(r,t).parseExpression()}var Ut=class{constructor(e,t){this.tokens=e,this.macros=t}tokens;macros;cursor=0;parseExpression(){return this.parseLogicalOr()}parseLogicalOr(){let e=this.parseLogicalAnd();for(;this.consumeOperator("||");){const t=this.parseLogicalAnd();e=0!==e||0!==t?1:0}return e}parseLogicalAnd(){let e=this.parseEquality();for(;this.consumeOperator("&&");){const t=this.parseEquality();e=0!==e&&0!==t?1:0}return e}parseEquality(){let e=this.parseComparison();for(;;)if(this.consumeOperator("=="))e=e===this.parseComparison()?1:0;else{if(!this.consumeOperator("!="))return e;e=e!==this.parseComparison()?1:0}}parseComparison(){let e=this.parseAdditive();for(;;)if(this.consumeOperator("<"))e=e<this.parseAdditive()?1:0;else if(this.consumeOperator(">"))e=e>this.parseAdditive()?1:0;else if(this.consumeOperator("<="))e=e<=this.parseAdditive()?1:0;else{if(!this.consumeOperator(">="))return e;e=e>=this.parseAdditive()?1:0}}parseAdditive(){let e=this.parseMultiplicative();for(;;)if(this.consumeOperator("+"))e+=this.parseMultiplicative();else{if(!this.consumeOperator("-"))return e;e-=this.parseMultiplicative()}}parseMultiplicative(){let e=this.parseUnary();for(;;)if(this.consumeOperator("*"))e*=this.parseUnary();else if(this.consumeOperator("/"))e/=this.parseUnary();else{if(!this.consumeOperator("%"))return e;e%=this.parseUnary()}}parseUnary(){return this.consumeOperator("!")?0===this.parseUnary()?1:0:this.consumeOperator("-")?-this.parseUnary():this.consumeOperator("+")?this.parseUnary():this.parsePrimary()}parsePrimary(){const e=this.peek();if(!e)return 0;if("number"===e.type)return this.cursor+=1,e.value.startsWith("0x")?Number.parseInt(e.value,16):Number.parseFloat(e.value);if("identifier"===e.type&&"defined"===e.value){if(this.cursor+=1,this.consumeParen("(")){const e=this.consumeIdentifier();return this.consumeParen(")"),e&&this.macros.has(e)?1:0}const e=this.consumeIdentifier();return e&&this.macros.has(e)?1:0}if("identifier"===e.type)return this.cursor+=1,function(e){if(!e)return 0;const t=e.body.trim();if("true"===t)return 1;if("false"===t)return 0;const r=t.startsWith("0x")?Number.parseInt(t,16):Number.parseFloat(t);return Number.isFinite(r)?r:1}(this.macros.get(e.value));if(this.consumeParen("(")){const e=this.parseExpression();return this.consumeParen(")"),e}return this.cursor+=1,0}consumeIdentifier(){const e=this.peek();return"identifier"!==e?.type?null:(this.cursor+=1,e.value)}consumeOperator(e){const t=this.peek();return"operator"===t?.type&&t.value===e&&(this.cursor+=1,!0)}consumeParen(e){const t=this.peek();return"paren"===t?.type&&t.value===e&&(this.cursor+=1,!0)}peek(){return this.tokens[this.cursor]}};function Vt(e){const t=e.indexOf("//");return t>=0?e.slice(0,t):e}function At(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}import{Material as Ft}from"three";var Et=[{name:"position",shaderLocation:0,format:"float32x3"},{name:"normal",shaderLocation:1,format:"float32x3",defaultValue:[0,0,1]},{name:"uv",shaderLocation:2,format:"float32x2",defaultValue:[0,0]},{name:"color",shaderLocation:3,format:"float32x4",defaultValue:[1,1,1,1]}],kt=class e extends Ft{isWGSLShaderMaterial=!0;vertexShader;fragmentShader;depthVertexShader;depthFragmentShader;pointShadowVertexShader;pointShadowFragmentShader;defines;uniforms;textures;sceneTextures;graphTextures;storageBuffers;vertexAttributes;primitiveTopology;wireframe;uniformLayoutCache=null;programCacheKeyCache=null;textureListCache=null;textureVersionsCache=[];textureVersionHashCache=0;storageBufferBindingListCache=null;storageBufferListCache=null;textureLayoutKeyDeviceCache=null;textureLayoutKeyCache=null;constructor(e){super();const{vertexShader:t,fragmentShader:r,depthVertexShader:n,depthFragmentShader:i,pointShadowVertexShader:a,pointShadowFragmentShader:s,defines:o,uniforms:l,textures:c,sceneTextures:u,graphTextures:d,storageBuffers:h,vertexAttributes:p,primitiveTopology:f,wireframe:m,...g}=e,x=function(e,t){const r={},n={...t};for(const[t,i]of Object.entries(e)){const e=Nt(t,i);"texture"!==e.kind?r[t]=e.uniform:n[t]=e.texture}return{uniforms:r,textures:n}}(l??{},c??{});this.type="WGSLShaderMaterial",this.vertexShader=t,this.fragmentShader=r,this.depthVertexShader=n??null,this.depthFragmentShader=i??null,this.pointShadowVertexShader=a??null,this.pointShadowFragmentShader=s??null,this.defines={...o??{}},this.uniforms=x.uniforms,this.textures=x.textures,this.sceneTextures={...u??{}},this.graphTextures={...d??{}},this.storageBuffers={...h??{}},this.vertexAttributes=$t(p??Et),this.primitiveTopology=f??"triangle-list",this.wireframe=m??!1,this.transparent=g.transparent??!1,this.depthTest=g.depthTest??!0,this.depthWrite=g.depthWrite??!0,this.setValues(g)}getUniformLayout(){return null===this.uniformLayoutCache&&(this.uniformLayoutCache=je(this.uniforms)),this.uniformLayoutCache}setUniform(e,t){const r=Nt(e,t);return"texture"===r.kind?(delete this.uniforms[e],this.textures[e]=r.texture,this.uniformLayoutCache=null,this.invalidateBindingCache(),this.invalidateProgramStructureCache(),this.needsUpdate=!0,this):(delete this.textures[e],this.uniforms[e]=r.uniform,this.uniformLayoutCache=null,this.invalidateBindingCache(),this.invalidateProgramStructureCache(),this.needsUpdate=!0,this)}setDefine(e,t=!0){return this.defines[e]=t,this.invalidateProgramStructureCache(),this.needsUpdate=!0,this}deleteDefine(e){return delete this.defines[e],this.invalidateProgramStructureCache(),this.needsUpdate=!0,this}setTexture(e,t){return delete this.uniforms[e],this.textures[e]=t,this.uniformLayoutCache=null,this.invalidateBindingCache(),this.invalidateProgramStructureCache(),this.needsUpdate=!0,this}setStorageBuffer(e,t){return this.storageBuffers[e]=t,this.invalidateBindingCache(),this.invalidateProgramStructureCache(),this.needsUpdate=!0,this}setVertexAttributes(e){return this.vertexAttributes=$t(e),this.invalidateProgramStructureCache(),this.needsUpdate=!0,this}copy(e){return super.copy(e),this.vertexShader=e.vertexShader,this.fragmentShader=e.fragmentShader,this.depthVertexShader=e.depthVertexShader,this.depthFragmentShader=e.depthFragmentShader,this.pointShadowVertexShader=e.pointShadowVertexShader,this.pointShadowFragmentShader=e.pointShadowFragmentShader,this.defines={...e.defines},this.uniforms=Object.fromEntries(Object.entries(e.uniforms).map(([e,t])=>[e,{type:t.type,value:jt(t.value)}])),this.textures={...e.textures},this.sceneTextures={...e.sceneTextures},this.graphTextures={...e.graphTextures},this.storageBuffers={...e.storageBuffers},this.vertexAttributes=$t(e.vertexAttributes),this.primitiveTopology=e.primitiveTopology,this.wireframe=e.wireframe,this.uniformLayoutCache=null,this.invalidateBindingCache(),this.invalidateProgramStructureCache(),this}clone(){return new e({vertexShader:this.vertexShader,fragmentShader:this.fragmentShader}).copy(this)}customProgramCacheKey(){if(null!==this.programCacheKeyCache)return this.programCacheKeyCache;const e=Object.keys(this.defines).sort((e,t)=>e.localeCompare(t));let t=`vertex:${this.vertexShader};fragment:${this.fragmentShader};depthVertex:${this.depthVertexShader??""};depthFragment:${this.depthFragmentShader??""};pointShadowVertex:${this.pointShadowVertexShader??""};pointShadowFragment:${this.pointShadowFragmentShader??""};`;for(const r of e)t+=`${r}:${String(this.defines[r])};`;for(const e in this.uniforms)t+=`uniform:${e}:${this.uniforms[e].type};`;for(const[e,r]of Object.entries(this.textures))t+=`texture:${e}:${be(r)};`;for(const[e,r]of Object.entries(this.sceneTextures))t+=`sceneTexture:${e}:${r};`;for(const[e,r]of Object.entries(this.getGraphTextureInputs()))t+=`graphTexture:${e}:${r.resource}:${r.dimension}:${r.sampleType??"float"}:${r.sampler??"filtering"}:${Number(r.requiresLatePass??!1)};`;for(const[e,r]of Object.entries(this.storageBuffers))t+=`storage:${e}:${r.type}:${r.visibility??"fragment"};`;for(const e of this.vertexAttributes){const r=e.defaultValue?e.defaultValue.join(","):"";t+=`attribute:${e.name}:${e.shaderLocation}:${e.format}:${e.stepMode??"vertex"}:${r};`}return t+=`topology:${this.primitiveTopology};wireframe:${Number(this.wireframe)};transparent:${Number(this.transparent)};blending:${this.blending};premultipliedAlpha:${Number(this.premultipliedAlpha)};blendSrc:${this.blendSrc};blendDst:${this.blendDst};blendEquation:${this.blendEquation};blendSrcAlpha:${this.blendSrcAlpha};blendDstAlpha:${this.blendDstAlpha};blendEquationAlpha:${this.blendEquationAlpha};depthWrite:${Number(this.depthWrite)};depthTest:${Number(this.depthTest)};side:${String(this.side)};shadowSide:${String(this.shadowSide)};`,this.programCacheKeyCache=t,this.programCacheKeyCache}getTexturesList(){return null===this.textureListCache&&(this.textureListCache=Object.values(this.textures)),this.textureListCache}usesSceneTextures(){return Object.keys(this.sceneTextures).length>0||Object.values(this.graphTextures).some(e=>"sceneColorSnapshot"===e.resource||"sceneDepthSnapshot"===e.resource)}getGraphTextureInputs(){const e={...this.graphTextures};for(const[t,r]of Object.entries(this.sceneTextures))e[t]="sceneDepth"===r?{resource:"sceneDepthSnapshot",dimension:"depth-2d",sampleType:"depth",sampler:"non-filtering",requiresLatePass:!0}:{resource:"sceneColorSnapshot",dimension:"2d",sampleType:"float",sampler:"filtering",requiresLatePass:!0};return e}requiresLatePass(){return Object.values(this.getGraphTextureInputs()).some(e=>!0===e.requiresLatePass)}getUniformValueHash(){return function(e,t){let r=2166136261;for(let n=0;n<t.entries.length;n+=1){const i=t.entries[n],a=e[i.name];if(a)switch(r=We(r,i.offset),i.type){case"f32":case"i32":case"u32":r=_e(r,"boolean"==typeof a.value?a.value?1:0:Number(a.value));break;case"vec2<f32>":r=qe(r,a.value,2);break;case"vec3<f32>":r=qe(r,a.value,3);break;case"vec4<f32>":r=qe(r,a.value,4);break;case"mat3x3<f32>":r=qe(r,a.value,9);break;case"mat4x4<f32>":r=qe(r,a.value,16);break;default:r=We(r,n+17)}else r=We(r,n+1)}return r>>>0}(this.uniforms,this.getUniformLayout())}getTextureVersionsList(){const e=this.getTexturesList(),t=this.textureVersionsCache;t.length=e.length;let r=2166136261;for(let n=0;n<e.length;n+=1){const i=e[n].version;t[n]=i,r=Math.imul((r^i)>>>0,16777619)>>>0}return this.textureVersionHashCache=r,t}getTextureVersionHash(){return this.getTextureVersionsList(),this.textureVersionHashCache}getStorageBufferBindingList(){return null===this.storageBufferBindingListCache&&(this.storageBufferBindingListCache=Object.values(this.storageBuffers)),this.storageBufferBindingListCache}getStorageBufferList(){if(null===this.storageBufferListCache){const e=this.getStorageBufferBindingList();this.storageBufferListCache=e.map(e=>e.buffer)}return this.storageBufferListCache}getTextureLayoutKey(e){return null!==this.textureLayoutKeyCache&&this.textureLayoutKeyDeviceCache===e||(this.textureLayoutKeyDeviceCache=e,this.textureLayoutKeyCache=this.getTexturesList().map(t=>we(t,e)).join("|")),this.textureLayoutKeyCache}invalidateProgramStructureCache(){this.programCacheKeyCache=null}invalidateBindingCache(){this.textureListCache=null,this.textureVersionsCache.length=0,this.textureVersionHashCache=0,this.storageBufferBindingListCache=null,this.storageBufferListCache=null,this.textureLayoutKeyDeviceCache=null,this.textureLayoutKeyCache=null}};function Ot(e){return!0===e.isWGSLShaderMaterial}function $t(e){return e.map(e=>({name:e.name,shaderLocation:e.shaderLocation,format:e.format,stepMode:e.stepMode,defaultValue:e.defaultValue?Array.from(e.defaultValue):void 0}))}function jt(e){return Array.isArray(e)?Array.from(e):"number"==typeof e||"boolean"==typeof e?e:e.clone()}function Nt(e,t){const r=_t(t)?t:null,n=null!==r&&"value"in r?r.value:t;if(function(e){return Wt(e,"isTexture")}(n))return{kind:"texture",texture:n};if(!function(e){return"number"==typeof e||"boolean"==typeof e||Array.isArray(e)||Wt(e,"isColor")||Wt(e,"isVector2")||Wt(e,"isVector3")||Wt(e,"isVector4")||Wt(e,"isMatrix3")||Wt(e,"isMatrix4")}(n))throw new Error(`Unsupported WGSLShaderMaterial uniform "${e}". Use a number, boolean, vector, color, matrix, numeric array, or Texture.`);const i=r?.type,a=function(e){return"f32"===e||"i32"===e||"u32"===e||"vec2<f32>"===e||"vec3<f32>"===e||"vec4<f32>"===e||"mat3x3<f32>"===e||"mat4x4<f32>"===e}(i)?i:function(e,t){if("number"==typeof t)return"f32";if("boolean"==typeof t)return"u32";if(Array.isArray(t)){if(t.length<=1)return"f32";if(2===t.length)return"vec2<f32>";if(3===t.length)return"vec3<f32>";if(4===t.length)return"vec4<f32>";if(9===t.length)return"mat3x3<f32>";if(16===t.length)return"mat4x4<f32>";throw new Error(`Cannot infer WGSL type for uniform "${e}" from an array of length ${t.length}. Provide an explicit type.`)}if(Wt(t,"isColor"))return"vec3<f32>";if(Wt(t,"isVector2"))return"vec2<f32>";if(Wt(t,"isVector3"))return"vec3<f32>";if(Wt(t,"isVector4"))return"vec4<f32>";if(Wt(t,"isMatrix3"))return"mat3x3<f32>";if(Wt(t,"isMatrix4"))return"mat4x4<f32>";throw new Error(`Cannot infer WGSL type for uniform "${e}". Provide an explicit type.`)}(e,n);return{kind:"uniform",uniform:{type:a,value:n}}}function Wt(e,t){return _t(e)&&!0===e[t]}function _t(e){return"object"==typeof e&&null!==e}var qt=class{passes=[];addPass(e){this.passes.push(e)}async executeAsync(e,t){const r=this.resolveExecutionOrder(),n=performance.now();t?.begin?.(r,e);for(let n=0;n<r.length;n+=1){const i=r[n];t?.beforePass?.(i,n,e);const a=performance.now();await(i.prepare?.(e)),i.execute(e),t?.afterPass?.(i,n,performance.now()-a,e)}t?.end?.(r,performance.now()-n,e)}execute(e,t){const r=this.resolveExecutionOrder(),n=performance.now();t?.begin?.(r,e);for(let n=0;n<r.length;n+=1){const i=r[n];t?.beforePass?.(i,n,e);const a=performance.now();i.execute(e),t?.afterPass?.(i,n,performance.now()-a,e)}t?.end?.(r,performance.now()-n,e)}reset(){this.passes.length=0}resolveExecutionOrder(){const e=new Map,t=new Map,r=new Map,n=new Map;for(const n of this.passes)e.set(n.name,n),t.set(n.name,new Set(n.dependsOn??[])),r.set(n.name,new Set);for(const e of this.passes){const r=t.get(e.name);for(const t of e.reads??[]){const i=n.get(t);i&&i!==e.name&&r.add(i)}for(const t of e.writes??[]){const i=n.get(t);i&&i!==e.name&&r.add(i),n.set(t,e.name)}}for(const[e,n]of t)for(const t of n){const n=r.get(t);if(!n)throw new Error(`RenderGraph dependency "${t}" for pass "${e}" is missing.`);n.add(e)}const i=Array.from(t.entries()).filter(([,e])=>0===e.size).map(([e])=>e),a=[];for(;i.length>0;){const n=i.shift();a.push(e.get(n));for(const e of r.get(n)??[]){const r=t.get(e);r.delete(n),0===r.size&&i.push(e)}}if(a.length!==this.passes.length)throw new Error("RenderGraph contains a dependency cycle.");return a}};import{CubeUVReflectionMapping as Ht,HalfFloatType as Kt,LinearFilter as Zt,LinearSRGBColorSpace as Yt,RGBAFormat as Xt,Texture as Jt}from"three";var Qt=[.125,.215,.35,.446,.526,.582],er=20,tr=function(){const e=(1+Math.sqrt(5))/2,t=1/e;return[[-e,t,0],[e,t,0],[-t,0,e],[t,0,e],[0,e,-t],[0,e,t],[-1,1,-1],[1,1,-1],[-1,1,1],[1,1,1]]}(),rr=class{constructor(e,t=20){this.context=e;const{device:r}=e,n=Math.max(1,Math.min(20,Math.floor(t)));this.maxBlurSamples=n,this.equirectBindGroupLayout=r.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}},{binding:1,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"unfilterable-float",viewDimension:"2d"}}]}),this.blurBindGroupLayout=r.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}},{binding:1,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float",viewDimension:"2d"}},{binding:2,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}}]}),this.equirectPipeline=nr(r,this.equirectBindGroupLayout,sr,"pmrem-equirectangular"),this.blurPipeline=nr(r,this.blurBindGroupLayout,or.replaceAll("PMREM_MAX_SAMPLES",String(n)),"pmrem-blur")}context;equirectPipeline;blurPipeline;equirectBindGroupLayout;blurBindGroupLayout;maxBlurSamples;fromEquirectangular(e){const t=this.context.getTextureResource(e);if("2d"!==t.viewDimension)throw new Error("WebGpuPMREMGenerator.fromEquirectangular() requires a 2D equirectangular texture.");const r=2**Math.floor(Math.log2(Math.max(16,Math.floor(t.width/4)))),n=Math.floor(Math.log2(r)),i=function(e){const t=[];for(let r=e;r>=4;r-=1){const n=2**r;t.push({mip:r,size:n,sigma:r===e?0:1/n})}for(let e=0;e<Qt.length;e+=1)t.push({mip:4-e-1,size:16,sigma:Qt[e]});return t}(n),a=3*Math.max(r,112),s=4*r,{device:o}=this.context,l=GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING,c=o.createTexture({label:"pmrem-cubeuv",size:{width:a,height:s},format:"rgba16float",usage:l}),u=o.createTexture({label:"pmrem-cubeuv-ping",size:{width:a,height:s},format:"rgba16float",usage:l}),d=o.createSampler({magFilter:"linear",minFilter:"linear"}),h=o.createCommandEncoder({label:"pmrem-generation"}),p=[],f=ir(o,new Float32Array([t.width,t.height,r,0]));p.push(f);const m=o.createBindGroup({layout:this.equirectBindGroupLayout,entries:[{binding:0,resource:{buffer:f}},{binding:1,resource:t.view}]}),g=h.beginRenderPass({colorAttachments:[{view:c.createView(),loadOp:"clear",storeOp:"store",clearValue:[0,0,0,1]}]});g.setViewport(0,0,3*r,2*r,0,1),g.setScissorRect(0,0,3*r,2*r),g.setPipeline(this.equirectPipeline),g.setBindGroup(0,m),g.draw(36),g.end();for(let e=1;e<i.length;e+=1){const t=i[e-1],r=i[e],o=Math.sqrt(r.sigma*r.sigma-t.sigma*t.sigma),l=tr[(i.length-e-1)%tr.length];this.encodeBlurPass({encoder:h,source:c,target:u,sampler:d,atlasWidth:a,atlasHeight:s,maxMip:n,inputLevel:t,outputLevel:r,sigma:o,poleAxis:l,latitudinal:!0,clear:!0,transientBuffers:p}),this.encodeBlurPass({encoder:h,source:u,target:c,sampler:d,atlasWidth:a,atlasHeight:s,maxMip:n,inputLevel:r,outputLevel:r,sigma:o,poleAxis:l,latitudinal:!1,clear:!1,transientBuffers:p})}o.queue.submit([h.finish()]),o.queue.onSubmittedWorkDone().then(()=>{for(const e of p)e.destroy();u.destroy()});const x=new Jt;return x.image={width:a,height:s},x.name="PMREM.cubeUv",x.mapping=Ht,x.format=Xt,x.type=Kt,x.colorSpace=Yt,x.minFilter=Zt,x.magFilter=Zt,x.generateMipmaps=!1,x.needsUpdate=!0,this.context.registerTextureResource(x,{version:x.version,width:a,height:s,depthOrArrayLayers:1,format:"rgba16float",textureDimension:"2d",viewDimension:"2d",sampleType:"float",samplerBindingType:"filtering",mipLevelCount:1,texture:c,view:c.createView(),sampler:d}),{texture:x,dispose:()=>{c.destroy(),x.dispose()}}}encodeBlurPass(e){const{encoder:t,source:r,target:n,sampler:i,atlasWidth:a,atlasHeight:s,maxMip:o,inputLevel:l,outputLevel:c,sigma:u,poleAxis:d,latitudinal:h,clear:p,transientBuffers:f}=e,m=l.size-1,g=Math.PI/(2*m),x=u/g,v=Math.min(this.maxBlurSamples,1+Math.floor(3*x)),w=function(e,t){const r=new Float32Array(er);let n=0;for(let i=0;i<er;i+=1){const a=i/e,s=Math.exp(-a*a/2);r[i]=s,0===i?n+=s:i<t&&(n+=2*s)}for(let e=0;e<r.length;e+=1)r[e]/=n;return r}(x,v),b=ir(this.context.device,function(e){const t=new ArrayBuffer(144),r=new DataView(t);return r.setFloat32(0,e.atlasWidth,!0),r.setFloat32(4,e.atlasHeight,!0),r.setFloat32(8,e.outputFaceSize,!0),r.setFloat32(12,e.inputMip,!0),r.setFloat32(16,e.dTheta,!0),r.setUint32(20,e.sampleCount,!0),r.setUint32(24,e.latitudinal?1:0,!0),r.setFloat32(28,e.maxMip,!0),r.setFloat32(32,e.poleAxis[0],!0),r.setFloat32(36,e.poleAxis[1],!0),r.setFloat32(40,e.poleAxis[2],!0),new Float32Array(t,48,er).set(e.weights),new Float32Array(t)}({atlasWidth:a,atlasHeight:s,outputFaceSize:c.size,inputMip:l.mip,dTheta:g,sampleCount:v,latitudinal:h,poleAxis:d,weights:w,maxMip:o}));f.push(b);const y=this.context.device.createBindGroup({layout:this.blurBindGroupLayout,entries:[{binding:0,resource:{buffer:b}},{binding:1,resource:r.createView()},{binding:2,resource:i}]}),S=3*c.size*Math.max(0,4-c.mip),C=4*(2**o-c.size),P=t.beginRenderPass({colorAttachments:[{view:n.createView(),loadOp:p?"clear":"load",storeOp:"store",clearValue:[0,0,0,1]}]});P.setViewport(S,C,3*c.size,2*c.size,0,1),P.setScissorRect(S,C,3*c.size,2*c.size),P.setPipeline(this.blurPipeline),P.setBindGroup(0,y),P.draw(36),P.end()}};function nr(e,t,r,n){const i=e.createShaderModule({code:r,label:`${n}-shader`});return i.getCompilationInfo().then(e=>{const t=e.messages.filter(e=>"error"===e.type);t.length>0&&console.error(`[WebGpuPMREMGenerator] ${n} WGSL compilation failed.`,t)}),e.createRenderPipeline({label:n,layout:e.createPipelineLayout({bindGroupLayouts:[t]}),vertex:{module:i,entryPoint:"vs"},fragment:{module:i,entryPoint:"fs",targets:[{format:"rgba16float"}]},primitive:{topology:"triangle-list"}})}function ir(e,t){const r=e.createBuffer({size:t.byteLength,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST});return e.queue.writeBuffer(r,0,t.buffer,t.byteOffset,t.byteLength),r}var ar="\nstruct VertexOutput {\n @builtin(position) position: vec4f,\n @location(0) uv: vec2f,\n @location(1) @interpolate(flat) face: u32,\n};\n\nconst corners = array<vec2f, 6>(\n vec2f(0, 0), vec2f(1, 0), vec2f(1, 1),\n vec2f(0, 0), vec2f(1, 1), vec2f(0, 1),\n);\n\n@vertex\nfn vs(@builtin(vertex_index) index: u32) -> VertexOutput {\n let face = index / 6u;\n let corner = corners[index % 6u];\n var output: VertexOutput;\n output.position = vec4f(\n (corner.x + f32(face % 3u)) / 3.0 * 2.0 - 1.0,\n 1.0 - (corner.y + f32(face / 3u)),\n 0.0,\n 1.0,\n );\n output.uv = corner;\n output.face = face;\n return output;\n}\n\nfn cubeDirection(inputUv: vec2f, face: u32, faceSize: f32) -> vec3f {\n let gutter = 1.0 / (faceSize - 2.0);\n let uv = (inputUv * (1.0 + 2.0 * gutter) - vec2f(gutter)) * 2.0 - 1.0;\n if (face == 0u) { return normalize(vec3f(1.0, uv.y, uv.x)); }\n if (face == 1u) { return normalize(vec3f(-uv.x, 1.0, -uv.y)); }\n if (face == 2u) { return normalize(vec3f(-uv.x, uv.y, 1.0)); }\n if (face == 3u) { return normalize(vec3f(-1.0, uv.y, -uv.x)); }\n if (face == 4u) { return normalize(vec3f(-uv.x, -1.0, uv.y)); }\n return normalize(vec3f(uv.x, uv.y, -1.0));\n}\n",sr=`${ar}\nstruct EquirectParams {\n sourceSize: vec2f,\n faceSize: f32,\n _padding: f32,\n};\n\n@group(0) @binding(0) var<uniform> params: EquirectParams;\n@group(0) @binding(1) var environmentMap: texture_2d<f32>;\n\nfn sampleEquirectangular(direction: vec3f) -> vec3f {\n let uv = vec2f(\n atan2(direction.z, direction.x) / (2.0 * 3.141592653589793) + 0.5,\n asin(clamp(direction.y, -1.0, 1.0)) / 3.141592653589793 + 0.5,\n );\n let pixel = uv * params.sourceSize - vec2f(0.5);\n let base = vec2i(floor(pixel));\n let fraction = fract(pixel);\n let width = i32(params.sourceSize.x);\n let height = i32(params.sourceSize.y);\n let x0 = (base.x % width + width) % width;\n let x1 = (x0 + 1) % width;\n let y0 = clamp(base.y, 0, height - 1);\n let y1 = min(y0 + 1, height - 1);\n let top = mix(\n textureLoad(environmentMap, vec2i(x0, y0), 0).rgb,\n textureLoad(environmentMap, vec2i(x1, y0), 0).rgb,\n fraction.x,\n );\n let bottom = mix(\n textureLoad(environmentMap, vec2i(x0, y1), 0).rgb,\n textureLoad(environmentMap, vec2i(x1, y1), 0).rgb,\n fraction.x,\n );\n return mix(top, bottom, fraction.y);\n}\n\n@fragment\nfn fs(input: VertexOutput) -> @location(0) vec4f {\n let direction = cubeDirection(input.uv, input.face, params.faceSize);\n return vec4f(sampleEquirectangular(direction), 1.0);\n}\n`,or=`${ar}\nstruct BlurParams {\n atlasSize: vec2f,\n outputFaceSize: f32,\n inputMip: f32,\n dTheta: f32,\n samples: u32,\n latitudinal: u32,\n maxMip: f32,\n poleAxis: vec3f,\n _padding: f32,\n weights: array<vec4f, 5>,\n};\n\n@group(0) @binding(0) var<uniform> params: BlurParams;\n@group(0) @binding(1) var environmentMap: texture_2d<f32>;\n@group(0) @binding(2) var environmentSampler: sampler;\n\nfn cubeFace(direction: vec3f) -> f32 {\n let absolute = abs(direction);\n if (absolute.x > absolute.z) {\n if (absolute.x > absolute.y) { return select(3.0, 0.0, direction.x > 0.0); }\n return select(4.0, 1.0, direction.y > 0.0);\n }\n if (absolute.z > absolute.y) { return select(5.0, 2.0, direction.z > 0.0); }\n return select(4.0, 1.0, direction.y > 0.0);\n}\n\nfn cubeUv(direction: vec3f, face: f32) -> vec2f {\n if (face == 0.0) { return 0.5 * (vec2f(direction.z, direction.y) / abs(direction.x) + 1.0); }\n if (face == 1.0) { return 0.5 * (vec2f(-direction.x, -direction.z) / abs(direction.y) + 1.0); }\n if (face == 2.0) { return 0.5 * (vec2f(-direction.x, direction.y) / abs(direction.z) + 1.0); }\n if (face == 3.0) { return 0.5 * (vec2f(-direction.z, direction.y) / abs(direction.x) + 1.0); }\n if (face == 4.0) { return 0.5 * (vec2f(-direction.x, direction.z) / abs(direction.y) + 1.0); }\n return 0.5 * (vec2f(direction.x, direction.y) / abs(direction.z) + 1.0);\n}\n\nfn sampleCubeUv(direction: vec3f) -> vec3f {\n var face = cubeFace(direction);\n let filterOffset = max(4.0 - params.inputMip, 0.0);\n let mip = max(params.inputMip, 4.0);\n let faceSize = exp2(mip);\n var uv = cubeUv(direction, face) * (faceSize - 2.0) + 1.0;\n if (face > 2.0) {\n uv.y += faceSize;\n face -= 3.0;\n }\n uv.x += face * faceSize + filterOffset * 3.0 * 16.0;\n uv.y += 4.0 * (exp2(params.maxMip) - faceSize);\n return textureSampleLevel(environmentMap, environmentSampler, uv / params.atlasSize, 0.0).rgb;\n}\n\nfn weight(index: u32) -> f32 {\n return params.weights[index / 4u][index % 4u];\n}\n\nfn rotatedSample(direction: vec3f, theta: f32, axis: vec3f) -> vec3f {\n let cosine = cos(theta);\n let sampleDirection = direction * cosine\n + cross(axis, direction) * sin(theta)\n + axis * dot(axis, direction) * (1.0 - cosine);\n return sampleCubeUv(sampleDirection);\n}\n\n@fragment\nfn fs(input: VertexOutput) -> @location(0) vec4f {\n let direction = cubeDirection(input.uv, input.face, params.outputFaceSize);\n var axis = select(cross(params.poleAxis, direction), params.poleAxis, params.latitudinal != 0u);\n if (dot(axis, axis) < 0.000001) { axis = vec3f(direction.z, 0.0, -direction.x); }\n axis = normalize(axis);\n var color = weight(0u) * rotatedSample(direction, 0.0, axis);\n for (var index = 1u; index < PMREM_MAX_SAMPLES; index += 1u) {\n if (index >= params.samples) { break; }\n let theta = params.dTheta * f32(index);\n color += weight(index) * rotatedSample(direction, -theta, axis);\n color += weight(index) * rotatedSample(direction, theta, axis);\n }\n return vec4f(color, 1.0);\n}\n`;function lr(e){return e.replace(/[^A-Za-z0-9_]/g,"_")}function cr(e,t){const r=Object.entries(e.uniforms).map(([e,t])=>` ${lr(e)}: ${t.type},`).join("\n"),n=r?`\nstruct MaterialUniforms {\n${r}\n};\n\n@group(1) @binding(0) var<uniform> materialUniforms: MaterialUniforms;\n`:"",i=Object.entries(e.textures).map(([e,r],n)=>{const i=1+2*n,a=lr(e),s=ve(r,t);return[`@group(1) @binding(${i}) var ${a}Sampler: ${s.wgslSamplerType};`,`@group(1) @binding(${i+1}) var ${a}Texture: ${s.wgslTextureType};`].join("\n")}).join("\n"),a=1+2*Object.keys(e.textures).length;return`${n}\n${i}\n${Object.entries(e.storageBuffers).map(([e,t],r)=>{const n=lr(e);return`@group(1) @binding(${a+r}) var<storage, read> ${n}: ${t.type};`}).join("\n")}`}function ur(e){return`\nfn rendererModelMatrix(instanceIndex: u32) -> mat4x4<f32> {\n return rendererInstanceModelMatrix(instanceIndex);\n}\n\nfn rendererNormalMatrix(instanceIndex: u32) -> mat3x3<f32> {\n ${e?"let view = rendererViewMatrix();\n let viewRotation = mat3x3<f32>(view[0].xyz, view[1].xyz, view[2].xyz);\n return viewRotation * rendererInstanceNormalMatrix(instanceIndex);":"return rendererInstanceNormalMatrix(instanceIndex);"}\n}\n\nfn modelMatrix(instanceIndex: u32) -> mat4x4<f32> {\n return rendererModelMatrix(instanceIndex);\n}\n\nfn normalMatrix(instanceIndex: u32) -> mat3x3<f32> {\n return rendererNormalMatrix(instanceIndex);\n}\n${e?`\nfn rendererViewMatrix() -> mat4x4<f32> {\n return ${e}.view;\n}\n\nfn rendererProjectionMatrix() -> mat4x4<f32> {\n return ${e}.projection;\n}\n\nfn rendererModelViewMatrix(instanceIndex: u32) -> mat4x4<f32> {\n return rendererViewMatrix() * rendererModelMatrix(instanceIndex);\n}\n\nfn rendererModelViewProjectionMatrix(instanceIndex: u32) -> mat4x4<f32> {\n return rendererProjectionMatrix() * rendererModelViewMatrix(instanceIndex);\n}\n\nfn rendererCameraPosition() -> vec3<f32> {\n return ${e}.cameraPosition.xyz;\n}\n\nfn rendererCameraNear() -> f32 {\n return ${e}.nearFar.x;\n}\n\nfn rendererCameraFar() -> f32 {\n return ${e}.nearFar.y;\n}\n\n${"rendererCamera"===e?`\nfn rendererFogColor() -> vec3<f32> {\n return ${e}.fogColor.rgb;\n}\n\nfn rendererFogNear() -> f32 {\n return ${e}.fogParams.x;\n}\n\nfn rendererFogFar() -> f32 {\n return ${e}.fogParams.y;\n}\n\nfn rendererFogDensity() -> f32 {\n return ${e}.fogParams.z;\n}\n\nfn rendererFogMode() -> f32 {\n return ${e}.fogParams.w;\n}\n`:""}\n\nfn rendererElapsedTime() -> f32 {\n return ${"rendererCamera"===e?"rendererCamera.viewportAndTime.w":"shadowCamera"===e?"shadowCamera.timeAndPadding.x":null};\n}\n\nfn viewMatrix() -> mat4x4<f32> {\n return rendererViewMatrix();\n}\n\nfn projectionMatrix() -> mat4x4<f32> {\n return rendererProjectionMatrix();\n}\n\nfn modelViewMatrix(instanceIndex: u32) -> mat4x4<f32> {\n return rendererModelViewMatrix(instanceIndex);\n}\n\nfn modelViewProjectionMatrix(instanceIndex: u32) -> mat4x4<f32> {\n return rendererModelViewProjectionMatrix(instanceIndex);\n}\n\nfn cameraPosition() -> vec3<f32> {\n return rendererCameraPosition();\n}\n`:""}`}function dr(e){return e?"\nstruct RendererSkinningUniforms {\n bindMatrix: mat4x4<f32>,\n bindMatrixInverse: mat4x4<f32>,\n};\n\n@group(2) @binding(0) var<storage, read> rendererBoneMatrixColumns: array<vec4<f32>>;\n@group(2) @binding(1) var<uniform> rendererSkinning: RendererSkinningUniforms;\n\nfn rendererBoneMatrix(index: u32) -> mat4x4<f32> {\n let base = index * 4u;\n return mat4x4<f32>(\n rendererBoneMatrixColumns[base + 0u],\n rendererBoneMatrixColumns[base + 1u],\n rendererBoneMatrixColumns[base + 2u],\n rendererBoneMatrixColumns[base + 3u],\n );\n}\n\nfn rendererSkinPosition(position: vec3<f32>, skinIndex: vec4<u32>, skinWeight: vec4<f32>) -> vec3<f32> {\n let boundPosition = rendererSkinning.bindMatrix * vec4(position, 1.0);\n let weightSum = skinWeight.x + skinWeight.y + skinWeight.z + skinWeight.w;\n if (weightSum <= 0.0) {\n return position;\n }\n let skinnedPosition =\n (rendererBoneMatrix(skinIndex.x) * boundPosition) * skinWeight.x +\n (rendererBoneMatrix(skinIndex.y) * boundPosition) * skinWeight.y +\n (rendererBoneMatrix(skinIndex.z) * boundPosition) * skinWeight.z +\n (rendererBoneMatrix(skinIndex.w) * boundPosition) * skinWeight.w;\n let fallbackWeight = max(0.0, 1.0 - weightSum);\n return (rendererSkinning.bindMatrixInverse * (skinnedPosition + boundPosition * fallbackWeight)).xyz;\n}\n\nfn rendererSkinNormal(normal: vec3<f32>, skinIndex: vec4<u32>, skinWeight: vec4<f32>) -> vec3<f32> {\n let boundNormal = rendererSkinning.bindMatrix * vec4(normal, 0.0);\n let weightSum = skinWeight.x + skinWeight.y + skinWeight.z + skinWeight.w;\n if (weightSum <= 0.0) {\n return normalize(normal);\n }\n let skinnedNormal =\n (rendererBoneMatrix(skinIndex.x) * boundNormal) * skinWeight.x +\n (rendererBoneMatrix(skinIndex.y) * boundNormal) * skinWeight.y +\n (rendererBoneMatrix(skinIndex.z) * boundNormal) * skinWeight.z +\n (rendererBoneMatrix(skinIndex.w) * boundNormal) * skinWeight.w;\n let fallbackWeight = max(0.0, 1.0 - weightSum);\n return normalize((rendererSkinning.bindMatrixInverse * (skinnedNormal + boundNormal * fallbackWeight)).xyz);\n}\n":""}function hr(e,t,r="packed",n=!0,i=!1){const a=cr(e,t),s=function(e){return Object.entries(e.getGraphTextureInputs()).map(([e,t],r)=>{const n=lr(e);return`@group(3) @binding(${2*r}) var ${n}Sampler: ${"comparison"===t.sampler?"sampler_comparison":"sampler"};\n@group(3) @binding(${2*r+1}) var ${n}Texture: ${"depth-2d"===t.dimension?"texture_depth_2d":"3d"===t.dimension?"texture_3d<f32>":"texture_2d<f32>"};`}).join("\n")}(e),o="packed-visible"===r,l=n?"\nfn rendererSampleDirectionalShadowForLight(lightIndex: u32, worldPosition: vec3<f32>) -> f32 {\n if (lightIndex >= rendererDirectionalLightCount() || !rendererDirectionalShadowEnabledForLight(lightIndex)) {\n return 1.0;\n }\n\n let matrix = rendererDirectionalShadowMatrixForLight(lightIndex);\n let shadowClip = matrix * vec4(worldPosition, 1.0);\n if (shadowClip.w <= 0.0) {\n return 1.0;\n }\n\n let ndc = shadowClip.xyz / shadowClip.w;\n if (ndc.x < -1.0 || ndc.x > 1.0 || ndc.y < -1.0 || ndc.y > 1.0 || ndc.z < 0.0 || ndc.z > 1.0) {\n return 1.0;\n }\n\n let uv = ndc.xy * vec2(0.5, -0.5) + vec2(0.5, 0.5);\n let dims = vec2<f32>(textureDimensions(rendererDirectionalShadowTexture));\n let texel = 1.0 / max(dims, vec2(1.0, 1.0));\n let radius = max(rendererLights.directionalShadowParams2[lightIndex].x, 0.0);\n // Match Three.js/three-shader-graph semantics: negative bias moves the\n // receiver toward the light and therefore reduces self-shadowing.\n let depth = ndc.z + rendererDirectionalShadowBiasForLight(lightIndex);\n let filterOffset = texel * radius;\n\n // Each comparison-level sample is already a hardware-filtered 2x2 PCF\n // lookup. A weighted center plus four cardinal taps gives a compact tent\n // filter (five lookups rather than nine manual depth loads) and is legal in\n // non-uniform control flow because the explicit level computes no derivatives.\n let center = textureSampleCompareLevel(\n rendererDirectionalShadowTexture,\n rendererShadowSampler,\n uv,\n i32(lightIndex),\n depth\n );\n let left = textureSampleCompareLevel(\n rendererDirectionalShadowTexture,\n rendererShadowSampler,\n clamp(uv - vec2(filterOffset.x, 0.0), vec2(0.0), vec2(1.0)),\n i32(lightIndex),\n depth\n );\n let right = textureSampleCompareLevel(\n rendererDirectionalShadowTexture,\n rendererShadowSampler,\n clamp(uv + vec2(filterOffset.x, 0.0), vec2(0.0), vec2(1.0)),\n i32(lightIndex),\n depth\n );\n let up = textureSampleCompareLevel(\n rendererDirectionalShadowTexture,\n rendererShadowSampler,\n clamp(uv - vec2(0.0, filterOffset.y), vec2(0.0), vec2(1.0)),\n i32(lightIndex),\n depth\n );\n let down = textureSampleCompareLevel(\n rendererDirectionalShadowTexture,\n rendererShadowSampler,\n clamp(uv + vec2(0.0, filterOffset.y), vec2(0.0), vec2(1.0)),\n i32(lightIndex),\n depth\n );\n let shadow = (center * 4.0 + left + right + up + down) * 0.125;\n return mix(1.0, shadow, rendererDirectionalShadowIntensityForLight(lightIndex));\n}\n\nfn rendererSampleDirectionalShadowForLightWithNormal(lightIndex: u32, worldPosition: vec3<f32>, worldNormal: vec3<f32>) -> f32 {\n let params = rendererLights.directionalShadowParams[lightIndex];\n return rendererSampleDirectionalShadowForLight(lightIndex, worldPosition + normalize(worldNormal) * params.w);\n}\n\nfn rendererPointShadowUvLayer(direction: vec3<f32>, pointIndex: u32) -> vec3<f32> {\n let absDir = abs(direction);\n var face = 0u;\n var uv = vec2<f32>(0.0, 0.0);\n if (absDir.x >= absDir.y && absDir.x >= absDir.z) {\n if (direction.x >= 0.0) {\n face = 0u;\n uv = vec2<f32>(-direction.z, -direction.y) / absDir.x;\n } else {\n face = 1u;\n uv = vec2<f32>(direction.z, -direction.y) / absDir.x;\n }\n } else if (absDir.y >= absDir.x && absDir.y >= absDir.z) {\n if (direction.y >= 0.0) {\n face = 2u;\n uv = vec2<f32>(direction.x, direction.z) / absDir.y;\n } else {\n face = 3u;\n uv = vec2<f32>(direction.x, -direction.z) / absDir.y;\n }\n } else {\n if (direction.z >= 0.0) {\n face = 4u;\n uv = vec2<f32>(direction.x, -direction.y) / absDir.z;\n } else {\n face = 5u;\n uv = vec2<f32>(-direction.x, -direction.y) / absDir.z;\n }\n }\n return vec3<f32>(uv * 0.5 + vec2(0.5, 0.5), f32(pointIndex * 6u + face));\n}\n\nfn rendererSamplePointShadowForLight(lightIndex: u32, worldPosition: vec3<f32>) -> f32 {\n if (lightIndex >= rendererPointLightCount() || !rendererPointShadowEnabledForLight(lightIndex)) {\n return 1.0;\n }\n let lightPosition = rendererPointLightPositionForLight(lightIndex);\n let range = rendererPointLightRangeForLight(lightIndex);\n let toFragment = worldPosition - lightPosition;\n let distanceToLight = length(toFragment);\n if (distanceToLight >= range) {\n return 1.0;\n }\n let uvLayer = rendererPointShadowUvLayer(toFragment, lightIndex);\n let dims = vec2<f32>(textureDimensions(rendererPointShadowTexture));\n let sampleUv = clamp(uvLayer.xy, vec2(0.0, 0.0), vec2(1.0, 1.0));\n let pixel = vec2<i32>(clamp(sampleUv * dims, vec2(0.0, 0.0), dims - vec2(1.0, 1.0)));\n let closestDepth = textureLoad(rendererPointShadowTexture, pixel, i32(round(uvLayer.z)), 0).r;\n let currentDepth = clamp(distanceToLight / max(range, 0.0001), 0.0, 1.0) - rendererPointShadowBiasForLight(lightIndex);\n let shadow = select(0.0, 1.0, currentDepth <= closestDepth);\n return mix(1.0, shadow, rendererPointShadowIntensityForLight(lightIndex));\n}\n\nfn rendererSamplePointShadowForLightWithNormal(lightIndex: u32, worldPosition: vec3<f32>, worldNormal: vec3<f32>) -> f32 {\n let params = rendererLights.pointShadowParams[lightIndex];\n let lightDirection = normalize(worldPosition - rendererPointLightPositionForLight(lightIndex));\n return rendererSamplePointShadowForLight(lightIndex, worldPosition + normalize(worldNormal + lightDirection) * params.w);\n}\n\nfn rendererSampleSpotShadowForLight(lightIndex: u32, worldPosition: vec3<f32>) -> f32 {\n if (lightIndex >= rendererSpotLightCount() || !rendererSpotShadowEnabledForLight(lightIndex)) {\n return 1.0;\n }\n let matrix = rendererSpotShadowMatrixForLight(lightIndex);\n let shadowClip = matrix * vec4(worldPosition, 1.0);\n if (shadowClip.w <= 0.0) {\n return 1.0;\n }\n let ndc = shadowClip.xyz / shadowClip.w;\n if (ndc.x < -1.0 || ndc.x > 1.0 || ndc.y < -1.0 || ndc.y > 1.0 || ndc.z < 0.0 || ndc.z > 1.0) {\n return 1.0;\n }\n let uv = ndc.xy * vec2(0.5, -0.5) + vec2(0.5, 0.5);\n let dims = vec2<f32>(textureDimensions(rendererSpotShadowTexture));\n let texel = 1.0 / max(dims, vec2(1.0, 1.0));\n let radius = max(rendererLights.spotShadowParams2[lightIndex].x, 1.0);\n let depth = ndc.z - rendererSpotShadowBiasForLight(lightIndex);\n var sum = 0.0;\n for (var y: i32 = -1; y <= 1; y = y + 1) {\n for (var x: i32 = -1; x <= 1; x = x + 1) {\n let offset = vec2<f32>(f32(x), f32(y)) * texel * radius;\n let sampleUv = clamp(uv + offset, vec2(0.0, 0.0), vec2(1.0, 1.0));\n let pixel = vec2<i32>(clamp(sampleUv * dims, vec2(0.0, 0.0), dims - vec2(1.0, 1.0)));\n let shadowDepth = textureLoad(rendererSpotShadowTexture, pixel, i32(lightIndex), 0);\n sum += select(0.0, 1.0, depth <= shadowDepth);\n }\n }\n return mix(1.0, sum / 9.0, rendererSpotShadowIntensityForLight(lightIndex));\n}\n\nfn rendererSampleSpotShadowForLightWithNormal(lightIndex: u32, worldPosition: vec3<f32>, worldNormal: vec3<f32>) -> f32 {\n let params = rendererLights.spotShadowParams[lightIndex];\n return rendererSampleSpotShadowForLight(lightIndex, worldPosition + normalize(worldNormal) * params.w);\n}\n\nfn rendererSampleDirectionalShadow(worldPosition: vec3<f32>) -> f32 {\n return rendererSampleDirectionalShadowForLight(0u, worldPosition);\n}\n\nfn rendererSampleDirectionalShadowWithNormal(worldPosition: vec3<f32>, worldNormal: vec3<f32>) -> f32 {\n return rendererSampleDirectionalShadowForLightWithNormal(0u, worldPosition, worldNormal);\n}\n\nfn rendererSamplePointShadow(worldPosition: vec3<f32>) -> f32 {\n return rendererSamplePointShadowForLight(0u, worldPosition);\n}\n\nfn rendererSamplePointShadowWithNormal(worldPosition: vec3<f32>, worldNormal: vec3<f32>) -> f32 {\n return rendererSamplePointShadowForLightWithNormal(0u, worldPosition, worldNormal);\n}\n\nfn rendererSampleSpotShadow(worldPosition: vec3<f32>) -> f32 {\n return rendererSampleSpotShadowForLight(0u, worldPosition);\n}\n\nfn rendererSampleSpotShadowWithNormal(worldPosition: vec3<f32>, worldNormal: vec3<f32>) -> f32 {\n return rendererSampleSpotShadowForLightWithNormal(0u, worldPosition, worldNormal);\n}\n":"\nfn rendererSampleDirectionalShadowForLight(lightIndex: u32, worldPosition: vec3<f32>) -> f32 {\n _ = lightIndex;\n _ = worldPosition;\n return 1.0;\n}\n\nfn rendererSampleDirectionalShadowForLightWithNormal(lightIndex: u32, worldPosition: vec3<f32>, worldNormal: vec3<f32>) -> f32 {\n _ = worldNormal;\n return rendererSampleDirectionalShadowForLight(lightIndex, worldPosition);\n}\n\nfn rendererSamplePointShadowForLight(lightIndex: u32, worldPosition: vec3<f32>) -> f32 {\n _ = lightIndex;\n _ = worldPosition;\n return 1.0;\n}\n\nfn rendererSamplePointShadowForLightWithNormal(lightIndex: u32, worldPosition: vec3<f32>, worldNormal: vec3<f32>) -> f32 {\n _ = worldNormal;\n return rendererSamplePointShadowForLight(lightIndex, worldPosition);\n}\n\nfn rendererSampleSpotShadowForLight(lightIndex: u32, worldPosition: vec3<f32>) -> f32 {\n _ = lightIndex;\n _ = worldPosition;\n return 1.0;\n}\n\nfn rendererSampleSpotShadowForLightWithNormal(lightIndex: u32, worldPosition: vec3<f32>, worldNormal: vec3<f32>) -> f32 {\n _ = worldNormal;\n return rendererSampleSpotShadowForLight(lightIndex, worldPosition);\n}\n\nfn rendererSampleDirectionalShadow(worldPosition: vec3<f32>) -> f32 {\n _ = worldPosition;\n return 1.0;\n}\n\nfn rendererSampleDirectionalShadowWithNormal(worldPosition: vec3<f32>, worldNormal: vec3<f32>) -> f32 {\n _ = worldPosition;\n _ = worldNormal;\n return 1.0;\n}\n\nfn rendererSamplePointShadow(worldPosition: vec3<f32>) -> f32 {\n _ = worldPosition;\n return 1.0;\n}\n\nfn rendererSamplePointShadowWithNormal(worldPosition: vec3<f32>, worldNormal: vec3<f32>) -> f32 {\n _ = worldPosition;\n _ = worldNormal;\n return 1.0;\n}\n\nfn rendererSampleSpotShadow(worldPosition: vec3<f32>) -> f32 {\n _ = worldPosition;\n return 1.0;\n}\n\nfn rendererSampleSpotShadowWithNormal(worldPosition: vec3<f32>, worldNormal: vec3<f32>) -> f32 {\n _ = worldPosition;\n _ = worldNormal;\n return 1.0;\n}\n";return`\nstruct RendererCameraUniforms {\n viewProj: mat4x4<f32>,\n cameraPosition: vec4<f32>,\n viewportAndTime: vec4<f32>,\n view: mat4x4<f32>,\n projection: mat4x4<f32>,\n nearFar: vec4<f32>,\n fogColor: vec4<f32>,\n fogParams: vec4<f32>,\n};\n\nstruct RendererLightUniforms {\n ambientColor: vec4<f32>,\n lightCounts: vec4<f32>,\n directionalDirections: array<vec4<f32>, 4>,\n directionalColorIntensities: array<vec4<f32>, 4>,\n directionalShadowParams: array<vec4<f32>, 4>,\n directionalShadowParams2: array<vec4<f32>, 4>,\n directionalShadowMatrices: array<mat4x4<f32>, 4>,\n pointPositionRanges: array<vec4<f32>, 4>,\n pointColorIntensities: array<vec4<f32>, 4>,\n pointShadowParams: array<vec4<f32>, 4>,\n pointShadowParams2: array<vec4<f32>, 4>,\n spotPositionRanges: array<vec4<f32>, 4>,\n spotDirectionCones: array<vec4<f32>, 4>,\n spotColorIntensities: array<vec4<f32>, 4>,\n spotShadowParams: array<vec4<f32>, 4>,\n spotShadowParams2: array<vec4<f32>, 4>,\n spotParams: array<vec4<f32>, 4>,\n spotShadowMatrices: array<mat4x4<f32>, 4>,\n csmCascadeRanges: array<vec4<f32>, 4>,\n hemisphereSkyColorIntensity: vec4<f32>,\n hemisphereGroundColorIntensity: vec4<f32>,\n hemisphereDirection: vec4<f32>,\n};\n\n${"instanced-direct"===r?"\n@group(0) @binding(0) var<uniform> rendererCamera: RendererCameraUniforms;\n@group(0) @binding(1) var<uniform> rendererLights: RendererLightUniforms;\n@group(0) @binding(2) var<storage, read> rendererInstanceMatrices: array<vec4<f32>>;\n@group(0) @binding(3) var<storage, read> rendererInstanceColors: array<vec4<f32>>;\n@group(0) @binding(4) var rendererShadowSampler: sampler_comparison;\n@group(0) @binding(5) var rendererDirectionalShadowTexture: texture_depth_2d_array;\n@group(0) @binding(6) var rendererLinearClampSampler: sampler;\n@group(0) @binding(7) var rendererPointShadowTexture: texture_2d_array<f32>;\n@group(0) @binding(8) var rendererSpotShadowTexture: texture_depth_2d_array;\n\nfn rendererBatchingId(instanceIndex: u32) -> u32 {\n return instanceIndex;\n}\n\nfn rendererInstanceModelMatrix(instanceIndex: u32) -> mat4x4<f32> {\n let base = instanceIndex * 4u;\n return mat4x4<f32>(\n rendererInstanceMatrices[base + 0u],\n rendererInstanceMatrices[base + 1u],\n rendererInstanceMatrices[base + 2u],\n rendererInstanceMatrices[base + 3u]\n );\n}\n\nfn rendererObjectColor(instanceIndex: u32) -> vec4<f32> {\n return rendererInstanceColors[instanceIndex];\n}\n":`\nstruct RendererInstanceData {\n model0: vec4<f32>,\n model1: vec4<f32>,\n model2: vec4<f32>,\n model3: vec4<f32>,\n color: vec4<f32>,\n batching: vec4<f32>,\n};\n\n@group(0) @binding(0) var<uniform> rendererCamera: RendererCameraUniforms;\n@group(0) @binding(1) var<uniform> rendererLights: RendererLightUniforms;\n@group(0) @binding(2) var<storage, read> rendererInstances: array<RendererInstanceData>;\n@group(0) @binding(3) var rendererShadowSampler: sampler_comparison;\n@group(0) @binding(4) var rendererDirectionalShadowTexture: texture_depth_2d_array;\n@group(0) @binding(5) var rendererLinearClampSampler: sampler;\n@group(0) @binding(6) var rendererPointShadowTexture: texture_2d_array<f32>;\n@group(0) @binding(7) var rendererSpotShadowTexture: texture_depth_2d_array;\n${o?"@group(0) @binding(8) var<storage, read> rendererVisibleInstanceIndices: array<u32>;":""}\n\nfn rendererResolveInstanceIndex(instanceIndex: u32) -> u32 {\n ${o?"return rendererVisibleInstanceIndices[instanceIndex];":"return instanceIndex;"}\n}\n\nfn rendererInstanceModelMatrix(instanceIndex: u32) -> mat4x4<f32> {\n let instance = rendererInstances[rendererResolveInstanceIndex(instanceIndex)];\n return mat4x4<f32>(instance.model0, instance.model1, instance.model2, instance.model3);\n}\n\nfn rendererObjectColor(instanceIndex: u32) -> vec4<f32> {\n return rendererInstances[rendererResolveInstanceIndex(instanceIndex)].color;\n}\n\nfn rendererBatchingId(instanceIndex: u32) -> u32 {\n return u32(round(rendererInstances[rendererResolveInstanceIndex(instanceIndex)].batching.x));\n}\n`}\n\nfn rendererInverseMat3(m: mat3x3<f32>) -> mat3x3<f32> {\n let a = m[0];\n let b = m[1];\n let c = m[2];\n let r0 = cross(b, c);\n let r1 = cross(c, a);\n let r2 = cross(a, b);\n let det = dot(r2, c);\n let safeDet = select(det, select(-1e-8, 1e-8, det >= 0.0), abs(det) < 1e-8);\n let invDet = 1.0 / safeDet;\n return transpose(mat3x3<f32>(r0 * invDet, r1 * invDet, r2 * invDet));\n}\n\nfn rendererInstanceNormalMatrix(instanceIndex: u32) -> mat3x3<f32> {\n let model = rendererInstanceModelMatrix(instanceIndex);\n let model3x3 = mat3x3<f32>(model[0].xyz, model[1].xyz, model[2].xyz);\n return transpose(rendererInverseMat3(model3x3));\n}\n\nfn rendererWorldPosition(localPosition: vec3<f32>, instanceIndex: u32) -> vec4<f32> {\n return rendererInstanceModelMatrix(instanceIndex) * vec4(localPosition, 1.0);\n}\n\nfn rendererClipPosition(localPosition: vec3<f32>, instanceIndex: u32) -> vec4<f32> {\n return rendererCamera.viewProj * rendererWorldPosition(localPosition, instanceIndex);\n}\n\nfn rendererWorldNormal(localNormal: vec3<f32>, instanceIndex: u32) -> vec3<f32> {\n return normalize(rendererInstanceNormalMatrix(instanceIndex) * localNormal);\n}\n\n${ur("rendererCamera")}\n\nfn rendererDirectionalLightDirection() -> vec3<f32> {\n return rendererDirectionalLightDirectionForLight(0u);\n}\n\nfn rendererDirectionalLightColor() -> vec3<f32> {\n return rendererDirectionalLightColorForLight(0u);\n}\n\nfn rendererPointLightPosition() -> vec3<f32> {\n return rendererPointLightPositionForLight(0u);\n}\n\nfn rendererPointLightRange() -> f32 {\n return rendererPointLightRangeForLight(0u);\n}\n\nfn rendererPointLightColor() -> vec3<f32> {\n return rendererPointLightColorForLight(0u);\n}\n\nfn rendererAmbientLight() -> vec3<f32> {\n return rendererLights.ambientColor.xyz * rendererLights.ambientColor.w;\n}\n\nfn rendererHemisphereLight(worldNormal: vec3<f32>) -> vec3<f32> {\n let directionLength = length(rendererLights.hemisphereDirection.xyz);\n if (directionLength <= 0.0) {\n return vec3<f32>(0.0);\n }\n let sky = rendererLights.hemisphereSkyColorIntensity;\n let ground = rendererLights.hemisphereGroundColorIntensity;\n let weight = dot(normalize(worldNormal), rendererLights.hemisphereDirection.xyz / directionLength) * 0.5 + 0.5;\n return mix(ground.xyz * ground.w, sky.xyz * sky.w, weight);\n}\n\nfn rendererIndirectDiffuse(worldNormal: vec3<f32>) -> vec3<f32> {\n return rendererAmbientLight() + rendererHemisphereLight(worldNormal);\n}\n\nfn rendererDirectionalLightCount() -> u32 {\n return u32(round(rendererLights.lightCounts.x));\n}\n\nfn rendererPointLightCount() -> u32 {\n return u32(round(rendererLights.lightCounts.y));\n}\n\nfn rendererSpotLightCount() -> u32 {\n return u32(round(rendererLights.lightCounts.z));\n}\n\nfn rendererCsmCascadeCount() -> u32 {\n return u32(round(rendererLights.lightCounts.w));\n}\n\nfn rendererCsmCascadeRangeForLight(lightIndex: u32) -> vec2<f32> {\n return rendererLights.csmCascadeRanges[lightIndex].xy;\n}\n\nfn rendererDirectionalLightDirectionForLight(lightIndex: u32) -> vec3<f32> {\n return normalize(-rendererLights.directionalDirections[lightIndex].xyz);\n}\n\nfn rendererDirectionalLightColorForLight(lightIndex: u32) -> vec3<f32> {\n let value = rendererLights.directionalColorIntensities[lightIndex];\n return value.xyz * value.w;\n}\n\nfn rendererPointLightPositionForLight(lightIndex: u32) -> vec3<f32> {\n return rendererLights.pointPositionRanges[lightIndex].xyz;\n}\n\nfn rendererPointLightRangeForLight(lightIndex: u32) -> f32 {\n return rendererLights.pointPositionRanges[lightIndex].w;\n}\n\nfn rendererPointLightColorForLight(lightIndex: u32) -> vec3<f32> {\n let value = rendererLights.pointColorIntensities[lightIndex];\n return value.xyz * value.w;\n}\n\nfn rendererSpotLightPositionForLight(lightIndex: u32) -> vec3<f32> {\n return rendererLights.spotPositionRanges[lightIndex].xyz;\n}\n\nfn rendererSpotLightRangeForLight(lightIndex: u32) -> f32 {\n return rendererLights.spotPositionRanges[lightIndex].w;\n}\n\nfn rendererSpotLightDirectionForLight(lightIndex: u32) -> vec3<f32> {\n // The packed value points from the light towards its target. Material\n // lighting evaluates the incident direction from the fragment back to the\n // light, matching rendererDirectionalLightDirectionForLight().\n return normalize(-rendererLights.spotDirectionCones[lightIndex].xyz);\n}\n\nfn rendererSpotLightConeCosForLight(lightIndex: u32) -> f32 {\n return rendererLights.spotDirectionCones[lightIndex].w;\n}\n\nfn rendererSpotLightPenumbraCosForLight(lightIndex: u32) -> f32 {\n return rendererLights.spotParams[lightIndex].y;\n}\n\nfn rendererSpotLightDecayForLight(lightIndex: u32) -> f32 {\n return rendererLights.spotParams[lightIndex].z;\n}\n\nfn rendererSpotLightColorForLight(lightIndex: u32) -> vec3<f32> {\n let value = rendererLights.spotColorIntensities[lightIndex];\n return value.xyz * value.w;\n}\n\n// These structs make the renderer's packed light buffer available to generic\n// graph nodes. The graph only depends on the semantic fields; this header can\n// later source them from Forward+ storage buffers without changing materials.\nstruct RendererDirectionalLight {\n direction: vec3<f32>,\n color: vec3<f32>,\n};\n\nfn rendererDirectionalLightForLight(lightIndex: u32) -> RendererDirectionalLight {\n return RendererDirectionalLight(\n rendererDirectionalLightDirectionForLight(lightIndex),\n rendererDirectionalLightColorForLight(lightIndex)\n );\n}\n\n// These records match three-shader-graph's established shadow structs. They\n// intentionally expose metadata only; sampling stays behind the renderer's\n// semantic shadow functions so graph code never depends on the atlas layout.\nstruct RendererDirectionalLightShadow {\n shadowBias: f32,\n shadowNormalBias: f32,\n shadowRadius: f32,\n shadowMapSize: vec2<f32>,\n};\n\nfn rendererDirectionalLightShadowForLight(lightIndex: u32) -> RendererDirectionalLightShadow {\n let params = rendererLights.directionalShadowParams[lightIndex];\n let params2 = rendererLights.directionalShadowParams2[lightIndex];\n return RendererDirectionalLightShadow(\n params.x,\n params.w,\n params2.x,\n vec2<f32>(params.z)\n );\n}\n\nstruct RendererPointLight {\n position: vec3<f32>,\n color: vec3<f32>,\n distance: f32,\n decay: f32,\n};\n\nfn rendererPointLightForLight(lightIndex: u32) -> RendererPointLight {\n return RendererPointLight(\n rendererPointLightPositionForLight(lightIndex),\n rendererPointLightColorForLight(lightIndex),\n rendererPointLightRangeForLight(lightIndex),\n 2.0\n );\n}\n\nstruct RendererPointLightShadow {\n shadowBias: f32,\n shadowNormalBias: f32,\n shadowRadius: f32,\n shadowMapSize: vec2<f32>,\n shadowCameraNear: f32,\n shadowCameraFar: f32,\n};\n\nfn rendererPointLightShadowForLight(lightIndex: u32) -> RendererPointLightShadow {\n let params = rendererLights.pointShadowParams[lightIndex];\n let params2 = rendererLights.pointShadowParams2[lightIndex];\n return RendererPointLightShadow(\n params.x,\n params.w,\n params2.x,\n vec2<f32>(params.z),\n params2.z,\n params2.w\n );\n}\n\nstruct RendererSpotLight {\n position: vec3<f32>,\n direction: vec3<f32>,\n color: vec3<f32>,\n distance: f32,\n decay: f32,\n coneCos: f32,\n penumbraCos: f32,\n};\n\nfn rendererSpotLightForLight(lightIndex: u32) -> RendererSpotLight {\n return RendererSpotLight(\n rendererSpotLightPositionForLight(lightIndex),\n rendererSpotLightDirectionForLight(lightIndex),\n rendererSpotLightColorForLight(lightIndex),\n rendererSpotLightRangeForLight(lightIndex),\n rendererSpotLightDecayForLight(lightIndex),\n rendererSpotLightConeCosForLight(lightIndex),\n rendererSpotLightPenumbraCosForLight(lightIndex)\n );\n}\n\nstruct RendererSpotLightShadow {\n shadowBias: f32,\n shadowNormalBias: f32,\n shadowRadius: f32,\n shadowMapSize: vec2<f32>,\n};\n\nfn rendererSpotLightShadowForLight(lightIndex: u32) -> RendererSpotLightShadow {\n let params = rendererLights.spotShadowParams[lightIndex];\n let params2 = rendererLights.spotShadowParams2[lightIndex];\n return RendererSpotLightShadow(\n params.x,\n params.w,\n params2.x,\n vec2<f32>(params.z)\n );\n}\n\nfn rendererDirectionalShadowMatrixForLight(lightIndex: u32) -> mat4x4<f32> {\n return rendererLights.directionalShadowMatrices[lightIndex];\n}\n\nfn rendererDirectionalShadowMatrix() -> mat4x4<f32> {\n return rendererDirectionalShadowMatrixForLight(0u);\n}\n\nfn rendererDirectionalShadowBias() -> f32 {\n return rendererDirectionalShadowBiasForLight(0u);\n}\n\nfn rendererDirectionalShadowBiasForLight(lightIndex: u32) -> f32 {\n return rendererLights.directionalShadowParams[lightIndex].x;\n}\n\nfn rendererDirectionalShadowEnabled() -> bool {\n return rendererDirectionalShadowEnabledForLight(0u);\n}\n\nfn rendererDirectionalShadowEnabledForLight(lightIndex: u32) -> bool {\n return rendererLights.directionalShadowParams[lightIndex].y >= 0.5;\n}\n\nfn rendererDirectionalShadowIntensityForLight(lightIndex: u32) -> f32 {\n return rendererLights.directionalShadowParams2[lightIndex].y;\n}\n\nfn rendererDirectionalShadowMapSize() -> f32 {\n return rendererLights.directionalShadowParams[0].z;\n}\n\nfn rendererPointShadowBias() -> f32 {\n return rendererPointShadowBiasForLight(0u);\n}\n\nfn rendererPointShadowBiasForLight(lightIndex: u32) -> f32 {\n return rendererLights.pointShadowParams[lightIndex].x;\n}\n\nfn rendererPointShadowEnabled() -> bool {\n return rendererPointShadowEnabledForLight(0u);\n}\n\nfn rendererPointShadowEnabledForLight(lightIndex: u32) -> bool {\n return rendererLights.pointShadowParams[lightIndex].y >= 0.5;\n}\n\nfn rendererPointShadowIntensityForLight(lightIndex: u32) -> f32 {\n return rendererLights.pointShadowParams2[lightIndex].y;\n}\n\nfn rendererSpotShadowMatrixForLight(lightIndex: u32) -> mat4x4<f32> {\n return rendererLights.spotShadowMatrices[lightIndex];\n}\n\nfn rendererSpotShadowBiasForLight(lightIndex: u32) -> f32 {\n return rendererLights.spotShadowParams[lightIndex].x;\n}\n\nfn rendererSpotShadowEnabledForLight(lightIndex: u32) -> bool {\n return rendererLights.spotShadowParams[lightIndex].y >= 0.5;\n}\n\nfn rendererSpotShadowIntensityForLight(lightIndex: u32) -> f32 {\n return rendererLights.spotShadowParams2[lightIndex].y;\n}\n\n${l}\n${dr(i)}\n${a}\n${s}\n`}function pr(e,t,r,n="packed",i=!1){const a="camera"===t?`\nstruct RendererCameraUniforms {\n viewProj: mat4x4<f32>,\n cameraPosition: vec4<f32>,\n viewportAndTime: vec4<f32>,\n view: mat4x4<f32>,\n projection: mat4x4<f32>,\n nearFar: vec4<f32>,\n fogColor: vec4<f32>,\n fogParams: vec4<f32>,\n};\n\n@group(0) @binding(0) var<uniform> rendererCamera: RendererCameraUniforms;\n@group(0) @binding(1) var<uniform> rendererLights: array<vec4<f32>, 11>;\n${"instanced-direct"===n?"@group(0) @binding(2) var<storage, read> rendererInstanceMatrices: array<vec4<f32>>;\n@group(0) @binding(3) var<storage, read> rendererInstanceColors: array<vec4<f32>>;":"@group(0) @binding(2) var<storage, read> rendererInstances: array<RendererInstanceData>;"}\n\nfn rendererClipPosition(localPosition: vec3<f32>, instanceIndex: u32) -> vec4<f32> {\n return rendererCamera.viewProj * rendererWorldPosition(localPosition, instanceIndex);\n}\n`:`\nstruct ShadowCameraUniforms {\n viewProj: mat4x4<f32>,\n lightPositionRange: vec4<f32>,\n view: mat4x4<f32>,\n projection: mat4x4<f32>,\n cameraPosition: vec4<f32>,\n nearFar: vec4<f32>,\n timeAndPadding: vec4<f32>,\n};\n\n@group(0) @binding(0) var<uniform> shadowCamera: ShadowCameraUniforms;\n${"instanced-direct"===n?"@group(0) @binding(1) var<storage, read> rendererInstanceMatrices: array<vec4<f32>>;\n@group(0) @binding(2) var<storage, read> rendererInstanceColors: array<vec4<f32>>;":"@group(0) @binding(1) var<storage, read> rendererInstances: array<RendererInstanceData>;"}\n\nfn rendererClipPosition(localPosition: vec3<f32>, instanceIndex: u32) -> vec4<f32> {\n return shadowCamera.viewProj * rendererWorldPosition(localPosition, instanceIndex);\n}\n`,s=cr(e,r);return`\n${a}\n\n${"instanced-direct"===n?"\nfn rendererInstanceModelMatrix(instanceIndex: u32) -> mat4x4<f32> {\n let base = instanceIndex * 4u;\n return mat4x4<f32>(\n rendererInstanceMatrices[base + 0u],\n rendererInstanceMatrices[base + 1u],\n rendererInstanceMatrices[base + 2u],\n rendererInstanceMatrices[base + 3u]\n );\n}\n\nfn rendererObjectColor(instanceIndex: u32) -> vec4<f32> {\n return rendererInstanceColors[instanceIndex];\n}\n\nfn rendererBatchingId(instanceIndex: u32) -> u32 {\n return instanceIndex;\n}\n":"\nstruct RendererInstanceData {\n model0: vec4<f32>,\n model1: vec4<f32>,\n model2: vec4<f32>,\n model3: vec4<f32>,\n color: vec4<f32>,\n batching: vec4<f32>,\n};\n\nfn rendererInstanceModelMatrix(instanceIndex: u32) -> mat4x4<f32> {\n let instance = rendererInstances[instanceIndex];\n return mat4x4<f32>(instance.model0, instance.model1, instance.model2, instance.model3);\n}\n\nfn rendererObjectColor(instanceIndex: u32) -> vec4<f32> {\n return rendererInstances[instanceIndex].color;\n}\n\nfn rendererBatchingId(instanceIndex: u32) -> u32 {\n return u32(round(rendererInstances[instanceIndex].batching.x));\n}\n"}\n\nfn rendererInverseMat3(m: mat3x3<f32>) -> mat3x3<f32> {\n let a = m[0];\n let b = m[1];\n let c = m[2];\n let r0 = cross(b, c);\n let r1 = cross(c, a);\n let r2 = cross(a, b);\n let det = dot(r2, c);\n let safeDet = select(det, select(-1e-8, 1e-8, det >= 0.0), abs(det) < 1e-8);\n let invDet = 1.0 / safeDet;\n return transpose(mat3x3<f32>(r0 * invDet, r1 * invDet, r2 * invDet));\n}\n\nfn rendererInstanceNormalMatrix(instanceIndex: u32) -> mat3x3<f32> {\n let model = rendererInstanceModelMatrix(instanceIndex);\n let model3x3 = mat3x3<f32>(model[0].xyz, model[1].xyz, model[2].xyz);\n return transpose(rendererInverseMat3(model3x3));\n}\n\nfn rendererWorldPosition(localPosition: vec3<f32>, instanceIndex: u32) -> vec4<f32> {\n return rendererInstanceModelMatrix(instanceIndex) * vec4(localPosition, 1.0);\n}\n\nfn rendererWorldNormal(localNormal: vec3<f32>, instanceIndex: u32) -> vec3<f32> {\n return normalize(rendererInstanceNormalMatrix(instanceIndex) * localNormal);\n}\n\n${ur("camera"===t?"rendererCamera":"shadowCamera")}\n${dr(i)}\n${s}\n`}var fr=class{constructor(e,t,r={}){this.name=e,this.callback=t,this.reads=r.reads,this.writes=r.writes,this.dependsOn=r.dependsOn}name;callback;reads;writes;dependsOn;execute(e){this.callback(e)}};import{AlwaysCompare as mr,BufferAttribute as gr,EqualCompare as xr,GreaterCompare as vr,GreaterEqualCompare as wr,LessCompare as br,LessEqualCompare as yr,MirroredRepeatWrapping as Sr,NearestFilter as Cr,NearestMipmapLinearFilter as Pr,NearestMipmapNearestFilter as Mr,NeverCompare as Br,NotEqualCompare as Dr,Object3D as Tr,RepeatWrapping as Ir,Vector3 as Gr}from"three";import{Matrix4 as Rr,Sphere as Lr,Vector3 as zr}from"three";var Ur=24,Vr=12,Ar=new Float32Array(Ur),Fr=new Float32Array([1,1,1,1]),Er="rgba16float",kr=(new Rr).set(1,0,0,0,0,1,0,0,0,0,.5,.5,0,0,0,1),Or=[new zr(0,-1,0),new zr(0,-1,0),new zr(0,0,1),new zr(0,0,-1),new zr(0,-1,0),new zr(0,-1,0)],$r=[new zr(1,0,0),new zr(-1,0,0),new zr(0,1,0),new zr(0,-1,0),new zr(0,0,1),new zr(0,0,-1)],jr=[{name:"position",shaderLocation:0,format:"float32x3"}],Nr=[{name:"position",shaderLocation:0,format:"float32x3"},{name:"skinIndex",shaderLocation:1,format:"uint32x4"},{name:"skinWeight",shaderLocation:2,format:"float32x4"}],Wr=new Rr,_r=new Rr,qr=(new Rr,new Rr,new Lr),Hr=new zr,Kr=new zr,Zr=new zr,Yr=(new zr,new zr,new zr,new zr,new WeakMap),Xr=1;function Jr(e){return e?"version"in e?e.version:e.data.version:0}function Qr(e){const t=Object.keys(e.attributes).sort().map(t=>{const r=e.getAttribute(t);return[t,Jr(r),r?.itemSize??0,r?.count??0].join(":")}).join("|"),r=e.index?.version??0,n=e.groups.map(e=>`${e.start}:${e.count}:${e.materialIndex??0}`).join("|");return[t,r,e.drawRange.start,e.drawRange.count,n].join(";")}function en(e){switch(e){case"float32":case"uint32":case"sint32":return 1;case"float32x2":case"uint32x2":case"sint32x2":return 2;case"float32x3":case"uint32x3":case"sint32x3":return 3;default:return 4}}function tn(e){return 4*en(e)}function rn(e,t){switch(t){case"uint32":return new Uint32Array(e);case"sint32":return new Int32Array(e);default:return new Float32Array(e)}}function nn(e,t,r,n){switch(r){case"uint32":e[t]=Math.max(0,Math.round(n));break;case"sint32":e[t]=Math.trunc(n);break;default:e[t]=n}}function an(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1)if(e[r]!==t[r])return!1;return!0}function sn(e,t,r,n){const i=Math.max(4,t.byteLength),a=e.createBuffer({label:n,size:4*Math.ceil(i/4),usage:r,mappedAtCreation:!0});return new Uint8Array(a.getMappedRange()).set(new Uint8Array(t.buffer,t.byteOffset,t.byteLength)),a.unmap(),a}function on(e){switch(e){case"vertex":return GPUShaderStage.VERTEX;case"vertex-fragment":return GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT;default:return GPUShaderStage.FRAGMENT}}function ln(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1)if(e[r]!==t[r])return!1;return!0}function cn(e,t){if(!e)return!1;if(e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1)if(e[r]!==t[r])return!1;return!0}function un(e,t,r){try{return e.beginComputePass({timestampWrites:{querySet:t,...r}}).end(),!0}catch{return!1}}function dn(e,t,r,n){const i=new Float32Array(t*r);if(!e){for(let e=0;e<t;e+=1)i.set(n,e*r);return i}for(let a=0;a<t;a+=1){for(let t=0;t<r;t+=1)t<e.itemSize?i[a*r+t]=e.getComponent(a,t):i[a*r+t]=n[t]??0;3===e.itemSize&&4===r&&(i[a*r+3]=n[3]??1)}return i}function hn(e,t,r,n,i=0){const a=en(r),s=(o=r).startsWith("uint32")?"uint32":o.startsWith("sint32")?"sint32":"float32";var o;if(!e)return function(e,t,r,n,i,a){const s=rn(r*n,a);for(let o=0;o<r;o+=1){const r=o*t,l=o*n;for(let o=0;o<n;o+=1)nn(s,l+o,a,e&&o<t?e[r+o]??i[o]??0:i[o]??0)}return s}(void 0,0,t,a,n,s);if(0===i&&e instanceof gr&&!e.normalized&&e.itemSize===a&&e.count===t){const t=e.array;if("float32"===s&&t instanceof Float32Array||"uint32"===s&&t instanceof Uint32Array||"sint32"===s&&t instanceof Int32Array)return t}const l=rn(t*a,s);for(let r=0;r<t;r+=1){const t=r*a,o=r-i,c=o>=0&&o<e.count;for(let r=0;r<a;r+=1){nn(l,t+r,s,c&&r<e.itemSize?e.getComponent(o,r):n[r]??0)}}return l}function pn(e,t,r,n){return Number.isFinite(n)&&n>0?n:t?Math.max(0,(e.index?.count??0)-r):Math.max(0,e.getAttribute("position").count-r)}function fn(e,t){return{start:e.drawRange.start,count:pn(e,t,e.drawRange.start,e.drawRange.count)}}function mn(e){return e===Ir?"repeat":e===Sr?"mirror-repeat":"clamp-to-edge"}function gn(e){return e===Cr||e===Mr||e===Pr?"nearest":"linear"}function xn(e){return e instanceof HTMLCanvasElement||e instanceof HTMLImageElement||e instanceof ImageBitmap||e instanceof OffscreenCanvas||e instanceof HTMLVideoElement?e:null}function vn(e){return e}function wn(e,t,r,n,i,a,s){return e.appendMatrixAndColorValues(t,r,n,i,a,s)}function bn(e,t,r,n,i,a,s){return e.appendMatrixAndColorValues(t.elements,r,n,i,a,s)}function yn(e,t,r){const n=e.elements;for(let e=0;e<16;e+=1)n[e]=t[r+e]??0;return e}function Sn(e){const t=Yr.get(e);if(void 0!==t)return t;const r=Xr+=1;return Yr.set(e,r),r}function Cn(e,t,r,n,i,a){return[Sn(e),Sn(t),r?1:0,n,i,a?Sn(a):0].join(":")}function Pn(e,t,r,n,i,a){let s=2166136261;return s=Tn(s,e),s=Tn(s,t),s=Tn(s,r?1:0),s=Tn(s,n),s=Tn(s,i),s=Tn(s,a),s}function Mn(e,t){return e.renderOrder!==t.renderOrder?e.renderOrder-t.renderOrder:(r=e.sortMaterialId,n=e.sortGeometryId,i=e.indexed,a=e.start,s=e.count,o=e.sortCustomDepthMaterialId,l=t.sortMaterialId,c=t.sortGeometryId,u=t.indexed,d=t.start,h=t.count,p=t.sortCustomDepthMaterialId,r!==l?r-l:n!==c?n-c:i!==u?i?-1:1:a!==d?a-d:s!==h?s-h:o-p);var r,n,i,a,s,o,l,c,u,d,h,p}function Bn(e,t){return e.renderOrder!==t.renderOrder?e.renderOrder-t.renderOrder:0!==e.transparentSortGroup&&e.transparentSortGroup===t.transparentSortGroup&&e.transparentSortOrder!==t.transparentSortOrder?e.transparentSortOrder-t.transparentSortOrder:e.sortDepth!==t.sortDepth?t.sortDepth-e.sortDepth:Mn(e,t)}function Dn(e){for(let t=0;t<e.length;t+=1)if(e[t].hasRenderCallbacks)return!0;return!1}function Tn(e,t){let r=Math.imul((e^t)>>>0,16777619);return r^=r>>>13,r>>>0}function In(e,t){return e.renderOrder===t.renderOrder&&!e.hasRenderCallbacks&&!t.hasRenderCallbacks&&e.castShadow===t.castShadow&&e.receiveShadow===t.receiveShadow&&e.usesBatching===t.usesBatching&&e.sortMaterialId===t.sortMaterialId&&e.sortGeometryId===t.sortGeometryId&&e.indexed===t.indexed&&e.start===t.start&&e.count===t.count&&e.sortCustomDepthMaterialId===t.sortCustomDepthMaterialId}function Gn(e,t){return e.renderOrder===t.renderOrder&&!e.hasRenderCallbacks&&!t.hasRenderCallbacks&&e.castShadow===t.castShadow&&e.receiveShadow===t.receiveShadow&&e.usesBatching===t.usesBatching&&e.sortMaterialId===t.sortMaterialId&&e.sortGeometryId===t.sortGeometryId&&e.indexed===t.indexed&&e.start===t.start&&e.count===t.count&&e.sortCustomDepthMaterialId===t.sortCustomDepthMaterialId}function Rn(e,t){for(let r=0;r<16;r+=1)t[r]=e[r]??0}function Ln(e,t){for(let r=0;r<16;r+=1)if((e[r]??0)!==(t[r]??0))return!1;return!0}function zn(e){return 1===(e[0]??0)&&0===(e[1]??0)&&0===(e[2]??0)&&0===(e[3]??0)&&0===(e[4]??0)&&1===(e[5]??0)&&0===(e[6]??0)&&0===(e[7]??0)&&0===(e[8]??0)&&0===(e[9]??0)&&1===(e[10]??0)&&0===(e[11]??0)&&0===(e[12]??0)&&0===(e[13]??0)&&0===(e[14]??0)&&1===(e[15]??0)}function Un(e,t,r,n){r.x<e.x&&(e.x=r.x),r.y<e.y&&(e.y=r.y),r.z<e.z&&(e.z=r.z),n.x>t.x&&(t.x=n.x),n.y>t.y&&(t.y=n.y),n.z>t.z&&(t.z=n.z)}function Vn(e,t){return t.multiplyMatrices(_r.multiplyMatrices(kr,e.projectionMatrix),e.matrixWorldInverse)}function An(e,t,r,n,i,a){const s=Math.hypot(r,n,i)||1;e[t+0]=r/s,e[t+1]=n/s,e[t+2]=i/s,e[t+3]=a/s}function Fn(e){return null===e.boundingSphere&&e.computeBoundingSphere(),e.boundingSphere?{center:e.boundingSphere.center.clone(),radius:e.boundingSphere.radius}:{center:new Gr,radius:1}}function En(e){const t=e.elements,r=Math.hypot(t[0],t[1],t[2]),n=Math.hypot(t[4],t[5],t[6]),i=Math.hypot(t[8],t[9],t[10]);return Math.max(r,n,i,1e-5)}function kn(e,t,r,n){const i=r.x-n,a=r.y-n,s=r.z-n,o=r.x+n,l=r.y+n,c=r.z+n;i<e.x&&(e.x=i),a<e.y&&(e.y=a),s<e.z&&(e.z=s),o>t.x&&(t.x=o),l>t.y&&(t.y=l),c>t.z&&(t.z=c)}function On(e){return Math.floor(Math.max(0,e.count)/3)*Math.max(0,e.instanceCount)}function $n(e){const t=e??1;if(!Number.isInteger(t)||t<1)throw new Error(`Renderer sampleCount must be a positive integer. Received: ${e}`);return t}function jn(e){const t=e.customDepthMaterial;return t&&Ot(t)?t:null}function Nn(e,t){e.latestFrameProfile=qn(t.profile),(t.pendingGpuRead||t.pendingVisibilityRead)&&Promise.all([t.pendingGpuRead?Wn(t.profile,t.pendingGpuRead):Promise.resolve(),t.pendingVisibilityRead?_n(t.profile,t.pendingVisibilityRead):Promise.resolve()]).then(()=>{const r=qn(t.profile);e.latestFrameProfile=r,e.latestCompletedFrameProfile=r})}async function Wn(e,t){try{await t.readBuffer.mapAsync(GPUMapMode.READ);const r=t.readBuffer.getMappedRange(),n=new BigUint64Array(r.slice(0));let i=0;const a=t.profile.passes.map((e,t)=>{const r=Number(n[2*t]??0n),a=Number(n[2*t+1]??0n),s=Math.max(0,a-r)/1e6;return i+=s,{...e,gpuTimeMs:s}});e.gpuTimeMs=i,e.gpuProfilingReason=null,e.passes=a}catch{e.timestampQueryActive=!1,e.gpuTimeMs=null,e.gpuProfilingReason="timestamp readback failed after submission",e.passes=e.passes.map(e=>({...e,gpuTimeMs:null}))}finally{"mapped"===t.readBuffer.mapState&&t.readBuffer.unmap(),t.querySet.destroy(),t.resolveBuffer.destroy(),t.readBuffer.destroy()}}async function _n(e,t){try{await t.readBuffer.mapAsync(GPUMapMode.READ);const r=new Uint32Array(t.readBuffer.getMappedRange());let n=0,i=0,a=0,s=0;for(const e of t.regions){let t=0;const o=e.byteOffset/Uint32Array.BYTES_PER_ELEMENT;for(let n=0;n<e.drawCount;n+=1)t+=r[o+5*n+1]??0;"dynamic"===e.kind?(n+=e.totalInstances,i+=t):(a+=e.totalInstances,s+=t)}const o=n+a,l=i+s;e.visibility={totalInstances:o,visibleInstances:l,culledInstances:Math.max(0,o-l),dynamicTotalInstances:n,dynamicVisibleInstances:i,staticTotalInstances:a,staticVisibleInstances:s}}catch{e.visibility=null}finally{"mapped"===t.readBuffer.mapState&&t.readBuffer.unmap(),t.readBuffer.destroy()}}function qn(e){return{...e,cpuPhases:{...e.cpuPhases},passes:e.passes.map(e=>({...e})),visibility:e.visibility?{...e.visibility}:null}}function Hn(e){return e.usesBatching}function Kn(e){return!e.wireframe&&e.material.primitiveTopology.startsWith("triangle")}function Zn(e,t){return"pointShadow"===t?null!==e.material.pointShadowVertexShader&&null!==e.material.pointShadowFragmentShader:null!==e.material.depthVertexShader||Hn(e)}function Yn(e,t){if(!this.state.visibilityKernel||!this.state.drawMetadataResource||0===this.state.drawMetadataResource.count)return;const r=e.beginComputePass({label:"renderer-visibility-pass"});r.setPipeline(this.state.visibilityKernel.pipeline),r.setBindGroup(0,t),r.dispatchWorkgroups(Math.ceil(this.state.drawMetadataResource.count/64)),r.end()}function Xn(e,t){if(this.state.staticVisibilityClearKernel&&this.state.staticVisibilityCullKernel&&this.state.staticVisibilityIndirectBuildKernel&&this.getHiZOcclusionCullingActive())for(const r of this.staticDrawSets){if(!r.publicSet.enabled||0===r.drawMetadataResource.count)continue;if("postpass"===t&&r.lastPreVisibilityFrameToken!==this.staticFrameToken)continue;if(!this.state.device)continue;const n="prepass"===t?r.visibilityParamsUpload:r.postVisibilityParamsUpload,i="prepass"===t?r.visibilityParamsBuffer:r.postVisibilityParamsBuffer;n[1]=this.state.hizMipCount,n[3]="prepass"===t?this.state.temporalHiZHistoryValid?3:0:5,this.state.device.queue.writeBuffer(i,0,vn(n),0,4);const a=this.getOrCreateStaticVisibilityBindGroup(r,t);if(!a)continue;if("prepass"!==t||r.visibilityClearBindGroup&&r.visibilityIndirectBuildBindGroup&&r.postVisibilityIndirectBuildBindGroup||(r.visibilityClearBindGroup=this.state.staticVisibilityClearKernel.createBindGroup(this.state.device,[{binding:0,resource:{buffer:r.visibilityParamsBuffer}},{binding:1,resource:{buffer:r.instanceVisibilityResource.visibleCountsBuffer}},{binding:2,resource:{buffer:r.instanceVisibilityResource.postVisibleCountsBuffer}},{binding:3,resource:{buffer:r.instanceVisibilityResource.visibleInstanceMaskBuffer}}],`${r.label}-visibility-clear-bind-group`),r.visibilityIndirectBuildBindGroup=this.state.staticVisibilityIndirectBuildKernel.createBindGroup(this.state.device,[{binding:0,resource:{buffer:r.visibilityParamsBuffer}},{binding:1,resource:{buffer:r.instanceVisibilityResource.visibleCountsBuffer}},{binding:2,resource:{buffer:r.instanceVisibilityResource.postVisibleCountsBuffer}},{binding:3,resource:{buffer:r.drawMetadataResource.indirectBuffer}},{binding:4,resource:{buffer:r.drawMetadataResource.postIndirectBuffer}}],`${r.label}-visibility-indirect-build-bind-group`),r.postVisibilityIndirectBuildBindGroup=this.state.staticVisibilityIndirectBuildKernel.createBindGroup(this.state.device,[{binding:0,resource:{buffer:r.postVisibilityParamsBuffer}},{binding:1,resource:{buffer:r.instanceVisibilityResource.visibleCountsBuffer}},{binding:2,resource:{buffer:r.instanceVisibilityResource.postVisibleCountsBuffer}},{binding:3,resource:{buffer:r.drawMetadataResource.indirectBuffer}},{binding:4,resource:{buffer:r.drawMetadataResource.postIndirectBuffer}}],`${r.label}-post-visibility-indirect-build-bind-group`)),"prepass"===t){const t=e.beginComputePass({label:`${r.label}-temporal-visibility-clear-pass`});t.setPipeline(this.state.staticVisibilityClearKernel.pipeline),t.setBindGroup(0,r.visibilityClearBindGroup),t.dispatchWorkgroups(Math.ceil(Math.max(r.drawMetadataResource.count,r.instanceVisibilityResource.instanceCount)/64)),t.end()}const s=e.beginComputePass({label:`${r.label}-temporal-visibility-${t}-cull-pass`});s.setPipeline(this.state.staticVisibilityCullKernel.pipeline),s.setBindGroup(0,a),s.dispatchWorkgroups(Math.ceil(r.instanceVisibilityResource.instanceCount/64)),s.end();const o=e.beginComputePass({label:`${r.label}-temporal-visibility-${t}-indirect-build-pass`});o.setPipeline(this.state.staticVisibilityIndirectBuildKernel.pipeline),o.setBindGroup(0,"prepass"===t?r.visibilityIndirectBuildBindGroup:r.postVisibilityIndirectBuildBindGroup),o.dispatchWorkgroups(Math.ceil(r.drawMetadataResource.count/64)),o.end(),"prepass"===t?r.lastPreVisibilityFrameToken=this.staticFrameToken:r.lastVisibilityFrameToken=this.staticFrameToken}}function Jn(e,t){if(!(this.state.device&&this.state.staticVisibilityCullKernel&&this.state.hizTexture&&this.state.temporalVisibilityBuffer&&this.state.nearestClampSampler))return null;const r="prepass"===t?e.visibilityBindGroup:e.postVisibilityBindGroup;if(r&&e.visibilityBindGroupHizVersion===this.hizResourceVersion)return r;const n=this.state.staticVisibilityCullKernel.createBindGroup(this.state.device,[{binding:0,resource:{buffer:this.state.temporalVisibilityBuffer}},{binding:1,resource:{buffer:"prepass"===t?e.visibilityParamsBuffer:e.postVisibilityParamsBuffer}},{binding:2,resource:this.state.nearestClampSampler},{binding:3,resource:this.state.hizTexture.createView()},{binding:4,resource:{buffer:e.instanceVisibilityResource.instanceMetadataBuffer}},{binding:5,resource:{buffer:e.drawMetadataResource.metadataBuffer}},{binding:6,resource:{buffer:e.instanceVisibilityResource.visibleCountsBuffer}},{binding:7,resource:{buffer:e.instanceVisibilityResource.visibleInstanceIndicesBuffer}},{binding:8,resource:{buffer:e.instanceVisibilityResource.visibleInstanceMaskBuffer}},{binding:9,resource:{buffer:e.instanceVisibilityResource.postVisibleCountsBuffer}}],`${e.label}-temporal-visibility-${t}-bind-group`);return"prepass"===t?e.visibilityBindGroup=n:e.postVisibilityBindGroup=n,e.visibilityBindGroupHizVersion=this.hizResourceVersion,n}function Qn(e,t,r,n){if(!this.state.shadowDepthPipeline||0===this.state.directionalShadowLayerViews.length)return void this.clearDirectionalShadow(e);let i=!1;for(let t=0;t<r.lights.directionals.length;t+=1){const a=r.lights.directionals[t],s=this.state.directionalShadowLayerViews[t];if(!a.castShadow||!s)continue;i=!0;const o=this.directionalShadowCameras[t];o.left=a.shadowCameraLeft,o.right=a.shadowCameraRight,o.top=a.shadowCameraTop,o.bottom=a.shadowCameraBottom,o.near=a.shadowCameraNear,o.far=a.shadowCameraFar,o.position.copy(a.position),o.lookAt(a.target),o.updateMatrixWorld(!0),o.updateProjectionMatrix();const l=this.getShadowCameraBuffer(t);this.writeShadowCameraBuffer(Vn(o,this.shadowViewProjScratch),0,0,0,1,l,o);const c=this.getSharedShadowBindGroupForCameraBuffer(l),u=e.beginRenderPass({label:`renderer-directional-shadow-pass-${t}`,colorAttachments:[],depthStencilAttachment:{view:s,depthClearValue:1,depthLoadOp:"clear",depthStoreOp:"store"}});u.setPipeline(this.state.shadowDepthPipeline),u.setBindGroup(0,c),this.drawDepthLike(u,r.gpuOpaqueDraws,n,{fallbackPipeline:this.state.shadowDepthPipeline,fallbackPipelineDirect:this.state.shadowDepthPipelineDirect,fallbackSkinnedPipeline:this.state.skinnedShadowDepthPipeline,fallbackBindGroup:c,shadowCameraBuffer:l,passKind:"directionalShadow",customDepthMode:"use"}),this.drawDepthLike(u,r.directOpaqueDraws,n,{fallbackPipeline:this.state.shadowDepthPipeline,fallbackPipelineDirect:this.state.shadowDepthPipelineDirect,fallbackSkinnedPipeline:this.state.skinnedShadowDepthPipeline,fallbackBindGroup:c,shadowCameraBuffer:l,passKind:"directionalShadow",customDepthMode:"use"});for(const e of this.staticDrawSets)e.publicSet.enabled&&0!==e.draws.length&&(this.renderBundleScratch[0]=li.call(this,e,c,l,"directionalShadow",this.state.shadowDepthPipeline,this.state.shadowDepthPipelineDirect),u.executeBundles(this.renderBundleScratch),this.recordStaticDrawStats(e,n));u.end()}i||this.clearDirectionalShadow(e)}function ei(e,t,r,n){if(!r.lights.points.some(e=>e.castShadow))return;if(!this.state.pointShadowPipeline||!this.state.pointShadowFaceViews.length||!this.state.pointShadowDepthFaceViews.length)return void this.clearPointShadow(e);let i=!1;for(let t=0;t<r.lights.points.length;t+=1){const a=r.lights.points[t];if(a.castShadow){i=!0;for(let i=0;i<6;i+=1){const s=6*t+i,o=this.pointShadowCameras[t][i];o.near=a.shadowCameraNear,o.far=a.shadowCameraFar,o.position.copy(a.position),Hr.copy(a.position).add($r[i]),o.up.copy(Or[i]),o.lookAt(Hr),o.updateMatrixWorld(!0),o.updateProjectionMatrix();const l=this.getShadowCameraBuffer(4+s);this.writeShadowCameraBuffer(Vn(o,this.shadowViewProjScratch),a.position.x,a.position.y,a.position.z,a.range,l,o);const c=this.getSharedShadowBindGroupForCameraBuffer(l),u=e.beginRenderPass({label:`renderer-point-shadow-pass-${t}-${i}`,colorAttachments:[{view:this.state.pointShadowFaceViews[s],clearValue:{r:1,g:1,b:1,a:1},loadOp:"clear",storeOp:"store"}],depthStencilAttachment:{view:this.state.pointShadowDepthFaceViews[s],depthClearValue:1,depthLoadOp:"clear",depthStoreOp:"store"}});u.setPipeline(this.state.pointShadowPipeline),u.setBindGroup(0,c),this.drawDepthLike(u,r.gpuOpaqueDraws,n,{fallbackPipeline:this.state.pointShadowPipeline,fallbackPipelineDirect:this.state.pointShadowPipelineDirect,fallbackSkinnedPipeline:this.state.skinnedPointShadowPipeline,fallbackBindGroup:c,shadowCameraBuffer:l,passKind:"pointShadow",customDepthMode:"use"}),this.drawDepthLike(u,r.directOpaqueDraws,n,{fallbackPipeline:this.state.pointShadowPipeline,fallbackPipelineDirect:this.state.pointShadowPipelineDirect,fallbackSkinnedPipeline:this.state.skinnedPointShadowPipeline,fallbackBindGroup:c,shadowCameraBuffer:l,passKind:"pointShadow",customDepthMode:"use"});for(const e of this.staticDrawSets)e.publicSet.enabled&&0!==e.draws.length&&(this.renderBundleScratch[0]=li.call(this,e,c,l,"pointShadow",this.state.pointShadowPipeline,this.state.pointShadowPipelineDirect),u.executeBundles(this.renderBundleScratch),this.recordStaticDrawStats(e,n));u.end()}}}i||this.clearPointShadow(e)}function ti(e,t,r,n){if(!r.lights.spots.some(e=>e.castShadow))return;if(!this.state.shadowDepthPipeline||0===this.state.spotShadowLayerViews.length)return void this.clearSpotShadow(e);let i=!1;for(let t=0;t<r.lights.spots.length;t+=1){const a=r.lights.spots[t],s=this.state.spotShadowLayerViews[t];if(!a.castShadow||!s)continue;i=!0;const o=this.spotShadowCameras[t];o.near=a.shadowCameraNear,o.far=a.shadowCameraFar,o.fov=a.shadowCameraFov,o.aspect=1,o.position.copy(a.position),Hr.copy(a.position).add(a.direction),o.lookAt(Hr),o.updateMatrixWorld(!0),o.updateProjectionMatrix();const l=this.getShadowCameraBuffer(28+t);this.writeShadowCameraBuffer(Vn(o,this.shadowViewProjScratch),0,0,0,1,l,o);const c=this.getSharedShadowBindGroupForCameraBuffer(l),u=e.beginRenderPass({label:`renderer-spot-shadow-pass-${t}`,colorAttachments:[],depthStencilAttachment:{view:s,depthClearValue:1,depthLoadOp:"clear",depthStoreOp:"store"}});u.setPipeline(this.state.shadowDepthPipeline),u.setBindGroup(0,c),this.drawDepthLike(u,r.gpuOpaqueDraws,n,{fallbackPipeline:this.state.shadowDepthPipeline,fallbackPipelineDirect:this.state.shadowDepthPipelineDirect,fallbackSkinnedPipeline:this.state.skinnedShadowDepthPipeline,fallbackBindGroup:c,shadowCameraBuffer:l,passKind:"directionalShadow",customDepthMode:"use"}),this.drawDepthLike(u,r.directOpaqueDraws,n,{fallbackPipeline:this.state.shadowDepthPipeline,fallbackPipelineDirect:this.state.shadowDepthPipelineDirect,fallbackSkinnedPipeline:this.state.skinnedShadowDepthPipeline,fallbackBindGroup:c,shadowCameraBuffer:l,passKind:"directionalShadow",customDepthMode:"use"});for(const e of this.staticDrawSets)e.publicSet.enabled&&0!==e.draws.length&&(this.renderBundleScratch[0]=li.call(this,e,c,l,"directionalShadow",this.state.shadowDepthPipeline,this.state.shadowDepthPipelineDirect),u.executeBundles(this.renderBundleScratch),this.recordStaticDrawStats(e,n));u.end()}i||this.clearSpotShadow(e)}function ri(e,t,r,n){if(!this.state.depthPrepassPipeline||!this.state.mainDepthView)return;const i=e.beginRenderPass({label:"renderer-depth-prepass",colorAttachments:[],depthStencilAttachment:{view:this.state.mainDepthView,depthClearValue:1,depthLoadOp:"clear",depthStoreOp:"store"}});i.setPipeline(this.state.depthPrepassPipeline),i.setBindGroup(0,t),this.executeStaticDepthPrepass(i,t,n),this.drawDepthLike(i,r.gpuOpaqueDraws,n,{fallbackPipeline:this.state.depthPrepassPipeline,fallbackPipelineDirect:this.state.depthPrepassPipelineDirect,fallbackSkinnedPipeline:this.state.skinnedDepthPrepassPipeline,fallbackBindGroup:t,passKind:"prepass",customDepthMode:"skip"}),this.drawDepthLike(i,r.directOpaqueDraws,n,{fallbackPipeline:this.state.depthPrepassPipeline,fallbackPipelineDirect:this.state.depthPrepassPipelineDirect,fallbackSkinnedPipeline:this.state.skinnedDepthPrepassPipeline,fallbackBindGroup:t,passKind:"prepass",customDepthMode:"skip"}),i.end()}function ni(e,t,r){for(const n of this.staticDrawSets){if(!n.publicSet.enabled||0===n.draws.length)continue;if(this.getHiZOcclusionCullingActive()&&n.lastPreVisibilityFrameToken===this.staticFrameToken){const e=this.getOrCreateStaticVisibleDepthSceneBindGroup(n);this.renderBundleScratch[0]=ii.call(this,n,e)}else this.renderBundleScratch[0]=this.getOrCreateStaticDepthPrepassBundle(n,t);e.executeBundles(this.renderBundleScratch),this.recordStaticDrawStats(n,r)}}function ii(e,t,r=e.drawMetadataResource.indirectBuffer,n="prepass"){if(!this.state.device||!this.state.depthPrepassPipelineVisible)throw new Error("Renderer visible depth prepass resources are not initialized.");const i=e.indirectDepthPrepassBundles[n];if(i?.sceneBindGroup===t&&i.indirectBuffer===r)return i.bundle;const a=`${e.label}-static-temporal-depth-${n}-bundle-${e.id}`,s=this.state.device.createRenderBundleEncoder({label:a,colorFormats:[],depthStencilFormat:"depth32float",sampleCount:1});s.setPipeline(this.state.depthPrepassPipelineVisible),s.setBindGroup(0,t);let o=null;for(let t=0;t<e.draws.length;t+=1){const n=e.draws[t];n.customDepthMaterial||Zn(n,"prepass")||Ci(n.material)||!Kn(n)||(o!==n.geometryKey&&(o=n.geometryKey,this.bindGeometryVertexBuffers(s,n.geometry,n.geometryResource,jr,0,1,n.wireframe)),s.drawIndexedIndirect(r,5*t*Uint32Array.BYTES_PER_ELEMENT))}const l=s.finish({label:a});return e.indirectDepthPrepassBundles[n]={sceneBindGroup:t,indirectBuffer:r,bundle:l},l}function ai(e){}function si(e,t){if(!this.state.device||!this.state.depthPrepassPipeline)throw new Error("Renderer is not initialized.");const r=this.resolveSceneBindGroupForDraw(e.draws[0],t);if(e.depthPrepassBundle&&e.depthPrepassBundleSceneBindGroup===r)return e.depthPrepassBundle;const n=oi.call(this,e,"prepass"),i=`${e.label}-static-depth-prepass-bundle-${e.id}`,a=this.state.device.createRenderBundleEncoder({label:i,colorFormats:[],depthStencilFormat:"depth32float",sampleCount:1});a.setBindGroup(0,r);let s=null,o=null,l=null;for(let t=0;t<e.draws.length;t+=1){const r=e.draws[t],i=n[t];if(r.customDepthMaterial||!i&&(Ci(r.material)||!Kn(r)))continue;const c=i?.pipeline??this.state.depthPrepassPipeline;s!==c&&(s=c,o=null,l=null,a.setPipeline(c)),i&&o!==i.bindGroup&&(o=i.bindGroup,a.setBindGroup(1,o)),l!==r.geometryKey&&(l=r.geometryKey,this.bindGeometryVertexBuffers(a,r.geometry,r.geometryResource,i?.vertexAttributes??jr,r.instanceStart,r.instanceCount,r.wireframe)),a.drawIndexed(r.count,r.instanceCount,r.start,0,r.instanceStart)}const c=a.finish({label:i});return e.depthPrepassBundle=c,e.depthPrepassBundleSceneBindGroup=r,c}function oi(e,t){const r=t,n=e.depthMaterialResources.get(r);if(n)return n;const i=e.draws.map(e=>{const r=Zn(e,t);if(e.customDepthMaterial||!r)return null;return this.getDepthPassMaterialResourceForDraw(e.material,t,e)});return e.depthMaterialResources.set(r,i),i}function li(e,t,r,n,i,a){if(!this.state.device)throw new Error("Renderer is not initialized.");const s=this.resolveShadowBindGroupForDraw(e.draws[0],t,r),o=e.shadowBundles.get(s),l=o?.[n];if(l)return l;const c=oi.call(this,e,n),u=`${e.label}-static-${n}-bundle-${e.id}`,d=this.state.device.createRenderBundleEncoder({label:u,colorFormats:"pointShadow"===n?["rgba16float"]:[],depthStencilFormat:"depth32float",sampleCount:1});d.setBindGroup(0,s);let h=null,p=null,f=null;for(let t=0;t<e.draws.length;t+=1){const r=e.draws[t];if(!r.castShadow)continue;const n=c[t],s=n?.pipeline??("instanced-direct"===this.getDrawInstanceAccessMode(r)&&a?a:i);h!==s&&(h=s,p=null,f=null,d.setPipeline(s)),n&&p!==n.bindGroup&&(p=n.bindGroup,d.setBindGroup(1,p)),f!==r.geometryKey&&(f=r.geometryKey,this.bindGeometryVertexBuffers(d,r.geometry,r.geometryResource,n?.vertexAttributes??jr,r.instanceStart,r.instanceCount,r.wireframe)),d.drawIndexed(r.count,r.instanceCount,r.start,0,r.instanceStart)}const m=d.finish({label:u});return e.shadowBundles.set(s,{...o,[n]:m}),m}function ci(e,t=!1){if(!(this.state.device&&this.state.hizTexture&&this.state.mainDepthTexture&&this.state.mainDepthView&&this.state.hizCopyKernel&&this.state.hizReduceKernel))return;let r=this.state.hizCopyBindGroup;r||(r=this.state.hizCopyKernel.createBindGroup(this.state.device,[{binding:0,resource:this.state.mainDepthView},{binding:1,resource:this.state.hizMipViews[0]}],"renderer-hiz-copy-bind-group"),this.state.hizCopyBindGroup=r);const n=e.beginComputePass({label:"renderer-hiz-copy-pass"});n.setPipeline(this.state.hizCopyKernel.pipeline),n.setBindGroup(0,r),n.dispatchWorkgroups(Math.ceil(this.state.width/8),Math.ceil(this.state.height/8)),n.end();for(let t=1;t<this.state.hizMipCount;t+=1){const r=Math.max(1,this.state.width>>t),n=Math.max(1,this.state.height>>t);let i=this.state.hizReduceBindGroups[t];i||(i=this.state.hizReduceKernel.createBindGroup(this.state.device,[{binding:0,resource:this.state.hizMipViews[t-1]},{binding:1,resource:this.state.hizMipViews[t]}],`renderer-hiz-reduce-bind-group-${t}`),this.state.hizReduceBindGroups[t]=i);const a=e.beginComputePass({label:`renderer-hiz-reduce-pass-${t}`});a.setPipeline(this.state.hizReduceKernel.pipeline),a.setBindGroup(0,i),a.dispatchWorkgroups(Math.ceil(r/8),Math.ceil(n/8)),a.end()}t&&this.commitTemporalHiZHistory()}function ui(e,t,r,n,i,a,s=!1,o="all",l=!1,c=this.sampleCount){if(!this.state.mainDepthView)return;const u=c>1,d=u?this.ensureMsaaColorTarget(t):null,h=u?this.ensureMsaaDepthTarget(d.width,d.height):null,p=e.beginRenderPass({label:"renderer-forward-pass",colorAttachments:[{view:d?.view??r,resolveTarget:d?r:void 0,clearValue:{r:this.clearColor[0],g:this.clearColor[1],b:this.clearColor[2],a:this.clearColor[3]},loadOp:l?"load":"clear",storeOp:d?"discard":"store"}],depthStencilAttachment:{view:h?.view??this.state.mainDepthView,depthClearValue:1,depthLoadOp:h||s?"clear":"load",depthStoreOp:h?"discard":"store"}});let f=null,m=null,g=null,x=null,v=null;const w=e=>{e.sourceObject&&e.hasRenderCallbacks&&e.sourceObject.onBeforeRender(this,i.scene,i.camera,e.geometry,e.material,e.geometryGroup);const t=e.geometryResource,r=this.getMaterialResourceForDraw(e,[Er],c),s=this.resolveSceneBindGroupForDraw(e,n);if(f!==r.pipeline&&(f=r.pipeline,g=null,v=null,p.setPipeline(f)),g!==e.geometryKey&&(g=e.geometryKey,this.bindGeometryVertexBuffers(p,e.geometry,t,r.vertexAttributes,e.instanceStart,e.instanceCount,e.wireframe)),x!==s&&(x=s,p.setBindGroup(0,s)),m!==e.material){if(m=e.material,p.setBindGroup(1,r.bindGroup),!r.graphTextureBindGroupLayout)throw new Error("Graph texture layout is missing.");p.setBindGroup(3,this.createGraphTextureBindGroup(e.material,r.graphTextureBindGroupLayout))}r.usesSkinning&&e.skinning&&v!==e.skinning.bindGroup&&(v=e.skinning.bindGroup,p.setBindGroup(2,v)),e.indexed&&(e.wireframe?t.wireframeIndex:t.index)?p.drawIndexed(e.count,e.instanceCount,e.start,0,e.instanceStart):p.draw(e.count,e.instanceCount,e.start,e.instanceStart),this.recordDraw(e,a),e.sourceObject&&e.hasRenderCallbacks&&e.sourceObject.onAfterRender(this,i.scene,i.camera,e.geometry,e.material,e.geometryGroup)};if("late"!==o&&this.executeStaticForwardPass(p,n,a),f=null,m=null,g=null,x=null,v=null,"late"!==o&&this.getHiZOcclusionCullingActive()&&this.state.drawMetadataResource){const e=this.buildIndirectSubmissionStreams(i.gpuOpaqueDraws,n),t=this.renderBundleScratch;t.length=0;for(let r=0;r<e.length;r+=1){const n=e[r];t[0]=this.getOrCreateIndirectForwardBundle(n),p.executeBundles(t),a.drawCallCount+=n.drawCallCount,a.triangleCount+=n.triangleCount}f=null,m=null,g=null,x=null}else if("late"!==o){const e=Dn(i.gpuOpaqueDraws)||i.gpuOpaqueDraws.some(e=>null!==e.skinning)?null:this.getOrCreateDirectForwardBundle(i.gpuOpaqueDraws,n,a);if(e)this.renderBundleScratch[0]=e,p.executeBundles(this.renderBundleScratch);else for(const e of i.gpuOpaqueDraws)w(e)}const b="late"===o||Dn(i.directOpaqueDraws)||i.directOpaqueDraws.some(e=>null!==e.skinning)?null:this.getOrCreateDirectForwardBundle(i.directOpaqueDraws,n,a);if(b)this.renderBundleScratch[0]=b,p.executeBundles(this.renderBundleScratch);else if("late"!==o)for(const e of i.directOpaqueDraws)w(e);if("opaque"!==o)for(const e of i.transparentDraws)w(e);p.end()}function di(e,t,r){for(const n of this.staticDrawSets)if(n.publicSet.enabled&&0!==n.draws.length){if(this.getHiZOcclusionCullingActive()&&n.lastVisibilityFrameToken===this.staticFrameToken){const t=this.getOrCreateStaticVisibleSceneBindGroup(n),i=this.getOrCreateStaticIndirectSubmissionStreams(n,t);for(const t of i)if(this.getMultiDrawIndirectActive()){if(e.setPipeline(t.materialResource.pipeline),this.bindGeometryVertexBuffers(e,t.geometry,t.geometryResource,t.materialResource.vertexAttributes,0,1,t.material.wireframe),e.setBindGroup(0,t.sceneBindGroup),e.setBindGroup(1,t.materialResource.bindGroup),!t.materialResource.graphTextureBindGroupLayout)throw new Error("Graph texture layout is missing.");e.setBindGroup(3,this.createGraphTextureBindGroup(t.material,t.materialResource.graphTextureBindGroupLayout)),e.multiDrawIndexedIndirect(n.drawMetadataResource.indirectBuffer,5*t.indirectStartIndex*Uint32Array.BYTES_PER_ELEMENT,t.indirectCount),r.drawCallCount+=t.drawCallCount,r.triangleCount+=t.triangleCount}else this.renderBundleScratch[0]=this.getOrCreateIndirectForwardBundle(t,n.drawMetadataResource,n.indirectForwardBundleCache,`${n.label}-static-indirect-forward-bundle`),e.executeBundles(this.renderBundleScratch),r.drawCallCount+=t.drawCallCount,r.triangleCount+=t.triangleCount;continue}this.renderBundleScratch[0]=this.getOrCreateStaticDirectForwardBundle(n,t),e.executeBundles(this.renderBundleScratch),this.recordStaticDrawStats(n,r)}}function hi(e,t){if(!this.state.device||!this.state.format)throw new Error("Renderer is not initialized.");const r=this.resolveSceneBindGroupForDraw(e.draws[0],t);if(e.directForwardBundle&&e.directForwardBundleSceneBindGroup===r)return e.directForwardBundle;null==e.draws[0]?.materialResource&&(this.refreshStaticDrawMaterialResources(e.draws),this.syncStaticVisibleMaterialBindingCaches(e));const n=`${e.label}-static-forward-direct-bundle-${e.id}`,i=this.state.device.createRenderBundleEncoder({label:n,colorFormats:[Er],depthStencilFormat:"depth32float",sampleCount:this.sampleCount});let a=null,s=null,o=null;i.setBindGroup(0,r);for(const t of e.draws){const e=t.materialResource??this.getMaterialResource(t.material,this.getDrawInstanceAccessMode(t),t.receiveShadow,void 0,null!==t.skinning,Hn(t));if(a!==e.pipeline&&(a=e.pipeline,o=null,i.setPipeline(a)),o!==t.geometryKey&&(o=t.geometryKey,this.bindGeometryVertexBuffers(i,t.geometry,t.geometryResource,e.vertexAttributes,t.instanceStart,t.instanceCount,t.wireframe)),s!==e.bindGroup){if(s=e.bindGroup,i.setBindGroup(1,s),!e.graphTextureBindGroupLayout)throw new Error("Graph texture layout is missing.");i.setBindGroup(3,this.createGraphTextureBindGroup(t.material,e.graphTextureBindGroupLayout))}i.drawIndexed(t.count,t.instanceCount,t.start,0,t.instanceStart)}const l=i.finish({label:n});return e.directForwardBundle=l,e.directForwardBundleSceneBindGroup=r,l}function pi(e){for(const t of e.visibleMaterialBindings){const r=t.drawIndices[0];t.resource=e.draws[r]?.materialResource??e.visibleDrawMaterialResources[r]??null}}function fi(e){for(const t of e)t.materialResource=this.getMaterialResource(t.material,this.getDrawInstanceAccessMode(t),t.receiveShadow,void 0,null!==t.skinning,Hn(t))}function mi(e,t){t.drawCallCount+=e.drawCallCount,t.triangleCount+=e.triangleCount}function gi(){return this.staticDrawSets.some(e=>e.publicSet.enabled&&e.draws.length>0)}function xi(e,t,r){if(!(this.state.device&&this.state.presentPipeline&&this.state.fullscreenTextureBindGroupLayout&&this.state.linearClampSampler))return;let n=this.state.presentBindGroups.get(t);n||(n=this.state.device.createBindGroup({label:"renderer-present-bind-group",layout:this.state.fullscreenTextureBindGroupLayout,entries:[{binding:0,resource:this.state.linearClampSampler},{binding:1,resource:t}]}),this.state.presentBindGroups.set(t,n));const i=e.beginRenderPass({label:"renderer-present-pass",colorAttachments:[{view:r,clearValue:{r:this.clearColor[0],g:this.clearColor[1],b:this.clearColor[2],a:this.clearColor[3]},loadOp:"clear",storeOp:"store"}]});i.setPipeline(this.state.presentPipeline),i.setBindGroup(0,n),i.draw(3),i.end()}function vi(e){for(let t=0;t<this.state.directionalShadowLayerViews.length;t+=1){e.beginRenderPass({label:`renderer-clear-directional-shadow-${t}`,colorAttachments:[],depthStencilAttachment:{view:this.state.directionalShadowLayerViews[t],depthClearValue:1,depthLoadOp:"clear",depthStoreOp:"store"}}).end()}}function wi(e){for(let t=0;t<this.state.pointShadowFaceViews.length;t+=1){e.beginRenderPass({label:`renderer-clear-point-shadow-${t}`,colorAttachments:[{view:this.state.pointShadowFaceViews[t],clearValue:{r:1,g:1,b:1,a:1},loadOp:"clear",storeOp:"store"}],depthStencilAttachment:{view:this.state.pointShadowDepthFaceViews[t],depthClearValue:1,depthLoadOp:"clear",depthStoreOp:"store"}}).end()}}function bi(e){for(let t=0;t<this.state.spotShadowLayerViews.length;t+=1){e.beginRenderPass({label:`renderer-clear-spot-shadow-${t}`,colorAttachments:[],depthStencilAttachment:{view:this.state.spotShadowLayerViews[t],depthClearValue:1,depthLoadOp:"clear",depthStoreOp:"store"}}).end()}}function yi(e,t,r,n){let i=null,a=null,s=null,o=null,l=null;for(const c of t){if("prepass"!==n.passKind&&!c.castShadow)continue;if("prepass"===n.passKind&&null===c.material.depthVertexShader&&Ci(c.material))continue;if("skip"===n.customDepthMode&&c.customDepthMaterial)continue;const t=Zn(c,n.passKind),u="use"===n.customDepthMode&&c.customDepthMaterial?c.customDepthMaterial:"ignore"!==n.customDepthMode&&t?c.material:null,d=u?this.getDepthPassMaterialResourceForDraw(u,n.passKind,c):null;if(!d&&!Kn(c))continue;const h=null!==c.skinning,p=d?.pipeline??(h&&n.fallbackSkinnedPipeline?n.fallbackSkinnedPipeline:"instanced-direct"===this.getDrawInstanceAccessMode(c)&&n.fallbackPipelineDirect?n.fallbackPipelineDirect:n.fallbackPipeline);a!==p&&(a=p,s=null,o=null,l=null,i=null,e.setPipeline(p));const f="prepass"===n.passKind?this.resolveSceneBindGroupForDraw(c,n.fallbackBindGroup):this.resolveShadowBindGroupForDraw(c,n.fallbackBindGroup,n.shadowCameraBuffer);s!==f&&(s=f,e.setBindGroup(0,f)),d?o!==d.bindGroup&&(o=d.bindGroup,e.setBindGroup(1,d.bindGroup)):o=null,(d?.usesSkinning??h)&&c.skinning&&l!==c.skinning.bindGroup&&(l=c.skinning.bindGroup,e.setBindGroup(2,l));const m=c.geometryResource;i!==c.geometryKey&&(i=c.geometryKey,this.bindGeometryVertexBuffers(e,c.geometry,m,d?.vertexAttributes??(h?Nr:jr),c.instanceStart,c.instanceCount,c.wireframe)),c.indexed&&(c.wireframe?m.wireframeIndex:m.index)?e.drawIndexed(c.count,c.instanceCount,c.start,0,c.instanceStart):e.draw(c.count,c.instanceCount,c.start,c.instanceStart),this.recordDraw(c,r)}}var Si=new WeakMap;function Ci(e){if(e.transparent)return!0;let t=Si.get(e);return null==t&&(t=e.transparent||e.alphaTest>0||/\bdiscard\b/.test(e.fragmentShader),Si.set(e,t)),t}import{Vector3 as Pi}from"three";var Mi=class{data;lengthFloats=0;constructor(e=1024){this.data=new Float32Array(e)}get floatLength(){return this.lengthFloats}get rawData(){return this.data}get byteLength(){return this.lengthFloats*Float32Array.BYTES_PER_ELEMENT}get instanceCount(){return this.lengthFloats/Ur}reset(){this.lengthFloats=0}appendMatrixAndColor(e,t){return this.appendMatrixAndColorValues(e,t[0]??1,t[1]??1,t[2]??1,t[3]??1)}appendMatrixAndColorValues(e,t,r,n,i,a=this.instanceCount){const s=this.instanceCount;this.ensureCapacity(this.lengthFloats+Ur);const o=this.lengthFloats;for(let t=0;t<16;t+=1)this.data[o+t]=e[t]??0;return this.data[o+16]=t,this.data[o+17]=r,this.data[o+18]=n,this.data[o+19]=i,this.data[o+20]=a,this.data[o+21]=0,this.data[o+22]=0,this.data[o+23]=0,this.lengthFloats+=Ur,s}appendRange(e,t,r){if(r<=0)return;const n=t*Ur,i=n+r*Ur;this.ensureCapacity(this.lengthFloats+(i-n)),this.data.set(e.data.subarray(n,i),this.lengthFloats),this.lengthFloats+=i-n}appendBuilder(e){this.appendRange(e,0,e.instanceCount)}beginWriteInstances(e){const t=e*Ur;return this.ensureCapacity(t),this.lengthFloats=t,this.data}toFloat32Array(){return this.data.slice(0,this.lengthFloats)}ensureCapacity(e){if(e<=this.data.length)return;let t=this.data.length;for(;t<e;)t*=2;const r=new Float32Array(t);r.set(this.data.subarray(0,this.lengthFloats),0),this.data=r}},Bi=class{constructor(e,t,r,n,i){this.state=e,this.staticDrawSets=t,this.getGeometryResourceForGeometry=r,this.resolveMaterial=n,this.ensureWireframeIndex=i}state;staticDrawSets;getGeometryResourceForGeometry;resolveMaterial;ensureWireframeIndex;nextStaticDrawSetId=1;activeMaterialSnapshots=null;getGeometryResource(e){return this.getGeometryResourceForGeometry(e)}resolveStaticMaterial(e){const t=this.resolveMaterial(e);if(!t||!this.activeMaterialSnapshots)return t;let r=this.activeMaterialSnapshots.get(t);return r||(r=t.clone(),r.name=t.name?`${t.name} (static snapshot)`:"Static draw-set material snapshot",this.activeMaterialSnapshots.set(t,r)),r}createStaticDrawSet(e,t={}){if(!(this.state.initialized&&this.state.device&&this.state.staticVisibilityClearKernel&&this.state.staticVisibilityCullKernel&&this.state.staticVisibilityIndirectBuildKernel))throw new Error("WebGpuRenderer.initialize() must complete before creating a static draw set.");const r=t.label??`static-draw-set-${this.nextStaticDrawSetId}`,n=t.onUnsupported??"throw",i=[],a=new Mi(4096),s=(e,t)=>{if("skip"!==n)throw new Error(`StaticDrawSet "${r}" does not support ${e.type||"Object3D"} "${e.name||e.uuid}": ${t}.`)};e.updateMatrixWorld(!0);const o=new Map;this.activeMaterialSnapshots=o;try{e.traverseVisible(e=>{e.isSkinnedMesh?s(e,"skinned meshes are dynamic"):e.isBatchedMesh?this.collectStaticBatchedMesh(e,a,i,r,s):e.isInstancedMesh?this.collectStaticInstancedMesh(e,a,i,r,s):e.isMesh&&this.collectStaticMesh(e,a,i,r,s)})}catch(e){for(const e of o.values())e.dispose();throw e}finally{this.activeMaterialSnapshots=null}const{draws:l,instanceData:c}=this.mergeStaticDraws(i,a),u=this.createVisibleMaterialBindings(l),d=Math.max(4,c.byteLength),h=this.state.device.createBuffer({label:`${r}-static-instance-buffer`,size:256*Math.ceil(d/256),usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST});c.floatLength>0?this.state.device.queue.writeBuffer(h,0,c.rawData.buffer,0,c.byteLength):this.state.device.queue.writeBuffer(h,0,Ar,0,Ur);const p={mode:"packed",buffer:h,colorBuffer:null,sceneBindGroup:null,shadowBindGroup:null,shadowBindGroups:new Map,sceneBindGroupVersion:0,shadowBindGroupVersion:0};for(const e of l)e.residentInstanceBinding=p;const f=this.createStaticDrawMetadataResource(r,l),m=this.createStaticInstanceVisibilityResource(r,l,c),g=new Uint32Array([l.length,this.state.hizMipCount,c.instanceCount,0]),x=this.state.device.createBuffer({label:`${r}-visibility-params-buffer`,size:16,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),v=new Uint32Array([l.length,this.state.hizMipCount,c.instanceCount,0]),w=this.state.device.createBuffer({label:`${r}-post-visibility-params-buffer`,size:16,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST});this.state.device.queue.writeBuffer(x,0,g,0,4),this.state.device.queue.writeBuffer(w,0,v,0,4);const b={id:this.nextStaticDrawSetId++,label:r,publicSet:null,ownedMaterials:[...o.values()],draws:l,drawCallCount:l.length,triangleCount:l.reduce((e,t)=>e+Math.floor(Math.max(0,t.count)/3)*Math.max(0,t.instanceCount),0),instanceCount:c.instanceCount,instanceBuffer:h,residentInstanceBinding:p,drawMetadataResource:f,instanceVisibilityResource:m,visibilityParamsBuffer:x,visibilityParamsUpload:g,postVisibilityParamsBuffer:w,postVisibilityParamsUpload:v,visibilityBindGroup:null,postVisibilityBindGroup:null,visibilityClearBindGroup:null,visibilityIndirectBuildBindGroup:null,postVisibilityIndirectBuildBindGroup:null,visibleSceneBindGroup:null,visibleSceneBindGroupVersion:0,visibleDepthSceneBindGroup:null,visibleDepthSceneBindGroupVersion:0,visibleMaterialBindings:u,visibleDrawMaterialResources:new Array(l.length),visibleIndirectSubmissionStreams:null,visibleIndirectStreamsSceneBindGroup:null,visibleIndirectStreamsSampleCount:-1,visibleIndirectStreamsColorFormatsKey:"",visibilityBindGroupHizVersion:0,lastPreVisibilityFrameToken:0,lastVisibilityFrameToken:0,indirectForwardBundleCache:new Map,directForwardBundle:null,directForwardBundleSceneBindGroup:null,depthPrepassBundle:null,depthPrepassBundleSceneBindGroup:null,indirectDepthPrepassBundles:{prepass:null,postpass:null},shadowBundles:new WeakMap,depthMaterialResources:new Map},y={label:r,enabled:!0,get drawCount(){return b.draws.length},get instanceCount(){return b.instanceCount},dispose:()=>{this.disposeStaticDrawSetResource(b)}};return b.publicSet=y,this.staticDrawSets.push(b),y}createVisibleMaterialBindings(e){const t=new Map;for(let r=0;r<e.length;r+=1){const n=e[r],i=`${Sn(n.material)}:${n.receiveShadow?1:0}:${n.usesBatching?1:0}`;let a=t.get(i);a||(a={material:n.material,receiveShadow:n.receiveShadow,usesBatching:n.usesBatching,drawIndices:[],resource:null},t.set(i,a)),a.drawIndices.push(r)}return[...t.values()]}mergeStaticDraws(e,t){e.sort(Mn);const r=[],n=new Mi(Math.max(1024,t.floatLength));for(let i=0;i<e.length;){const a=e[i],s=n.instanceCount;n.appendRange(t,a.instanceStart,a.instanceCount);let o=a.instanceCount,l=a.boundsCenter.x-a.boundsRadius,c=a.boundsCenter.y-a.boundsRadius,u=a.boundsCenter.z-a.boundsRadius,d=a.boundsCenter.x+a.boundsRadius,h=a.boundsCenter.y+a.boundsRadius,p=a.boundsCenter.z+a.boundsRadius,f=i+1;for(;f<e.length&&Gn(a,e[f]);){const r=e[f];n.appendRange(t,r.instanceStart,r.instanceCount),o+=r.instanceCount;const i=r.boundsCenter.x-r.boundsRadius,a=r.boundsCenter.y-r.boundsRadius,s=r.boundsCenter.z-r.boundsRadius,m=r.boundsCenter.x+r.boundsRadius,g=r.boundsCenter.y+r.boundsRadius,x=r.boundsCenter.z+r.boundsRadius;i<l&&(l=i),a<c&&(c=a),s<u&&(u=s),m>d&&(d=m),g>h&&(h=g),x>p&&(p=x),f+=1}const m=.5*(l+d),g=.5*(c+h),x=.5*(u+p),v=d-m,w=h-g,b=p-x;a.instanceStart=s,a.instanceCount=o,a.boundsCenter.set(m,g,x),a.boundsRadius=Math.sqrt(v*v+w*w+b*b),r.push(a),i=f}return{draws:r,instanceData:n}}collectStaticMesh(e,t,r,n,i){if(!(null!==e.geometry.index))return void i(e,"non-indexed geometry cannot use the v1 indirect static path");if(jn(e))return void i(e,"custom depth materials are not supported by StaticDrawSet v1");const a=this.getGeometryResource(e.geometry),s=Fn(e.geometry),o=Hr.copy(s.center).applyMatrix4(e.matrixWorld),l=s.radius*En(e.matrixWorld),c=bn(t,e.matrixWorld,1,1,1,1),u=Array.isArray(e.material)?e.material:null,d=Array.isArray(e.material)?null:e.material;if(e.geometry.groups.length>0){for(const t of e.geometry.groups){const n=u?u[t.materialIndex??0]??u[0]:d,h=this.resolveStaticMaterial(n);if(!h){i(e,"all static mesh materials must be WGSLShaderMaterial");continue}if(h.transparent){i(e,"transparent materials are not supported by StaticDrawSet v1");continue}if(Object.keys(h.getGraphTextureInputs()).length>0){i(e,"scene-texture materials are not supported by StaticDrawSet v1");continue}const p=pn(e.geometry,!0,t.start,t.count);p<=0||r.push(this.createStaticDrawRecord(e.geometry,e.geometry,a,h,!1,t.start,p,c,1,o.x,o.y,o.z,l,s.center,s.radius))}return}const h=d??u?.[0]??null,p=this.resolveStaticMaterial(h);if(!p)return void i(e,"all static mesh materials must be WGSLShaderMaterial");if(p.transparent)return void i(e,"transparent materials are not supported by StaticDrawSet v1");if(Object.keys(p.getGraphTextureInputs()).length>0)return void i(e,"scene-texture materials are not supported by StaticDrawSet v1");const f=fn(e.geometry,!0);f.count<=0||r.push(this.createStaticDrawRecord(e.geometry,e.geometry,a,p,!1,f.start,f.count,c,1,o.x,o.y,o.z,l,s.center,s.radius))}collectStaticInstancedMesh(e,t,r,n,i){const a=this.resolveStaticMaterial(e.material);if(!a)return void i(e,"static instanced meshes must use WGSLShaderMaterial");if(a.transparent)return void i(e,"transparent materials are not supported by StaticDrawSet v1");if(Object.keys(a.getGraphTextureInputs()).length>0)return void i(e,"scene-texture materials are not supported by StaticDrawSet v1");if(jn(e))return void i(e,"custom depth materials are not supported by StaticDrawSet v1");if(null===e.geometry.index)return void i(e,"non-indexed geometry cannot use the v1 indirect static path");const s=fn(e.geometry,!0);if(s.count<=0||e.count<=0)return;const o=Fn(e.geometry),l=Hr.set(1/0,1/0,1/0),c=Kr.set(-1/0,-1/0,-1/0),u=this.getGeometryResource(e.geometry),d=t.instanceCount;for(let r=0;r<e.count;r+=1){e.getMatrixAt(r,Wr),_r.multiplyMatrices(e.matrixWorld,Wr);const n=e.instanceColor?e.instanceColor.getComponent(r,0):1,i=e.instanceColor&&e.instanceColor.itemSize>1?e.instanceColor.getComponent(r,1):1,a=e.instanceColor&&e.instanceColor.itemSize>2?e.instanceColor.getComponent(r,2):1,s=e.instanceColor&&e.instanceColor.itemSize>3?e.instanceColor.getComponent(r,3):1;bn(t,_r,n,i,a,s);kn(l,c,Zr.copy(o.center).applyMatrix4(_r),o.radius*En(_r))}const h=.5*(l.x+c.x),p=.5*(l.y+c.y),f=.5*(l.z+c.z),m=c.x-h,g=c.y-p,x=c.z-f,v=Math.sqrt(m*m+g*g+x*x);r.push(this.createStaticDrawRecord(e.geometry,e.geometry,u,a,!1,s.start,s.count,d,e.count,h,p,f,v,o.center,o.radius))}collectStaticBatchedMesh(e,t,r,n,i){const a=this.resolveStaticMaterial(e.material);if(!a)return void i(e,"static batched meshes must use WGSLShaderMaterial");if(a.transparent)return void i(e,"transparent materials are not supported by StaticDrawSet v1");if(Object.keys(a.getGraphTextureInputs()).length>0)return void i(e,"scene-texture materials are not supported by StaticDrawSet v1");if(jn(e))return void i(e,"custom depth materials are not supported by StaticDrawSet v1");if(null===e.geometry.index)return void i(e,"non-indexed geometry cannot use the v1 indirect static path");const s=e,o=this.getGeometryResource(e.geometry),l=s._geometryCount??0,c=[],u=new Map;for(let t=0;t<l;t+=1){const r=e.getGeometryRangeAt(t);if(!r||r.count<=0)continue;const n=pn(e.geometry,!0,r.start,r.count);if(n<=0)continue;const i=e.getBoundingSphereAt(t,qr),a={geometryId:t,start:r.start,count:n,localBoundsCenter:i?i.center.clone():new Pi,localBoundsRadius:i?.radius??1,instances:[]};u.set(t,a),c.push(a)}const d=s._instanceInfo??s._drawInfo??[],h=s._matricesTexture?.image.data,p=s._colorsTexture?.image.data;for(let t=0;t<d.length;t+=1){const r=d[t];if(!r?.active||!r.visible)continue;const n=u.get(r.geometryIndex);if(!n)continue;h?yn(Wr,h,16*t):e.getMatrixAt(t,Wr),_r.multiplyMatrices(e.matrixWorld,Wr);const i=4*t,a=p?p[i+0]??1:1,s=p?p[i+1]??1:1,o=p?p[i+2]??1:1,l=p?p[i+3]??1:1,c=Zr.copy(n.localBoundsCenter).applyMatrix4(_r),f=n.localBoundsRadius*En(_r);n.instances.push({matrix:new Float32Array(_r.elements),color0:a,color1:s,color2:o,color3:l,batchingId:t,boundsCenter:c.clone(),boundsRadius:f})}for(const n of c){if(0===n.instances.length)continue;const i=Hr.set(1/0,1/0,1/0),s=Kr.set(-1/0,-1/0,-1/0),l=t.instanceCount;for(const e of n.instances)t.appendMatrixAndColorValues(e.matrix,e.color0,e.color1,e.color2,e.color3,e.batchingId),kn(i,s,e.boundsCenter,e.boundsRadius);const c=.5*(i.x+s.x),u=.5*(i.y+s.y),d=.5*(i.z+s.z),h=s.x-c,p=s.y-u,f=s.z-d,m=Math.sqrt(h*h+p*p+f*f);r.push(this.createStaticDrawRecord(e.geometry,e.geometry,o,a,!0,n.start,n.count,l,n.instances.length,c,u,d,m,n.localBoundsCenter,n.localBoundsRadius))}}createStaticDrawRecord(e,t,r,n,i,a,s,o,l,c,u,d,h,p,f){const m=Sn(n),g=n.wireframe&&"triangle-list"===n.primitiveTopology;g&&this.ensureWireframeIndex(e,r);const x=Sn(t);return{geometry:e,geometryKey:g?r.wireframeIndex:t,geometryResource:r,material:n,customDepthMaterial:null,residentInstanceBinding:null,sourceObject:null,usesBatching:i,geometryGroup:null,batchKey:Cn(n,t,!0,a,s,null),batchHash:Pn(m,x,!0,a,s,0),indexed:!0,wireframe:g,start:g?2*a:a,count:g?2*s:s,transparent:!1,renderOrder:0,hasRenderCallbacks:!1,castShadow:!0,receiveShadow:!0,sortMaterialId:m,sortGeometryId:x,sortCustomDepthMaterialId:0,skinning:null,materialResource:null,instanceStart:o,instanceCount:l,boundsCenter:new Pi(c,u,d),boundsRadius:h,sortDepth:0,transparentSortGroup:0,transparentSortOrder:0,staticLocalBoundsCenter:p.clone(),staticLocalBoundsRadius:f}}createStaticDrawMetadataResource(e,t){if(!this.state.device)throw new Error("Renderer is not initialized.");const r=Math.max(1,t.length),n=new Float32Array(r*Vr),i=new Uint32Array(5*r),a=new Uint32Array(5*r);for(let e=0;e<t.length;e+=1){const r=t[e],s=e*Vr;n[s+0]=r.boundsCenter.x,n[s+1]=r.boundsCenter.y,n[s+2]=r.boundsCenter.z,n[s+3]=r.boundsRadius,n[s+4]=r.count,n[s+5]=r.start,n[s+6]=r.instanceStart,n[s+7]=r.instanceCount,n[s+8]=1,n[s+9]=0,n[s+10]=0,n[s+11]=0;const o=5*e;i[o+0]=r.count,i[o+1]=r.instanceCount,i[o+2]=r.start,i[o+3]=0,i[o+4]=r.instanceStart,a[o+0]=r.count,a[o+1]=0,a[o+2]=r.start,a[o+3]=0,a[o+4]=r.instanceStart}const s=this.state.device.createBuffer({label:`${e}-static-draw-metadata-buffer`,size:r*Vr*4,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST}),o=this.state.device.createBuffer({label:`${e}-static-indirect-draw-buffer`,size:5*r*4,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.INDIRECT|GPUBufferUsage.COPY_DST|GPUBufferUsage.COPY_SRC}),l=this.state.device.createBuffer({label:`${e}-static-post-indirect-draw-buffer`,size:5*r*4,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.INDIRECT|GPUBufferUsage.COPY_DST});return this.state.device.queue.writeBuffer(s,0,n,0,n.length),this.state.device.queue.writeBuffer(o,0,i,0,i.length),this.state.device.queue.writeBuffer(l,0,a,0,a.length),{count:t.length,capacity:r,metadataBuffer:s,indirectBuffer:o,postIndirectBuffer:l}}createStaticInstanceVisibilityResource(e,t,r){if(!this.state.device)throw new Error("Renderer is not initialized.");const n=r.instanceCount,i=Math.max(32,32*n),a=new ArrayBuffer(i),s=new Float32Array(a),o=new Uint32Array(a);for(let e=0;e<t.length;e+=1){const n=t[e],i=n.staticLocalBoundsCenter??Fn(n.geometry).center,a=n.staticLocalBoundsRadius??Fn(n.geometry).radius;for(let t=0;t<n.instanceCount;t+=1){const l=n.instanceStart+t,c=l*Ur,u=8*l;Wr.fromArray(r.rawData,c);const d=Hr.copy(i).applyMatrix4(Wr),h=a*En(Wr);s[u+0]=d.x,s[u+1]=d.y,s[u+2]=d.z,s[u+3]=h,o[u+4]=e,o[u+5]=l,o[u+6]=0,o[u+7]=0}}const l=this.state.device.createBuffer({label:`${e}-static-instance-visibility-metadata`,size:256*Math.ceil(i/256),usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST}),c=this.state.device.createBuffer({label:`${e}-static-visible-instance-indices`,size:256*Math.ceil(Math.max(4,4*n)/256),usage:GPUBufferUsage.STORAGE}),u=this.state.device.createBuffer({label:`${e}-static-visible-instance-counts`,size:256*Math.ceil(Math.max(4,4*t.length)/256),usage:GPUBufferUsage.STORAGE}),d=this.state.device.createBuffer({label:`${e}-static-post-visible-instance-counts`,size:256*Math.ceil(Math.max(4,4*t.length)/256),usage:GPUBufferUsage.STORAGE}),h=this.state.device.createBuffer({label:`${e}-static-visible-instance-mask`,size:256*Math.ceil(Math.max(4,4*n)/256),usage:GPUBufferUsage.STORAGE});return n>0&&this.state.device.queue.writeBuffer(l,0,a),{instanceMetadataBuffer:l,visibleInstanceIndicesBuffer:c,visibleCountsBuffer:u,postVisibleCountsBuffer:d,visibleInstanceMaskBuffer:h,instanceCount:n}}disposeStaticDrawSetResource(e){const t=this.staticDrawSets.indexOf(e);if(t<0)return;this.staticDrawSets.splice(t,1);const r=new Set;for(const t of e.draws)t.materialResource&&r.add(t.materialResource);for(const t of e.visibleMaterialBindings)t.resource&&r.add(t.resource);for(const t of e.visibleDrawMaterialResources)t&&r.add(t);for(const t of e.depthMaterialResources.values())for(const e of t)e&&r.add(e);for(const e of r)e.uniformBuffer?.destroy();e.instanceBuffer.destroy(),e.drawMetadataResource.metadataBuffer.destroy(),e.drawMetadataResource.indirectBuffer.destroy(),e.drawMetadataResource.postIndirectBuffer.destroy(),e.instanceVisibilityResource.instanceMetadataBuffer.destroy(),e.instanceVisibilityResource.visibleInstanceIndicesBuffer.destroy(),e.instanceVisibilityResource.visibleCountsBuffer.destroy(),e.instanceVisibilityResource.postVisibleCountsBuffer.destroy(),e.instanceVisibilityResource.visibleInstanceMaskBuffer.destroy(),e.visibilityParamsBuffer.destroy(),e.postVisibilityParamsBuffer.destroy();for(const t of e.ownedMaterials)t.dispose();e.ownedMaterials.length=0,e.residentInstanceBinding.buffer=null,e.residentInstanceBinding.colorBuffer=null,e.residentInstanceBinding.sceneBindGroup=null,e.residentInstanceBinding.shadowBindGroup=null,e.residentInstanceBinding.shadowBindGroups.clear(),e.visibilityBindGroup=null,e.postVisibilityBindGroup=null,e.visibilityClearBindGroup=null,e.visibilityIndirectBuildBindGroup=null,e.postVisibilityIndirectBuildBindGroup=null,e.visibleSceneBindGroup=null,e.visibleDepthSceneBindGroup=null,e.visibleMaterialBindings.length=0,e.visibleDrawMaterialResources.length=0,e.visibleIndirectSubmissionStreams=null,e.visibleIndirectStreamsSceneBindGroup=null,e.visibleIndirectStreamsSampleCount=-1,e.visibleIndirectStreamsColorFormatsKey="",e.indirectForwardBundleCache.clear(),e.directForwardBundle=null,e.directForwardBundleSceneBindGroup=null,e.depthPrepassBundle=null,e.depthPrepassBundleSceneBindGroup=null,e.indirectDepthPrepassBundles.prepass=null,e.indirectDepthPrepassBundles.postpass=null,e.shadowBundles=new WeakMap,e.depthMaterialResources.clear()}},Di=class{constructor(e,t){this.state=e,this.textureCache=t}state;textureCache;skippedExternalTextureWarnings=new WeakSet;destroyTextureResource(e){e?.texture.destroy()}createTextureSampler(e,t){if(!this.state.device)throw new Error("Renderer is not initialized.");const r="non-filtering"===t,n=r?"nearest":gn(e.magFilter),i=r?"nearest":gn(e.minFilter),a=r?"nearest":gn(e.minFilter),s="comparison"===t?function(e){switch(e){case Br:return"never";case br:return"less";case xr:return"equal";case yr:return"less-equal";case vr:return"greater";case Dr:return"not-equal";case wr:return"greater-equal";case mr:return"always";default:return}}(e.compareFunction):void 0,o=r||"linear"!==n||"linear"!==i||"linear"!==a?1:Math.max(1,e.anisotropy);return this.state.device.createSampler({label:`${e.uuid}-sampler`,addressModeU:mn(e.wrapS),addressModeV:mn(e.wrapT),addressModeW:mn(e.wrapR??e.wrapT),magFilter:n,minFilter:i,mipmapFilter:a,maxAnisotropy:o,compare:s})}uploadDataTextureResource(e,t,r){if(!this.state.device)throw new Error("Renderer is not initialized.");const n=function(e){switch(e){case"r8unorm":case"r8snorm":case"r8uint":case"r8sint":return 1;case"r16uint":case"r16sint":case"r16float":case"rg8unorm":case"rg8snorm":case"rg8uint":case"rg8sint":case"depth16unorm":return 2;case"r32uint":case"r32sint":case"r32float":case"rg16uint":case"rg16sint":case"rg16float":case"rgba8unorm":case"rgba8unorm-srgb":case"rgba8snorm":case"rgba8uint":case"rgba8sint":case"bgra8unorm":case"bgra8unorm-srgb":case"rgb9e5ufloat":case"rgb10a2unorm":case"rg11b10ufloat":case"depth32float":return 4;case"rg32uint":case"rg32sint":case"rg32float":case"rgba16uint":case"rgba16sint":case"rgba16float":return 8;case"rgba32uint":case"rgba32sint":case"rgba32float":return 16;default:return null}}(r.format);if(null===n)throw new Error(`Texture format "${r.format}" from "${e.constructor.name}" cannot be uploaded with queue.writeTexture.`);const i=e.mipmaps;if(i&&i.length>0){for(let e=0;e<i.length;e+=1){const a=i[e];if(!a?.data)continue;const s=a.width??Math.max(1,r.width>>e),o=a.height??Math.max(1,r.height>>e),l=a.depth??r.depthOrArrayLayers;this.state.device.queue.writeTexture({texture:t,mipLevel:e},vn(a.data),{bytesPerRow:s*n,rowsPerImage:o},{width:s,height:o,depthOrArrayLayers:l})}return}const a=e.image;a?.data&&this.state.device.queue.writeTexture({texture:t},a.data,{bytesPerRow:r.width*n,rowsPerImage:r.height},{width:r.width,height:r.height,depthOrArrayLayers:r.depthOrArrayLayers})}uploadCompressedTextureResource(e,t,r){if(!this.state.device)throw new Error("Renderer is not initialized.");const n="bc1-rgba-unorm"===(i=r.format)||"bc1-rgba-unorm-srgb"===i?{byteLength:8,width:4,height:4}:"bc2-rgba-unorm"===i||"bc2-rgba-unorm-srgb"===i||"bc3-rgba-unorm"===i||"bc3-rgba-unorm-srgb"===i?{byteLength:16,width:4,height:4}:"bc4-r-unorm"===i||"bc4-r-snorm"===i?{byteLength:8,width:4,height:4}:"bc5-rg-unorm"===i||"bc5-rg-snorm"===i||"bc6h-rgb-ufloat"===i||"bc6h-rgb-float"===i||"bc7-rgba-unorm"===i||"bc7-rgba-unorm-srgb"===i?{byteLength:16,width:4,height:4}:"etc2-rgb8unorm"===i||"etc2-rgb8unorm-srgb"===i||"etc2-rgb8a1unorm"===i||"etc2-rgb8a1unorm-srgb"===i?{byteLength:8,width:4,height:4}:"etc2-rgba8unorm"===i||"etc2-rgba8unorm-srgb"===i?{byteLength:16,width:4,height:4}:"eac-r11unorm"===i||"eac-r11snorm"===i?{byteLength:8,width:4,height:4}:"eac-rg11unorm"===i||"eac-rg11snorm"===i||"astc-4x4-unorm"===i||"astc-4x4-unorm-srgb"===i?{byteLength:16,width:4,height:4}:"astc-5x4-unorm"===i||"astc-5x4-unorm-srgb"===i?{byteLength:16,width:5,height:4}:"astc-5x5-unorm"===i||"astc-5x5-unorm-srgb"===i?{byteLength:16,width:5,height:5}:"astc-6x5-unorm"===i||"astc-6x5-unorm-srgb"===i?{byteLength:16,width:6,height:5}:"astc-6x6-unorm"===i||"astc-6x6-unorm-srgb"===i?{byteLength:16,width:6,height:6}:"astc-8x5-unorm"===i||"astc-8x5-unorm-srgb"===i?{byteLength:16,width:8,height:5}:"astc-8x6-unorm"===i||"astc-8x6-unorm-srgb"===i?{byteLength:16,width:8,height:6}:"astc-8x8-unorm"===i||"astc-8x8-unorm-srgb"===i?{byteLength:16,width:8,height:8}:"astc-10x5-unorm"===i||"astc-10x5-unorm-srgb"===i?{byteLength:16,width:10,height:5}:"astc-10x6-unorm"===i||"astc-10x6-unorm-srgb"===i?{byteLength:16,width:10,height:6}:"astc-10x8-unorm"===i||"astc-10x8-unorm-srgb"===i?{byteLength:16,width:10,height:8}:"astc-10x10-unorm"===i||"astc-10x10-unorm-srgb"===i?{byteLength:16,width:10,height:10}:"astc-12x10-unorm"===i||"astc-12x10-unorm-srgb"===i?{byteLength:16,width:12,height:10}:"astc-12x12-unorm"===i||"astc-12x12-unorm-srgb"===i?{byteLength:16,width:12,height:12}:null;var i;if(!n)throw new Error(`Compressed texture format "${r.format}" is not supported for upload.`);if(!0===e.isCompressedCubeTexture){const i=e.image;for(let e=0;e<i.length;e+=1){const a=i[e]?.mipmaps??[];for(let i=0;i<a.length;i+=1){const s=a[i];if(!s?.data)continue;const o=s.width??Math.max(1,r.width>>i),l=s.height??Math.max(1,r.height>>i),c=Math.max(1,Math.ceil(o/n.width)),u=Math.max(1,Math.ceil(l/n.height));this.state.device.queue.writeTexture({texture:t,mipLevel:i,origin:{x:0,y:0,z:e}},vn(s.data),{bytesPerRow:c*n.byteLength,rowsPerImage:u},{width:c*n.width,height:u*n.height,depthOrArrayLayers:1})}}return}const a=e.mipmaps;for(let e=0;e<a.length;e+=1){const i=a[e];if(!i?.data)continue;const s=i.width??Math.max(1,r.width>>e),o=i.height??Math.max(1,r.height>>e),l=Math.max(1,Math.ceil(s/n.width)),c=Math.max(1,Math.ceil(o/n.height));this.state.device.queue.writeTexture({texture:t,mipLevel:e},vn(i.data),{bytesPerRow:l*n.byteLength,rowsPerImage:c},{width:l*n.width,height:c*n.height,depthOrArrayLayers:r.depthOrArrayLayers})}}uploadExternalTextureResource(e,t,r){if(!this.state.device)throw new Error("Renderer is not initialized.");if(!0===e.isCubeTexture){const n=e.image;if(!Array.isArray(n)||6!==n.length)return void this.warnSkippedExternalTextureUpload(e,r,"CubeTexture must provide exactly six face images.");for(let i=0;i<n.length;i+=1){const a=xn(n[i]);if(!a)return void this.warnSkippedExternalTextureUpload(e,r,`CubeTexture face ${i} is not a copyable image source.`);try{this.state.device.queue.copyExternalImageToTexture({source:a,flipY:e.flipY},{texture:t,origin:{x:0,y:0,z:i}},{width:r.width,height:r.height,depthOrArrayLayers:1})}catch(t){return void this.warnSkippedExternalTextureUpload(e,r,`CubeTexture face ${i} could not be copied: ${Ti(t)}`)}}return}const n=function(e){return xn(e.image)}(e);if(n)try{this.state.device.queue.copyExternalImageToTexture({source:n,flipY:e.flipY},{texture:t},{width:r.width,height:r.height,depthOrArrayLayers:1})}catch(t){this.warnSkippedExternalTextureUpload(e,r,`copyExternalImageToTexture failed: ${Ti(t)}`)}else this.warnSkippedExternalTextureUpload(e,r,"Texture.image is not an HTML image, canvas, video, ImageBitmap, or OffscreenCanvas.")}warnSkippedExternalTextureUpload(e,t,r){if(this.skippedExternalTextureWarnings.has(e))return;this.skippedExternalTextureWarnings.add(e);const n=e.image;console.warn(`[WebGpuRenderer] Skipped upload for texture "${e.name||e.uuid}"; the WebGPU material remains active and samples a zero-cleared fallback texture. ${r}`,{texture:e,textureClass:e.constructor.name,textureName:e.name||void 0,textureUuid:e.uuid,textureFlags:{isRenderTargetTexture:!0===e.isRenderTargetTexture,isVideoTexture:!0===e.isVideoTexture,isCanvasTexture:!0===e.isCanvasTexture,isCubeTexture:!0===e.isCubeTexture},descriptor:t,image:{className:n?.constructor?.name??typeof n,width:n?.width,height:n?.height,depth:n?.depth,src:n?.currentSrc??n?.src,hasData:null!=n?.data,keys:null==n?[]:Object.keys(n).slice(0,16)},userData:e.userData})}uploadTextureResource(e,t,r){!function(e){return!0===e.isCompressedTexture||!0===e.isCompressedArrayTexture}(e)&&!0!==e.isCompressedCubeTexture?!0!==e.isDataTexture&&!0!==e.isDataArrayTexture&&!0!==e.isData3DTexture?this.uploadExternalTextureResource(e,t,r):this.uploadDataTextureResource(e,t,r):this.uploadCompressedTextureResource(e,t,r)}getTextureResource(e){if(!this.state.device)throw new Error("Renderer is not initialized.");const t=this.textureCache.get(e),r=ve(e,this.state.device);if(t&&t.version===e.version&&t.width===r.width&&t.height===r.height&&t.depthOrArrayLayers===r.depthOrArrayLayers&&t.format===r.format&&t.textureDimension===r.textureDimension&&t.viewDimension===r.viewDimension&&t.sampleType===r.sampleType&&t.samplerBindingType===r.samplerBindingType&&t.mipLevelCount===r.mipLevelCount)return t;this.destroyTextureResource(t);const n=this.state.device.createTexture({label:`${e.uuid}-texture`,size:{width:r.width,height:r.height,depthOrArrayLayers:r.depthOrArrayLayers},dimension:r.textureDimension,format:r.format,mipLevelCount:r.mipLevelCount,usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|(r.compressed||"3d"===r.textureDimension?0:GPUTextureUsage.RENDER_ATTACHMENT)});this.uploadTextureResource(e,n,r);const i=this.createTextureSampler(e,r.samplerBindingType),a={version:e.version,width:r.width,height:r.height,depthOrArrayLayers:r.depthOrArrayLayers,format:r.format,textureDimension:r.textureDimension,viewDimension:r.viewDimension,sampleType:r.sampleType,samplerBindingType:r.samplerBindingType,mipLevelCount:r.mipLevelCount,texture:n,view:n.createView("2d"===r.viewDimension?void 0:"2d-array"===r.viewDimension?{dimension:"2d-array",arrayLayerCount:r.depthOrArrayLayers}:{dimension:r.viewDimension}),sampler:i};return this.textureCache.set(e,a),a}};function Ti(e){return e instanceof Error?e.message:String(e)}var Ii="\nstruct ShadowCameraUniforms {\n viewProj: mat4x4<f32>,\n lightPositionRange: vec4<f32>,\n};\n\nstruct RendererInstanceData {\n model0: vec4<f32>,\n model1: vec4<f32>,\n model2: vec4<f32>,\n model3: vec4<f32>,\n color: vec4<f32>,\n batching: vec4<f32>,\n};\n\nstruct PointShadowVertexOutput {\n @builtin(position) position: vec4<f32>,\n @location(0) worldPosition: vec3<f32>,\n};\n\n@group(0) @binding(0) var<uniform> shadowCamera: ShadowCameraUniforms;\n@group(0) @binding(1) var<storage, read> rendererInstances: array<RendererInstanceData>;\n\nfn rendererInstanceModelMatrix(instanceIndex: u32) -> mat4x4<f32> {\n let instance = rendererInstances[instanceIndex];\n return mat4x4<f32>(instance.model0, instance.model1, instance.model2, instance.model3);\n}\n\n@vertex\nfn vsMain(\n @location(0) position: vec3<f32>,\n @builtin(instance_index) instanceIndex: u32\n) -> PointShadowVertexOutput {\n var output: PointShadowVertexOutput;\n let world = rendererInstanceModelMatrix(instanceIndex) * vec4(position, 1.0);\n output.position = shadowCamera.viewProj * world;\n output.worldPosition = world.xyz;\n return output;\n}\n\n@fragment\nfn fsMain(input: PointShadowVertexOutput) -> @location(0) vec4<f32> {\n let distanceToLight = length(input.worldPosition - shadowCamera.lightPositionRange.xyz);\n let normalizedDepth = clamp(distanceToLight / shadowCamera.lightPositionRange.w, 0.0, 1.0);\n return vec4(normalizedDepth, normalizedDepth, normalizedDepth, 1.0);\n}\n",Gi="\nstruct ShadowCameraUniforms {\n viewProj: mat4x4<f32>,\n lightPositionRange: vec4<f32>,\n};\n\nstruct PointShadowVertexOutput {\n @builtin(position) position: vec4<f32>,\n @location(0) worldPosition: vec3<f32>,\n};\n\n@group(0) @binding(0) var<uniform> shadowCamera: ShadowCameraUniforms;\n@group(0) @binding(1) var<storage, read> rendererInstanceMatrices: array<vec4<f32>>;\n\nfn rendererInstanceModelMatrix(instanceIndex: u32) -> mat4x4<f32> {\n let base = instanceIndex * 4u;\n return mat4x4<f32>(\n rendererInstanceMatrices[base + 0u],\n rendererInstanceMatrices[base + 1u],\n rendererInstanceMatrices[base + 2u],\n rendererInstanceMatrices[base + 3u]\n );\n}\n\n@vertex\nfn vsMain(\n @location(0) position: vec3<f32>,\n @builtin(instance_index) instanceIndex: u32\n) -> PointShadowVertexOutput {\n var output: PointShadowVertexOutput;\n let world = rendererInstanceModelMatrix(instanceIndex) * vec4(position, 1.0);\n output.position = shadowCamera.viewProj * world;\n output.worldPosition = world.xyz;\n return output;\n}\n\n@fragment\nfn fsMain(input: PointShadowVertexOutput) -> @location(0) vec4<f32> {\n let distanceToLight = length(input.worldPosition - shadowCamera.lightPositionRange.xyz);\n let normalizedDepth = clamp(distanceToLight / shadowCamera.lightPositionRange.w, 0.0, 1.0);\n return vec4(normalizedDepth, normalizedDepth, normalizedDepth, 1.0);\n}\n",Ri="\nstruct RendererSkinningUniforms {\n bindMatrix: mat4x4<f32>,\n bindMatrixInverse: mat4x4<f32>,\n};\n\n@group(2) @binding(0) var<storage, read> rendererBoneMatrixColumns: array<vec4<f32>>;\n@group(2) @binding(1) var<uniform> rendererSkinning: RendererSkinningUniforms;\n\nfn rendererBoneMatrix(index: u32) -> mat4x4<f32> {\n let base = index * 4u;\n return mat4x4<f32>(\n rendererBoneMatrixColumns[base + 0u],\n rendererBoneMatrixColumns[base + 1u],\n rendererBoneMatrixColumns[base + 2u],\n rendererBoneMatrixColumns[base + 3u],\n );\n}\n\nfn rendererSkinPosition(position: vec3<f32>, skinIndex: vec4<u32>, skinWeight: vec4<f32>) -> vec3<f32> {\n let boundPosition = rendererSkinning.bindMatrix * vec4(position, 1.0);\n let weightSum = skinWeight.x + skinWeight.y + skinWeight.z + skinWeight.w;\n if (weightSum <= 0.0) {\n return position;\n }\n let skinnedPosition =\n (rendererBoneMatrix(skinIndex.x) * boundPosition) * skinWeight.x +\n (rendererBoneMatrix(skinIndex.y) * boundPosition) * skinWeight.y +\n (rendererBoneMatrix(skinIndex.z) * boundPosition) * skinWeight.z +\n (rendererBoneMatrix(skinIndex.w) * boundPosition) * skinWeight.w;\n let fallbackWeight = max(0.0, 1.0 - weightSum);\n return (rendererSkinning.bindMatrixInverse * (skinnedPosition + boundPosition * fallbackWeight)).xyz;\n}\n",Li=`\nstruct RendererCameraUniforms {\n viewProj: mat4x4<f32>,\n cameraPosition: vec4<f32>,\n viewportAndTime: vec4<f32>,\n view: mat4x4<f32>,\n projection: mat4x4<f32>,\n};\n\nstruct RendererInstanceData {\n model0: vec4<f32>,\n model1: vec4<f32>,\n model2: vec4<f32>,\n model3: vec4<f32>,\n color: vec4<f32>,\n batching: vec4<f32>,\n};\n\n@group(0) @binding(0) var<uniform> rendererCamera: RendererCameraUniforms;\n@group(0) @binding(1) var<uniform> rendererLights: array<vec4<f32>, 11>;\n@group(0) @binding(2) var<storage, read> rendererInstances: array<RendererInstanceData>;\n\n${Ri}\n\nfn rendererInstanceModelMatrix(instanceIndex: u32) -> mat4x4<f32> {\n let instance = rendererInstances[instanceIndex];\n return mat4x4<f32>(instance.model0, instance.model1, instance.model2, instance.model3);\n}\n\n@vertex\nfn vsMain(\n @location(0) position: vec3<f32>,\n @location(1) skinIndex: vec4<u32>,\n @location(2) skinWeight: vec4<f32>,\n @builtin(instance_index) instanceIndex: u32,\n) -> @builtin(position) vec4<f32> {\n let world = rendererInstanceModelMatrix(instanceIndex) * vec4(rendererSkinPosition(position, skinIndex, skinWeight), 1.0);\n return rendererCamera.viewProj * world;\n}\n`,zi=`\nstruct ShadowCameraUniforms {\n viewProj: mat4x4<f32>,\n lightPositionRange: vec4<f32>,\n};\n\nstruct RendererInstanceData {\n model0: vec4<f32>,\n model1: vec4<f32>,\n model2: vec4<f32>,\n model3: vec4<f32>,\n color: vec4<f32>,\n batching: vec4<f32>,\n};\n\n@group(0) @binding(0) var<uniform> shadowCamera: ShadowCameraUniforms;\n@group(0) @binding(1) var<storage, read> rendererInstances: array<RendererInstanceData>;\n\n${Ri}\n\nfn rendererInstanceModelMatrix(instanceIndex: u32) -> mat4x4<f32> {\n let instance = rendererInstances[instanceIndex];\n return mat4x4<f32>(instance.model0, instance.model1, instance.model2, instance.model3);\n}\n\n@vertex\nfn vsMain(\n @location(0) position: vec3<f32>,\n @location(1) skinIndex: vec4<u32>,\n @location(2) skinWeight: vec4<f32>,\n @builtin(instance_index) instanceIndex: u32,\n) -> @builtin(position) vec4<f32> {\n let world = rendererInstanceModelMatrix(instanceIndex) * vec4(rendererSkinPosition(position, skinIndex, skinWeight), 1.0);\n return shadowCamera.viewProj * world;\n}\n`,Ui=`\nstruct ShadowCameraUniforms {\n viewProj: mat4x4<f32>,\n lightPositionRange: vec4<f32>,\n};\n\nstruct RendererInstanceData {\n model0: vec4<f32>,\n model1: vec4<f32>,\n model2: vec4<f32>,\n model3: vec4<f32>,\n color: vec4<f32>,\n batching: vec4<f32>,\n};\n\nstruct PointShadowVertexOutput {\n @builtin(position) position: vec4<f32>,\n @location(0) worldPosition: vec3<f32>,\n};\n\n@group(0) @binding(0) var<uniform> shadowCamera: ShadowCameraUniforms;\n@group(0) @binding(1) var<storage, read> rendererInstances: array<RendererInstanceData>;\n\n${Ri}\n\nfn rendererInstanceModelMatrix(instanceIndex: u32) -> mat4x4<f32> {\n let instance = rendererInstances[instanceIndex];\n return mat4x4<f32>(instance.model0, instance.model1, instance.model2, instance.model3);\n}\n\n@vertex\nfn vsMain(\n @location(0) position: vec3<f32>,\n @location(1) skinIndex: vec4<u32>,\n @location(2) skinWeight: vec4<f32>,\n @builtin(instance_index) instanceIndex: u32,\n) -> PointShadowVertexOutput {\n var output: PointShadowVertexOutput;\n let world = rendererInstanceModelMatrix(instanceIndex) * vec4(rendererSkinPosition(position, skinIndex, skinWeight), 1.0);\n output.position = shadowCamera.viewProj * world;\n output.worldPosition = world.xyz;\n return output;\n}\n\n@fragment\nfn fsMain(input: PointShadowVertexOutput) -> @location(0) vec4<f32> {\n let distanceToLight = length(input.worldPosition - shadowCamera.lightPositionRange.xyz);\n let normalizedDepth = clamp(distanceToLight / shadowCamera.lightPositionRange.w, 0.0, 1.0);\n return vec4(normalizedDepth, normalizedDepth, normalizedDepth, 1.0);\n}\n`,Vi="\nstruct FullscreenVertexOutput {\n @builtin(position) position: vec4<f32>,\n @location(0) uv: vec2<f32>,\n};\n\n@group(0) @binding(0) var sourceSampler: sampler;\n@group(0) @binding(1) var sourceTexture: texture_2d<f32>;\n\n@vertex\nfn vsMain(@builtin(vertex_index) vertexIndex: u32) -> FullscreenVertexOutput {\n var output: FullscreenVertexOutput;\n let position = array<vec2<f32>, 3>(\n vec2(-1.0, -3.0),\n vec2(-1.0, 1.0),\n vec2(3.0, 1.0),\n );\n let clip = position[vertexIndex];\n output.position = vec4(clip, 0.0, 1.0);\n output.uv = clip * vec2(0.5, -0.5) + vec2(0.5, 0.5);\n return output;\n}\n\n@fragment\nfn fsMain(input: FullscreenVertexOutput) -> @location(0) vec4<f32> {\n let linearColor = textureSample(sourceTexture, sourceSampler, input.uv);\n let low = linearColor.rgb * 12.92;\n let high = 1.055 * pow(max(linearColor.rgb, vec3<f32>(0.0)), vec3<f32>(1.0 / 2.4)) - 0.055;\n let srgb = select(high, low, linearColor.rgb <= vec3<f32>(0.0031308));\n return vec4<f32>(srgb, linearColor.a);\n}\n";function Ai(e){if(e.transparent)switch(e.blending){case Qe:return{color:{srcFactor:"src-alpha",dstFactor:"one",operation:"add"},alpha:{srcFactor:"one",dstFactor:"one",operation:"add"}};case pt:return{color:{srcFactor:"zero",dstFactor:"one-minus-src",operation:"subtract"},alpha:{srcFactor:"one",dstFactor:"one",operation:"subtract"}};case ot:return{color:{srcFactor:"zero",dstFactor:"src",operation:"add"},alpha:{srcFactor:"zero",dstFactor:"src-alpha",operation:"add"}};default:return{color:{srcFactor:"src-alpha",dstFactor:"one-minus-src-alpha",operation:"add"},alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"}}}}function Fi(e,t,r,n){if(t<0||e[t]!==r)return-1;let i=0;for(let a=t;a<e.length;a+=1)if(e[a]===r&&(i+=1),e[a]===n&&(i-=1,0===i))return a;return-1}function Ei(e,t,r){const n=function(e,t="fsMain"){const r=e.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/.*$/gm,""),n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),i=new RegExp(`@fragment\\s+fn\\s+${n}\\s*\\(`).exec(r);if(!i)return null;const a=r.indexOf("(",i.index),s=Fi(r,a,"(",")");if(s<0)return null;const o=r.indexOf("{",s+1);if(o<0)return null;const l=r.slice(s+1,o),c=/->\s*@location\s*\(\s*(\d+)\s*\)/.exec(l);if(c)return new Set([Number(c[1])]);const u=/->\s*((?:@\w+(?:\s*\([^)]*\))?\s*)*)([A-Za-z_]\w*)/.exec(l);if(!u)return new Set;const d=u[2].replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),h=new RegExp(`\\bstruct\\s+${d}\\s*\\{`).exec(r);if(!h)return null;const p=r.indexOf("{",h.index),f=Fi(r,p,"{","}");if(f<0)return null;const m=new Set,g=/@location\s*\(\s*(\d+)\s*\)/g,x=r.slice(p+1,f);for(const e of x.matchAll(g))m.add(Number(e[1]));return m}(e);return t.map((e,t)=>null===n||n.has(t)?{format:e,blend:r}:{format:e,writeMask:0})}var ki="chromium-experimental-multi-draw-indirect",Oi=[{name:"position",shaderLocation:0,format:"float32x3"},{name:"normal",shaderLocation:1,format:"float32x3",defaultValue:[0,0,1]},{name:"uv",shaderLocation:2,format:"float32x2",defaultValue:[0,0]},{name:"color",shaderLocation:3,format:"float32x4",defaultValue:[1,1,1,1]},{name:"skinIndex",shaderLocation:4,format:"uint32x4"},{name:"skinWeight",shaderLocation:5,format:"float32x4"}];function $i(e){return e.wireframe&&"triangle-list"===e.primitiveTopology?"line-list":e.primitiveTopology}function ji(e,t,r){if(!$i(e).startsWith("triangle"))return"none";if("directionalShadow"===t){if(r&&null===e.shadowSide)return"none";const t=e.shadowSide??(e.side===et?at:e.side===it?it:et);return t===it?"none":t===et?"front":"back"}return e.side===it?"none":e.side===et?"front":"back"}function Ni(e){if(void 0===e)return 1;if(!Number.isFinite(e)||e<=0||e>1)throw new RangeError("renderScale must be a finite number greater than 0 and at most 1.");return e}var Wi=class{canvas;clearColor;powerPreference;shadowMapSize;pointShadowMapSize;fallbackMaterial;materialResolver;toonOutlineMaterialCache=new WeakMap;fallbackSkinnedMaterial;invokeObjectRenderCallbacks;sampleCount;renderScale;hiZOcclusionCullingEnabled;multiDrawIndirectEnabled;dynamicBatchingEnabled;multiDrawIndirectSupported=!1;renderGraphProfilingEnabled;indirectFirstInstanceSupported=!1;timestampQuerySupported=!1;geometryCache=new WeakMap;skinnedGeometryCache=new Map;skinPaletteCache=new WeakMap;skinPaletteResources=new Set;meshExtractionCache=new WeakMap;resolvedMaterialFrameCache=new WeakMap;instancedMeshExtractionCache=new WeakMap;batchedMeshExtractionCache=new WeakMap;materialCache=new WeakMap;skinnedMaterialCache=new WeakMap;materialCacheVisible=new WeakMap;materialCacheDirect=new WeakMap;materialNoReceiveShadowCache=new WeakMap;skinnedMaterialNoReceiveShadowCache=new WeakMap;materialNoReceiveShadowCacheVisible=new WeakMap;materialNoReceiveShadowCacheDirect=new WeakMap;depthPrepassMaterialCache=new WeakMap;directionalShadowMaterialCache=new WeakMap;skinnedDirectionalShadowMaterialCache=new WeakMap;directionalShadowMaterialCacheDirect=new WeakMap;lineMaterialCache=new WeakMap;lineBasicMaterialCache=new WeakMap;lineProxyCache=new WeakMap;spriteProxyCache=new WeakMap;depthMaterialFrameCache=new WeakMap;forwardMaterialFastCache=new WeakMap;forwardMaterialTargetFastCache=new WeakMap;forwardMaterialFrameCache=new WeakMap;depthMaterialFastCache=new WeakMap;sharedForwardPipelineCache=new Map;sharedForwardPipelinePromiseCache=new Map;sharedDepthPipelineCache=new Map;sharedDepthPipelinePromiseCache=new Map;state=function(){return{device:null,context:null,format:null,mainDepthTexture:null,mainDepthView:null,sceneColorTexture:null,sceneColorView:null,sceneColorSnapshotTexture:null,sceneColorSnapshotView:null,sceneDepthSnapshotTexture:null,sceneDepthSnapshotView:null,postProcessColorTexture:null,postProcessColorView:null,cameraBuffer:null,lightBuffer:null,shadowCameraBuffer:null,shadowCameraBufferPool:[],sharedShadowBindGroupByCameraBuffer:new Map,instanceBuffer:null,instanceBufferSize:0,drawMetadataResource:null,sharedSceneBindGroup:null,sharedShadowBindGroup:null,indirectForwardBundleCache:new Map,directForwardBundleCache:new Map,sceneBindGroupLayout:null,directSceneBindGroupLayout:null,visibleSceneBindGroupLayout:null,visibleDepthSceneBindGroupLayout:null,shadowBindGroupLayout:null,directShadowBindGroupLayout:null,emptyBindGroupLayout:null,skinningBindGroupLayout:null,sceneTextureBindGroupLayout:null,sceneTextureBindGroup:null,shadowComparisonSampler:null,linearClampSampler:null,nearestClampSampler:null,fullscreenTextureBindGroupLayout:null,directionalShadowTexture:null,directionalShadowView:null,directionalShadowLayerViews:[],pointShadowTexture:null,pointShadowArrayView:null,pointShadowFaceViews:[],pointShadowDepthTexture:null,pointShadowDepthFaceViews:[],spotShadowTexture:null,spotShadowView:null,spotShadowLayerViews:[],hizTexture:null,hizView:null,hizMipViews:[],hizCopyBindGroup:null,hizReduceBindGroups:[],visibilityBindGroup:null,visibilityBindGroupMetadataResource:null,presentBindGroups:new WeakMap,hizMipCount:1,temporalHiZHistoryValid:!1,temporalVisibilityBuffer:null,visibilityParamsBuffer:null,hizCopyKernel:null,hizReduceKernel:null,visibilityKernel:null,staticVisibilityClearKernel:null,staticVisibilityCullKernel:null,staticVisibilityIndirectBuildKernel:null,depthPrepassPipeline:null,depthPrepassPipelineVisible:null,depthPrepassPipelineDirect:null,skinnedDepthPrepassPipeline:null,shadowDepthPipeline:null,shadowDepthPipelineDirect:null,skinnedShadowDepthPipeline:null,pointShadowPipeline:null,pointShadowPipelineDirect:null,skinnedPointShadowPipeline:null,presentPipeline:null,pixelRatio:1,width:1,height:1,presentationWidth:1,presentationHeight:1,frameTimeSeconds:0,frameIndex:0,directionalShadowTextureSize:1,pointShadowTextureSize:1,spotShadowTextureSize:1,latestFrameProfile:null,latestCompletedFrameProfile:null,residentSceneBindGroupVersion:0,residentShadowBindGroupVersion:0,initialized:!1}}();textureCache=new WeakMap;graphTextureBindGroupCache=new WeakMap;materialGraphTextureReadCache=new WeakMap;defaultInstanceAttributeBuffers=new Map;textureManager=new Di(this.state,this.textureCache);renderGraph=new qt;directionalShadowCameras=Array.from({length:4},()=>new ut(-10,10,10,-10,.1,80));pointShadowCameras=Array.from({length:4},()=>$r.map(()=>new dt(90,1,.1,25)));spotShadowCameras=Array.from({length:4},()=>new dt(60,1,.5,500));colorTargetCache=new Map;msaaColorTargetCache=new Map;msaaDepthTargetCache=new Map;sourceInstanceDataScratch=new Mi(4096);opaqueInstanceDataScratch=new Mi(4096);finalInstanceDataScratch=new Mi(4096);residentInstanceUploadsScratch=[];gpuOpaqueDrawsScratch=[];directOpaqueDrawsScratch=[];stagedOpaqueDrawsScratch=[];residentOpaqueDrawsScratch=[];retiredGeometryResources=[];retiredGeometryBuffers=[];vertexAttributeBufferKeyCache=new WeakMap;standardVertexAttributeCache=new WeakMap;geometryVertexBufferFastCache=new WeakMap;vertexAttributeGroupCache=new WeakMap;vertexAttributeGroupBufferKeyCache=new WeakMap;compileDrawScratch=[];indirectSubmissionStreamsScratch=[];renderBundleScratch=[];directBundleDrawStatsScratch={drawCallCount:0,triangleCount:0};sortedOpaqueBatchesScratch=[];opaqueBatchPool=[];opaqueBatchPoolCount=0;drawCallPool=[];drawCallPoolCount=0;staticDrawSets=[];materialPassStaticBundleCache=new WeakMap;staticDrawSetManager=new Bi(this.state,this.staticDrawSets,e=>this.getGeometryResource(e),e=>this.resolveMaterial(e),(e,t)=>this.ensureWireframeIndex(e,t));staticFrameToken=0;hizResourceVersion=0;graphTextureResourceVersion=0;visibilityParamsUpload=new Uint32Array(4);drawMetadataUpload=new Float32Array(0);indirectDrawUpload=new Uint32Array(0);extractedAmbientScratch=new gt;extractedHemisphereScratch=this.createExtractedHemisphereLightScratch();extractedBoundsMinScratch=new mt;extractedBoundsMaxScratch=new mt;extractedDirectionalLightsScratch=Array.from({length:4},()=>this.createExtractedDirectionalLightScratch());extractedPointLightsScratch=Array.from({length:4},()=>this.createExtractedPointLightScratch());extractedSpotLightsScratch=Array.from({length:4},()=>this.createExtractedSpotLightScratch());activeDirectionalLightsScratch=[];activePointLightsScratch=[];activeSpotLightsScratch=[];resolvedMeshMaterialsScratch=[];extractedLightsScratch={ambient:this.extractedAmbientScratch,hemisphere:null,directionals:this.activeDirectionalLightsScratch,points:this.activePointLightsScratch,spots:this.activeSpotLightsScratch,directional:null,point:null,spot:null};extractedFrameScratch={scene:null,camera:null,gpuOpaqueDraws:this.gpuOpaqueDrawsScratch,directOpaqueDraws:this.directOpaqueDrawsScratch,transparentDraws:[],instanceData:this.finalInstanceDataScratch,residentInstanceUploads:this.residentInstanceUploadsScratch,lights:this.extractedLightsScratch,boundsMin:this.extractedBoundsMinScratch,boundsMax:this.extractedBoundsMaxScratch};cameraUniformScratch=new Float32Array(68);temporalVisibilityUniformScratch=new Float32Array(44);lightUniformScratch=new Float32Array(396);csmCascadeRanges=Array.from({length:4},()=>new ft);csmCascadeCount=0;csmCascadeLights=[];shadowCameraUniformScratch=new Float32Array(64);cameraViewProjScratch=new lt;cameraProjectionScratch=new lt;projectionJitterPixels=new ft;temporalVisibilityCurrentViewProj=new lt;temporalVisibilityPreviousViewProj=new lt;cameraFrustumPlanesScratch=new Float32Array(24);objectTraversalStackScratch=[];isSphereVisibleScratch=(e,t,r,n,i)=>!i||function(e,t,r,n,i){const a=-i;for(let i=0;i<24;i+=4)if(e[i+0]*t+e[i+1]*r+e[i+2]*n+e[i+3]<a)return!1;return!0}(this.cameraFrustumPlanesScratch,e,t,r,n);updateExtractedBoundsFromMatrixScratch=e=>{const t=this.extractedBoundsMinScratch,r=this.extractedBoundsMaxScratch,n=e[12],i=e[13],a=e[14];n<t.x&&(t.x=n),i<t.y&&(t.y=i),a<t.z&&(t.z=a),n>r.x&&(r.x=n),i>r.y&&(r.y=i),a>r.z&&(r.z=a)};transparentSortCameraPositionScratch=new mt;transparentSortCameraForwardScratch=new mt;temporalVisibilityCurrentCameraPosition=new mt;temporalVisibilityPreviousCameraPosition=new mt;shadowViewProjScratch=new lt;extractionVersion=0;graphBuilder=(e,t)=>{t.addDirectionalShadowPass(),t.addPointShadowPass(),t.addSpotShadowPass(),t.addDepthPrepass(),t.addHiZPasses(),t.addVisibilityPass(),t.addForwardPass(),t.addPresentPass()};createExtractedDirectionalLightScratch(){return{sourceLight:null,position:new mt,target:new mt,direction:new mt,color:new mt,intensity:0,castShadow:!1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowIntensity:1,shadowMapSize:this.shadowMapSize,shadowCameraLeft:-5,shadowCameraRight:5,shadowCameraTop:5,shadowCameraBottom:-5,shadowCameraNear:.5,shadowCameraFar:500}}createExtractedHemisphereLightScratch(){return{direction:new mt(0,1,0),skyColor:new mt,groundColor:new mt,intensity:0}}createExtractedPointLightScratch(){return{position:new mt,color:new mt,intensity:0,range:25,castShadow:!1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowIntensity:1,shadowMapSize:this.pointShadowMapSize,shadowCameraNear:.5,shadowCameraFar:500}}createExtractedSpotLightScratch(){return{position:new mt,direction:new mt(0,-1,0),color:new mt,intensity:0,range:500,angle:Math.PI/3,penumbra:0,decay:2,castShadow:!1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowIntensity:1,shadowMapSize:this.shadowMapSize,shadowCameraNear:.5,shadowCameraFar:500,shadowCameraFov:60}}constructor(e){this.canvas=e.canvas,this.clearColor=[...e.clearColor??[0,0,0,1]],this.powerPreference=e.powerPreference,this.shadowMapSize=e.shadowMapSize??2048,this.pointShadowMapSize=e.pointShadowMapSize??1024,this.fallbackMaterial=e.fallbackMaterial??null,this.materialResolver=e.materialResolver,this.fallbackSkinnedMaterial=e.fallbackSkinnedMaterial??new kt({vertexShader:"\nstruct VertexInput {\n @location(0) position: vec3<f32>,\n @location(1) normal: vec3<f32>,\n @location(2) uv: vec2<f32>,\n @location(3) color: vec4<f32>,\n @location(4) skinIndex: vec4<u32>,\n @location(5) skinWeight: vec4<f32>,\n @builtin(instance_index) instanceIndex: u32,\n};\n\nstruct VertexOutput {\n @builtin(position) position: vec4<f32>,\n @location(0) worldNormal: vec3<f32>,\n};\n\n@vertex\nfn vsMain(input: VertexInput) -> VertexOutput {\n var output: VertexOutput;\n let skinnedPosition = rendererSkinPosition(input.position, input.skinIndex, input.skinWeight);\n let skinnedNormal = rendererSkinNormal(input.normal, input.skinIndex, input.skinWeight);\n output.position = rendererClipPosition(skinnedPosition, input.instanceIndex);\n output.worldNormal = rendererWorldNormal(skinnedNormal, input.instanceIndex);\n return output;\n}\n",fragmentShader:"\nstruct VertexOutput {\n @builtin(position) position: vec4<f32>,\n @location(0) worldNormal: vec3<f32>,\n};\n\n@fragment\nfn fsMain(input: VertexOutput) -> @location(0) vec4<f32> {\n let normal = normalize(input.worldNormal);\n let diffuse = max(dot(normal, normalize(rendererDirectionalLightDirection())), 0.0);\n let lighting = rendererIndirectDiffuse(normal) + rendererDirectionalLightColor() * diffuse;\n return vec4<f32>(vec3<f32>(0.72, 0.76, 0.82) * lighting, 1.0);\n}\n",vertexAttributes:Oi}),this.invokeObjectRenderCallbacks=e.invokeObjectRenderCallbacks??!0,this.state.directionalShadowTextureSize=this.shadowMapSize,this.state.pointShadowTextureSize=this.pointShadowMapSize,this.state.spotShadowTextureSize=this.shadowMapSize,this.sampleCount=$n(e.sampleCount),this.renderScale=Ni(e.renderScale),this.hiZOcclusionCullingEnabled=e.hiZOcclusionCulling??!1,this.multiDrawIndirectEnabled=e.multiDrawIndirect??!0,this.dynamicBatchingEnabled=e.dynamicBatching??!0,this.renderGraphProfilingEnabled=e.renderGraphProfiling??!1}resolveMaterial(e){if(!1===e?.visible)return null;if(e&&Ot(e))return e;if(!e)return this.fallbackMaterial;if(!0===e.isLineMaterial)return this.resolveLineMaterial(e);const t=this.resolvedMaterialFrameCache.get(e);if(t?.extractionVersion===this.extractionVersion)return t.material;let r=e.transparent||function(e){if(e.transparent)return!0;if(e instanceof xt)return null!=e.uniforms.hology_depth_map||null!=e.uniforms.hology_scene_map;if(e instanceof kt)return e.requiresLatePass();return!1}(e)?"late":"opaque",n=this.materialResolver?.(e,r);"opaque"===r&&n?.requiresLatePass()&&(r="late",n=this.materialResolver?.(e,r));const i=void 0===n?this.fallbackMaterial:n;return this.resolvedMaterialFrameCache.set(e,{extractionVersion:this.extractionVersion,material:i}),void 0!==n?n:i}resolveLineMaterial(e){let t=this.lineMaterialCache.get(e);t||(t=new kt({vertexShader:"\nstruct VertexInput {\n @location(0) position: vec3<f32>,\n @location(4) instanceStart: vec3<f32>,\n @location(5) instanceEnd: vec3<f32>,\n @builtin(instance_index) instanceIndex: u32,\n};\n\nstruct VertexOutput {\n @builtin(position) position: vec4<f32>,\n @location(0) color: vec4<f32>,\n};\n\n@vertex\nfn vsMain(input: VertexInput) -> VertexOutput {\n var output: VertexOutput;\n let start = rendererCamera.view * rendererWorldPosition(input.instanceStart, input.instanceIndex);\n let end = rendererCamera.view * rendererWorldPosition(input.instanceEnd, input.instanceIndex);\n let clipStart = rendererCamera.projection * start;\n let clipEnd = rendererCamera.projection * end;\n let ndcStart = clipStart.xy / clipStart.w;\n let ndcEnd = clipEnd.xy / clipEnd.w;\n let aspect = rendererCamera.viewportAndTime.x / max(rendererCamera.viewportAndTime.y, 1.0);\n var direction = ndcEnd - ndcStart;\n direction.x *= aspect;\n direction = normalize(select(vec2<f32>(1.0, 0.0), direction, length(direction) > 0.00001));\n var offset = vec2<f32>(direction.y, -direction.x);\n direction.x /= aspect;\n offset.x /= aspect;\n if (input.position.x < 0.0) { offset = -offset; }\n if (input.position.y < 0.0) {\n offset -= direction;\n } else if (input.position.y > 1.0) {\n offset += direction;\n }\n offset *= materialUniforms.linewidth / max(rendererCamera.viewportAndTime.y, 1.0);\n var clip = select(clipEnd, clipStart, input.position.y < 0.5);\n clip.xy += offset * clip.w;\n output.position = clip;\n output.color = vec4<f32>(materialUniforms.color, materialUniforms.opacity);\n return output;\n}\n",fragmentShader:"\nstruct FragmentInput {\n @builtin(position) position: vec4<f32>,\n @location(0) color: vec4<f32>,\n};\n\n@fragment\nfn fsMain(input: FragmentInput) -> @location(0) vec4<f32> {\n return input.color;\n}\n",uniforms:{color:new nt(1,1,1),opacity:1,linewidth:1},vertexAttributes:[{name:"position",shaderLocation:0,format:"float32x3"},{name:"instanceStart",shaderLocation:4,format:"float32x3",stepMode:"instance"},{name:"instanceEnd",shaderLocation:5,format:"float32x3",stepMode:"instance"}],transparent:!0,side:it,depthTest:e.depthTest,depthWrite:e.depthWrite}),this.lineMaterialCache.set(e,t));const r=e,n=r.color;return n&&t.uniforms.color.value.copy(n),t.uniforms.opacity.value=r.opacity??1,t.uniforms.linewidth.value=r.linewidth??1,t.transparent=e.transparent||(r.opacity??1)<1,t.depthTest=e.depthTest,t.depthWrite=e.depthWrite,t}resolveLineBasicMaterial(e,t){let r=this.lineBasicMaterialCache.get(e);r||(r=new Map,this.lineBasicMaterialCache.set(e,r));let n=r.get(t);n||(n=new kt({vertexShader:"\nstruct VertexInput {\n @location(0) position: vec3<f32>,\n @builtin(instance_index) instanceIndex: u32,\n};\nstruct VertexOutput {\n @builtin(position) position: vec4<f32>,\n};\n@vertex\nfn vsMain(input: VertexInput) -> VertexOutput {\n return VertexOutput(rendererClipPosition(input.position, input.instanceIndex));\n}\n",fragmentShader:"\n@fragment\nfn fsMain() -> @location(0) vec4<f32> {\n return vec4<f32>(materialUniforms.color, materialUniforms.opacity);\n}\n",uniforms:{color:new nt(1,1,1),opacity:1},primitiveTopology:t,depthTest:e.depthTest,depthWrite:e.depthWrite}),r.set(t,n));const i=e;return i.color&&n.uniforms.color.value.copy(i.color),n.uniforms.opacity.value=i.opacity??1,n.transparent=e.transparent||(i.opacity??1)<1,n.depthTest=e.depthTest,n.depthWrite=e.depthWrite,n}resolveSkinnedMaterial(e){const t=this.resolveMaterial(e);return null===t?null:function(e){const t=e.vertexAttributes.find(e=>"skinIndex"===e.name),r=e.vertexAttributes.find(e=>"skinWeight"===e.name);return e.vertexShader.includes("USE_SKINNING")||"uint32x4"===t?.format&&"float32x4"===r?.format&&e.vertexShader.includes("rendererSkinPosition(")}(t)?t:this.fallbackSkinnedMaterial}hasRenderCallbacks(e){return null!==e&&this.invokeObjectRenderCallbacks&&function(e){return null!==e&&(e.onBeforeRender!==Tr.prototype.onBeforeRender||e.onAfterRender!==Tr.prototype.onAfterRender)}(e)}async initialize(){if(!("gpu"in navigator))throw new Error("WebGPU is not available in this browser.");const e=await navigator.gpu.requestAdapter({powerPreference:this.powerPreference});if(!e)throw new Error("A WebGPU adapter could not be created.");const t=[];e.features.has("indirect-first-instance")&&t.push("indirect-first-instance"),e.features.has("timestamp-query")&&t.push("timestamp-query"),e.features.has("texture-compression-bc")&&t.push("texture-compression-bc"),e.features.has("texture-compression-etc2")&&t.push("texture-compression-etc2"),e.features.has("texture-compression-astc")&&t.push("texture-compression-astc"),e.features.has("float32-filterable")&&t.push("float32-filterable"),e.features.has(ki)&&t.push(ki);const r=e.limits;if(this.state.device=await e.requestDevice({requiredFeatures:t,requiredLimits:{maxTextureArrayLayers:r.maxTextureArrayLayers,maxBufferSize:r.maxBufferSize,maxStorageBufferBindingSize:r.maxStorageBufferBindingSize}}),this.state.device.addEventListener("uncapturederror",e=>{console.error("Uncaptured WebGPU device error",e)}),this.indirectFirstInstanceSupported=t.includes("indirect-first-instance"),this.timestampQuerySupported=t.includes("timestamp-query"),this.multiDrawIndirectSupported=t.includes(ki),this.state.context=this.canvas.getContext("webgpu"),!this.state.context)throw new Error("The canvas does not provide a WebGPU context.");this.state.format=navigator.gpu.getPreferredCanvasFormat(),this.state.context.configure({device:this.state.device,format:this.state.format,alphaMode:"premultiplied"}),this.state.cameraBuffer=this.state.device.createBuffer({label:"renderer-camera-buffer",size:272,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this.state.temporalVisibilityBuffer=this.state.device.createBuffer({label:"renderer-temporal-visibility-buffer",size:176,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this.state.lightBuffer=this.state.device.createBuffer({label:"renderer-light-buffer",size:1584,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this.state.shadowCameraBuffer=this.state.device.createBuffer({label:"renderer-shadow-camera-buffer",size:256,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this.state.sceneBindGroupLayout=this.state.device.createBindGroupLayout({label:"renderer-scene-layout",entries:[{binding:0,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}},{binding:1,visibility:GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}},{binding:2,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"read-only-storage"}},{binding:3,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"comparison"}},{binding:4,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"depth",viewDimension:"2d-array"}},{binding:5,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}},{binding:6,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float",viewDimension:"2d-array"}},{binding:7,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"depth",viewDimension:"2d-array"}}]}),this.state.directSceneBindGroupLayout=this.state.device.createBindGroupLayout({label:"renderer-direct-scene-layout",entries:[{binding:0,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}},{binding:1,visibility:GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}},{binding:2,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"read-only-storage"}},{binding:3,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"read-only-storage"}},{binding:4,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"comparison"}},{binding:5,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"depth",viewDimension:"2d-array"}},{binding:6,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}},{binding:7,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float",viewDimension:"2d-array"}},{binding:8,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"depth",viewDimension:"2d-array"}}]}),this.state.visibleSceneBindGroupLayout=this.state.device.createBindGroupLayout({label:"renderer-visible-scene-layout",entries:[{binding:0,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}},{binding:1,visibility:GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}},{binding:2,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"read-only-storage"}},{binding:3,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"comparison"}},{binding:4,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"depth",viewDimension:"2d-array"}},{binding:5,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}},{binding:6,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float",viewDimension:"2d-array"}},{binding:7,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"depth",viewDimension:"2d-array"}},{binding:8,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"read-only-storage"}}]}),this.state.visibleDepthSceneBindGroupLayout=this.state.device.createBindGroupLayout({label:"renderer-visible-depth-scene-layout",entries:[{binding:0,visibility:GPUShaderStage.VERTEX,buffer:{type:"uniform"}},{binding:2,visibility:GPUShaderStage.VERTEX,buffer:{type:"read-only-storage"}},{binding:3,visibility:GPUShaderStage.VERTEX,buffer:{type:"read-only-storage"}}]}),this.state.shadowBindGroupLayout=this.state.device.createBindGroupLayout({label:"renderer-shadow-layout",entries:[{binding:0,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}},{binding:1,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"read-only-storage"}}]}),this.state.directShadowBindGroupLayout=this.state.device.createBindGroupLayout({label:"renderer-direct-shadow-layout",entries:[{binding:0,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}},{binding:1,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"read-only-storage"}},{binding:2,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"read-only-storage"}}]}),this.state.emptyBindGroupLayout=this.state.device.createBindGroupLayout({label:"renderer-empty-layout",entries:[]}),this.state.skinningBindGroupLayout=this.state.device.createBindGroupLayout({label:"renderer-skinning-layout",entries:[{binding:0,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"read-only-storage"}},{binding:1,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}}]}),this.state.sceneTextureBindGroupLayout=this.state.device.createBindGroupLayout({label:"renderer-scene-texture-layout",entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}},{binding:1,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float"}},{binding:2,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"non-filtering"}},{binding:3,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"depth"}}]}),this.state.residentSceneBindGroupVersion+=1,this.state.residentShadowBindGroupVersion+=1,this.state.fullscreenTextureBindGroupLayout=this.state.device.createBindGroupLayout({label:"renderer-fullscreen-texture-layout",entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}},{binding:1,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float"}}]}),this.state.shadowComparisonSampler=this.state.device.createSampler({label:"renderer-shadow-comparison-sampler",compare:"less-equal",magFilter:"linear",minFilter:"linear",addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge"}),this.state.linearClampSampler=this.state.device.createSampler({label:"renderer-linear-clamp-sampler",magFilter:"linear",minFilter:"linear",addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge",addressModeW:"clamp-to-edge"}),this.state.nearestClampSampler=this.state.device.createSampler({label:"renderer-nearest-clamp-sampler",magFilter:"nearest",minFilter:"nearest",mipmapFilter:"nearest",addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge",addressModeW:"clamp-to-edge"}),this.state.hizCopyKernel=this.createComputeKernel({label:"renderer-hiz-copy",code:"\n@group(0) @binding(0) var sourceDepth: texture_depth_2d;\n@group(0) @binding(1) var targetMip: texture_storage_2d<r32float, write>;\n\n@compute @workgroup_size(8, 8, 1)\nfn main(@builtin(global_invocation_id) globalId: vec3<u32>) {\n let dims = textureDimensions(targetMip);\n if (globalId.x >= dims.x || globalId.y >= dims.y) {\n return;\n }\n\n let depthValue = textureLoad(sourceDepth, vec2<i32>(globalId.xy), 0);\n textureStore(targetMip, vec2<i32>(globalId.xy), vec4(depthValue, 0.0, 0.0, 1.0));\n}\n",bindGroupLayoutEntries:[{binding:0,visibility:GPUShaderStage.COMPUTE,texture:{sampleType:"depth"}},{binding:1,visibility:GPUShaderStage.COMPUTE,storageTexture:{access:"write-only",format:"r32float"}}]}),this.state.hizReduceKernel=this.createComputeKernel({label:"renderer-hiz-reduce",code:"\n@group(0) @binding(0) var sourceMip: texture_2d<f32>;\n@group(0) @binding(1) var targetMip: texture_storage_2d<r32float, write>;\n\nfn readSource(coord: vec2<i32>, dims: vec2<i32>) -> f32 {\n let clamped = clamp(coord, vec2(0, 0), dims - vec2(1, 1));\n return textureLoad(sourceMip, clamped, 0).r;\n}\n\n@compute @workgroup_size(8, 8, 1)\nfn main(@builtin(global_invocation_id) globalId: vec3<u32>) {\n let outDims = textureDimensions(targetMip);\n if (globalId.x >= outDims.x || globalId.y >= outDims.y) {\n return;\n }\n\n let srcOrigin = vec2<i32>(globalId.xy * 2u);\n let srcDims = vec2<i32>(textureDimensions(sourceMip));\n // This renderer uses conventional depth (near = 0, far = 1). Keep the\n // farthest depth in each footprint so an object is rejected only when the\n // whole footprint is covered by closer geometry. A min reduction would let\n // a single nearby texel occlude an otherwise visible object.\n var reduced = max(\n max(readSource(srcOrigin, srcDims), readSource(srcOrigin + vec2(1, 0), srcDims)),\n max(readSource(srcOrigin + vec2(0, 1), srcDims), readSource(srcOrigin + vec2(1, 1), srcDims))\n );\n\n // WebGPU mip dimensions round down. When a source dimension is odd, fold\n // its otherwise-unrepresented final row/column into the last destination\n // texel so no depth coverage disappears from the hierarchy.\n let hasExtraColumn = (srcDims.x & 1) != 0 && globalId.x + 1u == outDims.x;\n let hasExtraRow = (srcDims.y & 1) != 0 && globalId.y + 1u == outDims.y;\n if (hasExtraColumn) {\n reduced = max(reduced, readSource(srcOrigin + vec2(2, 0), srcDims));\n reduced = max(reduced, readSource(srcOrigin + vec2(2, 1), srcDims));\n }\n if (hasExtraRow) {\n reduced = max(reduced, readSource(srcOrigin + vec2(0, 2), srcDims));\n reduced = max(reduced, readSource(srcOrigin + vec2(1, 2), srcDims));\n }\n if (hasExtraColumn && hasExtraRow) {\n reduced = max(reduced, readSource(srcOrigin + vec2(2, 2), srcDims));\n }\n\n textureStore(targetMip, vec2<i32>(globalId.xy), vec4(reduced, 0.0, 0.0, 1.0));\n}\n",bindGroupLayoutEntries:[{binding:0,visibility:GPUShaderStage.COMPUTE,texture:{sampleType:"unfilterable-float"}},{binding:1,visibility:GPUShaderStage.COMPUTE,storageTexture:{access:"write-only",format:"r32float"}}]}),this.state.visibilityKernel=this.createComputeKernel({label:"renderer-visibility-cull",code:"\nstruct RendererCameraUniforms {\n viewProj: mat4x4<f32>,\n cameraPosition: vec4<f32>,\n viewportAndTime: vec4<f32>,\n};\n\nstruct RendererVisibilityParams {\n drawCount: u32,\n hizMipCount: u32,\n reserved0: u32,\n reserved1: u32,\n};\n\nstruct DrawMetadata {\n centerRadius: vec4<f32>,\n args0: vec4<f32>,\n extra: vec4<f32>,\n};\n\nstruct IndirectIndexedArgs {\n indexCount: u32,\n instanceCount: u32,\n firstIndex: u32,\n baseVertex: i32,\n firstInstance: u32,\n};\n\n@group(0) @binding(0) var<uniform> rendererCamera: RendererCameraUniforms;\n@group(0) @binding(1) var<uniform> visibilityParams: RendererVisibilityParams;\n@group(0) @binding(2) var drawMetaTextureSampler: sampler;\n@group(0) @binding(3) var hizTexture: texture_2d<f32>;\n@group(0) @binding(4) var<storage, read> drawMetadata: array<DrawMetadata>;\n@group(0) @binding(5) var<storage, read_write> indirectArgs: array<IndirectIndexedArgs>;\n\nfn saturate(value: f32) -> f32 {\n return clamp(value, 0.0, 1.0);\n}\n\nfn projectedSphereRadius(\n viewProj: mat4x4<f32>,\n ndc: vec3<f32>,\n clipW: f32,\n radius: f32,\n) -> vec2<f32> {\n // Account for both numerator and perspective-denominator variation over the\n // sphere. Offsetting along world X/Y is not conservative once the camera is\n // rotated because those axes can also change clip W.\n let rowX = vec3(viewProj[0].x, viewProj[1].x, viewProj[2].x);\n let rowY = vec3(viewProj[0].y, viewProj[1].y, viewProj[2].y);\n let rowW = vec3(viewProj[0].w, viewProj[1].w, viewProj[2].w);\n let denominator = max(clipW - radius * length(rowW), 0.0001);\n return radius * vec2(\n length(rowX) + abs(ndc.x) * length(rowW),\n length(rowY) + abs(ndc.y) * length(rowW),\n ) / denominator;\n}\n\nfn spherePlaneRadius(viewProj: mat4x4<f32>, plane: vec4<f32>, radius: f32) -> f32 {\n let worldNormal = vec3(\n dot(viewProj[0], plane),\n dot(viewProj[1], plane),\n dot(viewProj[2], plane),\n );\n return radius * length(worldNormal);\n}\n\nfn isSphereInFrustum(viewProj: mat4x4<f32>, center: vec3<f32>, radius: f32) -> bool {\n let clip = viewProj * vec4(center, 1.0);\n return\n clip.w + clip.x >= -spherePlaneRadius(viewProj, vec4( 1.0, 0.0, 0.0, 1.0), radius) &&\n clip.w - clip.x >= -spherePlaneRadius(viewProj, vec4(-1.0, 0.0, 0.0, 1.0), radius) &&\n clip.w + clip.y >= -spherePlaneRadius(viewProj, vec4( 0.0, 1.0, 0.0, 1.0), radius) &&\n clip.w - clip.y >= -spherePlaneRadius(viewProj, vec4( 0.0, -1.0, 0.0, 1.0), radius) &&\n clip.z >= -spherePlaneRadius(viewProj, vec4(0.0, 0.0, 1.0, 0.0), radius) &&\n clip.w - clip.z >= -spherePlaneRadius(viewProj, vec4(0.0, 0.0, -1.0, 1.0), radius);\n}\n\nfn nearestSphereDepth(viewProj: mat4x4<f32>, clip: vec4<f32>, radius: f32) -> f32 {\n let rowZ = vec3(viewProj[0].z, viewProj[1].z, viewProj[2].z);\n let rowW = vec3(viewProj[0].w, viewProj[1].w, viewProj[2].w);\n let minClipZ = clip.z - radius * length(rowZ);\n let maxClipW = clip.w + radius * length(rowW);\n return max(0.0, minClipZ / max(maxClipW, 0.0001));\n}\n\n@compute @workgroup_size(64, 1, 1)\nfn main(@builtin(global_invocation_id) globalId: vec3<u32>) {\n let drawIndex = globalId.x;\n if (drawIndex >= visibilityParams.drawCount) {\n return;\n }\n\n let drawData = drawMetadata[drawIndex];\n let center = vec4(drawData.centerRadius.xyz, 1.0);\n let radius = drawData.centerRadius.w;\n var visible = isSphereInFrustum(\n rendererCamera.viewProj,\n drawData.centerRadius.xyz,\n radius,\n );\n\n let clip = rendererCamera.viewProj * center;\n let cameraDistance = distance(drawData.centerRadius.xyz, rendererCamera.cameraPosition.xyz);\n // A sphere that intersects the near plane, surrounds the camera, or has a\n // very large projected extent cannot be safely represented by its center.\n // Keep it rather than allowing a false negative to remove large terrain or\n // nearby geometry.\n let clipWRadius = radius * length(vec3(\n rendererCamera.viewProj[0].w,\n rendererCamera.viewProj[1].w,\n rendererCamera.viewProj[2].w,\n ));\n let needsConservativeVisibility =\n clip.w - clipWRadius <= 0.0001 || radius >= cameraDistance * 0.1;\n\n if (!needsConservativeVisibility) {\n let ndc = clip.xyz / clip.w;\n let projectedRadius = projectedSphereRadius(rendererCamera.viewProj, ndc, clip.w, radius);\n let clipRadiusX = projectedRadius.x;\n let clipRadiusY = projectedRadius.y;\n\n if (\n visible &&\n ndc.x - clipRadiusX >= -1.0 && ndc.x + clipRadiusX <= 1.0 &&\n ndc.y - clipRadiusY >= -1.0 && ndc.y + clipRadiusY <= 1.0\n ) {\n let uvCenter = ndc.xy * vec2(0.5, -0.5) + vec2(0.5, 0.5);\n let uvRadius = vec2(clipRadiusX, clipRadiusY) * 0.5;\n let viewport = rendererCamera.viewportAndTime.xy;\n let screenDiameter = max(\n max(clipRadiusX * viewport.x * 0.5, clipRadiusY * viewport.y * 0.5),\n 1.0,\n ) * 2.0;\n let maxMipLevel = max(f32(visibilityParams.hizMipCount) - 1.0, 0.0);\n // Round up from the full diameter. Using floor(log2(radius)) leaves\n // unsampled texels between the corner probes, especially for small\n // objects, and can turn partial coverage into a false occlusion.\n let mipLevel = clamp(ceil(log2(screenDiameter)), 0.0, maxMipLevel);\n // Cover the projected bounds rather than testing only their center. The\n // max-reduced pyramid makes background or a gap at any corner retain the\n // draw, avoiding false occlusion for partially covered objects.\n let hizDepth = max(\n max(\n textureSampleLevel(hizTexture, drawMetaTextureSampler, uvCenter + vec2(-uvRadius.x, -uvRadius.y), mipLevel).r,\n textureSampleLevel(hizTexture, drawMetaTextureSampler, uvCenter + vec2( uvRadius.x, -uvRadius.y), mipLevel).r,\n ),\n max(\n textureSampleLevel(hizTexture, drawMetaTextureSampler, uvCenter + vec2(-uvRadius.x, uvRadius.y), mipLevel).r,\n textureSampleLevel(hizTexture, drawMetaTextureSampler, uvCenter + vec2( uvRadius.x, uvRadius.y), mipLevel).r,\n ),\n );\n let conservativeDepth = nearestSphereDepth(rendererCamera.viewProj, clip, radius);\n visible = conservativeDepth <= hizDepth + 0.0005;\n }\n }\n\n let baseVertex = i32(round(drawData.extra.y));\n indirectArgs[drawIndex].indexCount = u32(round(drawData.args0.x));\n indirectArgs[drawIndex].instanceCount = select(0u, u32(round(drawData.args0.w)), visible);\n indirectArgs[drawIndex].firstIndex = u32(round(drawData.args0.y));\n indirectArgs[drawIndex].baseVertex = baseVertex;\n indirectArgs[drawIndex].firstInstance = u32(round(drawData.args0.z));\n}\n",bindGroupLayoutEntries:[{binding:0,visibility:GPUShaderStage.COMPUTE,buffer:{type:"uniform"}},{binding:1,visibility:GPUShaderStage.COMPUTE,buffer:{type:"uniform"}},{binding:2,visibility:GPUShaderStage.COMPUTE,sampler:{type:"non-filtering"}},{binding:3,visibility:GPUShaderStage.COMPUTE,texture:{sampleType:"unfilterable-float"}},{binding:4,visibility:GPUShaderStage.COMPUTE,buffer:{type:"read-only-storage"}},{binding:5,visibility:GPUShaderStage.COMPUTE,buffer:{type:"storage"}}]}),this.state.staticVisibilityClearKernel=this.createComputeKernel({label:"renderer-static-visibility-clear",code:"\nstruct RendererVisibilityParams {\n drawCount: u32,\n hizMipCount: u32,\n instanceCount: u32,\n flags: u32,\n};\n\n@group(0) @binding(0) var<uniform> visibilityParams: RendererVisibilityParams;\n@group(0) @binding(1) var<storage, read_write> visibleCounts: array<atomic<u32>>;\n@group(0) @binding(2) var<storage, read_write> postVisibleCounts: array<atomic<u32>>;\n@group(0) @binding(3) var<storage, read_write> visibleInstanceMask: array<atomic<u32>>;\n\n@compute @workgroup_size(64, 1, 1)\nfn main(@builtin(global_invocation_id) globalId: vec3<u32>) {\n let index = globalId.x;\n if (index < visibilityParams.drawCount) {\n atomicStore(&visibleCounts[index], 0u);\n atomicStore(&postVisibleCounts[index], 0u);\n }\n if (index < visibilityParams.instanceCount) {\n atomicStore(&visibleInstanceMask[index], 0u);\n }\n}\n",bindGroupLayoutEntries:[{binding:0,visibility:GPUShaderStage.COMPUTE,buffer:{type:"uniform"}},{binding:1,visibility:GPUShaderStage.COMPUTE,buffer:{type:"storage"}},{binding:2,visibility:GPUShaderStage.COMPUTE,buffer:{type:"storage"}},{binding:3,visibility:GPUShaderStage.COMPUTE,buffer:{type:"storage"}}]}),this.state.staticVisibilityCullKernel=this.createComputeKernel({label:"renderer-static-visibility-cull",code:"\nstruct RendererTemporalVisibilityUniforms {\n currentViewProj: mat4x4<f32>,\n previousViewProj: mat4x4<f32>,\n currentCameraPosition: vec4<f32>,\n previousCameraPosition: vec4<f32>,\n viewportAndTime: vec4<f32>,\n};\n\nstruct RendererVisibilityParams {\n drawCount: u32,\n hizMipCount: u32,\n instanceCount: u32,\n flags: u32,\n};\n\nstruct DrawMetadata {\n centerRadius: vec4<f32>,\n args0: vec4<f32>,\n extra: vec4<f32>,\n};\n\nstruct StaticInstanceMetadata {\n centerRadius: vec4<f32>,\n drawAndSourceIndex: vec4<u32>,\n};\n\n@group(0) @binding(0) var<uniform> temporalVisibility: RendererTemporalVisibilityUniforms;\n@group(0) @binding(1) var<uniform> visibilityParams: RendererVisibilityParams;\n@group(0) @binding(2) var hizSampler: sampler;\n@group(0) @binding(3) var hizTexture: texture_2d<f32>;\n@group(0) @binding(4) var<storage, read> instanceMetadata: array<StaticInstanceMetadata>;\n@group(0) @binding(5) var<storage, read> drawMetadata: array<DrawMetadata>;\n@group(0) @binding(6) var<storage, read_write> visibleCounts: array<atomic<u32>>;\n@group(0) @binding(7) var<storage, read_write> visibleInstanceIndices: array<u32>;\n@group(0) @binding(8) var<storage, read_write> visibleInstanceMask: array<atomic<u32>>;\n@group(0) @binding(9) var<storage, read_write> postVisibleCounts: array<atomic<u32>>;\n\nfn spherePlaneRadius(viewProj: mat4x4<f32>, plane: vec4<f32>, radius: f32) -> f32 {\n let worldNormal = vec3(\n dot(viewProj[0], plane),\n dot(viewProj[1], plane),\n dot(viewProj[2], plane),\n );\n return radius * length(worldNormal);\n}\n\nfn projectedSphereRadius(\n viewProj: mat4x4<f32>,\n ndc: vec3<f32>,\n clipW: f32,\n radius: f32,\n) -> vec2<f32> {\n let rowX = vec3(viewProj[0].x, viewProj[1].x, viewProj[2].x);\n let rowY = vec3(viewProj[0].y, viewProj[1].y, viewProj[2].y);\n let rowW = vec3(viewProj[0].w, viewProj[1].w, viewProj[2].w);\n let denominator = max(clipW - radius * length(rowW), 0.0001);\n return radius * vec2(\n length(rowX) + abs(ndc.x) * length(rowW),\n length(rowY) + abs(ndc.y) * length(rowW),\n ) / denominator;\n}\n\nfn nearestSphereDepth(viewProj: mat4x4<f32>, clip: vec4<f32>, radius: f32) -> f32 {\n let rowZ = vec3(viewProj[0].z, viewProj[1].z, viewProj[2].z);\n let rowW = vec3(viewProj[0].w, viewProj[1].w, viewProj[2].w);\n let minClipZ = clip.z - radius * length(rowZ);\n let maxClipW = clip.w + radius * length(rowW);\n return max(0.0, minClipZ / max(maxClipW, 0.0001));\n}\n\nfn isSphereInFrustum(\n viewProj: mat4x4<f32>,\n center: vec3<f32>,\n radius: f32,\n) -> bool {\n let clip = viewProj * vec4(center, 1.0);\n let left = clip.w + clip.x;\n let right = clip.w - clip.x;\n let bottom = clip.w + clip.y;\n let top = clip.w - clip.y;\n let near = clip.z;\n let far = clip.w - clip.z;\n\n return\n left >= -spherePlaneRadius(viewProj, vec4(1.0, 0.0, 0.0, 1.0), radius) &&\n right >= -spherePlaneRadius(viewProj, vec4(-1.0, 0.0, 0.0, 1.0), radius) &&\n bottom >= -spherePlaneRadius(viewProj, vec4(0.0, 1.0, 0.0, 1.0), radius) &&\n top >= -spherePlaneRadius(viewProj, vec4(0.0, -1.0, 0.0, 1.0), radius) &&\n near >= -spherePlaneRadius(viewProj, vec4(0.0, 0.0, 1.0, 0.0), radius) &&\n far >= -spherePlaneRadius(viewProj, vec4(0.0, 0.0, -1.0, 1.0), radius);\n}\n\nfn isSphereNearFrustumBoundary(\n viewProj: mat4x4<f32>,\n center: vec3<f32>,\n radius: f32,\n) -> bool {\n let clip = viewProj * vec4(center, 1.0);\n return\n clip.w + clip.x <= spherePlaneRadius(viewProj, vec4(1.0, 0.0, 0.0, 1.0), radius) ||\n clip.w - clip.x <= spherePlaneRadius(viewProj, vec4(-1.0, 0.0, 0.0, 1.0), radius) ||\n clip.w + clip.y <= spherePlaneRadius(viewProj, vec4(0.0, 1.0, 0.0, 1.0), radius) ||\n clip.w - clip.y <= spherePlaneRadius(viewProj, vec4(0.0, -1.0, 0.0, 1.0), radius) ||\n clip.z <= spherePlaneRadius(viewProj, vec4(0.0, 0.0, 1.0, 0.0), radius) ||\n clip.w - clip.z <= spherePlaneRadius(viewProj, vec4(0.0, 0.0, -1.0, 1.0), radius);\n}\n\nfn isSphereVisible(center: vec3<f32>, radius: f32) -> bool {\n let currentViewProj = temporalVisibility.currentViewProj;\n if (!isSphereInFrustum(currentViewProj, center, radius)) {\n return false;\n }\n\n let clip = currentViewProj * vec4(center, 1.0);\n // Near-plane intersections are deliberately kept. A false negative here would\n // incorrectly remove geometry surrounding the camera.\n if (clip.w <= 0.0001) {\n return true;\n }\n\n if ((visibilityParams.flags & 1u) == 0u) {\n return true;\n }\n\n let usesPreviousHiZ = (visibilityParams.flags & 2u) != 0u;\n var hizViewProj = temporalVisibility.currentViewProj;\n var hizCameraPosition = temporalVisibility.currentCameraPosition.xyz;\n if (usesPreviousHiZ) {\n hizViewProj = temporalVisibility.previousViewProj;\n hizCameraPosition = temporalVisibility.previousCameraPosition.xyz;\n }\n\n let hizClip = hizViewProj * vec4(center, 1.0);\n let hizClipWRadius = radius * length(vec3(\n hizViewProj[0].w,\n hizViewProj[1].w,\n hizViewProj[2].w,\n ));\n if (hizClip.w - hizClipWRadius <= 0.0001) {\n return true;\n }\n let hizNdc = hizClip.xyz / hizClip.w;\n let hizProjectedRadius = projectedSphereRadius(\n hizViewProj,\n hizNdc,\n hizClip.w,\n radius,\n );\n let hizClipRadiusX = hizProjectedRadius.x;\n let hizClipRadiusY = hizProjectedRadius.y;\n let hizClipRadiusZ = radius / max(distance(center, hizCameraPosition), 0.001);\n\n // Samples close to the viewport boundary cannot cover the whole projected\n // sphere. This also retains newly revealed regions during camera motion.\n if (\n isSphereNearFrustumBoundary(hizViewProj, center, radius) ||\n hizNdc.x - hizClipRadiusX < -1.0 || hizNdc.x + hizClipRadiusX > 1.0 ||\n hizNdc.y - hizClipRadiusY < -1.0 || hizNdc.y + hizClipRadiusY > 1.0 ||\n hizNdc.z < -hizClipRadiusZ || hizNdc.z > 1.0 + hizClipRadiusZ\n ) {\n return true;\n }\n\n let viewport = temporalVisibility.viewportAndTime.xy;\n let screenDiameter = max(\n max(hizClipRadiusX * viewport.x * 0.5, hizClipRadiusY * viewport.y * 0.5),\n 1.0,\n ) * 2.0;\n let maxMipLevel = max(f32(visibilityParams.hizMipCount) - 1.0, 0.0);\n let mipLevel = clamp(ceil(log2(screenDiameter)), 0.0, maxMipLevel);\n let uvCenter = hizNdc.xy * vec2(0.5, -0.5) + vec2(0.5, 0.5);\n let uvRadius = vec2(hizClipRadiusX, hizClipRadiusY) * 0.5;\n let hizDepth = max(\n max(\n textureSampleLevel(hizTexture, hizSampler, uvCenter + vec2(-uvRadius.x, -uvRadius.y), mipLevel).r,\n textureSampleLevel(hizTexture, hizSampler, uvCenter + vec2( uvRadius.x, -uvRadius.y), mipLevel).r,\n ),\n max(\n textureSampleLevel(hizTexture, hizSampler, uvCenter + vec2(-uvRadius.x, uvRadius.y), mipLevel).r,\n textureSampleLevel(hizTexture, hizSampler, uvCenter + vec2( uvRadius.x, uvRadius.y), mipLevel).r,\n ),\n );\n let conservativeNearestDepth = nearestSphereDepth(hizViewProj, hizClip, radius);\n return conservativeNearestDepth <= hizDepth + 0.001;\n}\n\n@compute @workgroup_size(64, 1, 1)\nfn main(@builtin(global_invocation_id) globalId: vec3<u32>) {\n let instanceIndex = globalId.x;\n if (instanceIndex >= visibilityParams.instanceCount) {\n return;\n }\n\n let instance = instanceMetadata[instanceIndex];\n if ((visibilityParams.flags & 4u) != 0u && atomicLoad(&visibleInstanceMask[instanceIndex]) != 0u) {\n return;\n }\n let drawIndex = instance.drawAndSourceIndex.x;\n if (drawIndex >= visibilityParams.drawCount || !isSphereVisible(instance.centerRadius.xyz, instance.centerRadius.w)) {\n return;\n }\n\n let isPostpass = (visibilityParams.flags & 4u) != 0u;\n if (!isPostpass) {\n atomicStore(&visibleInstanceMask[instanceIndex], 1u);\n }\n let firstInstance = u32(round(drawMetadata[drawIndex].args0.z));\n if (isPostpass) {\n let primaryVisibleCount = atomicLoad(&visibleCounts[drawIndex]);\n let postVisibleIndex = atomicAdd(&postVisibleCounts[drawIndex], 1u);\n visibleInstanceIndices[firstInstance + primaryVisibleCount + postVisibleIndex] = instance.drawAndSourceIndex.y;\n } else {\n let visibleIndex = atomicAdd(&visibleCounts[drawIndex], 1u);\n visibleInstanceIndices[firstInstance + visibleIndex] = instance.drawAndSourceIndex.y;\n }\n}\n",bindGroupLayoutEntries:[{binding:0,visibility:GPUShaderStage.COMPUTE,buffer:{type:"uniform"}},{binding:1,visibility:GPUShaderStage.COMPUTE,buffer:{type:"uniform"}},{binding:2,visibility:GPUShaderStage.COMPUTE,sampler:{type:"non-filtering"}},{binding:3,visibility:GPUShaderStage.COMPUTE,texture:{sampleType:"unfilterable-float"}},{binding:4,visibility:GPUShaderStage.COMPUTE,buffer:{type:"read-only-storage"}},{binding:5,visibility:GPUShaderStage.COMPUTE,buffer:{type:"read-only-storage"}},{binding:6,visibility:GPUShaderStage.COMPUTE,buffer:{type:"storage"}},{binding:7,visibility:GPUShaderStage.COMPUTE,buffer:{type:"storage"}},{binding:8,visibility:GPUShaderStage.COMPUTE,buffer:{type:"storage"}},{binding:9,visibility:GPUShaderStage.COMPUTE,buffer:{type:"storage"}}]}),this.state.staticVisibilityIndirectBuildKernel=this.createComputeKernel({label:"renderer-static-visibility-indirect-build",code:"\nstruct RendererVisibilityParams {\n drawCount: u32,\n hizMipCount: u32,\n instanceCount: u32,\n flags: u32,\n};\n\nstruct IndirectIndexedArgs {\n indexCount: u32,\n instanceCount: u32,\n firstIndex: u32,\n baseVertex: i32,\n firstInstance: u32,\n};\n\n@group(0) @binding(0) var<uniform> visibilityParams: RendererVisibilityParams;\n@group(0) @binding(1) var<storage, read_write> visibleCounts: array<atomic<u32>>;\n@group(0) @binding(2) var<storage, read_write> postVisibleCounts: array<atomic<u32>>;\n@group(0) @binding(3) var<storage, read_write> indirectArgs: array<IndirectIndexedArgs>;\n@group(0) @binding(4) var<storage, read_write> postIndirectArgs: array<IndirectIndexedArgs>;\n\n@compute @workgroup_size(64, 1, 1)\nfn main(@builtin(global_invocation_id) globalId: vec3<u32>) {\n let drawIndex = globalId.x;\n if (drawIndex >= visibilityParams.drawCount) {\n return;\n }\n\n let primaryVisibleCount = atomicLoad(&visibleCounts[drawIndex]);\n let postVisibleCount = atomicLoad(&postVisibleCounts[drawIndex]);\n indirectArgs[drawIndex].instanceCount = primaryVisibleCount + postVisibleCount;\n if ((visibilityParams.flags & 4u) != 0u) {\n postIndirectArgs[drawIndex].instanceCount = postVisibleCount;\n postIndirectArgs[drawIndex].firstInstance = indirectArgs[drawIndex].firstInstance + primaryVisibleCount;\n }\n}\n",bindGroupLayoutEntries:[{binding:0,visibility:GPUShaderStage.COMPUTE,buffer:{type:"uniform"}},{binding:1,visibility:GPUShaderStage.COMPUTE,buffer:{type:"storage"}},{binding:2,visibility:GPUShaderStage.COMPUTE,buffer:{type:"storage"}},{binding:3,visibility:GPUShaderStage.COMPUTE,buffer:{type:"storage"}},{binding:4,visibility:GPUShaderStage.COMPUTE,buffer:{type:"storage"}}]}),this.state.visibilityParamsBuffer=this.state.device.createBuffer({label:"renderer-visibility-params-buffer",size:16,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this.createStaticPipelines(),this.setSize(this.canvas.clientWidth||this.canvas.width||1,this.canvas.clientHeight||this.canvas.height||1),this.state.initialized=!0}createComputeKernel(t){if(!this.state.device)throw new Error("WebGpuRenderer.initialize() must complete before creating compute kernels.");return new e(this.state.device,t)}setRenderGraphBuilder(e){this.graphBuilder=e}setCascadedShadowRanges(e,t=[]){this.csmCascadeCount=Math.min(e.length,4),this.csmCascadeLights=t.slice(0,this.csmCascadeCount);for(let t=0;t<this.csmCascadeCount;t+=1)this.csmCascadeRanges[t].set(e[t].x,e[t].y);for(let e=this.csmCascadeCount;e<4;e+=1)this.csmCascadeRanges[e].set(0,0)}setRenderGraphProfilingEnabled(e){this.renderGraphProfilingEnabled=e}getRenderGraphProfilingEnabled(){return this.renderGraphProfilingEnabled}getTimestampQuerySupported(){return this.timestampQuerySupported}getSampleCount(){return this.sampleCount}setSampleCount(e){const t=$n(e);t!==this.sampleCount&&(this.sampleCount=t,this.destroyMsaaResources(),this.clearIndirectBundleCache(),this.clearStaticDrawSetBundleCaches())}setRenderScale(e){const t=Ni(e);if(t===this.renderScale)return;this.renderScale=t;const r=this.state.pixelRatio;this.setSize(this.state.presentationWidth/r,this.state.presentationHeight/r,r)}getRenderScale(){return this.renderScale}setProjectionJitter(e,t){if(!Number.isFinite(e)||!Number.isFinite(t))throw new RangeError("Projection jitter must contain finite pixel offsets.");this.projectionJitterPixels.set(e,t)}clearProjectionJitter(){this.projectionJitterPixels.set(0,0)}getLastFrameProfile(){const e=this.state.latestFrameProfile?.timestampQueryActive&&null===this.state.latestFrameProfile.gpuTimeMs&&this.state.latestCompletedFrameProfile?this.state.latestCompletedFrameProfile:this.state.latestFrameProfile;return e?{...e,cpuPhases:{...e.cpuPhases},passes:e.passes.map(e=>({...e})),visibility:e.visibility?{...e.visibility}:null}:null}setHiZOcclusionCullingEnabled(e){this.hiZOcclusionCullingEnabled!==e&&(this.state.temporalHiZHistoryValid=!1),this.hiZOcclusionCullingEnabled=e}getHiZOcclusionCullingEnabled(){return this.hiZOcclusionCullingEnabled}getHiZOcclusionCullingActive(){return this.hiZOcclusionCullingEnabled&&this.indirectFirstInstanceSupported}setMultiDrawIndirectEnabled(e){this.multiDrawIndirectEnabled=e}getMultiDrawIndirectEnabled(){return this.multiDrawIndirectEnabled}setDynamicBatchingEnabled(e){this.dynamicBatchingEnabled=e}getDynamicBatchingEnabled(){return this.dynamicBatchingEnabled}getMultiDrawIndirectSupported(){return this.multiDrawIndirectSupported}getMultiDrawIndirectActive(){return this.multiDrawIndirectEnabled&&this.multiDrawIndirectSupported&&this.getHiZOcclusionCullingActive()}setSize(e,t,r=window.devicePixelRatio||1){if(this.state.pixelRatio=r,this.state.presentationWidth=Math.max(1,Math.floor(e*r)),this.state.presentationHeight=Math.max(1,Math.floor(t*r)),this.state.width=Math.max(1,Math.floor(this.state.presentationWidth*this.renderScale)),this.state.height=Math.max(1,Math.floor(this.state.presentationHeight*this.renderScale)),this.canvas.width=this.state.presentationWidth,this.canvas.height=this.state.presentationHeight,this.canvas.style.width=`${Math.max(1,Math.floor(e))}px`,this.canvas.style.height=`${Math.max(1,Math.floor(t))}px`,this.state.device){for(const[e,t]of this.colorTargetCache){const r="presentation"===t.resolution?this.state.presentationWidth:this.state.width,n="presentation"===t.resolution?this.state.presentationHeight:this.state.height,i=Math.max(1,Math.floor(r*t.scale)),a=Math.max(1,Math.floor(n*t.scale));t.width===i&&t.height===a||(t.texture.destroy(),this.colorTargetCache.delete(e))}this.destroyMsaaResources(),this.state.mainDepthTexture?.destroy(),this.state.mainDepthTexture=this.state.device.createTexture({label:"renderer-main-depth",size:{width:this.state.width,height:this.state.height},format:"depth32float",usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_SRC}),this.state.mainDepthView=this.state.mainDepthTexture.createView(),this.state.hizCopyBindGroup=null,this.state.sceneColorTexture?.destroy(),this.state.sceneColorTexture=this.state.device.createTexture({label:"renderer-scene-color",size:{width:this.state.width,height:this.state.height},format:Er,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_SRC}),this.state.sceneColorView=this.state.sceneColorTexture.createView(),this.state.sceneColorSnapshotTexture?.destroy(),this.state.sceneColorSnapshotTexture=this.state.device.createTexture({label:"renderer-scene-color-snapshot",size:{width:this.state.width,height:this.state.height},format:Er,usage:GPUTextureUsage.COPY_DST|GPUTextureUsage.TEXTURE_BINDING}),this.state.sceneColorSnapshotView=this.state.sceneColorSnapshotTexture.createView(),this.state.sceneDepthSnapshotTexture?.destroy(),this.state.sceneDepthSnapshotTexture=this.state.device.createTexture({label:"renderer-scene-depth-snapshot",size:{width:this.state.width,height:this.state.height},format:"depth32float",usage:GPUTextureUsage.COPY_DST|GPUTextureUsage.TEXTURE_BINDING}),this.state.sceneDepthSnapshotView=this.state.sceneDepthSnapshotTexture.createView(),this.state.postProcessColorTexture?.destroy(),this.state.postProcessColorTexture=this.state.device.createTexture({label:"renderer-post-process-color",size:{width:this.state.width,height:this.state.height},format:Er,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_SRC}),this.state.postProcessColorView=this.state.postProcessColorTexture.createView(),this.state.sceneTextureBindGroupLayout&&this.state.linearClampSampler&&this.state.nearestClampSampler&&(this.state.sceneTextureBindGroup=this.state.device.createBindGroup({label:"renderer-scene-texture-bind-group",layout:this.state.sceneTextureBindGroupLayout,entries:[{binding:0,resource:this.state.linearClampSampler},{binding:1,resource:this.state.sceneColorSnapshotView},{binding:2,resource:this.state.nearestClampSampler},{binding:3,resource:this.state.sceneDepthSnapshotView}]})),this.state.hizTexture?.destroy(),this.state.hizMipCount=Math.max(1,Math.floor(Math.log2(Math.max(this.state.width,this.state.height)))+1),this.state.hizTexture=this.state.device.createTexture({label:"renderer-hiz-pyramid",size:{width:this.state.width,height:this.state.height},format:"r32float",mipLevelCount:this.state.hizMipCount,usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.STORAGE_BINDING}),this.state.hizView=this.state.hizTexture.createView(),this.state.hizMipViews=[],this.state.hizCopyBindGroup=null,this.state.hizReduceBindGroups=[],this.state.visibilityBindGroup=null,this.state.visibilityBindGroupMetadataResource=null;for(let e=0;e<this.state.hizMipCount;e+=1)this.state.hizMipViews.push(this.state.hizTexture.createView({baseMipLevel:e,mipLevelCount:1}));this.hizResourceVersion+=1,this.graphTextureResourceVersion+=1,this.state.temporalHiZHistoryValid=!1;for(const e of this.staticDrawSets)e.visibilityBindGroup=null,e.postVisibilityBindGroup=null,e.visibilityBindGroupHizVersion=0;this.recreateShadowResources()}}setClearColor(e){this.clearColor[0]=e[0],this.clearColor[1]=e[1],this.clearColor[2]=e[2],this.clearColor[3]=e[3]}render(e,t,r=.001*performance.now()){this.renderFrame(e,t,r,!1)}async renderAsync(e,t,r=.001*performance.now()){await this.renderFrame(e,t,r,!0)}compile(e,t){this.prepareSceneForCompilation(e,t,!1)}async compileAsync(e,t){this.state.initialized||await this.initialize(),await this.prepareSceneForCompilation(e,t,!0)}createPMREMGenerator(e=20){if(!this.state.device)throw new Error("WebGpuRenderer.initialize() must complete before creating a PMREM generator.");return new rr({device:this.state.device,getTextureResource:e=>this.getTextureResource(e),registerTextureResource:(e,t)=>this.textureCache.set(e,t)},e)}initTexture(e){this.textureManager.getTextureResource(e)}createStaticDrawSet(e,t={}){return this.staticDrawSetManager.createStaticDrawSet(e,t)}disposeStaticDrawSetResource(e){this.staticDrawSetManager.disposeStaticDrawSetResource(e)}renderFrame(e,t,r,n){if(!(this.state.initialized&&this.state.device&&this.state.context&&this.state.mainDepthView&&this.state.sceneColorView&&this.state.postProcessColorView&&this.state.cameraBuffer&&this.state.lightBuffer&&this.state.shadowCameraBuffer&&this.state.sceneBindGroupLayout&&this.state.shadowBindGroupLayout&&this.state.shadowComparisonSampler&&this.state.linearClampSampler&&this.state.nearestClampSampler&&this.state.visibilityParamsBuffer&&this.state.directionalShadowView&&this.state.pointShadowArrayView&&this.state.spotShadowView&&this.state.hizCopyKernel&&this.state.hizReduceKernel&&this.state.visibilityKernel&&this.state.presentPipeline))throw new Error("WebGpuRenderer.initialize() must complete before render().");this.state.frameTimeSeconds=r,this.staticFrameToken+=1,e.matrixWorldAutoUpdate&&e.updateMatrixWorld(),null===t.parent&&t.matrixWorldAutoUpdate&&t.updateMatrixWorld();const i=performance.now(),a=this.extractScene(e,t);this.ensureShadowTextureSizes(a);const s=performance.now()-i,o={drawCallCount:0,triangleCount:0},l=performance.now();this.uploadInstanceData(a.instanceData),this.uploadResidentInstanceData(a.residentInstanceUploads);const c=this.getHiZOcclusionCullingActive();this.uploadDrawMetadata(c?a.gpuOpaqueDraws:[]),this.updateCameraUniforms(t,e),this.updateTemporalVisibilityUniforms(t),this.updateLightUniforms(a);const u=performance.now()-l,d=this.state.device.createCommandEncoder({label:"renderer-command-encoder"}),h=this.state.context.getCurrentTexture().createView(),p=this.getSharedSceneBindGroup(),f=this.getSharedShadowBindGroup();let m=null;const g=this.state.drawMetadataResource;c&&g&&g.count>0&&this.state.hizView&&(this.state.visibilityBindGroup&&this.state.visibilityBindGroupMetadataResource===g||(this.state.visibilityBindGroup=this.state.visibilityKernel.createBindGroup(this.state.device,[{binding:0,resource:{buffer:this.state.cameraBuffer}},{binding:1,resource:{buffer:this.state.visibilityParamsBuffer}},{binding:2,resource:this.state.nearestClampSampler},{binding:3,resource:this.state.hizView},{binding:4,resource:{buffer:g.metadataBuffer}},{binding:5,resource:{buffer:g.indirectBuffer}}],"renderer-visibility-bind-group"),this.state.visibilityBindGroupMetadataResource=g),m=this.state.visibilityBindGroup),this.renderGraph.reset();const x=this.createGraphBuilderContext(this.renderGraph,d,p,f,m,h,a,o);this.graphBuilder(this.renderGraph,x);const v={device:this.state.device,encoder:d},w=function(e,t,r,n,i){if(!t.renderGraphProfilingEnabled||!e.device)return null;const a={frameIndex:e.frameIndex+=1,cpuTimeMs:0,gpuTimeMs:null,drawCallCount:n.drawCallCount,triangleCount:n.triangleCount,cpuPhases:{extractSceneMs:i.extractSceneMs,uploadMs:i.uploadMs,renderGraphMs:0},passes:[],timestampQuerySupported:t.timestampQuerySupported,timestampQueryActive:t.timestampQuerySupported,gpuProfilingReason:null,hiZOcclusionCullingEnabled:t.hiZOcclusionCullingEnabled,hiZOcclusionCullingActive:r,visibility:null};let s=null;const o={begin:(e,r)=>{if(a.passes=e.map(e=>({name:e.name,cpuTimeMs:0,gpuTimeMs:null})),!t.timestampQuerySupported)return a.timestampQueryActive=!1,void(a.gpuProfilingReason="timestamp-query is not supported by this adapter/device");if(0===e.length)return a.timestampQueryActive=!1,void(a.gpuProfilingReason="no render graph passes were recorded");const n=2*e.length,i=Math.max(8,8*n),o=r.device.createQuerySet({label:`renderer-frame-profile-${a.frameIndex}`,type:"timestamp",count:n}),l=r.device.createBuffer({label:`renderer-frame-profile-resolve-${a.frameIndex}`,size:i,usage:GPUBufferUsage.QUERY_RESOLVE|GPUBufferUsage.COPY_SRC}),c=r.device.createBuffer({label:`renderer-frame-profile-read-${a.frameIndex}`,size:i,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});s={profile:a,querySet:o,resolveBuffer:l,readBuffer:c,queryCount:n}},beforePass:(e,t,r)=>{s&&(un(r.encoder,s.querySet,{endOfPassWriteIndex:2*t})||(a.timestampQueryActive=!1,a.gpuProfilingReason="timestampWrites marker pass is not available on this browser/runtime",s.querySet.destroy(),s.resolveBuffer.destroy(),s.readBuffer.destroy(),s=null))},afterPass:(e,t,r,n)=>{a.passes[t].cpuTimeMs=r,s&&(un(n.encoder,s.querySet,{beginningOfPassWriteIndex:2*t+1})||(a.timestampQueryActive=!1,a.gpuProfilingReason="timestampWrites marker pass is not available on this browser/runtime",s.querySet.destroy(),s.resolveBuffer.destroy(),s.readBuffer.destroy(),s=null))},end:(t,r,i)=>{if(a.cpuPhases.renderGraphMs=r,a.cpuTimeMs=a.cpuPhases.extractSceneMs+a.cpuPhases.uploadMs+a.cpuPhases.renderGraphMs,a.drawCallCount=n.drawCallCount,a.triangleCount=n.triangleCount,!s){const t=qn(a);return e.latestFrameProfile=t,void(e.latestCompletedFrameProfile=t)}i.encoder.resolveQuerySet(s.querySet,0,s.queryCount,s.resolveBuffer,0),i.encoder.copyBufferToBuffer(s.resolveBuffer,0,s.readBuffer,0,8*s.queryCount),e.latestFrameProfile=qn(a)}};return{profile:a,observer:o,pendingVisibilityRead:null,get pendingGpuRead(){return s},set pendingGpuRead(e){s=e}}}(this.state,{renderGraphProfilingEnabled:this.renderGraphProfilingEnabled,timestampQuerySupported:this.timestampQuerySupported,hiZOcclusionCullingEnabled:this.hiZOcclusionCullingEnabled},c,o,{extractSceneMs:s,uploadMs:u}),b=()=>{if(!w||!c)return;const e=[];g&&g.count>0&&e.push({buffer:g.indirectBuffer,drawCount:g.count,totalInstances:a.gpuOpaqueDraws.reduce((e,t)=>e+Math.max(0,t.instanceCount),0),kind:"dynamic"});for(const t of this.staticDrawSets)t.publicSet.enabled&&t.lastVisibilityFrameToken===this.staticFrameToken&&e.push({buffer:t.drawMetadataResource.indirectBuffer,drawCount:t.drawMetadataResource.count,totalInstances:t.instanceCount,kind:"static"});!function(e,t,r,n){const i=n.filter(e=>e.drawCount>0);if(0===i.length)return void(e.profile.visibility={totalInstances:0,visibleInstances:0,culledInstances:0,dynamicTotalInstances:0,dynamicVisibleInstances:0,staticTotalInstances:0,staticVisibleInstances:0});let a=0;const s=i.map(e=>{const t={byteOffset:a,drawCount:e.drawCount,totalInstances:e.totalInstances,kind:e.kind};return a+=5*e.drawCount*Uint32Array.BYTES_PER_ELEMENT,t}),o=t.createBuffer({label:`renderer-visibility-profile-read-${e.profile.frameIndex}`,size:Math.max(4,a),usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});for(let e=0;e<i.length;e+=1){const t=i[e];r.copyBufferToBuffer(t.buffer,0,o,s[e].byteOffset,5*t.drawCount*Uint32Array.BYTES_PER_ELEMENT)}e.pendingVisibilityRead={readBuffer:o,regions:s}}(w,this.state.device,d,e)};if(n)return this.renderGraph.executeAsync(v,w?.observer).then(()=>{b(),this.state.device.queue.submit([d.finish()]),this.releaseRetiredGeometryResourcesAfterSubmit(),w&&Nn(this.state,w)});this.renderGraph.execute(v,w?.observer),b(),this.state.device.queue.submit([d.finish()]),this.releaseRetiredGeometryResourcesAfterSubmit(),w&&Nn(this.state,w)}destroy(){this.clearIndirectBundleCache();for(const e of this.staticDrawSets.slice())this.disposeStaticDrawSetResource(e);this.sharedForwardPipelineCache.clear(),this.sharedForwardPipelinePromiseCache.clear(),this.sharedDepthPipelineCache.clear(),this.sharedDepthPipelinePromiseCache.clear();for(const e of this.skinnedGeometryCache.values())e.skinning.bindUniformBuffer.destroy();this.skinnedGeometryCache.clear();for(const e of this.skinPaletteResources)e.matrixBuffer.destroy();this.skinPaletteResources.clear();for(const e of this.retiredGeometryResources)this.destroyGeometryResource(e);this.retiredGeometryResources.length=0;for(const e of this.colorTargetCache.values())e.texture.destroy();this.colorTargetCache.clear(),this.destroyMsaaResources(),this.state.mainDepthTexture?.destroy(),this.state.sceneColorTexture?.destroy(),this.state.sceneColorSnapshotTexture?.destroy(),this.state.sceneDepthSnapshotTexture?.destroy(),this.state.postProcessColorTexture?.destroy(),this.state.directionalShadowTexture?.destroy(),this.state.pointShadowTexture?.destroy(),this.state.pointShadowDepthTexture?.destroy(),this.state.spotShadowTexture?.destroy(),this.state.hizTexture?.destroy(),this.state.cameraBuffer?.destroy(),this.state.temporalVisibilityBuffer?.destroy(),this.state.lightBuffer?.destroy(),this.state.shadowCameraBuffer?.destroy();for(const e of this.state.shadowCameraBufferPool)e.destroy();this.state.shadowCameraBufferPool.length=0,this.state.sharedShadowBindGroupByCameraBuffer.clear(),this.state.instanceBuffer?.destroy();for(const e of this.defaultInstanceAttributeBuffers.values())for(const t of e.values())t.destroy();this.defaultInstanceAttributeBuffers.clear(),this.state.visibilityParamsBuffer?.destroy(),this.state.drawMetadataResource?.metadataBuffer.destroy(),this.state.drawMetadataResource?.indirectBuffer.destroy(),this.state.drawMetadataResource?.postIndirectBuffer.destroy(),this.state.initialized=!1,this.state.device?.destroy(),this.state.device=null}createStaticPipelines(){if(!(this.state.device&&this.state.sceneBindGroupLayout&&this.state.directSceneBindGroupLayout&&this.state.visibleDepthSceneBindGroupLayout&&this.state.shadowBindGroupLayout&&this.state.directShadowBindGroupLayout&&this.state.emptyBindGroupLayout&&this.state.skinningBindGroupLayout&&this.state.fullscreenTextureBindGroupLayout&&this.state.format))return;const e=this.state.device.createPipelineLayout({label:"renderer-depth-prepass-layout",bindGroupLayouts:[this.state.sceneBindGroupLayout]});this.state.depthPrepassPipeline=this.state.device.createRenderPipeline({label:"renderer-depth-prepass-pipeline",layout:e,vertex:{module:this.state.device.createShaderModule({label:"renderer-depth-prepass-module",code:"\nstruct RendererCameraUniforms {\n viewProj: mat4x4<f32>,\n cameraPosition: vec4<f32>,\n viewportAndTime: vec4<f32>,\n};\n\nstruct RendererInstanceData {\n model0: vec4<f32>,\n model1: vec4<f32>,\n model2: vec4<f32>,\n model3: vec4<f32>,\n color: vec4<f32>,\n batching: vec4<f32>,\n};\n\n@group(0) @binding(0) var<uniform> rendererCamera: RendererCameraUniforms;\n@group(0) @binding(1) var<uniform> rendererLights: array<vec4<f32>, 11>;\n@group(0) @binding(2) var<storage, read> rendererInstances: array<RendererInstanceData>;\n\nfn rendererInstanceModelMatrix(instanceIndex: u32) -> mat4x4<f32> {\n let instance = rendererInstances[instanceIndex];\n return mat4x4<f32>(instance.model0, instance.model1, instance.model2, instance.model3);\n}\n\n@vertex\nfn vsMain(\n @location(0) position: vec3<f32>,\n @builtin(instance_index) instanceIndex: u32\n) -> @builtin(position) vec4<f32> {\n let world = rendererInstanceModelMatrix(instanceIndex) * vec4(position, 1.0);\n return rendererCamera.viewProj * world;\n}\n"}),entryPoint:"vsMain",buffers:[{arrayStride:12,attributes:[{shaderLocation:0,offset:0,format:"float32x3"}]}]},primitive:{topology:"triangle-list",cullMode:"back",frontFace:"ccw"},depthStencil:{format:"depth32float",depthWriteEnabled:!0,depthCompare:"less"}});const t=this.state.device.createPipelineLayout({label:"renderer-depth-prepass-visible-layout",bindGroupLayouts:[this.state.visibleDepthSceneBindGroupLayout]});this.state.depthPrepassPipelineVisible=this.state.device.createRenderPipeline({label:"renderer-depth-prepass-visible-pipeline",layout:t,vertex:{module:this.state.device.createShaderModule({label:"renderer-depth-prepass-visible-module",code:"\nstruct RendererCameraUniforms {\n viewProj: mat4x4<f32>,\n cameraPosition: vec4<f32>,\n viewportAndTime: vec4<f32>,\n};\n\nstruct RendererInstanceData {\n model0: vec4<f32>,\n model1: vec4<f32>,\n model2: vec4<f32>,\n model3: vec4<f32>,\n color: vec4<f32>,\n batching: vec4<f32>,\n};\n\n@group(0) @binding(0) var<uniform> rendererCamera: RendererCameraUniforms;\n@group(0) @binding(2) var<storage, read> rendererInstances: array<RendererInstanceData>;\n@group(0) @binding(3) var<storage, read> rendererVisibleInstanceIndices: array<u32>;\n\nfn rendererInstanceModelMatrix(instanceIndex: u32) -> mat4x4<f32> {\n let instance = rendererInstances[rendererVisibleInstanceIndices[instanceIndex]];\n return mat4x4<f32>(instance.model0, instance.model1, instance.model2, instance.model3);\n}\n\n@vertex\nfn vsMain(\n @location(0) position: vec3<f32>,\n @builtin(instance_index) instanceIndex: u32\n) -> @builtin(position) vec4<f32> {\n let world = rendererInstanceModelMatrix(instanceIndex) * vec4(position, 1.0);\n return rendererCamera.viewProj * world;\n}\n"}),entryPoint:"vsMain",buffers:[{arrayStride:12,attributes:[{shaderLocation:0,offset:0,format:"float32x3"}]}]},primitive:{topology:"triangle-list",cullMode:"back",frontFace:"ccw"},depthStencil:{format:"depth32float",depthWriteEnabled:!0,depthCompare:"less"}});const r=this.state.device.createPipelineLayout({label:"renderer-depth-prepass-direct-layout",bindGroupLayouts:[this.state.directSceneBindGroupLayout]});this.state.depthPrepassPipelineDirect=this.state.device.createRenderPipeline({label:"renderer-depth-prepass-direct-pipeline",layout:r,vertex:{module:this.state.device.createShaderModule({label:"renderer-depth-prepass-direct-module",code:"\nstruct RendererCameraUniforms {\n viewProj: mat4x4<f32>,\n cameraPosition: vec4<f32>,\n viewportAndTime: vec4<f32>,\n};\n\n@group(0) @binding(0) var<uniform> rendererCamera: RendererCameraUniforms;\n@group(0) @binding(1) var<uniform> rendererLights: array<vec4<f32>, 11>;\n@group(0) @binding(2) var<storage, read> rendererInstanceMatrices: array<vec4<f32>>;\n\nfn rendererInstanceModelMatrix(instanceIndex: u32) -> mat4x4<f32> {\n let base = instanceIndex * 4u;\n return mat4x4<f32>(\n rendererInstanceMatrices[base + 0u],\n rendererInstanceMatrices[base + 1u],\n rendererInstanceMatrices[base + 2u],\n rendererInstanceMatrices[base + 3u]\n );\n}\n\n@vertex\nfn vsMain(\n @location(0) position: vec3<f32>,\n @builtin(instance_index) instanceIndex: u32\n) -> @builtin(position) vec4<f32> {\n let world = rendererInstanceModelMatrix(instanceIndex) * vec4(position, 1.0);\n return rendererCamera.viewProj * world;\n}\n"}),entryPoint:"vsMain",buffers:[{arrayStride:12,attributes:[{shaderLocation:0,offset:0,format:"float32x3"}]}]},primitive:{topology:"triangle-list",cullMode:"back",frontFace:"ccw"},depthStencil:{format:"depth32float",depthWriteEnabled:!0,depthCompare:"less"}});const n=this.state.device.createPipelineLayout({label:"renderer-skinned-depth-prepass-layout",bindGroupLayouts:[this.state.sceneBindGroupLayout,this.state.emptyBindGroupLayout,this.state.skinningBindGroupLayout]});this.state.skinnedDepthPrepassPipeline=this.state.device.createRenderPipeline({label:"renderer-skinned-depth-prepass-pipeline",layout:n,vertex:{module:this.state.device.createShaderModule({label:"renderer-skinned-depth-prepass-module",code:Li}),entryPoint:"vsMain",buffers:this.createVertexBufferLayouts(Nr)},primitive:{topology:"triangle-list",cullMode:"back",frontFace:"ccw"},depthStencil:{format:"depth32float",depthWriteEnabled:!0,depthCompare:"less"}});const i=this.state.device.createPipelineLayout({label:"renderer-shadow-layout",bindGroupLayouts:[this.state.shadowBindGroupLayout]}),a=this.state.device.createPipelineLayout({label:"renderer-direct-shadow-pipeline-layout",bindGroupLayouts:[this.state.directShadowBindGroupLayout]});this.state.shadowDepthPipeline=this.state.device.createRenderPipeline({label:"renderer-directional-shadow-pipeline",layout:i,vertex:{module:this.state.device.createShaderModule({label:"renderer-directional-shadow-module",code:"\nstruct ShadowCameraUniforms {\n viewProj: mat4x4<f32>,\n lightPositionRange: vec4<f32>,\n};\n\nstruct RendererInstanceData {\n model0: vec4<f32>,\n model1: vec4<f32>,\n model2: vec4<f32>,\n model3: vec4<f32>,\n color: vec4<f32>,\n batching: vec4<f32>,\n};\n\n@group(0) @binding(0) var<uniform> shadowCamera: ShadowCameraUniforms;\n@group(0) @binding(1) var<storage, read> rendererInstances: array<RendererInstanceData>;\n\nfn rendererInstanceModelMatrix(instanceIndex: u32) -> mat4x4<f32> {\n let instance = rendererInstances[instanceIndex];\n return mat4x4<f32>(instance.model0, instance.model1, instance.model2, instance.model3);\n}\n\n@vertex\nfn vsMain(\n @location(0) position: vec3<f32>,\n @builtin(instance_index) instanceIndex: u32\n) -> @builtin(position) vec4<f32> {\n let world = rendererInstanceModelMatrix(instanceIndex) * vec4(position, 1.0);\n return shadowCamera.viewProj * world;\n}\n"}),entryPoint:"vsMain",buffers:[{arrayStride:12,attributes:[{shaderLocation:0,offset:0,format:"float32x3"}]}]},primitive:{topology:"triangle-list",cullMode:"front",frontFace:"ccw"},depthStencil:{format:"depth32float",depthWriteEnabled:!0,depthCompare:"less",depthBias:1,depthBiasSlopeScale:2,depthBiasClamp:0}}),this.state.shadowDepthPipelineDirect=this.state.device.createRenderPipeline({label:"renderer-directional-shadow-direct-pipeline",layout:a,vertex:{module:this.state.device.createShaderModule({label:"renderer-directional-shadow-direct-module",code:"\nstruct ShadowCameraUniforms {\n viewProj: mat4x4<f32>,\n lightPositionRange: vec4<f32>,\n};\n\n@group(0) @binding(0) var<uniform> shadowCamera: ShadowCameraUniforms;\n@group(0) @binding(1) var<storage, read> rendererInstanceMatrices: array<vec4<f32>>;\n\nfn rendererInstanceModelMatrix(instanceIndex: u32) -> mat4x4<f32> {\n let base = instanceIndex * 4u;\n return mat4x4<f32>(\n rendererInstanceMatrices[base + 0u],\n rendererInstanceMatrices[base + 1u],\n rendererInstanceMatrices[base + 2u],\n rendererInstanceMatrices[base + 3u]\n );\n}\n\n@vertex\nfn vsMain(\n @location(0) position: vec3<f32>,\n @builtin(instance_index) instanceIndex: u32\n) -> @builtin(position) vec4<f32> {\n let world = rendererInstanceModelMatrix(instanceIndex) * vec4(position, 1.0);\n return shadowCamera.viewProj * world;\n}\n"}),entryPoint:"vsMain",buffers:[{arrayStride:12,attributes:[{shaderLocation:0,offset:0,format:"float32x3"}]}]},primitive:{topology:"triangle-list",cullMode:"front",frontFace:"ccw"},depthStencil:{format:"depth32float",depthWriteEnabled:!0,depthCompare:"less",depthBias:1,depthBiasSlopeScale:2,depthBiasClamp:0}});const s=this.state.device.createPipelineLayout({label:"renderer-skinned-shadow-layout",bindGroupLayouts:[this.state.shadowBindGroupLayout,this.state.emptyBindGroupLayout,this.state.skinningBindGroupLayout]});this.state.skinnedShadowDepthPipeline=this.state.device.createRenderPipeline({label:"renderer-skinned-directional-shadow-pipeline",layout:s,vertex:{module:this.state.device.createShaderModule({label:"renderer-skinned-directional-shadow-module",code:zi}),entryPoint:"vsMain",buffers:this.createVertexBufferLayouts(Nr)},primitive:{topology:"triangle-list",cullMode:"front",frontFace:"ccw"},depthStencil:{format:"depth32float",depthWriteEnabled:!0,depthCompare:"less",depthBias:1,depthBiasSlopeScale:2,depthBiasClamp:0}}),this.state.pointShadowPipeline=this.state.device.createRenderPipeline({label:"renderer-point-shadow-pipeline",layout:i,vertex:{module:this.state.device.createShaderModule({label:"renderer-point-shadow-module",code:Ii}),entryPoint:"vsMain",buffers:[{arrayStride:12,attributes:[{shaderLocation:0,offset:0,format:"float32x3"}]}]},fragment:{module:this.state.device.createShaderModule({label:"renderer-point-shadow-fragment-module",code:Ii}),entryPoint:"fsMain",targets:[{format:"rgba16float"}]},primitive:{topology:"triangle-list",cullMode:"back",frontFace:"ccw"},depthStencil:{format:"depth32float",depthWriteEnabled:!0,depthCompare:"less"}}),this.state.pointShadowPipelineDirect=this.state.device.createRenderPipeline({label:"renderer-point-shadow-direct-pipeline",layout:a,vertex:{module:this.state.device.createShaderModule({label:"renderer-point-shadow-direct-module",code:Gi}),entryPoint:"vsMain",buffers:[{arrayStride:12,attributes:[{shaderLocation:0,offset:0,format:"float32x3"}]}]},fragment:{module:this.state.device.createShaderModule({label:"renderer-point-shadow-direct-fragment-module",code:Gi}),entryPoint:"fsMain",targets:[{format:"rgba16float"}]},primitive:{topology:"triangle-list",cullMode:"back",frontFace:"ccw"},depthStencil:{format:"depth32float",depthWriteEnabled:!0,depthCompare:"less"}}),this.state.skinnedPointShadowPipeline=this.state.device.createRenderPipeline({label:"renderer-skinned-point-shadow-pipeline",layout:s,vertex:{module:this.state.device.createShaderModule({label:"renderer-skinned-point-shadow-module",code:Ui}),entryPoint:"vsMain",buffers:this.createVertexBufferLayouts(Nr)},fragment:{module:this.state.device.createShaderModule({label:"renderer-skinned-point-shadow-fragment-module",code:Ui}),entryPoint:"fsMain",targets:[{format:"rgba16float"}]},primitive:{topology:"triangle-list",cullMode:"back",frontFace:"ccw"},depthStencil:{format:"depth32float",depthWriteEnabled:!0,depthCompare:"less"}});const o=this.state.device.createPipelineLayout({label:"renderer-present-layout",bindGroupLayouts:[this.state.fullscreenTextureBindGroupLayout]});this.state.presentPipeline=this.state.device.createRenderPipeline({label:"renderer-present-pipeline",layout:o,vertex:{module:this.state.device.createShaderModule({label:"renderer-present-module",code:Vi}),entryPoint:"vsMain"},fragment:{module:this.state.device.createShaderModule({label:"renderer-present-fragment-module",code:Vi}),entryPoint:"fsMain",targets:[{format:this.state.format}]},primitive:{topology:"triangle-list"}})}recreateShadowResources(){if(this.state.device){this.state.residentSceneBindGroupVersion+=1,this.state.sharedSceneBindGroup=null,this.clearIndirectBundleCache(),this.clearStaticDrawSetBundleCaches(),this.state.directionalShadowTexture?.destroy(),this.state.directionalShadowTexture=this.state.device.createTexture({label:"renderer-directional-shadow-texture",size:{width:this.state.directionalShadowTextureSize,height:this.state.directionalShadowTextureSize,depthOrArrayLayers:4},format:"depth32float",dimension:"2d",usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_SRC}),this.state.directionalShadowView=this.state.directionalShadowTexture.createView({dimension:"2d-array"}),this.state.directionalShadowLayerViews=[];for(let e=0;e<4;e+=1)this.state.directionalShadowLayerViews.push(this.state.directionalShadowTexture.createView({dimension:"2d",baseArrayLayer:e,arrayLayerCount:1}));this.state.pointShadowTexture?.destroy(),this.state.pointShadowTexture=this.state.device.createTexture({label:"renderer-point-shadow-texture",size:{width:this.state.pointShadowTextureSize,height:this.state.pointShadowTextureSize,depthOrArrayLayers:24},format:"rgba16float",dimension:"2d",usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING}),this.state.pointShadowArrayView=this.state.pointShadowTexture.createView({dimension:"2d-array"}),this.state.pointShadowFaceViews=[];for(let e=0;e<24;e+=1)this.state.pointShadowFaceViews.push(this.state.pointShadowTexture.createView({dimension:"2d",baseArrayLayer:e,arrayLayerCount:1}));this.state.pointShadowDepthTexture?.destroy(),this.state.pointShadowDepthTexture=this.state.device.createTexture({label:"renderer-point-shadow-depth-texture",size:{width:this.state.pointShadowTextureSize,height:this.state.pointShadowTextureSize,depthOrArrayLayers:24},format:"depth32float",dimension:"2d",usage:GPUTextureUsage.RENDER_ATTACHMENT}),this.state.pointShadowDepthFaceViews=[];for(let e=0;e<24;e+=1)this.state.pointShadowDepthFaceViews.push(this.state.pointShadowDepthTexture.createView({dimension:"2d",baseArrayLayer:e,arrayLayerCount:1}));this.state.spotShadowTexture?.destroy(),this.state.spotShadowTexture=this.state.device.createTexture({label:"renderer-spot-shadow-texture",size:{width:this.state.spotShadowTextureSize,height:this.state.spotShadowTextureSize,depthOrArrayLayers:4},format:"depth32float",dimension:"2d",usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING}),this.state.spotShadowView=this.state.spotShadowTexture.createView({dimension:"2d-array"}),this.state.spotShadowLayerViews=[];for(let e=0;e<4;e+=1)this.state.spotShadowLayerViews.push(this.state.spotShadowTexture.createView({dimension:"2d",baseArrayLayer:e,arrayLayerCount:1}))}}ensureShadowTextureSizes(e){const t=Math.max(this.shadowMapSize,...e.lights.directionals.map(e=>Math.ceil(e.shadowMapSize))),r=Math.max(this.pointShadowMapSize,...e.lights.points.map(e=>Math.ceil(e.shadowMapSize))),n=Math.max(this.shadowMapSize,...e.lights.spots.map(e=>Math.ceil(e.shadowMapSize)));t===this.state.directionalShadowTextureSize&&r===this.state.pointShadowTextureSize&&n===this.state.spotShadowTextureSize||(this.state.directionalShadowTextureSize=t,this.state.pointShadowTextureSize=r,this.state.spotShadowTextureSize=n,this.recreateShadowResources())}ensureColorTarget(e,t={}){if(!this.state.device||!this.state.format)throw new Error("Renderer is not initialized.");if("sceneColor"===e||"postProcessColor"===e)throw new Error(`Color target "${e}" is reserved by the renderer.`);const r=t.scale??1,n=t.resolution??"render",i=t.format??Er,a="presentation"===n?this.state.presentationWidth:this.state.width,s="presentation"===n?this.state.presentationHeight:this.state.height,o=Math.max(1,Math.floor(a*r)),l=Math.max(1,Math.floor(s*r)),c=this.colorTargetCache.get(e);if(c&&c.format===i&&c.width===o&&c.height===l&&c.scale===r&&c.resolution===n)return c;c?.texture.destroy();const u=this.state.device.createTexture({label:`renderer-color-target-${e}`,size:{width:o,height:l},format:i,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_SRC}),d={name:e,format:i,width:o,height:l,scale:r,resolution:n,texture:u,view:u.createView()};return this.colorTargetCache.set(e,d),this.graphTextureResourceVersion+=1,d}ensureMsaaColorTarget(e){if(!this.state.device)throw new Error("Renderer is not initialized.");const t=this.getColorTargetDimensions(e),r=this.getColorTargetFormat(e),n=this.msaaColorTargetCache.get(e);if(n&&n.format===r&&n.width===t.width&&n.height===t.height&&1===n.scale)return n;n?.texture.destroy();const i=this.state.device.createTexture({label:`renderer-msaa-color-target-${e}`,size:{width:t.width,height:t.height},sampleCount:this.sampleCount,format:r,usage:GPUTextureUsage.RENDER_ATTACHMENT}),a={name:e,format:r,width:t.width,height:t.height,scale:1,texture:i,view:i.createView()};return this.msaaColorTargetCache.set(e,a),a}ensureMsaaDepthTarget(e,t){if(!this.state.device)throw new Error("Renderer is not initialized.");const r=`${e}x${t}`,n=this.msaaDepthTargetCache.get(r);if(n&&n.width===e&&n.height===t&&n.sampleCount===this.sampleCount)return n;n?.texture.destroy();const i=this.state.device.createTexture({label:`renderer-msaa-depth-${r}`,size:{width:e,height:t},sampleCount:this.sampleCount,format:"depth32float",usage:GPUTextureUsage.RENDER_ATTACHMENT}),a={width:e,height:t,sampleCount:this.sampleCount,texture:i,view:i.createView()};return this.msaaDepthTargetCache.set(r,a),a}destroyMsaaResources(){for(const e of this.msaaColorTargetCache.values())e.texture.destroy();this.msaaColorTargetCache.clear();for(const e of this.msaaDepthTargetCache.values())e.texture.destroy();this.msaaDepthTargetCache.clear()}getColorTargetView(e){if("sceneColor"===e){if(!this.state.sceneColorView)throw new Error("Scene color target is not available.");return this.state.sceneColorView}if("postProcessColor"===e){if(!this.state.postProcessColorView)throw new Error("Post-process color target is not available.");return this.state.postProcessColorView}const t=this.colorTargetCache.get(e);if(!t)throw new Error(`Color target "${e}" has not been defined.`);return t.view}ensureTextureTarget(e,t={}){if("2d"===(t.dimension??"2d")&&null==t.usage)return this.ensureColorTarget(e,t);if(!this.state.device)throw new Error("Renderer is not initialized.");const r=t.scale??1,n=t.resolution??"render",i="presentation"===n?this.state.presentationWidth:this.state.width,a="presentation"===n?this.state.presentationHeight:this.state.height,s=Math.max(1,Math.floor(i*r)),o=Math.max(1,Math.floor(a*r)),l=Math.max(1,t.depthOrArrayLayers??1),c=t.format??Er,u=this.colorTargetCache.get(e),d=t.dimension??"2d",h=t.usage??GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.STORAGE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.COPY_SRC;if(u&&u.format===c&&u.width===s&&u.height===o&&u.resolution===n&&u.dimension===d&&u.depthOrArrayLayers===l&&u.usage===h)return u;u?.texture.destroy();const p=this.state.device.createTexture({label:`renderer-texture-target-${e}`,size:{width:s,height:o,depthOrArrayLayers:l},dimension:d,format:c,usage:h}),f={name:e,format:c,width:s,height:o,scale:r,resolution:n,dimension:d,depthOrArrayLayers:l,usage:h,texture:p,view:p.createView({dimension:d})};return this.colorTargetCache.set(e,f),this.graphTextureResourceVersion+=1,f}getColorTargetTexture(e){if("sceneColor"===e){if(!this.state.sceneColorTexture)throw new Error("Scene color target is not available.");return this.state.sceneColorTexture}if("postProcessColor"===e){if(!this.state.postProcessColorTexture)throw new Error("Post-process color target is not available.");return this.state.postProcessColorTexture}const t=this.colorTargetCache.get(e);if(!t)throw new Error(`Color target "${e}" has not been defined.`);return t.texture}getColorTargetDimensions(e){if("sceneColor"===e||"postProcessColor"===e)return{width:this.state.width,height:this.state.height};const t=this.colorTargetCache.get(e);if(!t)throw new Error(`Color target "${e}" has not been defined.`);return{width:t.width,height:t.height}}getColorTargetFormat(e){if(!this.state.format)throw new Error("Renderer is not initialized.");if("sceneColor"===e||"postProcessColor"===e)return Er;const t=this.colorTargetCache.get(e);if(!t)throw new Error(`Color target "${e}" has not been defined.`);return t.format}getMaterialGraphTextureReads(e){const t=this.materialGraphTextureReadCache.get(e);if(t?.materialVersion===e.version)return t.resources;const r=e.getGraphTextureInputs(),n=[];for(const e in r){const t=r[e].resource;n.includes(t)||n.push(t)}return this.materialGraphTextureReadCache.set(e,{materialVersion:e.version,resources:n}),n}createGraphBuilderContext(e,t,r,n,i,a,s,o,l){let c=!1,u=!1;const d=e=>{const t=new Set;for(let r=0;r<e.length;r+=1){const n=this.getMaterialGraphTextureReads(e[r].material);for(let e=0;e<n.length;e+=1)t.add(n[e])}return Array.from(t)},h={device:this.state.device,encoder:t,camera:s.camera,sceneColorView:this.state.sceneColorView,postProcessColorView:this.state.postProcessColorView,presentationColorView:a,depthView:this.state.mainDepthView,colorFormat:Er,width:this.state.width,height:this.state.height,presentationWidth:this.state.presentationWidth,presentationHeight:this.state.presentationHeight,linearClampSampler:this.state.linearClampSampler,nearestClampSampler:this.state.nearestClampSampler,comparisonSampler:this.state.shadowComparisonSampler,getColorView:e=>this.getColorTargetView(e),getTextureView:e=>this.getGraphTextureView(e),getExternalTexture:e=>{const t=this.textureManager.getTextureResource(e);return{view:t.view,sampler:t.sampler}},getColorFormat:e=>this.getColorTargetFormat(e),getShadowMapDebugInfo:()=>({directional:{view:this.state.directionalShadowView,size:this.state.directionalShadowTextureSize,layerCount:4,activeLightCount:s.lights.directionals.length,activeLayerCount:s.lights.directionals.length},point:{view:this.state.pointShadowArrayView,size:this.state.pointShadowTextureSize,layerCount:24,activeLightCount:s.lights.points.length,activeLayerCount:6*s.lights.points.length},spot:{view:this.state.spotShadowView,size:this.state.spotShadowTextureSize,layerCount:4,activeLightCount:s.lights.spots.length,activeLayerCount:s.lights.spots.length}}),getSceneLightingResources:()=>{if(!(this.state.lightBuffer&&this.state.directionalShadowView&&this.state.pointShadowArrayView&&this.state.spotShadowView))throw new Error("Renderer scene lighting resources are not initialized.");return{lightBuffer:this.state.lightBuffer,directionalShadowView:this.state.directionalShadowView,pointShadowView:this.state.pointShadowArrayView,spotShadowView:this.state.spotShadowView}}};return{addDirectionalShadowPass:()=>{e.addPass(new fr("DirectionalShadowPass",()=>{this.executeDirectionalShadowPass(t,n,s,o)},{writes:["directionalShadow"]}))},addPointShadowPass:()=>{s.lights.points.some(e=>e.castShadow)&&e.addPass(new fr("PointShadowPass",()=>{this.executePointShadowPass(t,n,s,o)},{writes:["pointShadow"]}))},addSpotShadowPass:()=>{s.lights.spots.some(e=>e.castShadow)&&e.addPass(new fr("SpotShadowPass",()=>{this.executeSpotShadowPass(t,n,s,o)},{writes:["spotShadow"]}))},addDepthPrepass:()=>{c=!0,this.getHiZOcclusionCullingActive()&&this.hasEnabledStaticDrawSets()&&e.addPass(new fr("TemporalStaticVisibilityPrepass",()=>{this.executeStaticVisibilityPasses(t,"prepass")},{reads:["hiz"],writes:["staticIndirectArgs"]})),e.addPass(new fr("DepthPrepass",()=>{this.executeDepthPrepass(t,r,s,o)},{writes:["mainDepth"]}))},addHiZPasses:()=>{this.getHiZOcclusionCullingActive()&&e.addPass(new fr("HiZPasses",()=>{this.executeHiZPasses(t)},{reads:["mainDepth"],writes:["hiz"]}))},addVisibilityPass:()=>{this.getHiZOcclusionCullingActive()&&(i||this.hasEnabledStaticDrawSets())&&(e.addPass(new fr("VisibilityPass",()=>{i&&this.executeVisibilityPass(t,i),this.executeStaticVisibilityPasses(t,"postpass")},{reads:["hiz"],writes:["indirectArgs","staticIndirectArgs"]})),this.hasEnabledStaticDrawSets()&&e.addPass(new fr("TemporalStaticDepthResolvePass",()=>{this.executeStaticTemporalDepthResolvePass(t)},{reads:["staticIndirectArgs"],writes:["mainDepth"]})))},defineColorTarget:(e,t={})=>{this.ensureColorTarget(e,t)},defineTextureTarget:(e,t={})=>{this.ensureTextureTarget(e,t)},addForwardPass:(n="sceneColor")=>{const i=!c,a=[...s.gpuOpaqueDraws,...s.directOpaqueDraws,...s.transparentDraws],h=d(a);if(l?.push({draws:a,colorTargetFormats:[this.getColorTargetFormat(n)],sampleCount:this.sampleCount}),h.includes("mainDepth")){if(!c)throw new Error("Materials that sample mainDepth require a depth prepass.");e.addPass(new fr("ForwardDepthSnapshotPass",()=>{this.state.mainDepthTexture&&this.state.sceneDepthSnapshotTexture&&t.copyTextureToTexture({texture:this.state.mainDepthTexture},{texture:this.state.sceneDepthSnapshotTexture},{width:this.state.width,height:this.state.height})},{reads:["mainDepth"],writes:["sceneDepthSnapshot"]})),u=!0}e.addPass(new fr("ForwardPass",()=>{this.executeForwardPass(t,n,this.getColorTargetView(n),r,s,o,i)},{reads:["directionalShadow","pointShadow","spotShadow","mainDepth","indirectArgs",...h.map(e=>"mainDepth"===e?"sceneDepthSnapshot":e)],writes:[n]})),this.getHiZOcclusionCullingActive()&&this.hasEnabledStaticDrawSets()&&e.addPass(new fr("TemporalHiZHistoryPass",()=>{this.executeHiZPasses(t,!0)},{reads:["mainDepth"],writes:["hiz"],dependsOn:["ForwardPass"]}))},addOpaquePass:(n="sceneColor")=>{const i=!c,a=[...s.gpuOpaqueDraws,...s.directOpaqueDraws],h=d(a);if(l?.push({draws:a,colorTargetFormats:[this.getColorTargetFormat(n)],sampleCount:this.sampleCount}),h.includes("mainDepth")){if(!c)throw new Error("Materials that sample mainDepth require a depth prepass.");e.addPass(new fr("OpaqueDepthSnapshotPass",()=>{this.state.mainDepthTexture&&this.state.sceneDepthSnapshotTexture&&t.copyTextureToTexture({texture:this.state.mainDepthTexture},{texture:this.state.sceneDepthSnapshotTexture},{width:this.state.width,height:this.state.height})},{reads:["mainDepth"],writes:["sceneDepthSnapshot"]})),u=!0}e.addPass(new fr("OpaquePass",()=>{this.executeForwardPass(t,n,this.getColorTargetView(n),r,s,o,i,"opaque")},{reads:["directionalShadow","pointShadow","spotShadow","mainDepth","indirectArgs",...h.map(e=>"mainDepth"===e?"sceneDepthSnapshot":e)],writes:[n]}))},addSceneTextureCopyPass:(r="sceneColor")=>{if(!(s.transparentDraws.some(e=>e.material.usesSceneTextures())||d(s.transparentDraws).includes("mainDepth")))return;const n=this.getColorTargetDimensions(r);if(n.width!==this.state.width||n.height!==this.state.height||this.getColorTargetFormat(r)!==Er)throw new Error("Scene texture snapshots currently require a full-resolution rgba16float source.");e.addPass(new fr("SceneTextureCopyPass",()=>{this.state.sceneColorSnapshotTexture&&this.state.sceneDepthSnapshotTexture&&this.state.mainDepthTexture&&(t.copyTextureToTexture({texture:this.getColorTargetTexture(r)},{texture:this.state.sceneColorSnapshotTexture},{width:this.state.width,height:this.state.height}),t.copyTextureToTexture({texture:this.state.mainDepthTexture},{texture:this.state.sceneDepthSnapshotTexture},{width:this.state.width,height:this.state.height}))},{reads:[r,"mainDepth"],writes:["sceneColorSnapshot","sceneDepthSnapshot"]})),u=!0},addLatePass:(n="sceneColor")=>{if(0===s.transparentDraws.length)return;l?.push({draws:s.transparentDraws,colorTargetFormats:[this.getColorTargetFormat(n)],sampleCount:1});const i=[n,"mainDepth",...d(s.transparentDraws)];s.transparentDraws.some(e=>e.material.usesSceneTextures())&&i.push("sceneColorSnapshot","sceneDepthSnapshot"),e.addPass(new fr("LatePass",()=>{this.executeForwardPass(t,n,this.getColorTargetView(n),r,s,o,!1,"late",!0,1)},{reads:i,writes:[n,"mainDepth"]}))},addHiZHistoryPass:(r="ForwardPass")=>{if(!this.getHiZOcclusionCullingActive()||!this.hasEnabledStaticDrawSets())return;const n="LatePass"===r&&0===s.transparentDraws.length?"OpaquePass":r;e.addPass(new fr("TemporalHiZHistoryPass",()=>{this.executeHiZPasses(t,!0)},{reads:["mainDepth"],writes:["hiz"],dependsOn:[n]}))},addMaterialPass:(n={})=>{const i="string"==typeof n.outputs?[n.outputs]:Array.from(n.outputs??["sceneColor"]),a=n.drawStage??"all",c="opaque"===a?[...s.gpuOpaqueDraws,...s.directOpaqueDraws]:"late"===a?s.transparentDraws:[...s.gpuOpaqueDraws,...s.directOpaqueDraws,...s.transparentDraws],u=n.objectFilter?c.filter(e=>n.objectFilter(e.sourceObject)||!0===e.sourceRanges?.some(e=>n.objectFilter(e.sourceObject))):c,d=e=>"function"==typeof n.overrideMaterial?n.overrideMaterial(e.material,null!==e.skinning):n.overrideMaterial,h=n.overrideMaterial?u.map(e=>({...e,material:d(e)})):u;l?.push({draws:h,colorTargetFormats:i.map(e=>this.getColorTargetFormat(e)),sampleCount:this.sampleCount}),e.addPass(new fr(n.name??"MaterialPass",()=>{this.executeMaterialPass(t,i,r,s,o,n)},{reads:["directionalShadow","pointShadow","spotShadow",...n.loadDepth?["mainDepth"]:[],...n.loadColor?i:[]],writes:this.sampleCount>1?i:[...i,"mainDepth"]}))},addCustomPass:t=>{e.addPass(new fr(t.name,()=>{t.execute(h)},{reads:t.reads,writes:t.writes,dependsOn:t.dependsOn}))},addPresentPass:(r="sceneColor")=>{e.addPass(new fr("PresentPass",()=>{const e=this.getColorTargetView(r);this.executePresentPass(t,e,a)},{reads:[r],writes:["mainColor"]}))}}}transparentDraws=[];opaqueBatches=new Map;acquireDrawCall(){const e=this.drawCallPoolCount;this.drawCallPoolCount+=1;let t=this.drawCallPool[e];return t||(t={geometry:null,geometryKey:{},geometryResource:null,material:null,customDepthMaterial:null,residentInstanceBinding:null,sourceObject:null,usesBatching:!1,geometryGroup:null,batchKey:"",batchHash:0,indexed:!1,wireframe:!1,start:0,count:0,transparent:!1,renderOrder:0,hasRenderCallbacks:!1,castShadow:!0,receiveShadow:!0,sortMaterialId:0,sortGeometryId:0,sortCustomDepthMaterialId:0,skinning:null,materialResource:null,instanceStart:0,instanceCount:0,boundsCenter:new mt,boundsRadius:0,sortDepth:0,transparentSortGroup:0,transparentSortOrder:0},this.drawCallPool[e]=t),t}acquireOpaqueBatchBuilder(){const e=this.opaqueBatchPoolCount;this.opaqueBatchPoolCount+=1;let t=this.opaqueBatchPool[e];return t||(t={template:null,totalInstanceCount:0,rangePairCount:0,firstInstanceStart:0,firstInstanceCount:0,sourceRanges:[],boundsMin:new mt,boundsMax:new mt},this.opaqueBatchPool[e]=t),t}populateDrawCall(e,t,r,n,i,a,s,o){const l=t.wireframe;l&&this.ensureWireframeIndex(t.geometry,t.geometryResource);const c=t.sourceObject?Boolean(t.sourceObject.receiveShadow):t.receiveShadow;return this.shouldInvalidateDrawMaterialResource(e,t.material,c,t.usesBatching,null)&&(e.materialResource=null),e.geometry=t.geometry,e.geometryKey=l?t.geometryResource.wireframeIndex:t.geometryKey,e.geometryResource=t.geometryResource,e.material=t.material,e.customDepthMaterial=t.customDepthMaterial,e.residentInstanceBinding=t.residentInstanceBinding,e.sourceObject=t.sourceObject,e.usesBatching=t.usesBatching,e.geometryGroup=t.geometryGroup,e.batchKey=t.batchKey,e.batchHash=t.batchHash,e.indexed=l||t.indexed,e.wireframe=l,e.start=l?2*t.start:t.start,e.count=l?2*t.count:t.count,e.transparent=t.transparent,e.renderOrder=t.sourceObject?.renderOrder??t.renderOrder,e.hasRenderCallbacks=this.hasRenderCallbacks(t.sourceObject),e.castShadow=t.sourceObject?Boolean(t.sourceObject.castShadow):t.castShadow,e.receiveShadow=c,e.sortMaterialId=t.sortMaterialId,e.sortGeometryId=t.sortGeometryId,e.sortCustomDepthMaterialId=t.sortCustomDepthMaterialId,e.skinning=null,e.instanceStart=r,e.instanceCount=n,e.boundsCenter.set(i,a,s),e.boundsRadius=o,e.sortDepth=0,e.transparentSortGroup=0,e.transparentSortOrder=0,e.sourceRanges=void 0,e}populateDynamicDrawCall(e,t,r,n,i,a,s,o,l,c,u,d,h,p,f,m,g,x,v,w,b,y,S,C,P,M,B,D,T=null){const I=!0===o?.isBatchedMesh,G=i.wireframe&&"triangle-list"===i.primitiveTopology;return G&&this.ensureWireframeIndex(t,n),this.shouldInvalidateDrawMaterialResource(e,i,v,I,T)&&(e.materialResource=null),e.geometry=t,e.geometryKey=G?n.wireframeIndex:r,e.geometryResource=n,e.material=i,e.customDepthMaterial=a,e.residentInstanceBinding=s,e.sourceObject=o,e.usesBatching=I,e.geometryGroup=l,e.batchKey=c,e.batchHash=u,e.indexed=G||d,e.wireframe=G,e.start=G?2*h:h,e.count=G?2*p:p,e.transparent=f,e.renderOrder=m,e.hasRenderCallbacks=g,e.castShadow=x,e.receiveShadow=v,e.sortMaterialId=w,e.sortGeometryId=b,e.sortCustomDepthMaterialId=y,e.skinning=T,e.instanceStart=S,e.instanceCount=C,e.boundsCenter.set(P,M,B),e.boundsRadius=D,e.sortDepth=0,e.transparentSortGroup=0,e.transparentSortOrder=0,e.sourceRanges=void 0,e}pushOpaqueDrawTemplate(e,t,r,n,i,a,s){const o=e.batchHash,l=this.opaqueBatches.get(o);let c=null;if(l)if(Array.isArray(l))for(let t=0;t<l.length;t+=1){const r=l[t];if(In(r.template,e)){c=r;break}}else In(l.template,e)&&(c=l);if(c){if(c.totalInstanceCount+=r,1===c.rangePairCount){const e=c.sourceRanges;e.length=4,e[0]=c.firstInstanceStart,e[1]=c.firstInstanceCount,e[2]=t,e[3]=r}else{const e=c.sourceRanges,n=2*c.rangePairCount;e[n]=t,e[n+1]=r}c.rangePairCount+=1;const e=c.boundsMin,o=c.boundsMax,l=n-s,u=i-s,d=a-s,h=n+s,p=i+s,f=a+s;return l<e.x&&(e.x=l),u<e.y&&(e.y=u),d<e.z&&(e.z=d),h>o.x&&(o.x=h),p>o.y&&(o.y=p),void(f>o.z&&(o.z=f))}const u=this.acquireOpaqueBatchBuilder();u.template=e,u.totalInstanceCount=r,u.rangePairCount=1,u.firstInstanceStart=t,u.firstInstanceCount=r,u.sourceRanges.length=0,u.boundsMin.set(n-s,i-s,a-s),u.boundsMax.set(n+s,i+s,a+s),l?Array.isArray(l)?l.push(u):this.opaqueBatches.set(o,[l,u]):this.opaqueBatches.set(o,u)}pushDraw(e){e.transparent?this.transparentDraws.push(e):e.skinning||e.hasRenderCallbacks&&e.residentInstanceBinding?this.directOpaqueDrawsScratch.push(e):e.residentInstanceBinding?this.residentOpaqueDrawsScratch.push(e):this.stagedOpaqueDrawsScratch.push(e)}getToonOutlineParameters(e){if(!e||!e.visible||!0===e.wireframe||!e.depthTest)return null;const t=e.userData?.outlineParameters;return t&&!1!==t.visible?t:null}getToonOutlineMaterial(e,t){const r=this.getToonOutlineParameters(e);if(!r)return null;let n=this.toonOutlineMaterialCache.get(e);if(!n){const t=t=>new kt({vertexShader:t?"\nstruct VertexInput {\n @location(0) position: vec3<f32>,\n @location(1) normal: vec3<f32>,\n @location(4) skinIndex: vec4<u32>,\n @location(5) skinWeight: vec4<f32>,\n @builtin(instance_index) instanceIndex: u32,\n};\n\nstruct VertexOutput {\n @builtin(position) position: vec4<f32>,\n};\n\n@vertex\nfn vsMain(input: VertexInput) -> VertexOutput {\n let localPosition = rendererSkinPosition(input.position, input.skinIndex, input.skinWeight);\n let localNormal = rendererSkinNormal(input.normal, input.skinIndex, input.skinWeight);\n let worldPosition = rendererWorldPosition(localPosition, input.instanceIndex);\n let viewPosition = rendererCamera.view * worldPosition;\n let worldNormal = rendererWorldNormal(localNormal, input.instanceIndex);\n let viewNormal = normalize((rendererCamera.view * vec4(worldNormal, 0.0)).xyz);\n let distanceScale = sqrt(max(length(viewPosition.xyz), 0.0001)) * 0.5;\n let displaced = viewPosition.xyz + viewNormal * materialUniforms.outlineThickness * distanceScale;\n return VertexOutput(rendererCamera.projection * vec4(displaced, 1.0));\n}\n":"\nstruct VertexInput {\n @location(0) position: vec3<f32>,\n @location(1) normal: vec3<f32>,\n @builtin(instance_index) instanceIndex: u32,\n};\n\nstruct VertexOutput {\n @builtin(position) position: vec4<f32>,\n};\n\n@vertex\nfn vsMain(input: VertexInput) -> VertexOutput {\n let worldPosition = rendererWorldPosition(input.position, input.instanceIndex);\n let viewPosition = rendererCamera.view * worldPosition;\n let worldNormal = rendererWorldNormal(input.normal, input.instanceIndex);\n let viewNormal = normalize((rendererCamera.view * vec4(worldNormal, 0.0)).xyz);\n let distanceScale = sqrt(max(length(viewPosition.xyz), 0.0001)) * 0.5;\n let displaced = viewPosition.xyz + viewNormal * materialUniforms.outlineThickness * distanceScale;\n return VertexOutput(rendererCamera.projection * vec4(displaced, 1.0));\n}\n",fragmentShader:"\n@fragment\nfn fsMain() -> @location(0) vec4<f32> {\n return vec4(materialUniforms.outlineColor, materialUniforms.outlineAlpha);\n}\n",vertexAttributes:t?Oi:[{name:"position",shaderLocation:0,format:"float32x3"},{name:"normal",shaderLocation:1,format:"float32x3",defaultValue:[0,0,1]}],uniforms:{outlineThickness:r.thickness??.003,outlineColor:(new nt).fromArray(r.color??[0,0,0]),outlineAlpha:r.alpha??e.opacity},side:et,depthTest:!0,depthWrite:!0,transparent:!0});n={regular:t(!1),skinned:t(!0)},this.toonOutlineMaterialCache.set(e,n)}const i=t?n.skinned:n.regular;return i.uniforms.outlineThickness.value=r.thickness??.003,i.uniforms.outlineColor.value.fromArray(r.color??[0,0,0]),i.uniforms.outlineAlpha.value=r.alpha??e.opacity,i}pushToonOutlineDraw(e,t){const r=t?this.getToonOutlineMaterial(t,null!==e.skinning):null;if(!r||e.usesBatching)return;const n=this.populateDynamicDrawCall(this.acquireDrawCall(),e.geometry,e.geometryKey,e.geometryResource,r,null,e.residentInstanceBinding,e.sourceObject,e.geometryGroup,`toon-outline:${e.batchKey}`,Pn(Sn(r),Sn(e.geometryKey),e.indexed,e.start,e.count,0),e.indexed,e.start,e.count,!0,e.renderOrder,!1,!1,!1,Sn(r),e.sortGeometryId,0,e.instanceStart,e.instanceCount,e.boundsCenter.x,e.boundsCenter.y,e.boundsCenter.z,e.boundsRadius,e.skinning);this.transparentDraws.push(n)}updateTransparentDrawSortDepths(e,t,r){for(let n=0;n<e.length;n+=1){const i=e[n];0===i.transparentSortGroup&&(i.sortDepth=(i.boundsCenter.x-t.x)*r.x+(i.boundsCenter.y-t.y)*r.y+(i.boundsCenter.z-t.z)*r.z)}}extractScene(e,t){this.extractionVersion+=1,this.drawCallPoolCount=0,this.opaqueBatchPoolCount=0;this.opaqueBatches.clear();const r=this.transparentDraws;r.length=0;const n=this.residentInstanceUploadsScratch;n.length=0;const i=this.sourceInstanceDataScratch;i.reset();const a=this.gpuOpaqueDrawsScratch;a.length=0;const s=this.directOpaqueDrawsScratch;s.length=0;const o=this.stagedOpaqueDrawsScratch;o.length=0;const l=this.residentOpaqueDrawsScratch;l.length=0;const c=this.opaqueInstanceDataScratch;c.reset();const u=this.finalInstanceDataScratch;u.reset();const d=this.extractedAmbientScratch;d.set(0,0,0,0);let h=null;const p=this.activeDirectionalLightsScratch,f=this.activePointLightsScratch,m=this.activeSpotLightsScratch;p.length=0,f.length=0,m.length=0;const g=this.extractedBoundsMinScratch;g.set(1/0,1/0,1/0);const x=this.extractedBoundsMaxScratch;x.set(-1/0,-1/0,-1/0),function(e,t){const r=e.elements,n=r[0],i=r[1],a=r[2],s=r[3],o=r[4],l=r[5],c=r[6],u=r[7],d=r[8],h=r[9],p=r[10],f=r[11],m=r[12],g=r[13],x=r[14],v=r[15];An(t,0,s-n,u-o,f-d,v-m),An(t,4,s+n,u+o,f+d,v+m),An(t,8,s+i,u+l,f+h,v+g),An(t,12,s-i,u-l,f-h,v-g),An(t,16,s-a,u-c,f-p,v-x),An(t,20,a,c,p,x)}(Vn(t,this.cameraViewProjScratch),this.cameraFrustumPlanesScratch);const v=this.transparentSortCameraPositionScratch,w=this.transparentSortCameraForwardScratch;t.getWorldPosition(v),t.getWorldDirection(w);const b=this.isSphereVisibleScratch,y=this.updateExtractedBoundsFromMatrixScratch,S=this.objectTraversalStackScratch;S.length=0,S.push(e);for(let e=this.csmCascadeLights.length-1;e>=0;e-=1)S.push(this.csmCascadeLights[e]);for(;S.length>0;){const e=S.pop();if(!e.visible)continue;const r=0!==(e.layers.mask&t.layers.mask);if(e.isAmbientLight){if(r){const t=e;d.x+=t.color.r*t.intensity,d.y+=t.color.g*t.intensity,d.z+=t.color.b*t.intensity,d.w=1}}else if(e.isHemisphereLight){if(r&&null==h){const t=e,r=this.extractedHemisphereScratch;Hr.setFromMatrixPosition(t.matrixWorld),r.direction.copy(Hr),r.direction.lengthSq()<=1e-10?r.direction.set(0,1,0):r.direction.normalize(),r.skyColor.set(t.color.r,t.color.g,t.color.b),r.groundColor.set(t.groundColor.r,t.groundColor.g,t.groundColor.b),r.intensity=t.intensity,h=r}}else if(e.isDirectionalLight){if(r&&p.length<4&&!this.hasExtractedDirectionalLight(p,e)){const t=e,r=t.shadow,n=r.camera,i=this.extractedDirectionalLightsScratch[p.length];i.sourceLight=t,t.target.matrixWorldAutoUpdate&&t.target.updateMatrixWorld(!0),Hr.setFromMatrixPosition(t.matrixWorld),Kr.setFromMatrixPosition(t.target.matrixWorld),i.position.copy(Hr),i.target.copy(Kr),i.direction.copy(Kr).sub(Hr).normalize(),i.color.set(t.color.r,t.color.g,t.color.b),i.intensity=t.intensity,i.castShadow=t.castShadow,i.shadowBias=r.bias,i.shadowNormalBias=r.normalBias,i.shadowRadius=r.radius,i.shadowIntensity=r.intensity,i.shadowMapSize=Math.max(1,r.mapSize.width,r.mapSize.height),i.shadowCameraLeft=n.left,i.shadowCameraRight=n.right,i.shadowCameraTop=n.top,i.shadowCameraBottom=n.bottom,i.shadowCameraNear=n.near,i.shadowCameraFar=n.far,p.push(i)}}else if(e.isPointLight){if(r&&f.length<4){const t=e,r=t.shadow,n=r.camera,i=this.extractedPointLightsScratch[f.length];Hr.setFromMatrixPosition(t.matrixWorld),i.position.copy(Hr),i.color.set(t.color.r,t.color.g,t.color.b),i.intensity=t.intensity,i.range=t.distance>0?t.distance:Math.max(n.far,25),i.castShadow=t.castShadow,i.shadowBias=r.bias,i.shadowNormalBias=r.normalBias,i.shadowRadius=r.radius,i.shadowIntensity=r.intensity,i.shadowMapSize=Math.max(1,r.mapSize.width,r.mapSize.height),i.shadowCameraNear=n.near,i.shadowCameraFar=t.distance>0?t.distance:n.far,f.push(i)}}else if(e.isSpotLight){if(r&&m.length<4){const t=e,r=t.shadow,n=r.camera,i=this.extractedSpotLightsScratch[m.length];t.target.matrixWorldAutoUpdate&&t.target.updateMatrixWorld(!0),Hr.setFromMatrixPosition(t.matrixWorld),Kr.setFromMatrixPosition(t.target.matrixWorld),i.position.copy(Hr),i.direction.copy(Kr).sub(Hr).normalize(),i.color.set(t.color.r,t.color.g,t.color.b),i.intensity=t.intensity,i.range=t.distance>0?t.distance:n.far,i.angle=t.angle,i.penumbra=t.penumbra,i.decay=t.decay,i.castShadow=t.castShadow,i.shadowBias=r.bias,i.shadowNormalBias=r.normalBias,i.shadowRadius=r.radius,i.shadowIntensity=r.intensity,i.shadowMapSize=Math.max(1,r.mapSize.width,r.mapSize.height),i.shadowCameraNear=n.near,i.shadowCameraFar=t.distance>0?t.distance:n.far,i.shadowCameraFov=n.fov,m.push(i)}}else r&&e.isBatchedMesh?this.collectBatchedMesh(e,i,y,b,t,v,w):r&&e.isInstancedMesh?this.collectInstancedMesh(e,i,y,b):r&&e.isSkinnedMesh?this.collectSkinnedMesh(e,i,y,b):r&&e.isLine?this.collectLine(e,i,y,b):r&&e.isSprite?this.collectSprite(e,i,y,b):r&&e.isMesh&&this.collectMesh(e,i,y,b);const n=e.children;for(let e=n.length-1;e>=0;e-=1)S.push(n[e])}if(this.csmCascadeLights.length>0){const e=new Map;for(let t=0;t<this.csmCascadeLights.length;t+=1)e.set(this.csmCascadeLights[t],t);p.sort((t,r)=>((null==t.sourceLight?void 0:e.get(t.sourceLight))??4)-((null==r.sourceLight?void 0:e.get(r.sourceLight))??4))}const C=s.length;this.updateTransparentDrawSortDepths(r,v,w),r.sort(Bn),Number.isFinite(g.x)||(g.set(-6,-6,-6),x.set(6,6,6)),o.sort(Mn);for(let e=0;e<o.length;){const t=o[e],r=c.instanceCount;c.appendRange(i,t.instanceStart,t.instanceCount);let n,l=t.instanceCount,u=t.boundsCenter.x-t.boundsRadius,d=t.boundsCenter.y-t.boundsRadius,h=t.boundsCenter.z-t.boundsRadius,p=t.boundsCenter.x+t.boundsRadius,f=t.boundsCenter.y+t.boundsRadius,m=t.boundsCenter.z+t.boundsRadius,g=e+1;for(;this.dynamicBatchingEnabled&&g<o.length&&Gn(t,o[g]);){const e=o[g];c.appendRange(i,e.instanceStart,e.instanceCount),n??=[{sourceObject:t.sourceObject,instanceStart:r,instanceCount:t.instanceCount}],n.push({sourceObject:e.sourceObject,instanceStart:r+l,instanceCount:e.instanceCount}),l+=e.instanceCount;const a=e.boundsCenter.x-e.boundsRadius,s=e.boundsCenter.y-e.boundsRadius,x=e.boundsCenter.z-e.boundsRadius,v=e.boundsCenter.x+e.boundsRadius,w=e.boundsCenter.y+e.boundsRadius,b=e.boundsCenter.z+e.boundsRadius;a<u&&(u=a),s<d&&(d=s),x<h&&(h=x),v>p&&(p=v),w>f&&(f=w),b>m&&(m=b),g+=1}const x=.5*(u+p),v=.5*(d+f),w=.5*(h+m),b=p-x,y=f-v,S=m-w;t.instanceStart=r,t.instanceCount=l,t.sourceRanges=n,t.boundsCenter.set(x,v,w),t.boundsRadius=Math.sqrt(b*b+y*y+S*S),t.indexed&&!t.hasRenderCallbacks?a.push(t):s.push(t),e=g}l.sort(Mn);for(let e=0;e<l.length;e+=1){const t=l[e];t.indexed&&!t.hasRenderCallbacks?a.push(t):s.push(t)}u.appendBuilder(c);for(let e=0;e<C;e+=1){const t=s[e];if(t.residentInstanceBinding)continue;const r=u.instanceCount;u.appendRange(i,t.instanceStart,t.instanceCount),t.instanceStart=r}a.sort(Mn),s.sort(Mn);for(let e=0;e<r.length;e+=1){const t=r[e];if(t.residentInstanceBinding)continue;const n=u.instanceCount;u.appendRange(i,t.instanceStart,t.instanceCount),t.instanceStart=n}const P=this.extractedLightsScratch;P.hemisphere=h,P.directional=p[0]??null,P.point=f[0]??null,P.spot=m[0]??null;const M=this.extractedFrameScratch;return M.scene=e,M.camera=t,M.transparentDraws=r,M.instanceData=u,M.residentInstanceUploads=n,M}collectLine(e,t,r,n){if(Array.isArray(e.material)||!e.geometry.getAttribute("position"))return;const i=e.geometry,a=e.material;if(!1===a.visible)return;if((!0===a.isLineBasicMaterial||!0===a.isMeshBasicMaterial)&&!0!==a.isLineMaterial){const s=e.isLineSegments?"line-list":"line-strip",o=this.resolveLineBasicMaterial(a,s),l=`${Qr(i)}:${s}`;let c=this.lineProxyCache.get(e);c&&c.signature===l||(c={signature:l,mesh:new ct(i,o)},this.lineProxyCache.set(e,c));const u=c.mesh;return u.material=o,u.matrixWorld.copy(e.matrixWorld),u.frustumCulled=e.frustumCulled,u.renderOrder=e.renderOrder,u.castShadow=!1,u.receiveShadow=!1,u.onBeforeRender=(...t)=>e.onBeforeRender(...t),void this.collectMesh(u,t,r,n)}const s=Qr(i);let o=this.lineProxyCache.get(e);if(!o||o.signature!==s){const t=i.getAttribute("position"),r=i.index,n=r?.count??t.count,a=Math.max(0,Math.min(n,i.drawRange.start)),l=Number.isFinite(i.drawRange.count)?i.drawRange.count:n-a,c=Math.max(a,Math.min(n,a+l)),u=e.isLineSegments?2:1,d=[],h=[],p=e=>r?r.getX(e):e;for(let e=a;e+1<c;e+=u){const r=p(e),n=p(e+1);d.push(t.getX(r),t.getY(r),t.getZ(r)),h.push(t.getX(n),t.getY(n),t.getZ(n))}const f=new rt;f.setIndex([0,2,1,2,3,1,2,4,3,4,5,3,4,6,5,6,7,5]),f.setAttribute("position",new tt(new Float32Array([-1,2,0,1,2,0,-1,1,0,1,1,0,-1,0,0,1,0,0,-1,-1,0,1,-1,0]),3)),f.setAttribute("instanceStart",new st(new Float32Array(d),3)),f.setAttribute("instanceEnd",new st(new Float32Array(h),3)),f.instanceCount=d.length/3;const m=Fn(i);f.boundingSphere=new ht(m.center.clone(),m.radius),o={signature:s,mesh:new ct(f,e.material)},this.lineProxyCache.set(e,o)}const l=o.mesh;l.matrixWorld.copy(e.matrixWorld),l.frustumCulled=e.frustumCulled,l.renderOrder=e.renderOrder,l.castShadow=e.castShadow??!1,l.receiveShadow=e.receiveShadow??!1,l.onBeforeRender=(...t)=>e.onBeforeRender(...t),this.collectMesh(l,t,r,n)}collectSprite(e,t,r,n){let i=this.spriteProxyCache.get(e);if(!i){const t=e.geometry.clone();i={mesh:new ct(t,e.material),centerX:Number.NaN,centerY:Number.NaN},this.spriteProxyCache.set(e,i)}if(i.centerX!==e.center.x||i.centerY!==e.center.y){const t=i.mesh.geometry.getAttribute("position"),r=e.geometry.getAttribute("position");for(let n=0;n<t.count;n+=1)t.setXYZ(n,r.getX(n)+.5-e.center.x,r.getY(n)+.5-e.center.y,r.getZ(n));t.needsUpdate=!0,i.mesh.geometry.computeBoundingSphere(),i.centerX=e.center.x,i.centerY=e.center.y}const a=i.mesh;a.material=e.material,a.matrixWorld.copy(e.matrixWorld),a.frustumCulled=e.frustumCulled,a.renderOrder=e.renderOrder,a.castShadow=e.castShadow,a.receiveShadow=e.receiveShadow,a.onBeforeRender=(...t)=>e.onBeforeRender(...t),a.onAfterRender=(...t)=>e.onAfterRender(...t),this.collectMesh(a,t,r,n)}hasExtractedDirectionalLight(e,t){for(let r=0;r<e.length;r+=1)if(e[r].sourceLight===t)return!0;return!1}collectMesh(e,t,r,n){const i=e.geometry;if(void 0===i.attributes.position)return;const a=e.material,s=Array.isArray(a);if(!s&&!1===a.visible||s&&a.every(e=>!1===e.visible))return;const o=this.resolvedMeshMaterialsScratch;o.length=0;let l=null;if(s)for(let e=0;e<a.length;e+=1)o[e]=this.resolveMaterial(a[e]);else{if(!a.visible)return;l=this.resolveMaterial(a)}const c=jn(e),u=this.meshExtractionCache.get(e),d=u&&u.customDepthMaterial===c&&u.geometryResource.lastValidatedExtractionVersion===this.extractionVersion&&(!s&&u.material===a&&u.resolvedMaterial===l||s&&null!==u.materials&&null!==u.resolvedMaterials&&an(u.materials,a)&&ln(u.resolvedMaterials,o))?u:this.getMeshExtractionCacheEntry(e,a,l,o,c,this.getGeometryResource(i)),h=d.templates.length;if(0===h)return;const p=e.matrixWorld.elements,f=d.localBoundsCenter,m=f.x,g=f.y,x=f.z,v=p[0]*m+p[4]*g+p[8]*x+p[12],w=p[1]*m+p[5]*g+p[9]*x+p[13],b=p[2]*m+p[6]*g+p[10]*x+p[14],y=p[0]*p[0]+p[1]*p[1]+p[2]*p[2],S=p[4]*p[4]+p[5]*p[5]+p[6]*p[6],C=p[8]*p[8]+p[9]*p[9]+p[10]*p[10],P=d.localBoundsRadius*Math.sqrt(Math.max(y,S,C,1e-10));if(!n(v,w,b,P,e.frustumCulled))return;const M=function(e){const t=e.attributes;let r=!1,n=1/0;for(const e in t){const i=t[e];!0!==i.isInstancedBufferAttribute&&!0!==i.data?.isInstancedInterleavedBuffer||(r=!0,i.count<n&&(n=i.count))}if(!r)return 1;const i=e.instanceCount;return Number.isFinite(i)?Math.max(0,Math.floor(i)):Math.max(0,n)}(i);let B=0;for(let e=0;e<M;e+=1){const r=wn(t,p,1,1,1,1);0===e&&(B=r)}r(p);for(let e=0;e<h;e+=1){const t=d.templates[e],r=this.populateDrawCall(this.acquireDrawCall(),t,B,M,v,w,b,P);t.transparent?this.transparentDraws.push(r):this.pushDraw(r);const n=s?a[t.geometryGroup?.materialIndex??0]:a;this.pushToonOutlineDraw(r,n)}}prepareSceneForCompilation(e,t,r){if(!(this.state.initialized&&this.state.device&&this.state.context&&this.state.mainDepthView&&this.state.sceneColorView&&this.state.postProcessColorView&&this.state.cameraBuffer&&this.state.lightBuffer&&this.state.shadowCameraBuffer&&this.state.sceneBindGroupLayout&&this.state.shadowBindGroupLayout&&this.state.shadowComparisonSampler&&this.state.linearClampSampler&&this.state.nearestClampSampler&&this.state.visibilityParamsBuffer&&this.state.directionalShadowView&&this.state.pointShadowArrayView&&this.state.spotShadowView&&this.state.hizCopyKernel&&this.state.hizReduceKernel&&this.state.visibilityKernel&&this.state.presentPipeline))throw new Error("WebGpuRenderer.initialize() must complete before compile().");e.matrixWorldAutoUpdate&&e.updateMatrixWorld(),null===t.parent&&t.matrixWorldAutoUpdate&&t.updateMatrixWorld();const n=this.extractScene(e,t);this.ensureShadowTextureSizes(n),this.uploadInstanceData(n.instanceData),this.uploadResidentInstanceData(n.residentInstanceUploads),this.uploadDrawMetadata(this.getHiZOcclusionCullingActive()?n.gpuOpaqueDraws:[]),this.updateCameraUniforms(t,e),this.updateLightUniforms(n);const i=this.compileDrawScratch;if(i.length=0,i.push(...n.gpuOpaqueDraws,...n.directOpaqueDraws,...n.transparentDraws),r){const e=[];this.renderGraph.reset();const t=this.state.device.createCommandEncoder({label:"renderer-graph-compilation-encoder"}),r=this.createGraphBuilderContext(this.renderGraph,t,this.getSharedSceneBindGroup(),this.getSharedShadowBindGroup(),null,this.state.sceneColorView,n,{drawCallCount:0,triangleCount:0},e);return this.graphBuilder(this.renderGraph,r),Promise.all([...e.map(e=>this.compileDrawMaterialsAsync(e.draws,e.colorTargetFormats,e.sampleCount)),...e.map(e=>this.compileStaticDrawMaterialsAsync(e.colorTargetFormats,e.sampleCount))]).then(async()=>{await(this.state.device?.queue.onSubmittedWorkDone())})}this.compileDrawMaterials(i)}collectInstancedMesh(e,t,r,n){if(void 0===e.geometry?.getAttribute("position"))return;const i=e.material;if(!1===i.visible)return;const a=this.instancedMeshExtractionCache.get(e),s=!0===e.userData.webGpuCacheMaterial&&a?.sourceMaterial===i&&a.sourceMaterialVersion===i.version&&a.material!==this.fallbackMaterial?a.material:this.resolveMaterial(i);if(!s)return;const o=jn(e),l=this.getGeometryResource(e.geometry),c=this.getInstancedMeshExtractionCacheEntry(e,s,o,l),u=e.instanceMatrix.array,d=e.instanceMatrix.version,h=e.instanceColor?.array,p=e.instanceColor?.itemSize??0,f=e.instanceColor?.version??-1,m=c.cacheValid&&c.cachedCount===e.count&&c.cachedInstanceMatrixVersion===d&&c.cachedInstanceColorVersion===f&&Ln(c.cachedMatrixWorld,e.matrixWorld.elements),g=zn(e.matrixWorld.elements),x=g&&!e.frustumCulled;if(!m){const t=c.cachedInstanceMatrixVersion!==d||c.cachedCount!==e.count,r=c.cachedInstanceColorVersion!==f||c.cachedCount!==e.count;if(x){const n=e.matrixWorld.elements,i=n[12]??0,a=n[13]??0,s=n[14]??0;c.cachedDrawBoundsCenter.set(i,a,s),c.cachedDrawBoundsRadius=0,c.cachedBoundsMin.set(i,a,s),c.cachedBoundsMax.set(i,a,s),c.cachedInstanceMatrixVersion=d,c.cachedInstanceColorVersion=f,c.cachedCount=e.count,c.cachedDefaultColorData=null,Rn(e.matrixWorld.elements,c.cachedMatrixWorld),c.residentBufferDirty||=t,c.residentColorBufferDirty||=r,c.cacheValid=!0}else{const t=c.cachedInstanceData.beginWriteInstances(e.count),r=c.cachedBoundsMin,n=c.cachedBoundsMax;r.set(1/0,1/0,1/0),n.set(-1/0,-1/0,-1/0);const i=c.localBoundsCenter,a=c.localBoundsRadius,s=e.matrixWorld.elements,o=zn(s),l=i.x,m=i.y,g=i.z,x=s[0],v=s[4],w=s[8],b=s[12],y=s[1],S=s[5],C=s[9],P=s[13],M=s[2],B=s[6],D=s[10],T=s[14],I=s[3],G=s[7],R=s[11],L=s[15];for(let i=0;i<e.count;i+=1){const e=16*i,s=i*Ur,c=u[e+0]??0,d=u[e+1]??0,f=u[e+2]??0,z=u[e+3]??0,U=u[e+4]??0,V=u[e+5]??0,A=u[e+6]??0,F=u[e+7]??0,E=u[e+8]??0,k=u[e+9]??0,O=u[e+10]??0,$=u[e+11]??0,j=u[e+12]??0,N=u[e+13]??0,W=u[e+14]??0,_=u[e+15]??0;let q,H,K,Z,Y,X,J,Q,ee,te,re,ne,ie,ae,se,oe;o?(q=c,H=d,K=f,Z=z,Y=U,X=V,J=A,Q=F,ee=E,te=k,re=O,ne=$,ie=j,ae=N,se=W,oe=_):(q=x*c+v*d+w*f+b*z,Y=x*U+v*V+w*A+b*F,ee=x*E+v*k+w*O+b*$,ie=x*j+v*N+w*W+b*_,H=y*c+S*d+C*f+P*z,X=y*U+S*V+C*A+P*F,te=y*E+S*k+C*O+P*$,ae=y*j+S*N+C*W+P*_,K=M*c+B*d+D*f+T*z,J=M*U+B*V+D*A+T*F,re=M*E+B*k+D*O+T*$,se=M*j+B*N+D*W+T*_,Z=I*c+G*d+R*f+L*z,Q=I*U+G*V+R*A+L*F,ne=I*E+G*k+R*O+L*$,oe=I*j+G*N+R*W+L*_),t[s+0]=q,t[s+1]=H,t[s+2]=K,t[s+3]=Z,t[s+4]=Y,t[s+5]=X,t[s+6]=J,t[s+7]=Q,t[s+8]=ee,t[s+9]=te,t[s+10]=re,t[s+11]=ne,t[s+12]=ie,t[s+13]=ae,t[s+14]=se,t[s+15]=oe;const le=i*p;t[s+16]=h?h[le+0]??1:1,t[s+17]=h?h[le+1]??1:1,t[s+18]=h?h[le+2]??1:1,t[s+19]=h&&p>=4?h[le+3]??1:1,t[s+20]=i,t[s+21]=0,t[s+22]=0,t[s+23]=0;const ce=q*l+Y*m+ee*g+ie,ue=H*l+X*m+te*g+ae,de=K*l+J*m+re*g+se,he=Math.sqrt(q*q+H*H+K*K),pe=Math.sqrt(Y*Y+X*X+J*J),fe=Math.sqrt(ee*ee+te*te+re*re),me=a*Math.max(he,pe,fe,1e-5);kn(r,n,Hr.set(ce,ue,de),me)}c.cachedDrawBoundsCenter.copy(r).add(n).multiplyScalar(.5);const z=n.x-c.cachedDrawBoundsCenter.x,U=n.y-c.cachedDrawBoundsCenter.y,V=n.z-c.cachedDrawBoundsCenter.z;c.cachedDrawBoundsRadius=Math.sqrt(z*z+U*U+V*V),c.cachedInstanceMatrixVersion=d,c.cachedInstanceColorVersion=f,c.cachedCount=e.count,c.cachedDefaultColorData=null,Rn(e.matrixWorld.elements,c.cachedMatrixWorld),c.residentBufferDirty=!0,c.residentColorBufferDirty=!0,c.cacheValid=!0}}if(!n(c.cachedDrawBoundsCenter.x,c.cachedDrawBoundsCenter.y,c.cachedDrawBoundsCenter.z,c.cachedDrawBoundsRadius,e.frustumCulled))return;c.residentInstanceBinding&&c.residentInstanceBinding.mode!==(g?"instanced-direct":"packed")&&(c.residentInstanceBinding.mode=g?"instanced-direct":"packed",c.residentInstanceBinding.sceneBindGroup=null,c.residentInstanceBinding.shadowBindGroup=null,c.residentInstanceBinding.shadowBindGroups.clear(),c.residentInstanceBinding.sceneBindGroupVersion=0,c.residentInstanceBinding.shadowBindGroupVersion=0,c.residentBufferDirty=!0,c.residentColorBufferDirty=!0),(c.residentBufferDirty||c.residentColorBufferDirty||!c.residentInstanceBinding)&&this.residentInstanceUploadsScratch.push(c),Un(this.extractedBoundsMinScratch,this.extractedBoundsMaxScratch,c.cachedBoundsMin,c.cachedBoundsMax);const v=this.populateDynamicDrawCall(this.acquireDrawCall(),e.geometry,e.geometry,l,s,o,c.residentInstanceBinding,e,null,c.batchKey,c.batchHash,c.indexed,c.drawRangeStart,c.drawRangeCount,s.transparent||s.requiresLatePass(),e.renderOrder,this.hasRenderCallbacks(e),e.castShadow,e.receiveShadow,c.sortMaterialId,c.sortGeometryId,c.sortCustomDepthMaterialId,0,e.count,c.cachedDrawBoundsCenter.x,c.cachedDrawBoundsCenter.y,c.cachedDrawBoundsCenter.z,c.cachedDrawBoundsRadius);x&&!v.transparent?this.directOpaqueDrawsScratch.push(v):this.pushDraw(v)}collectSkinnedMesh(e,t,r,n){if(void 0===e.geometry?.getAttribute("position"))return;const i=e.boundingSphere;if(e.frustumCulled&&null!==i){const t=i.center,r=e.matrixWorld.elements;if(!n(r[0]*t.x+r[4]*t.y+r[8]*t.z+r[12],r[1]*t.x+r[5]*t.y+r[9]*t.z+r[13],r[2]*t.x+r[6]*t.y+r[10]*t.z+r[14],i.radius*En(e.matrixWorld),!0))return}const a=Array.isArray(e.material)?e.material:[e.material],s=jn(e),o=null!==e.geometry.index,l=this.getSkinnedGeometryResource(e);this.refreshSkinningPalette(l.skinning.palette),this.refreshSkinningBindMatrices(e,l.skinning),this.updateSkinnedBounds(e,l);const c=Hr.copy(l.localBoundsCenter).applyMatrix4(e.matrixWorld),u=l.localBoundsRadius*En(e.matrixWorld);if(!n(c.x,c.y,c.z,u,e.frustumCulled))return;this.uploadSkinningResources(l.skinning);const d=bn(t,e.matrixWorld,1,1,1,1);if(r(e.matrixWorld.elements),e.geometry.groups.length>0&&a.length>0){for(const t of e.geometry.groups){const r=a[t.materialIndex??0]??a[0],n=this.resolveSkinnedMaterial(r);if(!n)continue;const i=Cn(n,e,o,t.start,pn(e.geometry,o,t.start,t.count),s),h=this.populateDynamicDrawCall(this.acquireDrawCall(),e.geometry,e,l.resource,n,s,null,e,t,i,Pn(Sn(n),Sn(e),o,t.start,pn(e.geometry,o,t.start,t.count),s?Sn(s):0),o,t.start,pn(e.geometry,o,t.start,t.count),n.transparent,e.renderOrder,this.hasRenderCallbacks(e),e.castShadow,e.receiveShadow,Sn(n),Sn(e),s?Sn(s):0,d,1,c.x,c.y,c.z,u,l.skinning);this.pushDraw(h),this.pushToonOutlineDraw(h,r)}return}const h=this.resolveSkinnedMaterial(a[0]);if(!h)return;const p=fn(e.geometry,o),f=Cn(h,e,o,p.start,p.count,s),m=this.populateDynamicDrawCall(this.acquireDrawCall(),e.geometry,e,l.resource,h,s,null,e,null,f,Pn(Sn(h),Sn(e),o,p.start,p.count,s?Sn(s):0),o,p.start,p.count,h.transparent,e.renderOrder,this.hasRenderCallbacks(e),e.castShadow,e.receiveShadow,Sn(h),Sn(e),s?Sn(s):0,d,1,c.x,c.y,c.z,u,l.skinning);this.pushDraw(m),this.pushToonOutlineDraw(m,a[0])}collectBatchedMesh(e,t,r,n,i,a,s){if(void 0===e.geometry?.getAttribute("position"))return;const o=this.resolveMaterial(e.material);if(!o)return;const l=jn(e),c=(e.geometry.index,this.getGeometryResource(e.geometry)),u=e,d=u._instanceInfo??u._drawInfo??[],h=d.length,p=u._matricesTexture?.image.data,f=u._colorsTexture?.image.data,m=this.getBatchedMeshExtractionCacheEntry(e,o,l,c,u),g=e.matrixWorld.elements,x=u._matricesTexture?.version??0,v=u._colorsTexture?.version??-1;if(m.cacheValid&&!o.transparent&&m.cachedMatricesVersion===x&&m.cachedColorsVersion===v&&m.cachedInstanceInfoLength===d.length&&m.cachedGeometryCount===(u._geometryCount??0)&&Ln(m.cachedMatrixWorld,g)&&this.batchedGeometryIdsMatchSnapshot(m.geometryIdsSnapshot,d)){let t=!1;for(let r=0;r<m.cachedDraws.length;r+=1){const i=m.cachedDraws[r];n(i.boundsCenter.x,i.boundsCenter.y,i.boundsCenter.z,i.boundsRadius,e.frustumCulled)&&(t=!0,this.pushDraw(this.populateDynamicDrawCall(this.acquireDrawCall(),i.template.geometry,i.template.geometryKey,i.template.geometryResource,i.template.material,i.template.customDepthMaterial,m.residentInstanceBinding,i.template.sourceObject,i.template.geometryGroup,i.template.batchKey,i.template.batchHash,i.template.indexed,i.template.start,i.template.count,i.template.transparent,i.template.sourceObject?.renderOrder??i.template.renderOrder,this.hasRenderCallbacks(i.template.sourceObject),i.template.sourceObject?Boolean(i.template.sourceObject.castShadow):i.template.castShadow,i.template.sourceObject?Boolean(i.template.sourceObject.receiveShadow):i.template.receiveShadow,i.template.sortMaterialId,i.template.sortGeometryId,i.template.sortCustomDepthMaterialId,i.instanceStart,i.instanceCount,i.boundsCenter.x,i.boundsCenter.y,i.boundsCenter.z,i.boundsRadius)))}if(!t)return;return!m.residentBufferDirty&&m.residentInstanceBinding||this.residentInstanceUploadsScratch.push(m),void Un(this.extractedBoundsMinScratch,this.extractedBoundsMaxScratch,m.cachedBoundsMin,m.cachedBoundsMax)}if(o.transparent){const o=[],l=!e.sortObjects||null!==e.customSort;for(let i=0;i<h;i+=1){const c=d[i];if(!c?.active||!c.visible)continue;const u=m.templates[c.geometryIndex];if(!u)continue;p?Wr.fromArray(p,16*i):e.getMatrixAt(i,Wr),_r.multiplyMatrices(e.matrixWorld,Wr);const h=u.localBoundsCenter,g=_r.elements,x=g[0]*h.x+g[4]*h.y+g[8]*h.z+g[12],v=g[1]*h.x+g[5]*h.y+g[9]*h.z+g[13],w=g[2]*h.x+g[6]*h.y+g[10]*h.z+g[14],b=Math.sqrt(g[0]*g[0]+g[1]*g[1]+g[2]*g[2]),y=Math.sqrt(g[4]*g[4]+g[5]*g[5]+g[6]*g[6]),S=Math.sqrt(g[8]*g[8]+g[9]*g[9]+g[10]*g[10]),C=u.localBoundsRadius*Math.max(b,y,S,1e-5);if(!n(x,v,w,C,e.frustumCulled&&e.perObjectFrustumCulled))continue;const P=f?f[4*i+0]??1:1,M=f?f[4*i+1]??1:1,B=f?f[4*i+2]??1:1,D=f?f[4*i+3]??1:1,T=bn(t,_r,P,M,B,D,i);r(_r.elements);const I=this.populateDrawCall(this.acquireDrawCall(),u,T,1,x,v,w,C),G=(x-a.x)*s.x+(v-a.y)*s.y+(w-a.z)*s.z;l?o.push({start:u.start,count:u.count,z:G,index:i,draw:I}):(I.sortDepth=G,this.transparentDraws.push(I))}if(l&&o.length>0){e.sortObjects&&e.customSort?e.customSort.call(e,o,i):e.sortObjects&&o.sort((e,t)=>t.z-e.z);let t=0;for(let e=0;e<o.length;e+=1)t+=o[e].z;t/=o.length;const r=Sn(e);for(let e=0;e<o.length;e+=1){const n=o[e].draw;n.sortDepth=t,n.transparentSortGroup=r,n.transparentSortOrder=e,this.transparentDraws.push(n)}}return}const w=m.activeGroups;for(let e=0;e<w.length;e+=1){const t=w[e];t.activeInFrame=!1,t.activeCount=0}w.length=0;const b=m.cachedBoundsMin,y=m.cachedBoundsMax;b.set(1/0,1/0,1/0),y.set(-1/0,-1/0,-1/0),m.geometryIdsSnapshot.length!==d.length&&(m.geometryIdsSnapshot=new Int32Array(d.length));let S=0;for(let e=0;e<h;e+=1){const t=d[e];if(!t?.active||!t.visible){m.geometryIdsSnapshot[e]=-1;continue}const r=m.groups[t.geometryIndex];r?(m.geometryIdsSnapshot[e]=t.geometryIndex,r.activeInFrame||(r.activeInFrame=!0,r.activeCount=0,r.boundsMin.set(1/0,1/0,1/0),r.boundsMax.set(-1/0,-1/0,-1/0),w.push(r)),r.activeCount+=1,S+=1):m.geometryIdsSnapshot[e]=-1}const C=m.cachedInstanceData.beginWriteInstances(S);let P=0;for(let e=0;e<w.length;e+=1){const t=w[e];t.instanceStart=P,t.writeOffset=P*Ur,P+=t.activeCount}const M=zn(g),B=g[0],D=g[4],T=g[8],I=g[12],G=g[1],R=g[5],L=g[9],z=g[13],U=g[2],V=g[6],A=g[10],F=g[14],E=g[3],k=g[7],O=g[11],$=g[15];for(let t=0;t<h;t+=1){const r=m.geometryIdsSnapshot[t]??-1;if(r<0)continue;const n=m.groups[r];if(!n)continue;let i,a,s,o,l,c,u,d,h,g,x,v,w,S,P,j,N,W,_,q,H,K,Z,Y,X,J,Q,ee,te,re,ne,ie;if(p){const e=16*t;i=p[e+0]??0,a=p[e+1]??0,s=p[e+2]??0,o=p[e+3]??0,l=p[e+4]??0,c=p[e+5]??0,u=p[e+6]??0,d=p[e+7]??0,h=p[e+8]??0,g=p[e+9]??0,x=p[e+10]??0,v=p[e+11]??0,w=p[e+12]??0,S=p[e+13]??0,P=p[e+14]??0,j=p[e+15]??0}else{e.getMatrixAt(t,Wr);const r=Wr.elements;i=r[0]??0,a=r[1]??0,s=r[2]??0,o=r[3]??0,l=r[4]??0,c=r[5]??0,u=r[6]??0,d=r[7]??0,h=r[8]??0,g=r[9]??0,x=r[10]??0,v=r[11]??0,w=r[12]??0,S=r[13]??0,P=r[14]??0,j=r[15]??0}M?(N=i,W=a,_=s,q=o,H=l,K=c,Z=u,Y=d,X=h,J=g,Q=x,ee=v,te=w,re=S,ne=P,ie=j):(N=B*i+D*a+T*s+I*o,H=B*l+D*c+T*u+I*d,X=B*h+D*g+T*x+I*v,te=B*w+D*S+T*P+I*j,W=G*i+R*a+L*s+z*o,K=G*l+R*c+L*u+z*d,J=G*h+R*g+L*x+z*v,re=G*w+R*S+L*P+z*j,_=U*i+V*a+A*s+F*o,Z=U*l+V*c+A*u+F*d,Q=U*h+V*g+A*x+F*v,ne=U*w+V*S+A*P+F*j,q=E*i+k*a+O*s+$*o,Y=E*l+k*c+O*u+$*d,ee=E*h+k*g+O*x+$*v,ie=E*w+k*S+O*P+$*j);const ae=f?f[4*t+0]??1:1,se=f?f[4*t+1]??1:1,oe=f?f[4*t+2]??1:1,le=f?f[4*t+3]??1:1,ce=n.writeOffset;C[ce+0]=N,C[ce+1]=W,C[ce+2]=_,C[ce+3]=q,C[ce+4]=H,C[ce+5]=K,C[ce+6]=Z,C[ce+7]=Y,C[ce+8]=X,C[ce+9]=J,C[ce+10]=Q,C[ce+11]=ee,C[ce+12]=te,C[ce+13]=re,C[ce+14]=ne,C[ce+15]=ie,C[ce+16]=ae,C[ce+17]=se,C[ce+18]=oe,C[ce+19]=le,C[ce+20]=t,C[ce+21]=0,C[ce+22]=0,C[ce+23]=0,n.writeOffset+=Ur;const ue=n.template.localBoundsCenter,de=N*ue.x+H*ue.y+X*ue.z+te,he=W*ue.x+K*ue.y+J*ue.z+re,pe=_*ue.x+Z*ue.y+Q*ue.z+ne,fe=Math.sqrt(N*N+W*W+_*_),me=Math.sqrt(H*H+K*K+Z*Z),ge=Math.sqrt(X*X+J*J+Q*Q),xe=n.template.localBoundsRadius*Math.max(fe,me,ge,1e-5),ve=de-xe,we=he-xe,be=pe-xe,ye=de+xe,Se=he+xe,Ce=pe+xe;ve<n.boundsMin.x&&(n.boundsMin.x=ve),we<n.boundsMin.y&&(n.boundsMin.y=we),be<n.boundsMin.z&&(n.boundsMin.z=be),ye>n.boundsMax.x&&(n.boundsMax.x=ye),Se>n.boundsMax.y&&(n.boundsMax.y=Se),Ce>n.boundsMax.z&&(n.boundsMax.z=Ce),ve<b.x&&(b.x=ve),we<b.y&&(b.y=we),be<b.z&&(b.z=be),ye>y.x&&(y.x=ye),Se>y.y&&(y.y=Se),Ce>y.z&&(y.z=Ce)}const j=m.cachedDraws;let N=0;for(let e=0;e<w.length;e+=1){const t=w[e],r=.5*(t.boundsMin.x+t.boundsMax.x),n=.5*(t.boundsMin.y+t.boundsMax.y),i=.5*(t.boundsMin.z+t.boundsMax.z),a=t.boundsMax.x-r,s=t.boundsMax.y-n,o=t.boundsMax.z-i,l=Math.sqrt(a*a+s*s+o*o);let c=j[N];c||(c={template:t.template,instanceStart:0,instanceCount:0,boundsCenter:new mt,boundsRadius:0},j[N]=c),c.template=t.template,c.instanceStart=t.instanceStart,c.instanceCount=t.activeCount,c.boundsCenter.set(r,n,i),c.boundsRadius=l,N+=1}j.length=N,m.cachedMatricesVersion=x,m.cachedColorsVersion=v,m.cachedInstanceInfoLength=d.length,m.cachedGeometryCount=u._geometryCount??0,Rn(g,m.cachedMatrixWorld),m.residentBufferDirty=!0,m.cacheValid=!0;let W=!1;for(let t=0;t<j.length;t+=1){const r=j[t];n(r.boundsCenter.x,r.boundsCenter.y,r.boundsCenter.z,r.boundsRadius,e.frustumCulled)&&(W=!0,this.pushDraw(this.populateDynamicDrawCall(this.acquireDrawCall(),r.template.geometry,r.template.geometryKey,r.template.geometryResource,r.template.material,r.template.customDepthMaterial,m.residentInstanceBinding,r.template.sourceObject,r.template.geometryGroup,r.template.batchKey,r.template.batchHash,r.template.indexed,r.template.start,r.template.count,r.template.transparent,r.template.sourceObject?.renderOrder??r.template.renderOrder,this.hasRenderCallbacks(r.template.sourceObject),r.template.sourceObject?Boolean(r.template.sourceObject.castShadow):r.template.castShadow,r.template.sourceObject?Boolean(r.template.sourceObject.receiveShadow):r.template.receiveShadow,r.template.sortMaterialId,r.template.sortGeometryId,r.template.sortCustomDepthMaterialId,r.instanceStart,r.instanceCount,r.boundsCenter.x,r.boundsCenter.y,r.boundsCenter.z,r.boundsRadius)))}W&&(this.residentInstanceUploadsScratch.push(m),Un(this.extractedBoundsMinScratch,this.extractedBoundsMaxScratch,b,y))}uploadInstanceData(e){if(!this.state.device)return;const t=Math.max(4,e.byteLength);(!this.state.instanceBuffer||t>this.state.instanceBufferSize)&&(this.state.instanceBuffer?.destroy(),this.state.instanceBufferSize=256*Math.ceil(t/256),this.state.instanceBuffer=this.state.device.createBuffer({label:"renderer-instance-buffer",size:this.state.instanceBufferSize,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST}),this.state.sharedSceneBindGroup=null,this.state.sharedShadowBindGroup=null,this.state.sharedShadowBindGroupByCameraBuffer.clear(),this.clearIndirectBundleCache()),e.floatLength>0?this.state.device.queue.writeBuffer(this.state.instanceBuffer,0,e.rawData.buffer,0,e.byteLength):this.state.device.queue.writeBuffer(this.state.instanceBuffer,0,Ar,0,Ur)}uploadResidentInstanceData(e){if(this.state.device)for(let t=0;t<e.length;t+=1){const r=e[t],n=r.residentInstanceBinding;if(!n)continue;if("instanced-direct"===n.mode){const e=r,t=e.sourceMesh,i=t.instanceMatrix.array,a=Math.max(4,16*t.count*Float32Array.BYTES_PER_ELEMENT),s=Math.max(t.count,1),o=Math.max(16,4*s*Float32Array.BYTES_PER_ELEMENT);if((!n.buffer||a>r.residentBufferSize)&&(n.buffer?.destroy(),r.residentBufferSize=256*Math.ceil(a/256),n.buffer=this.state.device.createBuffer({label:"renderer-instanced-mesh-matrix-buffer",size:r.residentBufferSize,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST}),n.sceneBindGroup=null,n.shadowBindGroup=null,n.shadowBindGroups.clear(),n.sceneBindGroupVersion=0,n.shadowBindGroupVersion=0,r.residentBufferDirty=!0),(!n.colorBuffer||o>r.residentColorBufferSize)&&(n.colorBuffer?.destroy(),r.residentColorBufferSize=256*Math.ceil(o/256),n.colorBuffer=this.state.device.createBuffer({label:"renderer-instanced-mesh-color-buffer",size:r.residentColorBufferSize,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST}),n.sceneBindGroup=null,n.shadowBindGroup=null,n.shadowBindGroups.clear(),n.sceneBindGroupVersion=0,n.shadowBindGroupVersion=0,r.residentColorBufferDirty=!0),r.residentBufferDirty&&n.buffer&&(t.count>0?this.state.device.queue.writeBuffer(n.buffer,0,vn(i),0,16*t.count):this.state.device.queue.writeBuffer(n.buffer,0,Fr,0,4),r.residentBufferDirty=!1),r.residentColorBufferDirty&&n.colorBuffer){if(t.instanceColor&&4===t.instanceColor.itemSize&&t.instanceColor.array instanceof Float32Array)this.state.device.queue.writeBuffer(n.colorBuffer,0,vn(t.instanceColor.array),0,4*s);else{let r=e.cachedDefaultColorData;r&&r.length===4*s||(r=new Float32Array(4*s),e.cachedDefaultColorData=r);for(let e=0;e<s;e+=1){const n=4*e;t.instanceColor?(r[n+0]=t.instanceColor.getComponent(e,0),r[n+1]=t.instanceColor.itemSize>1?t.instanceColor.getComponent(e,1):1,r[n+2]=t.instanceColor.itemSize>2?t.instanceColor.getComponent(e,2):1,r[n+3]=t.instanceColor.itemSize>3?t.instanceColor.getComponent(e,3):1):(r[n+0]=1,r[n+1]=1,r[n+2]=1,r[n+3]=1)}this.state.device.queue.writeBuffer(n.colorBuffer,0,vn(r),0,r.length)}r.residentColorBufferDirty=!1}continue}const i=Math.max(4,r.cachedInstanceData.byteLength);if((!n.buffer||i>r.residentBufferSize)&&(n.buffer?.destroy(),r.residentBufferSize=256*Math.ceil(i/256),n.buffer=this.state.device.createBuffer({label:"renderer-instanced-mesh-buffer",size:r.residentBufferSize,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST}),n.sceneBindGroup=null,n.shadowBindGroup=null,n.shadowBindGroups.clear(),n.sceneBindGroupVersion=0,n.shadowBindGroupVersion=0,r.residentBufferDirty=!0),r.residentBufferDirty){if(!n.buffer)continue;r.cachedInstanceData.floatLength>0?this.state.device.queue.writeBuffer(n.buffer,0,r.cachedInstanceData.rawData.buffer,0,r.cachedInstanceData.byteLength):this.state.device.queue.writeBuffer(n.buffer,0,Ar,0,Ur),r.residentBufferDirty=!1}}}clearIndirectBundleCache(){this.state.indirectForwardBundleCache.clear(),this.state.directForwardBundleCache.clear()}clearStaticDrawSetBundleCaches(){this.materialPassStaticBundleCache=new WeakMap;for(const e of this.staticDrawSets){for(const t of e.visibleIndirectSubmissionStreams??[])t.forwardBundle=null;e.indirectForwardBundleCache.clear(),e.directForwardBundle=null,e.directForwardBundleSceneBindGroup=null,e.depthPrepassBundle=null,e.depthPrepassBundleSceneBindGroup=null,e.indirectDepthPrepassBundles.prepass=null,e.indirectDepthPrepassBundles.postpass=null,e.shadowBundles=new WeakMap,e.depthMaterialResources.clear()}}getViewport(e){return e.set(0,0,this.state.width,this.state.height)}getSharedSceneBindGroup(){if(!(this.state.device&&this.state.sceneBindGroupLayout&&this.state.cameraBuffer&&this.state.lightBuffer&&this.state.instanceBuffer&&this.state.shadowComparisonSampler&&this.state.directionalShadowView&&this.state.linearClampSampler&&this.state.pointShadowArrayView&&this.state.spotShadowView))throw new Error("Renderer scene bind group resources are not initialized.");return this.state.sharedSceneBindGroup||(this.state.sharedSceneBindGroup=this.state.device.createBindGroup({label:"renderer-scene-bind-group",layout:this.state.sceneBindGroupLayout,entries:[{binding:0,resource:{buffer:this.state.cameraBuffer}},{binding:1,resource:{buffer:this.state.lightBuffer}},{binding:2,resource:{buffer:this.state.instanceBuffer}},{binding:3,resource:this.state.shadowComparisonSampler},{binding:4,resource:this.state.directionalShadowView},{binding:5,resource:this.state.linearClampSampler},{binding:6,resource:this.state.pointShadowArrayView},{binding:7,resource:this.state.spotShadowView}]})),this.state.sharedSceneBindGroup}getSharedShadowBindGroup(){if(!(this.state.device&&this.state.shadowBindGroupLayout&&this.state.shadowCameraBuffer&&this.state.instanceBuffer))throw new Error("Renderer shadow bind group resources are not initialized.");return this.state.sharedShadowBindGroup||(this.state.sharedShadowBindGroup=this.state.device.createBindGroup({label:"renderer-shadow-bind-group",layout:this.state.shadowBindGroupLayout,entries:[{binding:0,resource:{buffer:this.state.shadowCameraBuffer}},{binding:1,resource:{buffer:this.state.instanceBuffer}}]})),this.state.sharedShadowBindGroup}getShadowCameraBuffer(e){if(!this.state.device)throw new Error("Renderer is not initialized.");for(;this.state.shadowCameraBufferPool.length<=e;)this.state.shadowCameraBufferPool.push(this.state.device.createBuffer({label:`renderer-shadow-camera-buffer-${this.state.shadowCameraBufferPool.length}`,size:256,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}));return this.state.shadowCameraBufferPool[e]}getSharedShadowBindGroupForCameraBuffer(e){if(!(this.state.device&&this.state.sceneBindGroupLayout&&this.state.directSceneBindGroupLayout&&this.state.shadowBindGroupLayout&&this.state.instanceBuffer))throw new Error("Renderer shadow bind group resources are not initialized.");const t=this.state.sharedShadowBindGroupByCameraBuffer.get(e);if(t)return t;const r=this.state.device.createBindGroup({label:"renderer-shadow-bind-group-per-camera",layout:this.state.shadowBindGroupLayout,entries:[{binding:0,resource:{buffer:e}},{binding:1,resource:{buffer:this.state.instanceBuffer}}]});return this.state.sharedShadowBindGroupByCameraBuffer.set(e,r),r}buildIndirectSubmissionStreams(e,t,r,n){const i=this.indirectSubmissionStreamsScratch;i.length=0;let a=null;for(let s=0;s<e.length;s+=1){const o=e[s],l=n?.[s]??(r?this.getMaterialResource(o.material,r,o.receiveShadow,void 0,null!==o.skinning,this.drawUsesBatching(o)):this.getMaterialResourceForDraw(o)),c=r?t:this.resolveSceneBindGroupForDraw(o,t),u=[Sn(l.pipeline),Sn(l.bindGroup),Sn(c),Sn(o.geometryKey)].join(":"),d=On(o);a&&a.key===u&&a.indirectStartIndex+a.indirectCount===s?(a.indirectCount+=1,a.drawCallCount+=1,a.triangleCount+=d):(a={key:u,material:o.material,materialResource:l,sceneBindGroup:c,geometry:o.geometry,geometryKey:o.geometryKey,geometryResource:o.geometryResource,indirectStartIndex:s,indirectCount:1,drawCallCount:1,triangleCount:d,forwardBundle:null},i.push(a))}return i}getOrCreateStaticIndirectSubmissionStreams(e,t,r=[Er]){const n=r.join("|"),i=null!==e.visibleIndirectSubmissionStreams&&e.visibleIndirectStreamsSceneBindGroup===t&&e.visibleIndirectStreamsSampleCount===this.sampleCount&&e.visibleIndirectStreamsColorFormatsKey===n;if(i)return e.visibleIndirectSubmissionStreams;let a=!i;for(const t of e.visibleMaterialBindings){const n=this.getMaterialResource(t.material,"packed-visible",t.receiveShadow,r,!1,t.usesBatching),i=t.resource;t.resource=n,i!==n&&(a=!0);for(const r of t.drawIndices)e.visibleDrawMaterialResources[r]!==n&&(a=!0),e.visibleDrawMaterialResources[r]=n}return!a&&e.visibleIndirectSubmissionStreams||(e.visibleIndirectSubmissionStreams=this.buildIndirectSubmissionStreams(e.draws,t,"packed-visible",e.visibleDrawMaterialResources).slice(),e.visibleIndirectStreamsSceneBindGroup=t,e.visibleIndirectStreamsSampleCount=this.sampleCount,e.visibleIndirectStreamsColorFormatsKey=n,e.indirectForwardBundleCache.clear()),e.visibleIndirectSubmissionStreams}getOrCreateIndirectForwardBundle(e,t=this.state.drawMetadataResource,r=this.state.indirectForwardBundleCache,n="renderer-indirect-forward-bundle",i=[Er]){if(!this.state.device||!this.state.format)throw new Error("Renderer is not initialized.");if(!t)throw new Error("Indirect draw metadata is not available.");if(e.forwardBundle)return e.forwardBundle;const a=[e.key,Sn(e.geometryResource.position),e.geometryResource.index?Sn(e.geometryResource.index):"no-index",Sn(t.indirectBuffer),e.indirectStartIndex,e.indirectCount,`samples=${this.sampleCount}`,`formats=${i.join("|")}`].join(":"),s=r.get(a);if(s)return e.forwardBundle=s,s;const o=this.state.device.createRenderBundleEncoder({label:`${n}-${a}`,colorFormats:i,depthStencilFormat:"depth32float",sampleCount:this.sampleCount});if(o.setPipeline(e.materialResource.pipeline),this.bindGeometryVertexBuffers(o,e.geometry,e.geometryResource,e.materialResource.vertexAttributes,0,1,e.material.wireframe),o.setBindGroup(0,e.sceneBindGroup),o.setBindGroup(1,e.materialResource.bindGroup),!e.materialResource.graphTextureBindGroupLayout)throw new Error("Graph texture layout is missing.");o.setBindGroup(3,this.createGraphTextureBindGroup(e.material,e.materialResource.graphTextureBindGroupLayout));for(let r=0;r<e.indirectCount;r+=1)o.drawIndexedIndirect(t.indirectBuffer,20*(e.indirectStartIndex+r));const l=o.finish({label:`${n}-${a}`});return r.set(a,l),e.forwardBundle=l,l}getDirectForwardBundleKey(e,t,r){let n=2166136261;n=Tn(n,e.length),n=Tn(n,this.sampleCount),n=Tn(n,Sn(t));for(let i=0;i<e.length;i+=1){const a=e[i],s=this.getMaterialResourceForDraw(a,r),o=this.resolveSceneBindGroupForDraw(a,t);n=Tn(n,Sn(a.material)),n=Tn(n,a.receiveShadow?1:0),n=Tn(n,a.material.version??0),n=Tn(n,Sn(s.pipeline)),n=Tn(n,Sn(s.bindGroup)),n=Tn(n,Sn(o)),n=Tn(n,Sn(a.geometryKey)),n=Tn(n,Sn(a.geometryResource.position)),n=Tn(n,Sn(a.geometryResource.normal)),n=Tn(n,Sn(a.geometryResource.uv)),n=Tn(n,Sn(a.geometryResource.color)),n=Tn(n,a.geometryResource.index?Sn(a.geometryResource.index):0);for(const e of a.geometryResource.extraAttributeBuffers.values())n=Tn(n,Sn(e));n=Tn(n,a.indexed?1:0),n=Tn(n,a.start),n=Tn(n,a.count),n=Tn(n,a.instanceStart),n=Tn(n,a.instanceCount);const l=a.material.getTexturesList();n=Tn(n,l.length);for(let e=0;e<l.length;e+=1){const t=l[e];n=Tn(n,Sn(t)),n=Tn(n,t.version)}}return`forward-direct:${n}:${e.length}:samples=${this.sampleCount}:formats=${r.join("|")}`}getOrCreateDirectForwardBundle(e,t,r,n=[Er]){if(!this.state.device||!this.state.format||0===e.length)return null;const i=this.getDirectForwardBundleKey(e,t,n),a=this.state.directForwardBundleCache.get(i);if(a){for(let t=0;t<e.length;t+=1){const n=e[t];n.materialResource&&this.updateMaterialUniformBuffer(n.material,n.materialResource),this.recordDraw(n,r)}return a}const s=this.state.device.createRenderBundleEncoder({label:`renderer-direct-forward-bundle-${i}`,colorFormats:n,depthStencilFormat:"depth32float",sampleCount:this.sampleCount});let o=null,l=null,c=null,u=null;for(let i=0;i<e.length;i+=1){const a=e[i],d=a.geometryResource,h=this.getMaterialResourceForDraw(a,n),p=this.resolveSceneBindGroupForDraw(a,t);if(o!==h.pipeline&&(o=h.pipeline,c=null,s.setPipeline(o)),c!==a.geometryKey&&(c=a.geometryKey,this.bindGeometryVertexBuffers(s,a.geometry,d,h.vertexAttributes,a.instanceStart,a.instanceCount,a.wireframe)),u!==p&&(u=p,s.setBindGroup(0,p)),l!==a.material){if(l=a.material,s.setBindGroup(1,h.bindGroup),!h.graphTextureBindGroupLayout)throw new Error("Graph texture layout is missing.");s.setBindGroup(3,this.createGraphTextureBindGroup(a.material,h.graphTextureBindGroupLayout))}a.indexed&&(a.wireframe?d.wireframeIndex:d.index)?s.drawIndexed(a.count,a.instanceCount,a.start,0,a.instanceStart):s.draw(a.count,a.instanceCount,a.start,a.instanceStart),this.recordDraw(a,r)}const d=s.finish({label:`renderer-direct-forward-bundle-${i}`});return this.state.directForwardBundleCache.set(i,d),d}getOrCreateStaticMaterialBundle(e,t,r,n){const i=`${Sn(t)}:${this.sampleCount}:${n.join("|")}`,a=this.materialPassStaticBundleCache.get(e)?.get(i);if(a)return this.recordStaticDrawStats(e,r),a;const s=this.getOrCreateDirectForwardBundle(e.draws,t,r,n);if(!s)return null;let o=this.materialPassStaticBundleCache.get(e);return o||(o=new Map,this.materialPassStaticBundleCache.set(e,o)),o.set(i,s),s}resolveSceneBindGroupForDraw(e,t){if(!(e.residentInstanceBinding&&this.state.device&&this.state.sceneBindGroupLayout&&this.state.directSceneBindGroupLayout&&this.state.cameraBuffer&&this.state.lightBuffer&&this.state.shadowComparisonSampler&&this.state.directionalShadowView&&this.state.linearClampSampler&&this.state.pointShadowArrayView&&this.state.spotShadowView&&e.residentInstanceBinding.buffer))return t;const r=e.residentInstanceBinding,n=r.buffer,i=r.colorBuffer??r.buffer;return n&&i?(r.sceneBindGroup&&r.sceneBindGroupVersion===this.state.residentSceneBindGroupVersion||(r.sceneBindGroup=this.state.device.createBindGroup("instanced-direct"===r.mode?{label:"renderer-resident-direct-scene-bind-group",layout:this.state.directSceneBindGroupLayout,entries:[{binding:0,resource:{buffer:this.state.cameraBuffer}},{binding:1,resource:{buffer:this.state.lightBuffer}},{binding:2,resource:{buffer:n}},{binding:3,resource:{buffer:i}},{binding:4,resource:this.state.shadowComparisonSampler},{binding:5,resource:this.state.directionalShadowView},{binding:6,resource:this.state.linearClampSampler},{binding:7,resource:this.state.pointShadowArrayView},{binding:8,resource:this.state.spotShadowView}]}:{label:"renderer-resident-scene-bind-group",layout:this.state.sceneBindGroupLayout,entries:[{binding:0,resource:{buffer:this.state.cameraBuffer}},{binding:1,resource:{buffer:this.state.lightBuffer}},{binding:2,resource:{buffer:n}},{binding:3,resource:this.state.shadowComparisonSampler},{binding:4,resource:this.state.directionalShadowView},{binding:5,resource:this.state.linearClampSampler},{binding:6,resource:this.state.pointShadowArrayView},{binding:7,resource:this.state.spotShadowView}]}),r.sceneBindGroupVersion=this.state.residentSceneBindGroupVersion),r.sceneBindGroup):t}resolveShadowBindGroupForDraw(e,t,r=this.state.shadowCameraBuffer){if(!(e.residentInstanceBinding&&this.state.device&&this.state.shadowBindGroupLayout&&this.state.directShadowBindGroupLayout&&r&&e.residentInstanceBinding.buffer))return t;const n=e.residentInstanceBinding,i=n.buffer,a=n.colorBuffer??n.buffer;if(!i||!a)return t;if(n.shadowBindGroupVersion!==this.state.residentShadowBindGroupVersion&&(n.shadowBindGroup=null,n.shadowBindGroups.clear(),n.shadowBindGroupVersion=this.state.residentShadowBindGroupVersion),r===this.state.shadowCameraBuffer&&n.shadowBindGroup)return n.shadowBindGroup;const s=n.shadowBindGroups.get(r);if(s)return s;const o=this.state.device.createBindGroup("instanced-direct"===n.mode?{label:"renderer-resident-direct-shadow-bind-group",layout:this.state.directShadowBindGroupLayout,entries:[{binding:0,resource:{buffer:r}},{binding:1,resource:{buffer:i}},{binding:2,resource:{buffer:a}}]}:{label:"renderer-resident-shadow-bind-group",layout:this.state.shadowBindGroupLayout,entries:[{binding:0,resource:{buffer:r}},{binding:1,resource:{buffer:i}}]});return n.shadowBindGroups.set(r,o),r===this.state.shadowCameraBuffer&&(n.shadowBindGroup=o),o}uploadDrawMetadata(e){if(!this.state.device||!this.state.visibilityParamsBuffer)return;if(0===e.length)return this.visibilityParamsUpload[0]=0,this.visibilityParamsUpload[1]=this.state.hizMipCount,this.visibilityParamsUpload[2]=0,this.visibilityParamsUpload[3]=0,this.state.device.queue.writeBuffer(this.state.visibilityParamsBuffer,0,this.visibilityParamsUpload,0,4),void(this.state.drawMetadataResource&&(this.state.drawMetadataResource.count=0));const t=e.length*Vr;this.drawMetadataUpload.length<t&&(this.drawMetadataUpload=new Float32Array(Math.max(t,2*this.drawMetadataUpload.length,768)));const r=5*e.length;this.indirectDrawUpload.length<r&&(this.indirectDrawUpload=new Uint32Array(Math.max(r,2*this.indirectDrawUpload.length,320)));const n=this.drawMetadataUpload,i=this.indirectDrawUpload;for(let t=0;t<e.length;t+=1){const r=e[t],a=t*Vr;n[a+0]=r.boundsCenter.x,n[a+1]=r.boundsCenter.y,n[a+2]=r.boundsCenter.z,n[a+3]=r.boundsRadius,n[a+4]=r.count,n[a+5]=r.start,n[a+6]=r.instanceStart,n[a+7]=r.instanceCount,n[a+8]=1,n[a+9]=0,n[a+10]=0,n[a+11]=0;const s=5*t;i[s+0]=r.count,i[s+1]=r.instanceCount,i[s+2]=r.start,i[s+3]=0,i[s+4]=r.instanceStart}const a=e.length;if(!(this.state.drawMetadataResource&&this.state.drawMetadataResource.capacity>=a)){this.state.drawMetadataResource?.metadataBuffer.destroy(),this.state.drawMetadataResource?.indirectBuffer.destroy(),this.state.drawMetadataResource?.postIndirectBuffer.destroy();const t=Math.max(64,1<<Math.ceil(Math.log2(a)));this.state.drawMetadataResource={count:e.length,capacity:t,metadataBuffer:this.state.device.createBuffer({label:"renderer-draw-metadata-buffer",size:t*Vr*4,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST}),indirectBuffer:this.state.device.createBuffer({label:"renderer-indirect-draw-buffer",size:5*t*4,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.INDIRECT|GPUBufferUsage.COPY_DST|GPUBufferUsage.COPY_SRC}),postIndirectBuffer:this.state.device.createBuffer({label:"renderer-post-indirect-draw-buffer",size:5*t*4,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.INDIRECT|GPUBufferUsage.COPY_DST})},this.state.visibilityBindGroup=null,this.state.visibilityBindGroupMetadataResource=null,this.clearIndirectBundleCache()}this.state.drawMetadataResource.count=e.length,this.state.device.queue.writeBuffer(this.state.drawMetadataResource.metadataBuffer,0,n,0,t),this.state.device.queue.writeBuffer(this.state.drawMetadataResource.indirectBuffer,0,i,0,r),this.visibilityParamsUpload[0]=e.length,this.visibilityParamsUpload[1]=this.state.hizMipCount,this.visibilityParamsUpload[2]=0,this.visibilityParamsUpload[3]=0,this.state.device.queue.writeBuffer(this.state.visibilityParamsBuffer,0,this.visibilityParamsUpload,0,4)}recordDraw(e,t){t.drawCallCount+=1,t.triangleCount+=On(e)}executeVisibilityPass(e,t){Yn.call(this,e,t)}executeStaticVisibilityPasses(e,t){Xn.call(this,e,t)}getOrCreateStaticVisibilityBindGroup(e,t){return Jn.call(this,e,t)}executeDirectionalShadowPass(e,t,r,n){Qn.call(this,e,t,r,n)}executePointShadowPass(e,t,r,n){ei.call(this,e,t,r,n)}executeSpotShadowPass(e,t,r,n){ti.call(this,e,t,r,n)}executeDepthPrepass(e,t,r,n){ri.call(this,e,t,r,n)}executeStaticDepthPrepass(e,t,r){ni.call(this,e,t,r)}executeStaticTemporalDepthResolvePass(e){ai.call(this,e)}getOrCreateStaticDepthPrepassBundle(e,t){return si.call(this,e,t)}executeHiZPasses(e,t=!1){ci.call(this,e,t)}getOrCreateStaticVisibleSceneBindGroup(e){if(!(this.state.device&&this.state.visibleSceneBindGroupLayout&&this.state.cameraBuffer&&this.state.lightBuffer&&this.state.shadowComparisonSampler&&this.state.directionalShadowView&&this.state.linearClampSampler&&this.state.pointShadowArrayView&&this.state.spotShadowView))throw new Error("Renderer visible scene bind group resources are not initialized.");return e.visibleSceneBindGroup&&e.visibleSceneBindGroupVersion===this.state.residentSceneBindGroupVersion||(e.visibleSceneBindGroup=this.state.device.createBindGroup({label:`${e.label}-static-visible-scene-bind-group`,layout:this.state.visibleSceneBindGroupLayout,entries:[{binding:0,resource:{buffer:this.state.cameraBuffer}},{binding:1,resource:{buffer:this.state.lightBuffer}},{binding:2,resource:{buffer:e.instanceBuffer}},{binding:3,resource:this.state.shadowComparisonSampler},{binding:4,resource:this.state.directionalShadowView},{binding:5,resource:this.state.linearClampSampler},{binding:6,resource:this.state.pointShadowArrayView},{binding:7,resource:this.state.spotShadowView},{binding:8,resource:{buffer:e.instanceVisibilityResource.visibleInstanceIndicesBuffer}}]}),e.visibleSceneBindGroupVersion=this.state.residentSceneBindGroupVersion),e.visibleSceneBindGroup}getOrCreateStaticVisibleDepthSceneBindGroup(e){if(!this.state.device||!this.state.visibleDepthSceneBindGroupLayout||!this.state.cameraBuffer)throw new Error("Renderer visible depth scene bind group resources are not initialized.");return e.visibleDepthSceneBindGroup&&e.visibleDepthSceneBindGroupVersion===this.state.residentSceneBindGroupVersion||(e.visibleDepthSceneBindGroup=this.state.device.createBindGroup({label:`${e.label}-static-visible-depth-scene-bind-group`,layout:this.state.visibleDepthSceneBindGroupLayout,entries:[{binding:0,resource:{buffer:this.state.cameraBuffer}},{binding:2,resource:{buffer:e.instanceBuffer}},{binding:3,resource:{buffer:e.instanceVisibilityResource.visibleInstanceIndicesBuffer}}]}),e.visibleDepthSceneBindGroupVersion=this.state.residentSceneBindGroupVersion),e.visibleDepthSceneBindGroup}executeMaterialPass(e,t,r,n,i,a={}){if(!this.state.mainDepthView||0===t.length)return;const s=t.map(e=>this.getColorTargetFormat(e)),o=t.map(e=>this.getColorTargetView(e)),l=this.sampleCount>1,c=l?t.map(e=>this.ensureMsaaColorTarget(e)):[],u=this.getColorTargetDimensions(t[0]),d=l?this.ensureMsaaDepthTarget(u.width,u.height):null,h=e.beginRenderPass({label:"renderer-material-pass",colorAttachments:t.map((e,t)=>({view:c[t]?.view??o[t],resolveTarget:c[t]?o[t]:void 0,clearValue:1===t?{r:.5,g:.5,b:1,a:1}:{r:this.clearColor[0],g:this.clearColor[1],b:this.clearColor[2],a:this.clearColor[3]},loadOp:a.loadColor?"load":"clear",storeOp:c[t]?"discard":"store"})),depthStencilAttachment:{view:d?.view??this.state.mainDepthView,depthClearValue:1,depthLoadOp:d?"clear":a.loadDepth?"load":"clear",depthStoreOp:d?"discard":"store"}});let p=null,f=null,m=null,g=null,x=null;const v=e=>{e.sourceObject&&e.hasRenderCallbacks&&e.sourceObject.onBeforeRender(this,n.scene,n.camera,e.geometry,e.material,e.geometryGroup);const t=e.geometryResource;let a=e.material;const o=this.getMaterialResourceForDraw(e,s),l=this.resolveSceneBindGroupForDraw(e,r);if(p!==o.pipeline&&(p=o.pipeline,m=null,x=null,h.setPipeline(p)),m!==e.geometryKey&&(m=e.geometryKey,this.bindGeometryVertexBuffers(h,e.geometry,t,o.vertexAttributes,e.instanceStart,e.instanceCount,e.wireframe)),g!==l&&(g=l,h.setBindGroup(0,l)),f!==a){if(f=a,h.setBindGroup(1,o.bindGroup),!o.graphTextureBindGroupLayout)throw new Error("Graph texture layout is missing.");h.setBindGroup(3,this.createGraphTextureBindGroup(a,o.graphTextureBindGroupLayout))}o.usesSkinning&&e.skinning&&x!==e.skinning.bindGroup&&(x=e.skinning.bindGroup,h.setBindGroup(2,x)),e.indexed&&(e.wireframe?t.wireframeIndex:t.index)?h.drawIndexed(e.count,e.instanceCount,e.start,0,e.instanceStart):h.draw(e.count,e.instanceCount,e.start,e.instanceStart),this.recordDraw(e,i),e.sourceObject&&e.hasRenderCallbacks&&e.sourceObject.onAfterRender(this,n.scene,n.camera,e.geometry,e.material,e.geometryGroup)},w=a.drawStage??"all";if(a.objectFilter||a.overrideMaterial){const e=e=>{if(a.objectFilter){const t=e.sourceRanges?.filter(e=>a.objectFilter(e.sourceObject));if(null!=t&&t.length>0){const r="function"==typeof a.overrideMaterial?a.overrideMaterial(e.material,null!==e.skinning):a.overrideMaterial;for(const n of t)v({...e,sourceObject:n.sourceObject,instanceStart:n.instanceStart,instanceCount:n.instanceCount,material:r??e.material,sourceRanges:void 0});return}if(!a.objectFilter(e.sourceObject))return}const t="function"==typeof a.overrideMaterial?a.overrideMaterial(e.material,null!==e.skinning):a.overrideMaterial;v(t?{...e,material:t}:e)};if("late"!==w){for(const t of this.staticDrawSets)if(t.publicSet.enabled)for(const r of t.draws)e(r);for(const t of n.gpuOpaqueDraws)e(t);for(const t of n.directOpaqueDraws)e(t)}if("opaque"!==w)for(const t of n.transparentDraws)e(t);return void h.end()}if("late"!==w){for(const e of this.staticDrawSets){if(!e.publicSet.enabled||0===e.draws.length)continue;if(this.getHiZOcclusionCullingActive()&&e.lastVisibilityFrameToken===this.staticFrameToken){const t=this.getOrCreateStaticVisibleSceneBindGroup(e),r=this.getOrCreateStaticIndirectSubmissionStreams(e,t,s);for(const t of r){if(this.getMultiDrawIndirectActive()){if(h.setPipeline(t.materialResource.pipeline),this.bindGeometryVertexBuffers(h,t.geometry,t.geometryResource,t.materialResource.vertexAttributes,0,1,t.material.wireframe),h.setBindGroup(0,t.sceneBindGroup),h.setBindGroup(1,t.materialResource.bindGroup),!t.materialResource.graphTextureBindGroupLayout)throw new Error("Graph texture layout is missing.");h.setBindGroup(3,this.createGraphTextureBindGroup(t.material,t.materialResource.graphTextureBindGroupLayout)),h.multiDrawIndexedIndirect(e.drawMetadataResource.indirectBuffer,5*t.indirectStartIndex*Uint32Array.BYTES_PER_ELEMENT,t.indirectCount)}else this.renderBundleScratch[0]=this.getOrCreateIndirectForwardBundle(t,e.drawMetadataResource,e.indirectForwardBundleCache,`${e.label}-static-indirect-material-bundle`,s),h.executeBundles(this.renderBundleScratch);i.drawCallCount+=t.drawCallCount,i.triangleCount+=t.triangleCount}continue}const t=this.getOrCreateStaticMaterialBundle(e,r,i,s);t&&(this.renderBundleScratch[0]=t,h.executeBundles(this.renderBundleScratch))}if(this.getHiZOcclusionCullingActive()&&this.state.drawMetadataResource){const e=n.gpuOpaqueDraws.map(e=>this.getMaterialResourceForDraw(e,s)),t=this.buildIndirectSubmissionStreams(n.gpuOpaqueDraws,r,void 0,e);for(const e of t)this.renderBundleScratch[0]=this.getOrCreateIndirectForwardBundle(e,this.state.drawMetadataResource,this.state.indirectForwardBundleCache,"renderer-indirect-material-bundle",s),h.executeBundles(this.renderBundleScratch),i.drawCallCount+=e.drawCallCount,i.triangleCount+=e.triangleCount}else{const e=Dn(n.gpuOpaqueDraws)||n.gpuOpaqueDraws.some(e=>null!==e.skinning)?null:this.getOrCreateDirectForwardBundle(n.gpuOpaqueDraws,r,i,s);if(e)this.renderBundleScratch[0]=e,h.executeBundles(this.renderBundleScratch);else for(const e of n.gpuOpaqueDraws)v(e)}const e=Dn(n.directOpaqueDraws)||n.directOpaqueDraws.some(e=>null!==e.skinning)?null:this.getOrCreateDirectForwardBundle(n.directOpaqueDraws,r,i,s);if(e)this.renderBundleScratch[0]=e,h.executeBundles(this.renderBundleScratch);else for(const e of n.directOpaqueDraws)v(e)}if("opaque"!==w)for(const e of n.transparentDraws)v(e);h.end()}executeForwardPass(e,t,r,n,i,a,s=!1,o="all",l=!1,c=this.sampleCount){ui.call(this,e,t,r,n,i,a,s,o,l,c)}executeStaticForwardPass(e,t,r){di.call(this,e,t,r)}getOrCreateStaticDirectForwardBundle(e,t){return hi.call(this,e,t)}refreshStaticDrawMaterialResources(e){fi.call(this,e)}syncStaticVisibleMaterialBindingCaches(e){pi.call(this,e)}recordStaticDrawStats(e,t){mi.call(this,e,t)}hasEnabledStaticDrawSets(){return gi.call(this)}executePresentPass(e,t,r){xi.call(this,e,t,r)}clearDirectionalShadow(e){vi.call(this,e)}clearPointShadow(e){wi.call(this,e)}clearSpotShadow(e){bi.call(this,e)}drawDepthLike(e,t,r,n){yi.call(this,e,t,r,n)}getGeometryResource(e){if(!this.state.device)throw new Error("Renderer is not initialized.");const t=this.geometryCache.get(e);if(t&&t.lastValidatedExtractionVersion===this.extractionVersion)return t;if(t&&function(e,t){if(t.indexVersion!==(e.index?.version??0)||t.drawRangeStart!==e.drawRange.start||t.drawRangeCount!==e.drawRange.count)return!1;if(t.groups.length!==e.groups.length)return!1;for(let r=0;r<t.groups.length;r+=1){const n=t.groups[r],i=e.groups[r];if(n.start!==i?.start||n.count!==i?.count||n.materialIndex!==(i?.materialIndex??0))return!1}for(let r=0;r<t.attributes.length;r+=1){const n=t.attributes[r],i=e.getAttribute(n.name);if(i?Jr(i)!==n.version||i.itemSize!==n.itemSize||i.count!==n.count:0!==n.version||0!==n.itemSize||0!==n.count)return!1}return!0}(e,t))return t.lastValidatedExtractionVersion=this.extractionVersion,t;t&&(this.clearIndirectBundleCache(),this.retireGeometryResource(t));const r=e.getAttribute("position");if(!r)throw new Error("BufferGeometry is missing the required position attribute.");const n=r.count,i=dn(r,n,3,[0,0,0]),a=dn(e.getAttribute("normal"),n,3,[0,0,1]),s=dn(e.getAttribute("uv"),n,2,[0,0]),o=dn(e.getAttribute("color"),n,4,[1,1,1,1]);let l=null,c=null;if(e.index){const t=e.index.array,r=t instanceof Uint32Array?t:new Uint16Array(t);c=t instanceof Uint32Array?"uint32":"uint16",l=sn(this.state.device,r,GPUBufferUsage.INDEX,`${e.uuid}-index`)}const u={signature:Qr(e),indexVersion:e.index?.version??0,drawRangeStart:e.drawRange.start,drawRangeCount:e.drawRange.count,vertexCount:n,attributes:["position","normal","uv","color"].map(t=>{const r=e.getAttribute(t);return{name:t,version:Jr(r),itemSize:r?.itemSize??0,count:r?.count??0}}),lastValidatedExtractionVersion:this.extractionVersion,groups:e.groups.map(e=>({start:e.start,count:e.count,materialIndex:e.materialIndex??0})),...this.createGeometryBuffers(e.uuid,i,a,s,o,e.index?.array),extraAttributeBuffers:new Map,extraAttributeBufferVersions:new Map,wireframeIndex:null,wireframeIndexFormat:null};return this.geometryCache.set(e,u),u}getSkinnedGeometryResource(e){if(!this.state.device)throw new Error("Renderer is not initialized.");const t=e.geometry.getAttribute("skinIndex"),r=e.geometry.getAttribute("skinWeight"),n=e.geometry.getAttribute("position");if(!t||!r||!n)throw new Error("SkinnedMesh requires position, skinIndex, and skinWeight attributes.");if(0===e.skeleton.bones.length)throw new Error("SkinnedMesh requires a skeleton with at least one bone.");const i=function(e){return[Qr(e.geometry),Jr(e.geometry.getAttribute("skinIndex")),Jr(e.geometry.getAttribute("skinWeight")),e.skeleton.bones.length].join(";")}(e);let a=this.skinnedGeometryCache.get(e);if(!a||a.sourceSignature!==i||a.skinning.palette.skeleton!==e.skeleton){a&&a.skinning.bindUniformBuffer.destroy();const s=this.getSkinningPalette(e.skeleton),o=this.state.device.createBuffer({label:`${e.uuid}-skinning-bind-matrices`,size:32*Float32Array.BYTES_PER_ELEMENT,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),l=new Float32Array(32);l.set(e.bindMatrix.elements,0),l.set(e.bindMatrixInverse.elements,16);const c={bindGroup:this.state.device.createBindGroup({label:`${e.uuid}-skinning-bind-group`,layout:this.state.skinningBindGroupLayout,entries:[{binding:0,resource:{buffer:s.matrixBuffer}},{binding:1,resource:{buffer:o}}]}),bindUniformBuffer:o,bindMatrices:l,palette:s,bindUniformDirty:!0},u={sourceSignature:i,resource:this.getGeometryResource(e.geometry),skinning:c,boneBounds:this.createSkinningBoneBounds(e,n,t,r),localBoundsMin:new mt,localBoundsMax:new mt,localBoundsCenter:new mt,localBoundsRadius:1};a=u,this.skinnedGeometryCache.set(e,u)}if(!a)throw new Error("Skinned geometry cache entry could not be created.");return a}getSkinningPalette(e){const t=this.skinPaletteCache.get(e);if(t)return t;if(!this.state.device||0===e.bones.length)throw new Error("A non-empty skeleton is required to create a GPU skinning palette.");const r=16*e.bones.length,n={skeleton:e,matrixBuffer:this.state.device.createBuffer({label:"renderer-skinning-bone-palette",size:r*Float32Array.BYTES_PER_ELEMENT,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST}),dirty:!0,lastRefreshExtractionVersion:-1};return this.skinPaletteCache.set(e,n),this.skinPaletteResources.add(n),n}refreshSkinningPalette(e){if(e.lastRefreshExtractionVersion===this.extractionVersion)return;e.lastRefreshExtractionVersion=this.extractionVersion;const{skeleton:t}=e;t.update(),e.dirty=!0}refreshSkinningBindMatrices(e,t){const r=t.bindMatrices;let n=!1;for(let t=0;t<16;t+=1){const i=e.bindMatrix.elements[t],a=e.bindMatrixInverse.elements[t];r[t]===i&&r[t+16]===a||(n=!0),r[t]=i,r[t+16]=a}t.bindUniformDirty||=n}uploadSkinningResources(e){if(this.state.device){if(e.palette.dirty){const t=e.palette.skeleton.boneMatrices;this.state.device.queue.writeBuffer(e.palette.matrixBuffer,0,t.buffer,t.byteOffset,16*e.palette.skeleton.bones.length*Float32Array.BYTES_PER_ELEMENT),e.palette.dirty=!1}e.bindUniformDirty&&(this.state.device.queue.writeBuffer(e.bindUniformBuffer,0,e.bindMatrices.buffer,e.bindMatrices.byteOffset,e.bindMatrices.byteLength),e.bindUniformDirty=!1)}}createSkinningBoneBounds(e,t,r,n){const i=Array.from({length:e.skeleton.bones.length},()=>new mt(1/0,1/0,1/0)),a=Array.from({length:e.skeleton.bones.length},()=>new mt(-1/0,-1/0,-1/0));for(let e=0;e<t.count;e+=1){Hr.set(t.getX(e),t.getY(e),t.getZ(e));for(let t=0;t<4;t+=1){if(n.getComponent(e,t)<=0)continue;const s=Math.round(r.getComponent(e,t)),o=i[s],l=a[s];o&&l&&(o.min(Hr),l.max(Hr))}}return i.map((e,t)=>{if(!Number.isFinite(e.x))return null;const r=a[t],n=e.clone().add(r).multiplyScalar(.5);return{center:n,radius:r.distanceTo(n)}})}updateSkinnedBounds(e,t){const r=t.localBoundsMin,n=t.localBoundsMax,i=Fn(e.geometry);r.set(i.center.x-i.radius,i.center.y-i.radius,i.center.z-i.radius),n.set(i.center.x+i.radius,i.center.y+i.radius,i.center.z+i.radius);for(let i=0;i<t.boneBounds.length;i+=1){const a=t.boneBounds[i];if(!a)continue;Wr.fromArray(t.skinning.palette.skeleton.boneMatrices,16*i),_r.multiplyMatrices(e.bindMatrixInverse,Wr).multiply(e.bindMatrix),Hr.copy(a.center).applyMatrix4(_r);const s=a.radius*En(_r);r.min(Kr.copy(Hr).addScalar(-s)),n.max(Kr.copy(Hr).addScalar(s))}t.localBoundsCenter.copy(r).add(n).multiplyScalar(.5),t.localBoundsRadius=n.distanceTo(t.localBoundsCenter)}createGeometryBuffers(e,t,r,n,i,a,s=GPUBufferUsage.VERTEX,o=GPUBufferUsage.VERTEX){if(!this.state.device)throw new Error("Renderer is not initialized.");let l=null,c=null;if(a){const t=a instanceof Uint32Array?a:new Uint16Array(a);c=a instanceof Uint32Array?"uint32":"uint16",l=sn(this.state.device,t,GPUBufferUsage.INDEX,`${e}-index`)}return{position:sn(this.state.device,t,s,`${e}-position`),normal:sn(this.state.device,r,o,`${e}-normal`),uv:sn(this.state.device,n,GPUBufferUsage.VERTEX,`${e}-uv`),color:sn(this.state.device,i,GPUBufferUsage.VERTEX,`${e}-color`),index:l,indexFormat:c}}createVertexBufferLayouts(e){return this.getVertexAttributeGroups(e).map(e=>{let t=0;const r=e.map(e=>{const r={shaderLocation:e.shaderLocation,offset:t,format:e.format};return t+=tn(e.format),r});return{arrayStride:t,stepMode:e[0].stepMode??"vertex",attributes:r}})}getVertexAttributeGroups(e){const t=this.vertexAttributeGroupCache.get(e);if(t)return t;const r=this.state.device?.limits.maxVertexBuffers??8;if(e.length<=r){const t=e.map(e=>[e]);return this.vertexAttributeGroupCache.set(e,t),t}let n=e.length-r;const i=[],a=new Set;for(const t of["vertex","instance"]){if(0===n)break;const r=e.filter(e=>(e.stepMode??"vertex")===t),s=Math.min(r.length,n+1);if(s<2)continue;const o=r.slice(0,s);i.push(o);for(const e of o)a.add(e);n-=s-1}if(n>0)throw new Error(`Vertex attributes cannot be packed into the device's ${r} vertex-buffer slots.`);const s=[];for(const t of e){if(!a.has(t)){s.push([t]);continue}const e=i.find(e=>e[0]===t);e&&s.push(e)}return this.vertexAttributeGroupCache.set(e,s),s}getGeometryAttributeBufferKey(e){const t=this.vertexAttributeBufferKeyCache.get(e);if(void 0!==t)return t;const r=function(e){const t=e.defaultValue?Array.from(e.defaultValue).join(","):"";return`${e.name}:${e.format}:${e.stepMode??"vertex"}:${t}`}(e);return this.vertexAttributeBufferKeyCache.set(e,r),r}getGeometryAttributeGroupBufferKey(e){const t=this.vertexAttributeGroupBufferKeyCache.get(e);if(void 0!==t)return t;const r=e.map(e=>this.getGeometryAttributeBufferKey(e)).join("|");return this.vertexAttributeGroupBufferKeyCache.set(e,r),r}getMaterialVertexAttributes(e,t){const r=e.vertexAttributes.slice();if(!t)return r;const n=[{name:"skinIndex",shaderLocation:4,format:"uint32x4"},{name:"skinWeight",shaderLocation:5,format:"float32x4"}];for(const e of n){const t=r.find(t=>t.name===e.name);if(t){if(t.shaderLocation!==e.shaderLocation||t.format!==e.format)throw new Error(`Skinned material attribute "${e.name}" must use ${e.format} at location ${e.shaderLocation}.`);continue}const n=r.find(t=>t.shaderLocation===e.shaderLocation);if(n)throw new Error(`Skinned material requires location ${e.shaderLocation} for "${e.name}", but it is used by "${n.name}".`);r.push(e)}return r}getGeometryVertexBuffer(e,t,r,n=0,i=1){if(!this.state.device)throw new Error("Renderer is not initialized.");let a=this.standardVertexAttributeCache.get(r);if(void 0===a&&(a="position"===r.name&&"float32x3"===r.format?"position":"normal"!==r.name||"float32x3"!==r.format||void 0!==r.defaultValue&&!cn(r.defaultValue,[0,0,1])?"uv"!==r.name||"float32x2"!==r.format||void 0!==r.defaultValue&&!cn(r.defaultValue,[0,0])?"color"!==r.name||"float32x4"!==r.format||void 0!==r.defaultValue&&!cn(r.defaultValue,[1,1,1,1])?null:"color":"uv":"normal",this.standardVertexAttributeCache.set(r,a)),a)return t[a];const s=e.getAttribute(r.name),o="instance"===r.stepMode,l=o?Math.max(0,Math.trunc(n)):0;if(o&&!s)return this.getDefaultInstanceAttributeBuffer(r,l+Math.max(1,i));const c=Jr(s),u=this.geometryVertexBufferFastCache.get(t),d=u?.get(r),h=d?.get(l);if(h&&h.source===s&&h.version===c&&h.itemSize===(s?.itemSize??0)&&h.count===(s?.count??0))return h.buffer;const p=`${this.getGeometryAttributeBufferKey(r)}${o?`:instance-start=${l}`:""}`,f=s?`${c}:${s.itemSize}:${s.count}`:"default",m=t.extraAttributeBuffers.get(p);if(m&&t.extraAttributeBufferVersions.get(p)===f)return this.cacheGeometryVertexBufferFast(t,r,l,s,c,m),m;if(!s&&!r.defaultValue)throw new Error(`Geometry "${e.uuid}" is missing required vertex attribute "${r.name}".`);const g=hn(s,o?l+Math.max(1,s?.count??1,i):t.vertexCount,r.format,r.defaultValue??[],o?l:0);if(m&&m.size>=Math.max(4,g.byteLength))return this.state.device.queue.writeBuffer(m,0,g.buffer,g.byteOffset,g.byteLength),t.extraAttributeBufferVersions.set(p,f),this.cacheGeometryVertexBufferFast(t,r,l,s,c,m),m;const x=sn(this.state.device,g,GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST,`${e.uuid}-${r.name}-${r.format}`);return m&&(this.clearIndirectBundleCache(),this.retiredGeometryBuffers.push(m)),t.extraAttributeBuffers.set(p,x),t.extraAttributeBufferVersions.set(p,f),this.cacheGeometryVertexBufferFast(t,r,l,s,c,x),x}cacheGeometryVertexBufferFast(e,t,r,n,i,a){let s=this.geometryVertexBufferFastCache.get(e);s||(s=new WeakMap,this.geometryVertexBufferFastCache.set(e,s));let o=s.get(t);o||(o=new Map,s.set(t,o));const l=n;o.set(r,{source:n,version:i,itemSize:l?.itemSize??0,count:l?.count??0,buffer:a})}getInterleavedGeometryVertexBuffer(e,t,r,n,i){if(!this.state.device)throw new Error("Renderer is not initialized.");const a=r[0].stepMode??"vertex",s=Math.max(0,Math.trunc(n)),o="instance"===a?s+Math.max(1,i,...r.map(t=>e.getAttribute(t.name)?.count??1)):t.vertexCount,l=`interleaved:${this.getGeometryAttributeGroupBufferKey(r)}:instance-start=${"instance"===a?s:0}`,c=r.map(t=>{const r=e.getAttribute(t.name);return r?`${Jr(r)}:${r.itemSize}:${r.count}`:"default"}).join("|"),u=t.extraAttributeBuffers.get(l);if(u&&t.extraAttributeBufferVersions.get(l)===c)return u;const d=[];let h=0;for(const e of r)d.push(h),h+=tn(e.format);const p=new Uint8Array(o*h);for(let t=0;t<r.length;t+=1){const n=r[t],i=hn(e.getAttribute(n.name),o,n.format,n.defaultValue??[],"instance"===a?s:0),l=new Uint8Array(i.buffer,i.byteOffset,i.byteLength),c=tn(n.format);for(let e=0;e<o;e+=1)p.set(l.subarray(e*c,(e+1)*c),e*h+d[t])}if(u&&u.size>=Math.max(4,p.byteLength))return this.state.device.queue.writeBuffer(u,0,p.buffer,p.byteOffset,p.byteLength),t.extraAttributeBufferVersions.set(l,c),u;const f=sn(this.state.device,p,GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST,`${e.uuid}-interleaved-${a}`);return u&&(this.clearIndirectBundleCache(),this.retiredGeometryBuffers.push(u)),t.extraAttributeBuffers.set(l,f),t.extraAttributeBufferVersions.set(l,c),f}ensureWireframeIndex(e,t){if(t.wireframeIndex)return;if(!this.state.device)throw new Error("Renderer is not initialized.");const r=e.index?.array,n=r?.length??t.vertexCount,i=Math.floor(n/3),a=t.vertexCount>65535,s=a?new Uint32Array(6*i):new Uint16Array(6*i);for(let e=0;e<i;e+=1){const t=3*e,n=6*e,i=r?r[t]:t,a=r?r[t+1]:t+1,o=r?r[t+2]:t+2;s[n]=i,s[n+1]=a,s[n+2]=a,s[n+3]=o,s[n+4]=o,s[n+5]=i}t.wireframeIndexFormat=a?"uint32":"uint16",t.wireframeIndex=sn(this.state.device,s,GPUBufferUsage.INDEX,`${e.uuid}-wireframe-index`)}bindGeometryVertexBuffers(e,t,r,n,i=0,a=1,s=!1){const o=this.getVertexAttributeGroups(n);for(let n=0;n<o.length;n+=1){const s=o[n];e.setVertexBuffer(n,1===s.length?this.getGeometryVertexBuffer(t,r,s[0],i,a):this.getInterleavedGeometryVertexBuffer(t,r,s,i,a))}s&&r.wireframeIndex&&r.wireframeIndexFormat?e.setIndexBuffer(r.wireframeIndex,r.wireframeIndexFormat):r.index&&r.indexFormat&&e.setIndexBuffer(r.index,r.indexFormat)}getDefaultInstanceAttributeBuffer(e,t){if(!this.state.device)throw new Error("Renderer is not initialized.");const r=Math.max(1,t,Math.ceil(this.state.instanceBufferSize/(Float32Array.BYTES_PER_ELEMENT*Ur))),n=2**Math.ceil(Math.log2(r)),i=`${e.format}:${(e.defaultValue??[]).join(",")}`;let a=this.defaultInstanceAttributeBuffers.get(i);a||(a=new Map,this.defaultInstanceAttributeBuffers.set(i,a));const s=a.get(n);if(s)return s;const o=sn(this.state.device,hn(void 0,n,e.format,e.defaultValue??[]),GPUBufferUsage.VERTEX,`renderer-default-instance-${e.format}`);return a.set(n,o),o}getMeshExtractionCacheEntry(e,t,r,n,i,a){const s=this.meshExtractionCache.get(e),o=Array.isArray(t)?t:null,l=Array.isArray(t)?null:t;if(s&&s.geometryResource===a&&s.customDepthMaterial===i&&(null!==l&&s.material===l&&s.resolvedMaterial===r||null!==o&&null!==s.materials&&null!==s.resolvedMaterials&&an(s.materials,o)&&ln(s.resolvedMaterials,n)))return s;const c=null!==e.geometry.index,u=Fn(e.geometry),d=[];if(e.geometry.groups.length>0)for(const t of e.geometry.groups){const s=o?n[t.materialIndex??0]??n[0]:r;if(!s)continue;const l=pn(e.geometry,c,t.start,t.count),u=Cn(s,e.geometry,c,t.start,l,i),h=Sn(s),p=Sn(e.geometry),f=i?Sn(i):0;d.push({geometry:e.geometry,geometryKey:e.geometry,geometryResource:a,material:s,customDepthMaterial:i,residentInstanceBinding:null,sourceObject:e,usesBatching:!1,geometryGroup:t,batchKey:u,batchHash:Pn(h,p,c,t.start,l,f),indexed:c,wireframe:s.wireframe&&"triangle-list"===s.primitiveTopology,start:t.start,count:l,transparent:s.transparent||s.requiresLatePass(),renderOrder:e.renderOrder,hasRenderCallbacks:this.hasRenderCallbacks(e),castShadow:e.castShadow,receiveShadow:e.receiveShadow,sortMaterialId:h,sortGeometryId:p,sortCustomDepthMaterialId:f})}else{const t=r??n?.[0]??null;if(t){const r=fn(e.geometry,c),n=Cn(t,e.geometry,c,r.start,r.count,i),s=Sn(t),o=Sn(e.geometry),l=i?Sn(i):0;d.push({geometry:e.geometry,geometryKey:e.geometry,geometryResource:a,material:t,customDepthMaterial:i,residentInstanceBinding:null,sourceObject:e,usesBatching:!1,geometryGroup:null,batchKey:n,batchHash:Pn(s,o,c,r.start,r.count,l),indexed:c,wireframe:t.wireframe&&"triangle-list"===t.primitiveTopology,start:r.start,count:r.count,transparent:t.transparent||t.requiresLatePass(),renderOrder:e.renderOrder,hasRenderCallbacks:this.hasRenderCallbacks(e),castShadow:e.castShadow,receiveShadow:e.receiveShadow,sortMaterialId:s,sortGeometryId:o,sortCustomDepthMaterialId:l})}}const h={geometryResource:a,material:l,materials:o?o.slice():null,resolvedMaterial:r,resolvedMaterials:o?n.slice():null,customDepthMaterial:i,indexed:c,templates:d,localBoundsCenter:u.center.clone(),localBoundsRadius:u.radius};return this.meshExtractionCache.set(e,h),h}getInstancedMeshExtractionCacheEntry(e,t,r,n){const i=null!==e.geometry.index,a=fn(e.geometry,i),s=Fn(e.geometry),o=this.instancedMeshExtractionCache.get(e);if(o&&o.geometryResource===n&&o.material===t&&o.customDepthMaterial===r&&o.indexed===i&&o.drawRangeStart===a.start&&o.drawRangeCount===a.count)return o.sourceMaterial=e.material,o.sourceMaterialVersion=e.material.version,o;o?.residentInstanceBinding?.buffer?.destroy(),o?.residentInstanceBinding?.colorBuffer?.destroy();const l=Sn(t),c=Sn(e.geometry),u=r?Sn(r):0,d={geometryResource:n,sourceMesh:e,sourceMaterial:e.material,sourceMaterialVersion:e.material.version,material:t,customDepthMaterial:r,indexed:i,drawRangeStart:a.start,drawRangeCount:a.count,batchKey:Cn(t,e,i,a.start,a.count,r),batchHash:Pn(l,c,i,a.start,a.count,u),sortMaterialId:l,sortGeometryId:c,sortCustomDepthMaterialId:u,localBoundsCenter:s.center.clone(),localBoundsRadius:s.radius,cachedInstanceData:new Mi(1024),cachedBoundsMin:new mt,cachedBoundsMax:new mt,cachedDrawBoundsCenter:new mt,cachedDrawBoundsRadius:0,cachedMatrixWorld:new Float64Array(16),cachedInstanceMatrixVersion:-1,cachedInstanceColorVersion:-1,cachedCount:0,cachedDefaultColorData:null,residentInstanceBinding:{mode:"packed",buffer:null,colorBuffer:null,sceneBindGroup:null,shadowBindGroup:null,shadowBindGroups:new Map,sceneBindGroupVersion:0,shadowBindGroupVersion:0},residentBufferSize:0,residentColorBufferSize:0,residentBufferDirty:!1,residentColorBufferDirty:!1,cacheValid:!1};return this.instancedMeshExtractionCache.set(e,d),d}getBatchedMeshExtractionCacheEntry(e,t,r,n,i){const a=i._geometryCount??0,s=this.batchedMeshExtractionCache.get(e);if(s&&s.geometryResource===n&&s.material===t&&s.customDepthMaterial===r&&s.indexed===(null!==e.geometry.index)&&s.cachedGeometryCount===a)return s;s?.residentInstanceBinding?.buffer?.destroy(),s?.residentInstanceBinding?.colorBuffer?.destroy();const o=null!==e.geometry.index,l=new Array(a).fill(null),c=new Array(a).fill(null);for(let i=0;i<a;i+=1){const a=e.getGeometryRangeAt(i);if(!a||a.count<=0)continue;const s=pn(e.geometry,o,a.start,a.count),u=Cn(t,e.geometry,o,a.start,s,r),d=Sn(t),h=Sn(e.geometry),p=r?Sn(r):0,f=e.getBoundingSphereAt(i,qr),m={geometry:e.geometry,geometryKey:e.geometry,geometryResource:n,material:t,customDepthMaterial:r,residentInstanceBinding:null,sourceObject:e,usesBatching:!0,geometryGroup:null,batchKey:u,batchHash:Pn(d,h,o,a.start,s,p),indexed:o,wireframe:t.wireframe&&"triangle-list"===t.primitiveTopology,start:a.start,count:s,transparent:t.transparent||t.requiresLatePass(),renderOrder:e.renderOrder,hasRenderCallbacks:this.hasRenderCallbacks(e),castShadow:e.castShadow,receiveShadow:e.receiveShadow,sortMaterialId:d,sortGeometryId:h,sortCustomDepthMaterialId:p,geometryId:i,localBoundsCenter:f?f.center.clone():new mt,localBoundsRadius:f?.radius??1};l[i]=m,c[i]={template:m,boundsMin:new mt,boundsMax:new mt,activeInFrame:!1,activeCount:0,instanceStart:0,writeOffset:0}}const u={geometryResource:n,material:t,customDepthMaterial:r,indexed:o,templates:l,groups:c,activeGroups:[],cachedInstanceData:new Mi(1024),cachedDraws:[],cachedBoundsMin:new mt,cachedBoundsMax:new mt,cachedMatrixWorld:new Float64Array(16),geometryIdsSnapshot:new Int32Array(0),cachedMatricesVersion:-1,cachedColorsVersion:-1,cachedGeometryCount:a,cachedInstanceInfoLength:0,residentInstanceBinding:{mode:"packed",buffer:null,colorBuffer:null,sceneBindGroup:null,shadowBindGroup:null,shadowBindGroups:new Map,sceneBindGroupVersion:0,shadowBindGroupVersion:0},residentBufferSize:0,residentColorBufferSize:0,residentBufferDirty:!1,residentColorBufferDirty:!1,cacheValid:!1};return this.batchedMeshExtractionCache.set(e,u),u}batchedGeometryIdsMatchSnapshot(e,t){if(e.length!==t.length)return!1;for(let r=0;r<t.length;r+=1){const n=t[r];if((e[r]??-1)!==(n?.active&&n.visible?n.geometryIndex:-1))return!1}return!0}destroyGeometryResource(e){e.position.destroy(),e.normal.destroy(),e.uv.destroy(),e.color.destroy();for(const t of e.extraAttributeBuffers.values())t.destroy();e.extraAttributeBuffers.clear(),e.extraAttributeBufferVersions.clear(),e.index?.destroy(),e.wireframeIndex?.destroy()}retireGeometryResource(e){this.retiredGeometryResources.push(e)}releaseRetiredGeometryResourcesAfterSubmit(){const e=this.retiredGeometryResources.splice(0),t=this.retiredGeometryBuffers.splice(0);if(0!==e.length||0!==t.length)if(this.state.device)this.state.device.queue.onSubmittedWorkDone().then(()=>{for(const t of e)this.destroyGeometryResource(t);for(const e of t)e.destroy()},()=>{for(const t of e)this.destroyGeometryResource(t);for(const e of t)e.destroy()});else{for(const t of e)this.destroyGeometryResource(t);for(const e of t)e.destroy()}}destroyTextureResource(e){this.textureManager.destroyTextureResource(e)}createTextureSampler(e,t){return this.textureManager.createTextureSampler(e,t)}uploadDataTextureResource(e,t,r){this.textureManager.uploadDataTextureResource(e,t,r)}uploadCompressedTextureResource(e,t,r){this.textureManager.uploadCompressedTextureResource(e,t,r)}uploadExternalTextureResource(e,t,r){this.textureManager.uploadExternalTextureResource(e,t,r)}uploadTextureResource(e,t,r){this.textureManager.uploadTextureResource(e,t,r)}getTextureResource(e){return this.textureManager.getTextureResource(e)}updateMaterialUniformBuffer(e,t){if(!this.state.device||!t.uniformBuffer||0===Object.keys(e.uniforms).length)return;const r=e.getUniformLayout(),n=e.getUniformValueHash();if(t.uniformValueHash===n)return;const i=Ne(e.uniforms,r);!t.uniformBuffer||i.byteLength>t.uniformBuffer.size||(t.uniformValueHash=n,this.state.device.queue.writeBuffer(t.uniformBuffer,0,i))}materialResourceMatches(e,t,r,n=this.sampleCount){if(e.key!==r)return!1;if(e.materialVersion===t.version&&e.textureVersionHash===t.getTextureVersionHash()&&e.rendererSampleCount===n&&e.uniformBufferSize===t.getUniformLayout().byteLength)return!0;const i=ln(e.textures,t.getTexturesList())&&cn(e.textureVersions,t.getTextureVersionsList())&&ln(e.storageBuffers,t.getStorageBufferList())&&e.rendererSampleCount===n&&e.uniformBufferSize===t.getUniformLayout().byteLength;return i&&(e.materialVersion=t.version,e.textureVersionHash=t.getTextureVersionHash()),i}destroyMaterialResource(e){e?.uniformBuffer?.destroy()}createMaterialBindGroupData(e,t,r){if(!this.state.device)throw new Error("Renderer is not initialized.");const n=[],i=[],a=Array.from(e.getTexturesList()),s=Array.from(e.getTextureVersionsList()),o=e.getStorageBufferBindingList();let l=null;if(Object.keys(e.uniforms).length>0){const r=Ne(e.uniforms,e.getUniformLayout());l=this.state.device.createBuffer({label:`${t}-uniforms`,size:r.byteLength,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this.state.device.queue.writeBuffer(l,0,r),n.push({binding:0,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}}),i.push({binding:0,resource:{buffer:l}})}for(const[e,t]of a.entries()){const a=1+2*e,s=this.getTextureResource(t);n.push({binding:a,visibility:r,sampler:{type:s.samplerBindingType}},{binding:a+1,visibility:r,texture:{sampleType:s.sampleType,viewDimension:s.viewDimension}}),i.push({binding:a,resource:s.sampler},{binding:a+1,resource:s.view})}const c=1+2*a.length,u=Array.from(e.getStorageBufferList());for(const[e,t]of o.entries()){const r=c+e;n.push({binding:r,visibility:on(t.visibility),buffer:{type:"read-only-storage"}}),i.push({binding:r,resource:{buffer:t.buffer}})}return{bindGroupLayoutEntries:n,bindGroupEntries:i,uniformBuffer:l,textures:a,textureVersions:s,storageBuffers:u}}createGraphTextureBindGroupLayout(e){if(!this.state.device)throw new Error("Renderer is not initialized.");const t=[];return Object.values(e.getGraphTextureInputs()).forEach((e,r)=>{t.push({binding:2*r,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,sampler:{type:e.sampler??("depth-2d"===e.dimension?"non-filtering":"filtering")}},{binding:2*r+1,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,texture:{sampleType:e.sampleType??("depth-2d"===e.dimension?"depth":"float"),viewDimension:"3d"===e.dimension?"3d":"2d"}})}),this.state.device.createBindGroupLayout({label:`${e.uuid}-graph-textures-layout`,entries:t})}createGraphTextureBindGroup(e,t){if(!(this.state.device&&this.state.linearClampSampler&&this.state.nearestClampSampler&&this.state.shadowComparisonSampler))throw new Error("Renderer graph texture bindings are not initialized.");let r=this.graphTextureBindGroupCache.get(e);const n=r?.get(t);if(n&&n.materialVersion===e.version&&n.resourceVersion===this.graphTextureResourceVersion)return n.bindGroup;const i=[];Object.values(e.getGraphTextureInputs()).forEach((e,t)=>{const r="comparison"===e.sampler?this.state.shadowComparisonSampler:"non-filtering"===e.sampler||"depth-2d"===e.dimension?this.state.nearestClampSampler:this.state.linearClampSampler,n="mainDepth"===e.resource?this.state.sceneDepthSnapshotView:this.getGraphTextureView(e.resource);i.push({binding:2*t,resource:r},{binding:2*t+1,resource:n})});const a=this.state.device.createBindGroup({label:`${e.uuid}-graph-textures`,layout:t,entries:i});return r||(r=new WeakMap,this.graphTextureBindGroupCache.set(e,r)),r.set(t,{materialVersion:e.version,resourceVersion:this.graphTextureResourceVersion,bindGroup:a}),a}getGraphTextureView(e){return"mainDepth"===e?this.state.mainDepthView:"sceneColorSnapshot"===e?this.state.sceneColorSnapshotView:"sceneDepthSnapshot"===e?this.state.sceneDepthSnapshotView:this.getColorTargetView(e)}compileDrawMaterials(e){const t=new Set;for(const r of e){const e=this.getDrawInstanceAccessMode(r),n=null!==r.skinning,i=this.drawUsesBatching(r),a=`${r.material.uuid}:${e}:receiveShadow=${r.receiveShadow?1:0}:skinning=${n?1:0}:batching=${i?1:0}`;t.has(a)||(r.materialResource=this.getMaterialResource(r.material,e,r.receiveShadow,void 0,n,i),t.add(a))}}async compileDrawMaterialsAsync(e,t=[Er],r=this.sampleCount){const n=new Set,i=new Set,a=[];for(const s of e){const e=this.getDrawInstanceAccessMode(s),o=null!==s.skinning,l=this.drawUsesBatching(s),c=`${s.material.uuid}:${e}:receiveShadow=${s.receiveShadow?1:0}:skinning=${o?1:0}:batching=${l?1:0}`;if(n.has(c)||(a.push(this.getMaterialResourceAsync(s.material,e,s.receiveShadow,t,o,l,r).then(e=>(s.materialResource=e,e))),n.add(c)),s.customDepthMaterial){const t=`${s.customDepthMaterial.uuid}:${e}:skinning=${o?1:0}`;i.has(t)||(a.push(this.getDepthPassMaterialResourceAsyncForDraw(s.customDepthMaterial,"directionalShadow",s)),i.add(t))}if(null!==s.material.depthVertexShader||l){const t=null!==s.material.depthVertexShader?["prepass","directionalShadow","pointShadow"]:["prepass","directionalShadow"];for(const r of t){const t=`${s.material.uuid}:${r}:${e}:skinning=${o?1:0}:batching=${l?1:0}`;i.has(t)||(a.push(this.getDepthPassMaterialResourceAsyncForDraw(s.material,r,s)),i.add(t))}}}await Promise.all(a)}async compileStaticDrawMaterialsAsync(e,t=this.sampleCount){const r=[],n=new Set;for(const i of this.staticDrawSets)if(i.publicSet.enabled){r.push(this.compileDrawMaterialsAsync(i.draws,e,t));for(const a of i.visibleMaterialBindings){const i=`${a.material.uuid}:receiveShadow=${a.receiveShadow?1:0}:batching=${a.usesBatching?1:0}`;n.has(i)||(n.add(i),r.push(this.getMaterialResourceAsync(a.material,"packed-visible",a.receiveShadow,e,!1,a.usesBatching,t)))}}await Promise.all(r)}getDepthPassMaterialKey(e,t,r,n,i){if(!this.state.device)throw new Error("Renderer is not initialized.");return`${e.customProgramCacheKey()}:${t}:instance=${r}:skinning=${n?1:0}:batching=${i?1:0}:textures=${e.getTextureLayoutKey(this.state.device)}`}getForwardMaterialKey(e,t,r,n,i,a,s=this.sampleCount){return`${e.customProgramCacheKey()}:instance=${t}:receiveShadow=${r?1:0}:skinning=${i?1:0}:batching=${a?1:0}:textures=${e.getTextureLayoutKey(this.state.device)}:samples=${s}:targets=${n.join("|")}`}getInstanceAccessModeIndex(e){return"packed"===e?0:"packed-visible"===e?1:2}getForwardMaterialFastCacheIndex(e,t,r,n){return this.getInstanceAccessModeIndex(e)|(t?4:0)|(r?8:0)|(n?16:0)}getDepthMaterialFastCacheIndex(e,t,r,n){return("prepass"===e?0:"directionalShadow"===e?1:2)+3*this.getInstanceAccessModeIndex(t)+(r?9:0)+(n?18:0)}fastMaterialResourceMatches(e,t,r=this.sampleCount){return e.materialVersion===t.version&&e.textureVersionHash===t.getTextureVersionHash()&&e.rendererSampleCount===r}setForwardMaterialFastCache(e,t,r){let n=this.forwardMaterialFastCache.get(e);n||(n=[],this.forwardMaterialFastCache.set(e,n)),n[t]=r}getForwardMaterialTargetFastCacheKey(e,t){return`${t}:${e.join("|")}`}setForwardMaterialTargetFastCache(e,t,r){let n=this.forwardMaterialTargetFastCache.get(e);n||(n=new Map,this.forwardMaterialTargetFastCache.set(e,n)),n.set(t,r)}setForwardMaterialFrameCache(e,t,r){let n=this.forwardMaterialFrameCache.get(e);n||(n=[],this.forwardMaterialFrameCache.set(e,n)),n[t]={extractionVersion:this.extractionVersion,resource:r}}setDepthMaterialFastCache(e,t,r){let n=this.depthMaterialFastCache.get(e);n||(n=[],this.depthMaterialFastCache.set(e,n)),n[t]=r}getDrawInstanceAccessMode(e){return"instanced-direct"===e.residentInstanceBinding?.mode?"instanced-direct":"packed"}drawUsesBatching(e){return e.usesBatching}buildMaterialShaderCode(e,t,r,n,i=!1,a=!1){return wt(`${t}\n${r}`,this.createMaterialPreprocessorDefines(e,n,i,a),{sourceName:n})}createMaterialPreprocessorDefines(e,t,r=!1,n=!1){const i={HIGH_PRECISION:!0,WEBGPU_RENDERER:!0,WGSL_SHADER_MATERIAL:!0,USE_BATCHING:n,USE_COLOR:!0,USE_COLOR_ALPHA:!0,NUM_DIR_LIGHTS:4,NUM_POINT_LIGHTS:4,NUM_SPOT_LIGHTS:4,NUM_DIR_LIGHT_SHADOWS:4,NUM_POINT_LIGHT_SHADOWS:4,NUM_SPOT_LIGHT_SHADOWS:4,NUM_CLIPPING_PLANES:0,UNION_CLIPPING_PLANES:0,USE_SKINNING:r,...this.createTexturePreprocessorDefines(e)};return e.side===it?i.DOUBLE_SIDED=!0:e.side===et&&(i.FLIP_SIDED=!0),!t.includes("receiveShadow=1")&&t.includes("receiveShadow=0")||(i.USE_SHADOWMAP=!0,i.SHADOWMAP_TYPE_PCF=!0),{...i,...e.defines,USE_BATCHING:n}}createTexturePreprocessorDefines(e){const t={},r={map:"USE_MAP",matcap:"USE_MATCAP",lightMap:"USE_LIGHTMAP",aoMap:"USE_AOMAP",bumpMap:"USE_BUMPMAP",normalMap:"USE_NORMALMAP",displacementMap:"USE_DISPLACEMENTMAP",emissiveMap:"USE_EMISSIVEMAP",anisotropyMap:"USE_ANISOTROPYMAP",clearcoatMap:"USE_CLEARCOATMAP",clearcoatRoughnessMap:"USE_CLEARCOAT_ROUGHNESSMAP",clearcoatNormalMap:"USE_CLEARCOAT_NORMALMAP",iridescenceMap:"USE_IRIDESCENCEMAP",iridescenceThicknessMap:"USE_IRIDESCENCE_THICKNESSMAP",specularMap:"USE_SPECULARMAP",specularColorMap:"USE_SPECULAR_COLORMAP",specularIntensityMap:"USE_SPECULAR_INTENSITYMAP",roughnessMap:"USE_ROUGHNESSMAP",metalnessMap:"USE_METALNESSMAP",alphaMap:"USE_ALPHAMAP",sheenColorMap:"USE_SHEEN_COLORMAP",sheenRoughnessMap:"USE_SHEEN_ROUGHNESSMAP",transmissionMap:"USE_TRANSMISSIONMAP",thicknessMap:"USE_THICKNESSMAP"};for(const[n,i]of Object.entries(r))e.textures[n]&&(t[i]=!0);return t}shouldInvalidateDrawMaterialResource(e,t,r,n,i){return!!e.materialResource&&(e.material!==t||e.receiveShadow!==r||e.usesBatching!==n||e.skinning!==i)}cachedDrawMaterialResourceMatches(e,t,r,n=this.sampleCount){const i=this.getDrawInstanceAccessMode(e),a=null!==e.skinning,s=this.drawUsesBatching(e),o=1===r.length&&r[0]===Er?Er:r.join("|");return t.instanceAccessMode===i&&t.receiveShadow===e.receiveShadow&&t.useBatching===s&&t.usesSkinning===a&&t.rendererSampleCount===n&&t.colorTargetFormatsKey===o&&(t.materialVersion===e.material.version&&t.textureVersionHash===e.material.getTextureVersionHash()||this.materialResourceMatches(t,e.material,t.key,n))}getMaterialResourceForDraw(e,t=[Er],r=this.sampleCount){const n=e.materialResource;if(n&&this.cachedDrawMaterialResourceMatches(e,n,t,r))return this.updateMaterialUniformBuffer(e.material,n),n;const i=this.getDrawInstanceAccessMode(e),a=null!==e.skinning,s=this.drawUsesBatching(e),o=this.getMaterialResource(e.material,i,e.receiveShadow,t,a,s,r);return e.materialResource=o,o}getMaterialResourceAsyncForDraw(e){return this.getMaterialResourceAsync(e.material,this.getDrawInstanceAccessMode(e),e.receiveShadow,void 0,null!==e.skinning,this.drawUsesBatching(e))}resolveForwardMaterialResources(e){for(let t=0;t<e.length;t+=1){const r=e[t];r.materialResource=this.getMaterialResource(r.material,this.getDrawInstanceAccessMode(r),r.receiveShadow,void 0,null!==r.skinning,this.drawUsesBatching(r))}}getDepthPassMaterialResourceForDraw(e,t,r){return this.getDepthPassMaterialResource(e,t,this.getDrawInstanceAccessMode(r),null!==r.skinning,this.drawUsesBatching(r))}getDepthPassMaterialResourceAsyncForDraw(e,t,r){return this.getDepthPassMaterialResourceAsync(e,t,this.getDrawInstanceAccessMode(r),null!==r.skinning,this.drawUsesBatching(r))}getOrCreateSharedDepthPipeline(e,t,r,n,i,a,s){if(!(this.state.device&&this.state.shadowBindGroupLayout&&this.state.directShadowBindGroupLayout&&this.state.skinningBindGroupLayout))throw new Error("Renderer is not initialized.");const o=this.sharedDepthPipelineCache.get(e);if(o)return o;const l=this.state.device.createBindGroupLayout({label:`${e}-shared-depth-material-layout`,entries:i}),c="prepass"===r?"instanced-direct"===n?this.state.directSceneBindGroupLayout:this.state.sceneBindGroupLayout:"instanced-direct"===n?this.state.directShadowBindGroupLayout:this.state.shadowBindGroupLayout,u=this.state.device.createPipelineLayout({label:`${e}-shared-depth-pipeline-layout`,bindGroupLayouts:[c,l,...a?[this.state.skinningBindGroupLayout]:[]]}),d=pr(t,"prepass"===r?"camera":"shadow",this.state.device,n,a),h=this.buildMaterialShaderCode(t,d,"pointShadow"===r?t.pointShadowVertexShader??t.vertexShader:t.depthVertexShader??t.vertexShader,`${e}-shared-depth-vertex`,a,s),p="pointShadow"===r?t.pointShadowFragmentShader:t.depthFragmentShader,f=p?this.buildMaterialShaderCode(t,d,p,`${e}-shared-depth-fragment`,a,s):null,m={bindGroupLayout:l,pipeline:this.state.device.createRenderPipeline({label:`${e}-shared-depth-pipeline`,layout:u,vertex:{module:this.state.device.createShaderModule({label:`${e}-shared-depth-vertex`,code:h}),entryPoint:"vsMain",buffers:this.createVertexBufferLayouts(this.getMaterialVertexAttributes(t,a))},...f?{fragment:{module:this.state.device.createShaderModule({label:`${e}-shared-depth-fragment`,code:f}),entryPoint:"fsMain",targets:"pointShadow"===r?[{format:"rgba16float"}]:[]}}:{},primitive:{topology:$i(t),cullMode:ji(t,r,s),frontFace:"ccw"},depthStencil:{format:"depth32float",depthWriteEnabled:!0,depthCompare:"less",..."directionalShadow"===r?{depthBias:1,depthBiasSlopeScale:2,depthBiasClamp:0}:{}}})};return this.sharedDepthPipelineCache.set(e,m),m}async getOrCreateSharedDepthPipelineAsync(e,t,r,n,i,a,s){if(!(this.state.device&&this.state.sceneBindGroupLayout&&this.state.directSceneBindGroupLayout&&this.state.shadowBindGroupLayout&&this.state.directShadowBindGroupLayout&&this.state.skinningBindGroupLayout))throw new Error("Renderer is not initialized.");const o=this.sharedDepthPipelineCache.get(e);if(o)return o;const l=this.sharedDepthPipelinePromiseCache.get(e);if(l)return l;const c=(async()=>{const o=this.state.device.createBindGroupLayout({label:`${e}-shared-depth-material-layout`,entries:i}),l="prepass"===r?"instanced-direct"===n?this.state.directSceneBindGroupLayout:this.state.sceneBindGroupLayout:"instanced-direct"===n?this.state.directShadowBindGroupLayout:this.state.shadowBindGroupLayout,c=this.state.device.createPipelineLayout({label:`${e}-shared-depth-pipeline-layout`,bindGroupLayouts:[l,o,...a?[this.state.skinningBindGroupLayout]:[]]}),u=pr(t,"prepass"===r?"camera":"shadow",this.state.device,n,a),d=this.buildMaterialShaderCode(t,u,"pointShadow"===r?t.pointShadowVertexShader??t.vertexShader:t.depthVertexShader??t.vertexShader,`${e}-shared-depth-vertex`,a,s),h="pointShadow"===r?t.pointShadowFragmentShader:t.depthFragmentShader,p=h?this.buildMaterialShaderCode(t,u,h,`${e}-shared-depth-fragment`,a,s):null,f={bindGroupLayout:o,pipeline:await this.state.device.createRenderPipelineAsync({label:`${e}-shared-depth-pipeline`,layout:c,vertex:{module:this.state.device.createShaderModule({label:`${e}-shared-depth-vertex`,code:d}),entryPoint:"vsMain",buffers:this.createVertexBufferLayouts(this.getMaterialVertexAttributes(t,a))},...p?{fragment:{module:this.state.device.createShaderModule({label:`${e}-shared-depth-fragment`,code:p}),entryPoint:"fsMain",targets:"pointShadow"===r?[{format:"rgba16float"}]:[]}}:{},primitive:{topology:$i(t),cullMode:ji(t,r,s),frontFace:"ccw"},depthStencil:{format:"depth32float",depthWriteEnabled:!0,depthCompare:"less",..."directionalShadow"===r?{depthBias:1,depthBiasSlopeScale:2,depthBiasClamp:0}:{}}})};return this.sharedDepthPipelineCache.set(e,f),this.sharedDepthPipelinePromiseCache.delete(e),f})();return this.sharedDepthPipelinePromiseCache.set(e,c),c}getOrCreateSharedForwardPipeline(e,t,r,n,i,a,s,o,l=this.sampleCount){if(!(this.state.device&&this.state.format&&this.state.sceneBindGroupLayout&&this.state.visibleSceneBindGroupLayout&&this.state.directSceneBindGroupLayout&&this.state.skinningBindGroupLayout&&this.state.emptyBindGroupLayout))throw new Error("Renderer is not initialized.");const c=this.sharedForwardPipelineCache.get(e);if(c)return c;const u=this.state.device.createBindGroupLayout({label:`${e}-shared-forward-material-layout`,entries:n}),d=this.createGraphTextureBindGroupLayout(t),h=this.state.device.createPipelineLayout({label:`${e}-shared-forward-pipeline-layout`,bindGroupLayouts:["instanced-direct"===r?this.state.directSceneBindGroupLayout:"packed-visible"===r?this.state.visibleSceneBindGroupLayout:this.state.sceneBindGroupLayout,u,s?this.state.skinningBindGroupLayout:this.state.emptyBindGroupLayout,d]}),p=hr(t,this.state.device,r,i,s),f=this.buildMaterialShaderCode(t,p,t.vertexShader,`${e}-shared-forward-vertex`,s,o),m=this.buildMaterialShaderCode(t,p,t.fragmentShader,`${e}-shared-forward-fragment`,s,o),g={bindGroupLayout:u,graphTextureBindGroupLayout:d,pipeline:this.state.device.createRenderPipeline({label:`${e}-shared-forward-pipeline`,layout:h,vertex:{module:this.state.device.createShaderModule({label:`${e}-shared-forward-vertex`,code:f}),entryPoint:"vsMain",buffers:this.createVertexBufferLayouts(this.getMaterialVertexAttributes(t,s))},fragment:{module:this.state.device.createShaderModule({label:`${e}-shared-forward-fragment`,code:m}),entryPoint:"fsMain",targets:Ei(m,a,Ai(t))},primitive:{topology:$i(t),cullMode:$i(t).startsWith("triangle")&&t.side!==it?t.side===et?"front":"back":"none",frontFace:"ccw"},multisample:{count:l},depthStencil:{format:"depth32float",depthWriteEnabled:t.depthWrite,depthCompare:t.depthTest?"less-equal":"always"}})};return this.sharedForwardPipelineCache.set(e,g),g}async getOrCreateSharedForwardPipelineAsync(e,t,r,n,i,a,s,o,l=this.sampleCount){if(!(this.state.device&&this.state.format&&this.state.sceneBindGroupLayout&&this.state.visibleSceneBindGroupLayout&&this.state.directSceneBindGroupLayout&&this.state.skinningBindGroupLayout&&this.state.emptyBindGroupLayout))throw new Error("Renderer is not initialized.");const c=this.sharedForwardPipelineCache.get(e);if(c)return c;const u=this.sharedForwardPipelinePromiseCache.get(e);if(u)return u;const d=(async()=>{const c=this.state.device.createBindGroupLayout({label:`${e}-shared-forward-material-layout`,entries:n}),u=this.createGraphTextureBindGroupLayout(t),d=this.state.device.createPipelineLayout({label:`${e}-shared-forward-pipeline-layout`,bindGroupLayouts:["instanced-direct"===r?this.state.directSceneBindGroupLayout:"packed-visible"===r?this.state.visibleSceneBindGroupLayout:this.state.sceneBindGroupLayout,c,s?this.state.skinningBindGroupLayout:this.state.emptyBindGroupLayout,u]}),h=hr(t,this.state.device,r,i,s),p=this.buildMaterialShaderCode(t,h,t.vertexShader,`${e}-shared-forward-vertex`,s,o),f=this.buildMaterialShaderCode(t,h,t.fragmentShader,`${e}-shared-forward-fragment`,s,o),m={bindGroupLayout:c,graphTextureBindGroupLayout:u,pipeline:await this.state.device.createRenderPipelineAsync({label:`${e}-shared-forward-pipeline`,layout:d,vertex:{module:this.state.device.createShaderModule({label:`${e}-shared-forward-vertex`,code:p}),entryPoint:"vsMain",buffers:this.createVertexBufferLayouts(this.getMaterialVertexAttributes(t,s))},fragment:{module:this.state.device.createShaderModule({label:`${e}-shared-forward-fragment`,code:f}),entryPoint:"fsMain",targets:Ei(f,a,Ai(t))},primitive:{topology:$i(t),cullMode:$i(t).startsWith("triangle")&&t.side!==it?t.side===et?"front":"back":"none",frontFace:"ccw"},multisample:{count:l},depthStencil:{format:"depth32float",depthWriteEnabled:t.depthWrite,depthCompare:t.depthTest?"less-equal":"always"}})};return this.sharedForwardPipelineCache.set(e,m),this.sharedForwardPipelinePromiseCache.delete(e),m})();return this.sharedForwardPipelinePromiseCache.set(e,d),d}getDepthPassMaterialResource(e,t,r,n,i){if(!(this.state.device&&this.state.shadowBindGroupLayout&&this.state.directShadowBindGroupLayout&&this.state.skinningBindGroupLayout))throw new Error("Renderer is not initialized.");if("prepass"===t&&null===e.depthVertexShader&&!i||"pointShadow"===t&&(null===e.pointShadowVertexShader||null===e.pointShadowFragmentShader))return null;const a=this.getDepthMaterialFastCacheIndex(t,r,n,i),s=this.depthMaterialFastCache.get(e)?.[a];if(s&&this.fastMaterialResourceMatches(s,e))return this.updateMaterialUniformBuffer(e,s),s;const o=`${t}:${r}:${n?1:0}:${i?1:0}`,l=this.depthMaterialFrameCache.get(e),c=l?.get(o);if(c?.extractionVersion===this.extractionVersion)return c.resource;const u="prepass"===t?this.depthPrepassMaterialCache:n?this.skinnedDirectionalShadowMaterialCache:"instanced-direct"===r?this.directionalShadowMaterialCacheDirect:this.directionalShadowMaterialCache,d=this.getDepthPassMaterialKey(e,t,r,n,i),h=u.get(e),p=h?.get(d);if(p&&this.materialResourceMatches(p,e,d))return this.setDepthMaterialFastCache(e,a,p),this.updateMaterialUniformBuffer(e,p),this.setDepthMaterialFrameCache(e,o,p),p;this.destroyMaterialResource(p),h&&h.delete(d);const{bindGroupLayoutEntries:f,bindGroupEntries:m,uniformBuffer:g,textures:x,textureVersions:v,storageBuffers:w}=this.createMaterialBindGroupData(e,`${e.uuid}-${t}-${r}-material`,GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT),b=this.getOrCreateSharedDepthPipeline(d,e,t,r,f,n,i),y=this.state.device.createBindGroup({label:`${e.uuid}-${t}-${r}-material-bind-group`,layout:b.bindGroupLayout,entries:m}),S={key:d,materialVersion:e.version,textureVersionHash:e.getTextureVersionHash(),rendererSampleCount:this.sampleCount,instanceAccessMode:r,receiveShadow:!0,useBatching:i,colorTargetFormatsKey:"",pipeline:b.pipeline,graphTextureBindGroupLayout:b.graphTextureBindGroupLayout,bindGroup:y,uniformBuffer:g,uniformBufferSize:g?.size??0,uniformValueHash:e.getUniformValueHash(),textures:x,textureVersions:v,storageBuffers:w,vertexAttributes:this.getMaterialVertexAttributes(e,n),usesSkinning:n};let C=u.get(e);return C||(C=new Map,u.set(e,C)),C.set(d,S),this.setDepthMaterialFastCache(e,a,S),this.setDepthMaterialFrameCache(e,o,S),S}setDepthMaterialFrameCache(e,t,r){let n=this.depthMaterialFrameCache.get(e);n||(n=new Map,this.depthMaterialFrameCache.set(e,n)),n.set(t,{extractionVersion:this.extractionVersion,resource:r})}async getDepthPassMaterialResourceAsync(e,t,r,n,i){if(!(this.state.device&&this.state.sceneBindGroupLayout&&this.state.directSceneBindGroupLayout&&this.state.shadowBindGroupLayout&&this.state.directShadowBindGroupLayout&&this.state.skinningBindGroupLayout))throw new Error("Renderer is not initialized.");if("prepass"===t&&null===e.depthVertexShader&&!i||"pointShadow"===t&&(null===e.pointShadowVertexShader||null===e.pointShadowFragmentShader))return null;const a=this.getDepthMaterialFastCacheIndex(t,r,n,i),s=this.depthMaterialFastCache.get(e)?.[a];if(s&&this.fastMaterialResourceMatches(s,e))return this.updateMaterialUniformBuffer(e,s),s;const o="prepass"===t?this.depthPrepassMaterialCache:n?this.skinnedDirectionalShadowMaterialCache:"instanced-direct"===r?this.directionalShadowMaterialCacheDirect:this.directionalShadowMaterialCache,l=this.getDepthPassMaterialKey(e,t,r,n,i),c=o.get(e),u=c?.get(l);if(u&&this.materialResourceMatches(u,e,l))return this.setDepthMaterialFastCache(e,a,u),this.updateMaterialUniformBuffer(e,u),u;this.destroyMaterialResource(u),c&&c.delete(l);const{bindGroupLayoutEntries:d,bindGroupEntries:h,uniformBuffer:p,textures:f,textureVersions:m,storageBuffers:g}=this.createMaterialBindGroupData(e,`${e.uuid}-${t}-${r}-material`,GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT),x=await this.getOrCreateSharedDepthPipelineAsync(l,e,t,r,d,n,i),v=this.state.device.createBindGroup({label:`${e.uuid}-${t}-${r}-material-bind-group`,layout:x.bindGroupLayout,entries:h}),w={key:l,materialVersion:e.version,textureVersionHash:e.getTextureVersionHash(),rendererSampleCount:this.sampleCount,instanceAccessMode:r,receiveShadow:!0,useBatching:i,colorTargetFormatsKey:"",pipeline:x.pipeline,graphTextureBindGroupLayout:x.graphTextureBindGroupLayout,bindGroup:v,uniformBuffer:p,uniformBufferSize:p?.size??0,uniformValueHash:e.getUniformValueHash(),textures:f,textureVersions:m,storageBuffers:g,vertexAttributes:this.getMaterialVertexAttributes(e,n),usesSkinning:n};let b=o.get(e);return b||(b=new Map,o.set(e,b)),b.set(l,w),this.setDepthMaterialFastCache(e,a,w),w}getMaterialResource(e,t,r=!0,n,i=!1,a=!1,s=this.sampleCount){if(!(this.state.device&&this.state.format&&this.state.sceneBindGroupLayout&&this.state.visibleSceneBindGroupLayout&&this.state.directSceneBindGroupLayout))throw new Error("Renderer is not initialized.");const o=i?r?this.skinnedMaterialCache:this.skinnedMaterialNoReceiveShadowCache:r?"instanced-direct"===t?this.materialCacheDirect:"packed-visible"===t?this.materialCacheVisible:this.materialCache:"instanced-direct"===t?this.materialNoReceiveShadowCacheDirect:"packed-visible"===t?this.materialNoReceiveShadowCacheVisible:this.materialNoReceiveShadowCache,l=n??[Er],c=void 0===n||1===n.length&&n[0]===Er,u=this.getForwardMaterialFastCacheIndex(t,r,i,a),d=c?null:this.getForwardMaterialTargetFastCacheKey(l,u);if(c){const t=this.forwardMaterialFrameCache.get(e)?.[u];if(t?.extractionVersion===this.extractionVersion&&t.resource.rendererSampleCount===s)return t.resource;const r=this.forwardMaterialFastCache.get(e)?.[u];if(r&&this.fastMaterialResourceMatches(r,e,s))return this.updateMaterialUniformBuffer(e,r),this.setForwardMaterialFrameCache(e,u,r),r}else{const t=this.forwardMaterialTargetFastCache.get(e)?.get(d);if(t&&this.fastMaterialResourceMatches(t,e,s))return this.updateMaterialUniformBuffer(e,t),t}const h=this.getForwardMaterialKey(e,t,r,l,i,a,s),p=o.get(e),f=p?.get(h);if(f&&this.materialResourceMatches(f,e,h,s))return c?(this.setForwardMaterialFastCache(e,u,f),this.setForwardMaterialFrameCache(e,u,f)):this.setForwardMaterialTargetFastCache(e,d,f),this.updateMaterialUniformBuffer(e,f),f;this.destroyMaterialResource(f),p&&p.delete(h);const{bindGroupLayoutEntries:m,bindGroupEntries:g,uniformBuffer:x,textures:v,textureVersions:w,storageBuffers:b}=this.createMaterialBindGroupData(e,`${e.uuid}-${t}-material`,GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT),y=this.getOrCreateSharedForwardPipeline(h,e,t,m,r,l,i,a,s),S=this.state.device.createBindGroup({label:`${e.uuid}-${t}-material-bind-group`,layout:y.bindGroupLayout,entries:g}),C={key:h,materialVersion:e.version,textureVersionHash:e.getTextureVersionHash(),rendererSampleCount:s,instanceAccessMode:t,receiveShadow:r,useBatching:a,colorTargetFormatsKey:l.join("|"),pipeline:y.pipeline,graphTextureBindGroupLayout:y.graphTextureBindGroupLayout,bindGroup:S,uniformBuffer:x,uniformBufferSize:x?.size??0,uniformValueHash:e.getUniformValueHash(),textures:v,textureVersions:w,storageBuffers:b,vertexAttributes:this.getMaterialVertexAttributes(e,i),usesSkinning:i};let P=o.get(e);return P||(P=new Map,o.set(e,P)),P.set(h,C),c?(this.setForwardMaterialFastCache(e,u,C),this.setForwardMaterialFrameCache(e,u,C)):this.setForwardMaterialTargetFastCache(e,d,C),C}async getMaterialResourceAsync(e,t,r=!0,n,i=!1,a=!1,s=this.sampleCount){if(!(this.state.device&&this.state.format&&this.state.sceneBindGroupLayout&&this.state.visibleSceneBindGroupLayout&&this.state.directSceneBindGroupLayout))throw new Error("Renderer is not initialized.");const o=i?r?this.skinnedMaterialCache:this.skinnedMaterialNoReceiveShadowCache:r?"instanced-direct"===t?this.materialCacheDirect:"packed-visible"===t?this.materialCacheVisible:this.materialCache:"instanced-direct"===t?this.materialNoReceiveShadowCacheDirect:"packed-visible"===t?this.materialNoReceiveShadowCacheVisible:this.materialNoReceiveShadowCache,l=n??[Er],c=void 0===n||1===n.length&&n[0]===Er,u=this.getForwardMaterialFastCacheIndex(t,r,i,a);if(c){const t=this.forwardMaterialFrameCache.get(e)?.[u];if(t?.extractionVersion===this.extractionVersion&&t.resource.rendererSampleCount===s)return t.resource;const r=this.forwardMaterialFastCache.get(e)?.[u];if(r&&this.fastMaterialResourceMatches(r,e,s))return this.updateMaterialUniformBuffer(e,r),this.setForwardMaterialFrameCache(e,u,r),r}const d=this.getForwardMaterialKey(e,t,r,l,i,a,s),h=o.get(e),p=h?.get(d);if(p&&this.materialResourceMatches(p,e,d,s))return c&&(this.setForwardMaterialFastCache(e,u,p),this.setForwardMaterialFrameCache(e,u,p)),this.updateMaterialUniformBuffer(e,p),p;this.destroyMaterialResource(p),h&&h.delete(d);const{bindGroupLayoutEntries:f,bindGroupEntries:m,uniformBuffer:g,textures:x,textureVersions:v,storageBuffers:w}=this.createMaterialBindGroupData(e,`${e.uuid}-${t}-material`,GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT),b=await this.getOrCreateSharedForwardPipelineAsync(d,e,t,f,r,l,i,a,s),y=this.state.device.createBindGroup({label:`${e.uuid}-${t}-material-bind-group`,layout:b.bindGroupLayout,entries:m}),S={key:d,materialVersion:e.version,textureVersionHash:e.getTextureVersionHash(),rendererSampleCount:s,instanceAccessMode:t,receiveShadow:r,useBatching:a,colorTargetFormatsKey:l.join("|"),pipeline:b.pipeline,graphTextureBindGroupLayout:b.graphTextureBindGroupLayout,bindGroup:y,uniformBuffer:g,uniformBufferSize:g?.size??0,uniformValueHash:e.getUniformValueHash(),textures:x,textureVersions:v,storageBuffers:w,vertexAttributes:this.getMaterialVertexAttributes(e,i),usesSkinning:i};let C=o.get(e);return C||(C=new Map,o.set(e,C)),C.set(d,S),c&&(this.setForwardMaterialFastCache(e,u,S),this.setForwardMaterialFrameCache(e,u,S)),S}updateCameraUniforms(e,t){if(!this.state.device||!this.state.cameraBuffer)return;const r=this.cameraProjectionScratch.copy(e.projectionMatrix);r.elements[8]-=2*this.projectionJitterPixels.x/this.state.width,r.elements[9]-=2*this.projectionJitterPixels.y/this.state.height;const n=this.cameraViewProjScratch.copy(kr).multiply(r).multiply(e.matrixWorldInverse);e.getWorldPosition(Hr);const i=this.cameraUniformScratch;i.set(n.elements,0),i[16]=Hr.x,i[17]=Hr.y,i[18]=Hr.z,i[19]=1,i[20]=this.state.width,i[21]=this.state.height,i[22]=this.state.pixelRatio,i[23]=this.state.frameTimeSeconds,i.set(e.matrixWorldInverse.elements,24),i.set(_r.multiplyMatrices(kr,r).elements,40),i[56]=e.near,i[57]=e.far,i[58]=1/Math.max(e.far-e.near,1e-4),i[59]=0;const a=t.fog;null!=a?(i[60]=a.color.r,i[61]=a.color.g,i[62]=a.color.b,i[63]=1,"density"in a?(i[64]=0,i[65]=0,i[66]=a.density,i[67]=1):(i[64]=a.near,i[65]=a.far,i[66]=0,i[67]=0)):(i.fill(0,60,68),i[67]=-1),this.state.device.queue.writeBuffer(this.state.cameraBuffer,0,i,0,68)}updateTemporalVisibilityUniforms(e){if(!this.state.device||!this.state.temporalVisibilityBuffer)return;const t=Vn(e,this.temporalVisibilityCurrentViewProj);e.getWorldPosition(this.temporalVisibilityCurrentCameraPosition);const r=this.temporalVisibilityUniformScratch;r.set(t.elements,0),r.set((this.state.temporalHiZHistoryValid?this.temporalVisibilityPreviousViewProj:t).elements,16),r[32]=this.temporalVisibilityCurrentCameraPosition.x,r[33]=this.temporalVisibilityCurrentCameraPosition.y,r[34]=this.temporalVisibilityCurrentCameraPosition.z,r[35]=1;const n=this.state.temporalHiZHistoryValid?this.temporalVisibilityPreviousCameraPosition:this.temporalVisibilityCurrentCameraPosition;r[36]=n.x,r[37]=n.y,r[38]=n.z,r[39]=1,r[40]=this.state.width,r[41]=this.state.height,r[42]=this.state.pixelRatio,r[43]=this.state.frameTimeSeconds,this.state.device.queue.writeBuffer(this.state.temporalVisibilityBuffer,0,r,0,44)}commitTemporalHiZHistory(){this.temporalVisibilityPreviousViewProj.copy(this.temporalVisibilityCurrentViewProj),this.temporalVisibilityPreviousCameraPosition.copy(this.temporalVisibilityCurrentCameraPosition),this.state.temporalHiZHistoryValid=!0}updateLightUniforms(e){if(!this.state.device||!this.state.lightBuffer)return;const t=this.lightUniformScratch;t.fill(0),t[0]=e.lights.ambient.x,t[1]=e.lights.ambient.y,t[2]=e.lights.ambient.z,t[3]=e.lights.ambient.w,t[4]=e.lights.directionals.length,t[5]=e.lights.points.length,t[6]=e.lights.spots.length,t[7]=Math.min(this.csmCascadeCount,e.lights.directionals.length);for(let e=0;e<this.csmCascadeCount;e+=1){const r=this.csmCascadeRanges[e],n=360+4*e;t[n+0]=r.x,t[n+1]=r.y}const r=e.lights.hemisphere;null!=r&&(t[376]=r.skyColor.x,t[377]=r.skyColor.y,t[378]=r.skyColor.z,t[379]=r.intensity,t[380]=r.groundColor.x,t[381]=r.groundColor.y,t[382]=r.groundColor.z,t[383]=r.intensity,t[384]=r.direction.x,t[385]=r.direction.y,t[386]=r.direction.z,t[387]=1);for(let r=0;r<e.lights.directionals.length;r+=1){const n=e.lights.directionals[r],i=this.directionalShadowCameras[r];i.left=n.shadowCameraLeft,i.right=n.shadowCameraRight,i.top=n.shadowCameraTop,i.bottom=n.shadowCameraBottom,i.near=n.shadowCameraNear,i.far=n.shadowCameraFar,i.position.copy(n.position),i.lookAt(n.target),i.updateMatrixWorld(!0),i.updateProjectionMatrix();const a=8+4*r;t[a+0]=n.direction.x,t[a+1]=n.direction.y,t[a+2]=n.direction.z,t[a+3]=1;const s=24+4*r;t[s+0]=n.color.x,t[s+1]=n.color.y,t[s+2]=n.color.z,t[s+3]=n.intensity;const o=40+4*r;t[o+0]=n.shadowBias,t[o+1]=n.castShadow?1:0,t[o+2]=this.state.directionalShadowTextureSize,t[o+3]=n.shadowNormalBias;const l=56+4*r;t[l+0]=n.shadowRadius,t[l+1]=n.shadowIntensity,t.set(Vn(i,this.shadowViewProjScratch).elements,72+16*r)}for(let r=0;r<e.lights.points.length;r+=1){const n=e.lights.points[r],i=136+4*r;t[i+0]=n.position.x,t[i+1]=n.position.y,t[i+2]=n.position.z,t[i+3]=n.range;const a=152+4*r;t[a+0]=n.color.x,t[a+1]=n.color.y,t[a+2]=n.color.z,t[a+3]=n.intensity;const s=168+4*r;t[s+0]=n.shadowBias,t[s+1]=n.castShadow?1:0,t[s+2]=this.state.pointShadowTextureSize,t[s+3]=n.shadowNormalBias;const o=184+4*r;t[o+0]=n.shadowRadius,t[o+1]=n.shadowIntensity,t[o+2]=n.shadowCameraNear,t[o+3]=n.shadowCameraFar}for(let r=0;r<e.lights.spots.length;r+=1){const n=e.lights.spots[r],i=this.spotShadowCameras[r];i.near=n.shadowCameraNear,i.far=n.shadowCameraFar,i.fov=n.shadowCameraFov,i.aspect=1,i.position.copy(n.position),Kr.copy(n.position).add(n.direction),i.lookAt(Kr),i.updateMatrixWorld(!0),i.updateProjectionMatrix();const a=200+4*r;t[a+0]=n.position.x,t[a+1]=n.position.y,t[a+2]=n.position.z,t[a+3]=n.range;const s=216+4*r;t[s+0]=n.direction.x,t[s+1]=n.direction.y,t[s+2]=n.direction.z,t[s+3]=Math.cos(n.angle);const o=232+4*r;t[o+0]=n.color.x,t[o+1]=n.color.y,t[o+2]=n.color.z,t[o+3]=n.intensity;const l=248+4*r;t[l+0]=n.shadowBias,t[l+1]=n.castShadow?1:0,t[l+2]=this.state.spotShadowTextureSize,t[l+3]=n.shadowNormalBias;const c=264+4*r;t[c+0]=n.shadowRadius,t[c+1]=n.shadowIntensity;const u=280+4*r;t[u+0]=n.range,t[u+1]=Math.cos(n.angle*(1-n.penumbra)),t[u+2]=n.decay,t.set(Vn(i,this.shadowViewProjScratch).elements,296+16*r)}this.state.device.queue.writeBuffer(this.state.lightBuffer,0,t,0,396)}writeShadowCameraBuffer(e,t,r,n,i,a=this.state.shadowCameraBuffer,s){if(!this.state.device||!a)return;const o=this.shadowCameraUniformScratch;o.set(e.elements,0),o[16]=t,o[17]=r,o[18]=n,o[19]=i,o[60]=this.state.frameTimeSeconds,o[61]=0,o[62]=0,o[63]=0,s&&(o.set(s.matrixWorldInverse.elements,20),o.set(s.projectionMatrix.elements,36),o[52]=s.position.x,o[53]=s.position.y,o[54]=s.position.z,o[55]=1,o[56]=s.near,o[57]=s.far,o[58]=0,o[59]=0),this.state.device.queue.writeBuffer(a,0,o,0,64)}};import{DataTexture as _i,Matrix4 as qi,RepeatWrapping as Hi}from"three";var Ki=class{options;noiseTexture=function(){const e=new Array(25).fill(0);let t=Math.floor(2.5),r=4;for(let n=1;n<=25;){-1===t&&5===r?(t=0,r=3):(5===r&&(r=0),t<0&&(t=4));const i=5*t+r;0===e[i]?(e[i]=n++,t-=1,r+=1):(t+=1,r-=2)}const n=new Uint8Array(100);for(let t=0;t<e.length;t+=1){const r=2*Math.PI*e[t]/e.length;n[4*t]=Math.round(255*(.5*Math.cos(r)+.5)),n[4*t+1]=Math.round(255*(.5*Math.sin(r)+.5)),n[4*t+2]=127,n[4*t+3]=255}const i=new _i(n,5,5);return i.wrapS=Hi,i.wrapT=Hi,i.needsUpdate=!0,i}();gtaoPasses=new Map;denoisePasses=new Map;compositePasses=new Map;constructor(e={}){this.options={radius:Math.max(.001,e.radius??.25),resolutionScale:Qi(e.resolutionScale??1,.25,1),thickness:Math.max(.001,e.thickness??1),distanceExponent:Math.max(.01,e.distanceExponent??1),distanceFalloff:Qi(e.distanceFalloff??1,0,1),directions:ea(e.directions??3,1,8),steps:ea(e.steps??6,1,16),normalSpace:e.normalSpace??"world",targetPrefix:e.targetPrefix??"gtao",denoise:!1!==e.denoise&&{radius:Math.max(1,e.denoise?.radius??8),depthPhi:Math.max(1e-4,e.denoise?.depthPhi??2),normalPhi:Math.max(1e-4,e.denoise?.normalPhi??3),lumaPhi:Math.max(1e-4,e.denoise?.lumaPhi??10)}}}addPasses(e,t){const r=e.createColorTarget(`${this.options.targetPrefix}Raw`,{format:"r16float",scale:this.options.resolutionScale}),n=`${t.depth}:${t.normal}:${r}`;let i=this.gtaoPasses.get(n);if(i||(i=new Zi(t.depth,t.normal,r,this.noiseTexture,this.options),this.gtaoPasses.set(n,i)),e.addFullscreenPass(i),!1===this.options.denoise)return r;const a=e.createColorTarget(`${this.options.targetPrefix}Denoised`,{format:"r16float",scale:this.options.resolutionScale}),s=`${r}:${t.depth}:${t.normal}:${a}`;let o=this.denoisePasses.get(s);return o||(o=new Yi(r,t.depth,t.normal,a,this.options.normalSpace,this.options.denoise),this.denoisePasses.set(s,o)),e.addFullscreenPass(o),a}addCompositePass(e,t,r,n={}){const i=n.output??e.createColorTarget(`${this.options.targetPrefix}Composite`,{format:"rgba16float"}),a=Math.max(0,n.intensity??.6),s=Math.max(1e-4,n.power??1),o=`${t}:${r}:${i}:${a}:${s}`;let l=this.compositePasses.get(o);return l||(l=new Xi(t,r,i,a,s),this.compositePasses.set(o,l)),e.addFullscreenPass(l),i}dispose(){this.noiseTexture.dispose()}},Zi=class{constructor(e,t,r,n,i){this.options=i,this.inputs={sceneDepth:e,sceneNormal:t},this.outputs=r,this.textures={gtaoNoise:n},this.fragmentShader=function(e){const t="world"===e.normalSpace?"normalize(viewRotation() * decodedNormal)":"decodedNormal";return`\nconst PI = 3.14159265359;\nconst DIRECTIONS: i32 = ${e.directions};\nconst STEPS: i32 = ${e.steps};\n\nfn projectionMatrix() -> mat4x4<f32> {\n return mat4x4<f32>(fullscreenUniforms[0], fullscreenUniforms[1], fullscreenUniforms[2], fullscreenUniforms[3]);\n}\nfn inverseProjectionMatrix() -> mat4x4<f32> {\n return mat4x4<f32>(fullscreenUniforms[4], fullscreenUniforms[5], fullscreenUniforms[6], fullscreenUniforms[7]);\n}\nfn viewRotation() -> mat3x3<f32> {\n return mat3x3<f32>(fullscreenUniforms[8].xyz, fullscreenUniforms[9].xyz, fullscreenUniforms[10].xyz);\n}\nfn getViewPosition(uv: vec2<f32>, depth: f32) -> vec3<f32> {\n let clip = vec4<f32>(uv.x * 2.0 - 1.0, 1.0 - uv.y * 2.0, depth, 1.0);\n let view = inverseProjectionMatrix() * clip;\n return view.xyz / view.w;\n}\nfn projectViewPosition(position: vec3<f32>) -> vec2<f32> {\n let clip = projectionMatrix() * vec4<f32>(position, 1.0);\n let ndc = clip.xy / clip.w;\n return vec2<f32>(ndc.x * 0.5 + 0.5, 0.5 - ndc.y * 0.5);\n}\nfn loadDepth(uv: vec2<f32>, size: vec2<i32>) -> f32 {\n let pixel = clamp(vec2<i32>(uv * vec2<f32>(size)), vec2<i32>(0), size - vec2<i32>(1));\n return textureLoad(sceneDepthTexture, pixel, 0);\n}\n\n@fragment\nfn fsMain(input: FullscreenVertexOutput) -> @location(0) vec4<f32> {\n let depthSize = vec2<i32>(textureDimensions(sceneDepthTexture));\n let pixel = clamp(vec2<i32>(input.uv * vec2<f32>(depthSize)), vec2<i32>(0), depthSize - vec2<i32>(1));\n let depth = textureLoad(sceneDepthTexture, pixel, 0);\n if (depth >= 1.0) { return vec4<f32>(1.0); }\n\n let viewPosition = getViewPosition(input.uv, depth);\n let decodedNormal = normalize(textureLoad(sceneNormalTexture, pixel, 0).rgb * 2.0 - vec3<f32>(1.0));\n let viewNormal = ${t};\n let viewDirection = normalize(-viewPosition);\n let radius = fullscreenUniforms[12].x;\n let thickness = fullscreenUniforms[12].y;\n let distanceExponent = fullscreenUniforms[12].z;\n let distanceFalloff = fullscreenUniforms[12].w;\n let noiseSize = vec2<f32>(textureDimensions(gtaoNoiseTexture));\n let noiseUv = input.uv * vec2<f32>(depthSize) / noiseSize;\n let noiseTexel = textureSampleLevel(gtaoNoiseTexture, gtaoNoiseSampler, noiseUv, 0.0);\n let tangent = normalize(vec3<f32>(noiseTexel.xy * 2.0 - vec2<f32>(1.0), 0.0));\n let bitangent = vec3<f32>(-tangent.y, tangent.x, 0.0);\n var ao = 0.0;\n\n for (var i = 0; i < DIRECTIONS; i += 1) {\n let angle = (f32(i) / f32(DIRECTIONS)) * PI;\n let sampleDirection = normalize(tangent * cos(angle) + bitangent * sin(angle));\n let sliceBitangent = normalize(cross(sampleDirection, viewDirection));\n let sliceTangent = cross(sliceBitangent, viewDirection);\n let normalInSlice = normalize(viewNormal - sliceBitangent * dot(viewNormal, sliceBitangent));\n let tangentToNormal = cross(normalInSlice, sliceBitangent);\n var cosHorizons = vec2<f32>(dot(viewDirection, tangentToNormal), dot(viewDirection, -tangentToNormal));\n for (var j = 0; j < STEPS; j += 1) {\n let distance = radius * pow(f32(j + 1) / f32(STEPS), distanceExponent);\n for (var side = 0; side < 2; side += 1) {\n let sign = select(-1.0, 1.0, side == 0);\n let sampleUv = projectViewPosition(viewPosition + sampleDirection * distance * sign);\n if (all(sampleUv >= vec2<f32>(0.0)) && all(sampleUv <= vec2<f32>(1.0))) {\n let sampleDepth = loadDepth(sampleUv, depthSize);\n if (sampleDepth < 1.0) {\n let viewDelta = getViewPosition(sampleUv, sampleDepth) - viewPosition;\n if (abs(viewDelta.z) < thickness) {\n let horizon = dot(viewDirection, normalize(viewDelta));\n let update = max(0.0, (horizon - cosHorizons[side]) * mix(1.0, 2.0 / f32(j + 2), distanceFalloff));\n cosHorizons[side] += update;\n }\n }\n }\n }\n }\n let sinHorizons = sqrt(max(vec2<f32>(0.0), vec2<f32>(1.0) - cosHorizons * cosHorizons));\n let nx = dot(normalInSlice, sliceTangent);\n let ny = dot(normalInSlice, viewDirection);\n let nxb = 0.5 * (acos(cosHorizons.y) - acos(cosHorizons.x) + sinHorizons.x * cosHorizons.x - sinHorizons.y * cosHorizons.y);\n let nyb = 0.5 * (2.0 - cosHorizons.x * cosHorizons.x - cosHorizons.y * cosHorizons.y);\n ao += nx * nxb + ny * nyb;\n }\n return vec4<f32>(vec3<f32>(clamp(ao / f32(DIRECTIONS), 0.0, 1.0)), 1.0);\n}\n`}(i)}options;name="GTAOPass";sampler="nearest";uniformBufferSize=208;inputs;outputs;textures;fragmentShader;uniforms=new Float32Array(this.uniformBufferSize/4);webGpuProjection=new qi;webGpuProjectionInverse=new qi;updateUniforms=e=>(this.webGpuProjection.copy(Ji).multiply(e.camera.projectionMatrix),this.webGpuProjectionInverse.copy(this.webGpuProjection).invert(),this.uniforms.set(this.webGpuProjection.elements,0),this.uniforms.set(this.webGpuProjectionInverse.elements,16),this.uniforms.set(e.camera.matrixWorldInverse.elements,32),this.uniforms.set([this.options.radius,this.options.thickness,this.options.distanceExponent,this.options.distanceFalloff],48),this.uniforms)},Yi=class{constructor(e,t,r,n,i,a){this.options=a,this.inputs={aoInput:e,sceneDepth:t,sceneNormal:r},this.outputs=n,this.fragmentShader=function(e){const t="world"===e?"normalize(viewRotation() * decoded)":"decoded";return`\nconst PI = 3.14159265359;\nconst MAGIC_SQUARE: array<u32, 25> = array<u32, 25>(9u, 3u, 22u, 16u, 15u, 2u, 21u, 20u, 14u, 8u, 25u, 19u, 13u, 7u, 1u, 18u, 12u, 6u, 5u, 24u, 11u, 10u, 4u, 23u, 17u);\nconst POISSON_DISK: array<vec3<f32>, 16> = array<vec3<f32>, 16>(\n vec3<f32>(1.0, 0.0, 0.0), vec3<f32>(0.707106781, 0.707106781, 0.066666667), vec3<f32>(0.0, 1.0, 0.133333333), vec3<f32>(-0.707106781, 0.707106781, 0.2),\n vec3<f32>(-1.0, 0.0, 0.266666667), vec3<f32>(-0.707106781, -0.707106781, 0.333333333), vec3<f32>(0.0, -1.0, 0.4), vec3<f32>(0.707106781, -0.707106781, 0.466666667),\n vec3<f32>(1.0, 0.0, 0.533333333), vec3<f32>(0.707106781, 0.707106781, 0.6), vec3<f32>(0.0, 1.0, 0.666666667), vec3<f32>(-0.707106781, 0.707106781, 0.733333333),\n vec3<f32>(-1.0, 0.0, 0.8), vec3<f32>(-0.707106781, -0.707106781, 0.866666667), vec3<f32>(0.0, -1.0, 0.933333333), vec3<f32>(0.707106781, -0.707106781, 1.0));\nfn inverseProjectionMatrix() -> mat4x4<f32> { return mat4x4<f32>(fullscreenUniforms[0], fullscreenUniforms[1], fullscreenUniforms[2], fullscreenUniforms[3]); }\nfn viewRotation() -> mat3x3<f32> { return mat3x3<f32>(fullscreenUniforms[4].xyz, fullscreenUniforms[5].xyz, fullscreenUniforms[6].xyz); }\nfn viewPosition(pixel: vec2<i32>, depth: f32, size: vec2<i32>) -> vec3<f32> {\n let uv = (vec2<f32>(pixel) + vec2<f32>(0.5)) / vec2<f32>(size);\n let view = inverseProjectionMatrix() * vec4<f32>(uv.x * 2.0 - 1.0, 1.0 - uv.y * 2.0, depth, 1.0);\n return view.xyz / view.w;\n}\nfn viewNormal(pixel: vec2<i32>) -> vec3<f32> {\n let decoded = normalize(textureLoad(sceneNormalTexture, pixel, 0).rgb * 2.0 - vec3<f32>(1.0));\n return ${t};\n}\nfn magicSquareAngle(pixel: vec2<i32>) -> f32 { return f32(MAGIC_SQUARE[u32((pixel.y % 5) * 5 + pixel.x % 5)]) * (2.0 * PI / 25.0); }\n@fragment\nfn fsMain(input: FullscreenVertexOutput) -> @location(0) vec4<f32> {\n let aoSize = vec2<i32>(textureDimensions(aoInputTexture));\n let depthSize = vec2<i32>(textureDimensions(sceneDepthTexture));\n let pixel = clamp(vec2<i32>(input.position.xy), vec2<i32>(0), aoSize - vec2<i32>(1));\n let depthPixel = clamp(vec2<i32>(input.uv * vec2<f32>(depthSize)), vec2<i32>(0), depthSize - vec2<i32>(1));\n let depth = textureLoad(sceneDepthTexture, depthPixel, 0);\n if (depth >= 1.0) { return vec4<f32>(1.0); }\n let center = textureLoad(aoInputTexture, pixel, 0).r;\n let normal = viewNormal(depthPixel);\n let position = viewPosition(depthPixel, depth, depthSize);\n let radius = fullscreenUniforms[8].x;\n let depthPhi = fullscreenUniforms[8].y;\n let normalPhi = fullscreenUniforms[8].z;\n let lumaPhi = fullscreenUniforms[8].w;\n let angle = magicSquareAngle(pixel);\n let rotation = mat2x2<f32>(vec2<f32>(cos(angle), sin(angle)), vec2<f32>(-sin(angle), cos(angle)));\n var denoised = center;\n var totalWeight = 1.0;\n for (var i = 0; i < 16; i += 1) {\n let sample = POISSON_DISK[i];\n let samplePixel = vec2<i32>(round(vec2<f32>(pixel) + rotation * sample.xy * (1.0 + sample.z * (radius - 1.0))));\n if (all(samplePixel >= vec2<i32>(0)) && all(samplePixel < aoSize)) {\n let sampleUv = (vec2<f32>(samplePixel) + vec2<f32>(0.5)) / vec2<f32>(aoSize);\n let sampleDepthPixel = clamp(vec2<i32>(sampleUv * vec2<f32>(depthSize)), vec2<i32>(0), depthSize - vec2<i32>(1));\n let sampleDepth = textureLoad(sceneDepthTexture, sampleDepthPixel, 0);\n if (sampleDepth < 1.0) {\n let neighbor = textureLoad(aoInputTexture, samplePixel, 0).r;\n let sampleNormal = viewNormal(sampleDepthPixel);\n let samplePosition = viewPosition(sampleDepthPixel, sampleDepth, depthSize);\n let normalSimilarity = pow(max(dot(normal, sampleNormal), 0.0), normalPhi);\n let lumaSimilarity = max(1.0 - abs(neighbor - center) / lumaPhi, 0.0);\n let depthSimilarity = max(1.0 - abs(dot(position - samplePosition, normal)) / depthPhi, 0.0);\n let weight = normalSimilarity * lumaSimilarity * depthSimilarity;\n denoised += neighbor * weight;\n totalWeight += weight;\n }\n }\n }\n return vec4<f32>(vec3<f32>(denoised / totalWeight), 1.0);\n}\n`}(i)}options;name="GTAODenoisePass";sampler="nearest";uniformBufferSize=144;inputs;outputs;fragmentShader;uniforms=new Float32Array(this.uniformBufferSize/4);webGpuProjectionInverse=new qi;updateUniforms=e=>(this.webGpuProjectionInverse.copy(Ji).multiply(e.camera.projectionMatrix).invert(),this.uniforms.set(this.webGpuProjectionInverse.elements,0),this.uniforms.set(e.camera.matrixWorldInverse.elements,16),this.uniforms.set([this.options.radius,this.options.depthPhi,this.options.normalPhi,this.options.lumaPhi],32),this.uniforms)},Xi=class{name="GTAOCompositePass";sampler="nearest";uniformBufferSize=16;inputs;outputs;uniforms;constructor(e,t,r,n,i){this.inputs={sceneColor:e,ambientOcclusion:t},this.outputs=r,this.uniforms=new Float32Array([n,i,0,0])}updateUniforms=()=>this.uniforms;fragmentShader="\n@fragment\nfn fsMain(input: FullscreenVertexOutput) -> @location(0) vec4<f32> {\n let color = textureLoad(sceneColorTexture, vec2<i32>(input.position.xy), 0);\n let aoSize = vec2<i32>(textureDimensions(ambientOcclusionTexture));\n let aoPixel = clamp(vec2<i32>(input.uv * vec2<f32>(aoSize)), vec2<i32>(0), aoSize - vec2<i32>(1));\n let ao = textureLoad(ambientOcclusionTexture, aoPixel, 0).r;\n let visibility = select(1.0, mix(1.0, pow(clamp(ao, 0.0, 1.0), fullscreenUniforms[0].y), fullscreenUniforms[0].x), color.a < 0.2);\n return vec4<f32>(color.rgb * visibility, 1.0);\n}\n"},Ji=(new qi).set(1,0,0,0,0,1,0,0,0,0,.5,.5,0,0,0,1);function Qi(e,t,r){return Math.min(r,Math.max(t,e))}function ea(e,t,r){return Math.floor(Qi(e,t,r))}import{Matrix4 as ta}from"three";var ra=class{options;passes=new Map;constructor(e={}){var t,r,n;this.options={resolutionScale:oa(e.resolutionScale??.5,.25,1),maxDistance:Math.max(.01,e.maxDistance??50),thickness:Math.max(.001,e.thickness??.15),intensity:Math.max(0,e.intensity??.65),distanceAttenuation:e.distanceAttenuation??!0,maxRoughness:oa(e.maxRoughness??.8,.01,1),steps:(t=e.steps??2048,r=8,n=2048,Math.round(oa(t,r,n))),pixelStride:oa(e.pixelStride??1,1,4),normalSpace:e.normalSpace??"world",blur:e.blur??!0,blurRadius:oa(e.blurRadius??6,1,12),targetPrefix:e.targetPrefix??"ssr"}}addPasses(e,t){const r=e.createColorTarget(`${this.options.targetPrefix}Raw`,{format:"rgba16float",scale:this.options.resolutionScale}),n=`trace:${t.sceneColor}:${t.depth}:${t.normalRoughness}:${r}`;let i=this.passes.get(n);i||(i=new na(t,r,this.options),this.passes.set(n,i)),e.addFullscreenPass(i);let a=r;if(this.options.blur)for(let r=0;r<2;r++){const n=e.createColorTarget(`${this.options.targetPrefix}Blur${r}`,{format:"rgba16float",scale:this.options.resolutionScale}),i=`blur:${a}:${t.depth}:${t.normalRoughness}:${n}:${r}:${this.options.blurRadius}`;let s=this.passes.get(i);s||(s=new ia(a,t.depth,t.normalRoughness,n,r,this.options.blurRadius),this.passes.set(i,s)),e.addFullscreenPass(s),a=n}const s=e.createColorTarget(`${this.options.targetPrefix}Composite`,{format:"rgba16float"}),o=`composite:${t.sceneColor}:${a}:${s}`;let l=this.passes.get(o);return l||(l=new aa(t.sceneColor,a,s,this.options.intensity),this.passes.set(o,l)),e.addFullscreenPass(l),s}},na=class{constructor(e,t,r){this.options=r,this.inputs={sceneColor:e.sceneColor,sceneDepth:e.depth,normalRoughness:e.normalRoughness},this.outputs=t,this.fragmentShader=function(e){const t="world"===e.normalSpace?"normalize(viewRotation() * encodedNormal)":"encodedNormal",r=e.distanceAttenuation?"pow(clamp(1.0 - hitDistance / maxDistance, 0.0, 1.0), 2.0)":"1.0";return`\nconst STEPS: i32 = ${e.steps};\nfn projectionMatrix() -> mat4x4<f32> { return mat4x4<f32>(fullscreenUniforms[0], fullscreenUniforms[1], fullscreenUniforms[2], fullscreenUniforms[3]); }\nfn inverseProjectionMatrix() -> mat4x4<f32> { return mat4x4<f32>(fullscreenUniforms[4], fullscreenUniforms[5], fullscreenUniforms[6], fullscreenUniforms[7]); }\nfn viewRotation() -> mat3x3<f32> { return mat3x3<f32>(fullscreenUniforms[8].xyz, fullscreenUniforms[9].xyz, fullscreenUniforms[10].xyz); }\nfn viewPosition(uv: vec2<f32>, depth: f32) -> vec3<f32> {\n let p = inverseProjectionMatrix() * vec4<f32>(uv.x * 2.0 - 1.0, 1.0 - uv.y * 2.0, depth, 1.0);\n return p.xyz / p.w;\n}\nfn projectUv(position: vec3<f32>) -> vec2<f32> {\n let p = projectionMatrix() * vec4<f32>(position, 1.0);\n return vec2<f32>(p.x / p.w * 0.5 + 0.5, 0.5 - p.y / p.w * 0.5);\n}\nfn depthAt(uv: vec2<f32>) -> f32 {\n let size = vec2<i32>(textureDimensions(sceneDepthTexture));\n return textureLoad(sceneDepthTexture, clamp(vec2<i32>(uv * vec2<f32>(size)), vec2<i32>(0), size - vec2<i32>(1)), 0);\n}\nfn viewZFromDepth(depth: f32) -> f32 {\n let projection = projectionMatrix();\n return (projection[3].z - depth * projection[3].w)\n / (depth * projection[2].w - projection[2].z);\n}\nfn pointToLineDistanceSquared(point: vec3<f32>, start: vec3<f32>, end: vec3<f32>) -> f32 {\n let line = end - start;\n let perpendicular = cross(point - start, point - end);\n return dot(perpendicular, perpendicular) / max(dot(line, line), 0.0000001);\n}\nfn pointPlaneDistance(point: vec3<f32>, planePoint: vec3<f32>, planeNormal: vec3<f32>) -> f32 {\n return dot(point - planePoint, planeNormal);\n}\n@fragment\nfn fsMain(input: FullscreenVertexOutput) -> @location(0) vec4<f32> {\n let depth = depthAt(input.uv);\n if (depth >= 1.0) { return vec4<f32>(0.0); }\n let normalSize = vec2<i32>(textureDimensions(normalRoughnessTexture));\n let normalPixel = clamp(vec2<i32>(input.uv * vec2<f32>(normalSize)), vec2<i32>(0), normalSize - vec2<i32>(1));\n let material = textureLoad(normalRoughnessTexture, normalPixel, 0);\n let encodedNormal = normalize(material.rgb * 2.0 - vec3<f32>(1.0));\n let normal = ${t};\n let roughness = clamp(material.a, 0.0, 1.0);\n let maxRoughness = fullscreenUniforms[12].z;\n let reflectivity = 1.0 - roughness;\n if (roughness >= maxRoughness || reflectivity <= 0.0) { return vec4<f32>(0.0); }\n let origin = viewPosition(input.uv, depth);\n let incident = normalize(origin);\n let direction = normalize(reflect(incident, normal));\n let maxDistance = fullscreenUniforms[12].x;\n let thickness = fullscreenUniforms[12].y;\n let pixelStride = fullscreenUniforms[12].w;\n let near = fullscreenUniforms[13].x;\n let resolutionScale = fullscreenUniforms[13].z;\n let perspective = fullscreenUniforms[13].w > 0.5;\n let incidence = max(dot(-incident, normal), 0.001);\n let rayLength = maxDistance / incidence;\n var endpoint = origin + direction * rayLength;\n if (perspective && endpoint.z > -near && direction.z > 0.0) {\n endpoint = origin + direction * ((-near - origin.z) / direction.z);\n }\n let traceSize = vec2<f32>(textureDimensions(sceneDepthTexture)) * resolutionScale;\n let startPixel = input.position.xy;\n let endPixel = projectUv(endpoint) * traceSize;\n let pixelDelta = endPixel - startPixel;\n let totalSteps = max(abs(pixelDelta.x), abs(pixelDelta.y));\n if (totalSteps < 1.0) { return vec4<f32>(0.0); }\n let pixelStep = pixelDelta / totalSteps;\n let reciprocalOriginZ = 1.0 / origin.z;\n for (var i = 1; i <= STEPS; i += 1) {\n let traversedPixels = f32(i) * pixelStride;\n if (traversedPixels >= totalSteps) { break; }\n let samplePixel = startPixel + traversedPixels * pixelStep;\n if (any(samplePixel < vec2<f32>(0.0)) || any(samplePixel >= traceSize)) { break; }\n let sampleUv = samplePixel / traceSize;\n let sampleDepth = depthAt(sampleUv);\n if (sampleDepth < 1.0) {\n let progress = traversedPixels / totalSteps;\n let rayZ = select(\n mix(origin.z, endpoint.z, progress),\n 1.0 / mix(reciprocalOriginZ, 1.0 / endpoint.z, progress),\n perspective,\n );\n let sceneZ = viewZFromDepth(sampleDepth);\n if (rayZ <= sceneZ) {\n let scene = viewPosition(sampleUv, sampleDepth);\n let neighborUv = sampleUv + vec2<f32>(1.0 / traceSize.x, 0.0);\n let neighbor = viewPosition(neighborUv, sampleDepth);\n let minimumThickness = abs(neighbor.x - scene.x) * 3.0;\n let hitThickness = max(minimumThickness, thickness);\n if (pointToLineDistanceSquared(scene, origin, endpoint) <= hitThickness * hitThickness) {\n let hitPixel = clamp(vec2<i32>(sampleUv * vec2<f32>(normalSize)), vec2<i32>(0), normalSize - vec2<i32>(1));\n let hitEncodedNormal = normalize(textureLoad(normalRoughnessTexture, hitPixel, 0).rgb * 2.0 - vec3<f32>(1.0));\n let hitNormal = ${t.replace("encodedNormal","hitEncodedNormal")};\n if (dot(direction, hitNormal) < 0.0) {\n let hitDistance = pointPlaneDistance(scene, origin, normal);\n if (hitDistance > maxDistance) { break; }\n let distanceFade = ${r};\n let fresnel = (dot(incident, direction) + 1.0) * 0.5;\n let reflected = textureSampleLevel(sceneColorTexture, fullscreenSampler, sampleUv, 0.0).rgb;\n return vec4<f32>(reflected, reflectivity * distanceFade * fresnel);\n }\n }\n }\n }\n }\n return vec4<f32>(0.0);\n}`}(r)}options;name="SSRTracePass";sampler="linear";uniformBufferSize=224;inputs;outputs;fragmentShader;uniforms=new Float32Array(56);projection=new ta;inverseProjection=new ta;updateUniforms=e=>(this.projection.copy(sa).multiply(e.camera.projectionMatrix),this.inverseProjection.copy(this.projection).invert(),this.uniforms.set(this.projection.elements,0),this.uniforms.set(this.inverseProjection.elements,16),this.uniforms.set(e.camera.matrixWorldInverse.elements,32),this.uniforms.set([this.options.maxDistance,this.options.thickness,this.options.maxRoughness,this.options.pixelStride],48),this.uniforms.set([e.camera.near,e.camera.far,this.options.resolutionScale,"isPerspectiveCamera"in e.camera&&e.camera.isPerspectiveCamera?1:0],52),this.uniforms)},ia=class{name;sampler="linear";uniformBufferSize=16;inputs;outputs;uniforms;constructor(e,t,r,n,i,a){this.name=0===i?"SSRBlurHorizontalPass":"SSRBlurVerticalPass",this.inputs={reflection:e,sceneDepth:t,normalRoughness:r},this.outputs=n,this.uniforms=new Float32Array([0===i?1:0,1===i?1:0,a,0])}updateUniforms=()=>this.uniforms;fragmentShader="\nconst MIN_BLUR = 0.02; // Helps reducing artifacts\n@fragment\nfn fsMain(input: FullscreenVertexOutput) -> @location(0) vec4<f32> {\n let reflectionSize = vec2<i32>(textureDimensions(reflectionTexture));\n let depthSize = vec2<i32>(textureDimensions(sceneDepthTexture));\n let p = clamp(vec2<i32>(input.position.xy), vec2<i32>(0), reflectionSize - vec2<i32>(1));\n let fullP = clamp(vec2<i32>(input.uv * vec2<f32>(depthSize)), vec2<i32>(0), depthSize - vec2<i32>(1));\n let centerDepth = textureLoad(sceneDepthTexture, fullP, 0);\n let centerMaterial = textureLoad(normalRoughnessTexture, fullP, 0);\n let centerNormal = normalize(centerMaterial.rgb * 2.0 - vec3<f32>(1.0));\n let blurAmount = smoothstep(0.03, 0.75, centerMaterial.a);\n // A tiny base radius antialiases trace silhouettes on perfect mirrors. The\n // outer Gaussian tap reaches blurRadius pixels on a fully rough receiver.\n let radiusPixels = mix(0.75, fullscreenUniforms[0].z, max(MIN_BLUR, blurAmount));\n let axis = fullscreenUniforms[0].xy;\n let tapSpacing = radiusPixels / 4.0;\n var premultiplied = vec3<f32>(0.0);\n var alphaSum = 0.0;\n var weightSum = 0.0;\n for (var i = -4; i <= 4; i += 1) {\n let fi = f32(i);\n let sampleUv = clamp(\n input.uv + axis * fi * tapSpacing / vec2<f32>(reflectionSize),\n vec2<f32>(0.0),\n vec2<f32>(1.0),\n );\n let sampleFullP = clamp(vec2<i32>(sampleUv * vec2<f32>(depthSize)), vec2<i32>(0), depthSize - vec2<i32>(1));\n let sampleDepth = textureLoad(sceneDepthTexture, sampleFullP, 0);\n let sampleNormal = normalize(textureLoad(normalRoughnessTexture, sampleFullP, 0).rgb * 2.0 - vec3<f32>(1.0));\n let geometryWeight = select(\n exp(-abs(sampleDepth - centerDepth) * 350.0) * pow(max(dot(centerNormal, sampleNormal), 0.0), 16.0),\n 1.0,\n i == 0,\n );\n let reflected = textureSampleLevel(reflectionTexture, fullscreenSampler, sampleUv, 0.0);\n let gaussianWeight = exp(-0.5 * fi * fi / 4.0);\n let weight = geometryWeight * gaussianWeight;\n premultiplied += reflected.rgb * reflected.a * weight;\n alphaSum += reflected.a * weight;\n weightSum += weight;\n }\n let alpha = alphaSum / max(weightSum, 0.0001);\n let color = select(vec3<f32>(0.0), premultiplied / max(alphaSum, 0.0001), alphaSum > 0.0001);\n return vec4<f32>(color, alpha);\n}"},aa=class{name="SSRCompositePass";sampler="linear";uniformBufferSize=16;inputs;outputs;uniforms;constructor(e,t,r,n){this.inputs={sceneColor:e,reflection:t},this.outputs=r,this.uniforms=new Float32Array([n,0,0,0])}updateUniforms=()=>this.uniforms;fragmentShader="\n@fragment\nfn fsMain(input: FullscreenVertexOutput) -> @location(0) vec4<f32> {\n let color = textureLoad(sceneColorTexture, vec2<i32>(input.position.xy), 0);\n let reflection = textureSampleLevel(reflectionTexture, fullscreenSampler, input.uv, 0.0);\n let reflectionWeight = clamp(reflection.a * fullscreenUniforms[0].x, 0.0, 1.0);\n return vec4<f32>(mix(color.rgb, reflection.rgb, reflectionWeight), color.a);\n}"};var sa=(new ta).set(1,0,0,0,0,1,0,0,0,0,.5,.5,0,0,0,1);function oa(e,t,r){return Math.min(r,Math.max(t,e))}import{Matrix4 as la,Vector2 as ca}from"three";var ua=(new la).set(1,0,0,0,0,1,0,0,0,0,.5,.5,0,0,0,1),da=class{renderScale;sampleCount;minCurrentWeight;motionWeightScale;depthThreshold;relativeDepthThreshold;targetPrefix;writeIndex=0;historyValid=!1;frameIndex=0;renderWidth=1;renderHeight=1;outputWidth=1;outputHeight=1;jitter=new ca;unjitteredProjection=new la;previousJitterUv=new ca;currentJitterUv=new ca;previousViewProjection=new la;resolvePasses=new Map;constructor(e={}){this.renderScale=fa(e.renderScale??1,.25,1),this.sampleCount=Math.max(1,Math.floor(e.sampleCount??32)),this.minCurrentWeight=fa(e.minCurrentWeight??.06,0,1),this.motionWeightScale=Math.max(.001,e.motionWeightScale??24),this.depthThreshold=Math.max(0,e.depthThreshold??.001),this.relativeDepthThreshold=Math.max(0,e.relativeDepthThreshold??.002),this.targetPrefix=e.targetPrefix??"taa"}prepareCamera(e,t,r){this.setSize(t,r),e.updateProjectionMatrix(),this.unjitteredProjection.copy(e.projectionMatrix),this.jitter.set(pa(this.frameIndex%this.sampleCount+1,2)-.5,pa(this.frameIndex%this.sampleCount+1,3)-.5),this.currentJitterUv.set(this.jitter.x/this.renderWidth,-this.jitter.y/this.renderHeight),e.projectionMatrix.elements[8]-=2*this.jitter.x/this.renderWidth,e.projectionMatrix.elements[9]-=2*this.jitter.y/this.renderHeight,e.projectionMatrixInverse?.copy(e.projectionMatrix).invert()}finishCamera(e){e.projectionMatrix.copy(this.unjitteredProjection),e.projectionMatrixInverse?.copy(e.projectionMatrix).invert()}addPass(e,t,r=e.mainDepth){const n=e.createColorTarget(`${this.targetPrefix}HistoryColorA`,{format:"rgba16float",resolution:"presentation"}),i=e.createColorTarget(`${this.targetPrefix}HistoryColorB`,{format:"rgba16float",resolution:"presentation"}),a=e.createColorTarget(`${this.targetPrefix}HistoryDepthA`,{format:"r32float",resolution:"presentation"}),s=e.createColorTarget(`${this.targetPrefix}HistoryDepthB`,{format:"r32float",resolution:"presentation"}),o=0===this.writeIndex?i:n,l=0===this.writeIndex?n:i,c=0===this.writeIndex?s:a,u=0===this.writeIndex?a:s,d=`${t}:${r}:${o}:${c}:${l}:${u}`;let h=this.resolvePasses.get(d);return h||(h=new ha(t,r,o,c,l,u,this),this.resolvePasses.set(d,h)),e.addFullscreenPass(h),this.writeIndex=1-this.writeIndex,this.frameIndex+=1,l}reset(){this.frameIndex=0,this.writeIndex=0,this.historyValid=!1,this.previousViewProjection.identity(),this.currentJitterUv.set(0,0),this.previousJitterUv.set(0,0)}setSize(e,t){const r=Math.max(1,Math.floor(e)),n=Math.max(1,Math.floor(t));r===this.outputWidth&&n===this.outputHeight||(this.outputWidth=r,this.outputHeight=n,this.renderWidth=Math.max(1,Math.floor(r*this.renderScale)),this.renderHeight=Math.max(1,Math.floor(n*this.renderScale)),this.reset())}updateResolveUniforms(e,t,r,n){t.copy(ua).multiply(n.camera.projectionMatrix).multiply(n.camera.matrixWorldInverse),r.copy(t).invert(),e.set(r.elements,0),e.set((this.historyValid?this.previousViewProjection:t).elements,16),e.set([n.presentationWidth,n.presentationHeight,this.historyValid?1:0,0],32),e.set([this.currentJitterUv.x,this.currentJitterUv.y,this.previousJitterUv.x,this.previousJitterUv.y],36),e.set([this.minCurrentWeight,this.motionWeightScale,this.depthThreshold,this.relativeDepthThreshold],40),this.previousViewProjection.copy(t),this.previousJitterUv.copy(this.currentJitterUv),this.historyValid=!0}},ha=class{constructor(e,t,r,n,i,a,s){this.state=s,this.inputs={currentColor:e,currentDepth:t,historyColor:r,historyDepth:n},this.outputs=[i,a]}state;name="TemporalAAResolvePass";sampler="nearest";uniformBufferSize=176;inputs;outputs;uniforms=new Float32Array(this.uniformBufferSize/4);currentViewProjection=new la;currentViewProjectionInverse=new la;updateUniforms=e=>(this.state.updateResolveUniforms(this.uniforms,this.currentViewProjection,this.currentViewProjectionInverse,e),this.uniforms);fragmentShader="\nstruct TAAOutput {\n @location(0) color: vec4<f32>,\n @location(1) depth: vec4<f32>,\n};\n\nfn currentViewProjectionInverse() -> mat4x4<f32> {\n return mat4x4<f32>(fullscreenUniforms[0], fullscreenUniforms[1], fullscreenUniforms[2], fullscreenUniforms[3]);\n}\n\nfn previousViewProjection() -> mat4x4<f32> {\n return mat4x4<f32>(fullscreenUniforms[4], fullscreenUniforms[5], fullscreenUniforms[6], fullscreenUniforms[7]);\n}\n\nfn loadCurrentDepth(pixel: vec2<i32>, size: vec2<i32>) -> f32 {\n return textureLoad(currentDepthTexture, clamp(pixel, vec2<i32>(0), size - vec2<i32>(1)), 0);\n}\n\nfn loadCurrentColor(pixel: vec2<i32>, size: vec2<i32>) -> vec3<f32> {\n return textureLoad(currentColorTexture, clamp(pixel, vec2<i32>(0), size - vec2<i32>(1)), 0).rgb;\n}\n\nfn sampleCurrentColorBilinear(uv: vec2<f32>) -> vec3<f32> {\n let size = vec2<i32>(textureDimensions(currentColorTexture));\n let position = uv * vec2<f32>(size) - 0.5;\n let base = vec2<i32>(floor(position));\n let fraction = fract(position);\n let c00 = loadCurrentColor(base, size);\n let c10 = loadCurrentColor(base + vec2<i32>(1, 0), size);\n let c01 = loadCurrentColor(base + vec2<i32>(0, 1), size);\n let c11 = loadCurrentColor(base + vec2<i32>(1, 1), size);\n return mix(mix(c00, c10, fraction.x), mix(c01, c11, fraction.x), fraction.y);\n}\n\nfn sampleHistoryColorBilinear(uv: vec2<f32>) -> vec3<f32> {\n let size = vec2<i32>(textureDimensions(historyColorTexture));\n let position = uv * vec2<f32>(size) - 0.5;\n let base = vec2<i32>(floor(position));\n let fraction = fract(position);\n let maximum = size - vec2<i32>(1);\n let c00 = textureLoad(historyColorTexture, clamp(base, vec2<i32>(0), maximum), 0).rgb;\n let c10 = textureLoad(historyColorTexture, clamp(base + vec2<i32>(1, 0), vec2<i32>(0), maximum), 0).rgb;\n let c01 = textureLoad(historyColorTexture, clamp(base + vec2<i32>(0, 1), vec2<i32>(0), maximum), 0).rgb;\n let c11 = textureLoad(historyColorTexture, clamp(base + vec2<i32>(1, 1), vec2<i32>(0), maximum), 0).rgb;\n return mix(mix(c00, c10, fraction.x), mix(c01, c11, fraction.x), fraction.y);\n}\n\nfn sampleHistoryDepthNearest(uv: vec2<f32>) -> f32 {\n let size = vec2<i32>(textureDimensions(historyDepthTexture));\n let pixel = clamp(vec2<i32>(uv * vec2<f32>(size)), vec2<i32>(0), size - vec2<i32>(1));\n return textureLoad(historyDepthTexture, pixel, 0).r;\n}\n\nfn historyUvFor(currentUv: vec2<f32>, depth: f32) -> vec2<f32> {\n let clip = vec4<f32>(currentUv.x * 2.0 - 1.0, 1.0 - currentUv.y * 2.0, depth, 1.0);\n let worldH = currentViewProjectionInverse() * clip;\n let world = worldH / worldH.w;\n let previousClip = previousViewProjection() * world;\n let previousNdc = previousClip.xy / previousClip.w;\n let previousRasterUv = vec2<f32>(previousNdc.x * 0.5 + 0.5, 0.5 - previousNdc.y * 0.5);\n return previousRasterUv - fullscreenUniforms[9].zw;\n}\n\n@fragment\nfn fsMain(input: FullscreenVertexOutput) -> TAAOutput {\n let renderSize = vec2<i32>(textureDimensions(currentDepthTexture));\n let outputSize = vec2<i32>(fullscreenUniforms[8].xy);\n let centerPixel = clamp(vec2<i32>(input.position.xy), vec2<i32>(0), outputSize - vec2<i32>(1));\n let centerUv = (vec2<f32>(centerPixel) + 0.5) / vec2<f32>(outputSize);\n let currentJitterUv = fullscreenUniforms[9].xy;\n let currentSampleUv = centerUv + currentJitterUv;\n let currentSamplePixel = clamp(vec2<i32>(currentSampleUv * vec2<f32>(renderSize)), vec2<i32>(0), renderSize - vec2<i32>(1));\n let centerDepth = loadCurrentDepth(currentSamplePixel, renderSize);\n\n var closestDepth = centerDepth;\n var closestPixel = currentSamplePixel;\n var mean = vec3<f32>(0.0);\n var meanSquared = vec3<f32>(0.0);\n for (var y = -1; y <= 1; y += 1) {\n for (var x = -1; x <= 1; x += 1) {\n let samplePixel = clamp(currentSamplePixel + vec2<i32>(x, y), vec2<i32>(0), renderSize - vec2<i32>(1));\n let sampleDepth = loadCurrentDepth(samplePixel, renderSize);\n if (sampleDepth < closestDepth) {\n closestDepth = sampleDepth;\n closestPixel = samplePixel;\n }\n let sampleColor = sampleCurrentColorBilinear(currentSampleUv + vec2<f32>(f32(x), f32(y)) / vec2<f32>(renderSize));\n mean += sampleColor;\n meanSquared += sampleColor * sampleColor;\n }\n }\n mean /= 9.0;\n let sigma = sqrt(max(meanSquared / 9.0 - mean * mean, vec3<f32>(0.0)));\n\n let currentColor = sampleCurrentColorBilinear(currentSampleUv);\n let closestUv = (vec2<f32>(closestPixel) + 0.5) / vec2<f32>(renderSize);\n let closestHistoryUv = historyUvFor(closestUv, closestDepth);\n let closestOutputUv = closestUv - currentJitterUv;\n let historyUv = centerUv - (closestOutputUv - closestHistoryUv);\n let validUv = all(historyUv >= vec2<f32>(0.0)) && all(historyUv <= vec2<f32>(1.0));\n let historyWasValid = fullscreenUniforms[8].z > 0.5;\n\n var validHistory = historyWasValid && validUv && centerDepth < 1.0;\n var historyColor = currentColor;\n if (validHistory) {\n historyColor = sampleHistoryColorBilinear(historyUv);\n let previousDepth = sampleHistoryDepthNearest(historyUv);\n let expectedPreviousDepth = previousViewProjection() *\n (currentViewProjectionInverse() * vec4<f32>(currentSampleUv.x * 2.0 - 1.0, 1.0 - currentSampleUv.y * 2.0, centerDepth, 1.0));\n let expectedDepth = expectedPreviousDepth.z / expectedPreviousDepth.w;\n let depthThreshold = fullscreenUniforms[10].z;\n let relativeDepthThreshold = fullscreenUniforms[10].w;\n validHistory = abs(previousDepth - expectedDepth) < max(depthThreshold, abs(expectedDepth) * relativeDepthThreshold);\n }\n\n let clippedHistory = clamp(historyColor, mean - sigma, mean + sigma);\n let motionPixels = length((centerUv - historyUv) * vec2<f32>(outputSize));\n let minCurrentWeight = fullscreenUniforms[10].x;\n let currentWeight = clamp(minCurrentWeight + motionPixels / fullscreenUniforms[10].y, minCurrentWeight, 1.0);\n let resolved = select(currentColor, mix(clippedHistory, currentColor, currentWeight), validHistory);\n\n var output: TAAOutput;\n output.color = vec4<f32>(resolved, 1.0);\n output.depth = vec4<f32>(centerDepth, 0.0, 0.0, 1.0);\n return output;\n}\n"};function pa(e,t){let r=1,n=0;for(;e>0;)r/=t,n+=r*(e%t),e=Math.floor(e/t);return n}function fa(e,t,r){return Math.min(r,Math.max(t,e))}var ma=class{contrastThreshold;relativeThreshold;subpixelBlending;targetPrefix;passes=new Map;constructor(e={}){this.contrastThreshold=Math.max(0,e.contrastThreshold??.0312),this.relativeThreshold=Math.max(0,e.relativeThreshold??.063),this.subpixelBlending=xa(e.subpixelBlending??.75,0,1),this.targetPrefix=e.targetPrefix??"fxaa"}addPass(e,t,r={}){const n=r.output??e.createColorTarget(`${this.targetPrefix}Color`,{format:"rgba16float",resolution:"presentation"}),i=`${t}:${n}`;let a=this.passes.get(i);return a||(a=new ga(t,n,this),this.passes.set(i,a)),e.addFullscreenPass(a),n}},ga=class{constructor(e,t,r){this.state=r,this.inputs={source:e},this.outputs=t}state;name="FXAAPass";sampler="linear";uniformBufferSize=16;inputs;outputs;uniforms=new Float32Array(4);updateUniforms=()=>(this.uniforms.set([Math.max(0,this.state.contrastThreshold),Math.max(0,this.state.relativeThreshold),xa(this.state.subpixelBlending,0,1),0]),this.uniforms);fragmentShader="\nconst EDGE_STEP_COUNT: i32 = 6;\nconst EDGE_GUESS: f32 = 8.0;\nconst EDGE_STEPS = array<f32, 6>(1.0, 1.5, 2.0, 2.0, 2.0, 4.0);\n\nstruct LuminanceData {\n m: f32,\n n: f32,\n e: f32,\n s: f32,\n w: f32,\n ne: f32,\n nw: f32,\n se: f32,\n sw: f32,\n highest: f32,\n lowest: f32,\n contrast: f32,\n};\n\nstruct EdgeData {\n isHorizontal: bool,\n pixelStep: f32,\n oppositeLuminance: f32,\n gradient: f32,\n};\n\nfn sampleColor(uv: vec2<f32>) -> vec4<f32> {\n return textureSampleLevel(sourceTexture, fullscreenSampler, uv, 0.0);\n}\n\nfn sampleLuminance(uv: vec2<f32>) -> f32 {\n // The renderer's intermediate buffers are linear. FXAA thresholds are tuned\n // for perceptual luminance, so sqrt is a cheap gamma approximation here.\n return sqrt(max(dot(sampleColor(uv).rgb, vec3<f32>(0.299, 0.587, 0.114)), 0.0));\n}\n\nfn offsetLuminance(uv: vec2<f32>, texel: vec2<f32>, offset: vec2<f32>) -> f32 {\n return sampleLuminance(uv + texel * offset);\n}\n\nfn sampleNeighborhood(uv: vec2<f32>, texel: vec2<f32>) -> LuminanceData {\n var l: LuminanceData;\n l.m = sampleLuminance(uv);\n l.n = offsetLuminance(uv, texel, vec2<f32>(0.0, -1.0));\n l.e = offsetLuminance(uv, texel, vec2<f32>(1.0, 0.0));\n l.s = offsetLuminance(uv, texel, vec2<f32>(0.0, 1.0));\n l.w = offsetLuminance(uv, texel, vec2<f32>(-1.0, 0.0));\n l.ne = offsetLuminance(uv, texel, vec2<f32>(1.0, -1.0));\n l.nw = offsetLuminance(uv, texel, vec2<f32>(-1.0, -1.0));\n l.se = offsetLuminance(uv, texel, vec2<f32>(1.0, 1.0));\n l.sw = offsetLuminance(uv, texel, vec2<f32>(-1.0, 1.0));\n l.highest = max(max(max(max(l.n, l.e), l.s), l.w), l.m);\n l.lowest = min(min(min(min(l.n, l.e), l.s), l.w), l.m);\n l.contrast = l.highest - l.lowest;\n return l;\n}\n\nfn pixelBlendFactor(l: LuminanceData) -> f32 {\n var filterAmount = 2.0 * (l.n + l.e + l.s + l.w);\n filterAmount += l.ne + l.nw + l.se + l.sw;\n filterAmount = abs(filterAmount / 12.0 - l.m);\n filterAmount = clamp(filterAmount / max(l.contrast, 1e-5), 0.0, 1.0);\n let blend = smoothstep(0.0, 1.0, filterAmount);\n return blend * blend * fullscreenUniforms[0].z;\n}\n\nfn determineEdge(texel: vec2<f32>, l: LuminanceData) -> EdgeData {\n let horizontal =\n abs(l.n + l.s - 2.0 * l.m) * 2.0 +\n abs(l.ne + l.se - 2.0 * l.e) +\n abs(l.nw + l.sw - 2.0 * l.w);\n let vertical =\n abs(l.e + l.w - 2.0 * l.m) * 2.0 +\n abs(l.ne + l.nw - 2.0 * l.n) +\n abs(l.se + l.sw - 2.0 * l.s);\n\n var edge: EdgeData;\n edge.isHorizontal = horizontal >= vertical;\n let positiveLuminance = select(l.e, l.n, edge.isHorizontal);\n let negativeLuminance = select(l.w, l.s, edge.isHorizontal);\n let positiveGradient = abs(positiveLuminance - l.m);\n let negativeGradient = abs(negativeLuminance - l.m);\n edge.pixelStep = select(texel.x, texel.y, edge.isHorizontal);\n if (positiveGradient < negativeGradient) {\n edge.pixelStep = -edge.pixelStep;\n edge.oppositeLuminance = negativeLuminance;\n edge.gradient = negativeGradient;\n } else {\n edge.oppositeLuminance = positiveLuminance;\n edge.gradient = positiveGradient;\n }\n return edge;\n}\n\nfn edgeBlendFactor(uv: vec2<f32>, texel: vec2<f32>, l: LuminanceData, edge: EdgeData) -> f32 {\n var edgeUv = uv;\n var edgeStep: vec2<f32>;\n if (edge.isHorizontal) {\n edgeUv.y += edge.pixelStep * 0.5;\n edgeStep = vec2<f32>(texel.x, 0.0);\n } else {\n edgeUv.x += edge.pixelStep * 0.5;\n edgeStep = vec2<f32>(0.0, texel.y);\n }\n\n let edgeLuminance = (l.m + edge.oppositeLuminance) * 0.5;\n let gradientThreshold = edge.gradient * 0.25;\n var positiveUv = edgeUv + edgeStep * EDGE_STEPS[0];\n var positiveDelta = sampleLuminance(positiveUv) - edgeLuminance;\n var positiveAtEnd = abs(positiveDelta) >= gradientThreshold;\n for (var i = 1; i < EDGE_STEP_COUNT; i += 1) {\n if (!positiveAtEnd) {\n positiveUv += edgeStep * EDGE_STEPS[i];\n positiveDelta = sampleLuminance(positiveUv) - edgeLuminance;\n positiveAtEnd = abs(positiveDelta) >= gradientThreshold;\n }\n }\n if (!positiveAtEnd) {\n positiveUv += edgeStep * EDGE_GUESS;\n }\n\n var negativeUv = edgeUv - edgeStep * EDGE_STEPS[0];\n var negativeDelta = sampleLuminance(negativeUv) - edgeLuminance;\n var negativeAtEnd = abs(negativeDelta) >= gradientThreshold;\n for (var i = 1; i < EDGE_STEP_COUNT; i += 1) {\n if (!negativeAtEnd) {\n negativeUv -= edgeStep * EDGE_STEPS[i];\n negativeDelta = sampleLuminance(negativeUv) - edgeLuminance;\n negativeAtEnd = abs(negativeDelta) >= gradientThreshold;\n }\n }\n if (!negativeAtEnd) {\n negativeUv -= edgeStep * EDGE_GUESS;\n }\n\n let positiveDistance = select(positiveUv.y - uv.y, positiveUv.x - uv.x, edge.isHorizontal);\n let negativeDistance = select(uv.y - negativeUv.y, uv.x - negativeUv.x, edge.isHorizontal);\n var shortestDistance = negativeDistance;\n var deltaSign = negativeDelta >= 0.0;\n if (positiveDistance <= negativeDistance) {\n shortestDistance = positiveDistance;\n deltaSign = positiveDelta >= 0.0;\n }\n if (deltaSign == (l.m - edgeLuminance >= 0.0)) {\n return 0.0;\n }\n return 0.5 - shortestDistance / max(positiveDistance + negativeDistance, 1e-5);\n}\n\n@fragment\nfn fsMain(input: FullscreenVertexOutput) -> @location(0) vec4<f32> {\n let texel = 1.0 / vec2<f32>(textureDimensions(sourceTexture));\n let luminance = sampleNeighborhood(input.uv, texel);\n let threshold = max(fullscreenUniforms[0].x, fullscreenUniforms[0].y * luminance.highest);\n if (luminance.contrast < threshold) {\n return sampleColor(input.uv);\n }\n\n let edge = determineEdge(texel, luminance);\n let blend = max(pixelBlendFactor(luminance), edgeBlendFactor(input.uv, texel, luminance, edge));\n var sampleUv = input.uv;\n if (edge.isHorizontal) {\n sampleUv.y += edge.pixelStep * blend;\n } else {\n sampleUv.x += edge.pixelStep * blend;\n }\n return sampleColor(sampleUv);\n}\n"};function xa(e,t,r){return Math.min(r,Math.max(t,e))}var va=class{strength;threshold;knee;radius;levels;targetPrefix;passes=new Map;constructor(e={}){var t,r,n;this.strength=Math.max(0,e.strength??.9),this.threshold=Math.max(0,e.threshold??1),this.knee=Math.max(1e-4,e.knee??.1),this.radius=Sa(e.radius??.2,0,1),this.levels=(t=e.levels??5,r=1,n=5,Math.floor(Sa(t,r,n))),this.targetPrefix=e.targetPrefix??"bloom"}addPass(e,t,r={}){const n=[];let i=t;for(let t=0;t<this.levels;t+=1){const r=1/2**(t+1),a=e.createColorTarget(`${this.targetPrefix}Horizontal${t}`,{format:"rgba16float",scale:r}),s=e.createColorTarget(`${this.targetPrefix}Vertical${t}`,{format:"rgba16float",scale:r}),o=i,l=`h:${t}:${o}:${a}`;let c=this.passes.get(l);c||(c=0===t?new wa(o,a,this):new ba(`BloomDownsampleHorizontal${t}`,o,a,!0,t),this.passes.set(l,c)),e.addFullscreenPass(c);const u=`v:${t}:${a}:${s}`;let d=this.passes.get(u);d||(d=new ba(`BloomVertical${t}`,a,s,!1,t),this.passes.set(u,d)),e.addFullscreenPass(d),n.push(s),i=s}const a=r.output??e.createColorTarget(`${this.targetPrefix}Color`,{format:"rgba16float"}),s=Object.fromEntries(n.map((e,t)=>[`blur${t}`,e])),o=`composite:${t}:${n.join(":")}:${a}`;let l=this.passes.get(o);return l||(l=new ya(t,s,a,this,this.levels),this.passes.set(o,l)),e.addFullscreenPass(l),a}},wa=class{constructor(e,t,r){this.state=r,this.inputs={source:e},this.outputs=t}state;name="BloomThresholdHorizontal";sampler="linear";uniformBufferSize=16;inputs;outputs;uniforms=new Float32Array(4);updateUniforms=()=>(this.uniforms.set([this.state.threshold,this.state.knee,0,0]),this.uniforms);fragmentShader="\nfn bright(color: vec3<f32>) -> vec3<f32> {\n let brightness = dot(color, vec3<f32>(0.2126, 0.7152, 0.0722));\n let threshold = fullscreenUniforms[0].x;\n let knee = fullscreenUniforms[0].y;\n let soft = clamp(brightness - threshold + knee, 0.0, 2.0 * knee);\n let contribution = max(brightness - threshold, soft * soft / (4.0 * knee));\n return color * contribution / max(brightness, 0.0001);\n}\n\n@fragment\nfn fsMain(input: FullscreenVertexOutput) -> @location(0) vec4<f32> {\n let texel = 1.0 / vec2<f32>(textureDimensions(sourceTexture));\n let center = bright(textureSample(sourceTexture, fullscreenSampler, input.uv).rgb) * 0.227027;\n let a = bright(textureSample(sourceTexture, fullscreenSampler, input.uv + vec2<f32>(1.384615 * texel.x, 0.0)).rgb);\n let b = bright(textureSample(sourceTexture, fullscreenSampler, input.uv - vec2<f32>(1.384615 * texel.x, 0.0)).rgb);\n let c = bright(textureSample(sourceTexture, fullscreenSampler, input.uv + vec2<f32>(3.230769 * texel.x, 0.0)).rgb);\n let d = bright(textureSample(sourceTexture, fullscreenSampler, input.uv - vec2<f32>(3.230769 * texel.x, 0.0)).rgb);\n return vec4<f32>(center + (a + b) * 0.316216 + (c + d) * 0.070270, 1.0);\n}"},ba=class{constructor(e,t,r,n,i){this.name=e,this.inputs={source:t},this.outputs=r;const a=n?"vec2<f32>(texel.x, 0.0)":"vec2<f32>(0.0, texel.y)",s=(1+.35*i).toFixed(2);this.fragmentShader=`\n@fragment\nfn fsMain(input: FullscreenVertexOutput) -> @location(0) vec4<f32> {\n let texel = 1.0 / vec2<f32>(textureDimensions(sourceTexture));\n let axis = ${a} * ${s};\n var color = textureSample(sourceTexture, fullscreenSampler, input.uv).rgb * 0.227027;\n color += textureSample(sourceTexture, fullscreenSampler, input.uv + axis * 1.384615).rgb * 0.316216;\n color += textureSample(sourceTexture, fullscreenSampler, input.uv - axis * 1.384615).rgb * 0.316216;\n color += textureSample(sourceTexture, fullscreenSampler, input.uv + axis * 3.230769).rgb * 0.070270;\n color += textureSample(sourceTexture, fullscreenSampler, input.uv - axis * 3.230769).rgb * 0.070270;\n return vec4<f32>(color, 1.0);\n}`}name;sampler="linear";inputs;outputs;fragmentShader},ya=class{constructor(e,t,r,n,i){this.state=n,this.inputs={source:e,...t},this.outputs=r;const a=[1,.8,.6,.4,.2],s=Array.from({length:i},(e,t)=>`bloom += textureSample(blur${t}Texture, fullscreenSampler, input.uv).rgb * mix(${a[t].toFixed(1)}, ${(1.2-a[t]).toFixed(1)}, radius);`).join("\n ");this.fragmentShader=`\n@fragment\nfn fsMain(input: FullscreenVertexOutput) -> @location(0) vec4<f32> {\n let scene = textureSample(sourceTexture, fullscreenSampler, input.uv);\n let radius = fullscreenUniforms[0].y;\n var bloom = vec3<f32>(0.0);\n ${s}\n return vec4<f32>(scene.rgb + bloom * fullscreenUniforms[0].x, scene.a);\n}`}state;name="BloomComposite";sampler="linear";uniformBufferSize=32;inputs;outputs;uniforms=new Float32Array(8);updateUniforms=()=>(this.uniforms.set([this.state.strength,Sa(this.state.radius,0,1),0,0]),this.uniforms);fragmentShader};function Sa(e,t,r){return Math.min(r,Math.max(t,e))}var Ca=[1,1,1],Pa=[0,0,0],Ma=class{options;passes=new Map;targetPrefix;constructor(e={}){this.options=e,this.targetPrefix=e.targetPrefix??"colorGrading"}addPass(e,t){const r=e.createColorTarget(`${this.targetPrefix}Color`,{format:"rgba16float"}),n=`${t}:${r}`;let i=this.passes.get(n);return i||(i=new Ba(t,r,this.options),this.passes.set(n,i)),e.addFullscreenPass(i),r}},Ba=class{constructor(e,t,r){this.state=r,this.inputs={source:e},this.outputs=t}state;name="ColorGrading";sampler="linear";uniformBufferSize=384;inputs;outputs;uniforms=new Float32Array(this.uniformBufferSize/4);updateUniforms=()=>{const e=[],t=(t,r)=>e.push(...t??r,0),r=e=>{t(e?.saturation,Ca),t(e?.contrast,Ca),t(e?.gamma,Ca),t(e?.gain,Ca),t(e?.offset,Pa)};return t(this.state.whiteBalance,Ca),t(this.state.tint,Ca),r(this.state),r(this.state.shadows),r(this.state.midtones),r(this.state.highlights),e.push(this.state.exposure??1,{none:0,linear:1,reinhard:2,cineon:3,aces:4,agx:5,neutral:6}[this.state.toneMapping??"none"],Math.max(0,this.state.vignetteIntensity??0),Math.min(1,Math.max(0,this.state.tintIntensity??0)),this.state.shadowsMax??.09,this.state.highlightsMin??.5,!1===this.state.enabled?0:1,0),this.uniforms.fill(0),this.uniforms.set(e),this.uniforms};fragmentShader="\nfn grade(color: vec3<f32>, s: vec3<f32>, c: vec3<f32>, g: vec3<f32>, gain: vec3<f32>, offset: vec3<f32>) -> vec3<f32> {\n let luma = dot(color, vec3<f32>(0.2126, 0.7152, 0.0722));\n var result = mix(vec3<f32>(luma), color, s);\n result = (result - vec3<f32>(0.18)) * c + vec3<f32>(0.18);\n result = pow(max(result, vec3<f32>(0.0)), vec3<f32>(1.0) / max(g, vec3<f32>(0.0001)));\n return max(result * gain + offset, vec3<f32>(0.0));\n}\nfn aces(x: vec3<f32>) -> vec3<f32> { return clamp((x * (2.51*x + vec3<f32>(0.03))) / (x * (2.43*x + vec3<f32>(0.59)) + vec3<f32>(0.14)), vec3<f32>(0.0), vec3<f32>(1.0)); }\nfn tonemap(x: vec3<f32>, mode: i32) -> vec3<f32> {\n if (mode == 1) { return clamp(x, vec3<f32>(0.0), vec3<f32>(1.0)); }\n if (mode == 2) { return x / (vec3<f32>(1.0) + x); }\n if (mode == 3) { let y=max(vec3<f32>(0.0),x-vec3<f32>(0.004)); return pow((y*(6.2*y+vec3<f32>(0.5)))/(y*(6.2*y+vec3<f32>(1.7))+vec3<f32>(0.06)),vec3<f32>(2.2)); }\n if (mode == 4) { return aces(x); }\n if (mode == 5) { return clamp((x * (x + vec3<f32>(0.0245786)) - vec3<f32>(0.000090537)) / (x * (0.983729*x + vec3<f32>(0.432951)) + vec3<f32>(0.238081)), vec3<f32>(0.0), vec3<f32>(1.0)); }\n if (mode == 6) { return clamp(x / (max(max(x.r,x.g),x.b) + 1.0), vec3<f32>(0.0), vec3<f32>(1.0)); }\n return x;\n}\n@fragment\nfn fsMain(input: FullscreenVertexOutput) -> @location(0) vec4<f32> {\n let source = textureSample(sourceTexture, fullscreenSampler, input.uv);\n if (fullscreenUniforms[23].z < 0.5) { return source; }\n var color = source.rgb * fullscreenUniforms[0].xyz;\n color = mix(color, color * fullscreenUniforms[1].xyz, fullscreenUniforms[22].w);\n let lum = clamp(dot(color, vec3<f32>(0.2126,0.7152,0.0722)), 0.0, 1.0);\n let shadowLimit = clamp(fullscreenUniforms[23].x, 0.0, 0.98);\n let highlightLimit = clamp(max(fullscreenUniforms[23].y, shadowLimit + 0.02), 0.02, 1.0);\n let sw = 1.0 - smoothstep(shadowLimit, min(1.0, shadowLimit + 0.05), lum);\n let hw = smoothstep(max(0.0, highlightLimit - 0.05), highlightLimit, lum);\n let mw = clamp(1.0-sw-hw, 0.0, 1.0);\n var s=fullscreenUniforms[2].xyz; var c=fullscreenUniforms[3].xyz; var g=fullscreenUniforms[4].xyz; var gn=fullscreenUniforms[5].xyz; var o=fullscreenUniforms[6].xyz;\n s*=mix(vec3<f32>(1),fullscreenUniforms[7].xyz,sw)*mix(vec3<f32>(1),fullscreenUniforms[12].xyz,mw)*mix(vec3<f32>(1),fullscreenUniforms[17].xyz,hw);\n c*=mix(vec3<f32>(1),fullscreenUniforms[8].xyz,sw)*mix(vec3<f32>(1),fullscreenUniforms[13].xyz,mw)*mix(vec3<f32>(1),fullscreenUniforms[18].xyz,hw);\n g*=mix(vec3<f32>(1),fullscreenUniforms[9].xyz,sw)*mix(vec3<f32>(1),fullscreenUniforms[14].xyz,mw)*mix(vec3<f32>(1),fullscreenUniforms[19].xyz,hw);\n gn*=mix(vec3<f32>(1),fullscreenUniforms[10].xyz,sw)*mix(vec3<f32>(1),fullscreenUniforms[15].xyz,mw)*mix(vec3<f32>(1),fullscreenUniforms[20].xyz,hw);\n o+=fullscreenUniforms[11].xyz*sw+fullscreenUniforms[16].xyz*mw+fullscreenUniforms[21].xyz*hw;\n color=grade(color,s,c,g,gn,o);\n color=tonemap(color*fullscreenUniforms[22].x,i32(fullscreenUniforms[22].y));\n let d=distance(input.uv,vec2<f32>(0.5));\n color*=smoothstep(0.8,0.1598,d*(fullscreenUniforms[22].z+0.2));\n return vec4<f32>(color,source.a);\n}"};import{Matrix4 as Da}from"three";var Ta=class{options;passes=new Map;targetPrefix;constructor(e={}){this.options=e,this.targetPrefix=e.targetPrefix??"depthOfField"}addPass(e,t,r){const n=e.createColorTarget(`${this.targetPrefix}Color`,{format:"rgba16float"}),i=`${t}:${r}:${n}`;let a=this.passes.get(i);return a||(a=new Ia(t,r,n,this.options),this.passes.set(i,a)),e.addFullscreenPass(a),n}},Ia=class{constructor(e,t,r,n){this.state=n,this.inputs={source:e,sceneDepth:t},this.outputs=r}state;name="DepthOfField";sampler="linear";uniformBufferSize=80;inputs;outputs;uniforms=new Float32Array(20);inverseProjection=new Da;updateUniforms=e=>(this.inverseProjection.copy(Ga).multiply(e.camera.projectionMatrix).invert(),this.uniforms.set(this.inverseProjection.elements,0),this.uniforms.set([this.state.focus??10,this.state.aperture??2e-4,this.state.maxBlur??.01,!1===this.state.enabled?0:1],16),this.uniforms);fragmentShader="\nfn viewDistance(uv:vec2<f32>,depth:f32)->f32 { let clip=vec4<f32>(uv*vec2<f32>(2,-2)+vec2<f32>(-1,1),depth,1); let view=mat4x4<f32>(fullscreenUniforms[0],fullscreenUniforms[1],fullscreenUniforms[2],fullscreenUniforms[3])*clip; return abs(view.z/view.w); }\n@fragment fn fsMain(input:FullscreenVertexOutput)->@location(0) vec4<f32>{\n let center=textureSample(sourceTexture,fullscreenSampler,input.uv); if(fullscreenUniforms[4].w<0.5){return center;}\n let px=vec2<f32>(1)/vec2<f32>(textureDimensions(sourceTexture)); let depth=textureLoad(sceneDepthTexture,vec2<i32>(input.position.xy),0);\n let blur=clamp(abs(viewDistance(input.uv,depth)-fullscreenUniforms[4].x)*fullscreenUniforms[4].y,0,fullscreenUniforms[4].z);\n var color=center.rgb*0.2; color+=textureSample(sourceTexture,fullscreenSampler,input.uv+vec2<f32>( blur,0)*px*400).rgb*0.1; color+=textureSample(sourceTexture,fullscreenSampler,input.uv-vec2<f32>( blur,0)*px*400).rgb*0.1;\n color+=textureSample(sourceTexture,fullscreenSampler,input.uv+vec2<f32>(0, blur)*px*400).rgb*0.1; color+=textureSample(sourceTexture,fullscreenSampler,input.uv-vec2<f32>(0, blur)*px*400).rgb*0.1;\n color+=textureSample(sourceTexture,fullscreenSampler,input.uv+vec2<f32>( blur, blur)*px*280).rgb*0.1; color+=textureSample(sourceTexture,fullscreenSampler,input.uv+vec2<f32>(-blur, blur)*px*280).rgb*0.1; color+=textureSample(sourceTexture,fullscreenSampler,input.uv+vec2<f32>( blur,-blur)*px*280).rgb*0.1; color+=textureSample(sourceTexture,fullscreenSampler,input.uv-vec2<f32>( blur, blur)*px*280).rgb*0.1;\n return vec4<f32>(color,center.a); }"},Ga=(new Da).set(1,0,0,0,0,1,0,0,0,0,.5,.5,0,0,0,1),Ra=class{enabled;visibleEdgeColor;edgeStrength;edgeThickness;selectedObjects=new Set;selectedInstances=[];targetPrefix;maskMaterial;skinnedMaskMaterial;instanceMaskMaterials=new Map;passes=new Map;constructor(e={}){this.enabled=e.enabled??!0,this.visibleEdgeColor=[...e.visibleEdgeColor??[1,1,1]],this.edgeStrength=Math.max(0,e.edgeStrength??5),this.edgeThickness=Math.max(0,e.edgeThickness??1.5),this.targetPrefix=e.targetPrefix??"outline",this.maskMaterial=La(!1),this.skinnedMaskMaterial=La(!0)}setSelectedObjects(e){this.selectedObjects.clear();for(const t of e)this.selectedObjects.add(t)}setSelectedInstances(e){this.selectedInstances.length=0;for(const t of e)Number.isInteger(t.instanceIndex)&&t.instanceIndex>=0&&this.selectedInstances.push(t)}addPass(e,t){if(!this.enabled||0===this.selectedObjects.size&&0===this.selectedInstances.length)return t;const r=e.createColorTarget(`${this.targetPrefix}Mask`,{format:"rgba8unorm"}),n=this.selectedObjects;e.addMaterialPass({name:"OutlineMask",outputs:r,loadDepth:!0,objectFilter:e=>null!==e&&function(e,t){for(let r=e;null!==r;r=r.parent)if(t.has(r))return!0;return!1}(e,n),overrideMaterial:(e,t)=>t?this.skinnedMaskMaterial:this.maskMaterial});for(let t=0;t<this.selectedInstances.length;t+=1){const n=this.selectedInstances[t];let i=this.instanceMaskMaterials.get(n.instanceIndex);i||(i=[La(!1,n.instanceIndex),La(!0,n.instanceIndex)],this.instanceMaskMaterials.set(n.instanceIndex,i)),e.addMaterialPass({name:`OutlineInstanceMask${t}-${n.instanceIndex}`,outputs:r,loadColor:!0,loadDepth:!0,objectFilter:e=>e===n.object,overrideMaterial:(e,t)=>t?i[1]:i[0]})}const i=e.createColorTarget(`${this.targetPrefix}Color`,{format:"rgba16float"}),a=`${t}:${r}:${i}`;let s=this.passes.get(a);return s||(s=new za(t,r,i,this),this.passes.set(a,s)),e.addFullscreenPass(s),i}dispose(){this.maskMaterial.dispose(),this.skinnedMaskMaterial.dispose();for(const e of this.instanceMaskMaterials.values())e[0].dispose(),e[1].dispose();this.instanceMaskMaterials.clear(),this.passes.clear()}};function La(e,t=-1){return new kt({vertexShader:`\nstruct VertexInput {\n @location(0) position: vec3<f32>,${e?"\n @location(4) skinIndex: vec4<u32>,\n @location(5) skinWeight: vec4<f32>,":""}\n @builtin(instance_index) instanceIndex: u32,\n};\nstruct VertexOutput {\n @builtin(position) position: vec4<f32>,\n @interpolate(flat) @location(0) batchingId: u32,\n};\n@vertex fn vsMain(input: VertexInput) -> VertexOutput {\n return VertexOutput(\n rendererClipPosition(${e?"rendererSkinPosition(input.position, input.skinIndex, input.skinWeight)":"input.position"}, input.instanceIndex),\n rendererBatchingId(input.instanceIndex)\n );\n}`,fragmentShader:"\nstruct VertexOutput {\n @builtin(position) position: vec4<f32>,\n @interpolate(flat) @location(0) batchingId: u32,\n};\n@fragment fn fsMain(input: VertexOutput) -> @location(0) vec4<f32> {\n if (materialUniforms.selectedInstance >= 0.0 &&\n input.batchingId != u32(materialUniforms.selectedInstance)) { discard; }\n return vec4(1.0);\n}",uniforms:{selectedInstance:t},depthWrite:!1,depthTest:!0})}var za=class{constructor(e,t,r,n){this.state=n,this.inputs={source:e,mask:t},this.outputs=r}state;name="OutlineComposite";sampler="linear";uniformBufferSize=32;inputs;outputs;uniforms=new Float32Array(8);updateUniforms=()=>(this.uniforms.set([this.state.visibleEdgeColor[0],this.state.visibleEdgeColor[1],this.state.visibleEdgeColor[2],this.state.edgeStrength,this.state.edgeThickness,0,0,0]),this.uniforms);fragmentShader="\n@fragment fn fsMain(input: FullscreenVertexOutput) -> @location(0) vec4<f32> {\n let scene = textureSample(sourceTexture, fullscreenSampler, input.uv);\n let texel = 1.0 / vec2<f32>(textureDimensions(maskTexture));\n let radius = max(fullscreenUniforms[1].x, 0.5);\n let center = textureSample(maskTexture, fullscreenSampler, input.uv).r;\n var around = 0.0;\n around = max(around, textureSample(maskTexture, fullscreenSampler, input.uv + vec2(texel.x * radius, 0.0)).r);\n around = max(around, textureSample(maskTexture, fullscreenSampler, input.uv - vec2(texel.x * radius, 0.0)).r);\n around = max(around, textureSample(maskTexture, fullscreenSampler, input.uv + vec2(0.0, texel.y * radius)).r);\n around = max(around, textureSample(maskTexture, fullscreenSampler, input.uv - vec2(0.0, texel.y * radius)).r);\n around = max(around, textureSample(maskTexture, fullscreenSampler, input.uv + texel * radius).r);\n around = max(around, textureSample(maskTexture, fullscreenSampler, input.uv - texel * radius).r);\n let edge = clamp(around - center, 0.0, 1.0);\n let color = fullscreenUniforms[0].rgb * fullscreenUniforms[0].a;\n return vec4(scene.rgb + color * edge, scene.a);\n}"};import{AmbientLight as Ua,BackSide as Va,Bone as Aa,BatchedMesh as Fa,BoxGeometry as Ea,BufferAttribute as ka,BufferGeometry as Oa,CanvasTexture as $a,Color as ja,CompressedArrayTexture as Na,CompressedArrayTexture as Wa,CompressedCubeTexture as _a,CompressedTexture as qa,CubeTexture as Ha,Data3DTexture as Ka,DataArrayTexture as Za,DataTexture as Ya,DepthTexture as Xa,DirectionalLight as Ja,DoubleSide as Qa,FrontSide as es,Group as ts,HemisphereLight as rs,InstancedMesh as ns,MathUtils as is,Matrix4 as as,Mesh as ss,Object3D as os,OrthographicCamera as ls,PerspectiveCamera as cs,PlaneGeometry as us,PointLight as ds,RepeatWrapping as hs,Scene as ps,Skeleton as fs,SkinnedMesh as ms,SphereGeometry as gs,SpotLight as xs,Texture as vs,Vector2 as ws,Vector3 as bs,Vector4 as ys}from"three";export{Ua as AmbientLight,Va as BackSide,Fa as BatchedMesh,va as BloomEffect,Aa as Bone,Ea as BoxGeometry,ka as BufferAttribute,Oa as BufferGeometry,$a as CanvasTexture,ja as Color,Ma as ColorGradingEffect,Na as CompressedArrayTexture,_a as CompressedCubeTexture,qa as CompressedTexture,Wa as CompressedTextureArray,e as ComputeKernel,Ha as CubeTexture,Et as DEFAULT_WGSL_VERTEX_ATTRIBUTES,Ka as Data3DTexture,Za as DataArrayTexture,Ya as DataTexture,Ta as DepthOfFieldEffect,Xa as DepthTexture,Ja as DirectionalLight,Qa as DoubleSide,ma as FXAAEffect,Je as FrameGraphBuilder,es as FrontSide,Ki as GTAOEffect,ts as Group,rs as HemisphereLight,ns as InstancedMesh,is as MathUtils,as as Matrix4,ss as Mesh,os as Object3D,ls as OrthographicCamera,Ra as OutlineEffect,cs as PerspectiveCamera,us as PlaneGeometry,ds as PointLight,qt as RenderGraph,hs as RepeatWrapping,ra as SSREffect,ps as Scene,fs as Skeleton,ms as SkinnedMesh,gs as SphereGeometry,xs as SpotLight,da as TemporalAAEffect,vs as Texture,w as VOLUMETRIC_FOG_MATERIAL_WGSL,ws as Vector2,bs as Vector3,ys as Vector4,f as VolumetricFogEffect,c as VolumetricFogVolumeObject,kt as WGSLShaderMaterial,rr as WebGpuPMREMGenerator,Wi as WebGpuRenderer,b as configureVolumetricFogMaterial};
|