@hology/webgpu-renderer 0.1.29 → 0.1.30
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.d.ts +22 -2
- package/dist/index.js +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var e=new WeakMap;function t(t,i,r){const n=e.get(t);n&&(i?(n.loadingStartedAt=performance.now(),n.loadingRequests=[]):n.loading&&(!function(e,t){const i=e.loadingRequests,r=new Map;for(const e of i){const t=e.kind+":"+(e.origin?.key??e.label??"unlabelled"),i=r.get(t);i?i.push(e):r.set(t,[e])}const n=(console.groupCollapsed??console.info).bind(console),a=(console.table??console.info).bind(console);n("[Hology shaders] Loading compilation summary: "+t),console.info("New creation requests during this load (previously cached pipelines are excluded)",{elapsedMs:Math.round(performance.now()-e.loadingStartedAt),...l(i),render:l(i.filter(e=>"render"===e.kind)),compute:l(i.filter(e=>"compute"===e.kind)),gpuVfx:l(i.filter(e=>e.origin?.key.startsWith("gpu-vfx:")))}),a([...r].map(([e,t])=>({origin:e,...l(t)})).sort((e,t)=>t.uniquePipelineVariants-e.uniquePipelineVariants)),console.info("Slowest creation requests",[...i].sort((e,t)=>t.durationMs-e.durationMs).slice(0,20).map(({signature:e,shaders:t,state:i,...r})=>r));const s=u(i);a(s.map(({variants:e,...t})=>t)),console.info("GPU VFX variant report (copy this array)",s);const o=u(i,!1);a(o.map(({variants:e,...t})=>t)),console.info("Material variant report (copy this array)",o),console.info("VFX groups attribute each created pipeline to its first requester; cache-hit users are not enumerated. Difference fields compare against the first variant in each group and do not prove why shader source changed."),console.info("Counts use descriptor signatures and shader source fingerprints, not material counts. Async totals overlap; sync timings measure handle creation, not full GPU compilation. GPU VFX attribution excludes CPU-simulated VFX drawn through ordinary mesh pipelines."),console.groupEnd?.()}(n,r),n.loadingRequests=[]),n.loading=i,n.phase=r)}function i(t,i,r){const n=e.get(t);n&&(n.origins.size>=4096&&!n.origins.has(i)&&n.origins.delete(n.origins.keys().next().value),n.origins.set(i,r))}function r(t,i){const r=e.get(t),n=r?.origins.get(i.label??"");n&&r.descriptorOrigins.set(i,n)}function n(e){let t=2166136261;for(let i=0;i<e.length;i++)t=Math.imul(t^e.charCodeAt(i),16777619);return(t>>>0).toString(16)}function a(e,t){if(null==e||"object"!=typeof e)return e;const i=t.objects.get(e);if(null!=i)return i;if(Array.isArray(e))return e.map(e=>a(e,t));const r={};for(const i of Object.keys(e).sort())"label"!==i&&(r[i]=a(e[i],t));return r}function s(e,t,i=""){if(JSON.stringify(e)===JSON.stringify(t))return[];if(e&&t&&"object"==typeof e&&"object"==typeof t){const r=e,n=t;return[...new Set([...Object.keys(r),...Object.keys(n)])].flatMap(e=>s(r[e],n[e],i?i+"."+e:e))}return[{field:i,previous:e,current:t}]}function o(e){const t=[];for(const i of["vertex","fragment","compute"]){const r=e[i]?.module;r?.shaderHash&&t.push(r.shaderHash+":"+r.codeLength)}return t}function l(e){const t=new Set(e.map(e=>e.kind+":"+e.signature));return{requests:e.length,uniquePipelineVariants:t.size,uniqueShaderSources:new Set(e.flatMap(e=>e.shaders)).size,duplicateRequests:e.length-t.size,failed:e.filter(e=>"failed"===e.status).length,pending:e.filter(e=>"pending"===e.status).length,asyncReadyTotalMs:Math.round(e.reduce((e,t)=>e+(t.async?t.durationMs:0),0)),syncCreationTotalMs:Math.round(e.reduce((e,t)=>e+(t.async?0:t.durationMs),0))}}function c(e){const t={...e};for(const i of["vertex","fragment","compute"])if(null!=e[i]){const{module:r,...n}=e[i];t[i]=n}return t}function u(e,t=!0){const i=new Map;for(const r of e){if("render"!==r.kind||Boolean(r.origin?.key.startsWith("gpu-vfx:"))!==t)continue;const e=r.origin?.shader,n=r.origin?.material,a=t?e?.key??"unattributed":String(n?.assetId??n?.sourceUuid??r.origin?.key.replace(/:(forward|depth:.*)$/,"")??r.label??"unattributed"),s=i.get(a);s?s.push(r):i.set(a,[r])}return[...i].map(([e,i])=>{const r=[...new Map(i.map(e=>[e.signature,e])).values()],a=c(r[0].state),o=r[0].origin?.shader,u=r.map(e=>{const t=c(e.state);return{pipelineId:n(e.signature),origin:e.origin?.key,material:e.origin?.material,shaderSources:[...new Set(e.shaders)],stageSources:Object.fromEntries(["vertex","fragment"].filter(t=>null!=e.state[t]).map(t=>[t,e.state[t].module])),stateId:n(JSON.stringify(t)),layoutId:n(JSON.stringify(t.layout??null)),stateDifferenceFields:s(a,t).map(e=>e.field),shaderProfileDifferences:s(o,e.origin?.shader),shader:e.origin?.shader,features:e.origin?.variant,featureDifferences:s(r[0].origin?.variant,e.origin?.variant),defines:e.origin?.defines,bindings:e.origin?.bindings,assets:e.origin?.vfxAssets,pipelineState:t,readyAfterMs:Math.round(e.durationMs),status:e.status}});return{graph:e,name:t?i[0].origin?.shader?.name??e:i[0].origin?.material?.assetName||i[0].origin?.material?.name||e,...l(i),shaderCombinations:new Set(r.map(e=>JSON.stringify(e.shaders))).size,pipelineStates:new Set(u.map(e=>e.stateId)).size,layouts:new Set(u.map(e=>e.layoutId)).size,variants:u}}).sort((e,t)=>t.uniquePipelineVariants-e.uniquePipelineVariants)}function d(e,t){e.userData.detailCulling=t}var h=Object.freeze({minScreenSize:10,maxDistance:0,shadowMinScreenSize:2,shadowMaxDistance:0}),p=[];function f(e,t){let i=!!t;for(let t=e;t&&!i;t=t.parent)i=!!t.userData.detailCulling;if(!i)return h;let r=!0,{minScreenSize:n,maxDistance:a,shadowMinScreenSize:s,shadowMaxDistance:o}=h,l=!0;const c=e=>{e&&(r=e.enabled??r,n=e.minScreenSize??n,a=e.maxDistance??a,l=e.shadow?.enabled??l,s=e.shadow?.minScreenSize??s,o=e.shadow?.maxDistance??o)};c(t),p.length=0;for(let t=e;t;t=t.parent)p.push(t);for(let e=p.length-1;e>=0;e--)c(p[e].userData.detailCulling);const u=e=>Number.isFinite(e)&&e>0?e:0;return{minScreenSize:r?u(n):0,maxDistance:u(a),shadowMinScreenSize:l?u(s):0,shadowMaxDistance:u(o)}}var m=class{rowXLength=1;rowYLength=1;rowWLength=0;update(e){const t=e.elements;this.rowXLength=Math.hypot(t[0],t[4],t[8]),this.rowYLength=Math.hypot(t[1],t[5],t[9]),this.rowWLength=Math.hypot(t[3],t[7],t[11])}};function g(e,t,i,r,n,a,s,o,l){if(o>0&&e.distanceTo(a)-t>o)return!1;if(s<=0)return!0;const c=i.elements,u=e.x,d=e.y,h=e.z,p=c[3]*u+c[7]*d+c[11]*h+c[15],f=l?.rowWLength??Math.hypot(c[3],c[7],c[11]),m=p-t*f;if(m<=1e-4)return!0;const g=(c[0]*u+c[4]*d+c[8]*h+c[12])/p,v=(c[1]*u+c[5]*d+c[9]*h+c[13])/p,x=l?.rowXLength??Math.hypot(c[0],c[4],c[8]),w=l?.rowYLength??Math.hypot(c[1],c[5],c[9]);return t*Math.max((x+Math.abs(g)*f)*r,(w+Math.abs(v)*f)*n)/m>=s}function v(e,t,i,r,n,a){const s=e.boundsCenter,o=e.boundsRadius;if(e.maxDistance>0&&s.distanceTo(n)-o>e.maxDistance)return!1;if(e.minScreenSize<=0)return!0;const l=t.elements,c=s.x,u=s.y,d=s.z,h=a?.rowWLength??Math.hypot(l[3],l[7],l[11]),p=l[3]*c+l[7]*u+l[11]*d+l[15]-o*h;if(p<=1e-4)return!0;const f=a?.rowXLength??Math.hypot(l[0],l[4],l[8]),m=a?.rowYLength??Math.hypot(l[1],l[5],l[9]),g=(Math.abs(l[0]*c+l[4]*u+l[8]*d+l[12])+o*f)/p,v=(Math.abs(l[1]*c+l[5]*u+l[9]*d+l[13])+o*m)/p;return e.maxMemberRadius*Math.max((f+g*h)*i,(m+v*h)*r)/p>=.85*e.minScreenSize}import{Matrix4 as x,Sphere as w,Vector3 as b}from"three";var y=64,S=64,C=40,M=12,P=new Float32Array(C),B=new Float32Array([1,1,1,1]),D="rgba16float",I="rgba8unorm",T=(new x).set(1,0,0,0,0,1,0,0,0,0,.5,.5,0,0,0,1),R=[new b(0,-1,0),new b(0,-1,0),new b(0,0,1),new b(0,0,-1),new b(0,-1,0),new b(0,-1,0)],V=[new b(1,0,0),new b(-1,0,0),new b(0,1,0),new b(0,-1,0),new b(0,0,1),new b(0,0,-1)],G=4004,z=[{name:"position",shaderLocation:0,format:"float32x3"}],L=[{name:"position",shaderLocation:0,format:"float32x3"},{name:"skinIndex",shaderLocation:1,format:"uint32x4"},{name:"skinWeight",shaderLocation:2,format:"float32x4"}],U=new x,A=new x,k=(new x,new x,new w),F=new b,O=new b,E=new b,j=(new b,new b,new b,new b,new WeakMap);async function $(e,t){const i=j.get(e)??Promise.resolve();let r;const n=new Promise(e=>{r=e});j.set(e,i.catch(()=>{}).then(()=>n)),await i.catch(()=>{});try{return await new Promise(e=>requestAnimationFrame(()=>e())),t()}finally{r()}}function W(e,t){return r(e,t),"function"==typeof e.createRenderPipelineAsync?e.createRenderPipelineAsync(t):$(e,()=>e.createRenderPipeline(t))}function N(e,t){return r(e,t),"function"==typeof e.createComputePipelineAsync?e.createComputePipelineAsync(t):$(e,()=>e.createComputePipeline(t))}var _=class e{layout;pipeline;static async createAsync(t,i){const{pipelineDescriptor:r}=H(t,i),n=await N(t,r);return new e(t,i,n)}constructor(e,t,i){if(i)return this.layout=i.getBindGroupLayout(0),void(this.pipeline=i);const{layout:r,pipelineDescriptor:n}=H(e,t);this.layout=r,this.pipeline=e.createComputePipeline(n)}createBindGroup(e,t,i){return e.createBindGroup({label:i,layout:this.layout,entries:t})}};function H(e,t){const i=e.createBindGroupLayout({label:t.label?`${t.label}-layout`:void 0,entries:t.bindGroupLayoutEntries});return{layout:i,pipelineDescriptor:{label:t.label,layout:e.createPipelineLayout({label:t.label?`${t.label}-pipeline-layout`:void 0,bindGroupLayouts:[i]}),compute:{module:e.createShaderModule({label:t.label?`${t.label}-module`:void 0,code:t.code}),entryPoint:t.entryPoint??"main"}}}}import{DirectionalLight as q,DoubleSide as K,Light as Y,NoBlending as Z,PointLight as X,SpotLight as J,Vector3 as Q}from"three";var ee="\nfn rendererSdfgiSample(worldPosition: vec3<f32>, worldNormal: vec3<f32>, bank: u32) -> vec3<f32> {\n let originCell = sdfgiField[bank + 0];\n let settings = sdfgiField[bank + 1]; // spacing, probe count per axis, intensity, normal bias\n if (settings.z <= 0.0 || sdfgiField[bank + 2].x < 0.5) { return vec3<f32>(0.0); }\n let n = u32(settings.y);\n let normal = normalize(worldNormal);\n let position = worldPosition + normal * settings.w;\n let local = (position - originCell.xyz - vec3<f32>(originCell.w * 2.0)) / settings.x;\n let edge = min(local, vec3<f32>(f32(n - 1u)) - local);\n let fade = smoothstep(0.0, 1.0, min(edge.x, min(edge.y, edge.z)));\n if (fade <= 0.0) { return vec3<f32>(0.0); }\n // Quadratic B-spline support overlaps two probe planes at a cell boundary.\n // Trilinear's single shared plane can consist entirely of inactive probes\n // near geometry, causing a discontinuous normalized blend and square seams.\n let base = vec3<i32>(floor(local + vec3<f32>(0.5))) - vec3<i32>(1);\n var result = vec3<f32>(0.0);\n var weightSum = 0.0;\n var unoccludedWeightSum = 0.0;\n for (var neighbor = 0u; neighbor < 27u; neighbor++) {\n let cell = base + vec3<i32>(i32(neighbor % 3u), i32((neighbor / 3u) % 3u), i32(neighbor / 9u));\n if (any(cell < vec3<i32>(0)) || any(cell >= vec3<i32>(i32(n)))) { continue; }\n let distance = abs(local - vec3<f32>(cell));\n let tail = max(vec3<f32>(1.5) - distance, vec3<f32>(0.0));\n let spatial = select(0.5 * tail * tail, vec3<f32>(0.75) - distance * distance, distance <= vec3<f32>(0.5));\n let spatialWeight = spatial.x * spatial.y * spatial.z;\n if (spatialWeight <= 0.0) { continue; }\n let index = 4u + u32(cell.x + i32(n) * (cell.y + i32(n) * cell.z)) * 10u;\n if (sdfgiField[bank + index].w < 0.5) { continue; }\n let probePosition = originCell.xyz + vec3<f32>(originCell.w * 2.0) + vec3<f32>(cell) * settings.x;\n let delta = position - probePosition;\n let distanceToProbe = length(delta);\n let direction = delta / max(distanceToProbe, 0.0001);\n // Keep directional bounds separate. Averaging a nearby wall with an open\n // direction creates a large variance that incorrectly admits light through\n // the wall. Moments store distances projected onto each cardinal axis.\n var visibility = 1.0;\n for (var axis = 0u; axis < 3u; axis++) {\n let moment = sdfgiField[bank + index + 4u + axis * 2u + select(1u, 0u, delta[axis] >= 0.0)].xy;\n let variance = max(moment.y - moment.x * moment.x, originCell.w * originCell.w * 0.001);\n let difference = max(abs(delta[axis]) - moment.x - originCell.w * 0.05, 0.0);\n let bound = variance / (variance + difference * difference);\n visibility = min(visibility, bound * bound * bound);\n }\n let facing = max(0.05, dot(-direction, normal) * 0.5 + 0.5);\n let unoccludedWeight = spatialWeight * facing * facing;\n let weight = unoccludedWeight * visibility;\n let irradiance = sdfgiField[bank + index].xyz * 0.282095\n + sdfgiField[bank + index + 1u].xyz * (0.488603 * normal.x)\n + sdfgiField[bank + index + 2u].xyz * (0.488603 * normal.y)\n + sdfgiField[bank + index + 3u].xyz * (0.488603 * normal.z);\n result += max(irradiance, vec3<f32>(0.0)) * weight;\n weightSum += weight;\n unoccludedWeightSum += unoccludedWeight;\n }\n // Visibility and normal weights can be tiny near walls or inactive probes.\n // A large denominator floor turns those weights into dark lattice patches\n // instead of normalizing the remaining valid irradiance.\n // Normalization must not amplify an entirely occluded neighborhood back to\n // full brightness. Fade unsupported lighting continuously instead of using\n // a fixed denominator cutoff that would expose the probe lattice again.\n let support = weightSum / max(unoccludedWeightSum, 1e-8);\n let confidence = smoothstep(0.0, 0.1, support);\n return result / max(weightSum, 1e-8) * (fade * confidence);\n}\nfn rendererSdfgiIrradiance(worldPosition: vec3<f32>, worldNormal: vec3<f32>) -> vec3<f32> {\n let intensity = sdfgiField[1].z;\n if (intensity <= 0.0 || sdfgiField[2].x < 0.5) { return vec3<f32>(0.0); }\n let blend = sdfgiField[2].y;\n var previous = vec3<f32>(0.0);\n if (blend < 1.0 && sdfgiField[2].z > 0.5) {\n previous = rendererSdfgiSample(worldPosition, worldNormal, u32(sdfgiField[3].x));\n }\n if (blend <= 0.0) { return previous * intensity; }\n let current = rendererSdfgiSample(worldPosition, worldNormal, 0u);\n return mix(previous, current, blend) * intensity;\n}\n";var te="\nstruct Params {\n originCell: vec4<f32>,\n grid: vec4<u32>, // voxel resolution, probe resolution, ray count, frame\n settings: vec4<f32>, // probe spacing, history weight, bias, max ray distance\n sky: vec4<f32>,\n update: vec4<u32>, // first probe, probe count, reset history, maximum steps\n lights: vec4<u32>, // count\n};\nfn cellIndex(cell: vec3<u32>, n: u32) -> u32 { return cell.x + n * (cell.y + n * cell.z); }\nfn cellPosition(index: u32, n: u32) -> vec3<u32> { return vec3<u32>(index % n, (index / n) % n, index / (n * n)); }\n",ie=te+"\n@group(0) @binding(0) var<uniform> params: Params;\n@group(0) @binding(1) var<storage, read> surfaces: array<vec4<f32>>;\n@group(0) @binding(2) var<storage, read_write> output: array<vec4<i32>>;\n@compute @workgroup_size(64)\nfn main(@builtin(global_invocation_id) id: vec3<u32>) {\n let n = params.grid.x;\n if (id.x >= n * n * n) { return; }\n let cell = cellPosition(id.x, n);\n output[id.x] = vec4<i32>(vec3<i32>(cell), select(0, 1, surfaces[id.x * 3u].w > 0.0));\n}\n",re=te+"\n@group(0) @binding(0) var<uniform> params: Params;\n@group(0) @binding(1) var<uniform> jump: vec4<u32>;\n@group(0) @binding(2) var<storage, read> source: array<vec4<i32>>;\n@group(0) @binding(3) var<storage, read_write> output: array<vec4<i32>>;\n@compute @workgroup_size(64)\nfn main(@builtin(global_invocation_id) id: vec3<u32>) {\n let n = params.grid.x;\n if (id.x >= n * n * n) { return; }\n let position = vec3<i32>(cellPosition(id.x, n));\n var nearest = source[id.x];\n var best = 1e20;\n if (nearest.w != 0) { let delta = vec3<f32>(nearest.xyz - position); best = dot(delta, delta); }\n for (var z = -1; z <= 1; z++) { for (var y = -1; y <= 1; y++) { for (var x = -1; x <= 1; x++) {\n let cell = position + vec3<i32>(x, y, z) * i32(jump.x);\n if (any(cell < vec3<i32>(0)) || any(cell >= vec3<i32>(i32(n)))) { continue; }\n let candidate = source[cellIndex(vec3<u32>(cell), n)];\n if (candidate.w == 0) { continue; }\n let delta = vec3<f32>(candidate.xyz - position);\n let distanceSquared = dot(delta, delta);\n if (distanceSquared < best) { nearest = candidate; best = distanceSquared; }\n } } }\n output[id.x] = nearest;\n}\n",ne="\nfn distanceField(position: vec3<f32>) -> vec2<f32> {\n let local = (position - params.originCell.xyz) / params.originCell.w;\n let n = params.grid.x;\n if (any(local < vec3<f32>(0.0)) || any(local >= vec3<f32>(f32(n)))) { return vec2<f32>(params.settings.w, -1.0); }\n let seed = nearest[cellIndex(vec3<u32>(local), n)];\n if (seed.w == 0) { return vec2<f32>(params.settings.w, -1.0); }\n // Distance to the voxel box. A circumscribed sphere inflates its faces and\n // corners, making nearby receivers appear occluded even outside the voxel.\n let distance = length(max(abs(local - vec3<f32>(seed.xyz) - vec3<f32>(0.5)) - vec3<f32>(0.5), vec3<f32>(0.0)));\n return vec2<f32>(distance * params.originCell.w, f32(cellIndex(vec3<u32>(seed.xyz), n)));\n}\nfn trace(origin: vec3<f32>, direction: vec3<f32>, limit: f32) -> vec2<f32> {\n var distance = 0.0;\n for (var step = 0u; step < params.update.w; step++) {\n let sample = distanceField(origin + direction * distance);\n if (sample.y < 0.0) { return vec2<f32>(-1.0, limit); }\n if (sample.x < params.originCell.w * 0.2) { return vec2<f32>(sample.y, distance); }\n distance += max(sample.x * 0.8, params.originCell.w * 0.2);\n if (distance >= limit) { return vec2<f32>(-1.0, limit); }\n }\n // A step-budget miss is conservatively occluded, avoiding light leaks.\n return vec2<f32>(-2.0, distance);\n}\n",ae=te+"\n@group(0) @binding(0) var<uniform> params: Params;\n@group(0) @binding(1) var<storage, read> surfaces: array<vec4<f32>>;\n@group(0) @binding(2) var<storage, read> nearest: array<vec4<i32>>;\n@group(0) @binding(3) var<storage, read> lights: array<vec4<f32>>;\n@group(0) @binding(4) var<storage, read_write> radiance: array<vec4<f32>>;\n"+ne+"\n@compute @workgroup_size(64)\nfn main(@builtin(global_invocation_id) id: vec3<u32>) {\n let n = params.grid.x;\n if (id.x >= n * n * n) { return; }\n let albedo = surfaces[id.x * 3u];\n if (albedo.w == 0.0) { radiance[id.x * 2u] = vec4<f32>(0.0); radiance[id.x * 2u + 1u] = vec4<f32>(0.0); return; }\n let surface = surfaces[id.x * 3u + 1u];\n let position = params.originCell.xyz + (vec3<f32>(cellPosition(id.x, n)) + vec3<f32>(0.5)) * params.originCell.w;\n var illumination = vec3<f32>(0.0);\n var backIllumination = vec3<f32>(0.0);\n for (var light = 0u; light < params.lights.x; light++) {\n let source = lights[light * 4u]; // position/directional flag\n let color = lights[light * 4u + 1u].xyz;\n let directionRange = lights[light * 4u + 2u];\n let coneDecay = lights[light * 4u + 3u];\n var direction = directionRange.xyz;\n var limit = params.settings.w;\n var attenuation = 1.0;\n if (source.w > 0.5) {\n let delta = source.xyz - position;\n limit = length(delta);\n direction = delta / max(limit, 0.0001);\n attenuation = 1.0 / max(pow(limit, coneDecay.z), 0.01);\n if (directionRange.w > 0.0) {\n let ratio = limit / directionRange.w;\n attenuation *= pow(clamp(1.0 - pow(ratio, 4.0), 0.0, 1.0), 2.0);\n }\n if (source.w > 1.5) {\n let cone = dot(-direction, directionRange.xyz);\n if (coneDecay.y - coneDecay.x > 0.00001) { attenuation *= smoothstep(coneDecay.x, coneDecay.y, cone); }\n else { attenuation *= select(0.0, 1.0, cone >= coneDecay.x); }\n }\n }\n let cosine = select(max(dot(surface.xyz, direction), 0.0), abs(dot(surface.xyz, direction)), surface.w > 0.5);\n if (cosine * attenuation <= 0.00001) { continue; }\n let biasNormal = surface.xyz * select(1.0, -1.0, dot(surface.xyz, direction) < 0.0);\n let shadow = trace(position + biasNormal * params.originCell.w * 1.8, direction, limit);\n if (shadow.x == -1.0) {\n if (dot(surface.xyz, direction) >= 0.0) { illumination += color * (cosine * attenuation); }\n else { backIllumination += color * (cosine * attenuation); }\n }\n }\n // Keep both sides separate so a double-sided wall cannot transmit sunlight.\n let emission = surfaces[id.x * 3u + 2u].xyz;\n radiance[id.x * 2u] = vec4<f32>(emission + albedo.xyz * illumination * 0.318309886, 1.0);\n radiance[id.x * 2u + 1u] = vec4<f32>(emission + albedo.xyz * backIllumination * 0.318309886, 1.0);\n}\n",se=te+"\n@group(0) @binding(0) var<uniform> params: Params;\n@group(0) @binding(1) var<storage, read> surfaces: array<vec4<f32>>;\n@group(0) @binding(2) var<storage, read> nearest: array<vec4<i32>>;\n@group(0) @binding(3) var<storage, read> radiance: array<vec4<f32>>;\n@group(0) @binding(4) var<storage, read_write> field: array<vec4<f32>>;\n"+ne+"\n@compute @workgroup_size(32)\nfn main(@builtin(global_invocation_id) id: vec3<u32>) {\n if (id.x >= params.update.y) { return; }\n let p = params.grid.y;\n let probe = (params.update.x + id.x) % (p * p * p);\n let base = 4u + probe * 10u;\n let position = params.originCell.xyz + vec3<f32>(params.originCell.w * 2.0)\n + vec3<f32>(cellPosition(probe, p)) * params.settings.x;\n if (distanceField(position).x < params.originCell.w * 0.6) {\n for (var i = 0u; i < 10u; i++) { field[base + i] = vec4<f32>(0.0); }\n return;\n }\n var coefficients: array<vec3<f32>, 4>;\n var moments: array<vec3<f32>, 6>;\n let count = params.grid.z;\n // Keep each probe's integration directions stable. Rotating every update\n // repeatedly hits/misses small emissive surfaces and makes their light pulse,\n // including in a completely stationary scene. Different probes retain\n // different azimuths to avoid aligning sampling errors across the lattice.\n // Seed from the global lattice coordinate, never the index in the moving\n // volume, so a retained world probe traces the same rays after a scroll.\n let worldProbe = bitcast<vec3<u32>>(vec3<i32>(round((position - vec3<f32>(params.originCell.w * 2.0)) / params.settings.x)));\n var hash = (worldProbe.x * 73856093u) ^ (worldProbe.y * 19349663u) ^ (worldProbe.z * 83492791u);\n hash = hash ^ (hash >> 16u);\n let rotation = f32(hash & 65535u) * (6.283185307 / 65536.0);\n for (var ray = 0u; ray < count; ray++) {\n let y = 1.0 - 2.0 * (f32(ray) + 0.5) / f32(count);\n let radius = sqrt(max(0.0, 1.0 - y * y));\n let angle = f32(ray) * 2.39996323 + rotation;\n let direction = vec3<f32>(cos(angle) * radius, y, sin(angle) * radius);\n let hit = trace(position, direction, params.settings.w);\n var visibilityDistance = hit.y;\n var incoming = vec3<f32>(0.0);\n if (hit.x == -1.0) { incoming = params.sky.xyz; }\n if (hit.x >= 0.0) {\n let index = u32(hit.x);\n let normal = surfaces[index * 3u + 1u];\n // Trace conservatively against voxel boxes, but measure visibility to\n // the captured physical surface plane. Using the thick voxel shell here\n // falsely hides floor-adjacent receivers behind the floor's own voxels.\n let center = params.originCell.xyz + (vec3<f32>(cellPosition(index, params.grid.x)) + vec3<f32>(0.5)) * params.originCell.w;\n let plane = center + normal.xyz * surfaces[index * 3u + 2u].w;\n let denominator = dot(direction, normal.xyz);\n if (abs(denominator) > 0.0001) {\n let planeDistance = dot(plane - position, normal.xyz) / denominator;\n let intersection = position + direction * planeDistance;\n if (planeDistance >= 0.0 && all(abs(intersection - center) <= vec3<f32>(params.originCell.w * 1.5))) {\n visibilityDistance = planeDistance;\n }\n }\n let front = dot(normal.xyz, -direction) > 0.0;\n if (normal.w > 0.5 || front) { incoming = radiance[index * 2u + select(1u, 0u, front)].xyz; }\n }\n coefficients[0] += incoming * 0.282095;\n coefficients[1] += incoming * (0.488603 * direction.x);\n coefficients[2] += incoming * (0.488603 * direction.y);\n coefficients[3] += incoming * (0.488603 * direction.z);\n for (var axis = 0u; axis < 6u; axis++) {\n var axisDirection = vec3<f32>(0.0);\n axisDirection[axis / 2u] = select(-1.0, 1.0, axis % 2u == 0u);\n let projection = max(dot(direction, axisDirection), 0.0);\n let weight = pow(projection, 8.0);\n let distance = visibilityDistance * projection;\n moments[axis] += vec3<f32>(distance, distance * distance, 1.0) * weight;\n }\n }\n let history = select(0.0, params.settings.y, params.update.z == 0u && field[base].w > 0.5);\n for (var i = 0u; i < 4u; i++) {\n let convolution = select(2.094395102, 3.141592654, i == 0u);\n let value = coefficients[i] * (12.566370614 / f32(count)) * convolution;\n field[base + i] = vec4<f32>(mix(value, field[base + i].xyz, history), 1.0);\n }\n for (var i = 0u; i < 6u; i++) {\n let value = moments[i].xy / max(moments[i].z, 0.00001);\n field[base + 4u + i] = vec4<f32>(mix(value, field[base + 4u + i].xy, history), 0.0, 0.0);\n }\n}\n";function oe(e,t,i,r){return null!=e&&Number.isFinite(e)?Math.min(r,Math.max(i,e)):t}function le(e,t,i,r,n,a){e[t]=i,e[t+1]=r,e[t+2]=n,e[t+3]=a}var ce={label:"SDFGISeed"},ue={label:"SDFGIJumpFlood"},de={label:"SDFGILightInjection"},he={label:"SDFGIProbeUpdate"},pe={label:"SDFGIProbeSnapshot"},fe=class e{constructor(t,i={}){if(this.device=t,this.resolution=i.resolution??64,![32,64,128].includes(this.resolution))throw new Error("SDFGI resolution must be 32, 64, or 128.");this.extent=oe(i.extent,48,4,4096),this.probeResolution=Math.round(oe(i.probeResolution,12,4,24)),this.cellSize=this.extent/this.resolution,this.spacing=this.cellSize*Math.max(1,Math.floor((this.resolution-4)/(this.probeResolution-1))),this.setOptions(i);const r=this.resolution**3,n=(e,i,r=!1)=>{if(!r&&i>t.limits.maxStorageBufferBindingSize)throw new Error(`SDFGI ${e} exceeds the adapter's storage buffer limit.`);const n=t.createBuffer({label:`sdfgi-${e}`,size:i,usage:(r?GPUBufferUsage.UNIFORM:GPUBufferUsage.STORAGE)|GPUBufferUsage.COPY_DST|("probes"===e||"surfaces"===e||"surface-statistics"===e?GPUBufferUsage.COPY_SRC:0)});return this.buffers.push(n),this.stats.gpuBytes+=i,n};this.params=n("params",96,!0),this.surfaces=n("surfaces",48*r),this.fieldBankBytes=16*(4+this.probeResolution**3*10),this.field=n("probes",2*this.fieldBankBytes),this.lightBuffer=n("lights",this.lightData.byteLength),this.surfaceConfig=n("surface-config",32),this.surfaceAccum=n("surface-accum",32*r),this.surfaceStatistics=n("surface-statistics",16);const a=[n("nearest-a",16*r),n("nearest-b",16*r)],s=n("radiance",32*r),o=(e,i,r)=>new _(t,{label:`sdfgi-${e}`,code:i,bindGroupLayoutEntries:r.map((e,t)=>((e,t)=>({binding:e,visibility:GPUShaderStage.COMPUTE,buffer:{type:t}}))(t,e))}),l=(e,i)=>e.createBindGroup(t,i.map((e,t)=>({binding:t,resource:{buffer:e}})));this.snapshot=o("probe-snapshot","\n@group(0) @binding(0) var<storage, read_write> field: array<vec4<f32>>;\n@compute @workgroup_size(64)\nfn main(@builtin(global_invocation_id) id: vec3<u32>) {\n let bankSize = arrayLength(&field) / 2u;\n let index = id.x + 4u;\n if (index < bankSize) { field[bankSize + index] = field[index]; }\n}\n",["storage"]),this.snapshotBinding=l(this.snapshot,[this.field]),this.resolveSurface=o("resolve-surface","\n@group(0) @binding(0) var<storage, read> config: array<vec4<f32>>;\n@group(0) @binding(1) var<storage, read> accum: array<u32>;\n@group(0) @binding(2) var<storage, read_write> surfaces: array<vec4<f32>>;\n@group(0) @binding(3) var<storage, read_write> statistics: array<atomic<u32>>;\n@compute @workgroup_size(64)\nfn main(@builtin(global_invocation_id) id: vec3<u32>) {\n let n = u32(config[1].x);\n if (id.x >= n * n * n) { return; }\n let base = id.x * 8u;\n let count = accum[base];\n if (count == 0u) {\n surfaces[id.x * 3u] = vec4<f32>(0.0);\n surfaces[id.x * 3u + 1u] = vec4<f32>(0.0);\n surfaces[id.x * 3u + 2u] = vec4<f32>(0.0);\n return;\n }\n let inverseCount = 1.0 / f32(count);\n let color = vec3<f32>(f32(accum[base + 1u]), f32(accum[base + 2u]), f32(accum[base + 3u])) * (inverseCount / 4096.0);\n let emission = vec3<f32>(f32(accum[base + 4u]), f32(accum[base + 5u]), f32(accum[base + 6u])) * (inverseCount / 1024.0);\n let packed = accum[base + 7u];\n let packedNormal = unpack4x8snorm(packed & 0x00ffffffu);\n let metadata = packed >> 24u;\n let doubleSided = f32(metadata >> 7u);\n let planeOffset = (f32(metadata & 127u) / 127.0 - 0.5) * 3.0 * config[0].w;\n let normal = packedNormal.xyz * inverseSqrt(max(dot(packedNormal.xyz, packedNormal.xyz), 0.0001));\n surfaces[id.x * 3u] = vec4<f32>(color, 1.0);\n surfaces[id.x * 3u + 1u] = vec4<f32>(normal, doubleSided);\n surfaces[id.x * 3u + 2u] = vec4<f32>(emission, planeOffset);\n atomicAdd(&statistics[0], 1u);\n}\n",["read-only-storage","read-only-storage","storage","storage"]),this.resolveSurfaceBinding=l(this.resolveSurface,[this.surfaceConfig,this.surfaceAccum,this.surfaces,this.surfaceStatistics]),this.seed=o("seed",ie,["uniform","read-only-storage","storage"]),this.seedBinding=l(this.seed,[this.params,this.surfaces,a[0]]);const c=o("jump-flood",re,["uniform","uniform","read-only-storage","storage"]);let u=0;for(let e=this.resolution/2;e>=.5;e/=2){const i=n(`jump-${this.jumps.length}`,16,!0);t.queue.writeBuffer(i,0,new Uint32Array([Math.max(1,e),0,0,0])),this.jumps.push({kernel:c,binding:l(c,[this.params,i,a[u],a[1-u]])}),u=1-u}if(this.inject=o("light-injection",ae,["uniform","read-only-storage","read-only-storage","read-only-storage","storage"]),this.injectBinding=l(this.inject,[this.params,this.surfaces,a[u],this.lightBuffer,s]),this.probes=o("probe-update",se,["uniform","read-only-storage","read-only-storage","read-only-storage","storage"]),this.probeBinding=l(this.probes,[this.params,this.surfaces,a[u],s,this.field]),i.cascades){const r=i.cascades,n=Math.round(oe(r.count,2,2,3)),a=oe(r.extentScale,2,1.5,8),s=Math.round(oe(r.updateInterval,4,1,60)),o=Math.round(oe(r.raysPerProbe,32,16,256)),l=oe(r.updateFraction,.125,.01,1);this.distantVolumes=[];try{for(let c=1;c<n;c++){const n=this.extent*a**c;if(n>4096)throw new Error("SDFGI cascade extent exceeds 4096.");const u=new e(t,{...i,cascades:!1,extent:n,resolution:r.resolution??32,probeResolution:r.probeResolution??8,raysPerProbe:Math.min(this.rays,o),updateFraction:Math.min(this.fraction,l)});this.distantVolumes.push({volume:u,interval:s*2**(c-1),rays:o,fraction:l,scheduled:!1,settingsDirty:!1}),this.stats.gpuBytes+=u.stats.gpuBytes}}catch(e){throw this.dispose(),e}this.stats.cascadeCount=n}}device;stats={cascadeCount:1,ready:!1,building:!1,triangles:0,occupiedCells:0,geometryCpuMs:0,geometryBuildMs:0,gpuBytes:0,updatedProbes:0};resolution;extent;probeResolution;cellSize;spacing;enabled=!0;intensity=1;rays=64;fraction=.25;history=.85;steps=64;sky=[0,0,0];buffers=[];uniformData=new ArrayBuffer(96);floats=new Float32Array(this.uniformData);integers=new Uint32Array(this.uniformData);header=new Float32Array(16);lightData=new Float32Array(256);field;fieldBankBytes;snapshot;snapshotBinding;populatedProbes=0;blend=1;previousValid=!1;lastUpdateSeconds=0;params;surfaces;seed;seedBinding;jumps=[];inject;injectBinding;probes;probeBinding;lightBuffer;surfaceConfig;surfaceAccum;surfaceStatistics;surfaceConfigData=new Float32Array(8);resolveSurface;resolveSurfaceBinding;configuredSurfaces=new WeakSet;surfaceCapture=null;captureAxis=0;pendingTriangleCount=0;pendingCounts=0;configured=new WeakSet;materialCapabilities=new WeakMap;watched=new Set;lights=new Set;staticDrawRoots=new Map;cascadeDirectionalLights=[];scene=null;grid=null;pending=null;dirty=!0;upload=!1;frame=0;probeOffset=0;disposed=!1;cameraPosition=new Q;sourcePosition=new Q;targetPosition=new Q;direction=new Q;buildMs=0;lightCount=0;distantVolumes=null;cascadeFrame=0;setOptions(e){const t=this.enabled,i=this.intensity;if(this.enabled=e.enabled??this.enabled,t&&!this.enabled&&this.buffers.length>0&&(this.header[6]=this.header[8]=0,this.device.queue.writeBuffer(this.field,0,this.header),this.stats.updatedProbes=0,this.stats.geometryCpuMs=0),this.intensity=oe(e.intensity,this.intensity,0,10),this.rays=Math.round(oe(e.raysPerProbe,this.rays,16,256)),this.fraction=oe(e.updateFraction,this.fraction,.01,1),this.history=oe(e.historyWeight,this.history,0,.99),this.steps=Math.round(oe(e.maxSteps,this.steps,16,256)),e.skyColor)for(let t=0;t<3;t++)this.sky[t]=oe(e.skyColor[t],0,0,100);if(this.distantVolumes)for(const e of this.distantVolumes)e.volume.setOptions({enabled:this.enabled,intensity:this.intensity,historyWeight:this.history,maxSteps:this.steps,skyColor:this.sky,raysPerProbe:Math.min(this.rays,e.rays),updateFraction:Math.min(this.fraction,e.fraction)}),!e.volume.grid||t===this.enabled&&i===this.intensity||(e.settingsDirty=!0)}invalidate(){if(this.dirty=!0,this.distantVolumes)for(const e of this.distantVolumes)e.volume.invalidate()}get surfaceResolution(){return 2*this.resolution}setSurfaceCapture(e){this.surfaceCapture?.dispose(),this.surfaceCapture=e,this.invalidate()}setSurfaceCaptureFactory(e){if(this.setSurfaceCapture(e(this)),this.distantVolumes)for(const t of this.distantVolumes)t.volume.setSurfaceCapture(e(t.volume))}configureSurfaceMaterial(e){if(!this.configuredSurfaces.has(e)){if(!e.fragmentShader.includes("sdfgiWriteSurface("))throw new Error("SDFGI capture requires an attribute-only material graph.");this.configuredSurfaces.add(e),e.fragmentShader.includes("fn sdfgiWriteSurface(")||(e.fragmentShader+="\nfn sdfgiWriteSurface(position: vec3<f32>, normal: vec3<f32>, diffuse: vec3<f32>, emission: vec3<f32>, doubleSided: bool) {\n let originCell = sdfgiSurfaceConfig[0];\n let n = u32(sdfgiSurfaceConfig[1].x);\n let color = vec3<u32>(round(clamp(diffuse, vec3<f32>(0.0), vec3<f32>(1.0)) * 4096.0));\n let emissive = vec3<u32>(round(clamp(emission, vec3<f32>(0.0), vec3<f32>(64.0)) * 1024.0));\n let surfaceNormal = normalize(normal);\n let packedNormal = pack4x8snorm(vec4<f32>(surfaceNormal, 0.0)) & 0x00ffffffu;\n // Half-voxel coverage in each projection and a small normal extrusion keep\n // subpixel edges connected without relying on conservative-raster hardware.\n for (var offset = -1; offset <= 1; offset++) {\n let local = (position - originCell.xyz) / originCell.w + surfaceNormal * (f32(offset) * 0.5);\n if (any(local < vec3<f32>(0.0)) || any(local >= vec3<f32>(f32(n)))) { continue; }\n let cell = vec3<u32>(local);\n let center = originCell.xyz + (vec3<f32>(cell) + vec3<f32>(0.5)) * originCell.w;\n // The fourth normal byte carries a two-sided flag and a seven-bit plane\n // offset over +/-1.5 cells, including the conservative extrusion shell.\n let planeOffset = dot(position - center, surfaceNormal) / originCell.w;\n let planeBits = u32(round(clamp(planeOffset / 3.0 + 0.5, 0.0, 1.0) * 127.0));\n let metadata = planeBits | select(0u, 128u, doubleSided);\n let base = (cell.x + n * (cell.y + n * cell.z)) * 8u;\n atomicAdd(&sdfgiSurfaceAccum[base], 1u);\n atomicAdd(&sdfgiSurfaceAccum[base + 1u], color.x);\n atomicAdd(&sdfgiSurfaceAccum[base + 2u], color.y);\n atomicAdd(&sdfgiSurfaceAccum[base + 3u], color.z);\n atomicAdd(&sdfgiSurfaceAccum[base + 4u], emissive.x);\n atomicAdd(&sdfgiSurfaceAccum[base + 5u], emissive.y);\n atomicAdd(&sdfgiSurfaceAccum[base + 6u], emissive.z);\n // The normal and its plane offset stay atomic and refer to the same\n // captured surface, including where several surfaces share a voxel.\n atomicStore(&sdfgiSurfaceAccum[base + 7u], packedNormal | (metadata << 24u));\n }\n}\n"),e.depthTest=e.depthWrite=e.transparent=e.wireframe=!1,e.side=K,e.blending=Z,e.setStorageBuffer("sdfgiSurfaceAccum",{buffer:this.surfaceAccum,type:"array<atomic<u32>>",visibility:"fragment",access:"read_write"}),e.setStorageBuffer("sdfgiSurfaceConfig",{buffer:this.surfaceConfig,type:"array<vec4<f32>>",visibility:"fragment"})}}registerStaticDrawRoot(e){this.staticDrawRoots.set(e,(this.staticDrawRoots.get(e)??0)+1),this.invalidate();let t=!1;return()=>{if(t)return;t=!0;const i=(this.staticDrawRoots.get(e)??1)-1;i>0?this.staticDrawRoots.set(e,i):this.staticDrawRoots.delete(e),this.invalidate()}}setCascadedDirectionalLights(e){if(this.cascadeDirectionalLights=e,this.distantVolumes)for(const t of this.distantVolumes)t.volume.setCascadedDirectionalLights(e)}configureMaterial(e){let t=this.materialCapabilities.get(e);if(!t||t.vertex!==e.vertexShader||t.fragment!==e.fragmentShader){const i=e.vertexShader.includes("rendererDiffuseGIAt(");t={vertex:e.vertexShader,fragment:e.fragmentShader,visibility:i?"vertex-fragment":e.fragmentShader.includes("rendererIndirectDiffuseAt(")||e.fragmentShader.includes("rendererDiffuseGIAt(")?"fragment":null},this.materialCapabilities.set(e,t),this.configured.delete(e)}if(!1===e.userData.receiveGI)return void(!0===e.defines.USE_SDFGI&&e.setDefine("USE_SDFGI",!1));if(this.configured.has(e))return void(!0!==e.defines.USE_SDFGI&&e.setDefine("USE_SDFGI",!0));const i=t.visibility;if(null!==i){if(this.configured.add(e),e.setStorageBuffer("sdfgiField",{buffer:this.field,type:"array<vec4<f32>>",visibility:i}),this.distantVolumes){e.setDefine("SDFGI_CASCADE_COUNT",this.stats.cascadeCount);for(let t=0;t<this.distantVolumes.length;t++)e.setStorageBuffer(`sdfgiField${t+1}`,{buffer:this.distantVolumes[t].volume.field,type:"array<vec4<f32>>",visibility:i})}e.setDefine("USE_SDFGI",!0)}else!0===e.defines.USE_SDFGI&&e.setDefine("USE_SDFGI",!1)}added=e=>{this.watch(e.child),this.hasStaticGeometry(e.child)&&this.invalidate()};removed=e=>{const t=this.hasStaticGeometry(e.child);e.child.traverse(e=>{e.removeEventListener("childadded",this.added),e.removeEventListener("childremoved",this.removed),this.watched.delete(e),e instanceof Y&&this.lights.delete(e)}),t&&this.invalidate()};hasStaticGeometry(e){let t=!1;return e.traverse(e=>{if(!t&&e.isMesh&&!e.isSkinnedMesh){for(let t=e;t;t=t.parent)if(!1===t.userData.sdfgi||!0===t.userData.isSky)return;t=!0}}),t}watch(e){e.traverse(e=>{this.watched.has(e)||(this.watched.add(e),e.addEventListener("childadded",this.added),e.addEventListener("childremoved",this.removed),(e instanceof q||e instanceof X||e instanceof J)&&this.lights.add(e))})}unwatch(){for(const e of this.watched)e.removeEventListener("childadded",this.added),e.removeEventListener("childremoved",this.removed);this.watched.clear(),this.lights.clear()}prepare(e,t){if(this.disposed||!this.enabled)return;if(this.stats.geometryCpuMs=0,this.stats.updatedProbes=0,this.scene!==e&&(this.unwatch(),this.scene=e,this.watch(e),this.grid=null,this.pending=null,this.dirty=!0,this.stats.ready=!1,this.blend=1,this.previousValid=!1),!this.enabled||!this.surfaceCapture)return;t.getWorldPosition(this.cameraPosition);const i=this.pending??this.grid;if(i&&this.blend>=1){const e=i.origin;(Math.abs(this.cameraPosition.x-e.x-this.extent/2)>.25*this.extent||Math.abs(this.cameraPosition.y-e.y-this.extent/2)>.25*this.extent||Math.abs(this.cameraPosition.z-e.z-this.extent/2)>.25*this.extent)&&(this.dirty=!0)}const r=performance.now();if(this.dirty&&(!this.stats.ready||this.blend>=1)){this.dirty=!1;const e=this.spacing,t=this.cameraPosition.clone().addScalar(-this.extent/2);t.set(Math.floor(t.x/e)*e,Math.floor(t.y/e)*e,Math.floor(t.z/e)*e),this.pending={origin:t,resolution:this.resolution,extent:this.extent},le(this.surfaceConfigData,0,t.x,t.y,t.z,this.cellSize),le(this.surfaceConfigData,4,this.resolution,0,0,0),this.device.queue.writeBuffer(this.surfaceConfig,0,this.surfaceConfigData);const i=this.device.createCommandEncoder({label:"sdfgi-clear-surfaces"});i.clearBuffer(this.surfaceAccum),this.device.queue.submit([i.finish()]),this.captureAxis=0,this.pendingTriangleCount=0,this.buildMs=0}if(this.pending&&(this.pendingTriangleCount=Math.max(this.pendingTriangleCount,this.surfaceCapture.capture(e,this.pending,this.captureAxis++)),this.stats.geometryCpuMs=performance.now()-r,this.buildMs+=this.stats.geometryCpuMs,3===this.captureAxis&&(this.grid=this.pending,this.pending=null,this.upload=!0,this.stats.triangles=this.pendingTriangleCount,this.stats.geometryBuildMs=this.buildMs)),this.stats.building=this.dirty||null!=this.pending||this.pendingCounts>0,this.updateLights(),this.distantVolumes){this.cascadeFrame++;for(const i of this.distantVolumes){const r=i.volume;i.scheduled=i.settingsDirty||null!=r.scene&&r.scene!==e||null!=r.pending||r.upload||r.blend<1||this.cascadeFrame%i.interval===0,i.scheduled&&(r.prepare(e,t),this.stats.geometryCpuMs+=r.stats.geometryCpuMs),this.stats.building||=r.stats.building}}}updateLights(){let e=0;for(let t=0;t<2;t++)for(const i of 0===t?this.cascadeDirectionalLights:this.lights){if(0===t?i!==this.cascadeDirectionalLights[0]:this.cascadeDirectionalLights.includes(i))continue;let r=!0;for(let e=i;e;e=e.parent)if(!e.visible){r=!1;break}if(!r||i.intensity<=0||!1===i.userData.sdfgi)continue;if(16===e)break;const n=16*e++;i.getWorldPosition(this.sourcePosition);let a=0,s=0,o=0,l=-1,c=-1;i instanceof q||i instanceof J?(i.target.getWorldPosition(this.targetPosition),this.direction.subVectors(this.targetPosition,this.sourcePosition).normalize(),i instanceof q?this.direction.negate():(a=2,l=Math.cos(i.angle),c=Math.cos(i.angle*(1-i.penumbra)))):(a=1,this.direction.set(0,0,0)),(i instanceof X||i instanceof J)&&(s=i.distance,o=i.decay),le(this.lightData,n,this.sourcePosition.x,this.sourcePosition.y,this.sourcePosition.z,a),le(this.lightData,n+4,i.color.r*i.intensity,i.color.g*i.intensity,i.color.b*i.intensity,0),le(this.lightData,n+8,this.direction.x,this.direction.y,this.direction.z,s),le(this.lightData,n+12,l,c,o,0)}this.lightCount=e}addPasses(e){return!(!this.enabled||this.disposed)&&(e.addPass({name:"SDFGIUpdate",execute:e=>this.encode(e.encoder)}),!0)}encode(e,t=performance.now()/1e3){if(this.enabled&&!this.disposed&&(this.encodeVolume(e,t),this.distantVolumes))for(const i of this.distantVolumes)(i.scheduled||i.settingsDirty)&&(i.volume.encodeVolume(e,t),i.settingsDirty=!1,this.stats.updatedProbes+=i.volume.stats.updatedProbes)}encodeVolume(e,t){if(this.stats.updatedProbes=0,this.disposed)return;const i=this.grid,r=this.probeResolution**3,n=Math.ceil(r*this.fraction);if(this.upload&&this.enabled&&i)this.previousValid=this.stats.ready,this.previousValid&&(this.device.queue.writeBuffer(this.field,this.fieldBankBytes,this.header),this.dispatch(e,pe,this.snapshot,this.snapshotBinding,Math.ceil(10*r/64))),this.populatedProbes=0,this.probeOffset=0,this.blend=0;else if(this.enabled&&this.populatedProbes>=r){const e=Math.max(0,t-this.lastUpdateSeconds);this.blend=Math.min(1,this.blend+e/.4)}if(this.lastUpdateSeconds=t,this.header[0]=i?.origin.x??0,this.header[1]=i?.origin.y??0,this.header[2]=i?.origin.z??0,this.header[3]=this.cellSize,this.header[4]=this.spacing,this.header[5]=this.probeResolution,this.header[6]=this.enabled?this.intensity:0,this.header[7]=1.25*this.cellSize,this.header[8]=i&&this.enabled?1:0,this.header[9]=this.blend,this.header[10]=this.previousValid?1:0,this.header[12]=this.fieldBankBytes/16,this.device.queue.writeBuffer(this.field,0,this.header),!this.enabled||!i)return;le(this.floats,0,i.origin.x,i.origin.y,i.origin.z,this.cellSize),le(this.integers,4,this.resolution,this.probeResolution,this.rays,this.frame++),le(this.floats,8,this.spacing,this.history,this.cellSize,1.732051*this.extent),le(this.floats,12,this.sky[0],this.sky[1],this.sky[2],0),le(this.integers,16,this.probeOffset,n,this.upload?1:0,this.steps),le(this.integers,20,this.lightCount,0,0,0),this.device.queue.writeBuffer(this.params,0,this.uniformData),this.device.queue.writeBuffer(this.lightBuffer,0,this.lightData);const a=Math.ceil(this.resolution**3/64);if(this.upload){e.clearBuffer(this.field,64,this.fieldBankBytes-64),e.clearBuffer(this.surfaceStatistics),this.dispatch(e,{label:"SDFGIResolveSurface"},this.resolveSurface,this.resolveSurfaceBinding,a),this.readSurfaceCount(e,i),this.dispatch(e,ce,this.seed,this.seedBinding,a);for(const t of this.jumps)this.dispatch(e,ue,t.kernel,t.binding,a)}this.dispatch(e,de,this.inject,this.injectBinding,a),this.dispatch(e,he,this.probes,this.probeBinding,Math.ceil(n/32)),this.probeOffset=(this.probeOffset+n)%r,this.populatedProbes=Math.min(r,this.populatedProbes+n),this.upload=!1,this.stats.ready=!0,this.stats.updatedProbes=n}readSurfaceCount(e,t){const i=this.device.createBuffer({label:"sdfgi-cell-count",size:16,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});e.copyBufferToBuffer(this.surfaceStatistics,0,i,0,16),this.pendingCounts++,Promise.resolve().then(async()=>{try{await i.mapAsync(GPUMapMode.READ),this.disposed||this.grid!==t||(this.stats.occupiedCells=new Uint32Array(i.getMappedRange())[0]),i.unmap()}catch{}finally{i.destroy(),this.pendingCounts--}})}dispatch(e,t,i,r,n){const a=e.beginComputePass(t);a.setPipeline(i.pipeline),a.setBindGroup(0,r),a.dispatchWorkgroups(n),a.end()}dispose(){if(this.disposed=!0,this.unwatch(),this.surfaceCapture?.dispose(),this.distantVolumes)for(const e of this.distantVolumes)e.volume.dispose();this.staticDrawRoots.clear();for(const e of this.buffers)e.destroy()}};import{OrthographicCamera as me,Vector3 as ge}from"three";var ve=class{camera=new me;center=new ge;target;options;variants;constructor(e,t,i,r=!1){this.variants=r?new Map:null,this.target=e.createSceneCapture(null,t.surfaceResolution,t.surfaceResolution),this.options={objectFilter:e=>{if(e?.isSkinnedMesh)return!1;for(let t=e;t;t=t.parent)if(!1===t.userData.sdfgi||!0===t.userData.isSky)return!1;return!0},overrideMaterial:(e,r)=>{if(r||e.transparent||!1===e.userData.sdfgi)return null;let n=i(e);if(n&&this.variants){const e=n;let t=this.variants.get(e);t||(t=e.clone(),this.variants.set(e,t)),t.uniforms=e.uniforms,t.textures=e.textures,t.uniformValuesNeedsUpdate=!0,n=t}return n&&t.configureSurfaceMaterial(n),n},includeLocalLights:!1,postProcess:()=>{}}}capture(e,t,i){const{origin:r,extent:n}=t;this.center.copy(r).addScalar(n/2);const a=this.camera;return a.left=a.bottom=-n/2,a.right=a.top=n/2,a.near=.01,a.far=n+2,a.position.copy(this.center).setComponent(i,this.center.getComponent(i)+n/2+1),a.up.set(0,1===i?0:1,1===i?1:0),a.lookAt(this.center),a.updateProjectionMatrix(),this.target.capture(e,a,this.options),this.target.triangleCount}dispose(){if(this.target.dispose(),this.variants){for(const e of this.variants.values())e.dispose();this.variants.clear()}}};import{Color as xe,DirectionalLight as we,Matrix4 as be,Object3D as ye,PointLight as Se,Scene as Ce,SpotLight as Me,Vector3 as Pe}from"three";var Be=class extends ye{constructor(e){super(),this.volume=e}volume;isFogVolumeObject=!0},De={low:{froxelPixelSize:16,depthSlices:32,integrationSubsteps:1,shadowFilterTaps:1,temporalJitter:!0,temporal:{historyWeight:.88,depthRejection:.055,neighborhoodClamp:!0},blur:{scale:.25,radius:2,depthSigma:.06,spatialSigma:1.5,depthAwareUpsample:!1}},medium:{froxelPixelSize:12,depthSlices:40,integrationSubsteps:1,shadowFilterTaps:1,temporalJitter:!0,temporal:{historyWeight:.92,depthRejection:.045,neighborhoodClamp:!0},blur:{scale:.375,radius:2,depthSigma:.055,spatialSigma:1.75,depthAwareUpsample:!0}},high:{froxelPixelSize:8,depthSlices:64,integrationSubsteps:1,shadowFilterTaps:1,temporalJitter:!0,temporal:{historyWeight:.94,depthRejection:.04,neighborhoodClamp:!0},blur:{scale:.5,radius:3,depthSigma:.05,spatialSigma:2,depthAwareUpsample:!0}}},Ie=20,Te=16,Re=(new be).set(1,0,0,0,0,1,0,0,0,0,.5,.5,0,0,0,1),Ve=new Pe,Ge=new Pe,ze=new Pe,Le={label:"VolumetricFogFroxelPass"};function Ue(e,t,i,r,n,a){e[t]=i,e[t+1]=r,e[t+2]=n,e[t+3]=a}var Ae=class{constructor(e=new Ce,t={}){this.scene=e,this.options=ke(t),this.integratedVolume=`${this.options.targetPrefix}Integrated`,this.columnDepthBounds=`${this.options.targetPrefix}DepthBounds`,this.scatteringHistoryA=`${this.options.targetPrefix}ScatteringHistoryA`,this.scatteringHistoryB=`${this.options.targetPrefix}ScatteringHistoryB`,this.activeHistoryRead=this.scatteringHistoryB,this.activeHistoryWrite=this.scatteringHistoryA,this.volumeData=new Float32Array(this.options.maxVolumes*Ie);const i=this.options.maxDirectionalLights+this.options.maxPointLights+this.options.maxSpotLights;this.lightData=new Float32Array(i*Te),this.selectedPointIndices=new Int32Array(this.options.maxPointLights),this.selectedPointScores=new Float32Array(this.options.maxPointLights),this.selectedSpotIndices=new Int32Array(this.options.maxSpotLights),this.selectedSpotScores=new Float32Array(this.options.maxSpotLights)}scene;integratedVolume;columnDepthBounds;scatteringHistoryA;scatteringHistoryB;options;resources=new WeakMap;uniformStorage=new ArrayBuffer(256);uniforms=new Float32Array(this.uniformStorage);uniformIntegers=new Uint32Array(this.uniformStorage);volumeData;lightData;selectedPointIndices;selectedPointScores;selectedSpotIndices;selectedSpotScores;collectedVolumes=[];collectedDirectionals=[];collectedPoints=[];collectedSpots=[];volumeCount=0;directionalCount=0;pointCount=0;spotCount=0;collectionCamera=null;collectVolumeObject=e=>{const t=e;t.isFogVolumeObject&&t.volume&&!this.collectedVolumes.includes(t.volume)&&this.collectedVolumes.push(t.volume)};collectLightObject=e=>{const t=this.collectionCamera;e instanceof we&&e.layers.test(t.layers)&&!this.collectedDirectionals.includes(e)?this.collectedDirectionals.push(e):e instanceof Se&&e.layers.test(t.layers)?this.collectedPoints.push(e):e instanceof Me&&e.layers.test(t.layers)&&this.collectedSpots.push(e)};executeFroxelPass=e=>{this.executeFroxels(e)};projectionInverse=new be;viewProjectionInverse=new be;previousTemporalViewProjection=new be;previousFroxelViewProjection=new be;previousFroxelCameraPosition=new Pe;previousFroxelNear=.1;previousFroxelFar=1;previousFroxelWidth=0;previousFroxelHeight=0;froxelHistoryValid=!1;froxelHistoryWriteIndex=0;activeHistoryRead;activeHistoryWrite;explicitVolumes=[];volumeObjects;extractedLights;cascadeDirectionalLights=[];compositePass=null;blurPassCache=new Map;temporalPassCache=new Map;temporalWriteIndex=0;temporalHistoryValid=!1;activeLastFrame=!1;frameIndex=0;setScene(e){this.scene=e}get enabled(){return this.options.enabled}setOptions(e){const t=ke({...this.options,...e,ambientColor:e.ambientColor??this.options.ambientColor,blur:void 0===e.blur?this.options.blur:e.blur,temporal:void 0===e.temporal?this.options.temporal:e.temporal,targetPrefix:this.options.targetPrefix,maxVolumes:this.options.maxVolumes,maxDirectionalLights:this.options.maxDirectionalLights,maxPointLights:this.options.maxPointLights,maxSpotLights:this.options.maxSpotLights});Object.assign(this.options,t),this.compositePass=null,this.blurPassCache.clear(),this.temporalPassCache.clear(),this.reset()}applyPreset(e){this.setOptions(De[e])}reset(){this.frameIndex=0,this.temporalWriteIndex=0,this.temporalHistoryValid=!1,this.froxelHistoryValid=!1,this.froxelHistoryWriteIndex=0,this.previousFroxelWidth=0,this.previousFroxelHeight=0,this.activeLastFrame=!1,this.previousTemporalViewProjection.identity()}setCascadedDirectionalLights(e){this.cascadeDirectionalLights=e}addPasses(e,t){if(this.explicitVolumes=t.volumes??[],this.volumeObjects=t.volumeObjects,this.extractedLights=t.lights,!this.options.enabled||0===this.explicitVolumes.length&&0===this.volumeObjects?.length)return this.activeLastFrame&&this.reset(),t.sceneColor;this.activeLastFrame=!0,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});for(const t of[this.scatteringHistoryA,this.scatteringHistoryB])e.createTextureTarget(t,{dimension:"3d",depthOrArrayLayers:this.options.depthSlices,scale:1/this.options.froxelPixelSize,format:"rgba16float",usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.STORAGE_BINDING});this.activeHistoryRead=0===this.froxelHistoryWriteIndex?this.scatteringHistoryB:this.scatteringHistoryA,this.activeHistoryWrite=0===this.froxelHistoryWriteIndex?this.scatteringHistoryA:this.scatteringHistoryB,e.addPass({name:"VolumetricFogFroxelPass",inputs:{sceneDepth:t.depth,scatteringHistory:this.activeHistoryRead},outputs:[this.integratedVolume,this.columnDepthBounds,this.activeHistoryWrite],execute:this.executeFroxelPass}),this.froxelHistoryWriteIndex=1-this.froxelHistoryWriteIndex;const i=e.createColorTarget(`${this.options.targetPrefix}Composite`,{format:"rgba16float"});return!1!==this.options.blur?this.addBlurredComposite(e,t,i):(this.compositePass&&this.compositePass.matches(t.sceneColor,t.depth,i)||(this.compositePass=new Fe(t.sceneColor,t.depth,this.integratedVolume,this.columnDepthBounds,i,this.options.maxDistance,this.options.fogDitherStrength)),this.compositePass.setFrameIndex(this.frameIndex),e.addFullscreenPass(this.compositePass),i)}addBlurredComposite(e,t,i){const r=this.options.blur;if(!1===r)return i;const n=e.createColorTarget(`${this.options.targetPrefix}Resolved`,{format:"rgba16float",scale:r.scale}),a=e.createColorTarget(`${this.options.targetPrefix}BlurTemporary`,{format:"rgba16float",scale:r.scale}),s=e.createColorTarget(`${this.options.targetPrefix}Blurred`,{format:"rgba16float",scale:r.scale}),o=`resolve:${t.depth}:${n}`;let l=this.blurPassCache.get(o);l||(l=new Oe(t.depth,this.integratedVolume,this.columnDepthBounds,n,this.options.maxDistance,this.options.fogDitherStrength),this.blurPassCache.set(o,l)),l.setFrameIndex(this.frameIndex),e.addFullscreenPass(l);const c=n;for(const[i,n,o]of[[c,a,[1,0]],[a,s,[0,1]]]){const a=`blur:${i}:${n}:${o[0]}:${r.radius}:${r.depthSigma}:${r.spatialSigma}`;let s=this.blurPassCache.get(a);s||(s=new je(i,t.depth,n,o,r),this.blurPassCache.set(a,s)),e.addFullscreenPass(s)}const u=`blurComposite:${t.sceneColor}:${t.depth}:${s}:${i}:${r.depthAwareUpsample}`;let d=this.blurPassCache.get(u);return d||(d=new $e(t.sceneColor,t.depth,s,this.integratedVolume,this.columnDepthBounds,i,r.depthAwareUpsample),this.blurPassCache.set(u,d)),e.addFullscreenPass(d),i}addTemporalPass(e,t,i,r){const n=this.options.temporal;if(!1===n)return i;const a=e.createColorTarget(`${this.options.targetPrefix}TemporalA`,{format:"rgba16float",scale:r}),s=e.createColorTarget(`${this.options.targetPrefix}TemporalB`,{format:"rgba16float",scale:r}),o=e.createColorTarget(`${this.options.targetPrefix}TemporalDepthA`,{format:"r16float",scale:r}),l=e.createColorTarget(`${this.options.targetPrefix}TemporalDepthB`,{format:"r16float",scale:r}),c=0===this.temporalWriteIndex?s:a,u=0===this.temporalWriteIndex?a:s,d=0===this.temporalWriteIndex?l:o,h=0===this.temporalWriteIndex?o:l,p=[i,t.depth,t.velocity??"camera",c,d,u,h].join(":");let f=this.temporalPassCache.get(p);return f||(f=new Ee(i,t.depth,t.velocity,c,d,u,h,n,this),this.temporalPassCache.set(p,f)),e.addFullscreenPass(f),this.temporalWriteIndex=1-this.temporalWriteIndex,u}consumeTemporalHistoryValid(){const e=this.temporalHistoryValid;return this.temporalHistoryValid=!0,e}updateTemporalUniforms(e,t,i,r,n){t.copy(Re).multiply(n.camera.projectionMatrix).multiply(n.camera.matrixWorldInverse),i.copy(t).invert();const a=this.consumeTemporalHistoryValid();e.set(i.elements,0),e.set((a?this.previousTemporalViewProjection:t).elements,16),Ue(e,32,r.historyWeight,r.depthRejection,r.neighborhoodClamp?1:0,a?1:0),this.previousTemporalViewProjection.copy(t)}dispose(){this.compositePass=null,this.blurPassCache.clear(),this.temporalPassCache.clear()}executeFroxels(e){const t=this.getResources(e.device);this.collectSceneData(e.camera);const i=Math.max(.01,e.camera.near),r=Math.min(e.camera.far,this.options.maxDistance);e.camera.getWorldPosition(Ge);let n=i+.01;for(let e=0;e<this.volumeCount;e++){const t=e*Ie,i=this.volumeData[t]-Ge.x,r=this.volumeData[t+1]-Ge.y,a=this.volumeData[t+2]-Ge.z;n=Math.max(n,Math.sqrt(i*i+r*r+a*a)+this.volumeData[t+3])}const a=Math.max(i+.01,Math.min(r,n));let s=a;for(let e=0;e<this.volumeCount;e++)s=Math.min(s,Math.max(this.volumeData[e*Ie+10],i));s=Math.min(s,a);const o=Math.max(1,Math.floor(e.width/this.options.froxelPixelSize)),l=Math.max(1,Math.floor(e.height/this.options.froxelPixelSize));o===this.previousFroxelWidth&&l===this.previousFroxelHeight||(this.froxelHistoryValid=!1),this.projectionInverse.copy(Re).multiply(e.camera.projectionMatrix).multiply(e.camera.matrixWorldInverse),this.viewProjectionInverse.copy(this.projectionInverse).invert(),this.uniforms.set(this.viewProjectionInverse.elements,0),this.uniforms[16]=e.camera.position.x,this.uniforms[17]=e.camera.position.y,this.uniforms[18]=e.camera.position.z,this.uniforms[19]=i,Ue(this.uniforms,20,o,l,this.options.depthSlices,a),this.uniformIntegers[24]=this.volumeCount,this.uniformIntegers[25]=this.directionalCount,this.uniformIntegers[26]=this.pointCount,this.uniformIntegers[27]=this.spotCount,Ue(this.uniforms,28,this.options.ambientColor.r,this.options.ambientColor.g,this.options.ambientColor.b,this.options.temporalJitter?this.frameIndex++%1024+1:0),e.camera.getWorldDirection(Ge),Ue(this.uniforms,32,Ge.x,Ge.y,Ge.z,Math.max(e.camera.far-i,1e-4)),Ue(this.uniforms,36,this.options.scatteringIntensity,this.options.spatialJitter?1:0,0,0),this.uniforms.set((this.froxelHistoryValid?this.previousFroxelViewProjection:this.projectionInverse).elements,40),Ue(this.uniforms,56,this.previousFroxelCameraPosition.x,this.previousFroxelCameraPosition.y,this.previousFroxelCameraPosition.z,this.froxelHistoryValid&&!1!==this.options.temporal?1:0),Ue(this.uniforms,60,this.previousFroxelNear,this.previousFroxelFar,!1===this.options.temporal?0:this.options.temporal.historyWeight,0),e.device.queue.writeBuffer(t.uniformBuffer,0,this.uniforms),this.volumeCount>0&&e.device.queue.writeBuffer(t.volumeBuffer,0,this.volumeData.buffer,this.volumeData.byteOffset,this.volumeCount*Ie*4);const c=this.directionalCount+this.pointCount+this.spotCount;c>0&&e.device.queue.writeBuffer(t.lightBuffer,0,this.lightData.buffer,this.lightData.byteOffset,c*Te*4);const u=e.getSceneLightingResources(),d=e.getTextureView(this.integratedVolume),h=e.getTextureView(this.columnDepthBounds),p=e.getTextureView(this.activeHistoryRead),f=e.getTextureView(this.activeHistoryWrite),m=e.depthView,g=t.bindGroupResources;t.bindGroup&&g&&g.integratedVolumeView===d&&g.historyReadView===p&&g.historyWriteView===f&&g.lightBuffer===u.lightBuffer&&g.comparisonSampler===e.comparisonSampler&&g.directionalShadowView===u.directionalShadowView&&g.pointShadowView===u.pointShadowView&&g.spotShadowView===u.spotShadowView&&g.spotLightMapView===u.spotLightMapView&&g.depthView===m&&g.columnDepthBoundsView===h||(t.bindGroup=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:d},{binding:4,resource:{buffer:u.lightBuffer}},{binding:5,resource:e.comparisonSampler},{binding:6,resource:u.directionalShadowView},{binding:7,resource:u.pointShadowView},{binding:8,resource:u.spotShadowView},{binding:9,resource:m},{binding:10,resource:h},{binding:11,resource:e.linearClampSampler},{binding:12,resource:p},{binding:13,resource:f},{binding:14,resource:u.spotLightMapView}]}),t.bindGroupResources={integratedVolumeView:d,historyReadView:p,historyWriteView:f,lightBuffer:u.lightBuffer,comparisonSampler:e.comparisonSampler,directionalShadowView:u.directionalShadowView,pointShadowView:u.pointShadowView,spotShadowView:u.spotShadowView,spotLightMapView:u.spotLightMapView,depthView:m,columnDepthBoundsView:h});const v=e.encoder.beginComputePass(Le);v.setPipeline(t.pipeline),v.setBindGroup(0,t.bindGroup),v.dispatchWorkgroups(Math.ceil(o/8),Math.ceil(l/8)),v.end(),this.previousFroxelViewProjection.copy(this.projectionInverse),this.previousFroxelCameraPosition.set(this.uniforms[16],this.uniforms[17],this.uniforms[18]),this.previousFroxelNear=s,this.previousFroxelFar=a,this.previousFroxelWidth=o,this.previousFroxelHeight=l,this.froxelHistoryValid=!0}collectSceneData(e){const t=this.collectedVolumes,i=this.collectedDirectionals,r=this.collectedPoints,n=this.collectedSpots;t.length=0,i.length=0,r.length=0,n.length=0;for(const e of this.explicitVolumes)t.push(e);for(const t of this.cascadeDirectionalLights)t.visible&&t.layers.test(e.layers)&&!i.includes(t)&&i.push(t);if(void 0===this.volumeObjects)this.scene.traverseVisible(this.collectVolumeObject);else for(const e of this.volumeObjects)this.collectVolumeObject(e);void 0===this.extractedLights&&(this.collectionCamera=e,this.scene.traverseVisible(this.collectLightObject),this.collectionCamera=null);const a=Math.min(t.length,this.options.maxVolumes);this.volumeData.fill(0,0,a*Ie);for(let e=0;e<a;e++)this.writeVolume(e,t[e]);const s=Math.min(this.extractedLights?.directionals.length??i.length,this.options.maxDirectionalLights),o=this.extractedLights?.points,l=this.extractedLights?.spots,c=this.selectClosestLights(o??r,e,this.selectedPointIndices,this.selectedPointScores),u=this.selectClosestLights(l??n,e,this.selectedSpotIndices,this.selectedSpotScores);this.lightData.fill(0,0,(s+c+u)*Te);let d=0;for(let e=0;e<s;e++){const t=this.extractedLights?.directionals[e];t?this.writeExtractedDirectional(d++,t):this.writeDirectional(d++,i[e])}for(let e=0;e<c;e++){const t=this.selectedPointIndices[e];o?this.writeExtractedPoint(d++,o[t],t):this.writePoint(d++,r[t])}for(let e=0;e<u;e++){const t=this.selectedSpotIndices[e];l?this.writeExtractedSpot(d++,l[t],t):this.writeSpot(d++,n[t])}this.volumeCount=a,this.directionalCount=s,this.pointCount=c,this.spotCount=u}selectClosestLights(e,t,i,r){const n=i.length;if(0===n)return 0;t.getWorldPosition(Ge);let a=0;for(let t=0;t<e.length;t+=1){const s=e[t],o=Number(s instanceof ye?s.userData?.volumetricIntensity??0:s.volumetricIntensity);if(!Number.isFinite(o)||o<=0)continue;const l=s instanceof ye?s.getWorldPosition(Ve):s.position,c=Ge.distanceToSquared(l);if(a===n&&c>=r[n-1])continue;let u=Math.min(a,n-1);for(;u>0&&c<r[u-1];)u<n&&(r[u]=r[u-1],i[u]=i[u-1]),u-=1;r[u]=c,i[u]=t,a<n&&(a+=1)}return a}writeVolume(e,t){const i=e*Ie;t.object.getWorldPosition(Ve),t.object.getWorldScale(ze),Ue(this.volumeData,i,Ve.x,Ve.y,Ve.z,5*Math.max(ze.x,ze.y,ze.z)),Ue(this.volumeData,i+4,t.albedo.r,t.albedo.g,t.albedo.b,Math.max(0,t.baseDensity)),Ue(this.volumeData,i+8,t.heightFalloff,t.heightOffset,t.startDistance??3,-Math.max(-.99,Math.min(.99,t.scatteringDistribution))),Ue(this.volumeData,i+12,t.emissive.r,t.emissive.g,t.emissive.b,t.ambientIntensity??1),this.volumeData[i+16]="lightShaft"===t.scatteringMode?1:0}writeDirectional(e,t){const i=e*Te;t.getWorldPosition(Ve),t.target.getWorldPosition(Ge),Ge.sub(Ve).normalize(),Ue(this.lightData,i,Ge.x,Ge.y,Ge.z,0);const r=t.intensity*(t.userData?.volumetricIntensity??1);Ue(this.lightData,i+4,t.color.r*r,t.color.g*r,t.color.b*r,0)}writeExtractedDirectional(e,t){const i=e*Te;Ue(this.lightData,i,t.direction.x,t.direction.y,t.direction.z,0);const r=t.intensity*t.volumetricIntensity;Ue(this.lightData,i+4,t.color.x*r,t.color.y*r,t.color.z*r,0)}writePoint(e,t,i=e){const r=e*Te;t.getWorldPosition(Ve),Ue(this.lightData,r,Ve.x,Ve.y,Ve.z,Math.max(.001,t.distance||this.options.maxDistance));const n=t.intensity*(t.userData?.volumetricIntensity??1);Ue(this.lightData,r+4,t.color.r*n,t.color.g*n,t.color.b*n,Math.max(0,t.decay)),this.lightData[r+13]=i}writeExtractedPoint(e,t,i){const r=e*Te;Ue(this.lightData,r,t.position.x,t.position.y,t.position.z,Math.max(.001,t.range||this.options.maxDistance));const n=t.intensity*t.volumetricIntensity;Ue(this.lightData,r+4,t.color.x*n,t.color.y*n,t.color.z*n,Math.max(0,t.decay)),this.lightData[r+13]=i,this.lightData[r+14]=1}writeSpot(e,t,i=e){const r=e*Te;t.getWorldPosition(Ve),t.target.getWorldPosition(Ge),Ge.sub(Ve).normalize(),Ue(this.lightData,r,Ve.x,Ve.y,Ve.z,Math.max(.001,t.distance||this.options.maxDistance));const n=t.intensity*(t.userData?.volumetricIntensity??1);Ue(this.lightData,r+4,t.color.r*n,t.color.g*n,t.color.b*n,Math.max(0,t.decay)),Ue(this.lightData,r+8,Ge.x,Ge.y,Ge.z,Math.cos(t.angle)),this.lightData[r+12]=Math.cos(t.angle*(1-t.penumbra)),this.lightData[r+13]=i}writeExtractedSpot(e,t,i){const r=e*Te;Ue(this.lightData,r,t.position.x,t.position.y,t.position.z,Math.max(.001,t.range||this.options.maxDistance));const n=t.intensity*t.volumetricIntensity;Ue(this.lightData,r+4,t.color.x*n,t.color.y*n,t.color.z*n,Math.max(0,t.decay)),Ue(this.lightData,r+8,t.direction.x,t.direction.y,t.direction.z,Math.cos(t.angle)),this.lightData[r+12]=Math.cos(t.angle*(1-t.penumbra)),this.lightData[r+13]=i,this.lightData[r+14]=1}getResources(e){let t=this.resources.get(e);t||(t=new Map,this.resources.set(e,t));const i=[this.options.shadowFilterTaps,this.options.integrationSubsteps,this.options.maxVolumes,this.options.maxDirectionalLights,this.options.maxPointLights,this.options.maxSpotLights].join(":"),r=t.get(i);if(r)return r;const n=e.createBuffer({size:256,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),a=e.createBuffer({size:this.volumeData.byteLength,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST}),s=e.createBuffer({size:this.lightData.byteLength,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST}),o=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"}},{binding:11,visibility:GPUShaderStage.COMPUTE,sampler:{type:"filtering"}},{binding:12,visibility:GPUShaderStage.COMPUTE,texture:{sampleType:"float",viewDimension:"3d"}},{binding:13,visibility:GPUShaderStage.COMPUTE,storageTexture:{access:"write-only",format:"rgba16float",viewDimension:"3d"}},{binding:14,visibility:GPUShaderStage.COMPUTE,texture:{sampleType:"float",viewDimension:"2d"}}]}),l=e.createShaderModule({label:"volumetric-fog-compute",code:_e.replace("__SHADOW_TAPS__",String(this.options.shadowFilterTaps)).replace("__INTEGRATION_SUBSTEPS__",String(this.options.integrationSubsteps))}),c={uniformBuffer:n,volumeBuffer:a,lightBuffer:s,layout:o,pipeline:e.createComputePipeline({layout:e.createPipelineLayout({bindGroupLayouts:[o]}),compute:{module:l,entryPoint:"main"}})};return t.set(i,c),c}};function ke(e){return{enabled:e.enabled??!0,froxelPixelSize:Math.max(2,Math.floor(e.froxelPixelSize??8)),depthSlices:Math.max(8,Math.floor(e.depthSlices??64)),integrationSubsteps:e.integrationSubsteps??1,maxDistance:Math.max(1,e.maxDistance??256),targetPrefix:e.targetPrefix??"volumetricFog",maxVolumes:Math.max(1,Math.floor(e.maxVolumes??32)),maxDirectionalLights:Math.min(4,Math.max(1,Math.floor(e.maxDirectionalLights??4))),maxPointLights:Math.min(4,Math.max(0,Math.floor(e.maxPointLights??4))),maxSpotLights:Math.min(4,Math.max(0,Math.floor(e.maxSpotLights??4))),ambientColor:e.ambientColor?.clone()??new xe(.03,.035,.045),shadowFilterTaps:e.shadowFilterTaps??1,temporalJitter:e.temporalJitter??!0,temporal:!1!==e.temporal&&{historyWeight:Math.min(.98,Math.max(0,e.temporal?.historyWeight??.92)),depthRejection:Math.max(1e-4,e.temporal?.depthRejection??.04),neighborhoodClamp:e.temporal?.neighborhoodClamp??!0},spatialJitter:e.spatialJitter??!0,fogDitherStrength:Math.max(0,e.fogDitherStrength??.75),scatteringIntensity:Math.max(0,e.scatteringIntensity??1),blur:!1!==e.blur&&{scale:Math.max(.125,Math.min(1,e.blur?.scale??.5)),radius:Math.max(1,Math.min(12,Math.floor(e.blur?.radius??3))),depthSigma:Math.max(1e-4,e.blur?.depthSigma??.05),spatialSigma:Math.max(.1,e.blur?.spatialSigma??2),depthAwareUpsample:e.blur?.depthAwareUpsample??!0}}}var Fe=class{constructor(e,t,i,r,n,a,s){this.maxDistance=a,this.ditherStrength=s,this.inputs={sceneColor:e,sceneDepth:t,fogVolume:i,fogBounds:r},this.outputs=n}maxDistance;ditherStrength;name="VolumetricFogCompositePass";sampler="linear";uniformBufferSize=80;inputs;inputDimensions={fogVolume:"3d"};outputs;fragmentShader=He;data=new Float32Array(20);inverseProjection=new be;frameIndex=0;setFrameIndex(e){this.frameIndex=e}matches(e,t,i){return this.inputs.sceneColor===e&&this.inputs.sceneDepth===t&&this.outputs===i}updateUniforms=e=>(this.inverseProjection.copy(Re).multiply(e.camera.projectionMatrix).invert(),this.data.set(this.inverseProjection.elements,0),Ue(this.data,16,Math.max(.01,e.camera.near),Math.min(e.camera.far,this.maxDistance),this.frameIndex>0?this.frameIndex%1024:-1,this.ditherStrength),this.data)},Oe=class{constructor(e,t,i,r,n,a){this.maxDistance=n,this.ditherStrength=a,this.inputs={sceneDepth:e,fogVolume:t,fogBounds:i},this.outputs=r}maxDistance;ditherStrength;name="VolumetricFogResolvePass";sampler="linear";uniformBufferSize=80;inputDimensions={fogVolume:"3d"};inputs;outputs;fragmentShader=qe;data=new Float32Array(20);inverseProjection=new be;frameIndex=0;setFrameIndex(e){this.frameIndex=e}updateUniforms=e=>(this.inverseProjection.copy(Re).multiply(e.camera.projectionMatrix).invert(),this.data.set(this.inverseProjection.elements,0),Ue(this.data,16,Math.max(.01,e.camera.near),Math.min(e.camera.far,this.maxDistance),this.frameIndex>0?this.frameIndex%1024:-1,this.ditherStrength),this.data)},Ee=class{constructor(e,t,i,r,n,a,s,o,l){var c;this.temporal=o,this.state=l,this.inputs=null==i?{currentFog:e,sceneDepth:t,historyFog:r,historyDepth:n}:{currentFog:e,sceneDepth:t,historyFog:r,historyDepth:n,velocity:i},this.outputs=[a,s],this.fragmentShader=`\nstruct FogTemporalOutput{\n @location(0) fog:vec4<f32>,\n @location(1) depth:vec4<f32>,\n};\nfn currentViewProjectionInverse()->mat4x4<f32>{\n return mat4x4<f32>(fullscreenUniforms[0],fullscreenUniforms[1],fullscreenUniforms[2],fullscreenUniforms[3]);\n}\nfn previousViewProjection()->mat4x4<f32>{\n return mat4x4<f32>(fullscreenUniforms[4],fullscreenUniforms[5],fullscreenUniforms[6],fullscreenUniforms[7]);\n}\nfn loadCurrentFog(pixel:vec2<i32>,size:vec2<i32>)->vec4<f32>{\n return textureLoad(currentFogTexture,clamp(pixel,vec2<i32>(0),size-vec2<i32>(1)),0);\n}\nfn loadHistoryFog(pixel:vec2<i32>,size:vec2<i32>)->vec4<f32>{\n return textureLoad(historyFogTexture,clamp(pixel,vec2<i32>(0),size-vec2<i32>(1)),0);\n}\nfn sampleHistoryBilinear(uv:vec2<f32>)->vec4<f32>{\n let size=vec2<i32>(textureDimensions(historyFogTexture));\n let position=uv*vec2<f32>(size)-0.5;\n let base=vec2<i32>(floor(position));\n let f=fract(position);\n let a=mix(loadHistoryFog(base,size),loadHistoryFog(base+vec2<i32>(1,0),size),f.x);\n let b=mix(loadHistoryFog(base+vec2<i32>(0,1),size),loadHistoryFog(base+vec2<i32>(1,1),size),f.x);\n return mix(a,b,f.y);\n}\nfn loadSceneDepth(uv:vec2<f32>)->f32{\n let size=vec2<i32>(textureDimensions(sceneDepthTexture));\n let pixel=clamp(vec2<i32>(uv*vec2<f32>(size)),vec2<i32>(0),size-vec2<i32>(1));\n return textureLoad(sceneDepthTexture,pixel,0);\n}\nfn loadHistoryDepth(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${(c=null!=i)?"\nfn loadVelocity(uv:vec2<f32>)->vec2<f32>{\n let size=vec2<i32>(textureDimensions(velocityTexture));\n let pixel=clamp(vec2<i32>(uv*vec2<f32>(size)),vec2<i32>(0),size-vec2<i32>(1));\n return textureLoad(velocityTexture,pixel,0).xy;\n}\n":""}\n@fragment fn fsMain(input:FullscreenVertexOutput)->FogTemporalOutput{\n let size=vec2<i32>(textureDimensions(currentFogTexture));\n let pixel=clamp(vec2<i32>(input.position.xy),vec2<i32>(0),size-vec2<i32>(1));\n let uv=(vec2<f32>(pixel)+0.5)/vec2<f32>(size);\n let current=textureLoad(currentFogTexture,pixel,0);\n var neighborhoodMin=current;\n var neighborhoodMax=current;\n for(var y=-1;y<=1;y+=1){\n for(var x=-1;x<=1;x+=1){\n let value=loadCurrentFog(pixel+vec2<i32>(x,y),size);\n neighborhoodMin=min(neighborhoodMin,value);\n neighborhoodMax=max(neighborhoodMax,value);\n }\n }\n let rawDepth=loadSceneDepth(uv);\n let clip=vec4<f32>(uv.x*2.0-1.0,1.0-uv.y*2.0,rawDepth,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 cameraHistoryUv=vec2<f32>(previousNdc.x*0.5+0.5,0.5-previousNdc.y*0.5);\n${c?"\n let velocity=loadVelocity(uv);\n let finiteVelocity=all(velocity==velocity)&&all(abs(velocity)<vec2<f32>(2.0));\n let hasUsefulVelocity=finiteVelocity&&dot(velocity,velocity)>1e-12;\n let historyUv=select(cameraHistoryUv,uv-velocity,hasUsefulVelocity);\n":"\n let historyUv=cameraHistoryUv;\n"}\n let validUv=all(historyUv>=vec2<f32>(0.0))&&all(historyUv<=vec2<f32>(1.0));\n let historyValid=fullscreenUniforms[8].w>0.5&&validUv;\n let history=sampleHistoryBilinear(clamp(historyUv,vec2<f32>(0.0),vec2<f32>(1.0)));\n let previousDistance=loadHistoryDepth(clamp(historyUv,vec2<f32>(0.0),vec2<f32>(1.0)));\n let currentDistance=length(world.xyz-fullscreenUniforms[9].xyz);\n let relativeDepthDelta=abs(log(max(previousDistance,0.001)/max(currentDistance,0.001)));\n let rejection=max(fullscreenUniforms[8].y,0.0001);\n let depthWeight=exp(-relativeDepthDelta*relativeDepthDelta/(rejection*rejection));\n let clampedHistory=select(history,clamp(history,neighborhoodMin,neighborhoodMax),fullscreenUniforms[8].z>0.5);\n let historyWeight=select(0.0,fullscreenUniforms[8].x*depthWeight,historyValid);\n var output:FogTemporalOutput;\n output.fog=mix(current,clampedHistory,clamp(historyWeight,0.0,0.98));\n output.depth=vec4<f32>(min(currentDistance,65504.0),0.0,0.0,1.0);\n return output;\n}`}temporal;state;name="VolumetricFogTemporalPass";sampler="nearest";uniformBufferSize=160;inputs;outputs;fragmentShader;uniforms=new Float32Array(this.uniformBufferSize/4);currentViewProjection=new be;currentViewProjectionInverse=new be;updateUniforms=e=>(this.state.updateTemporalUniforms(this.uniforms,this.currentViewProjection,this.currentViewProjectionInverse,this.temporal,e),Ue(this.uniforms,36,e.camera.position.x,e.camera.position.y,e.camera.position.z,e.camera.far),this.uniforms)},je=class{name;sampler="linear";uniformBufferSize=80;inputs;outputs;fragmentShader;data=new Float32Array(20);inverseProjection=new be;constructor(e,t,i,r,n){this.name=r[0]?"VolumetricFogBlurHorizontalPass":"VolumetricFogBlurVerticalPass",this.inputs={fogInput:e,sceneDepth:t},this.outputs=i,this.data.set([r[0],r[1],n.depthSigma,n.spatialSigma],16),this.fragmentShader=`\nconst BLUR_RADIUS:i32=${n.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(Re).multiply(e.camera.projectionMatrix).invert(),this.data.set(this.inverseProjection.elements,0),this.data)},$e=class{name="VolumetricFogBlurCompositePass";sampler="linear";uniformBufferSize=64;inputs;inputDimensions={};outputs;fragmentShader;data=new Float32Array(16);inverseProjection=new be;constructor(e,t,i,r,n,a,s){this.inputs=s?{sceneColor:e,sceneDepth:t,fogInput:i}:{sceneColor:e,fogInput:i},this.outputs=a,this.fragmentShader=s?Ke:Ye}updateUniforms=e=>(this.inverseProjection.copy(Re).multiply(e.camera.projectionMatrix).invert(),this.data.set(this.inverseProjection.elements),this.data)},We="\nfn rendererSampleIntegratedFogRaw(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 rendererSampleIntegratedFog(uv: vec2<f32>, normalizedDepth: f32) -> vec4<f32> {\n return rendererSampleIntegratedFogRaw(uv, normalizedDepth);\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(log(max(distance, bounds.x) / bounds.x) / max(log(bounds.y / bounds.x), 0.0001), 0.0, 1.0);\n let fog = rendererSampleIntegratedFog(uv, z);\n return vec4<f32>(fog.rgb + color.rgb * fog.a, color.a);\n}";function Ne(e,t="volumetricFogIntegrated",i=(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:i,dimension:"2d",sampleType:"float",sampler:"filtering",requiresLatePass:!0},e.needsUpdate=!0,e}var _e="\nstruct FogUniforms { inverseViewProjection: mat4x4<f32>, cameraNear: vec4<f32>, dimensionsFar: vec4<f32>, counts: vec4<u32>, ambient: vec4<f32>, cameraForwardDepthRange: vec4<f32>, scattering: vec4<f32>, previousViewProjection: mat4x4<f32>, historyCameraValid: vec4<f32>, historyNearFarWeight: 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>,64>, pointColorIntensities: array<vec4<f32>,64>, pointParams: array<vec4<f32>,64>, pointShadowParams: array<vec4<f32>,64>, pointShadowParams2: array<vec4<f32>,64>,\n spotPositionRanges: array<vec4<f32>,64>, spotDirectionCones: array<vec4<f32>,64>, spotColorIntensities: array<vec4<f32>,64>,\n spotShadowParams: array<vec4<f32>,64>, spotShadowParams2: array<vec4<f32>,64>, spotParams: array<vec4<f32>,64>, spotShadowMatrices: array<mat4x4<f32>,64>,\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>;\n@group(0) @binding(11) var historySampler: sampler;\n@group(0) @binding(12) var scatteringHistory: texture_3d<f32>;\n@group(0) @binding(13) var outputScatteringHistory: texture_storage_3d<rgba16float, write>;\n@group(0) @binding(14) var spotLightMapAtlas: texture_2d<f32>;\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 spotConeAttenuation(angleCos: f32, coneCos: f32, penumbraCos: f32) -> f32 {\n // Three.js spotlights default to a zero-width penumbra. smoothstep() is\n // undefined when both edges are equal, so use a hard cutoff in that case.\n let width = penumbraCos - coneCos;\n if (width <= 0.000001) { return select(0.0, 1.0, angleCos >= coneCos); }\n return smoothstep(coneCos, penumbraCos, angleCos);\n}\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 halton(index:u32,base:u32)->f32{var i=index;var fraction=1.0;var result=0.0;loop{if(i==0u){break;}fraction/=f32(base);result+=fraction*f32(i%base);i/=base;}return result;}\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 fogPointVisibility(light:FogLight,p:vec3<f32>)->f32 { if(light.penumbra.z<0.5){return 1.0;} return pointVisibility(u32(round(light.penumbra.y)),p); }\nfn fogSpotVisibility(light:FogLight,p:vec3<f32>)->f32 { if(light.penumbra.z<0.5){return 1.0;} return spotVisibility(u32(round(light.penumbra.y)),p); }\nfn fogSpotMap(light:FogLight,p:vec3<f32>)->vec3<f32> { let index=u32(round(light.penumbra.y)); if(rendererLights.spotParams[index].w<0.5){return vec3<f32>(1.0);} let clip=rendererLights.spotShadowMatrices[index]*vec4<f32>(p,1.0); if(clip.w<=0.0){return vec3<f32>(1.0);} let ndc=clip.xyz/clip.w; if(any(ndc<vec3<f32>(-1.0,-1.0,0.0))||any(ndc>vec3<f32>(1.0))){return vec3<f32>(1.0);} let uv=ndc.xy*vec2<f32>(0.5,-0.5)+vec2<f32>(0.5);let cell=vec2<f32>(f32(index%8u),f32(index/8u));let cellUv=clamp(uv,vec2<f32>(0.0),vec2<f32>(1.0))*(255.0/256.0)+vec2<f32>(0.5/256.0);return textureSampleLevel(spotLightMapAtlas,historySampler,(cell+cellUv)/8.0,0.0).rgb; }\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 // Keep the froxel lattice fixed. Moving the complete XY grid with a Halton\n // offset makes high-contrast shaft boundaries alternate between adjacent\n // froxels, which reads as the entire shadow edge blinking. We still use a\n // temporal Z offset to integrate within-slice variation over time without\n // moving the grid or the shadow-classification position sideways.\n let frameIndex=u32(max(uniforms.ambient.w,1.0));\n let temporal=vec2<f32>(0.5);\n let rayJitter=select(hash12(vec2<f32>(id.xy)+vec2<f32>(17.17,43.43)),halton(frameIndex,5u),uniforms.ambient.w>0.0);\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 centerUv=(vec2<f32>(id.xy)+vec2<f32>(0.5))/vec2<f32>(dims.xy);\n let centerFarPoint4=uniforms.inverseViewProjection*vec4<f32>(centerUv.x*2.0-1.0,1.0-centerUv.y*2.0,1.0,1.0);\n let centerRay=normalize(centerFarPoint4.xyz/centerFarPoint4.w-camera);\n let nearPlane = uniforms.cameraNear.w; let farPlane = uniforms.dimensionsFar.w;\n 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,farPlane);let columnFar=max(farPlane,columnNear+0.001);textureStore(outputDepthBounds,vec2<i32>(id.xy),vec4<f32>(columnNear,columnFar,0.0,0.0));\n let sliceRatio=pow(columnFar/columnNear,1.0/f32(dims.z));\n var transmittance = 1.0; var scattering = vec3<f32>(0.0); var previousDistance = columnNear; var sliceEnd=columnNear;\n for (var z=0u; z<dims.z; z+=1u) {\n // Every column uses the same logarithmic Z coordinate, so XY filtering\n // blends cumulative fog evaluated at the same physical distance.\n sliceEnd*=sliceRatio; let stepSize = sliceEnd-previousDistance;\n var localScattering=vec3<f32>(0.0);var localExtinction=0.0;\n if(stepSize>0.0){\n // Resizing recreates the 3D history. Use a few stratified samples only on\n // that first frame so the raw one-sample slice pattern is never exposed.\n let integrationSubsteps=max(INTEGRATION_SUBSTEPS,select(4u,INTEGRATION_SUBSTEPS,uniforms.historyCameraValid.w>0.5));\n let substepSize=stepSize/f32(integrationSubsteps);\n for(var substep=0u;substep<integrationSubsteps;substep+=1u){\n let sampleOffset=select(0.5,fract(rayJitter+f32(substep)/f32(integrationSubsteps)),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 // Follow the temporally stratified Z sample so history integrates shadow\n // transitions within a slice. XY remains fixed, preventing the complete\n // edge from oscillating sideways between neighboring froxels.\n let shadowP=p;\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));}filteredDirectionalVisibility[d]=directionalVisibility(d,shadowP)*cascadeWeight;}\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 shaftVisibility=0.0; var li=0u;\n for (var d=0u; d<uniforms.counts.y; d+=1u) {\n let l=lights[li]; li+=1u;\n shaftVisibility=max(shaftVisibility,filteredDirectionalVisibility[d]);\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)*fogPointVisibility(l,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=spotConeAttenuation(cd,l.directionCone.w,l.penumbra.x); direct += l.colorDecay.rgb*fogSpotMap(l,p)*attenuation(dist,l.positionRange.w,l.colorDecay.w)*cone*phaseHG(dot(ray,normalize(delta)),volume.heightStartPhase.w)*fogSpotVisibility(l,p); }\n direct*=uniforms.scattering.x;\n if (volume.mode.x < 0.5) { lighting += direct; } else { lighting = direct; }\n // Preserve fractional filtered visibility at shaft boundaries. A hard\n // threshold produces a temporally moving saw-tooth edge as jittered\n // froxels alternate between lit and shadowed. Direct lighting already\n // contains this visibility, while extinction must be scaled explicitly.\n if (volume.mode.x < 0.5) {\n sigma += density; source += lighting*volume.albedoDensity.rgb*density;\n } else {\n let visibleDensity=density*clamp(shaftVisibility,0.0,1.0);\n sigma += visibleDensity; source += lighting*volume.albedoDensity.rgb*density;\n }\n }\n }\n localScattering+=source/f32(integrationSubsteps);localExtinction+=sigma/f32(integrationSubsteps);\n }\n let historyPosition=camera+ray*(previousDistance+0.5*stepSize);\n let previousClip=uniforms.previousViewProjection*vec4<f32>(historyPosition,1.0);\n let previousUv=previousClip.xy/previousClip.w*vec2<f32>(0.5,-0.5)+vec2<f32>(0.5);\n let previousDistanceToCamera=length(historyPosition-uniforms.historyCameraValid.xyz);\n let previousNear=uniforms.historyNearFarWeight.x;let previousFar=uniforms.historyNearFarWeight.y;\n let previousZ=log(max(previousDistanceToCamera,previousNear)/previousNear)/max(log(previousFar/previousNear),0.0001);\n let validHistory=uniforms.historyCameraValid.w>0.5&&previousClip.w>0.0&&all(previousUv>=vec2<f32>(0.0))&&all(previousUv<=vec2<f32>(1.0))&&previousZ>=0.0&&previousZ<=1.0;\n if(validHistory){let history=textureSampleLevel(scatteringHistory,historySampler,vec3<f32>(previousUv,previousZ),0.0);let weight=uniforms.historyNearFarWeight.z;localScattering=mix(localScattering,history.rgb,weight);localExtinction=mix(localExtinction,history.a,weight);}\n }\n textureStore(outputScatteringHistory,vec3<i32>(i32(id.x),i32(id.y),i32(z)),vec4<f32>(localScattering,localExtinction));\n if(localExtinction>0.000001){let extinction=exp(-localExtinction*stepSize);scattering+=transmittance*localScattering*((1.0-extinction)/localExtinction);transmittance*=extinction;}\n textureStore(outputFog, vec3<i32>(i32(id.x),i32(id.y),i32(z)), vec4<f32>(scattering,transmittance)); previousDistance=sliceEnd;\n }\n}",He="\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 sampleIntegratedFogRaw(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}\nfn sampleIntegratedFog(uv:vec2<f32>,normalizedDepth:f32)->vec4<f32>{return sampleIntegratedFogRaw(uv,normalizedDepth);}\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(log(max(distance,bounds.x)/bounds.x)/max(log(bounds.y/bounds.x),0.0001),0.0,1.0);\n let frame=fullscreenUniforms[4].z; let ditherStrength=fullscreenUniforms[4].w;\n let noise=fogDither(input.position.xy,max(frame,0.0));\n let fog=sampleIntegratedFog(input.uv,z);\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}",qe="\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 sampleIntegratedFogRaw(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}\nfn sampleIntegratedFog(uv:vec2<f32>,normalizedDepth:f32)->vec4<f32>{return sampleIntegratedFogRaw(uv,normalizedDepth);}\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(log(max(distance,bounds.x)/bounds.x)/max(log(bounds.y/bounds.x),0.0001),0.0,1.0);var fog=sampleIntegratedFog(input.uv,z);let frame=fullscreenUniforms[4].z; let noise=fogDither(input.position.xy,max(frame,0.0));\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 Ke="\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);}\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 centerDepth=loadDepth(input.uv);var bestUv=clamp(candidates[0],vec2<f32>(0.0),vec2<f32>(1.0));var bestDifference=abs(centerDepth-loadDepth(bestUv));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(centerDepth-loadDepth(uv));maxDifference=max(maxDifference,difference);if(difference<bestDifference){bestDifference=difference;bestUv=uv;}}\n let sampleUv=select(input.uv,bestUv,maxDifference>0.001);let fog=textureSampleLevel(fogInputTexture,fullscreenSampler,sampleUv,0.0);return vec4<f32>(fog.rgb+color.rgb*fog.a,color.a);\n}",Ye="\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 Ze,DepthFormat as Xe,DepthStencilFormat as Je,FloatType as Qe,HalfFloatType as et,IntType as tt,RED_GREEN_RGTC2_Format as it,RED_RGTC1_Format as rt,RGBA_ASTC_10x10_Format as nt,RGBA_ASTC_10x5_Format as at,RGBA_ASTC_10x6_Format as st,RGBA_ASTC_10x8_Format as ot,RGBA_ASTC_12x10_Format as lt,RGBA_ASTC_12x12_Format as ct,RGBA_ASTC_4x4_Format as ut,RGBA_ASTC_5x4_Format as dt,RGBA_ASTC_5x5_Format as ht,RGBA_ASTC_6x5_Format as pt,RGBA_ASTC_6x6_Format as ft,RGBA_ASTC_8x5_Format as mt,RGBA_ASTC_8x6_Format as gt,RGBA_ASTC_8x8_Format as vt,RGBA_BPTC_Format as xt,RGBA_ETC2_EAC_Format as wt,RGBA_S3TC_DXT1_Format as bt,RGBA_S3TC_DXT3_Format as yt,RGBA_S3TC_DXT5_Format as St,RGBAFormat as Ct,RGBAIntegerFormat as Mt,RGFormat as Pt,RGIntegerFormat as Bt,RGB_ETC1_Format as Dt,RGB_ETC2_Format as It,RGB_S3TC_DXT1_Format as Tt,RGBFormat as Rt,RedFormat as Vt,RedIntegerFormat as Gt,ShortType as zt,SIGNED_RED_GREEN_RGTC2_Format as Lt,SIGNED_RED_RGTC1_Format as Ut,SRGBColorSpace as At,UnsignedByteType as kt,UnsignedInt248Type as Ft,UnsignedInt5999Type as Ot,UnsignedIntType as Et,UnsignedShortType as jt}from"three";function $t(e,t){const i=function(e){if(!0===e.isCubeTexture){const t=e.image,i=t?.[0],r=i?.image??i;return{width:r?.width??1,height:r?.height??1,depthOrArrayLayers:6}}const t=e.image;return{width:t?.width??1,height:t?.height??1,depthOrArrayLayers:t?.depth??1}}(e),r=Ht(e,t),n=Xt(e),a=function(e){return"3d"===Zt(e)?"3d":"2d"}(e),s=qt(e,r,t),o=Kt(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:r,textureDimension:a,viewDimension:n,sampleType:s,samplerBindingType:o,wgslTextureType:Yt(n,s),wgslSamplerType:"comparison"===o?"sampler_comparison":"sampler",width:i.width,height:i.height,depthOrArrayLayers:i.depthOrArrayLayers,mipLevelCount:l,compressed:Jt(e)}}function Wt(e,t){const i=$t(e,t);return[i.format,i.textureDimension,i.viewDimension,i.sampleType,i.samplerBindingType,i.width,i.height,i.depthOrArrayLayers,i.mipLevelCount].join(":")}function Nt(e){const t=qt(e,Ht(e,void 0,!1));return[Yt(Xt(e),t),"comparison"===Kt(e,t)?"sampler_comparison":"sampler"].join(":")}function _t(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}}function Ht(e,t,i=!0){const r=e.format,n=e.type,a=e.colorSpace===At;let s=null;if(Jt(e))switch(r){case Tt:case bt:s=a?"bc1-rgba-unorm-srgb":"bc1-rgba-unorm";break;case yt:s=a?"bc2-rgba-unorm-srgb":"bc2-rgba-unorm";break;case St:s=a?"bc3-rgba-unorm-srgb":"bc3-rgba-unorm";break;case rt:s="bc4-r-unorm";break;case Ut:s="bc4-r-snorm";break;case it:s="bc5-rg-unorm";break;case Lt:s="bc5-rg-snorm";break;case xt:s=a?"bc7-rgba-unorm-srgb":"bc7-rgba-unorm";break;case It:case Dt:s=a?"etc2-rgb8unorm-srgb":"etc2-rgb8unorm";break;case wt:s=a?"etc2-rgba8unorm-srgb":"etc2-rgba8unorm";break;case ut:s=a?"astc-4x4-unorm-srgb":"astc-4x4-unorm";break;case dt:s=a?"astc-5x4-unorm-srgb":"astc-5x4-unorm";break;case ht:s=a?"astc-5x5-unorm-srgb":"astc-5x5-unorm";break;case pt:s=a?"astc-6x5-unorm-srgb":"astc-6x5-unorm";break;case ft:s=a?"astc-6x6-unorm-srgb":"astc-6x6-unorm";break;case mt:s=a?"astc-8x5-unorm-srgb":"astc-8x5-unorm";break;case gt:s=a?"astc-8x6-unorm-srgb":"astc-8x6-unorm";break;case vt:s=a?"astc-8x8-unorm-srgb":"astc-8x8-unorm";break;case at:s=a?"astc-10x5-unorm-srgb":"astc-10x5-unorm";break;case st:s=a?"astc-10x6-unorm-srgb":"astc-10x6-unorm";break;case ot:s=a?"astc-10x8-unorm-srgb":"astc-10x8-unorm";break;case nt:s=a?"astc-10x10-unorm-srgb":"astc-10x10-unorm";break;case lt:s=a?"astc-12x10-unorm-srgb":"astc-12x10-unorm";break;case ct:s=a?"astc-12x12-unorm-srgb":"astc-12x12-unorm";break;case Ct:s=a?"rgba8unorm-srgb":"rgba8unorm"}else switch(r){case Ct:switch(n){case Ze:s="rgba8snorm";break;case zt:s="rgba16sint";break;case jt:s="rgba16uint";break;case Et:s="rgba32uint";break;case tt:s="rgba32sint";break;case kt:s=a?"rgba8unorm-srgb":"rgba8unorm";break;case et:s="rgba16float";break;case Qe:s="rgba32float"}break;case Rt:switch(n){case Ot:s="rgb9e5ufloat";break;case 35899:s="rg11b10ufloat"}break;case Vt:switch(n){case Ze:s="r8snorm";break;case zt:s="r16sint";break;case jt:s="r16uint";break;case Et:s="r32uint";break;case tt:s="r32sint";break;case kt:s="r8unorm";break;case et:s="r16float";break;case Qe:s="r32float"}break;case Pt:switch(n){case Ze:s="rg8snorm";break;case zt:s="rg16sint";break;case jt:s="rg16uint";break;case Et:s="rg32uint";break;case tt:s="rg32sint";break;case kt:s="rg8unorm";break;case et:s="rg16float";break;case Qe:s="rg32float"}break;case Xe:switch(n){case jt:s="depth16unorm";break;case Et:s="depth24plus";break;case Qe:s="depth32float"}break;case Je:switch(n){case Ft:s="depth24plus-stencil8";break;case Qe:Qt("depth32float-stencil8",t,e,"DepthTexture with DepthStencilFormat + FloatType"),s="depth32float-stencil8"}break;case Gt:switch(n){case tt:s="r32sint";break;case Et:s="r32uint"}break;case Bt:switch(n){case tt:s="rg32sint";break;case Et:s="rg32uint"}break;case Mt:switch(n){case tt:s="rgba32sint";break;case Et:s="rgba32uint"}}if(!s)throw new Error(`Texture format "${r}" with type "${n}" from "${e.constructor.name}" is not supported by this renderer yet.`);const o=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}(s);return o&&i&&Qt(o,t,e,`Texture format "${s}"`),s}function qt(e,t,i){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===tt)return"sint";if(e.type===Et)return"uint";if(e.type===Qe&&!ei(i,"float32-filterable")&&("r32float"===t||"rg32float"===t||"rgba32float"===t))return"unfilterable-float"}return"float"}function Kt(e,t){const i=e.compareFunction;return"depth"===t&&null!=i?"comparison":"float"===t?"filtering":"non-filtering"}function Yt(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 i="uint"===t?"u32":"sint"===t?"i32":"f32";switch(e){case"2d-array":return`texture_2d_array<${i}>`;case"cube":return`texture_cube<${i}>`;case"3d":return`texture_3d<${i}>`;default:return`texture_2d<${i}>`}}function Zt(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 Xt(e){const t=Zt(e);return"cube"===t?"cube":"2d-array"===t?"2d-array":"3d"===t?"3d":"2d"}function Jt(e){return!0===e.isCompressedTexture||!0===e.isCompressedArrayTexture}function Qt(e,t,i,r){if(!ei(t,e))throw new Error(`${r} for "${i.name||i.uuid}" requires the WebGPU feature "${e}", which is not enabled on this device.`)}function ei(e,t){return!!e&&(e instanceof Set?e.has(t):"features"in e?e.features.has(t):e.has(t))}import{Color as ti,Matrix3 as ii,Matrix4 as ri,Vector2 as ni,Vector3 as ai,Vector4 as si}from"three";var oi=new ArrayBuffer(8),li=new Float64Array(oi),ci=new Uint32Array(oi),ui={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 di(e,t){return Math.ceil(e/t)*t}function hi(e,t,i,r){const n="boolean"==typeof r?r?1:0:Number(r);"i32"!==i?"u32"!==i?e.setFloat32(t,n,!0):e.setUint32(t,n,!0):e.setInt32(t,n,!0)}function pi(e,t,i,r){for(let n=0;n<r;n+=1)e[t+n]=fi(i,n,r)}function fi(e,t,i){if("number"==typeof e||"boolean"==typeof e)return 0===t?Number(e):0;if(Array.isArray(e))return e[t]??0;if(e instanceof ii||e instanceof ri)return e.elements[t]??0;if(e instanceof ti)return 0===t?e.r:1===t?e.g:2===t?e.b:3===t&&i>=4?1:0;if(e instanceof ni||e instanceof ai||e instanceof si){if(0===t)return e.x;if(1===t)return e.y;if(2===t&&(e instanceof ai||e instanceof si))return e.z;if(3===t&&e instanceof si)return e.w}return 0}function mi(e,t,i){for(let r=0;r<3;r+=1){const n=3*r,a=t+4*r;e[a+0]=fi(i,n+0,9),e[a+1]=fi(i,n+1,9),e[a+2]=fi(i,n+2,9),e[a+3]=0}}function gi(e){let t=0;const i=[];for(const[r,n]of Object.entries(e)){const e=ui[n.type];t=di(t,e.alignment),i.push({name:r,offset:t,type:n.type}),t+=e.size}return{byteLength:di(t,16),entries:i}}var vi=class{constructor(e){this.layout=e,this.buffer=new ArrayBuffer(e.byteLength),this.view=new DataView(this.buffer),this.floats=new Float32Array(this.buffer)}layout;buffer;view;floats;update(e){return xi(e,this.layout,this.view,this.floats),this.buffer}};function xi(e,t,i,r){r.fill(0);for(const n of t.entries){const t=e[n.name],a=n.offset/4;switch(n.type){case"f32":case"i32":case"u32":hi(i,n.offset,n.type,t.value);break;case"vec2<f32>":pi(r,a,t.value,2);break;case"vec3<f32>":pi(r,a,t.value,3);break;case"vec4<f32>":pi(r,a,t.value,4);break;case"mat3x3<f32>":mi(r,a,t.value);break;case"mat4x4<f32>":t.value instanceof ri?r.set(t.value.elements,a):pi(r,a,t.value,16)}}}function wi(e,t){let i=Math.imul(e^t,16777619);return i^=i>>>13,i>>>0}function bi(e,t){return li[0]=t,e=wi(e,ci[0]??0),e=wi(e,ci[1]??0)}function yi(e,t,i){const r="number"==typeof t||"boolean"==typeof t?1:Array.isArray(t)?Math.min(t.length,i):t instanceof ti?i>=4?4:3:t instanceof ni?2:t instanceof ai?3:t instanceof si?4:t instanceof ii?9:t instanceof ri?16:0;e=wi(e,r);for(let n=0;n<r;n+=1)e=bi(e,fi(t,n,i));return e}var Si="\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";function Ci(e,t,i,r){let n=e.execution;if(!n){const a=[];for(let e=0;e<t;e++)a.push({binding:e,resource:null});e.uniformBuffer&&a.push({binding:t,resource:{buffer:e.uniformBuffer}});const s=[];for(let e=0;e<i;e++)s.push({view:null,clearValue:{r:0,g:0,b:0,a:1},loadOp:"clear",storeOp:"store"});n={resources:[],entries:a,attachments:s,bindGroupDescriptor:{label:`${r}-bind-group`,layout:e.bindGroupLayout,entries:a},passDescriptor:{label:r,colorAttachments:s}},e.execution=n}return n.passDescriptor.label=r,n}var Mi=new WeakMap;function Pi(e){let t=Mi.get(e);return t||(t={outputFormats:[],inputDimensions:[]},Mi.set(e,t)),t}var Bi=new WeakMap;function Di(e,t,i,r,n){let a=Bi.get(e);a||Bi.set(e,a=new Map);let s=a.get(t);s||(s={module:e.createShaderModule({label:i,code:t}),variants:new Map},a.set(t,s));let o=s.variants.get(r);return o||s.variants.set(r,o=n(s.module)),o}function Ii(){return{children:new WeakMap}}function Ti(e,t,i,r){let n=e;for(const e of t){let t=n.children.get(e);t||(t=Ii(),n.children.set(e,t)),n=t}return n.bindGroup??=i.createBindGroup(r),n.bindGroup}var Ri=new WeakMap,Vi=new WeakMap;function Gi(e){return e?"string"==typeof e?[e]:Array.from(e):[]}var zi=new WeakMap;function Li(e,t){let i=0;if(e)for(const r in e){if(!Object.hasOwn(e,r))continue;const n=t[i];if(!n||n[0]!==r||n[1]!==e[r])return!1;i+=1}return i===t.length}function Ui(e){return e.replace(/[^A-Za-z0-9_]/g,"_")}var Ai=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,t){this.context.addSceneTextureCopyPass(e,t)}addLatePass(e=this.sceneColor){this.context.addLatePass(e)}addHiZHistoryPass(e="ForwardPass"){this.context.addHiZHistoryPass(e)}addMaterialPass(e={}){const t={name:e.name,dependsOn:e.dependsOn,outputs:e.outputs??this.sceneColor,drawStage:e.drawStage,loadColor:e.loadColor,clearColor:e.clearColor,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,i=Gi(e.outputs),r={name:e.name,reads:t,writes:i.length>0?i:void 0,dependsOn:e.dependsOn,execute:e.execute};this.context.addCustomPass(r)}addFullscreenPass(e){const t=zi.get(e);if(t&&t.pass.name===e.name&&Li(e.inputs,t.inputs)&&Li(e.textures,t.textures)&&function(e,t){if("string"==typeof e)return 1===t.length&&t[0]===e;if(e.length!==t.length)return!1;for(let i=0;i<e.length;i+=1)if(e[i]!==t[i])return!1;return!0}(e.outputs,t.outputs))return void this.context.addCustomPass(t.pass);const i=Gi(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 a=r.map(([,e])=>e===this.mainDepth?"depth":"color"),s={name:e.name,reads:r.map(([,e])=>e),writes:i.length>0?i:void 0,execute:t=>{const{outputFormats:s,inputDimensions:o}=Pi(e);s.length=i.length;for(let e=0;e<i.length;e++)s[e]=t.getColorFormat(i[e]);const l=n.map(([,e])=>Wt(e,t.device)).join("|");o.length=r.length;for(let t=0;t<r.length;t++)o[t]=e.inputDimensions?.[r[t][0]]??"2d";const c=`${s.join("|")}:${a.map((e,t)=>`${e}-${o[t]}`).join("|")}:${l}:${e.uniformBufferSize??0}`,u=c,d=function(e,t){let i=Ri.get(e);i||(i=new WeakMap,Ri.set(e,i));let r=i.get(t);return r||(r=new Map,i.set(t,r)),r}(e,t.device);let h=d.get(u);if(!h){const i=n.map(([,e])=>$t(e,t.device)),l=[Si,"@group(0) @binding(0) var fullscreenSampler: sampler;",r.map(([e],t)=>`@group(0) @binding(${t+1}) var ${e}Texture: ${"depth"===a[t]?"texture_depth_2d":"3d"===o[t]?"texture_3d<f32>":"texture_2d<f32>"};`).join("\n"),n.map(([e],t)=>{const n=r.length+1+2*t,a=i[t];return`@group(0) @binding(${n}) var ${e}Sampler: ${a.wgslSamplerType};\n@group(0) @binding(${n+1}) var ${e}Texture: ${a.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"),p=`${c}:sampler=${"nearest"===e.sampler?"non-filtering":"filtering"}`,{bindGroupLayout:f,pipeline:m}=Di(t.device,l,`${e.name}-shader-module`,p,l=>{const c=t.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"===a[t]?"depth":"float",viewDimension:"3d"===o[t]?"3d":"2d"}})),...i.flatMap((e,t)=>{const i=r.length+1+2*t;return[{binding:i,visibility:GPUShaderStage.FRAGMENT,sampler:{type:e.samplerBindingType}},{binding:i+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"}}]:[]]}),u=t.device.createPipelineLayout({label:`${e.name}-pipeline-layout`,bindGroupLayouts:[c]});return{bindGroupLayout:c,pipeline:t.device.createRenderPipeline({label:`${e.name}-pipeline`,layout:u,vertex:{module:l,entryPoint:"vsMain"},fragment:{module:l,entryPoint:"fsMain",targets:s.map(e=>({format:e}))},primitive:{topology:"triangle-list"}})}});h={bindGroupLayout:f,pipeline:m,uniformBuffer:e.uniformBufferSize?t.device.createBuffer({label:`${e.name}-uniform-buffer`,size:16*Math.ceil(Math.max(16,e.uniformBufferSize)/16),usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}):null,bindGroupCache:Ii()},d.set(u,h)}const{pipeline:p,uniformBuffer:f}=h,m=e.updateUniforms?.(t)??null;f&&m&&t.device.queue.writeBuffer(f,0,m.buffer,m.byteOffset,m.byteLength);const g=Ci(h,r.length+1+2*n.length,i.length,e.name),v=g.resources;v[0]="nearest"===e.sampler||"linear"!==e.sampler&&a.includes("depth")?t.nearestClampSampler:t.linearClampSampler;for(let e=0;e<r.length;e++)v[e+1]="depth"===a[e]?t.depthView:t.getColorView(r[e][1]);for(let e=0;e<n.length;e++){const i=t.getExternalTexture(n[e][1]),a=r.length+1+2*e;v[a]=i.sampler,v[a+1]=i.view}const x=r.length+1+2*n.length;for(let e=0;e<x;e++)g.entries[e].resource=v[e];f&&(v[x]=f);const w=Ti(h.bindGroupCache,v,t.device,g.bindGroupDescriptor);for(let e=0;e<i.length;e++)g.attachments[e].view=t.getColorView(i[e]);const b=t.encoder.beginRenderPass(g.passDescriptor);b.setPipeline(p),b.setBindGroup(0,w),b.draw(3),b.end()}};zi.set(e,{inputs:r,textures:n,outputs:i,pass:s}),this.context.addCustomPass(s)}addNodeFullscreenPass(e){const t=Gi(e.outputs),r=Object.entries(function(e){const t={};for(const[i,r]of Object.entries(e.sceneTextures??{}))t[i]="sceneDepth"===r?{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,i])=>[t,null!=e.inputOverrides?.[t]?{...i,resource:e.inputOverrides[t]}:i]),n=Object.entries(e.shader.textures??{}),a=Object.fromEntries(r.map(([e,t])=>[e,t.resource])),s=gi(e.shader.uniforms);this.addPass({name:e.name,inputs:a,outputs:t,execute:a=>{const{outputFormats:o}=Pi(e);o.length=t.length;for(let e=0;e<t.length;e++)o[e]=a.getColorFormat(t[e]);const l=r.map(([e,t])=>`${e}:${t.dimension}:${t.sampleType}:${t.sampler??"filtering"}`).join("|"),c=n.map(([,e])=>Wt(e,a.device)).join("|"),u=s.entries.map(e=>`${e.name}:${e.type}:${e.offset}`).join("|"),d=`${o.join("|")}:${l}:${c}:${u}`,h=function(e,t){let i=Vi.get(e);i||(i=new WeakMap,Vi.set(e,i));let r=i.get(t);return r||(r=new Map,i.set(t,r)),r}(e.shader,a.device);let p=h.get(d);if(!p){const t=n.map(([,e])=>$t(e,a.device)),l=[];for(const[,e]of r){const t=l.length;l.push({binding:t,visibility:GPUShaderStage.FRAGMENT,sampler:{type:e.sampler??("depth-2d"===e.dimension?"non-filtering":"filtering")}},{binding:t+1,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:e.sampleType??("depth-2d"===e.dimension?"depth":"float"),viewDimension:"3d"===e.dimension?"3d":"2d"}})}for(const[e,i]of t.entries()){const e=l.length;l.push({binding:e,visibility:GPUShaderStage.FRAGMENT,sampler:{type:i.samplerBindingType}},{binding:e+1,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:i.sampleType,viewDimension:i.viewDimension}})}const c=2*(r.length+n.length);s.byteLength>0&&l.push({binding:c,visibility:GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}});const u=r.map(([e,t],i)=>{const r=Ui(e);return`@group(0) @binding(${2*i}) var ${r}Sampler: ${"comparison"===t.sampler?"sampler_comparison":"sampler"};\n@group(0) @binding(${2*i+1}) var ${r}Texture: ${"depth-2d"===t.dimension?"texture_depth_2d":"3d"===t.dimension?"texture_3d<f32>":"texture_2d<f32>"};`}).join("\n"),f=n.map(([e],i)=>{const n=2*(r.length+i),a=t[i],s=Ui(e);return`@group(0) @binding(${n}) var ${s}Sampler: ${a.wgslSamplerType};\n@group(0) @binding(${n+1}) var ${s}Texture: ${a.wgslTextureType};`}).join("\n"),m=s.entries.map(e=>` ${Ui(e.name)}: ${e.type},`).join("\n"),g=s.byteLength>0?`struct MaterialUniforms {\n${m}\n};\n@group(0) @binding(${c}) var<uniform> materialUniforms: MaterialUniforms;`:"",v=[Si,u,f,g,e.shader.fragmentShader].filter(Boolean).join("\n\n"),x=JSON.stringify([o,l]),{bindGroupLayout:w,pipeline:b}=Di(a.device,v,`${e.name}-node-shader-module`,x,t=>{const r=a.device.createBindGroupLayout({label:`${e.name}-node-layout`,entries:l}),n=a.device.createPipelineLayout({label:`${e.name}-node-pipeline-layout`,bindGroupLayouts:[r]});e.diagnosticOrigin&&i(a.device,`${e.name}-node-pipeline`,e.diagnosticOrigin);return{bindGroupLayout:r,pipeline:a.device.createRenderPipeline({label:`${e.name}-node-pipeline`,layout:n,vertex:{module:t,entryPoint:"vsMain"},fragment:{module:t,entryPoint:"fsMain",targets:o.map(e=>({format:e}))},primitive:{topology:"triangle-list"}})}});p={bindGroupLayout:w,pipeline:b,uniformBuffer:s.byteLength>0?a.device.createBuffer({label:`${e.name}-node-uniforms`,size:s.byteLength,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}):null,bindGroupCache:Ii()},h.set(d,p)}const{pipeline:f,uniformBuffer:m}=p;e.shader.syncLiveUniforms(e.shader.uniforms),m&&a.device.queue.writeBuffer(m,0,(p.uniformData??=new vi(s)).update(e.shader.uniforms));const g=2*(r.length+n.length),v=Ci(p,g,t.length,e.name),x=v.resources;for(let e=0;e<r.length;e++){const t=r[e][1];x[2*e]="comparison"===t.sampler?a.comparisonSampler:"non-filtering"===t.sampler||"depth-2d"===t.dimension?a.nearestClampSampler:a.linearClampSampler,x[2*e+1]=a.getTextureView(t.resource)}for(let e=0;e<n.length;e++){const t=a.getExternalTexture(n[e][1]),i=2*(r.length+e);x[i]=t.sampler,x[i+1]=t.view}for(let e=0;e<g;e++)v.entries[e].resource=x[e];m&&(x[g]=m);const w=Ti(p.bindGroupCache,x,a.device,v.bindGroupDescriptor);for(let e=0;e<t.length;e++)v.attachments[e].view=a.getColorView(t[e]);const b=a.encoder.beginRenderPass(v.passDescriptor);b.setPipeline(f),b.setBindGroup(0,w),b.draw(3),b.end()}})}present(e=this.sceneColor){this.context.addPresentPass(e)}};function ki(e,t=!1){return e.wireframe||!e.primitiveTopology.startsWith("triangle")?{depthBias:0,depthBiasSlopeScale:0,depthBiasClamp:0}:{depthBias:(t?1:0)+(e.polygonOffset?Math.trunc(e.polygonOffsetUnits):0),depthBiasSlopeScale:(t?2:0)+(e.polygonOffset?e.polygonOffsetFactor:0),depthBiasClamp:0}}var Fi=new WeakMap,Oi=new WeakMap;function Ei(e){const t=Oi.get(e);if(t){for(const e of t)e();t.clear(),Oi.delete(e)}}function ji(e,t){t?Fi.set(e,t):Fi.delete(e)}function $i(e){return Fi.get(e)}import{AlwaysCompare as Wi,BufferAttribute as Ni,EqualCompare as _i,GreaterCompare as Hi,GreaterEqualCompare as qi,InterleavedBufferAttribute as Ki,LessCompare as Yi,LessEqualCompare as Zi,MirroredRepeatWrapping as Xi,NearestFilter as Ji,NearestMipmapLinearFilter as Qi,NearestMipmapNearestFilter as er,NeverCompare as tr,NotEqualCompare as ir,Object3D as rr,RepeatWrapping as nr,Vector3 as ar}from"three";import{Material as sr}from"three";var or=[{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]}],lr=class e extends sr{isWGSLShaderMaterial=!0;vertexShader;fragmentShader;depthVertexShader;depthFragmentShader;pointShadowVertexShader;pointShadowFragmentShader;defines;uniforms;textures;sceneTextures;graphTextures;storageBuffers;vertexAttributes;primitiveTopology;wireframe;uniformLayoutCache=null;programCacheKeyCache=null;depthProgramCacheKeyCache=null;pointShadowProgramCacheKeyCache=null;textureListCache=null;textureVersionsCache=[];textureVersionHashCache=0;storageBufferBindingListCache=null;storageBufferListCache=null;textureLayoutKeyDeviceCache=null;textureLayoutKeyCache=null;uniformValuesAutoUpdate=!0;uniformValuesAutoVersion=0;set uniformValuesNeedsUpdate(e){e&&this.uniformValuesAutoVersion++}constructor(e){super();const{vertexShader:t,fragmentShader:i,depthVertexShader:r,depthFragmentShader:n,pointShadowVertexShader:a,pointShadowFragmentShader:s,defines:o,uniforms:l,textures:c,sceneTextures:u,graphTextures:d,storageBuffers:h,vertexAttributes:p,primitiveTopology:f,uniformValuesAutoUpdate:m,wireframe:g,...v}=e,x=function(e,t){const i={},r={...t};for(const[t,n]of Object.entries(e)){const e=hr(t,n);"texture"!==e.kind?i[t]=e.uniform:r[t]=e.texture}return{uniforms:i,textures:r}}(l??{},c??{});this.type="WGSLShaderMaterial",this.vertexShader=t,this.fragmentShader=i,this.depthVertexShader=r??null,this.depthFragmentShader=n??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=ur(p??or),this.primitiveTopology=f??"triangle-list",this.uniformValuesAutoUpdate=m??!0,this.wireframe=g??!1,this.transparent=v.transparent??!1,this.depthTest=v.depthTest??!0,this.depthWrite=v.depthWrite??!0,this.setValues(v)}getUniformLayout(){return null===this.uniformLayoutCache&&(this.uniformLayoutCache=gi(this.uniforms)),this.uniformLayoutCache}setUniform(e,t){const i=hr(e,t);return"texture"===i.kind?(delete this.uniforms[e],this.textures[e]=i.texture,this.uniformLayoutCache=null,this.invalidateBindingCache(),this.invalidateProgramStructureCache(),this.needsUpdate=!0,this):(delete this.textures[e],this.uniforms[e]=i.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=ur(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:dr(t.value)}])),this.textures={...e.textures},this.sceneTextures={...e.sceneTextures},this.graphTextures={...e.graphTextures},this.storageBuffers={...e.storageBuffers},this.vertexAttributes=ur(e.vertexAttributes),this.primitiveTopology=e.primitiveTopology,this.wireframe=e.wireframe,this.uniformValuesAutoUpdate=e.uniformValuesAutoUpdate,this.uniformValuesAutoVersion=e.uniformValuesAutoVersion,this.uniformLayoutCache=null,this.invalidateBindingCache(),this.invalidateProgramStructureCache(),this}clone(){return new e({vertexShader:this.vertexShader,fragmentShader:this.fragmentShader}).copy(this)}customProgramCacheKey(){return null!==this.programCacheKeyCache||(this.programCacheKeyCache=this.createProgramCacheKey(`vertex:${this.vertexShader};fragment:${this.fragmentShader};depthVertex:${this.depthVertexShader??""};depthFragment:${this.depthFragmentShader??""};pointShadowVertex:${this.pointShadowVertexShader??""};pointShadowFragment:${this.pointShadowFragmentShader??""};`)),this.programCacheKeyCache+this.getPolygonOffsetCacheKey()}getDepthProgramCacheKey(e=!1){const t=e?this.pointShadowProgramCacheKeyCache:this.depthProgramCacheKeyCache;if(null!==t)return t+this.getPolygonOffsetCacheKey();const i=(e?this.pointShadowVertexShader:this.depthVertexShader)??this.vertexShader,r=e?this.pointShadowFragmentShader:this.depthFragmentShader,n=this.createProgramCacheKey(`vertex:${i};fragment:${r??""};`);return e?this.pointShadowProgramCacheKeyCache=n:this.depthProgramCacheKeyCache=n,n+this.getPolygonOffsetCacheKey()}getPolygonOffsetCacheKey(){return this.polygonOffset&&!this.wireframe&&this.primitiveTopology.startsWith("triangle")?`polygonOffset:${Math.trunc(this.polygonOffsetUnits)}:${this.polygonOffsetFactor};`:""}createProgramCacheKey(e){const t=Object.keys(this.defines).sort((e,t)=>e.localeCompare(t));let i=e;for(const e of t)i+=`${e}:${String(this.defines[e])};`;for(const e in this.uniforms)i+=`uniform:${e}:${this.uniforms[e].type};`;for(const[e,t]of Object.entries(this.textures))i+=`texture:${e}:${Nt(t)};`;for(const[e,t]of Object.entries(this.sceneTextures))i+=`sceneTexture:${e}:${t};`;for(const[e,t]of Object.entries(this.getGraphTextureInputs()))i+=`graphTexture:${e}:${t.resource}:${t.dimension}:${t.sampleType??"float"}:${t.sampler??"filtering"}:${Number(t.requiresLatePass??!1)};`;for(const[e,t]of Object.entries(this.storageBuffers))i+=`storage:${e}:${t.type}:${t.visibility??"fragment"}:${t.access??"read"};`;for(const e of this.vertexAttributes){const t=e.defaultValue?e.defaultValue.join(","):"";i+=`attribute:${e.name}:${e.shaderLocation}:${e.format}:${e.stepMode??"vertex"}:${t};`}return i+=`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)};`,i}getTexturesList(){return null===this.textureListCache&&(this.textureListCache=Object.values(this.textures)),this.textureListCache}usesSceneTextures(){return this.usesSceneColor()||this.usesSceneDepth()}usesSceneColor(){return Object.values(this.sceneTextures).includes("sceneColor")||Object.values(this.graphTextures).some(e=>"sceneColorSnapshot"===e.resource)}usesSceneDepth(){return Object.values(this.sceneTextures).includes("sceneDepth")||Object.values(this.graphTextures).some(e=>"sceneDepthSnapshot"===e.resource)}getGraphTextureInputs(){const e={...this.graphTextures};for(const[t,i]of Object.entries(this.sceneTextures))e[t]="sceneDepth"===i?{resource:"sceneDepthSnapshot",dimension:"2d",sampleType:"unfilterable-float",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 i=2166136261;for(let r=0;r<t.entries.length;r+=1){const n=t.entries[r],a=e[n.name];if(a)switch(i=wi(i,n.offset),n.type){case"f32":case"i32":case"u32":i=bi(i,"boolean"==typeof a.value?a.value?1:0:Number(a.value));break;case"vec2<f32>":i=yi(i,a.value,2);break;case"vec3<f32>":i=yi(i,a.value,3);break;case"vec4<f32>":i=yi(i,a.value,4);break;case"mat3x3<f32>":i=yi(i,a.value,9);break;case"mat4x4<f32>":i=yi(i,a.value,16);break;default:i=wi(i,r+17)}else i=wi(i,r+1)}return i>>>0}(this.uniforms,this.getUniformLayout())}getTextureVersionsList(){const e=this.getTexturesList(),t=this.textureVersionsCache;t.length=e.length;let i=2166136261;for(let r=0;r<e.length;r+=1){const n=e[r].version;t[r]=n,i=Math.imul((i^n)>>>0,16777619)>>>0}return this.textureVersionHashCache=i,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=>function(e,t){const i=$t(e,t);return[i.viewDimension,i.sampleType,i.samplerBindingType].join(":")}(t,e)).join("|")),this.textureLayoutKeyCache}invalidateProgramStructureCache(){this.programCacheKeyCache=null,this.depthProgramCacheKeyCache=null,this.pointShadowProgramCacheKeyCache=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 cr(e){return!0===e.isWGSLShaderMaterial}function ur(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 dr(e){return Array.isArray(e)?Array.from(e):"number"==typeof e||"boolean"==typeof e?e:e.clone()}function hr(e,t){const i=fr(t)?t:null,r=null!==i&&"value"in i?i.value:t;if(function(e){return pr(e,"isTexture")}(r))return{kind:"texture",texture:r};if(!function(e){return"number"==typeof e||"boolean"==typeof e||Array.isArray(e)||pr(e,"isColor")||pr(e,"isVector2")||pr(e,"isVector3")||pr(e,"isVector4")||pr(e,"isMatrix3")||pr(e,"isMatrix4")}(r))throw new Error(`Unsupported WGSLShaderMaterial uniform "${e}". Use a number, boolean, vector, color, matrix, numeric array, or Texture.`);const n=i?.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}(n)?n: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(pr(t,"isColor"))return"vec3<f32>";if(pr(t,"isVector2"))return"vec2<f32>";if(pr(t,"isVector3"))return"vec3<f32>";if(pr(t,"isVector4"))return"vec4<f32>";if(pr(t,"isMatrix3"))return"mat3x3<f32>";if(pr(t,"isMatrix4"))return"mat4x4<f32>";throw new Error(`Cannot infer WGSL type for uniform "${e}". Provide an explicit type.`)}(e,r);return{kind:"uniform",uniform:{type:a,value:r}}}function pr(e,t){return fr(e)&&!0===e[t]}function fr(e){return"object"==typeof e&&null!==e}var mr=new WeakMap,gr=1;function vr(e){return e?"version"in e?e.version:e.data.version:0}function xr(e){const t=Object.keys(e.attributes).sort().map(t=>{const i=e.getAttribute(t);return[t,vr(i),i?.itemSize??0,i?.count??0].join(":")}).join("|"),i=e.index?.version??0,r=e.groups.map(e=>`${e.start}:${e.count}:${e.materialIndex??0}`).join("|");return[t,i,e.drawRange.start,e.drawRange.count,r].join(";")}function wr(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 br(e){return e.startsWith("uint32")?"uint32":e.startsWith("sint32")?"sint32":"float32"}function yr(e,t){switch(t){case"uint32":return new Uint32Array(e);case"sint32":return new Int32Array(e);default:return new Float32Array(e)}}function Sr(e,t,i,r){switch(i){case"uint32":e[t]=Math.max(0,Math.round(r));break;case"sint32":e[t]=Math.trunc(r);break;default:e[t]=r}}function Cr(e,t){const i=e[0]??0;for(let r=1;r<t;r++)if((e[r]??0)!==i)return!1;return!0}function Mr(e,t){if(e.length!==t.length)return!1;for(let i=0;i<e.length;i+=1)if(e[i]!==t[i])return!1;return!0}function Pr(e,t,i,r){const n=Math.max(4,t.byteLength),a=e.createBuffer({label:r,size:4*Math.ceil(n/4),usage:i,mappedAtCreation:!0});return new Uint8Array(a.getMappedRange()).set(new Uint8Array(t.buffer,t.byteOffset,t.byteLength)),a.unmap(),a}function Br(e){switch(e){case"vertex":return GPUShaderStage.VERTEX;case"vertex-fragment":return GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT;default:return GPUShaderStage.FRAGMENT}}function Dr(e,t){if(e.length!==t.length)return!1;for(let i=0;i<e.length;i+=1)if(e[i]!==t[i])return!1;return!0}function Ir(e,t){if(!e)return!1;if(e.length!==t.length)return!1;for(let i=0;i<e.length;i+=1)if(e[i]!==t[i])return!1;return!0}function Tr(e,t,i){try{return e.beginComputePass({timestampWrites:{querySet:t,...i}}).end(),!0}catch{return!1}}function Rr(e,t,i,r){if(e instanceof Ni&&!e.normalized&&e.itemSize===i&&e.count===t&&e.array instanceof Float32Array)return e.array;const n=new Float32Array(t*i);if(!e){if(Cr(r,i))return 0!==(r[0]??0)&&n.fill(r[0]),n;for(let e=0;e<t;e+=1)n.set(r,e*i);return n}if(!e.normalized&&(e instanceof Ni?e.getComponent===Ni.prototype.getComponent:e.getComponent===Ki.prototype.getComponent)){const a=e instanceof Ki,s=a?e.data.array:e.array,o=a?e.data.stride:e.itemSize,l=a?e.offset:0,c=Math.min(e.itemSize,i);for(let a=0;a<t;a++){const t=a*o+l,u=a*i;for(let e=0;e<i;e++)n[u+e]=e<c?s[t+e]:r[e]??0;3===e.itemSize&&4===i&&(n[u+3]=r[3]??1)}return n}for(let a=0;a<t;a+=1){for(let t=0;t<i;t+=1)t<e.itemSize?n[a*i+t]=e.getComponent(a,t):n[a*i+t]=r[t]??0;3===e.itemSize&&4===i&&(n[a*i+3]=r[3]??1)}return n}function Vr(e,t,i,r,n=0,a){const s=wr(i),o=br(i);if(!e)return function(e,t,i,r,n,a){const s=yr(i*r,a);if(!e&&Cr(n,r)){const e=n[0]??0;if(0!==e){const t="uint32"===a?Math.max(0,Math.round(e)):"sint32"===a?Math.trunc(e):e;s.fill(t)}return s}for(let o=0;o<i;o+=1){const i=o*t,l=o*r;for(let o=0;o<r;o+=1)Sr(s,l+o,a,e&&o<t?e[i+o]??n[o]??0:n[o]??0)}return s}(void 0,0,t,s,r,o);if(0===n&&e instanceof Ni&&!e.normalized&&e.itemSize===s&&e.count===t){const t=e.array;if("float32"===o&&t instanceof Float32Array||"uint32"===o&&t instanceof Uint32Array||"sint32"===o&&t instanceof Int32Array)return t}const l=t*s,c=a?.length===l&&("float32"===o?a instanceof Float32Array:"uint32"===o?a instanceof Uint32Array:a instanceof Int32Array)?a:yr(l,o);if("float32"===o&&!e.normalized&&(e instanceof Ni?e.getComponent===Ni.prototype.getComponent:e.getComponent===Ki.prototype.getComponent)){const i=e instanceof Ki,a=i?e.data.array:e.array,o=i?e.data.stride:e.itemSize,l=i?e.offset:0,u=Math.min(s,e.itemSize);for(let i=0;i<t;i++){const t=i*s,d=i-n,h=d>=0&&d<e.count,p=d*o+l;for(let e=0;e<s;e++)c[t+e]=h&&e<u?a[p+e]:r[e]??0}return c}for(let i=0;i<t;i+=1){const t=i*s,a=i-n,l=a>=0&&a<e.count;for(let i=0;i<s;i+=1){Sr(c,t+i,o,l&&i<e.itemSize?e.getComponent(a,i):r[i]??0)}}return c}function Gr(e,t,i,r){return Number.isFinite(r)&&r>0?r:t?Math.max(0,(e.index?.count??0)-i):Math.max(0,e.getAttribute("position").count-i)}function zr(e,t){return{start:e.drawRange.start,count:Gr(e,t,e.drawRange.start,e.drawRange.count)}}function Lr(e){return e===nr?"repeat":e===Xi?"mirror-repeat":"clamp-to-edge"}function Ur(e){return e===Ji||e===er||e===Qi?"nearest":"linear"}function Ar(e){return"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap||"undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas||"undefined"!=typeof HTMLVideoElement&&e instanceof HTMLVideoElement?e:null}function kr(e){return e}function Fr(e,t,i,r,n,a,s,o,l,c,u){return e.appendMatrixAndColorValues(t,i,r,n,a,s,o,l,c,u)}function Or(e,t,i,r,n,a,s,o,l,c,u){return e.appendMatrixAndColorValues(t.elements,i,r,n,a,s,o,l,c,u)}function Er(e,t,i){const r=e.elements;for(let e=0;e<16;e+=1)r[e]=t[i+e]??0;return e}function jr(e){const t=mr.get(e);if(void 0!==t)return t;const i=gr+=1;return mr.set(e,i),i}function $r(e,t,i,r,n,a){return[jr(e),jr(t),i?1:0,r,n,a?jr(a):0].join(":")}function Wr(e,t,i,r,n,a){let s=2166136261;return s=qr(s,e),s=qr(s,t),s=qr(s,i?1:0),s=qr(s,r),s=qr(s,n),s=qr(s,a),s}function Nr(e,t){return e.renderOrder!==t.renderOrder?e.renderOrder-t.renderOrder:(i=e.sortMaterialId,r=e.sortGeometryId,n=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,i!==l?i-l:r!==c?r-c:n!==u?n?-1:1:a!==d?a-d:s!==h?s-h:o-p);var i,r,n,a,s,o,l,c,u,d,h,p}function _r(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:Nr(e,t)}function Hr(e){for(let t=0;t<e.length;t+=1)if(e[t].hasRenderCallbacks)return!0;return!1}function qr(e,t){let i=Math.imul((e^t)>>>0,16777619);return i^=i>>>13,i>>>0}function Kr(e,t){return e.cameraDetailRejected===t.cameraDetailRejected&&e.detailCulling?.minScreenSize===t.detailCulling?.minScreenSize&&e.detailCulling?.maxDistance===t.detailCulling?.maxDistance&&e.detailCulling?.shadowMinScreenSize===t.detailCulling?.shadowMinScreenSize&&e.detailCulling?.shadowMaxDistance===t.detailCulling?.shadowMaxDistance&&e.renderOrder===t.renderOrder&&!e.hasRenderCallbacks&&!t.hasRenderCallbacks&&e.castShadow===t.castShadow&&e.receiveShadow===t.receiveShadow&&Zr(e)===Zr(t)&&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 Yr(e,t){return e.cameraDetailRejected===t.cameraDetailRejected&&e.detailCulling?.minScreenSize===t.detailCulling?.minScreenSize&&e.detailCulling?.maxDistance===t.detailCulling?.maxDistance&&e.detailCulling?.shadowMinScreenSize===t.detailCulling?.shadowMinScreenSize&&e.detailCulling?.shadowMaxDistance===t.detailCulling?.shadowMaxDistance&&e.renderOrder===t.renderOrder&&!e.hasRenderCallbacks&&!t.hasRenderCallbacks&&e.castShadow===t.castShadow&&e.receiveShadow===t.receiveShadow&&Zr(e)===Zr(t)&&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 Zr(e){return e.frontFaceCW}function Xr(e,t){for(let i=0;i<16;i+=1)t[i]=e[i]??0}function Jr(e,t){for(let i=0;i<16;i+=1)if((e[i]??0)!==(t[i]??0))return!1;return!0}function Qr(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 en(e,t,i,r){i.x<e.x&&(e.x=i.x),i.y<e.y&&(e.y=i.y),i.z<e.z&&(e.z=i.z),r.x>t.x&&(t.x=r.x),r.y>t.y&&(t.y=r.y),r.z>t.z&&(t.z=r.z)}function tn(e,t){return t.multiplyMatrices(A.multiplyMatrices(T,e.projectionMatrix),e.matrixWorldInverse)}function rn(e,t){const i=e.elements,r=i[0],n=i[1],a=i[2],s=i[3],o=i[4],l=i[5],c=i[6],u=i[7],d=i[8],h=i[9],p=i[10],f=i[11],m=i[12],g=i[13],v=i[14],x=i[15];return nn(t,0,s-r,u-o,f-d,x-m),nn(t,4,s+r,u+o,f+d,x+m),nn(t,8,s+n,u+l,f+h,x+g),nn(t,12,s-n,u-l,f-h,x-g),nn(t,16,s-a,u-c,f-p,x-v),nn(t,20,a,c,p,v),t}function nn(e,t,i,r,n,a){const s=Math.hypot(i,r,n)||1;e[t+0]=i/s,e[t+1]=r/s,e[t+2]=n/s,e[t+3]=a/s}function an(e,t,i,r,n){const a=-n;for(let n=0;n<24;n+=4){if(e[n+0]*t+e[n+1]*i+e[n+2]*r+e[n+3]<a)return!1}return!0}function sn(e){return null===e.boundingSphere&&e.computeBoundingSphere(),e.boundingSphere?{center:e.boundingSphere.center.clone(),radius:e.boundingSphere.radius}:{center:new ar,radius:1}}function on(e){const t=e.elements,i=Math.hypot(t[0],t[1],t[2]),r=Math.hypot(t[4],t[5],t[6]),n=Math.hypot(t[8],t[9],t[10]);return Math.max(i,r,n,1e-5)}function ln(e,t,i,r,n,a,s){const o=i.elements,l=a.elements,c=e.x,u=e.y,d=e.z,h=o[0]*c+o[4]*u+o[8]*d+o[12],p=o[1]*c+o[5]*u+o[9]*d+o[13],f=o[2]*c+o[6]*u+o[10]*d+o[14],m=r[n]*h+r[n+4]*p+r[n+8]*f+r[n+12],g=r[n+1]*h+r[n+5]*p+r[n+9]*f+r[n+13],v=r[n+2]*h+r[n+6]*p+r[n+10]*f+r[n+14];s.set(l[0]*m+l[4]*g+l[8]*v+l[12],l[1]*m+l[5]*g+l[9]*v+l[13],l[2]*m+l[6]*g+l[10]*v+l[14]);const x=r[n],w=r[n+4],b=r[n+8],y=r[n+1],S=r[n+5],C=r[n+9],M=r[n+2],P=r[n+6],B=r[n+10],D=x*o[0]+w*o[1]+b*o[2],I=x*o[4]+w*o[5]+b*o[6],T=x*o[8]+w*o[9]+b*o[10],R=y*o[0]+S*o[1]+C*o[2],V=y*o[4]+S*o[5]+C*o[6],G=y*o[8]+S*o[9]+C*o[10],z=M*o[0]+P*o[1]+B*o[2],L=M*o[4]+P*o[5]+B*o[6],U=M*o[8]+P*o[9]+B*o[10],A=l[0]*D+l[4]*R+l[8]*z,k=l[0]*I+l[4]*V+l[8]*L,F=l[0]*T+l[4]*G+l[8]*U,O=l[1]*D+l[5]*R+l[9]*z,E=l[1]*I+l[5]*V+l[9]*L,j=l[1]*T+l[5]*G+l[9]*U,$=l[2]*D+l[6]*R+l[10]*z,W=l[2]*I+l[6]*V+l[10]*L,N=l[2]*T+l[6]*G+l[10]*U,_=Math.hypot(A,O,$),H=Math.hypot(k,E,W),q=Math.hypot(F,j,N);return t*Math.max(_,H,q,1e-5)}function cn(e,t,i,r){const n=i.x-r,a=i.y-r,s=i.z-r,o=i.x+r,l=i.y+r,c=i.z+r;n<e.x&&(e.x=n),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 un(e){return Math.floor(Math.max(0,e.count)/3)*Math.max(0,e.instanceCount)}function dn(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 hn(e){const t=e.customDepthMaterial;return t&&cr(t)?t:null}var pn=class{external=new WeakMap;palettes=new WeakMap;dispose(){this.palettes=new WeakMap,this.external=new WeakMap}update(e){const t=$i(e);if(t){const i=this.external.get(e);return(i?.source!==t||i.version!==t.version)&&(i?(i.source=t,i.version=t.version):this.external.set(e,{source:t,version:t.version}),!0)}const i=this.external.delete(e);i&&this.palettes.delete(e);const r=16*e.bones.length;if(e.boneInverses.length!==e.bones.length)throw new Error("Skeleton inverse-bind count does not match bones");let n=this.palettes.get(e);n&&n.values.length===r||(n={values:new Float32Array(r),published:null,source:null},this.palettes.set(e,n)),e.boneMatrices.length<r&&(e.boneMatrices=new Float32Array(r)),n.published!==e.boneMatrices&&(n.source=e.boneMatrices.length===r?e.boneMatrices:new Float32Array(e.boneMatrices.buffer,e.boneMatrices.byteOffset,r)),function(e,t=!0){const i=e.bones,r=e.boneInverses,n=e.boneMatrices;for(let e=0;e<i.length;e+=1){const t=i[e],a=t?.matrixWorld.elements,s=r[e].elements,o=16*e;if(!a){n.set(s,o);continue}const l=a[0],c=a[4],u=a[8],d=a[12],h=a[1],p=a[5],f=a[9],m=a[13],g=a[2],v=a[6],x=a[10],w=a[14],b=a[3],y=a[7],S=a[11],C=a[15],M=s[0],P=s[4],B=s[8],D=s[12],I=s[1],T=s[5],R=s[9],V=s[13],G=s[2],z=s[6],L=s[10],U=s[14],A=s[3],k=s[7],F=s[11],O=s[15];n[o]=l*M+c*I+u*G+d*A,n[o+4]=l*P+c*T+u*z+d*k,n[o+8]=l*B+c*R+u*L+d*F,n[o+12]=l*D+c*V+u*U+d*O,n[o+1]=h*M+p*I+f*G+m*A,n[o+5]=h*P+p*T+f*z+m*k,n[o+9]=h*B+p*R+f*L+m*F,n[o+13]=h*D+p*V+f*U+m*O,n[o+2]=g*M+v*I+x*G+w*A,n[o+6]=g*P+v*T+x*z+w*k,n[o+10]=g*B+v*R+x*L+w*F,n[o+14]=g*D+v*V+x*U+w*O,n[o+3]=b*M+y*I+S*G+C*A,n[o+7]=b*P+y*T+S*z+C*k,n[o+11]=b*B+y*R+S*L+C*F,n[o+15]=b*D+y*V+S*U+C*O}t&&null!==e.boneTexture&&(e.boneTexture.needsUpdate=!0)}(e,!1);let a=i;for(let t=0;t<r;t++)if(n.values[t]!==e.boneMatrices[t]){a=!0;break}return a&&n.values.set(n.source),!a&&n.published===e.boneMatrices||null===e.boneTexture||(e.boneTexture.needsUpdate=!0),n.published=e.boneMatrices,a}},fn=new WeakMap;function mn(e,t){let i=fn.get(e);return i||(i=new Set,fn.set(e,i)),i.add(t),()=>i.delete(t)}function gn(e){const t=fn.get(e);if(t){for(const e of t)e();t.clear(),fn.delete(e)}}var vn=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/C}reset(){this.lengthFloats=0}appendMatrixAndColor(e,t,i=e,r=2,n=1,a=0){return this.appendMatrixAndColorValues(e,t[0]??1,t[1]??1,t[2]??1,t[3]??1,void 0,i,r,n,a)}appendMatrixAndColorValues(e,t,i,r,n,a=this.instanceCount,s=e,o=2,l=1,c=0){const u=this.instanceCount;this.ensureCapacity(this.lengthFloats+C);const d=this.lengthFloats;for(let t=0;t<16;t+=1)this.data[d+t]=e[t]??0;this.data[d+16]=t,this.data[d+17]=i,this.data[d+18]=r,this.data[d+19]=n,this.data[d+20]=a,this.data[d+21]=o,this.data[d+22]=l,this.data[d+23]=c;for(let t=0;t<16;t+=1)this.data[d+24+t]=s[t]??e[t]??0;return this.lengthFloats+=C,u}appendRange(e,t,i){if(i<=0)return;const r=t*C,n=r+i*C;this.ensureCapacity(this.lengthFloats+(n-r)),this.data.set(e.data.subarray(r,n),this.lengthFloats),this.lengthFloats+=n-r}appendBuilder(e){this.appendRange(e,0,e.instanceCount)}beginWriteInstances(e){const t=e*C;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 i=new Float32Array(t);i.set(this.data.subarray(0,this.lengthFloats),0),this.data=i}},xn=class{disposed=!1;cachedInstanceData=new vn;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;count=-1;update(e,t,i,r,n,a){const s=this.cachedInstanceData.rawData;let o=e!==this.count||s[21]!==Math.fround(r)||s[22]!==Math.fround(n)||s[23]!==a;for(let e=0;!o&&e<16;e++)o=s[e]!==Math.fround(t[e])||s[24+e]!==Math.fround(i[e]);if(o){this.cachedInstanceData.reset();for(let s=0;s<e;s++)this.cachedInstanceData.appendMatrixAndColorValues(t,1,1,1,1,s,i,r,n,a);this.count=e,this.residentBufferDirty=!0}}dispose(){this.disposed=!0;const e=this.residentInstanceBinding;e.buffer?.destroy(),e.buffer=null,e.sceneBindGroup=null,e.shadowBindGroup=null,e.shadowBindGroups.clear(),this.residentBufferSize=0,this.count=-1}};import{BufferAttribute as wn,InterleavedBufferAttribute as bn}from"three";var yn=class{constructor(e){this.attributes=e;let t=0;for(const i of e){this.offsets.push(t);const e=wr(i.format);this.components.push(e),this.kinds.push(br(i.format)),t+=e}this.stride=t}attributes;sources=[];versions=[];counts=[];itemSizes=[];components=[];offsets=[];kinds=[];stride;count=-1;floats=new Float32Array(0);unsigned=new Uint32Array(0);signed=new Int32Array(0);data=new Uint8Array(0);update(e,t,i,r,n=0){const a="instance"===this.attributes[0].stepMode;let s=a?Math.max(1,r):t,o=this.count<0,l=!1;for(let t=0;t<this.attributes.length;t++){const i=e.getAttribute(this.attributes[t].name);l||=void 0!==i;const r=vr(i);a&&(s=Math.max(s,i?.count??1)),o||=this.sources[t]!==i||this.versions[t]!==r||this.counts[t]!==(i?.count??0)||this.itemSizes[t]!==(i?.itemSize??0),this.sources[t]=i,this.versions[t]=r,this.counts[t]=i?.count??0,this.itemSizes[t]=i?.itemSize??0}if(a&&(s+=i,l||(s=Math.max(s,n))),o||=this.count!==s,!o)return!1;this.count=s;const c=s*this.stride;if(this.floats.length<c){const e=new ArrayBuffer(4*c);this.floats=new Float32Array(e),this.unsigned=new Uint32Array(e),this.signed=new Int32Array(e)}this.data.buffer===this.floats.buffer&&this.data.byteLength===4*c||(this.data=new Uint8Array(this.floats.buffer,0,4*c));for(let e=0;e<this.attributes.length;e++){const t=this.sources[e],r=this.attributes[e],n=this.components[e],o=this.kinds[e],l="uint32"===o?this.unsigned:"sint32"===o?this.signed:this.floats,c=t instanceof bn,u=t&&!t.normalized&&(c?t.getComponent===bn.prototype.getComponent:t.getComponent===wn.prototype.getComponent),d=t?c?t.data.array:t.array:void 0,h=t?c?t.data.stride:t.itemSize:0,p=c?t.offset:0;for(let c=0;c<s;c++){const s=c-(a?i:0),f=t&&s>=0&&s<t.count,m=c*this.stride+this.offsets[e];for(let e=0;e<n;e++){const i=f&&e<t.itemSize?u?d[s*h+p+e]:t.getComponent(s,e):r.defaultValue?.[e]??0;l[m+e]="uint32"===o?Math.max(0,Math.round(i)):"sint32"===o?Math.trunc(i):i}}}return!0}};import{FloatNode as Sn,compileNodeWebGpuExpression as Cn}from"three-shader-graph";var Mn=class extends Sn{constructor(e){super(),this.name=e}name;compile(){return{out:this.name}}},Pn=new Mn("radius"),Bn=new Mn("scale"),Dn=new Mn("threshold"),In=new Mn("boundary"),Tn=new Mn("maxDistance"),Rn=new Mn("distanceSquared"),Vn=Tn.add(Pn),Gn=Cn(Dn.lte(0).or(Pn.multiply(Bn).gte(Dn.multiply(In))).and(Tn.lte(0).or(Rn.lte(Vn.multiply(Vn))))),zn=`\nstruct ShadowCullParams {\n planes: array<vec4<f32>, 6>,\n viewer: vec4<f32>,\n diameterPerRadius: f32,\n instanceCount: u32,\n drawCount: u32,\n padding: u32,\n};\nstruct ShadowInstance { centerRadius: vec4<f32>, drawAndSource: vec4<u32> };\n@group(0) @binding(0) var<uniform> params: ShadowCullParams;\n@group(0) @binding(1) var<storage, read> metadata: array<ShadowInstance>;\n@group(0) @binding(2) var<storage, read> policies: array<vec4<f32>>;\n@group(0) @binding(3) var<storage, read_write> indirect: array<atomic<u32>>;\n@group(0) @binding(4) var<storage, read_write> indices: array<u32>;\n@group(0) @binding(5) var<storage, read_write> history: array<u32>;\n${`${Gn.definitions}\nfn shadowDetailVisible(radius: f32, scale: f32, threshold: f32, boundary: f32,\n maxDistance: f32, distanceSquared: f32) -> bool {\n ${Gn.statements}\n return ${Gn.expression};\n}`}\n\n@compute @workgroup_size(64)\nfn clear(@builtin(global_invocation_id) id: vec3<u32>) {\n if (id.x < params.drawCount) { atomicStore(&indirect[id.x * 5u + 1u], 0u); }\n}\n\n@compute @workgroup_size(64)\nfn main(@builtin(global_invocation_id) id: vec3<u32>) {\n if (id.x >= params.instanceCount) { return; }\n let instance = metadata[id.x];\n let draw = instance.drawAndSource.x;\n if (draw >= params.drawCount) { return; }\n let policy = policies[draw];\n if (policy.z < 0.5 || policy.w < 0.5) { history[id.x] = 0u; return; }\n let sphere = instance.centerRadius;\n let delta = sphere.xyz - params.viewer.xyz;\n let boundary = select(1.15, 0.85, history[id.x] != 0u);\n var visible = shadowDetailVisible(sphere.w, params.diameterPerRadius, policy.x,\n boundary, policy.y, dot(delta, delta));\n for (var plane = 0u; plane < 6u && visible; plane++) {\n visible = dot(params.planes[plane].xyz, sphere.xyz) + params.planes[plane].w >= -sphere.w;\n }\n history[id.x] = select(0u, 1u, visible);\n if (!visible) { return; }\n let destination = atomicLoad(&indirect[draw * 5u + 4u]);\n let slot = atomicAdd(&indirect[draw * 5u + 1u], 1u);\n indices[destination + slot] = instance.drawAndSource.y;\n}\n`,Ln="\n// Roughly eight f32 ULPs near depth 1. A 0.001 bias spans hundreds of\n// world units at distance with conventional perspective depth.\nconst OCCLUSION_DEPTH_BIAS: f32 = 0.000001;\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 nearestW = clip.w - radius * length(rowW);\n if (nearestW <= 0.0001) { return 0.0; }\n let depth = clip.z / clip.w;\n // For any sphere offset u, depth(u) - depth(center) equals\n // dot(rowZ - depth * rowW, u) / (clip.w + dot(rowW, u)).\n // Bound that difference, preserving the correlation of clip Z and W.\n // Independently minimizing Z and maximizing W grossly underestimates\n // distant depths and makes hidden buildings pass the occlusion test.\n let depthRadius = radius * length(rowZ - depth * rowW) / nearestW;\n return max(0.0, depth - depthRadius);\n}\n",Un=`\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\n${Ln}\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 + OCCLUSION_DEPTH_BIAS;\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`,An=`\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\n${Ln}\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 + OCCLUSION_DEPTH_BIAS;\n}\n\nfn cullInstance(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]) & 1u) != 0u) {\n return;\n }\n let drawIndex = instance.drawAndSourceIndex.x;\n let threshold = bitcast<f32>(instance.drawAndSourceIndex.z);\n let maxDistance = bitcast<f32>(instance.drawAndSourceIndex.w);\n let center = instance.centerRadius.xyz;\n let radius = instance.centerRadius.w;\n if (maxDistance > 0.0 && distance(center, temporalVisibility.currentCameraPosition.xyz) - radius > maxDistance) {\n return;\n }\n if (threshold > 0.0) {\n let vp = temporalVisibility.currentViewProj;\n let clip = vp * vec4(center, 1.0);\n let wRadius = radius * length(vec3(vp[0].w, vp[1].w, vp[2].w));\n if (clip.w - wRadius > 0.0001) {\n let projected = projectedSphereRadius(vp, clip.xyz / clip.w, clip.w, radius);\n let diameter = max(projected.x * temporalVisibility.viewportAndTime.x, projected.y * temporalVisibility.viewportAndTime.y);\n let wasDetailed = (atomicLoad(&visibleInstanceMask[instanceIndex]) & 4u) != 0u;\n let boundary = threshold * select(1.15, 0.85, wasDetailed);\n if (diameter < boundary) {\n atomicAnd(&visibleInstanceMask[instanceIndex], ~4u);\n return;\n }\n }\n }\n atomicOr(&visibleInstanceMask[instanceIndex], 4u);\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 atomicOr(&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// Only sets fitting in one workgroup may use fused clear/cull/build.\nstruct CompactIndirectArgs {\n indexCount: u32,\n instanceCount: u32,\n firstIndex: u32,\n baseVertex: i32,\n firstInstance: u32,\n};\n@group(0) @binding(10) var<storage, read_write> compactIndirectArgs: array<CompactIndirectArgs>;\n@group(0) @binding(11) var<storage, read_write> compactPostIndirectArgs: array<CompactIndirectArgs>;\n\n@compute @workgroup_size(64, 1, 1)\nfn main(@builtin(global_invocation_id) globalId: vec3<u32>) {\n let compact = (visibilityParams.flags & 8u) != 0u;\n let postpass = (visibilityParams.flags & 4u) != 0u;\n let index = globalId.x;\n if (compact && !postpass) {\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], atomicLoad(&visibleInstanceMask[index]) & 4u);\n }\n }\n if (compact) { storageBarrier(); }\n cullInstance(globalId);\n if (compact) {\n storageBarrier();\n if (index < visibilityParams.drawCount) {\n let primaryCount = atomicLoad(&visibleCounts[index]);\n let postCount = atomicLoad(&postVisibleCounts[index]);\n compactIndirectArgs[index].instanceCount = primaryCount + postCount;\n if (postpass) {\n compactPostIndirectArgs[index].instanceCount = postCount;\n compactPostIndirectArgs[index].firstInstance = compactIndirectArgs[index].firstInstance + primaryCount;\n }\n }\n }\n}\n`,kn="\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 previousModel0: vec4<f32>,\n previousModel1: vec4<f32>,\n previousModel2: vec4<f32>,\n previousModel3: 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) @invariant vec4<f32> {\n let world = rendererInstanceModelMatrix(instanceIndex) * vec4(position, 1.0);\n return shadowCamera.viewProj * world;\n}\n",Fn="\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 previousModel0: vec4<f32>,\n previousModel1: vec4<f32>,\n previousModel2: vec4<f32>,\n previousModel3: 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",On="\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",En="\nstruct RendererSkinningUniforms {\n bindMatrix: mat4x4<f32>,\n bindMatrixInverse: mat4x4<f32>,\n previousBindMatrix: mat4x4<f32>,\n previousBindMatrixInverse: 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",jn=`\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 previousModel0: vec4<f32>,\n previousModel1: vec4<f32>,\n previousModel2: vec4<f32>,\n previousModel3: 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${En}\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) @invariant vec4<f32> {\n let world = rendererInstanceModelMatrix(instanceIndex) * vec4(rendererSkinPosition(position, skinIndex, skinWeight), 1.0);\n return rendererCamera.viewProj * world;\n}\n`,$n=`\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 previousModel0: vec4<f32>,\n previousModel1: vec4<f32>,\n previousModel2: vec4<f32>,\n previousModel3: 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${En}\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`,Wn=`\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 previousModel0: vec4<f32>,\n previousModel1: vec4<f32>,\n previousModel2: vec4<f32>,\n previousModel3: 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${En}\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`,Nn="\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 _n(e){return`\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\n fn fsMain(input: FullscreenVertexOutput) -> @location(0) vec4<f32> {\n let source = textureSample(sourceTexture, sourceSampler, input.uv);\n ${e?"return vec4(source.rgb, 1.0);":"return vec4(clamp(source.rgb, vec3(0.0), vec3(1.0)), clamp(source.a / 3.0, 0.0, 1.0));"}\n }\n`}var Hn=_n(!1),qn=_n(!0),Kn=class{enabled=!0;available=!1;sets=new Map;device=null;layout=null;clear=null;cull=null;pipeline=null;frame=0;paramData=new Float32Array(32);paramInts=new Uint32Array(this.paramData.buffer);async initialize(e,t){if(!e.features.has("indirect-first-instance"))return;this.device=e,this.layout=t;const i=Array.from({length:6},(e,t)=>({binding:t,visibility:GPUShaderStage.COMPUTE,buffer:{type:0===t?"uniform":t<3?"read-only-storage":"storage"}})),r=zn,n=kn.replace("let instance = rendererInstances[instanceIndex];","let instance = rendererInstances[rendererVisibleInstanceIndices[instanceIndex]];").replace("@vertex","@group(0) @binding(2) var<storage, read> rendererVisibleInstanceIndices: array<u32>;\n@vertex");[this.clear,this.cull,this.pipeline]=await Promise.all([_.createAsync(e,{label:"directional-shadow-clear",code:r,entryPoint:"clear",bindGroupLayoutEntries:i}),_.createAsync(e,{label:"directional-shadow-cull",code:r,bindGroupLayoutEntries:i}),W(e,{label:"directional-shadow-visible-depth",layout:e.createPipelineLayout({bindGroupLayouts:[t]}),vertex:{module:e.createShaderModule({code: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",depthBias:1,depthBiasSlopeScale:2,depthBiasClamp:0}})]),this.available=!0}buffer(e,t,i){return this.device.createBuffer({label:e,size:256*Math.ceil(Math.max(4,t)/256),usage:i})}getSet(e){let t=this.sets.get(e);if(!t){const i=new Uint32Array(5*e.draws.length);for(let t=0;t<e.draws.length;t++){const r=e.draws[t];i.set([r.count,0,r.start,0,r.instanceStart],5*t)}t={materials:[],depthDrawIndices:[],materialVersion:0,preparedFrame:-1,eligibleDrawCount:0,triangleCount:0,commands:i,policies:this.buffer(`${e.label}-shadow-policies`,16*e.draws.length,GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST),policyData:new Float32Array(4*e.draws.length),eligibility:new Uint8Array(e.draws.length),eligibilityVersion:0,layers:new Map},this.sets.set(e,t),e.disposeDirectionalGpuShadows=()=>this.disposeSet(e)}return t}eligible(e){if(!e.indexed||e.wireframe||e.skinning||e.hasRenderCallbacks||"triangle-list"!==e.material.primitiveTopology||"packed"!==e.residentInstanceBinding?.mode)return!1;const t=e.customDepthMaterial??(null!==e.material.depthVertexShader?e.material:null);return!t||"triangle-list"===t.primitiveTopology&&!t.vertexAttributes.some(e=>"instance"===e.stepMode)}beginFrame(){this.frame++}prepareCascade(e,t,i,r){for(let t=0;t<6;t++){const i=e.planes[t],r=4*t;this.paramData[r]=i.normal.x,this.paramData[r+1]=i.normal.y,this.paramData[r+2]=i.normal.z,this.paramData[r+3]=i.constant}this.paramData[24]=i.x,this.paramData[25]=i.y,this.paramData[26]=i.z,this.paramData[28]=Math.max(Math.abs(t.projectionMatrix.elements[0]),Math.abs(t.projectionMatrix.elements[5]))*r}prepareSet(e,t,i){if(i.preparedFrame===this.frame)return;if(-1===i.preparedFrame){for(let e=0;e<t.draws.length;e++){const r=t.draws[e],n=r.detailCulling,a=this.eligible(r)?1:0,s=4*e;i.eligibility[e]=a,a&&(i.eligibleDrawCount++,r.castShadow&&(i.triangleCount+=un(r)),(r.customDepthMaterial||null!==r.material.depthVertexShader)&&i.depthDrawIndices.push(e)),i.policyData[s]=n.shadowMinScreenSize,i.policyData[s+1]=n.shadowMaxDistance,i.policyData[s+2]=r.castShadow?1:0,i.policyData[s+3]=a,i.materials[e]=null}this.device.queue.writeBuffer(i.policies,0,i.policyData)}let r=!1;for(const n of i.depthDrawIndices){const a=t.draws[n],s=a.customDepthMaterial??a.material,o=e.getDepthPassMaterialResourceForDraw(s,"directionalShadow",a,"packed-visible");i.materials[n]!==o&&(r=!0),i.materials[n]=o}r&&i.materialVersion++,i.preparedFrame=this.frame}prepare(e,t,i,r,n){if(!this.enabled||!this.available||i.instanceCount>64*this.device.limits.maxComputeWorkgroupsPerDimension)return null;const a=this.getSet(i);this.prepareSet(e,i,a);let s=a.layers.get(r);if(!s){const e=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST|GPUBufferUsage.COPY_SRC,t=this.buffer(`${i.label}-shadow-cull-params`,128,GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST),n=this.buffer(`${i.label}-shadow-indirect`,a.commands.byteLength,e|GPUBufferUsage.INDIRECT),o=this.buffer(`${i.label}-shadow-indices`,4*i.instanceCount,e),l=this.buffer(`${i.label}-shadow-history`,4*i.instanceCount,e);this.device.queue.writeBuffer(n,0,a.commands);const c=[t,i.instanceVisibilityResource.instanceMetadataBuffer,a.policies,n,o,l].map((e,t)=>({binding:t,resource:{buffer:e}}));s={params:t,indirect:n,indices:o,history:l,clearGroup:this.clear.createBindGroup(this.device,c),cullGroup:this.cull.createBindGroup(this.device,c),shadowGroup:this.device.createBindGroup({layout:this.layout,entries:[{binding:0,resource:{buffer:r}},{binding:1,resource:{buffer:i.instanceBuffer}},{binding:2,resource:{buffer:o}}]}),bundle:null,materials:[],eligibilityVersion:-1,materialVersion:-1,bundles:[],materialCacheKey:`directional-shadow-gpu-${a.layers.size}`},a.layers.set(r,s),i.depthMaterialResources.set(s.materialCacheKey,s.materials)}this.paramInts[29]=i.instanceCount,this.paramInts[30]=i.draws.length,this.device.queue.writeBuffer(s.params,0,this.paramData);const o=s.materialVersion!==a.materialVersion;if(o){for(let e=0;e<a.materials.length;e++)s.materials[e]=a.materials[e];s.materialVersion=a.materialVersion}s.bundle&&s.eligibilityVersion===a.eligibilityVersion&&!o||this.buildBundle(e,i,a,s);const l=n??t.beginComputePass({label:`${i.label}-directional-shadow-selection`});return l.setPipeline(this.clear.pipeline),l.setBindGroup(0,s.clearGroup),l.dispatchWorkgroups(Math.ceil(i.draws.length/64)),l.setPipeline(this.cull.pipeline),l.setBindGroup(0,s.cullGroup),l.dispatchWorkgroups(Math.ceil(i.instanceCount/64)),n||l.end(),a.eligibility}buildBundle(e,t,i,r){const n=this.device.createRenderBundleEncoder({colorFormats:[],depthStencilFormat:"depth32float",sampleCount:1});let a=null,s=null,o=null;for(let l=0;l<t.draws.length;l++){if(!i.eligibility[l])continue;const c=t.draws[l],u=r.materials[l],d=u?.pipeline??this.pipeline;d!==a&&(n.setPipeline(d),n.setBindGroup(0,r.shadowGroup),a=d,s=null,o=null),u&&s!==u.bindGroup&&(n.setBindGroup(1,u.bindGroup),s=u.bindGroup),o!==c.geometryKey&&(e.bindGeometryVertexBuffers(n,c.geometry,c.geometryResource,u?.vertexAttributes??z,c.instanceStart,c.instanceCount,!1),o=c.geometryKey),n.drawIndexedIndirect(r.indirect,20*l)}r.bundle=n.finish(),r.bundles[0]=r.bundle,r.eligibilityVersion=i.eligibilityVersion}submit(e,t,i,r){const n=this.sets.get(t),a=n?.layers.get(i);return!!(this.enabled&&this.available&&n&&a)&&(e.executeBundles(a.bundles),r.drawCallCount+=n.eligibleDrawCount,r.directionalShadowGpuDraws=(r.directionalShadowGpuDraws??0)+n.eligibleDrawCount,r.triangleCount+=n.triangleCount,!0)}disposeSet(e){const t=this.sets.get(e);if(t){t.policies.destroy();for(const e of t.layers.values())e.params.destroy(),e.indirect.destroy(),e.indices.destroy(),e.history.destroy();t.layers.clear(),this.sets.delete(e),e.disposeDirectionalGpuShadows=void 0}}dispose(){for(const e of this.sets.keys())this.disposeSet(e);this.available=!1}},Yn=class{constructor(e,t=1048576){this.device=e,this.alignment=Math.max(64,e.limits.minStorageBufferOffsetAlignment??256),this.maxBytes=Math.min(e.limits.maxStorageBufferBindingSize??134217728,e.limits.maxBufferSize??268435456),this.pageBytes=Math.floor(Math.min(t,this.maxBytes)/this.alignment)*this.alignment}device;pages=new Set;dirtyPages=new Set;alignment;pageBytes;maxBytes;allocate(e){const t=64*e,i=Math.ceil(t/this.alignment)*this.alignment;if(!e||i>this.maxBytes)throw new Error("Skeleton exceeds GPU palette buffer limits");let r,n=-1;for(const e of this.pages)if(n=e.free.findIndex(e=>e.size>=i),n>=0){r=e;break}if(!r){const e=Math.max(this.pageBytes,i),t=t=>this.device.createBuffer({label:t,size:e,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST});r={current:t("renderer-skinning-current-page"),previous:t("renderer-skinning-previous-page"),currentData:new Float32Array(e/4),previousData:new Float32Array(e/4),currentStart:1/0,currentEnd:0,previousStart:1/0,previousEnd:0,free:[{offset:0,size:e}],count:0},this.pages.add(r),n=0}const a=r.free[n],s=a.offset;return a.offset+=i,a.size-=i,a.size||r.free.splice(n,1),r.count++,{page:r,offset:s,byteLength:t,reservedBytes:i,currentBinding:{buffer:r.current,offset:s,size:t},previousBinding:{buffer:r.previous,offset:s,size:t}}}stage(e,t,i){const{page:r,offset:n,byteLength:a}=e;this.dirtyPages.add(r);const s=i?r.previousData:r.currentData,o=n/4,l=a/4;if(t.length===l)s.set(t,o);else for(let e=0;e<l;e++)s[o+e]=t[e];i?(r.previousStart=Math.min(r.previousStart,n),r.previousEnd=Math.max(r.previousEnd,n+a)):(r.currentStart=Math.min(r.currentStart,n),r.currentEnd=Math.max(r.currentEnd,n+a))}flush(){for(const e of this.dirtyPages)e.previousEnd>e.previousStart&&(this.device.queue.writeBuffer(e.previous,e.previousStart,e.previousData.buffer,e.previousStart,e.previousEnd-e.previousStart),e.previousStart=1/0,e.previousEnd=0),e.currentEnd>e.currentStart&&(this.device.queue.writeBuffer(e.current,e.currentStart,e.currentData.buffer,e.currentStart,e.currentEnd-e.currentStart),e.currentStart=1/0,e.currentEnd=0);this.dirtyPages.clear()}release(e){const{page:t,offset:i,reservedBytes:r}=e;if(0===--t.count)return t.current.destroy(),t.previous.destroy(),this.pages.delete(t),void this.dirtyPages.delete(t);const n=t.free;let a=0;for(;a<n.length&&n[a].offset<i;)a++;n.splice(a,0,{offset:i,size:r}),a>0&&n[a-1].offset+n[a-1].size===n[a].offset&&(n[a-1].size+=n[a].size,n.splice(a,1),a--),a+1<n.length&&n[a].offset+n[a].size===n[a+1].offset&&(n[a].size+=n[a+1].size,n.splice(a+1,1))}dispose(){for(const e of this.pages)e.current.destroy(),e.previous.destroy();this.pages.clear(),this.dirtyPages.clear()}},Zn=class{records=new WeakMap;get(e,t,i,r,n,a,s){let o=this.records.get(e);o||(o=[],this.records.set(e,o));let l=o[t];if(!l||l.material!==i||l.customDepthMaterial!==s||l.indexed!==r||l.start!==n||l.count!==a){const c=jr(i),u=jr(e),d=s?jr(s):0;l={material:i,customDepthMaterial:s,indexed:r,start:n,count:a,materialId:c,geometryId:u,depthMaterialId:d,batchKey:$r(i,e,r,n,a,s),batchHash:Wr(c,u,r,n,a,d)},o[t]=l}return l}},Xn=class{constructor(e=128){this.pageCapacity=e}pageCapacity;pages=new Set;get instanceCapacity(){return this.pages.size>0?this.pageCapacity:0}allocate(){let e;for(const t of this.pages)if(t.free.length){e=t;break}if(!e){const t=new vn(this.pageCapacity*C);t.beginWriteInstances(this.pageCapacity),e={cachedInstanceData:t,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,residentBufferDirtyRange:{start:1/0,end:0},free:Array.from({length:this.pageCapacity},(e,t)=>this.pageCapacity-t-1),count:0,queuedExtraction:-1},this.pages.add(e)}return e.count++,{page:e,index:e.free.pop()}}write(e,t,i,r,n,a,s,o){const l=e.page,c=l.cachedInstanceData.rawData,u=e.index*C;let d=!1;for(let s=0;s<C;s++){const o=Math.fround(s<16?t[s]:s>=24?i[s-24]:s<20?1:20===s?e.index:21===s?r:22===s?n:a);c[u+s]!==o&&(c[u+s]=o,d=!0)}d&&(l.residentBufferDirty=!0,l.residentBufferDirtyRange.start=Math.min(l.residentBufferDirtyRange.start,e.index),l.residentBufferDirtyRange.end=Math.max(l.residentBufferDirtyRange.end,e.index+1)),this.queueUpload(e,s,o)}queueUpload(e,t,i){const r=e.page;!r.residentBufferDirty&&r.residentInstanceBinding.buffer||r.queuedExtraction===t||(r.queuedExtraction=t,i.push(r))}release(e){const t=e.page;t.free.push(e.index),0===--t.count&&(t.residentInstanceBinding.buffer?.destroy(),t.residentInstanceBinding.buffer=null,t.residentInstanceBinding.sceneBindGroup=null,t.residentInstanceBinding.shadowBindGroup=null,t.residentInstanceBinding.shadowBindGroups.clear(),this.pages.delete(t))}dispose(){for(const e of this.pages)e.residentInstanceBinding.buffer?.destroy();this.pages.clear()}};function Jn(e=4){let t=performance.now()+e;return()=>{if(!(performance.now()<t))return new Promise(i=>setTimeout(()=>{t=performance.now()+e,i()},0))}}var Qn=class e{constructor(e,t,i,r){this.device=e,this.camera=t,this.lights=i,this.pipeline=r}device;camera;lights;pipeline;texture=null;textureView=null;bindGroup=null;columns=0;rows=0;static async createAsync(t,i,r){const n=await N(t,{label:"tiled-point-lights",layout:"auto",compute:{module:t.createShaderModule({label:"tiled-point-lights",code:"\nstruct Camera {\n viewProj: mat4x4<f32>,\n position: vec4<f32>,\n viewport: vec4<f32>,\n};\n@group(0) @binding(0) var<uniform> camera: Camera;\n@group(0) @binding(1) var<uniform> lights: array<vec4<f32>, 1001>;\n@group(0) @binding(2) var masks: texture_storage_2d<rg32uint, write>;\n\nfn normalizePlane(plane: vec4<f32>) -> vec4<f32> {\n return plane / max(length(plane.xyz), 1e-20);\n}\n\n@compute @workgroup_size(8, 8)\nfn main(@builtin(global_invocation_id) id: vec3<u32>) {\n if (any(id.xy >= textureDimensions(masks))) { return; }\n let lo = vec2<f32>(id.xy * 16u) / camera.viewport.xy;\n let hi = min(vec2<f32>((id.xy + 1u) * 16u), camera.viewport.xy) / camera.viewport.xy;\n let rows = transpose(camera.viewProj);\n let left = normalizePlane(rows[0] - (lo.x * 2.0 - 1.0) * rows[3]);\n let right = normalizePlane((hi.x * 2.0 - 1.0) * rows[3] - rows[0]);\n let top = normalizePlane((1.0 - lo.y * 2.0) * rows[3] - rows[1]);\n let bottom = normalizePlane(rows[1] - (1.0 - hi.y * 2.0) * rows[3]);\n var mask = vec2<u32>(0u);\n let count = min(u32(lights[1].y), 64u);\n for (var i = 0u; i < count; i++) {\n let center = vec4<f32>(lights[34u + i].xyz, 1.0);\n // Use the authored attenuation cutoff, NOT the finite shadow-camera range.\n let radius = lights[162u + i].x;\n let distance = min(min(dot(left, center), dot(right, center)), min(dot(top, center), dot(bottom, center)));\n // A small conservative tolerance avoids precision cracks on tile boundaries.\n if (radius <= 0.0 || distance >= -radius - max(0.001, radius * 1e-5)) {\n mask[i >> 5u] |= 1u << (i & 31u);\n }\n }\n textureStore(masks, vec2<i32>(id.xy), vec4<u32>(mask, 0u, 0u));\n}\n"}),entryPoint:"main"}});return new e(t,i,r,n)}get view(){if(!this.textureView)throw new Error("Tiled lighting has not been sized.");return this.textureView}resize(e,t){const i=Math.max(1,Math.ceil(e/16)),r=Math.max(1,Math.ceil(t/16));return(i!==this.columns||r!==this.rows)&&(this.texture?.destroy(),this.columns=i,this.rows=r,this.texture=this.device.createTexture({label:"tiled-point-light-masks",size:[i,r],format:"rg32uint",usage:GPUTextureUsage.STORAGE_BINDING|GPUTextureUsage.TEXTURE_BINDING}),this.textureView=this.texture.createView(),this.bindGroup=this.device.createBindGroup({layout:this.pipeline.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:this.camera}},{binding:1,resource:{buffer:this.lights}},{binding:2,resource:this.textureView}]}),!0)}execute(e){const t=e.beginComputePass({label:"TiledPointLightsPass"});t.setPipeline(this.pipeline),t.setBindGroup(0,this.bindGroup),t.dispatchWorkgroups(Math.ceil(this.columns/8),Math.ceil(this.rows/8)),t.end()}destroy(){this.texture?.destroy()}};import{AdditiveBlending as ea,BackSide as ta,BufferAttribute as ia,BufferGeometry as ra,Color as na,DoubleSide as aa,InstancedBufferAttribute as sa,InstancedBufferGeometry as oa,InstancedMesh as la,MultiplyBlending as ca,Matrix4 as ua,Mesh as da,OrthographicCamera as ha,PerspectiveCamera as pa,SkinnedMesh as fa,Sphere as ma,SubtractiveBlending as ga,Vector2 as va,Vector3 as xa,Vector4 as wa,ShaderMaterial as ba}from"three";var ya=/^[A-Za-z_][A-Za-z0-9_]*$/;function Sa(e,t={},i={}){const r=function(e){const t=new Map;for(const[i,r]of Object.entries(e))ya.test(i)&&!1!==r&&null!=r&&t.set(i,{name:i,parameters:null,body:Ca(r)});return t}(t),n=new Map,a=[],s=[],o=e.split(/\r?\n/),l=i.sourceName??"shader";for(let e=0;e<o.length;e+=1){const t=o[e],i=Ma(t),c=Ba(a);if(!i){s.push(c?Ia(t,r,n):"");continue}const{name:u,rest:d}=i;switch(u){case"define":if(c){const t=Pa(d,r,l,e+1),i=r.get(t);null===i.parameters?n.delete(t):n.set(t,i)}s.push("");break;case"undef":c&&(r.delete(d.trim()),n.delete(d.trim())),s.push("");break;case"ifdef":{const e=c,t=e&&r.has(d.trim());a.push({parentActive:e,active:t,branchTaken:t,elseSeen:!1}),s.push("");break}case"ifndef":{const e=c,t=e&&!r.has(d.trim());a.push({parentActive:e,active:t,branchTaken:t,elseSeen:!1}),s.push("");break}case"if":{const e=c,t=e&&Aa(d,r);a.push({parentActive:e,active:t,branchTaken:t,elseSeen:!1}),s.push("");break}case"elif":{const t=Da(a,l,e+1,u);if(t.elseSeen)throw new Error(`${l}:${e+1}: #elif after #else`);const i=t.parentActive&&!t.branchTaken&&Aa(d,r);t.active=i,t.branchTaken=t.branchTaken||i,s.push("");break}case"else":{const t=Da(a,l,e+1,u);if(t.elseSeen)throw new Error(`${l}:${e+1}: duplicate #else`);t.active=t.parentActive&&!t.branchTaken,t.branchTaken=!0,t.elseSeen=!0,s.push("");break}case"endif":Da(a,l,e+1,u),a.pop(),s.push("");break;case"error":if(c)throw new Error(`${l}:${e+1}: ${d.trim()||"#error"}`);s.push("");break;case"warning":case"line":case"version":case"pragma":s.push("");break;default:if(c)throw new Error(`${l}:${e+1}: unsupported preprocessor directive #${u}`);s.push("")}}if(a.length>0)throw new Error(`${l}: unterminated preprocessor conditional`);return s.join("\n")}function Ca(e){return"boolean"==typeof e?e?"1":"0":String(e)}function Ma(e){const t=/^\s*#\s*([A-Za-z_][A-Za-z0-9_]*)(.*)$/.exec(e);return t?{name:t[1],rest:t[2]??""}:null}function Pa(e,t,i,r){const n=/^\s*([A-Za-z_][A-Za-z0-9_]*)(.*)$/.exec(e);if(!n)throw new Error(`${i}:${r}: invalid #define`);const a=n[1],s=n[2]??"";if(s.startsWith("(")){const e=Ua(s,0);if(e<0)throw new Error(`${i}:${r}: invalid function-like #define ${a}`);const n=s.slice(1,e).trim(),o=0===n.length?[]:n.split(",").map(e=>e.trim());for(const e of o)if(!ya.test(e))throw new Error(`${i}:${r}: invalid macro parameter "${e}"`);return t.set(a,{name:a,parameters:o,body:Fa(s.slice(e+1)).trim()||"1"}),a}return t.set(a,{name:a,parameters:null,body:Fa(s).trim()||"1"}),a}function Ba(e){for(const t of e)if(!t.active)return!1;return!0}function Da(e,t,i,r){const n=e[e.length-1];if(!n)throw new Error(`${t}:${i}: #${r} without matching #if`);return n}function Ia(e,t,i){let r=e;for(let e=0;e<8;e+=1){const e=r;if(r=Ra(r,i),r=Ta(r,t),r===e)return r}return r}function Ta(e,t){let i=null,r=0;for(let n=0;n<e.length;){let a=e.charCodeAt(n);if(a>=65&&a<=90||a>=97&&a<=122||95===a){const s=n++;let o=a>=65&&a<=90;for(;n<e.length;)if(a=e.charCodeAt(n),a>=65&&a<=90)n++;else if(a>=97&&a<=122)o=!1,n++;else{if(!(a>=48&&a<=57||95===a))break;n++}if(!o)continue;const l=e.slice(s,n),c=t.get(l);null===c?.parameters&&(i??=[],i.push(e.slice(r,s),c.body),r=n)}else n++}return null===i?e:(i.push(e.slice(r)),i.join(""))}function Ra(e,t){if(0===t.size||!e.includes("("))return e;let i=e;for(const e of t.values())null!==e.parameters&&(i=Va(i,e));return i}function Va(e,t){let i="",r=0;for(;r<e.length;){const n=Ga(e,t.name,r);if(n<0){i+=e.slice(r);break}let a=n+t.name.length;for(;/\s/.test(e[a]??"");)a+=1;if("("!==e[a]){i+=e.slice(r,n+t.name.length),r=n+t.name.length;continue}const s=Ua(e,a);if(s<0){i+=e.slice(r);break}const o=La(e.slice(a+1,s));i+=e.slice(r,n),i+=za(t,o),r=s+1}return i}function Ga(e,t,i){let r=e.indexOf(t,i);for(;r>=0;){const i=r>0?e[r-1]:"",n=e[r+t.length]??"";if(!/[A-Za-z0-9_]/.test(i)&&!/[A-Za-z0-9_]/.test(n))return r;r=e.indexOf(t,r+t.length)}return-1}function za(e,t){let i=e.body;const r=e.parameters??[];for(let e=0;e<r.length;e+=1){const n=r[e],a=t[e]?.trim()??"";i=i.replace(new RegExp(`\\b${Oa(n)}\\b`,"g"),a)}return i}function La(e){const t=[];let i=0,r=0;for(let n=0;n<e.length;n+=1){const a=e[n];"("===a?i+=1:")"===a?i-=1:","===a&&0===i&&(t.push(e.slice(r,n)),r=n+1)}return(e.length>0||r>0)&&t.push(e.slice(r)),t}function Ua(e,t){let i=0;for(let r=t;r<e.length;r+=1){const t=e[r];if("("===t)i+=1;else if(")"===t&&(i-=1,0===i))return r}return-1}function Aa(e,t){const i=function(e){const t=[];let i=0;for(;i<e.length;){const r=e[i];if(/\s/.test(r)){i+=1;continue}const n=e.slice(i,i+2);if(["&&","||","==","!=","<=",">="].includes(n)){t.push({type:"operator",value:n}),i+=2;continue}if("!<>+-*/%".includes(r)){t.push({type:"operator",value:r}),i+=1;continue}if("("===r||")"===r){t.push({type:"paren",value:r}),i+=1;continue}const a=/^(?:0x[0-9A-Fa-f]+|\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)/.exec(e.slice(i));if(a){t.push({type:"number",value:a[0]}),i+=a[0].length;continue}const s=/^[A-Za-z_][A-Za-z0-9_]*/.exec(e.slice(i));s?(t.push({type:"identifier",value:s[0]}),i+=s[0].length):i+=1}return t}(Fa(e));return 0!==new ka(i,t).parseExpression()}var ka=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 i=t.startsWith("0x")?Number.parseInt(t,16):Number.parseFloat(t);return Number.isFinite(i)?i: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 Fa(e){const t=e.indexOf("//");return t>=0?e.slice(0,t):e}function Oa(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var Ea=/(?!\s*@invariant)\s+(?=(?:[A-Za-z_]\w*\s*:|vec4(?:\s*<\s*f32\s*>|f)\b))/y;function ja(e){return 32===e||9===e||10===e||13===e}var $a=class{passes=[];topologies=[];executionSnapshots=[];matchesTopology(e){if(e.passes.length!==this.passes.length)return!1;for(let t=0;t<this.passes.length;t+=1){const i=this.passes[t],r=e.passes[t];if(i.name!==r.name||!this.matchesResources(i.reads,r.reads)||!this.matchesResources(i.writes,r.writes)||!this.matchesResources(i.dependsOn,r.dependsOn))return!1}return!0}matchesResources(e,t){if((e?.length??0)!==t.length)return!1;for(let i=0;i<t.length;i+=1)if(e[i]!==t[i])return!1;return!0}addPass(e){this.passes.push(e)}async executeAsync(e,t){const i=this.createExecutionSnapshot(t),r=t?.end?performance.now():0;try{t?.begin?.(i,e);for(let r=0;r<i.length;r+=1){const n=i[r];t?.beforePass?.(n,r,e);const a=t?.afterPass?performance.now():0;n.prepare&&await n.prepare(e),n.execute(e),t?.afterPass?.(n,r,performance.now()-a,e)}t?.end?.(i,performance.now()-r,e)}finally{this.releaseExecutionSnapshot(i,t)}}execute(e,t){const i=this.createExecutionSnapshot(t),r=t?.end?performance.now():0;try{t?.begin?.(i,e);for(let r=0;r<i.length;r+=1){const n=i[r];t?.beforePass?.(n,r,e);const a=t?.afterPass?performance.now():0;n.execute(e),t?.afterPass?.(n,r,performance.now()-a,e)}t?.end?.(i,performance.now()-r,e)}finally{this.releaseExecutionSnapshot(i,t)}}reset(){this.passes.length=0}createExecutionSnapshot(e){const t=this.resolveExecutionOrder(),i=e?[]:this.executionSnapshots.pop()??[];i.length=t.length;for(let e=0;e<t.length;e+=1)i[e]=this.passes[t[e]];return i}releaseExecutionSnapshot(e,t){if(t)return;const i=e;i.fill(void 0),this.executionSnapshots.push(i)}resolveExecutionOrder(){for(let e=0;e<this.topologies.length;e+=1){const t=this.topologies[e];if(this.matchesTopology(t)){for(let t=e;t>0;t-=1)this.topologies[t]=this.topologies[t-1];return this.topologies[0]=t,t.executionOrder}}const e=new Map,t=new Map,i=new Map,r=new Map;for(let r=0;r<this.passes.length;r+=1){const n=this.passes[r];e.set(n.name,r),t.set(n.name,new Set(n.dependsOn??[])),i.set(n.name,new Set)}for(const e of this.passes){const i=t.get(e.name);for(const t of e.reads??[]){const n=r.get(t);n&&n!==e.name&&i.add(n)}for(const t of e.writes??[]){const n=r.get(t);n&&n!==e.name&&i.add(n),r.set(t,e.name)}}for(const[e,r]of t)for(const t of r){const r=i.get(t);if(!r)throw new Error(`RenderGraph dependency "${t}" for pass "${e}" is missing.`);r.add(e)}const n=Array.from(t.entries()).filter(([,e])=>0===e.size).map(([e])=>e),a=[];for(let r=0;r<n.length;r+=1){const s=n[r];a.push(e.get(s));for(const e of i.get(s)){const i=t.get(e);i.delete(s),0===i.size&&n.push(e)}}if(a.length!==this.passes.length)throw new Error("RenderGraph contains a dependency cycle.");const s={passes:this.passes.map(e=>({name:e.name,reads:Array.from(e.reads??[]),writes:Array.from(e.writes??[]),dependsOn:Array.from(e.dependsOn??[])})),executionOrder:a};return this.topologies.unshift(s),this.topologies.length>8&&this.topologies.pop(),a}};import{CubeUVReflectionMapping as Wa,HalfFloatType as Na,LinearFilter as _a,LinearSRGBColorSpace as Ha,RGBAFormat as qa,Texture as Ka}from"three";var Ya=[.125,.215,.35,.446,.526,.582],Za=20,Xa=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]]}(),Ja=class{constructor(e,t=20){this.context=e;const{device:i}=e,r=Math.max(1,Math.min(20,Math.floor(t)));this.maxBlurSamples=r,this.equirectBindGroupLayout=i.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}},{binding:1,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"unfilterable-float",viewDimension:"2d"}}]}),this.blurBindGroupLayout=i.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=Qa(i,this.equirectBindGroupLayout,is,"pmrem-equirectangular"),this.blurPipeline=Qa(i,this.blurBindGroupLayout,rs.replaceAll("PMREM_MAX_SAMPLES",String(r)),"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 i=2**Math.floor(Math.log2(Math.max(16,Math.floor(t.width/4)))),r=Math.floor(Math.log2(i)),n=function(e){const t=[];for(let i=e;i>=4;i-=1){const r=2**i;t.push({mip:i,size:r,sigma:i===e?0:1/r})}for(let e=0;e<Ya.length;e+=1)t.push({mip:4-e-1,size:16,sigma:Ya[e]});return t}(r),a=3*Math.max(i,112),s=4*i,{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=es(o,new Float32Array([t.width,t.height,i,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*i,2*i,0,1),g.setScissorRect(0,0,3*i,2*i),g.setPipeline(this.equirectPipeline),g.setBindGroup(0,m),g.draw(36),g.end();for(let e=1;e<n.length;e+=1){const t=n[e-1],i=n[e],o=Math.sqrt(i.sigma*i.sigma-t.sigma*t.sigma),l=Xa[(n.length-e-1)%Xa.length];this.encodeBlurPass({encoder:h,source:c,target:u,sampler:d,atlasWidth:a,atlasHeight:s,maxMip:r,inputLevel:t,outputLevel:i,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:r,inputLevel:i,outputLevel:i,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 v=new Ka;return v.image={width:a,height:s},v.name="PMREM.cubeUv",v.mapping=Wa,v.format=qa,v.type=Na,v.colorSpace=Ha,v.minFilter=_a,v.magFilter=_a,v.generateMipmaps=!1,v.needsUpdate=!0,this.context.registerTextureResource(v,{version:v.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:v,dispose:()=>{c.destroy(),v.dispose()}}}encodeBlurPass(e){const{encoder:t,source:i,target:r,sampler:n,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),v=u/g,x=Math.min(this.maxBlurSamples,1+Math.floor(3*v)),w=function(e,t){const i=new Float32Array(Za);let r=0;for(let n=0;n<Za;n+=1){const a=n/e,s=Math.exp(-a*a/2);i[n]=s,0===n?r+=s:n<t&&(r+=2*s)}for(let e=0;e<i.length;e+=1)i[e]/=r;return i}(v,x),b=es(this.context.device,function(e){const t=new ArrayBuffer(144),i=new DataView(t);return i.setFloat32(0,e.atlasWidth,!0),i.setFloat32(4,e.atlasHeight,!0),i.setFloat32(8,e.outputFaceSize,!0),i.setFloat32(12,e.inputMip,!0),i.setFloat32(16,e.dTheta,!0),i.setUint32(20,e.sampleCount,!0),i.setUint32(24,e.latitudinal?1:0,!0),i.setFloat32(28,e.maxMip,!0),i.setFloat32(32,e.poleAxis[0],!0),i.setFloat32(36,e.poleAxis[1],!0),i.setFloat32(40,e.poleAxis[2],!0),new Float32Array(t,48,Za).set(e.weights),new Float32Array(t)}({atlasWidth:a,atlasHeight:s,outputFaceSize:c.size,inputMip:l.mip,dTheta:g,sampleCount:x,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:i.createView()},{binding:2,resource:n}]}),S=3*c.size*Math.max(0,4-c.mip),C=4*(2**o-c.size),M=t.beginRenderPass({colorAttachments:[{view:r.createView(),loadOp:p?"clear":"load",storeOp:"store",clearValue:[0,0,0,1]}]});M.setViewport(S,C,3*c.size,2*c.size,0,1),M.setScissorRect(S,C,3*c.size,2*c.size),M.setPipeline(this.blurPipeline),M.setBindGroup(0,y),M.draw(36),M.end()}};function Qa(e,t,i,r){const n=e.createShaderModule({code:i,label:`${r}-shader`});return"function"==typeof n.getCompilationInfo&&n.getCompilationInfo().then(e=>{const t=e.messages.filter(e=>"error"===e.type);t.length>0&&console.error(`[WebGpuPMREMGenerator] ${r} WGSL compilation failed.`,t)}),e.createRenderPipeline({label:r,layout:e.createPipelineLayout({bindGroupLayouts:[t]}),vertex:{module:n,entryPoint:"vs"},fragment:{module:n,entryPoint:"fs",targets:[{format:"rgba16float"}]},primitive:{topology:"triangle-list"}})}function es(e,t){const i=e.createBuffer({size:t.byteLength,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST});return e.queue.writeBuffer(i,0,t.buffer,t.byteOffset,t.byteLength),i}var ts="\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",is=`${ts}\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`,rs=`${ts}\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`;var ns="\n let offset0 = vec2(-filterOffset.x, 0.0);\n let offset1 = vec2(filterOffset.x, 0.0);\n let offset2 = vec2(0.0, -filterOffset.y);\n let offset3 = vec2(0.0, filterOffset.y);";function as(e,t,i){if("basic"===e)return`\n let pixel = vec2<i32>(clamp(uv * dims, vec2(0.0), dims - vec2(1.0)));\n let closestDepth = textureLoad(${t}, pixel, i32(lightIndex), 0);\n let shadow = select(0.0, 1.0, depth <= closestDepth);`;const r=`\n let center = textureSampleCompareLevel(${t}, rendererShadowSampler, uv, i32(lightIndex), depth);`;if("pcf-2x2"===e)return r+"\n let shadow = center;";const n=[0,1,2,3].map(e=>`\n let uv${e} = clamp(uv + offset${e}, vec2(0.0), vec2(1.0));\n let tap${e} = textureSampleCompareLevel(${t}, rendererShadowSampler, uv${e}, i32(lightIndex),\n depth${i?` + dot(depthGradient, uv${e} - uv)`:""});`).join("\n");return`${r}\n let filterOffset = texel * radius;\n${"pcf-poisson-5tap"===e?"\n let seed = floor(uv * dims);\n let angle = fract(52.9829189 * fract(dot(seed, vec2(0.06711056, 0.00583715)))) * 6.28318530718;\n let rotation = mat2x2<f32>(vec2(cos(angle), sin(angle)), vec2(-sin(angle), cos(angle)));\n let offset0 = (rotation * vec2(-0.94201624, -0.39906216)) * filterOffset;\n let offset1 = (rotation * vec2(0.94558609, -0.76890725)) * filterOffset;\n let offset2 = (rotation * vec2(-0.09418410, -0.92938870)) * filterOffset;\n let offset3 = (rotation * vec2(0.34495938, 0.29387760)) * filterOffset;":ns}\n${n}\n let shadow = ${"renderer"===e?"(center * 4.0 + tap0 + tap1 + tap2 + tap3) * 0.125":"(center + tap0 + tap1 + tap2 + tap3) * 0.2"};`}function ss(e){return e.replace(/[^A-Za-z0-9_]/g,"_")}function os(e,t){const i=Object.entries(e.uniforms).map(([e,t])=>` ${ss(e)}: ${t.type},`).join("\n"),r=i?`\nstruct MaterialUniforms {\n${i}\n};\n\n@group(1) @binding(0) var<uniform> materialUniforms: MaterialUniforms;\n`:"",n=Object.entries(e.textures).map(([e,i],r)=>{const n=1+2*r,a=ss(e),s=$t(i,t);return[`@group(1) @binding(${n}) var ${a}Sampler: ${s.wgslSamplerType};`,`@group(1) @binding(${n+1}) var ${a}Texture: ${s.wgslTextureType};`].join("\n")}).join("\n"),a=1+2*Object.keys(e.textures).length;return`${r}\n${n}\n${Object.entries(e.storageBuffers).map(([e,t],i)=>{const r=ss(e);return`@group(1) @binding(${a+i}) var<storage, ${t.access??"read"}> ${r}: ${t.type};`}).join("\n")}`}function ls(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 rendererViewportSize() -> vec2<f32> {\n return ${"rendererCamera"===e?"rendererCamera.viewportAndTime.xy":"shadowCamera"===e?"shadowCamera.timeAndPadding.yz":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 cs(e){return e?"\nstruct RendererSkinningUniforms {\n bindMatrix: mat4x4<f32>,\n bindMatrixInverse: mat4x4<f32>,\n previousBindMatrix: mat4x4<f32>,\n previousBindMatrixInverse: 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@group(2) @binding(2) var<storage, read> rendererPreviousBoneMatrixColumns: array<vec4<f32>>;\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 rendererPreviousBoneMatrix(index: u32) -> mat4x4<f32> {\n let base = index * 4u;\n return mat4x4<f32>(\n rendererPreviousBoneMatrixColumns[base + 0u],\n rendererPreviousBoneMatrixColumns[base + 1u],\n rendererPreviousBoneMatrixColumns[base + 2u],\n rendererPreviousBoneMatrixColumns[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 rendererPreviousSkinPosition(position: vec3<f32>, skinIndex: vec4<u32>, skinWeight: vec4<f32>) -> vec3<f32> {\n let boundPosition = rendererSkinning.previousBindMatrix * 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 (rendererPreviousBoneMatrix(skinIndex.x) * boundPosition) * skinWeight.x +\n (rendererPreviousBoneMatrix(skinIndex.y) * boundPosition) * skinWeight.y +\n (rendererPreviousBoneMatrix(skinIndex.z) * boundPosition) * skinWeight.z +\n (rendererPreviousBoneMatrix(skinIndex.w) * boundPosition) * skinWeight.w;\n let fallbackWeight = max(0.0, 1.0 - weightSum);\n return (rendererSkinning.previousBindMatrixInverse * (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 us(e,t,i="packed",r=!0,n=!1,a){const s="particle"!==i&&!e.transparent&&!e.requiresLatePass(),o=!0===e.defines?.USE_SDFGI,l=e.defines?.SDFGI_CASCADE_COUNT,c=(u=e.defines).TSG_SHADOWMAP_TYPE_BASIC?"basic":u.TSG_SHADOWMAP_TYPE_PCF_2X2?"pcf-2x2":u.TSG_SHADOWMAP_TYPE_PCF_POISSON_5TAP?"pcf-poisson-5tap":u.TSG_SHADOWMAP_TYPE_PCF_5TAP?"pcf-5tap":"renderer";var u;const d=os(e,t),h=function(e){return Object.entries(e.getGraphTextureInputs()).map(([e,t],i)=>{const r=ss(e);return`@group(3) @binding(${2*i}) var ${r}Sampler: ${"comparison"===t.sampler?"sampler_comparison":"sampler"};\n@group(3) @binding(${2*i+1}) var ${r}Texture: ${"depth-2d"===t.dimension?"texture_depth_2d":"3d"===t.dimension?"texture_3d<f32>":"texture_2d<f32>"};`}).join("\n")}(e),p="packed-visible"===i,f="particle"===i?`\n@group(1) @binding(0) var<uniform> rendererCamera: RendererCameraUniforms;\n@group(1) @binding(1) var<uniform> rendererLights: RendererLightUniforms;\n@group(1) @binding(2) var rendererShadowSampler: sampler_comparison;\n@group(1) @binding(3) var rendererDirectionalShadowTexture: texture_depth_2d_array;\n@group(1) @binding(4) var rendererLinearClampSampler: sampler;\n@group(1) @binding(5) var rendererPointShadowTexture: texture_2d_array<f32>;\n@group(1) @binding(6) var rendererSpotShadowTexture: texture_depth_2d_array;\n@group(1) @binding(7) var rendererSpotLightMapAtlas: texture_2d<f32>;\n\nfn rendererBatchingId(instanceIndex: u32) -> u32 { return instanceIndex; }\nfn rendererInstanceModelMatrix(instanceIndex: u32) -> mat4x4<f32> {\n ${a??"_ = instanceIndex;\n return mat4x4<f32>(vec4(1.0, 0.0, 0.0, 0.0), vec4(0.0, 1.0, 0.0, 0.0), vec4(0.0, 0.0, 1.0, 0.0), vec4(0.0, 0.0, 0.0, 1.0));"}\n}\nfn rendererPreviousInstanceModelMatrix(instanceIndex: u32) -> mat4x4<f32> { return rendererInstanceModelMatrix(instanceIndex); }\nfn rendererMotionBlurParams(instanceIndex: u32) -> vec4<f32> { _ = instanceIndex; return vec4<f32>(1.0, 1.0, 0.0, 0.0); }\nfn rendererObjectColor(instanceIndex: u32) -> vec4<f32> { _ = instanceIndex; return vec4<f32>(1.0); }\n`:"instanced-direct"===i?"\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@group(0) @binding(10) var rendererSpotLightMapAtlas: texture_2d<f32>;\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 rendererPreviousInstanceModelMatrix(instanceIndex: u32) -> mat4x4<f32> {\n return rendererInstanceModelMatrix(instanceIndex);\n}\n\nfn rendererMotionBlurParams(instanceIndex: u32) -> vec4<f32> {\n _ = instanceIndex;\n return vec4<f32>(1.0, 1.0, 0.0, 0.0);\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 previousModel0: vec4<f32>,\n previousModel1: vec4<f32>,\n previousModel2: vec4<f32>,\n previousModel3: 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@group(0) @binding(9) var rendererSpotLightMapAtlas: texture_2d<f32>;\n${p?"@group(0) @binding(8) var<storage, read> rendererVisibleInstanceIndices: array<u32>;":""}\n\nfn rendererResolveInstanceIndex(instanceIndex: u32) -> u32 {\n ${p?"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 rendererPreviousInstanceModelMatrix(instanceIndex: u32) -> mat4x4<f32> {\n let instance = rendererInstances[rendererResolveInstanceIndex(instanceIndex)];\n return mat4x4<f32>(instance.previousModel0, instance.previousModel1, instance.previousModel2, instance.previousModel3);\n}\n\nfn rendererMotionBlurParams(instanceIndex: u32) -> vec4<f32> {\n return vec4<f32>(rendererInstances[rendererResolveInstanceIndex(instanceIndex)].batching.yzw, 0.0);\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`,m=r?`\nfn rendererDirectionalReceiverDepthGradient(matrix: mat4x4<f32>, worldNormal: vec3<f32>) -> vec2<f32> {\n // Directional shadow projections are orthographic. Transform the receiver\n // plane normal with the inverse transpose of the orthogonal matrix rows;\n // multiplying it as a direction would be wrong for unequal cascade extents.\n let x = vec3(matrix[0].x, matrix[1].x, matrix[2].x);\n let y = vec3(matrix[0].y, matrix[1].y, matrix[2].y);\n let z = vec3(matrix[0].z, matrix[1].z, matrix[2].z);\n let normal = vec3(\n dot(worldNormal, x) / max(dot(x, x), 1e-20),\n dot(worldNormal, y) / max(dot(y, y), 1e-20),\n dot(worldNormal, z) / max(dot(z, z), 1e-20)\n );\n // A plane parallel to the light has no usable depth gradient. Keep the\n // existing raster bias there instead of dividing by a near-zero value.\n if (abs(normal.z) <= length(normal) * 1e-4) {\n return vec2(0.0);\n }\n // NDC X/Y span two units; texture Y is inverted.\n return vec2(-2.0 * normal.x, 2.0 * normal.y) / normal.z;\n}\n\nfn rendererSampleDirectionalShadowOnPlane(lightIndex: u32, worldPosition: vec3<f32>, depthGradient: vec2<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 // Hardware PCF compares a 2x2 footprint with one reference depth. Cover\n // only that half-texel footprint; wider taps are corrected individually.\n let footprintBias = ${"basic"===c?"0.0":"dot(abs(depthGradient), texel * 0.5)"};\n let depth = ndc.z + rendererDirectionalShadowBiasForLight(lightIndex) - footprintBias;\n // Comparison-level sampling provides hardware 2x2 PCF and remains legal\n // inside non-uniform light loops. The default keeps the existing tent filter.\n${as(c,"rendererDirectionalShadowTexture",!0)}\n return mix(1.0, shadow, rendererDirectionalShadowIntensityForLight(lightIndex));\n}\n\nfn rendererSampleDirectionalShadowForLight(lightIndex: u32, worldPosition: vec3<f32>) -> f32 {\n return rendererSampleDirectionalShadowOnPlane(lightIndex, worldPosition, vec2(0.0));\n}\n\nfn rendererSampleDirectionalShadowForLightWithNormal(lightIndex: u32, worldPosition: vec3<f32>, worldNormal: vec3<f32>) -> f32 {\n let params = rendererLights.directionalShadowParams[lightIndex];\n let gradient = rendererDirectionalReceiverDepthGradient(rendererDirectionalShadowMatrixForLight(lightIndex), worldNormal);\n return rendererSampleDirectionalShadowOnPlane(lightIndex, worldPosition + normalize(worldNormal) * params.w, gradient);\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 // WebGPU's framebuffer/texture Y axis points down. The face-local value\n // above is NDC (Y up), so mirror Y just like the projected directional and\n // spot shadow paths do before sampling their render targets.\n let textureUv = uv * vec2(0.5, -0.5) + vec2(0.5, 0.5);\n return vec3<f32>(textureUv, f32(pointIndex * 6u + face));\n}\n\nfn rendererComparePointShadow(lightIndex: u32, direction: vec3<f32>, depth: f32) -> f32 {\n let uvLayer = rendererPointShadowUvLayer(direction, lightIndex);\n let dims = vec2<f32>(textureDimensions(rendererPointShadowTexture));\n let sampleUv = clamp(uvLayer.xy, vec2(0.0), vec2(1.0));\n let pixel = vec2<i32>(clamp(sampleUv * dims, vec2(0.0), dims - vec2(1.0)));\n let closestDepth = textureLoad(rendererPointShadowTexture, pixel, i32(round(uvLayer.z)), 0).r;\n return select(0.0, 1.0, depth <= closestDepth);\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 = rendererPointLightShadowRangeForLight(lightIndex);\n let toFragment = worldPosition - lightPosition;\n let distanceToLight = length(toFragment);\n if (distanceToLight >= range) {\n return 1.0;\n }\n let currentDepth = clamp(distanceToLight / max(range, 0.0001), 0.0, 1.0) - rendererPointShadowBiasForLight(lightIndex);\n${g=c,"pcf-5tap"!==g&&"pcf-poisson-5tap"!==g?" let shadow = rendererComparePointShadow(lightIndex, toFragment, currentDepth);":`\n let direction = normalize(toFragment);\n let up = select(vec3(1.0, 0.0, 0.0), vec3(0.0, 1.0, 0.0), abs(direction.y) < 0.999);\n let tangent = normalize(cross(up, direction));\n let bitangent = cross(direction, tangent);\n let dims = vec2<f32>(textureDimensions(rendererPointShadowTexture));\n let uv = rendererPointShadowUvLayer(direction, lightIndex).xy;\n let filterOffset = max(rendererLights.pointShadowParams2[lightIndex].x, 0.0) / max(dims, vec2(1.0));\n${"pcf-poisson-5tap"===g?"\n let seed = floor(uv * dims);\n let angle = fract(52.9829189 * fract(dot(seed, vec2(0.06711056, 0.00583715)))) * 6.28318530718;\n let rotation = mat2x2<f32>(vec2(cos(angle), sin(angle)), vec2(-sin(angle), cos(angle)));\n let offset0 = (rotation * vec2(-0.94201624, -0.39906216)) * filterOffset;\n let offset1 = (rotation * vec2(0.94558609, -0.76890725)) * filterOffset;\n let offset2 = (rotation * vec2(-0.09418410, -0.92938870)) * filterOffset;\n let offset3 = (rotation * vec2(0.34495938, 0.29387760)) * filterOffset;":ns}\n let center = rendererComparePointShadow(lightIndex, direction, currentDepth);\n${[0,1,2,3].map(e=>`\n let tap${e} = rendererComparePointShadow(lightIndex, direction + tangent * offset${e}.x + bitangent * offset${e}.y, currentDepth);`).join("\n")}\n let shadow = (center + tap0 + tap1 + tap2 + tap3) * 0.2;`}\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, ${"renderer"===c?"1.0":"0.0"});\n let depth = ndc.z - rendererSpotShadowBiasForLight(lightIndex);\n${"renderer"===c?"\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 let shadow = sum / 9.0;\n":as(c,"rendererSpotShadowTexture",!1)}\n return mix(1.0, shadow, 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";var g;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 motionCurrentViewProj: mat4x4<f32>,\n motionPreviousViewProj: mat4x4<f32>,\n motionParams: 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>, 64>,\n pointColorIntensities: array<vec4<f32>, 64>,\n pointParams: array<vec4<f32>, 64>,\n pointShadowParams: array<vec4<f32>, 64>,\n pointShadowParams2: array<vec4<f32>, 64>,\n spotPositionRanges: array<vec4<f32>, 64>,\n spotDirectionCones: array<vec4<f32>, 64>,\n spotColorIntensities: array<vec4<f32>, 64>,\n spotShadowParams: array<vec4<f32>, 64>,\n spotShadowParams2: array<vec4<f32>, 64>,\n spotParams: array<vec4<f32>, 64>,\n spotShadowMatrices: array<mat4x4<f32>, 64>,\n csmCascadeRanges: array<vec4<f32>, 4>,\n hemisphereSkyColorIntensity: vec4<f32>,\n hemisphereGroundColorIntensity: vec4<f32>,\n hemisphereDirection: vec4<f32>,\n};\n\n${f}\n\n${s?"@group(0) @binding(11) var rendererPointLightTiles: texture_2d<u32>;":""}\n\nfn rendererFullPointLightMask() -> vec2<u32> {\n let count = min(rendererPointLightCount(), 64u);\n // Shifts by 32 wrap to zero in WGSL; explicitly handle empty words.\n let low = 0xffffffffu >> (32u - min(count, 32u));\n let high = 0xffffffffu >> (32u - min(count - min(count, 32u), 32u));\n return vec2<u32>(select(low, 0u, count == 0u), select(high, 0u, count <= 32u));\n}\n\nfn rendererPointLightMask(pixel: vec2<f32>) -> vec2<u32> {\n ${s?"\n if (rendererCamera.nearFar.w > 0.5 && rendererPointLightCount() > 0u) {\n // Tile boundaries align to derivative quads; clamp edge helpers.\n let tile = min(vec2<u32>(max(pixel, vec2<f32>(0.0))) / 16u, textureDimensions(rendererPointLightTiles) - 1u);\n return textureLoad(rendererPointLightTiles, vec2<i32>(tile), 0).xy;\n }":"_ = pixel;"}\n return rendererFullPointLightMask();\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 rendererMotionCurrentClip(localPosition: vec3<f32>, instanceIndex: u32) -> vec4<f32> {\n let world = rendererInstanceModelMatrix(instanceIndex) * vec4(localPosition, 1.0);\n return rendererCamera.motionCurrentViewProj * world;\n}\n\nfn rendererMotionPreviousClip(\n currentLocalPosition: vec3<f32>,\n previousLocalPosition: vec3<f32>,\n instanceIndex: u32\n) -> vec4<f32> {\n let params = rendererMotionBlurParams(instanceIndex);\n let useObjectHistory = params.x >= 1.5 && params.z >= 0.5;\n var previousModel = rendererInstanceModelMatrix(instanceIndex);\n var previousLocal = currentLocalPosition;\n if (useObjectHistory) {\n previousModel = rendererPreviousInstanceModelMatrix(instanceIndex);\n previousLocal = previousLocalPosition;\n }\n return rendererCamera.motionPreviousViewProj * previousModel * vec4(previousLocal, 1.0);\n}\n\nfn rendererWorldNormal(localNormal: vec3<f32>, instanceIndex: u32) -> vec3<f32> {\n return normalize(rendererInstanceNormalMatrix(instanceIndex) * localNormal);\n}\n\n${ls("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\n// Probe GI can be interpolated from vertices without exposing the fragment-only\n// direct/ambient light uniform block to the vertex stage.\nfn rendererDiffuseGIAt(worldPosition: vec3<f32>, worldNormal: vec3<f32>) -> vec3<f32> {\n return ${o?"rendererSdfgiIrradiance(worldPosition, worldNormal)":"vec3<f32>(0.0)"};\n}\n\nfn rendererIndirectDiffuseAt(worldPosition: vec3<f32>, worldNormal: vec3<f32>) -> vec3<f32> {\n return rendererIndirectDiffuse(worldNormal) + rendererDiffuseGIAt(worldPosition, worldNormal);\n}\n\n${o?2===l||3===l?function(e){let t="",i="var result = vec3<f32>(0.0);\nvar remaining = 1.0;\n";for(let r=0;r<e;r++){const e=0===r?"sdfgiField":`sdfgiField${r}`;t+=ee.replace(/\bsdfgiField\b/g,e).replace(/rendererSdfgiSample/g,`rendererSdfgiSample${r}`).replace(/rendererSdfgiIrradiance/g,`rendererSdfgiIrradiance${r}`),t+=`\nfn rendererSdfgiBankCoverage${r}(position: vec3<f32>, normal: vec3<f32>, bank: u32) -> f32 {\n let origin = ${e}[bank];\n let settings = ${e}[bank + 1u];\n if (settings.z <= 0.0 || ${e}[bank + 2u].x < 0.5) { return 0.0; }\n let local = (position + normalize(normal) * settings.w - origin.xyz - vec3<f32>(origin.w * 2.0)) / settings.x;\n let edge = min(local, vec3<f32>(settings.y - 1.0) - local);\n return smoothstep(0.0, 1.0, min(edge.x, min(edge.y, edge.z)));\n}\nfn rendererSdfgiCoverage${r}(position: vec3<f32>, normal: vec3<f32>) -> f32 {\n if (${e}[1].z <= 0.0 || ${e}[2].x < 0.5) { return 0.0; }\n let blend = ${e}[2].y;\n var previous = 0.0;\n if (blend < 1.0 && ${e}[2].z > 0.5) {\n previous = rendererSdfgiBankCoverage${r}(position, normal, u32(${e}[3].x));\n }\n return mix(previous, rendererSdfgiBankCoverage${r}(position, normal, 0u), blend);\n}\n`,i+=`\n if (remaining > 0.0) {\n let coverage = rendererSdfgiCoverage${r}(worldPosition, worldNormal);\n if (coverage > 0.0) {\n result += rendererSdfgiIrradiance${r}(worldPosition, worldNormal) * remaining;\n remaining *= 1.0 - coverage;\n }\n }\n`}return t+`\nfn rendererSdfgiIrradiance(worldPosition: vec3<f32>, worldNormal: vec3<f32>) -> vec3<f32> {\n ${i}\n return result;\n}\n`}(l):ee:""}\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.pointParams[lightIndex].x;\n}\n\nfn rendererPointLightShadowRangeForLight(lightIndex: u32) -> f32 {\n return rendererLights.pointPositionRanges[lightIndex].w;\n}\n\nfn rendererPointLightDecayForLight(lightIndex: u32) -> f32 {\n return rendererLights.pointParams[lightIndex].y;\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 rendererPointLightDecayForLight(lightIndex)\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\nfn rendererSampleSpotLightMapForLight(lightIndex: u32, worldPosition: vec3<f32>) -> vec3<f32> {\n if (lightIndex >= rendererSpotLightCount() || rendererLights.spotParams[lightIndex].w < 0.5) {\n return vec3<f32>(1.0);\n }\n let clip = rendererSpotShadowMatrixForLight(lightIndex) * vec4<f32>(worldPosition, 1.0);\n if (clip.w <= 0.0) { return vec3<f32>(1.0); }\n let ndc = clip.xyz / clip.w;\n if (any(ndc < vec3<f32>(-1.0, -1.0, 0.0)) || any(ndc > vec3<f32>(1.0))) {\n return vec3<f32>(1.0);\n }\n let projectedUv = ndc.xy * vec2<f32>(0.5, -0.5) + vec2<f32>(0.5);\n let cell = vec2<f32>(f32(lightIndex % 8u), f32(lightIndex / 8u));\n let cellUv = clamp(projectedUv, vec2<f32>(0.0), vec2<f32>(1.0)) * (255.0 / 256.0) + vec2<f32>(0.5 / 256.0);\n let atlasUv = (cell + cellUv) / 8.0;\n return textureSampleLevel(rendererSpotLightMapAtlas, rendererLinearClampSampler, atlasUv, 0.0).rgb;\n}\n\n${m}\n${cs(n)}\n${d}\n${h}\n`}function ds(e=!0,t){return us({uniforms:{},textures:{},storageBuffers:{},defines:{},getGraphTextureInputs:()=>({})},void 0,"particle",e,!1,t)}function hs(e,t,i,r="packed",n=!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"===r?"@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"===r?"@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=os(e,i),o="instanced-direct"===r?"\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 previousModel0: vec4<f32>,\n previousModel1: vec4<f32>,\n previousModel2: vec4<f32>,\n previousModel3: 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",l="packed-visible"===r;return`\n${a}\n${l?`@group(0) @binding(${"shadow"===t?2:3}) var<storage, read> rendererVisibleInstanceIndices: array<u32>;\nfn rendererResolveInstanceIndex(instanceIndex: u32) -> u32 { return rendererVisibleInstanceIndices[instanceIndex]; }`:""}\n\n${l?o.replaceAll("rendererInstances[instanceIndex]","rendererInstances[rendererResolveInstanceIndex(instanceIndex)]"):o}\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${ls("camera"===t?"rendererCamera":"shadowCamera")}\n${cs(n)}\n${s}\n`}var ps=class{constructor(e,t,i={}){this.name=e,this.callback=t,this.reads=i.reads,this.writes=i.writes,this.dependsOn=i.dependsOn}name;callback;reads;writes;dependsOn;execute(e){this.callback(e)}},fs=class{constructor(e){this.device=e}device;timestamps=[];visibility=[];disposed=!1;acquire(e,t){if(this.disposed)return null;const i=t?this.timestamps:this.visibility;let r=i.find(t=>!t.busy&&t.capacity>=e);if(!r){const n=i.findIndex(e=>!e.busy);if(n<0&&i.length>=3)return null;n>=0&&this.destroy(i[n]);const a=Math.max(8,t?8*e:e);r={busy:!1,capacity:e,readBuffer:this.device.createBuffer({label:"renderer-profile-read",size:a,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ})},t&&(r.querySet=this.device.createQuerySet({label:"renderer-profile-timestamps",type:"timestamp",count:e}),r.resolveBuffer=this.device.createBuffer({label:"renderer-profile-resolve",size:a,usage:GPUBufferUsage.QUERY_RESOLVE|GPUBufferUsage.COPY_SRC})),n>=0?i[n]=r:i.push(r)}return r.busy=!0,r}release(e,t){if(this.disposed)return;if(t)return void(e.busy=!1);this.destroy(e);const i=e.querySet?this.timestamps:this.visibility,r=i.indexOf(e);r>=0&&i.splice(r,1)}dispose(){this.disposed=!0;for(const e of this.timestamps)this.destroy(e);for(const e of this.visibility)this.destroy(e);this.timestamps.length=this.visibility.length=0}destroy(e){e.readBuffer.destroy(),e.querySet?.destroy(),e.resolveBuffer?.destroy()}},ms=new WeakMap,gs=new WeakMap,vs=new WeakSet;function xs(e){ms.get(e)?.dispose(),ms.delete(e)}function ws(e,t){vs.has(t)||((!e.latestFrameProfile||t.profile.frameIndex>=e.latestFrameProfile.frameIndex)&&(e.latestFrameProfile=Ss(t.profile)),(t.pendingGpuRead||t.pendingVisibilityRead)&&Promise.all([t.pendingGpuRead?bs(t.profile,t.pendingGpuRead):Promise.resolve(),t.pendingVisibilityRead?ys(t.profile,t.pendingVisibilityRead):Promise.resolve()]).then(()=>{if(gs.get(t)!==ms.get(e))return;const i=Ss(t.profile);(!e.latestFrameProfile||i.frameIndex>=e.latestFrameProfile.frameIndex)&&(e.latestFrameProfile=i),(!e.latestCompletedFrameProfile||i.frameIndex>=e.latestCompletedFrameProfile.frameIndex)&&(e.latestCompletedFrameProfile=i)}))}async function bs(e,t){let i=!1;try{await t.readBuffer.mapAsync(GPUMapMode.READ);const r=t.readBuffer.getMappedRange(),n=new BigUint64Array(r);let a=0;const s=t.profile.passes.map((e,t)=>{const i=Number(n[2*t]??0n),r=Number(n[2*t+1]??0n),s=Math.max(0,r-i)/1e6;return a+=s,{...e,gpuTimeMs:s}});e.gpuTimeMs=a,e.gpuProfilingReason=null,e.passes=s,i=!0}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.release?t.release(i):(t.querySet.destroy(),t.resolveBuffer.destroy(),t.readBuffer.destroy())}}async function ys(e,t){let i=!1;try{await t.readBuffer.mapAsync(GPUMapMode.READ);const r=new Uint32Array(t.readBuffer.getMappedRange());let n=0,a=0,s=0,o=0,l=0;for(const e of t.regions){let t=0;const i=e.byteOffset/Uint32Array.BYTES_PER_ELEMENT;for(let n=0;n<e.drawCount;n+=1)t+=r[i+5*n+1]??0,l+=Math.floor((r[i+5*n]??0)/3)*(r[i+5*n+1]??0);"dynamic"===e.kind?(n+=e.totalInstances,a+=t):(s+=e.totalInstances,o+=t)}const c=n+s,u=a+o;e.visibility={visibleTriangles:l,totalInstances:c,visibleInstances:u,culledInstances:Math.max(0,c-u),dynamicTotalInstances:n,dynamicVisibleInstances:a,staticTotalInstances:s,staticVisibleInstances:o},i=!0}catch{e.visibility=null}finally{"mapped"===t.readBuffer.mapState&&t.readBuffer.unmap(),t.release?t.release(i):t.readBuffer.destroy()}}function Ss(e){return{...e,cpuPhases:{...e.cpuPhases},passes:e.passes.map(e=>({...e})),visibility:e.visibility?{...e.visibility}:null}}import{Frustum as Cs,Matrix4 as Ms,Sphere as Ps}from"three";function Bs(e,t,i,r,n,a,s,o){const l=e[t+3];if(n>0&&!(l*r>=n*(s?.85:1.15)))return!1;const c=e[t],u=e[t+1],d=e[t+2];if(a>0){const e=c-o.x,t=u-o.y,i=d-o.z,r=a+l;if(!(e*e+t*t+i*i<=r*r))return!1}for(let e=0;e<6;e++){const t=i.planes[e],r=t.normal;if(r.x*c+r.y*u+r.z*d+t.constant<-l)return!1}return!0}var Ds=class{draws=[];directDraws=[];bundles=[];signatures=[];count=-1;bindGroup=null;pipeline=null;invalidation=null;matches(e,t,i){let r=this.count===this.draws.length&&this.bindGroup===e&&this.pipeline===t&&this.invalidation===i;for(let e=0;e<this.draws.length;e++){const t=this.draws[e],i=t.geometryResource,n=this.signatures[e];n&&n.geometry===t.geometryKey&&n.position===i.position&&n.index===i.index&&n.binding===t.residentInstanceBinding&&n.start===t.start&&n.count===t.count&&n.firstInstance===t.instanceStart&&n.instances===t.instanceCount||(r=!1)}return r}store(e,t,i,r){for(let e=0;e<this.draws.length;e++){const t=this.draws[e],i=t.geometryResource;let r=this.signatures[e];r||(r={},this.signatures[e]=r),r.geometry=t.geometryKey,r.position=i.position,r.index=i.index,r.binding=t.residentInstanceBinding,r.start=t.start,r.count=t.count,r.firstInstance=t.instanceStart,r.instances=t.instanceCount}this.count=this.draws.length,this.bindGroup=t,this.pipeline=i,this.invalidation=r,e?this.bundles[0]=e:this.bundles.length=0}},Is=class{valid=!1;matrix=new Float64Array(16);policies=new Float64Array(0);size=0;x=0;y=0;z=0;update(e,t,i,r){let n=!this.valid||this.size!==t;for(let t=0;t<16;t++)this.matrix[t]!==e.elements[t]&&(n=!0);this.policies.length!==3*i.length&&(this.policies=new Float64Array(3*i.length),n=!0);let a=!1;for(let e=0;e<i.length;e++){const t=i[e],r=t.detailCulling,s=3*e,o=t.castShadow?1:0;this.policies[s]===r.shadowMinScreenSize&&this.policies[s+1]===r.shadowMaxDistance&&this.policies[s+2]===o||(n=!0),this.policies[s]=r.shadowMinScreenSize,this.policies[s+1]=r.shadowMaxDistance,this.policies[s+2]=o,a||=0!==o&&r.shadowMaxDistance>0}return!a||this.x===r.x&&this.y===r.y&&this.z===r.z||(n=!0),this.matrix.set(e.elements),this.size=t,this.x=r.x,this.y=r.y,this.z=r.z,this.valid=!0,n}},Ts=new WeakMap;function Rs(e){if(e.transparent||e.polygonOffset)return!0;let t=Ts.get(e);return void 0===t&&(t=e.alphaTest>0||/\bdiscard\b/.test(e.fragmentShader),Ts.set(e,t)),t}function Vs(e){for(const t of e)if(t.customDepthMaterial||null!==t.skinning||t.material.vertexAttributes.some(e=>"instance"===e.stepMode)||null===t.material.depthVertexShader&&(Rs(t.material)||t.wireframe||!t.material.primitiveTopology.startsWith("triangle")))return!1;return!0}var Gs=new WeakMap,zs={drawCallCount:0,triangleCount:0},Ls=new Cs,Us=new Ms,As=new Cs,ks=new Ms,Fs=new m,Os=new Ps,Es=new WeakMap,js=new WeakMap,$s=F.clone();function Ws(e,t,i,r,n=0){let a=Es.get(e);a||(a=new WeakMap,Es.set(e,a));let s=a.get(t);s||(s={pool:[],draws:[],key:new Is},a.set(t,s));if(!s.key.update(ks,i,e.draws,$s)&&s.excluded===r&&s.exclusionVersion===n)return this.directionalShadowSubmissionStats.selectionHits++,s.draws;s.excluded=r,s.exclusionVersion=n,this.directionalShadowSubmissionStats.selections++;const o=s.pool,l=s.draws;l.length=0;const c=e.instanceVisibilityResource.metadata,u=Math.max(Math.abs(t.projectionMatrix.elements[0])*i,Math.abs(t.projectionMatrix.elements[5])*i);let d=js.get(e);d||(d=new WeakMap,js.set(e,d));let h=d.get(t);h||(h=new Uint8Array(e.instanceCount),d.set(t,h));let p=0;for(const t of e.shadowChunks)if(Os.center.copy(t.boundsCenter),Os.radius=t.boundsRadius,As.intersectsSphere(Os))for(const i of t.drawIndices){if(r?.[i])continue;const t=e.draws[i];if(!t.castShadow)continue;const n=t.detailCulling;let a=-1;const s=t.instanceStart+t.instanceCount;for(let e=t.instanceStart;e<=s;e++){let i=!1;if(e<s){i=Bs(c,8*e,As,u,n.shadowMinScreenSize,n.shadowMaxDistance,0!==h[e],$s),h[e]=i?1:0}if(i&&a<0&&(a=e),!i&&a>=0){let i=o[p];i?i.source!==t&&(Object.assign(i.draw,t),i.source=t):(i={source:t,draw:{...t}},o[p]=i);const r=i.draw;r.instanceStart=a,r.instanceCount=e-a,l.push(r),p++,a=-1}}}return l}function Ns(e){return e.usesBatching}function _s(e){return!e.wireframe&&e.material.primitiveTopology.startsWith("triangle")}function Hs(e,t){return"pointShadow"===t?null!==e.material.pointShadowVertexShader&&null!==e.material.pointShadowFragmentShader:null!==e.material.depthVertexShader}function qs(e,t){if(!this.state.visibilityKernel||!this.state.drawMetadataResource||0===this.state.drawMetadataResource.count)return;const i=e.beginComputePass({label:"renderer-visibility-pass"});i.setPipeline(this.state.visibilityKernel.pipeline),i.setBindGroup(0,t),i.dispatchWorkgroups(Math.ceil(this.state.drawMetadataResource.count/64)),i.end()}function Ks(e){return e.instanceVisibilityResource.instanceCount<=64&&e.drawMetadataResource.count<=64}var Ys=new WeakMap;function Zs(e,t){if(!(this.state.staticVisibilityClearKernel&&this.state.staticVisibilityCullKernel&&this.state.staticVisibilityIndirectBuildKernel&&this.getHiZOcclusionCullingActive()&&this.state.device))return;let i=Ys.get(this);i||(i=[],Ys.set(this,i)),i.length=0;for(const e of this.getCameraStaticDrawSets()){if(!e.publicSet.enabled||!this.isStaticDrawSetCameraVisible(e)||e.cpuVisibility||0===e.drawMetadataResource.count)continue;if("postpass"===t&&e.lastPreVisibilityFrameToken!==this.staticFrameToken)continue;if(!this.state.device)continue;const r="prepass"===t?e.visibilityParamsUpload:e.postVisibilityParamsUpload,n="prepass"===t?e.visibilityParamsBuffer:e.postVisibilityParamsBuffer,a=("prepass"===t?this.state.temporalHiZHistoryValid?3:0:5)|(Ks(e)?8:0);r[1]===this.state.hizMipCount&&r[3]===a||(r[1]=this.state.hizMipCount,r[3]=a,this.state.device.queue.writeBuffer(n,0,kr(r),0,4));this.getOrCreateStaticVisibilityBindGroup(e,t)&&("prepass"!==t||Ks(e)||e.visibilityClearBindGroup&&e.visibilityIndirectBuildBindGroup&&e.postVisibilityIndirectBuildBindGroup||(e.visibilityClearBindGroup=this.state.staticVisibilityClearKernel.createBindGroup(this.state.device,[{binding:0,resource:{buffer:e.visibilityParamsBuffer}},{binding:1,resource:{buffer:e.instanceVisibilityResource.visibleCountsBuffer}},{binding:2,resource:{buffer:e.instanceVisibilityResource.postVisibleCountsBuffer}},{binding:3,resource:{buffer:e.instanceVisibilityResource.visibleInstanceMaskBuffer}}],`${e.label}-visibility-clear-bind-group`),e.visibilityIndirectBuildBindGroup=this.state.staticVisibilityIndirectBuildKernel.createBindGroup(this.state.device,[{binding:0,resource:{buffer:e.visibilityParamsBuffer}},{binding:1,resource:{buffer:e.instanceVisibilityResource.visibleCountsBuffer}},{binding:2,resource:{buffer:e.instanceVisibilityResource.postVisibleCountsBuffer}},{binding:3,resource:{buffer:e.drawMetadataResource.indirectBuffer}},{binding:4,resource:{buffer:e.drawMetadataResource.postIndirectBuffer}}],`${e.label}-visibility-indirect-build-bind-group`),e.postVisibilityIndirectBuildBindGroup=this.state.staticVisibilityIndirectBuildKernel.createBindGroup(this.state.device,[{binding:0,resource:{buffer:e.postVisibilityParamsBuffer}},{binding:1,resource:{buffer:e.instanceVisibilityResource.visibleCountsBuffer}},{binding:2,resource:{buffer:e.instanceVisibilityResource.postVisibleCountsBuffer}},{binding:3,resource:{buffer:e.drawMetadataResource.indirectBuffer}},{binding:4,resource:{buffer:e.drawMetadataResource.postIndirectBuffer}}],`${e.label}-post-visibility-indirect-build-bind-group`)),i.push(e))}if(0===i.length)return;let r=!1;for(const e of i)if(!Ks(e)){r=!0;break}if("prepass"===t&&r){const t=e.beginComputePass({label:"static-temporal-visibility-clear-pass"});t.setPipeline(this.state.staticVisibilityClearKernel.pipeline);for(const e of i)Ks(e)||(t.setBindGroup(0,e.visibilityClearBindGroup),t.dispatchWorkgroups(Math.ceil(Math.max(e.drawMetadataResource.count,e.instanceVisibilityResource.instanceCount)/64)));t.end()}const n=e.beginComputePass({label:`static-temporal-visibility-${t}-cull-pass`});n.setPipeline(this.state.staticVisibilityCullKernel.pipeline);for(const e of i)n.setBindGroup(0,"prepass"===t?e.visibilityBindGroup:e.postVisibilityBindGroup),n.dispatchWorkgroups(Math.ceil(e.instanceVisibilityResource.instanceCount/64));n.end();const a=r?e.beginComputePass({label:`static-temporal-visibility-${t}-indirect-build-pass`}):null;a?.setPipeline(this.state.staticVisibilityIndirectBuildKernel.pipeline);for(const e of i)!Ks(e)&&a&&(a.setBindGroup(0,"prepass"===t?e.visibilityIndirectBuildBindGroup:e.postVisibilityIndirectBuildBindGroup),a.dispatchWorkgroups(Math.ceil(e.drawMetadataResource.count/64))),"prepass"===t?e.lastPreVisibilityFrameToken=this.staticFrameToken:e.lastVisibilityFrameToken=this.staticFrameToken;a?.end(),i.length=0}function Xs(e,t){if(!(this.state.device&&this.state.staticVisibilityCullKernel&&this.state.hizTexture&&this.state.temporalVisibilityBuffer&&this.state.nearestClampSampler))return null;const i="prepass"===t?e.visibilityBindGroup:e.postVisibilityBindGroup;if(i&&e.visibilityBindGroupHizVersion===this.hizResourceVersion)return i;const r=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}},{binding:10,resource:{buffer:e.drawMetadataResource.indirectBuffer}},{binding:11,resource:{buffer:e.drawMetadataResource.postIndirectBuffer}}],`${e.label}-temporal-visibility-${t}-bind-group`);return"prepass"===t?e.visibilityBindGroup=r:e.postVisibilityBindGroup=r,e.visibilityBindGroupHizVersion=this.hizResourceVersion,r}function Js(e,t,i,r){if(!this.state.shadowDepthPipeline||0===this.state.directionalShadowLayerViews.length)return void this.clearDirectionalShadow(e);this.directionalShadowGpu.beginFrame();let n=!1;i.camera.getWorldPosition($s);for(let t=0;t<i.lights.directionals.length;t+=1){const a=i.lights.directionals[t],s=this.state.directionalShadowLayerViews[t];if(!a.castShadow||!s)continue;n=!0;const o=this.directionalShadowCameras[t];if(!(this.directionalShadowScheduler.updateMask&1<<t)){r.directionalShadowReused=(r.directionalShadowReused??0)+1;continue}r.directionalShadowUpdates=(r.directionalShadowUpdates??0)+1,r.directionalShadowUpdateMask=(r.directionalShadowUpdateMask??0)|1<<t,this.directionalShadowScheduler.forcedMask&1<<t&&(r.directionalShadowForced=(r.directionalShadowForced??0)+1),As.setFromProjectionMatrix(ks.multiplyMatrices(o.projectionMatrix,o.matrixWorldInverse)),Fs.update(ks);const l=this.queryStaticShadowResources(As),c=this.getShadowCameraBuffer(t);this.writeShadowCameraBuffer(tn(o,this.shadowViewProjScratch),0,0,0,1,c,o);const u=this.getSharedShadowBindGroupForCameraBuffer(c);let d;this.directionalShadowGpu.prepareCascade(As,o,$s,this.state.directionalShadowTextureSize);for(const i of l)i.publicSet.enabled&&0!==i.draws.length&&"late"!==i.drawStage&&(Os.center.copy(i.spatialBounds.boundsCenter),Os.radius=i.spatialBounds.boundsRadius,As.intersectsSphere(Os)&&(!d&&this.directionalShadowGpu.enabled&&this.directionalShadowGpu.available&&(d=e.beginComputePass({label:`renderer-directional-shadow-selection-${t}`})),this.directionalShadowGpu.prepare(this,e,i,c,d)));d?.end();const h=e.beginRenderPass({label:`renderer-directional-shadow-pass-${t}`,colorAttachments:[],depthStencilAttachment:{view:s,depthClearValue:1,depthLoadOp:"clear",depthStoreOp:"store"}});h.setPipeline(this.state.shadowDepthPipeline),h.setBindGroup(0,u),this.drawDepthLike(h,i.shadowDraws??[...i.gpuOpaqueDraws,...i.directOpaqueDraws],r,{fallbackPipeline:this.state.shadowDepthPipeline,fallbackPipelineDirect:this.state.shadowDepthPipelineDirect,fallbackSkinnedPipeline:this.state.skinnedShadowDepthPipeline,fallbackBindGroup:u,shadowCameraBuffer:c,passKind:"directionalShadow",customDepthMode:"use"});for(const e of l){if(!e.publicSet.enabled||0===e.draws.length||"late"===e.drawStage)continue;if(Os.center.copy(e.spatialBounds.boundsCenter),Os.radius=e.spatialBounds.boundsRadius,!As.intersectsSphere(Os))continue;const t=this.directionalShadowGpu.submit(h,e,c,r)?this.directionalShadowGpu.sets.get(e):void 0;t?.eligibleDrawCount!==e.draws.length&&Qs.call(this,h,e,o,Ws.call(this,e,o,this.state.directionalShadowTextureSize,t?.eligibility,t?.eligibilityVersion),u,c,r)}h.end(),this.directionalShadowScheduler.commit(t)}n||this.clearDirectionalShadow(e)}function Qs(e,t,i,r,n,a,s){let o=Gs.get(t);o||(o=new WeakMap,Gs.set(t,o));let l=o.get(i);l||(l=new Ds,o.set(i,l)),l.draws.length=0,l.directDraws.length=0;let c=0;for(const e of r)e.customDepthMaterial||Hs(e,"directionalShadow")||e.hasRenderCallbacks||e.skinning||!e.indexed||e.wireframe||!_s(e)||"packed"!==this.getDrawInstanceAccessMode(e)?l.directDraws.push(e):(l.draws.push(e),c+=un(e));if(l.draws.length>0){const i=this.state.shadowDepthPipeline,r=this.resolveShadowBindGroupForDraw(l.draws[0],n,a),o=l.matches(r,i,t.shadowBundles);if(o)if(0===l.bundles.length){const e=this.state.device.createRenderBundleEncoder({label:`${t.label}-directional-selected-runs`,colorFormats:[],depthStencilFormat:"depth32float",sampleCount:1});zs.drawCallCount=0,zs.triangleCount=0,Mo.call(this,e,l.draws,zs,{fallbackPipeline:i,fallbackBindGroup:n,shadowCameraBuffer:a,passKind:"directionalShadow",customDepthMode:"ignore",preculled:!0}),l.store(e.finish(),r,i,t.shadowBundles),this.directionalShadowSubmissionStats.bundleBuilds++}else this.directionalShadowSubmissionStats.bundleHits++;else l.store(null,r,i,t.shadowBundles),zs.drawCallCount=0,zs.triangleCount=0,Mo.call(this,e,l.draws,zs,{fallbackPipeline:i,fallbackBindGroup:n,shadowCameraBuffer:a,passKind:"directionalShadow",customDepthMode:"ignore",preculled:!0});o&&e.executeBundles(l.bundles),s.drawCallCount+=l.draws.length,s.triangleCount+=c}l.directDraws.length>0&&this.drawDepthLike(e,l.directDraws,s,{fallbackPipeline:this.state.shadowDepthPipeline,fallbackPipelineDirect:this.state.shadowDepthPipelineDirect,fallbackBindGroup:n,shadowCameraBuffer:a,passKind:"directionalShadow",customDepthMode:"use"})}function eo(e,t,i,r){if(!i.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 n=!1;for(let t=0;t<i.lights.points.length;t+=1){const a=i.lights.points[t];if(a.castShadow){n=!0;for(let n=0;n<6;n+=1){const s=6*t+n,o=this.pointShadowCameras[t][n];o.near=a.shadowCameraNear,o.far=a.shadowCameraFar,o.position.copy(a.position),F.copy(a.position).add(V[n]),o.up.copy(R[n]),o.lookAt(F),o.updateMatrixWorld(!0),o.updateProjectionMatrix();const l=this.getShadowCameraBuffer(4+s);this.writeShadowCameraBuffer(tn(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}-${n}`,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,i.gpuOpaqueDraws,r,{fallbackPipeline:this.state.pointShadowPipeline,fallbackPipelineDirect:this.state.pointShadowPipelineDirect,fallbackSkinnedPipeline:this.state.skinnedPointShadowPipeline,fallbackBindGroup:c,shadowCameraBuffer:l,passKind:"pointShadow",customDepthMode:"use"}),this.drawDepthLike(u,i.directOpaqueDraws,r,{fallbackPipeline:this.state.pointShadowPipeline,fallbackPipelineDirect:this.state.pointShadowPipelineDirect,fallbackSkinnedPipeline:this.state.skinnedPointShadowPipeline,fallbackBindGroup:c,shadowCameraBuffer:l,passKind:"pointShadow",customDepthMode:"use"}),io.call(this,u,o,c,l,"pointShadow",this.state.pointShadowPipeline,this.state.pointShadowPipelineDirect,r),u.end()}}}n||this.clearPointShadow(e)}function to(e,t,i,r){if(!i.lights.spots.some(e=>e.castShadow))return;if(!this.state.shadowDepthPipeline||0===this.state.spotShadowLayerViews.length)return void this.clearSpotShadow(e);let n=!1;for(let t=0;t<i.lights.spots.length;t+=1){const a=i.lights.spots[t],s=this.state.spotShadowLayerViews[t];if(!a.castShadow||!s)continue;n=!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),F.copy(a.position).add(a.direction),o.lookAt(F),o.updateMatrixWorld(!0),o.updateProjectionMatrix();const l=this.getShadowCameraBuffer(28+t);this.writeShadowCameraBuffer(tn(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,i.gpuOpaqueDraws,r,{fallbackPipeline:this.state.shadowDepthPipeline,fallbackPipelineDirect:this.state.shadowDepthPipelineDirect,fallbackSkinnedPipeline:this.state.skinnedShadowDepthPipeline,fallbackBindGroup:c,shadowCameraBuffer:l,passKind:"directionalShadow",customDepthMode:"use"}),this.drawDepthLike(u,i.directOpaqueDraws,r,{fallbackPipeline:this.state.shadowDepthPipeline,fallbackPipelineDirect:this.state.shadowDepthPipelineDirect,fallbackSkinnedPipeline:this.state.skinnedShadowDepthPipeline,fallbackBindGroup:c,shadowCameraBuffer:l,passKind:"directionalShadow",customDepthMode:"use"}),io.call(this,u,o,c,l,"directionalShadow",this.state.shadowDepthPipeline,this.state.shadowDepthPipelineDirect,r),u.end()}n||this.clearSpotShadow(e)}function io(e,t,i,r,n,a,s,o){Ls.setFromProjectionMatrix(Us.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse));const l=this.renderBundleScratch;l.length=0;for(const e of this.queryStaticShadowResources(Ls))for(const t of e.shadowChunks)Os.center.copy(t.boundsCenter),Os.radius=t.boundsRadius,Ls.intersectsSphere(Os)&&(l.push(uo.call(this,e,i,r,n,a,s,t)),o.drawCallCount+=t.drawCallCount,o.triangleCount+=t.triangleCount);l.length&&e.executeBundles(l),l.length=0}function ro(e,t,i,r){if(!this.state.depthPrepassPipeline||!this.state.mainDepthView)return;const n=e.beginRenderPass({label:"renderer-depth-prepass",colorAttachments:[],depthStencilAttachment:{view:this.state.mainDepthView,depthClearValue:1,depthLoadOp:"clear",depthStoreOp:"store"}});n.setPipeline(this.state.depthPrepassPipeline),n.setBindGroup(0,t),this.executeStaticDepthPrepass(n,t,r),this.drawDepthLike(n,i.gpuOpaqueDraws,r,{fallbackPipeline:this.state.depthPrepassPipeline,fallbackPipelineDirect:this.state.depthPrepassPipelineDirect,fallbackSkinnedPipeline:this.state.skinnedDepthPrepassPipeline,fallbackBindGroup:t,passKind:"prepass",customDepthMode:"skip"}),this.drawDepthLike(n,i.directOpaqueDraws,r,{fallbackPipeline:this.state.depthPrepassPipeline,fallbackPipelineDirect:this.state.depthPrepassPipelineDirect,fallbackSkinnedPipeline:this.state.skinnedDepthPrepassPipeline,fallbackBindGroup:t,passKind:"prepass",customDepthMode:"skip"}),n.end()}function no(e,t,i){const r=this.renderBundleScratch;r.length=0;for(const e of this.getCameraStaticDrawSets()){if(!e.publicSet.enabled||!this.isStaticDrawSetCameraVisible(e)||0===e.draws.length||"late"===e.drawStage)continue;if(this.getHiZOcclusionCullingActive()&&e.lastPreVisibilityFrameToken===this.staticFrameToken&&oo(e)){const t=this.getOrCreateStaticVisibleDepthSceneBindGroup(e);r.push(ao.call(this,e,t))}else r.push(this.getOrCreateStaticDepthPrepassBundle(e,t));this.recordStaticDrawStats(e,i)}r.length&&e.executeBundles(r),r.length=0}function ao(e,t,i=e.drawMetadataResource.indirectBuffer,r="prepass"){if(!this.state.device||!this.state.depthPrepassPipelineVisible)throw new Error("Renderer visible depth prepass resources are not initialized.");const n=e.indirectDepthPrepassBundles[r];if(n?.sceneBindGroup===t&&n.indirectBuffer===i)return n.bundle;const a=`${e.label}-static-temporal-depth-${r}-bundle-${e.id}`,s=this.state.device.createRenderBundleEncoder({label:a,colorFormats:[],depthStencilFormat:"depth32float",sampleCount:1}),o=co.call(this,e,"prepass","packed-visible");s.setBindGroup(0,t);let l=null,c=null,u=null;for(let t=0;t<e.draws.length;t+=1){const r=e.draws[t],n=o[t];if(r.customDepthMaterial||!n&&(Hs(r,"prepass")||Rs(r.material)||!_s(r)))continue;const a=n?.pipeline??this.state.depthPrepassPipelineVisible;l!==a&&(l=a,u=null,c=null,s.setPipeline(a)),n&&c!==n.bindGroup&&(c=n.bindGroup,s.setBindGroup(1,c)),u!==r.geometryKey&&(u=r.geometryKey,this.bindGeometryVertexBuffers(s,r.geometry,r.geometryResource,n?.vertexAttributes??z,0,1,r.wireframe)),s.drawIndexedIndirect(i,5*t*Uint32Array.BYTES_PER_ELEMENT)}const d=s.finish({label:a});return e.indirectDepthPrepassBundles[r]={sceneBindGroup:t,indirectBuffer:i,bundle:d},d}function so(e){if(this.sampleCount<=1||!this.state.mainDepthView||!this.getHiZOcclusionCullingActive())return;let t=null;const i=this.renderBundleScratch;i.length=0;for(const r of this.getCameraStaticDrawSets()){if(!r.publicSet.enabled||!this.isStaticDrawSetCameraVisible(r)||0===r.draws.length||"late"===r.drawStage||r.lastVisibilityFrameToken!==this.staticFrameToken||!oo(r))continue;t||(t=e.beginRenderPass({label:"renderer-static-temporal-depth-resolve",colorAttachments:[],depthStencilAttachment:{view:this.state.mainDepthView,depthLoadOp:"load",depthStoreOp:"store"}}));const n=this.getOrCreateStaticVisibleDepthSceneBindGroup(r);i.push(ao.call(this,r,n,r.drawMetadataResource.postIndirectBuffer,"postpass"))}i.length&&t.executeBundles(i),i.length=0,t?.end()}function oo(e){return e.temporalDepthSupported??Vs(e.draws)}function lo(e,t){if(!this.state.device||!this.state.depthPrepassPipeline)throw new Error("Renderer is not initialized.");const i=this.resolveSceneBindGroupForDraw(e.draws[0],t);if(e.depthPrepassBundle&&e.depthPrepassBundleSceneBindGroup===i)return e.depthPrepassBundle;const r=co.call(this,e,"prepass"),n=`${e.label}-static-depth-prepass-bundle-${e.id}`,a=this.state.device.createRenderBundleEncoder({label:n,colorFormats:[],depthStencilFormat:"depth32float",sampleCount:1});a.setBindGroup(0,i);let s=null,o=null,l=null;for(let t=0;t<e.draws.length;t+=1){const i=e.draws[t],n=r[t];if(i.customDepthMaterial||!n&&(Rs(i.material)||!_s(i)))continue;const c=n?.pipeline??this.state.depthPrepassPipeline;s!==c&&(s=c,o=null,l=null,a.setPipeline(c)),n&&o!==n.bindGroup&&(o=n.bindGroup,a.setBindGroup(1,o)),l!==i.geometryKey&&(l=i.geometryKey,this.bindGeometryVertexBuffers(a,i.geometry,i.geometryResource,n?.vertexAttributes??z,i.instanceStart,i.instanceCount,i.wireframe)),a.drawIndexed(i.count,i.instanceCount,i.start,0,i.instanceStart)}const c=a.finish({label:n});return e.depthPrepassBundle=c,e.depthPrepassBundleSceneBindGroup=i,c}function co(e,t,i){const r=i?`${t}:${i}`:t,n=e.depthMaterialResources.get(r);if(n)return n;const a=e.draws.map(e=>{const r=Hs(e,t);if(e.customDepthMaterial||!r)return null;return this.getDepthPassMaterialResourceForDraw(e.material,t,e,i)});return e.depthMaterialResources.set(r,a),a}function uo(e,t,i,r,n,a,s){if(!this.state.device)throw new Error("Renderer is not initialized.");const o=this.resolveShadowBindGroupForDraw(e.draws[0],t,i),l=s?null:e.shadowBundles.get(o),c=s?s.bundles.get(o):l?.[r];if(c)return c;const u=co.call(this,e,r),d=`${e.label}-static-${r}-bundle-${e.id}`,h=this.state.device.createRenderBundleEncoder({label:d,colorFormats:"pointShadow"===r?["rgba16float"]:[],depthStencilFormat:"depth32float",sampleCount:1});h.setBindGroup(0,o);let p=null,f=null,m=null;const g=s?.drawIndices;for(let t=0;t<(g?.length??e.draws.length);t+=1){const i=g?.[t]??t,r=e.draws[i];if(!r.castShadow)continue;const s=u[i],o=s?.pipeline??("instanced-direct"===this.getDrawInstanceAccessMode(r)&&a?a:n);p!==o&&(p=o,f=null,m=null,h.setPipeline(o)),s&&f!==s.bindGroup&&(f=s.bindGroup,h.setBindGroup(1,f)),m!==r.geometryKey&&(m=r.geometryKey,this.bindGeometryVertexBuffers(h,r.geometry,r.geometryResource,s?.vertexAttributes??z,r.instanceStart,r.instanceCount,r.wireframe)),h.drawIndexed(r.count,r.instanceCount,r.start,0,r.instanceStart)}const v=h.finish({label:d});return s?s.bundles.set(o,v):e.shadowBundles.set(o,{...l,[r]:v}),v}function ho(e,t=!1,i=!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"});if(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(),!i){for(let t=1;t<this.state.hizMipCount;t+=1){const i=Math.max(1,this.state.width>>t),r=Math.max(1,this.state.height>>t);let n=this.state.hizReduceBindGroups[t];n||(n=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]=n);const a=e.beginComputePass({label:`renderer-hiz-reduce-pass-${t}`});a.setPipeline(this.state.hizReduceKernel.pipeline),a.setBindGroup(0,n),a.dispatchWorkgroups(Math.ceil(i/8),Math.ceil(r/8)),a.end()}t&&this.commitTemporalHiZHistory()}}function po(e,t,i,r,n,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??i,resolveTarget:d?i: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,v=null,x=null;const w=e=>{e.sourceObject&&e.hasRenderCallbacks&&e.sourceObject.onBeforeRender(this,n.scene,n.camera,e.geometry,e.material,e.geometryGroup);const t=e.geometryResource,i=this.getMaterialResourceForDraw(e,[D],c),s=this.resolveSceneBindGroupForDraw(e,r);if(f!==i.pipeline&&(f=i.pipeline,g=null,x=null,p.setPipeline(f)),g!==e.geometryKey&&(g=e.geometryKey,this.bindGeometryVertexBuffers(p,e.geometry,t,i.vertexAttributes,e.instanceStart,e.instanceCount,e.wireframe)),v!==s&&(v=s,p.setBindGroup(0,s)),m!==e.material){if(m=e.material,p.setBindGroup(1,i.bindGroup),!i.graphTextureBindGroupLayout)throw new Error("Graph texture layout is missing.");p.setBindGroup(3,this.createGraphTextureBindGroup(e.material,i.graphTextureBindGroupLayout))}i.usesSkinning&&e.skinning&&x!==e.skinning.bindGroup&&(x=e.skinning.bindGroup,p.setBindGroup(2,x)),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,n.scene,n.camera,e.geometry,e.material,e.geometryGroup)};if(this.executeStaticForwardPass(p,r,a,o,c),f=null,m=null,g=null,v=null,x=null,"late"!==o&&this.getHiZOcclusionCullingActive()&&this.state.drawMetadataResource){const e=this.buildIndirectSubmissionStreams(n.gpuOpaqueDraws,r),t=this.renderBundleScratch;t.length=0;for(let i=0;i<e.length;i+=1){const r=e[i];t[0]=this.getOrCreateIndirectForwardBundle(r),p.executeBundles(t),a.drawCallCount+=r.drawCallCount,a.triangleCount+=r.triangleCount}f=null,m=null,g=null,v=null}else if("late"!==o){const e=Hr(n.gpuOpaqueDraws)||n.gpuOpaqueDraws.some(e=>null!==e.skinning)?null:this.getOrCreateDirectForwardBundle(n.gpuOpaqueDraws,r,a);if(e)this.renderBundleScratch[0]=e,p.executeBundles(this.renderBundleScratch);else for(const e of n.gpuOpaqueDraws)w(e)}const b="late"===o||Hr(n.directOpaqueDraws)||n.directOpaqueDraws.some(e=>null!==e.skinning)?null:this.getOrCreateDirectForwardBundle(n.directOpaqueDraws,r,a);if(b)this.renderBundleScratch[0]=b,p.executeBundles(this.renderBundleScratch);else if("late"!==o)for(const e of n.directOpaqueDraws)w(e);if("opaque"!==o)for(const e of n.transparentDraws)w(e);p.end()}function fo(e,t,i,r="all",n=this.sampleCount){const a=this.renderBundleScratch;a.length=0;for(const s of this.getCameraStaticDrawSets())if(s.publicSet.enabled&&this.isStaticDrawSetCameraVisible(s)&&0!==s.draws.length&&("all"===r||s.drawStage===r)){if("opaque"===s.drawStage&&this.getHiZOcclusionCullingActive()&&s.lastVisibilityFrameToken===this.staticFrameToken){const t=this.getOrCreateStaticVisibleSceneBindGroup(s),r=this.getOrCreateStaticIndirectSubmissionStreams(s,t);for(const t of r)if(this.getMultiDrawIndirectActive()){if(a.length&&(e.executeBundles(a),a.length=0),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(s.drawMetadataResource.indirectBuffer,5*t.indirectStartIndex*Uint32Array.BYTES_PER_ELEMENT,t.indirectCount),i.drawCallCount+=t.drawCallCount,i.triangleCount+=t.triangleCount}else a.push(this.getOrCreateIndirectForwardBundle(t,s.drawMetadataResource,s.indirectForwardBundleCache,`${s.label}-static-indirect-forward-bundle`)),i.drawCallCount+=t.drawCallCount,i.triangleCount+=t.triangleCount;continue}a.push(this.getOrCreateStaticDirectForwardBundle(s,t,n)),this.recordStaticDrawStats(s,i)}a.length&&e.executeBundles(a),a.length=0}function mo(e,t,i=this.sampleCount){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&&e.directForwardBundleSampleCount===i)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}`,a=this.state.device.createRenderBundleEncoder({label:n,colorFormats:[D],depthStencilFormat:"depth32float",sampleCount:i});let s=null,o=null,l=null;a.setBindGroup(0,r);for(const t of e.draws){const r=("opaque"===e.drawStage?t.materialResource:null)??this.getMaterialResource(t.material,this.getDrawInstanceAccessMode(t),t.receiveShadow,void 0,null!==t.skinning,Ns(t),i);if(s!==r.pipeline&&(s=r.pipeline,l=null,a.setPipeline(s)),l!==t.geometryKey&&(l=t.geometryKey,this.bindGeometryVertexBuffers(a,t.geometry,t.geometryResource,r.vertexAttributes,t.instanceStart,t.instanceCount,t.wireframe)),o!==r.bindGroup){if(o=r.bindGroup,a.setBindGroup(1,o),!r.graphTextureBindGroupLayout)throw new Error("Graph texture layout is missing.");a.setBindGroup(3,this.createGraphTextureBindGroup(t.material,r.graphTextureBindGroupLayout))}a.drawIndexed(t.count,t.instanceCount,t.start,0,t.instanceStart)}const c=a.finish({label:n});return e.directForwardBundle=c,e.directForwardBundleSceneBindGroup=r,e.directForwardBundleSampleCount=i,c}function go(e){for(const t of e.visibleMaterialBindings){const i=t.drawIndices[0];t.resource=e.draws[i]?.materialResource??e.visibleDrawMaterialResources[i]??null}}function vo(e){for(const t of e)t.materialResource=this.getMaterialResource(t.material,this.getDrawInstanceAccessMode(t),t.receiveShadow,void 0,null!==t.skinning,Ns(t))}function xo(e,t){t.drawCallCount+=e.drawCallCount,t.triangleCount+=e.triangleCount}function wo(){return this.getCameraStaticDrawSets().some(e=>e.publicSet.enabled&&this.isStaticDrawSetCameraVisible(e)&&!e.cpuVisibility&&"opaque"===e.drawStage&&e.draws.length>0)}function bo(e,t,i){if(!(this.state.device&&this.state.presentPipeline&&this.state.fullscreenTextureBindGroupLayout&&this.state.linearClampSampler))return;let r=this.state.presentBindGroups.get(t);r||(r=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,r));const n=e.beginRenderPass({label:"renderer-present-pass",colorAttachments:[{view:i,clearValue:{r:this.clearColor[0],g:this.clearColor[1],b:this.clearColor[2],a:this.clearColor[3]},loadOp:"clear",storeOp:"store"}]});n.setPipeline(this.state.presentPipeline),n.setBindGroup(0,r),n.draw(3),n.end()}function yo(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 So(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 Co(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 Mo(e,t,i,r){let n=null,a=null,s=null,o=null,l=null;for(const c of t){if("directionalShadow"===r.passKind&&!r.preculled){if(Os.center.copy(c.boundsCenter),Os.radius=c.boundsRadius,!As.intersectsSphere(Os))continue;const e=c.detailCulling??f(c.sourceObject);if(!c.staticLocalBoundsCenter&&!g(c.boundsCenter,c.boundsRadius,ks,this.state.directionalShadowTextureSize,this.state.directionalShadowTextureSize,$s,.85*e.shadowMinScreenSize,e.shadowMaxDistance,Fs))continue}if("prepass"!==r.passKind&&!c.castShadow)continue;if("prepass"===r.passKind&&null===c.material.depthVertexShader&&Rs(c.material))continue;if("skip"===r.customDepthMode&&c.customDepthMaterial)continue;const t=Hs(c,r.passKind),u="use"===r.customDepthMode&&c.customDepthMaterial?c.customDepthMaterial:"ignore"!==r.customDepthMode&&t?c.material:null,d=u?this.getDepthPassMaterialResourceForDraw(u,r.passKind,c):null;if(!d&&!_s(c))continue;const h=null!==c.skinning,p=d?.pipeline??(h&&r.fallbackSkinnedPipeline?r.fallbackSkinnedPipeline:"instanced-direct"===this.getDrawInstanceAccessMode(c)&&r.fallbackPipelineDirect?r.fallbackPipelineDirect:r.fallbackPipeline);a!==p&&(a=p,s=null,o=null,l=null,n=null,e.setPipeline(p));const m="prepass"===r.passKind?this.resolveSceneBindGroupForDraw(c,r.fallbackBindGroup):this.resolveShadowBindGroupForDraw(c,r.fallbackBindGroup,r.shadowCameraBuffer);s!==m&&(s=m,e.setBindGroup(0,m)),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 v=c.geometryResource;n!==c.geometryKey&&(n=c.geometryKey,this.bindGeometryVertexBuffers(e,c.geometry,v,d?.vertexAttributes??(h?L:z),c.instanceStart,c.instanceCount,c.wireframe)),c.indexed&&(c.wireframe?v.wireframeIndex:v.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,i)}}var Po=class extends Map{oldest=null;newest=null;touch(e,t){e.lastUsedExtractionVersion=t,this.newest!==e&&(this.unlink(e),e.previous=this.newest,this.newest?this.newest.next=e:this.oldest=e,this.newest=e)}add(e,t,i){const r=this.get(e);r?r.push(t):this.set(e,[t]),this.touch(t,i)}prune(e){for(;this.oldest&&e-this.oldest.lastUsedExtractionVersion>120;){const e=this.oldest,t=this.get(e.hash),i=t.indexOf(e);t.splice(i,1),0===t.length&&this.delete(e.hash),this.unlink(e),e.bundle=null}}clear(){let e=this.oldest;for(;e;){const t=e.next;e.bundle=null,e.previous=null,e.next=null,e=t}this.oldest=this.newest=null,super.clear()}unlink(e){e.previous?e.previous.next=e.next:this.oldest===e&&(this.oldest=e.next),e.next?e.next.previous=e.previous:this.newest===e&&(this.newest=e.previous),e.previous=e.next=null}};import{Box3 as Bo,Mesh as Do,Sphere as Io}from"three";import{Vector3 as To}from"three";var Ro=class{entries=[];pending=[];root=null;stack=[];stateStack=[];retired=0;add(e,t){const i={...t,boundsCenter:t.boundsCenter.clone(),value:e,active:!0};return this.pending.push(i),i}remove(e){e.active&&(e.active=!1,this.retired++)}clear(){this.entries.length=this.pending.length=this.stack.length=this.stateStack.length=0,this.root=null,this.retired=0}prepareQuery(){if(!this.root||this.pending.length+this.retired>Math.max(128,this.entries.length/4)){this.entries=this.entries.filter(e=>e.active);for(const e of this.pending)e.active&&this.entries.push(e);this.pending.length=0,this.retired=0,this.root=this.entries.length?this.build(0,this.entries.length):null}}query(e,t){if(!this.entries.length&&!this.pending.length)return;this.prepareQuery();const i=this.stack;for(i.length=0,this.root&&i.push(this.root);i.length;){const r=i.pop();if(e(r))if(r.left&&r.right)i.push(r.left,r.right);else for(let i=r.start;i<r.end;i++){const r=this.entries[i];r.active&&e(r)&&t(r.value)}}for(const i of this.pending)i.active&&e(i)&&t(i.value)}queryWithState(e,t,i){if(!this.entries.length&&!this.pending.length)return;this.prepareQuery();const r=this.stack,n=this.stateStack;for(r.length=n.length=0,this.root&&(r.push(this.root),n.push(i));r.length;){const i=r.pop(),a=e(i,n.pop());if(!(a<0))if(i.left&&i.right)r.push(i.left,i.right),n.push(a,a);else for(let r=i.start;r<i.end;r++){const i=this.entries[r];i.active&&e(i,a)>=0&&t(i.value)}}for(const r of this.pending)r.active&&e(r,i)>=0&&t(r.value)}build(e,t){let i=1/0,r=1/0,n=1/0,a=-1/0,s=-1/0,o=-1/0,l=0,c=1/0,u=0,d=!1,h=!1;for(let p=e;p<t;p++){const e=this.entries[p],t=e.boundsCenter,f=e.boundsRadius;i=Math.min(i,t.x-f),a=Math.max(a,t.x+f),r=Math.min(r,t.y-f),s=Math.max(s,t.y+f),n=Math.min(n,t.z-f),o=Math.max(o,t.z+f),l=Math.max(l,e.maxMemberRadius),c=Math.min(c,e.minScreenSize),d||=0===e.maxDistance,u=Math.max(u,e.maxDistance),h||=e.castShadow}const p=new To((i+a)/2,(r+s)/2,(n+o)/2),f={start:e,end:t,boundsCenter:p,boundsRadius:Math.hypot(a-p.x,s-p.y,o-p.z),maxMemberRadius:l,minScreenSize:c,maxDistance:d?0:u,castShadow:h,left:null,right:null};if(t-e>16){const l=a-i>=s-r&&a-i>=o-n?"x":s-r>=o-n?"y":"z",c=this.entries.slice(e,t).sort((e,t)=>e.boundsCenter[l]-t.boundsCenter[l]);for(let t=0;t<c.length;t++)this.entries[e+t]=c[t];const u=e+t>>>1;f.left=this.build(e,u),f.right=this.build(u,t)}return f}},Vo=class{index=new Ro;roots=new Set;children=new Map;invalidateChildren=e=>{e.target&&this.children.delete(e.target)};observed=new Set;indexedParents=new Map;registrations=new Set;registrationByRoot=new Map;meshSnapshots=new WeakMap;traversals=new WeakMap;getMeshSnapshot(e){return this.meshSnapshots.get(e)}queryScene=null;queryVisit=null;visitRoot=e=>{let t=e;for(;t&&t!==this.queryScene;t=t.parent)if(!t.visible)return;t===this.queryScene&&t?.visible&&this.queryVisit(e)};register(e){let t;this.registrationByRoot.get(e)?.dispose();let i=!1,r=!1,n=null;const a=new Set,s=[],o=()=>l(),l=()=>{if(t&&this.index.remove(t),t=void 0,this.roots.delete(e),this.traversals.delete(e),n){this.children.delete(n);const e=this.indexedParents.get(n)-1;e>0?this.indexedParents.set(n,e):(this.indexedParents.delete(n),this.observed.delete(n),n.removeEventListener("childadded",this.invalidateChildren),n.removeEventListener("childremoved",this.invalidateChildren)),n=null}for(const e of a)e.removeEventListener("childadded",o),e.removeEventListener("childremoved",o);a.clear();for(const e of s)this.meshSnapshots.get(e)?.onInvalidate?.(),this.meshSnapshots.delete(e);if(s.length=0,i||r)return;let l=!0,c=0,u=1/0,d=0,h=!1,p=!1;const m=new Bo,g=new Io,v=new Bo;if(e.updateWorldMatrix(!0,!0),e.traverse(e=>{if(a.add(e),e.addEventListener("childadded",o),e.addEventListener("childremoved",o),e.isFogVolumeObject&&(l=!1),!(e instanceof Do))return void("Group"!==e.type&&"Object3D"!==e.type&&(l=!1));(e.isSkinnedMesh||e.isInstancedMesh||e.isBatchedMesh||!e.frustumCulled||e.morphTargetInfluences?.length)&&(l=!1);const t=f(e);e.geometry.boundingSphere||e.geometry.computeBoundingSphere(),e.geometry.boundingSphere?(g.copy(e.geometry.boundingSphere).applyMatrix4(e.matrixWorld),m.union(g.getBoundingBox(v))):l=!1,u=Math.min(u,t.minScreenSize),h||=0===t.maxDistance,p||=e.castShadow,d=Math.max(d,t.maxDistance),c++}),!l||!c)return;if(m.getBoundingSphere(g),!Number.isFinite(g.radius)||!Number.isFinite(g.center.lengthSq()))return;for(const e of a)e instanceof Do&&(g.copy(e.geometry.boundingSphere).applyMatrix4(e.matrixWorld),this.meshSnapshots.set(e,{boundsCenter:g.center.clone(),boundsRadius:g.radius,frontFaceCW:e.matrixWorld.determinant()<0,detailCulling:f(e)}),s.push(e));m.getBoundingSphere(g),this.roots.add(e);const x=Array.from(a),w=new Uint32Array(x.length),b=new Uint8Array(x.length),y=[];for(let e=0;e<x.length;e++){for(;y.length&&x[y[y.length-1]]!==x[e].parent;)w[y.pop()]=e;b[e]=x[e]instanceof Do?1:0,y.push(e)}for(;y.length;)w[y.pop()]=x.length;this.traversals.set(e,{objects:x,subtreeEnds:w,meshes:b}),n=e.parent,n&&(this.indexedParents.set(n,(this.indexedParents.get(n)??0)+1),this.children.delete(n)),t=this.index.add(e,{boundsCenter:g.center,boundsRadius:g.radius,maxMemberRadius:g.radius,minScreenSize:u,maxDistance:h?0:d,castShadow:p})},c=()=>l();e.addEventListener("added",c),e.addEventListener("removed",c),l();const u={update:()=>{r||l()},setEditing:e=>{r||e===i||(i=e,l())},dispose:()=>{r||(r=!0,l(),e.removeEventListener("added",c),e.removeEventListener("removed",c),this.registrations.delete(u),this.registrationByRoot.delete(e))}};return this.registrations.add(u),this.registrationByRoot.set(e,u),u}traversalChildren(e){if(!this.indexedParents.has(e))return e.children;let t=this.children.get(e);return t||(t=e.children.filter(e=>!this.roots.has(e)),this.children.set(e,t),this.observed.has(e)||(this.observed.add(e),e.addEventListener("childadded",this.invalidateChildren),e.addEventListener("childremoved",this.invalidateChildren))),t}visitMeshes(e,t,i){const r=this.traversals.get(e);if(!r)return;const{objects:n,subtreeEnds:a,meshes:s}=r;for(let e=0;e<n.length;){const r=n[e];!r.visible||i&&!i(r)?e=a[e]:(s[e]&&t(r),e++)}}query(e,t,i){this.queryScene=e,this.queryVisit=i;try{this.index.query(t,this.visitRoot)}finally{this.queryScene=null,this.queryVisit=null}}queryWithState(e,t,i,r){this.queryScene=e,this.queryVisit=i;try{this.index.queryWithState(t,this.visitRoot,r)}finally{this.queryScene=null,this.queryVisit=null}}dispose(){for(const e of this.registrations)e.dispose();for(const e of this.observed)e.removeEventListener("childadded",this.invalidateChildren),e.removeEventListener("childremoved",this.invalidateChildren);this.observed.clear(),this.indexedParents.clear(),this.children.clear(),this.roots.clear(),this.index.clear()}};import{Matrix4 as Go,OrthographicCamera as zo,Vector3 as Lo}from"three";var Uo=(e,t)=>void 0!==e&&Number.isFinite(e)&&e>0?e:t,Ao=class{constructor(e){this.cameras=e,this.layers=e.map(()=>({valid:!1,source:null,direction:new Lo,rangeX:0,rangeY:0,nextUpdateMs:0,lastUpdateMs:-1/0,candidate:new zo}))}cameras;layers;updateMask=0;forcedMask=0;settings={enabled:!1,maxUpdateHz:60,cascadeUpdateHz:[60,30,15,7.5],maxUpdatesPerFrame:2,coverageMargin:.05,teleportDistance:10};previousProjection=new Go;previousPosition=new Lo;viewerPosition=new Lo;corner=new Lo;viewerValid=!1;revision=-1;timeMs=0;setOptions(e){this.settings={enabled:e.enabled??!1,maxUpdateHz:Uo(e.maxUpdateHz,60),cascadeUpdateHz:(e.cascadeUpdateHz?.length?e.cascadeUpdateHz:[60,30,15,7.5]).map(e=>Uo(e,60)),maxUpdatesPerFrame:Math.max(1,Math.floor(Uo(e.maxUpdatesPerFrame,2))),coverageMargin:Number.isFinite(e.coverageMargin)?Math.max(0,Math.min(.5,e.coverageMargin)):.05,teleportDistance:Uo(e.teleportDistance,10)},this.invalidate()}invalidate(){for(const e of this.layers)e.valid=!1}interval(e){const t=this.settings.cascadeUpdateHz;return 1e3/Math.min(this.settings.maxUpdateHz,t[Math.min(e,t.length-1)])}prepare(e,t,i,r,n,a){this.timeMs=n,this.updateMask=this.forcedMask=0,t.getWorldPosition(this.viewerPosition);let s=this.revision!==a;if(this.viewerValid){s||=this.viewerPosition.distanceToSquared(this.previousPosition)>this.settings.teleportDistance**2;const e=t.projectionMatrix.elements,i=this.previousProjection.elements,r=!0===t.isPerspectiveCamera;for(let t=0;t<16;t++)if((r?8!==t&&9!==t:12!==t&&13!==t)&&Math.abs(e[t]-i[t])>1e-6){s=!0;break}}this.revision=a,this.previousPosition.copy(this.viewerPosition),this.previousProjection.copy(t.projectionMatrix),this.viewerValid=!0,s&&this.invalidate();for(let t=0;t<this.layers.length;t++){const n=this.layers[t],a=e[t];if(!a?.castShadow){n.valid=!1;continue}const s=n.candidate;s.left=a.shadowCameraLeft,s.right=a.shadowCameraRight,s.top=a.shadowCameraTop,s.bottom=a.shadowCameraBottom,s.near=a.shadowCameraNear,s.far=a.shadowCameraFar,s.position.copy(a.position),s.lookAt(a.target),s.updateMatrixWorld(!0),s.updateProjectionMatrix();const o=t<r?i[t].x:0,l=t<r?i[t].y:0,c=!n.valid||n.source!==a.sourceLight||n.direction.distanceToSquared(a.direction)>1e-12||n.rangeX!==o||n.rangeY!==l||!this.containsCandidate(this.cameras[t],s);this.settings.enabled&&!c||(this.updateMask|=1<<t,c&&(this.forcedMask|=1<<t))}let o=this.settings.maxUpdatesPerFrame;for(;this.settings.enabled&&o-- >0;){let t=-1,i=1/0;for(let r=0;r<e.length;r++){if(!e[r].castShadow||this.updateMask&1<<r)continue;const a=this.layers[r].nextUpdateMs;n+1e-6>=a&&a<i&&(i=a,t=r)}if(t<0)break;this.updateMask|=1<<t}for(let t=0;t<e.length;t++){if(!(this.updateMask&1<<t))continue;const n=e[t],a=this.layers[t],s=this.cameras[t];if(s.copy(a.candidate),this.settings.enabled){const e=this.settings.coverageMargin,t=s.right-s.left,i=s.top-s.bottom,r=s.far-s.near;s.left-=t*e,s.right+=t*e,s.bottom-=i*e,s.top+=i*e,s.near-=r*e,s.far+=r*e,s.updateProjectionMatrix()}a.source=n.sourceLight,a.direction.copy(n.direction),a.rangeX=t<r?i[t].x:0,a.rangeY=t<r?i[t].y:0}}commit(e){const t=this.layers[e],i=this.interval(e);!t.valid||this.forcedMask&1<<e||!Number.isFinite(t.nextUpdateMs)?t.nextUpdateMs=this.timeMs+i+e*(1e3/this.settings.maxUpdateHz)/this.layers.length:(t.nextUpdateMs+=Math.max(1,Math.floor((this.timeMs-t.nextUpdateMs)/i)+1)*i,t.nextUpdateMs<=this.timeMs&&(t.nextUpdateMs=this.timeMs+i)),t.lastUpdateMs=this.timeMs,t.valid=!0}containsCandidate(e,t){for(let i=0;i<2;i++)for(let r=0;r<2;r++)for(let n=0;n<2;n++){this.corner.set(i?t.right:t.left,r?t.top:t.bottom,-(n?t.far:t.near)).applyMatrix4(t.matrixWorld).applyMatrix4(e.matrixWorldInverse);const a=1e-5;if(this.corner.x<e.left-a||this.corner.x>e.right+a||this.corner.y<e.bottom-a||this.corner.y>e.top+a||this.corner.z<-e.far-a||this.corner.z>-e.near+a)return!1}return!0}};import{Sphere as ko,Vector3 as Fo}from"three";function Oo(e,t){return e.id-t.id}function Eo(e){return`${Math.floor(e.x/32)}:${Math.floor(e.y/32)}:${Math.floor(e.z/32)}`}function jo(e,t){if(!t)return[e];const i=new Map;for(const t of e){const e=Eo(t.boundsCenter);let r=i.get(e);r||(r=[],i.set(e,r)),r.push(t)}return[...i.values()]}var $o=class{constructor(e,t,i,r,n){this.state=e,this.staticDrawSets=t,this.getGeometryResourceForGeometry=i,this.resolveMaterial=r,this.ensureWireframeIndex=n}state;staticDrawSets;getGeometryResourceForGeometry;resolveMaterial;ensureWireframeIndex;revision=0;spatialIndex=new Ro;spatialEntries=new Map;cameraCandidates=[];shadowCandidates=[];shadowFrustum=null;shadowSphere=new ko;testShadow=e=>!!e.castShadow&&(this.shadowSphere.center.copy(e.boundsCenter),this.shadowSphere.radius=e.boundsRadius,this.shadowFrustum.intersectsSphere(this.shadowSphere));collectShadow=e=>{e.publicSet.enabled&&"late"!==e.drawStage&&this.shadowCandidates.push(e)};markCameraVisible=e=>{e.publicSet.enabled&&(e.cameraVisible=!0,this.cameraCandidates.push(e))};updateCameraVisibility(e){for(const e of this.cameraCandidates)e.cameraVisible=!1;this.cameraCandidates.length=0,this.spatialIndex.query(e,this.markCameraVisible),this.cameraCandidates.sort(Oo)}queryShadowResources(e){return this.shadowCandidates.length=0,this.shadowFrustum=e,this.spatialIndex.query(this.testShadow,this.collectShadow),this.shadowFrustum=null,this.shadowCandidates}nextStaticDrawSetId=1;activeMutableTransforms=!1;activeObject=null;activeDetailDefaults;activeMaterialSnapshots=null;snapshotSources=new WeakMap;getSourceMaterial(e){return this.snapshotSources.get(e)??e}getGeometryResource(e){return this.getGeometryResourceForGeometry(e)}resolveStaticMaterial(e){const t=this.resolveMaterial(e);if(!t||!this.activeMaterialSnapshots)return t;let i=this.activeMaterialSnapshots.get(t);return i||(i=t.clone(),this.snapshotSources.set(i,t),i.name=t.name?`${t.name} (static snapshot)`:"Static draw-set material snapshot",this.activeMaterialSnapshots.set(t,i)),i}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 i=t.label??`static-draw-set-${this.nextStaticDrawSetId}`,r=t.onUnsupported??"throw",n=t.allowUnsortedLateDraws??!1,a=[],s=new vn(4096),o=(e,t)=>{if("skip"!==r)throw new Error(`StaticDrawSet "${i}" does not support ${e.type||"Object3D"} "${e.name||e.uuid}": ${t}.`)};this.activeMutableTransforms=!0===t.mutableTransforms,this.activeDetailDefaults=t.detailCulling,e.updateMatrixWorld(!0);const l=new Map;this.activeMaterialSnapshots=l;try{e.traverseVisible(e=>{this.activeObject=e,e.isSkinnedMesh?o(e,"skinned meshes are dynamic"):e.isBatchedMesh?this.collectStaticBatchedMesh(e,s,a,i,o,n):e.isInstancedMesh?this.collectStaticInstancedMesh(e,s,a,i,o,n):e.isMesh&&this.collectStaticMesh(e,s,a,i,o,n)})}catch(e){for(const e of l.values())e.dispose();throw e}finally{this.activeMutableTransforms=!1,this.activeMaterialSnapshots=null,this.activeObject=null,this.activeDetailDefaults=void 0}const c=new Map;if(!(s.instanceCount>=512&&!a.some(e=>e.transparent)))return this.createResource(i,a,s,l,!0===t.mutableTransforms);let u=1/0,d=1/0,h=1/0;for(const e of a)u=Math.min(u,e.boundsCenter.x),d=Math.min(d,e.boundsCenter.y),h=Math.min(h,e.boundsCenter.z);for(const e of a){const t=e.boundsCenter,i=`${Math.floor((t.x-u)/256)}:${Math.floor((t.y-d)/256)}:${Math.floor((t.z-h)/256)}`;let r=c.get(i);r||c.set(i,r=[]),r.push(e)}if(c.size<=1)return this.createResource(i,a,s,l,!0===t.mutableTransforms);const p=[];try{for(const[e,r]of c)p.push(this.createResource(`${i}-${e}`,r,s,0===p.length?l:new Map,!0===t.mutableTransforms))}catch(e){for(const e of p)e.dispose();if(!p.length)for(const e of l.values())e.dispose();throw e}let f=!0,m=!1;return{label:i,get enabled(){return f},set enabled(e){f=e;for(const t of p)t.enabled=e},get drawCount(){return p.reduce((e,t)=>e+t.drawCount,0)},get instanceCount(){return p.reduce((e,t)=>e+t.instanceCount,0)},updateTransforms(){if(!m)for(const e of p)e.updateTransforms()},dispose(){if(!m){m=!0;for(const e of p)e.dispose()}}}}createResource(e,t,i,r,n){if(!this.state.device)throw new Error("Renderer is not initialized.");const{draws:a,instanceData:s}=this.mergeStaticDraws(t,i),o=a.some(e=>e.transparent),l=a.some(e=>!e.transparent);if(o&&l)throw new Error(`StaticDrawSet "${e}" cannot mix opaque and late materials; register them as separate sets.`);const c=this.createVisibleMaterialBindings(a),u=this.createShadowChunks(a),d=Math.max(4,s.byteLength),h=this.state.device.createBuffer({label:`${e}-static-instance-buffer`,size:256*Math.ceil(d/256),usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST});s.floatLength>0?this.state.device.queue.writeBuffer(h,0,s.rawData.buffer,0,s.byteLength):this.state.device.queue.writeBuffer(h,0,P,0,C);const p={mode:"packed",buffer:h,colorBuffer:null,sceneBindGroup:null,shadowBindGroup:null,shadowBindGroups:new Map,sceneBindGroupVersion:0,shadowBindGroupVersion:0};for(const e of a)e.residentInstanceBinding=p;const f=this.createStaticDrawMetadataResource(e,a),m=this.createStaticInstanceVisibilityResource(e,a,s),g=new Fo(1/0,1/0,1/0),v=new Fo(-1/0,-1/0,-1/0);let x=0,w=1/0,b=0,y=!1;const S=m.metadata;for(let e=0;e<s.instanceCount;e++){const t=8*e,i=S[t+3];F.set(S[t],S[t+1],S[t+2]),cn(g,v,F,i),x=Math.max(x,i),w=Math.min(w,S[t+6]),y||=0===S[t+7],b=Math.max(b,S[t+7])}const M=(new Fo).addVectors(g,v).multiplyScalar(.5),B={boundsCenter:M,boundsRadius:M.distanceTo(v),maxMemberRadius:x,minScreenSize:w,maxDistance:y?0:b,castShadow:a.some(e=>e.castShadow)},D=new Uint32Array([a.length,this.state.hizMipCount,s.instanceCount,0]),I=this.state.device.createBuffer({label:`${e}-visibility-params-buffer`,size:16,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),T=new Uint32Array([a.length,this.state.hizMipCount,s.instanceCount,0]),R=this.state.device.createBuffer({label:`${e}-post-visibility-params-buffer`,size:16,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST});this.state.device.queue.writeBuffer(I,0,D,0,4),this.state.device.queue.writeBuffer(R,0,T,0,4);const V={temporalDepthSupported:Vs(a),spatialBounds:B,cpuVisibility:!o&&1===a.length&&1===s.instanceCount,cameraVisible:!1,cameraDetailVisible:!1,id:this.nextStaticDrawSetId++,label:e,publicSet:null,ownedMaterials:[...r.values()],draws:a,shadowChunks:u,drawStage:o?"late":"opaque",drawCallCount:a.length,triangleCount:a.reduce((e,t)=>e+Math.floor(Math.max(0,t.count)/3)*Math.max(0,t.instanceCount),0),instanceCount:s.instanceCount,instanceBuffer:h,residentInstanceBinding:p,drawMetadataResource:f,instanceVisibilityResource:m,visibilityParamsBuffer:I,visibilityParamsUpload:D,postVisibilityParamsBuffer:R,postVisibilityParamsUpload:T,visibilityBindGroup:null,postVisibilityBindGroup:null,visibilityClearBindGroup:null,visibilityIndirectBuildBindGroup:null,postVisibilityIndirectBuildBindGroup:null,visibleSceneBindGroup:null,visibleSceneBindGroupVersion:0,visibleDepthSceneBindGroup:null,visibleDepthSceneBindGroupVersion:0,visibleMaterialBindings:c,visibleDrawMaterialResources:new Array(a.length),visibleIndirectSubmissionStreams:null,visibleIndirectStreamsSceneBindGroup:null,visibleIndirectStreamsSampleCount:-1,visibleIndirectStreamsColorFormatsKey:"",visibilityBindGroupHizVersion:0,lastPreVisibilityFrameToken:0,lastVisibilityFrameToken:0,indirectForwardBundleCache:new Po,directForwardBundle:null,directForwardBundleSampleCount:-1,directForwardBundleSceneBindGroup:null,depthPrepassBundle:null,depthPrepassBundleSceneBindGroup:null,indirectDepthPrepassBundles:{prepass:null,postpass:null},shadowBundles:new WeakMap,depthMaterialResources:new Map},G=n?s:null;let z=!0;const L=this,U={label:e,get enabled(){return z},set enabled(e){z!==e&&(z=e,L.revision++)},get drawCount(){return V.draws.length},get instanceCount(){return V.instanceCount},updateTransforms:()=>{if(!G)throw new Error("StaticDrawSet requires mutableTransforms to refresh transforms.");this.staticDrawSets.includes(V)&&this.updateTransforms(V,G)},dispose:()=>{this.disposeStaticDrawSetResource(V)}};return V.publicSet=U,this.staticDrawSets.push(V),this.revision++,s.instanceCount>0&&this.spatialEntries.set(V,this.spatialIndex.add(V,B)),U}updateTransforms(e,t){const i=this.state.device,r=e.instanceVisibilityResource.metadata,n=t.rawData,a=new Float32Array(4),s=new Fo,o=new Fo,l=new Fo(1/0,1/0,1/0),c=new Fo(-1/0,-1/0,-1/0);let u=0;for(let t=0;t<e.draws.length;t++){const d=e.draws[t];s.set(1/0,1/0,1/0),o.set(-1/0,-1/0,-1/0);for(const e of d.sourceRanges){const t=e.sourceObject;t.updateWorldMatrix(!0,!1);for(let i=0;i<e.instanceCount;i++){const a=e.sourceInstanceIds?.[i]??0;if(t.isBatchedMesh){const e=t._instanceInfo?.[a]??t._drawInfo?.[a];e?.active&&e.visible?t.getMatrixAt(a,U):U.makeScale(0,0,0),A.multiplyMatrices(t.matrixWorld,U)}else t.isInstancedMesh?(a<t.count?t.getMatrixAt(a,U):U.makeScale(0,0,0),A.multiplyMatrices(t.matrixWorld,U)):A.copy(t.matrixWorld);const l=e.instanceStart+i,c=l*C;A.toArray(n,c),A.toArray(n,c+24),n[c+23]=0;const h=E.copy(d.staticLocalBoundsCenter).applyMatrix4(A),p=d.staticLocalBoundsRadius*on(A),f=8*l;r[f]=h.x,r[f+1]=h.y,r[f+2]=h.z,r[f+3]=p,cn(s,o,h,p),u=Math.max(u,p)}}d.boundsCenter.addVectors(s,o).multiplyScalar(.5),d.boundsRadius=d.boundsCenter.distanceTo(o),cn(l,c,d.boundsCenter,d.boundsRadius),a[0]=d.boundsCenter.x,a[1]=d.boundsCenter.y,a[2]=d.boundsCenter.z,a[3]=d.boundsRadius,i.queue.writeBuffer(e.drawMetadataResource.metadataBuffer,t*M*4,a)}if(t.instanceCount){i.queue.writeBuffer(e.instanceBuffer,0,n.buffer,0,t.byteLength),i.queue.writeBuffer(e.instanceVisibilityResource.instanceMetadataBuffer,0,r.buffer);const a=e.spatialBounds;a.boundsCenter.addVectors(l,c).multiplyScalar(.5),a.boundsRadius=a.boundsCenter.distanceTo(c),a.maxMemberRadius=u;const s=this.spatialEntries.get(e);s&&this.spatialIndex.remove(s),this.spatialEntries.set(e,this.spatialIndex.add(e,a))}for(const t of e.shadowChunks){s.set(1/0,1/0,1/0),o.set(-1/0,-1/0,-1/0);for(const i of t.drawIndices){const t=e.draws[i];cn(s,o,t.boundsCenter,t.boundsRadius)}t.boundsCenter.addVectors(s,o).multiplyScalar(.5),t.boundsRadius=t.boundsCenter.distanceTo(o)}e.lastPreVisibilityFrameToken=e.lastVisibilityFrameToken=0,this.state.temporalHiZHistoryValid=!1,this.revision++}createVisibleMaterialBindings(e){const t=new Map;for(let i=0;i<e.length;i+=1){const r=e[i],n=`${jr(r.material)}:${r.receiveShadow?1:0}:${r.usesBatching?1:0}`;let a=t.get(n);a||(a={material:r.material,receiveShadow:r.receiveShadow,usesBatching:r.usesBatching,drawIndices:[],resource:null},t.set(n,a)),a.drawIndices.push(i)}return[...t.values()]}createShadowChunks(e){const t=new Map;for(let i=0;i<e.length;i+=1){const r=e[i];if(!r.castShadow||r.transparent)continue;const n=Eo(r.boundsCenter);let a=t.get(n);a||(a=[],t.set(n,a)),a.push(i)}const i=[];for(const r of t.values())for(let t=0;t<r.length;t+=64){const n=r.slice(t,t+64);let a=1/0,s=1/0,o=1/0,l=-1/0,c=-1/0,u=-1/0;for(const t of n){const i=e[t],r=i.boundsCenter,n=i.boundsRadius;a=Math.min(a,r.x-n),s=Math.min(s,r.y-n),o=Math.min(o,r.z-n),l=Math.max(l,r.x+n),c=Math.max(c,r.y+n),u=Math.max(u,r.z+n)}const d=new Fo(.5*(a+l),.5*(s+c),.5*(o+u)),h=l-d.x,p=c-d.y,f=u-d.z;i.push({drawIndices:n,drawCallCount:n.length,triangleCount:n.reduce((t,i)=>{const r=e[i];return t+Math.floor(Math.max(0,r.count)/3)*Math.max(0,r.instanceCount)},0),boundsCenter:d,boundsRadius:Math.sqrt(h*h+p*p+f*f),bundles:new WeakMap})}return i}mergeStaticDraws(e,t){e.sort(Nr);const i=[],r=e.reduce((e,t)=>e+t.instanceCount*C,0),n=new vn(Math.max(1024,r));for(let r=0;r<e.length;){const a=e[r],s=n.instanceCount;n.appendRange(t,a.instanceStart,a.instanceCount);const o=a.sourceRanges;for(const e of o)e.instanceStart+=s-a.instanceStart;let l=a.instanceCount,c=a.boundsCenter.x-a.boundsRadius,u=a.boundsCenter.y-a.boundsRadius,d=a.boundsCenter.z-a.boundsRadius,h=a.boundsCenter.x+a.boundsRadius,p=a.boundsCenter.y+a.boundsRadius,f=a.boundsCenter.z+a.boundsRadius,m=r+1;for(;m<e.length&&Yr(a,e[m]);){const i=e[m];n.appendRange(t,i.instanceStart,i.instanceCount);for(const e of i.sourceRanges)o.push({...e,instanceStart:s+l+e.instanceStart-i.instanceStart});l+=i.instanceCount;const r=i.boundsCenter.x-i.boundsRadius,a=i.boundsCenter.y-i.boundsRadius,g=i.boundsCenter.z-i.boundsRadius,v=i.boundsCenter.x+i.boundsRadius,x=i.boundsCenter.y+i.boundsRadius,w=i.boundsCenter.z+i.boundsRadius;r<c&&(c=r),a<u&&(u=a),g<d&&(d=g),v>h&&(h=v),x>p&&(p=x),w>f&&(f=w),m+=1}const g=.5*(c+h),v=.5*(u+p),x=.5*(d+f),w=h-g,b=p-v,y=f-x;a.instanceStart=s,a.instanceCount=l,a.boundsCenter.set(g,v,x),a.boundsRadius=Math.sqrt(w*w+b*b+y*y),i.push(a),r=m}return{draws:i,instanceData:n}}collectStaticMesh(e,t,i,r,n,a){if(!(null!==e.geometry.index))return void n(e,"non-indexed geometry cannot use the v1 indirect static path");if(hn(e))return void n(e,"custom depth materials are not supported by StaticDrawSet v1");const s=this.getGeometryResource(e.geometry),o=sn(e.geometry),l=F.copy(o.center).applyMatrix4(e.matrixWorld),c=o.radius*on(e.matrixWorld),u=Or(t,e.matrixWorld,1,1,1,1),d=Array.isArray(e.material)?e.material:null,h=Array.isArray(e.material)?null:e.material;if(e.geometry.groups.length>0){for(const t of e.geometry.groups){const r=d?d[t.materialIndex??0]??d[0]:h,p=this.resolveStaticMaterial(r);if(!p){n(e,"all static mesh materials must be WGSLShaderMaterial");continue}if(p.transparent&&!a){n(e,"transparent materials are not supported by StaticDrawSet v1");continue}if(Object.keys(p.getGraphTextureInputs()).length>0&&!a){n(e,"scene-texture materials are not supported by StaticDrawSet v1");continue}const f=Gr(e.geometry,!0,t.start,t.count);f<=0||i.push(this.createStaticDrawRecord(e.geometry,e.geometry,s,p,!1,t.start,f,u,1,l.x,l.y,l.z,c,o.center,o.radius,e.matrixWorld.determinant()<0))}return}const p=h??d?.[0]??null,f=this.resolveStaticMaterial(p);if(!f)return void n(e,"all static mesh materials must be WGSLShaderMaterial");if(f.transparent&&!a)return void n(e,"transparent materials are not supported by StaticDrawSet v1");if(Object.keys(f.getGraphTextureInputs()).length>0&&!a)return void n(e,"scene-texture materials are not supported by StaticDrawSet v1");const m=zr(e.geometry,!0);m.count<=0||i.push(this.createStaticDrawRecord(e.geometry,e.geometry,s,f,!1,m.start,m.count,u,1,l.x,l.y,l.z,c,o.center,o.radius,e.matrixWorld.determinant()<0))}collectStaticInstancedMesh(e,t,i,r,n,a){const s=this.resolveStaticMaterial(e.material);if(!s)return void n(e,"static instanced meshes must use WGSLShaderMaterial");if(s.transparent&&!a)return void n(e,"transparent materials are not supported by StaticDrawSet v1");if(Object.keys(s.getGraphTextureInputs()).length>0&&!a)return void n(e,"scene-texture materials are not supported by StaticDrawSet v1");if(hn(e))return void n(e,"custom depth materials are not supported by StaticDrawSet v1");if(null===e.geometry.index)return void n(e,"non-indexed geometry cannot use the v1 indirect static path");const o=zr(e.geometry,!0);if(o.count<=0||e.count<=0)return;const l=sn(e.geometry),c=this.getGeometryResource(e.geometry),u=[];for(let t=0;t<e.count;t+=1){e.getMatrixAt(t,U),A.multiplyMatrices(e.matrixWorld,U);const i=e.instanceColor?e.instanceColor.getComponent(t,0):1,r=e.instanceColor&&e.instanceColor.itemSize>1?e.instanceColor.getComponent(t,1):1,n=e.instanceColor&&e.instanceColor.itemSize>2?e.instanceColor.getComponent(t,2):1,a=e.instanceColor&&e.instanceColor.itemSize>3?e.instanceColor.getComponent(t,3):1,s=E.copy(l.center).applyMatrix4(A),o=l.radius*on(A);u.push({matrix:new Float32Array(A.elements),color0:i,color1:r,color2:n,color3:a,batchingId:t,boundsCenter:s.clone(),boundsRadius:o})}for(const r of jo(u,!s.transparent&&!s.requiresLatePass())){const n=F.set(1/0,1/0,1/0),a=O.set(-1/0,-1/0,-1/0),u=t.instanceCount;for(const e of r)t.appendMatrixAndColorValues(e.matrix,e.color0,e.color1,e.color2,e.color3),cn(n,a,e.boundsCenter,e.boundsRadius);const d=.5*(n.x+a.x),h=.5*(n.y+a.y),p=.5*(n.z+a.z),f=a.x-d,m=a.y-h,g=a.z-p;i.push(this.createStaticDrawRecord(e.geometry,e.geometry,c,s,!1,o.start,o.count,u,r.length,d,h,p,Math.sqrt(f*f+m*m+g*g),l.center,l.radius)),this.activeMutableTransforms&&(i[i.length-1].sourceRanges[0].sourceInstanceIds=r.map(e=>e.batchingId))}}collectStaticBatchedMesh(e,t,i,r,n,a){const s=this.resolveStaticMaterial(e.material);if(!s)return void n(e,"static batched meshes must use WGSLShaderMaterial");if(s.transparent&&!a)return void n(e,"transparent materials are not supported by StaticDrawSet v1");if(Object.keys(s.getGraphTextureInputs()).length>0&&!a)return void n(e,"scene-texture materials are not supported by StaticDrawSet v1");if(hn(e))return void n(e,"custom depth materials are not supported by StaticDrawSet v1");if(null===e.geometry.index)return void n(e,"non-indexed geometry cannot use the v1 indirect static path");const o=e,l=this.getGeometryResource(e.geometry),c=o._geometryCount??0,u=[],d=new Map;for(let t=0;t<c;t+=1){const i=e.getGeometryRangeAt(t);if(!i||i.count<=0)continue;const r=Gr(e.geometry,!0,i.start,i.count);if(r<=0)continue;const n=e.getBoundingSphereAt(t,k),a={geometryId:t,start:i.start,count:r,localBoundsCenter:n?n.center.clone():new Fo,localBoundsRadius:n?.radius??1,instances:[]};d.set(t,a),u.push(a)}const h=o._instanceInfo??o._drawInfo??[],p=o._matricesTexture?.image.data,f=o._colorsTexture?.image.data;for(let t=0;t<h.length;t+=1){const i=h[t];if(!i?.active||!i.visible&&!this.activeMutableTransforms)continue;const r=d.get(i.geometryIndex);if(!r)continue;p?Er(U,p,16*t):e.getMatrixAt(t,U),A.multiplyMatrices(e.matrixWorld,U);const n=4*t;i.visible||A.makeScale(0,0,0);const a=f?f[n+0]??1:1,s=f?f[n+1]??1:1,o=f?f[n+2]??1:1,l=f?f[n+3]??1:1,c=E.copy(r.localBoundsCenter).applyMatrix4(A),u=r.localBoundsRadius*on(A);r.instances.push({matrix:new Float32Array(A.elements),color0:a,color1:s,color2:o,color3:l,batchingId:t,boundsCenter:c.clone(),boundsRadius:u})}for(const r of u)if(0!==r.instances.length)for(const n of jo(r.instances,!s.transparent&&!s.requiresLatePass())){const a=F.set(1/0,1/0,1/0),o=O.set(-1/0,-1/0,-1/0),c=t.instanceCount;for(const e of n)t.appendMatrixAndColorValues(e.matrix,e.color0,e.color1,e.color2,e.color3,e.batchingId),cn(a,o,e.boundsCenter,e.boundsRadius);const u=.5*(a.x+o.x),d=.5*(a.y+o.y),h=.5*(a.z+o.z),p=o.x-u,f=o.y-d,m=o.z-h,g=Math.sqrt(p*p+f*f+m*m);i.push(this.createStaticDrawRecord(e.geometry,e.geometry,l,s,!0,r.start,r.count,c,n.length,u,d,h,g,r.localBoundsCenter,r.localBoundsRadius)),this.activeMutableTransforms&&(i[i.length-1].sourceRanges[0].sourceInstanceIds=n.map(e=>e.batchingId))}}createStaticDrawRecord(e,t,i,r,n,a,s,o,l,c,u,d,h,p,m,g=!1){const v=jr(r),x=r.wireframe&&"triangle-list"===r.primitiveTopology;x&&this.ensureWireframeIndex(e,i);const w=jr(t);return{geometry:e,geometryKey:x?i.wireframeIndex:t,geometryResource:i,material:r,customDepthMaterial:null,residentInstanceBinding:null,sourceObject:null,sourceRanges:[{sourceObject:this.activeObject,instanceStart:o,instanceCount:l}],detailCulling:f(this.activeObject,this.activeDetailDefaults),frontFaceCW:g,usesBatching:n,geometryGroup:null,batchKey:$r(r,t,!0,a,s,null),batchHash:Wr(v,w,!0,a,s,0),indexed:!0,wireframe:x,start:x?2*a:a,count:x?2*s:s,transparent:r.transparent||r.requiresLatePass(),renderOrder:0,hasRenderCallbacks:!1,castShadow:this.activeObject?.castShadow??!1,receiveShadow:this.activeObject?.receiveShadow??!1,sortMaterialId:v,sortGeometryId:w,sortCustomDepthMaterialId:0,skinning:null,materialResource:null,instanceStart:o,instanceCount:l,boundsCenter:new Fo(c,u,d),boundsRadius:h,sortDepth:0,transparentSortGroup:0,transparentSortOrder:0,staticLocalBoundsCenter:p.clone(),staticLocalBoundsRadius:m}}createStaticDrawMetadataResource(e,t){if(!this.state.device)throw new Error("Renderer is not initialized.");const i=Math.max(1,t.length),r=new Float32Array(i*M),n=new Uint32Array(5*i),a=new Uint32Array(5*i);for(let e=0;e<t.length;e+=1){const i=t[e],s=e*M;r[s+0]=i.boundsCenter.x,r[s+1]=i.boundsCenter.y,r[s+2]=i.boundsCenter.z,r[s+3]=i.boundsRadius,r[s+4]=i.count,r[s+5]=i.start,r[s+6]=i.instanceStart,r[s+7]=i.instanceCount,r[s+8]=1,r[s+9]=0,r[s+10]=0,r[s+11]=0;const o=5*e;n[o+0]=i.count,n[o+1]=i.instanceCount,n[o+2]=i.start,n[o+3]=0,n[o+4]=i.instanceStart,a[o+0]=i.count,a[o+1]=0,a[o+2]=i.start,a[o+3]=0,a[o+4]=i.instanceStart}const s=this.state.device.createBuffer({label:`${e}-static-draw-metadata-buffer`,size:i*M*4,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST}),o=this.state.device.createBuffer({label:`${e}-static-indirect-draw-buffer`,size:5*i*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*i*4,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.INDIRECT|GPUBufferUsage.COPY_DST});return this.state.device.queue.writeBuffer(s,0,r,0,r.length),this.state.device.queue.writeBuffer(o,0,n,0,n.length),this.state.device.queue.writeBuffer(l,0,a,0,a.length),{count:t.length,capacity:i,metadataBuffer:s,indirectBuffer:o,postIndirectBuffer:l}}createStaticInstanceVisibilityResource(e,t,i){if(!this.state.device)throw new Error("Renderer is not initialized.");const r=i.instanceCount,n=Math.max(32,32*r),a=new ArrayBuffer(n),s=new Float32Array(a),o=new Uint32Array(a);for(let e=0;e<t.length;e+=1){const r=t[e],n=r.staticLocalBoundsCenter??sn(r.geometry).center,a=r.staticLocalBoundsRadius??sn(r.geometry).radius;for(let t=0;t<r.instanceCount;t+=1){const l=r.instanceStart+t,c=l*C,u=8*l;U.fromArray(i.rawData,c);const d=F.copy(n).applyMatrix4(U),h=a*on(U);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,s[u+6]=r.detailCulling?.minScreenSize??0,s[u+7]=r.detailCulling?.maxDistance??0}}const l=this.state.device.createBuffer({label:`${e}-static-instance-visibility-metadata`,size:256*Math.ceil(n/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*r)/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*r)/256),usage:GPUBufferUsage.STORAGE});return r>0&&this.state.device.queue.writeBuffer(l,0,a),{metadata:s,instanceMetadataBuffer:l,visibleInstanceIndicesBuffer:c,visibleCountsBuffer:u,postVisibleCountsBuffer:d,visibleInstanceMaskBuffer:h,instanceCount:r}}disposeStaticDrawSetResource(e){const t=this.staticDrawSets.indexOf(e);if(t<0)return;const i=this.spatialEntries.get(e);i&&this.spatialIndex.remove(i),this.spatialEntries.delete(e),e.disposeDirectionalGpuShadows?.(),this.staticDrawSets.splice(t,1);const r=this.cameraCandidates.indexOf(e);r>=0&&this.cameraCandidates.splice(r,1),this.shadowCandidates.length=0,e.cameraVisible=!1,this.revision++;const n=new Set;for(const t of e.draws)t.materialResource&&n.add(t.materialResource);for(const t of e.visibleMaterialBindings)t.resource&&n.add(t.resource);for(const t of e.visibleDrawMaterialResources)t&&n.add(t);for(const t of e.depthMaterialResources.values())for(const e of t)e&&n.add(e);for(const e of n)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()}};import{RGBAFormat as Wo}from"three";function No(e,t,i,r){const n=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),a=new Uint8Array(n.byteLength);for(let e=0;e<r;e++){const r=e*t*i;for(let e=0;e<i;e++){const s=r+e*t;a.set(n.subarray(s,s+t),r+(i-e-1)*t)}}return a}var _o=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 i="non-filtering"===t,r=i?"nearest":Ur(e.magFilter),n=i?"nearest":Ur(e.minFilter),a=i?"nearest":Ur(e.minFilter),s="comparison"===t?function(e){switch(e){case tr:return"never";case Yi:return"less";case _i:return"equal";case Zi:return"less-equal";case Hi:return"greater";case ir:return"not-equal";case qi:return"greater-equal";case Wi:return"always";default:return}}(e.compareFunction):void 0,o=i||"linear"!==r||"linear"!==n||"linear"!==a?1:Math.max(1,e.anisotropy);return this.state.device.createSampler({label:`${e.uuid}-sampler`,addressModeU:Lr(e.wrapS),addressModeV:Lr(e.wrapT),addressModeW:Lr(e.wrapR??e.wrapT),magFilter:r,minFilter:n,mipmapFilter:a,maxAnisotropy:o,compare:s})}uploadDataTextureResource(e,t,i){if(!this.state.device)throw new Error("Renderer is not initialized.");const r=_t(i.format);if(null===r)throw new Error(`Texture format "${i.format}" from "${e.constructor.name}" cannot be uploaded with queue.writeTexture.`);const n=e.mipmaps;if(n&&n.length>0){for(let a=0;a<n.length;a+=1){const s=n[a];if(!s?.data)continue;const o=s.width??Math.max(1,i.width>>a),l=s.height??Math.max(1,i.height>>a),c=s.depth??i.depthOrArrayLayers;this.state.device.queue.writeTexture({texture:t,mipLevel:a},kr(e.flipY?No(s.data,o*r,l,c):s.data),{bytesPerRow:o*r,rowsPerImage:l},{width:o,height:l,depthOrArrayLayers:c})}return}const a=e.image;a?.data&&this.state.device.queue.writeTexture({texture:t},e.flipY?No(a.data,i.width*r,i.height,i.depthOrArrayLayers):a.data,{bytesPerRow:i.width*r,rowsPerImage:i.height},{width:i.width,height:i.height,depthOrArrayLayers:i.depthOrArrayLayers})}uploadCompressedTextureResource(e,t,i){if(!this.state.device)throw new Error("Renderer is not initialized.");let r="bc1-rgba-unorm"===(n=i.format)||"bc1-rgba-unorm-srgb"===n?{byteLength:8,width:4,height:4}:"bc2-rgba-unorm"===n||"bc2-rgba-unorm-srgb"===n||"bc3-rgba-unorm"===n||"bc3-rgba-unorm-srgb"===n?{byteLength:16,width:4,height:4}:"bc4-r-unorm"===n||"bc4-r-snorm"===n?{byteLength:8,width:4,height:4}:"bc5-rg-unorm"===n||"bc5-rg-snorm"===n||"bc6h-rgb-ufloat"===n||"bc6h-rgb-float"===n||"bc7-rgba-unorm"===n||"bc7-rgba-unorm-srgb"===n?{byteLength:16,width:4,height:4}:"etc2-rgb8unorm"===n||"etc2-rgb8unorm-srgb"===n||"etc2-rgb8a1unorm"===n||"etc2-rgb8a1unorm-srgb"===n?{byteLength:8,width:4,height:4}:"etc2-rgba8unorm"===n||"etc2-rgba8unorm-srgb"===n?{byteLength:16,width:4,height:4}:"eac-r11unorm"===n||"eac-r11snorm"===n?{byteLength:8,width:4,height:4}:"eac-rg11unorm"===n||"eac-rg11snorm"===n||"astc-4x4-unorm"===n||"astc-4x4-unorm-srgb"===n?{byteLength:16,width:4,height:4}:"astc-5x4-unorm"===n||"astc-5x4-unorm-srgb"===n?{byteLength:16,width:5,height:4}:"astc-5x5-unorm"===n||"astc-5x5-unorm-srgb"===n?{byteLength:16,width:5,height:5}:"astc-6x5-unorm"===n||"astc-6x5-unorm-srgb"===n?{byteLength:16,width:6,height:5}:"astc-6x6-unorm"===n||"astc-6x6-unorm-srgb"===n?{byteLength:16,width:6,height:6}:"astc-8x5-unorm"===n||"astc-8x5-unorm-srgb"===n?{byteLength:16,width:8,height:5}:"astc-8x6-unorm"===n||"astc-8x6-unorm-srgb"===n?{byteLength:16,width:8,height:6}:"astc-8x8-unorm"===n||"astc-8x8-unorm-srgb"===n?{byteLength:16,width:8,height:8}:"astc-10x5-unorm"===n||"astc-10x5-unorm-srgb"===n?{byteLength:16,width:10,height:5}:"astc-10x6-unorm"===n||"astc-10x6-unorm-srgb"===n?{byteLength:16,width:10,height:6}:"astc-10x8-unorm"===n||"astc-10x8-unorm-srgb"===n?{byteLength:16,width:10,height:8}:"astc-10x10-unorm"===n||"astc-10x10-unorm-srgb"===n?{byteLength:16,width:10,height:10}:"astc-12x10-unorm"===n||"astc-12x10-unorm-srgb"===n?{byteLength:16,width:12,height:10}:"astc-12x12-unorm"===n||"astc-12x12-unorm-srgb"===n?{byteLength:16,width:12,height:12}:null;var n;if(!r&&e.format===Wo){const e=_t(i.format);null!==e&&(r={width:1,height:1,byteLength:e})}if(!r)throw new Error(`Compressed texture format "${i.format}" is not supported for upload.`);if(!0===e.isCompressedCubeTexture){const n=e.image;for(let e=0;e<n.length;e+=1){const a=n[e]?.mipmaps??[];for(let n=0;n<a.length;n+=1){const s=a[n];if(!s?.data)continue;const o=s.width??Math.max(1,i.width>>n),l=s.height??Math.max(1,i.height>>n),c=Math.max(1,Math.ceil(o/r.width)),u=Math.max(1,Math.ceil(l/r.height));this.state.device.queue.writeTexture({texture:t,mipLevel:n,origin:{x:0,y:0,z:e}},kr(s.data),{bytesPerRow:c*r.byteLength,rowsPerImage:u},{width:c*r.width,height:u*r.height,depthOrArrayLayers:1})}}return}const a=e.mipmaps;for(let e=0;e<a.length;e+=1){const n=a[e];if(!n?.data)continue;const s=n.width??Math.max(1,i.width>>e),o=n.height??Math.max(1,i.height>>e),l=Math.max(1,Math.ceil(s/r.width)),c=Math.max(1,Math.ceil(o/r.height));this.state.device.queue.writeTexture({texture:t,mipLevel:e},kr(n.data),{bytesPerRow:l*r.byteLength,rowsPerImage:c},{width:l*r.width,height:c*r.height,depthOrArrayLayers:i.depthOrArrayLayers})}}uploadExternalTextureResource(e,t,i){if(!this.state.device)throw new Error("Renderer is not initialized.");if(!0===e.isCubeTexture){const r=e.image;if(!Array.isArray(r)||6!==r.length)return void this.warnSkippedExternalTextureUpload(e,i,"CubeTexture must provide exactly six face images.");for(let n=0;n<r.length;n+=1){const a=Ar(r[n]);if(!a)return void this.warnSkippedExternalTextureUpload(e,i,`CubeTexture face ${n} 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:n}},{width:i.width,height:i.height,depthOrArrayLayers:1})}catch(t){return void this.warnSkippedExternalTextureUpload(e,i,`CubeTexture face ${n} could not be copied: ${Ho(t)}`)}}return}const r=function(e){return Ar(e.image)}(e);if(r)try{this.state.device.queue.copyExternalImageToTexture({source:r,flipY:e.flipY},{texture:t},{width:i.width,height:i.height,depthOrArrayLayers:1})}catch(t){this.warnSkippedExternalTextureUpload(e,i,`copyExternalImageToTexture failed: ${Ho(t)}`)}else this.warnSkippedExternalTextureUpload(e,i,"Texture.image is not an HTML image, canvas, video, ImageBitmap, or OffscreenCanvas.")}warnSkippedExternalTextureUpload(e,t,i){if(this.skippedExternalTextureWarnings.has(e))return;this.skippedExternalTextureWarnings.add(e);const r=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. ${i}`,{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:r?.constructor?.name??typeof r,width:r?.width,height:r?.height,depth:r?.depth,src:r?.currentSrc??r?.src,hasData:null!=r?.data,keys:null==r?[]:Object.keys(r).slice(0,16)},userData:e.userData})}uploadTextureResource(e,t,i){!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,i):this.uploadDataTextureResource(e,t,i):this.uploadCompressedTextureResource(e,t,i)}getTextureResource(e){if(!this.state.device)throw new Error("Renderer is not initialized.");const t=this.textureCache.get(e),i=$t(e,this.state.device);if(t&&t.version===e.version&&t.width===i.width&&t.height===i.height&&t.depthOrArrayLayers===i.depthOrArrayLayers&&t.format===i.format&&t.textureDimension===i.textureDimension&&t.viewDimension===i.viewDimension&&t.sampleType===i.sampleType&&t.samplerBindingType===i.samplerBindingType&&t.mipLevelCount===i.mipLevelCount)return t;this.destroyTextureResource(t);const r=performance.now(),n=this.state.device.createTexture({label:`${e.uuid}-texture`,size:{width:i.width,height:i.height,depthOrArrayLayers:i.depthOrArrayLayers},dimension:i.textureDimension,format:i.format,mipLevelCount:i.mipLevelCount,usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|(i.compressed||"3d"===i.textureDimension?0:GPUTextureUsage.RENDER_ATTACHMENT)}),a=performance.now();this.uploadTextureResource(e,n,i);const s=performance.now()-a,o=a-r;(s>16||o>16)&&this.warnSlowTextureUpload(e,i,o,s,t?.version);const l=this.createTextureSampler(e,i.samplerBindingType),c={version:e.version,width:i.width,height:i.height,depthOrArrayLayers:i.depthOrArrayLayers,format:i.format,textureDimension:i.textureDimension,viewDimension:i.viewDimension,sampleType:i.sampleType,samplerBindingType:i.samplerBindingType,mipLevelCount:i.mipLevelCount,texture:n,view:n.createView("2d"===i.viewDimension?void 0:"2d-array"===i.viewDimension?{dimension:"2d-array",arrayLayerCount:i.depthOrArrayLayers}:{dimension:i.viewDimension}),sampler:l};return this.textureCache.set(e,c),c}warnSlowTextureUpload(e,t,i,r,n){let a=null;if(!0===e.isCompressedCubeTexture){a=0;for(const t of e.image)for(const e of t.mipmaps??[])a+=e.data?.byteLength??0}else if(e.mipmaps&&e.mipmaps.length>0){a=0;for(const t of e.mipmaps)a+=t.data?.byteLength??0}else a=e.image?.data?.byteLength??null;console.warn("[WebGPU] Slow texture upload",{textureName:e.name||void 0,textureUuid:e.uuid,assetId:e.userData.assetId,textureClass:e.constructor.name,format:t.format,width:t.width,height:t.height,depthOrArrayLayers:t.depthOrArrayLayers,mipLevelCount:t.mipLevelCount,sourceBytes:a,allocationMs:Math.round(100*i)/100,uploadMs:Math.round(100*r)/100,thresholdMs:16,version:e.version,previousVersion:n,timing:"CPU call duration, including browser waits; not GPU transfer time. sourceBytes is null for external images."})}};function Ho(e){return e instanceof Error?e.message:String(e)}function qo(e){if(e.transparent)switch(e.blending){case ea:return{color:{srcFactor:"src-alpha",dstFactor:"one",operation:"add"},alpha:{srcFactor:"one",dstFactor:"one",operation:"add"}};case ga:return{color:{srcFactor:"zero",dstFactor:"one-minus-src",operation:"subtract"},alpha:{srcFactor:"one",dstFactor:"one",operation:"subtract"}};case ca: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 Ko(e,t,i,r){if(t<0||e[t]!==i)return-1;let n=0;for(let a=t;a<e.length;a+=1)if(e[a]===i&&(n+=1),e[a]===r&&(n-=1,0===n))return a;return-1}function Yo(e,t,i){const r=function(e,t="fsMain"){const i=e.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/.*$/gm,""),r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),n=new RegExp(`@fragment\\s+fn\\s+${r}\\s*\\(`).exec(i);if(!n)return null;const a=i.indexOf("(",n.index),s=Ko(i,a,"(",")");if(s<0)return null;const o=i.indexOf("{",s+1);if(o<0)return null;const l=i.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(i);if(!h)return null;const p=i.indexOf("{",h.index),f=Ko(i,p,"{","}");if(f<0)return null;const m=new Set,g=/@location\s*\(\s*(\d+)\s*\)/g,v=i.slice(p+1,f);for(const e of v.matchAll(g))m.add(Number(e[1]));return m}(e);return t.map((e,t)=>null===r||r.has(t)?{format:e,blend:i}:{format:e,writeMask:0})}function Zo(e,t){const i=Nr(e,t);return 0!==i?i:e.residentInstanceBinding!==t.residentInstanceBinding?jr(e.residentInstanceBinding)-jr(t.residentInstanceBinding):e.instanceStart-t.instanceStart}function Xo(e){const t=e.userData.motionBlurMode;if(null==t&&e.isSkinnedMesh)return 1;if("number"==typeof t&&Number.isFinite(t))return Math.max(0,Math.min(3,Math.round(t)));switch(t){case"disabled":case"Disabled":return 0;case"cameraOnly":case"CameraOnly":return 1;case"forceObjectBlur":case"ForceObjectBlur":return 3;default:return 2}}function Jo(e){const t=Number(e.userData.motionBlurScale??1);return Number.isFinite(t)?Math.max(0,Math.min(t,8)):1}var Qo="chromium-experimental-multi-draw-indirect";function el(e,t){return Number(t.castShadow)-Number(e.castShadow)}var tl=[D],il=[{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"}];var rl=new WeakMap;function nl(e){return e.wireframe&&"triangle-list"===e.primitiveTopology?"line-list":e.primitiveTopology}function al(e,t,i){if(!nl(e).startsWith("triangle"))return"none";if("directionalShadow"===t){if(i&&null===e.shadowSide)return"none";const t=e.shadowSide??e.side;return t===aa?"none":t===ta?"front":"back"}return e.side===aa?"none":e.side===ta?"front":"back"}function sl(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 ol=class{pipelineCompilationDiagnostics;canvas;clearColor;powerPreference;shadowMapSize;directionalShadowsEnabled=!0;spotShadowMapSize;pointShadowMapSize;fallbackMaterial;materialResolver;toonOutlineMaterialCache=new WeakMap;fallbackSkinnedMaterial;invokeObjectRenderCallbacks;sampleCount;renderScale;hiZOcclusionCullingEnabled;frameHiZOcclusionCullingNeeded=!0;multiDrawIndirectEnabled;dynamicBatchingEnabled;multiDrawIndirectSupported=!1;tiledPointLights=null;tiledLightingEnabled;transientPointLightsScratch=[];transientPointScoresScratch=new Float64Array(16);renderGraphProfilingEnabled;indirectFirstInstanceSupported=!1;timestampQuerySupported=!1;geometryCache=new WeakMap;skinnedGeometryCache=new Map;skinPaletteCache=new WeakMap;skinPaletteResources=new Set;meshExtractionCache=new WeakMap;resolvedMaterialFrameCache=new WeakMap;repeatedMeshInstances=new WeakMap;repeatedInstanceResources=new Map;instancedMeshExtractionCache=new WeakMap;batchedMeshExtractionCache=new WeakMap;materialUniformData=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;drawMaterialResourceFrameValidation=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 Po,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:[],spotLightMapTexture:null,spotLightMapView:null,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,sceneColorSnapshotPipeline:null,sceneColorSnapshotBindGroups:new WeakMap,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;defaultVertexAttributeBuffers=new Map;textureManager=new _o(this.state,this.textureCache);renderGraph=new $a;nativePostSubmit;presentationOverlay;presentationOverlayContext={device:null,encoder:null,targetView:null,targetFormat:"bgra8unorm",presentationWidth:1,presentationHeight:1};directionalShadowCameras=Array.from({length:4},()=>new ha(-10,10,10,-10,.1,80));directionalShadowScheduler=new Ao(this.directionalShadowCameras);directionalShadowGpu=new Kn;directionalShadowSubmissionStats={bundleHits:0,bundleBuilds:0,selectionHits:0,selections:0};pointShadowCameras=Array.from({length:4},()=>V.map(()=>new pa(90,1,.1,25)));spotShadowCameras=Array.from({length:4},()=>new pa(60,1,.5,500));colorTargetCache=new Map;msaaColorTargetCache=new Map;msaaDepthTargetCache=new Map;sourceInstanceDataScratch=new vn(4096);opaqueInstanceDataScratch=new vn(4096);finalInstanceDataScratch=new vn(4096);residentInstanceUploadsScratch=[];gpuOpaqueDrawsScratch=[];directOpaqueDrawsScratch=[];stagedOpaqueDrawsScratch=[];residentOpaqueDrawsScratch=[];retiredGeometryResources=[];retiredGeometryBuffers=[];vertexAttributeBufferKeyCache=new WeakMap;standardVertexAttributeCache=new WeakMap;geometryVertexBufferFastCache=new WeakMap;vertexAttributeGroupCache=new WeakMap;materialVertexAttributeCache=new WeakMap;sharedVertexAttributeLayouts=new Map;vertexBufferBindingPlanCache=new WeakMap;preparedVertexBufferCache=new WeakMap;vertexAttributeGroupBufferKeyCache=new WeakMap;compileDrawScratch=[];dynamicIndirectSubmissionCache=new WeakMap;indirectStreamKeyCache=new WeakMap;nextIndirectStreamKey=1;indirectBundleInvalidationVersion=0;colorFormatsIdentityCache=new WeakMap;colorFormatsValueCache=new Map([[D,1]]);nextColorFormatsId=2;renderBundleScratch=[];indirectMaterialResourcesScratch=[];directBundleDrawStatsScratch={drawCallCount:0,triangleCount:0};sortedOpaqueBatchesScratch=[];opaqueBatchPool=[];opaqueBatchPoolCount=0;drawCallPool=[];drawCallPoolCount=0;staticDrawSets=[];materialPassStaticBundleCache=new WeakMap;staticDrawSetManager=new $o(this.state,this.staticDrawSets,e=>this.getGeometryResource(e),e=>this.resolveMaterial(e),(e,t)=>this.ensureWireframeIndex(e,t));staticFrameToken=0;hizResourceVersion=0;graphTextureResourceVersion=0;transmissionSnapshotTexture=null;transmissionSnapshotView=null;transmissionSnapshotSize={width:0,height:0};transmissionMipViews=[];transmissionMipBindGroups=[];transmissionSourceBindGroups=new WeakMap;transmissionSnapshotPipeline=null;transmissionSampler=null;visibilityParamsUpload=new Uint32Array(4);drawMetadataUpload=new Float32Array(0);indirectDrawUpload=new Uint32Array(0);extractedAmbientScratch=new wa;extractedHemisphereScratch=this.createExtractedHemisphereLightScratch();extractedBoundsMinScratch=new xa;extractedBoundsMaxScratch=new xa;extractedDirectionalLightsScratch=Array.from({length:4},()=>this.createExtractedDirectionalLightScratch());extractedPointLightsScratch=Array.from({length:y},()=>this.createExtractedPointLightScratch());extractedSpotLightsScratch=Array.from({length:S},()=>this.createExtractedSpotLightScratch());activeDirectionalLightsScratch=[];activePointLightsScratch=[];activeSpotLightsScratch=[];fogVolumeObjectsScratch=[];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,fogVolumeObjects:this.fogVolumeObjectsScratch,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(104);temporalVisibilityUniformScratch=new Float32Array(44);lightUniformScratch=new Float32Array(G);spotLightMapAtlasSignature="";spotLightMapAtlasSize=0;spotLightMapAtlasLayout=null;spotLightMapAtlasPipeline=null;csmCascadeRanges=Array.from({length:4},()=>new va);csmCascadeCount=0;csmCascadeLights=[];shadowCameraUniformScratch=new Float32Array(64);cameraViewProjScratch=new ua;cameraDetailProjectionScratch=new m;cameraProjectionScratch=new ua;projectionJitterPixels=new va;temporalVisibilityCurrentViewProj=new ua;temporalVisibilityPreviousViewProj=new ua;motionVectorProjection=new ua;motionVectorCurrentViewProj=new ua;motionVectorPreviousViewProj=new ua;motionVectorProjectionPending=!1;motionVectorHistoryValid=!1;motionVectorHistoryGeneration=1;lastMotionVectorTimeSeconds=Number.NaN;objectMotionHistory=new WeakMap;cameraFrustumPlanesScratch=new Float32Array(24);objectTraversalStackScratch=[];staticSceneSpatialIndex=new Vo;staticMeshDraws=new WeakMap;staticInstanceSlots=new Xn(1024);retiredStaticInstanceSlots=[];staticSpatialDraws=new WeakSet;staticSpatialDrawRevision=0;staticSpatialBatches=new WeakMap;spatialShadowPlanes=Array.from({length:4},()=>new Float32Array(24));spatialShadowCount=0;spatialLocalShadowSpheres=new Float64Array(512);spatialLocalShadowCount=0;spatialShadowMatrix=new ua;spatialIncludeOffscreen=!1;spatialCameraLayers=0;testSpatialCamera=e=>an(this.cameraFrustumPlanesScratch,e.boundsCenter.x,e.boundsCenter.y,e.boundsCenter.z,e.boundsRadius)&&v(e,this.cameraViewProjScratch,this.state.width,this.state.height,this.transparentSortCameraPositionScratch,this.cameraDetailProjectionScratch);testSpatialScene=(e,t)=>{if(this.spatialIncludeOffscreen)return 0;if(64!==t){if((t=function(e,t,i,r,n,a){for(let s=0,o=1;s<6;s++,o<<=1){if(!(a&o))continue;const l=4*s,c=e[l]*t+e[l+1]*i+e[l+2]*r+e[l+3];if(c<-n)return-1;c>=n&&(a&=~o)}return a}(this.cameraFrustumPlanesScratch,e.boundsCenter.x,e.boundsCenter.y,e.boundsCenter.z,e.boundsRadius,t))>=0&&v(e,this.cameraViewProjScratch,this.state.width,this.state.height,this.transparentSortCameraPositionScratch,this.cameraDetailProjectionScratch))return t;t=64}return e.castShadow&&this.isSpatialShadowSphereVisible(e.boundsCenter.x,e.boundsCenter.y,e.boundsCenter.z,e.boundsRadius)?t:-1};filterSpatialCaptureObject=e=>!1!==this.sceneCaptureOptions?.objectFilter?.(e)&&!1!==e.userData.sceneCapture;pushSpatialRoot=e=>{this.objectTraversalStackScratch.push(e)};collectSpatialMesh=e=>{0!==(e.layers.mask&this.spatialCameraLayers)&&(this.extractingCaster=e.castShadow,this.collectMesh(e,this.sourceInstanceDataScratch,this.updateExtractedBoundsFromMatrixScratch,this.spatialIncludeOffscreen?this.isSphereVisibleForCompilationScratch:this.isSpatialSphereVisible))};isSpatialSphereVisible=(e,t,i,r,n)=>!n||an(this.cameraFrustumPlanesScratch,e,t,i,r)||this.extractingCaster&&this.isSpatialShadowSphereVisible(e,t,i,r);isSpatialShadowSphereVisible(e,t,i,r){for(let n=0;n<this.spatialShadowCount;n++)if(an(this.spatialShadowPlanes[n],e,t,i,r))return!0;for(let n=0;n<this.spatialLocalShadowCount;n++){const a=4*n,s=this.spatialLocalShadowSpheres,o=e-s[a],l=t-s[a+1],c=i-s[a+2],u=r+s[a+3];if(o*o+l*l+c*c<=u*u)return!0}return!1}collectSpatialRoot=e=>{if(null!==this.sceneCaptureOptions)for(let t=e;t;t=t.parent)if(!1===this.sceneCaptureOptions.objectFilter?.(t)||!1===t.userData.sceneCapture)return;this.staticSceneSpatialIndex.visitMeshes(e,this.collectSpatialMesh,null===this.sceneCaptureOptions?void 0:this.filterSpatialCaptureObject)};shadowDrawsScratch=[];extractingCaster=!1;cameraDetailHistory=new WeakMap;isSphereVisibleScratch=(e,t,i,r,n)=>this.extractingCaster||!n||an(this.cameraFrustumPlanesScratch,e,t,i,r);isSphereVisibleForCompilationScratch=()=>!0;updateExtractedBoundsFromMatrixScratch=e=>{const t=this.extractedBoundsMinScratch,i=this.extractedBoundsMaxScratch,r=e[12],n=e[13],a=e[14];r<t.x&&(t.x=r),n<t.y&&(t.y=n),a<t.z&&(t.z=a),r>i.x&&(i.x=r),n>i.y&&(i.y=n),a>i.z&&(i.z=a)};transparentSortCameraPositionScratch=new xa;transparentSortCameraForwardScratch=new xa;temporalVisibilityCurrentCameraPosition=new xa;temporalVisibilityPreviousCameraPosition=new xa;shadowViewProjScratch=new ua;extractionVersion=0;motionHistoryExtractionVersion=0;sceneCaptureOptions=null;sceneCaptureDisposers=new Set;captureMotionHistory={matrix:new Float32Array(16),generation:0,lastExtractionVersion:-1,valid:!1};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 xa,target:new xa,direction:new xa,color:new xa,intensity:0,volumetricIntensity:1,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 xa(0,1,0),skyColor:new xa,groundColor:new xa,intensity:0}}createExtractedPointLightScratch(){return{sourceLight:null,position:new xa,color:new xa,intensity:0,volumetricIntensity:1,distance:0,range:25,decay:2,castShadow:!1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowIntensity:1,shadowMapSize:this.pointShadowMapSize,shadowCameraNear:.5,shadowCameraFar:500}}createExtractedSpotLightScratch(){return{sourceLight:null,position:new xa,direction:new xa(0,-1,0),color:new xa,intensity:0,volumetricIntensity:1,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,map:null}}skinnedDrawKeys=new Zn;skinnedInstanceSlots=new Xn;skinnedRenderRecords=new Map;skinningPaletteArena;skeletonPalettes=new pn;getSkeletonBoneBufferForPass=e=>{const t=this.getSkinningPalette(e);if(this.refreshSkinningPalette(t),this.uploadSkinningPalette(t),t.standaloneBuffer||(t.standaloneBuffer=this.state.device.createBuffer({label:"renderer-skinning-compatibility-palette",size:t.allocation.byteLength,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST}),t.standaloneDirty=!0),t.standaloneDirty){const i=e.boneMatrices;this.state.device.queue.writeBuffer(t.standaloneBuffer,0,i.buffer,i.byteOffset,t.allocation.byteLength),t.standaloneDirty=!1}return t.standaloneBuffer};getSkeletonBoneBindingForPass=e=>{const t=this.getSkinningPalette(e);return this.refreshSkinningPalette(t),this.uploadSkinningPalette(t),t.allocation.currentBinding};outlineResolvedFrameCache=new WeakMap;preparedOutlineFrameCache=new WeakMap;opaqueSortMs=0;opaqueSortSamples=new Float64Array(120);opaqueSortSampleIndex=0;opaqueSortSampleCount=0;opaqueSortSampleTotal=0;sortOpaqueDraws(e,t=Nr){const i=this.renderGraphProfilingEnabled?performance.now():0;e.sort(t),this.renderGraphProfilingEnabled&&(this.opaqueSortMs+=performance.now()-i)}constructor(e){this.canvas=e.canvas,this.nativePostSubmit=e.nativePostSubmit,this.presentationOverlay=e.presentationOverlay,this.clearColor=[...e.clearColor??[0,0,0,1]],this.powerPreference=e.powerPreference,this.directionalShadowScheduler.setOptions(e.directionalShadowUpdates??{}),this.directionalShadowGpu.enabled=e.directionalShadowGpuCulling??!0,this.shadowMapSize=e.shadowMapSize??2048,this.spotShadowMapSize=this.shadowMapSize,this.pointShadowMapSize=e.pointShadowMapSize??1024,this.fallbackMaterial=e.fallbackMaterial??null,this.materialResolver=e.materialResolver,this.fallbackSkinnedMaterial=e.fallbackSkinnedMaterial??new lr({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:il}),this.invokeObjectRenderCallbacks=e.invokeObjectRenderCallbacks??!0,this.state.directionalShadowTextureSize=this.shadowMapSize,this.state.pointShadowTextureSize=this.pointShadowMapSize,this.state.spotShadowTextureSize=this.shadowMapSize,this.sampleCount=dn(e.sampleCount),this.renderScale=sl(e.renderScale),this.hiZOcclusionCullingEnabled=e.hiZOcclusionCulling??!1,this.multiDrawIndirectEnabled=e.multiDrawIndirect??!0,this.dynamicBatchingEnabled=e.dynamicBatching??!0,this.tiledLightingEnabled=e.tiledLighting??!0,this.renderGraphProfilingEnabled=e.renderGraphProfiling??!1}invalidateMaterialResolution(){this.extractionVersion+=1}resolveMaterial(e){if(!1===e?.visible)return null;if(e&&cr(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 i=e.transparent||function(e){if(e.transparent||(e.transmission??0)>0)return!0;if(e instanceof ba)return null!=e.uniforms.hology_depth_map||null!=e.uniforms.hology_scene_map||null!=e.uniforms.hology_transmission_map;if(e instanceof lr)return e.requiresLatePass();return!1}(e)?"late":"opaque",r=this.materialResolver?.(e,i);"opaque"===i&&r?.requiresLatePass()&&(i="late",r=this.materialResolver?.(e,i));const n=void 0===r?this.fallbackMaterial:r;return t?(t.extractionVersion=this.extractionVersion,t.material=n):this.resolvedMaterialFrameCache.set(e,{extractionVersion:this.extractionVersion,material:n}),void 0!==r?r:n}resolveLineMaterial(e){let t=this.lineMaterialCache.get(e);t||(t=new lr({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 let offsetW = offset * clip.w;\n clip = vec4<f32>(clip.x + offsetW.x, clip.y + offsetW.y, clip.z, 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 na(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:aa,depthTest:e.depthTest,depthWrite:e.depthWrite}),this.lineMaterialCache.set(e,t));const i=e,r=i.color;return r&&t.uniforms.color.value.copy(r),t.uniforms.opacity.value=i.opacity??1,t.uniforms.linewidth.value=i.linewidth??1,t.transparent=e.transparent||(i.opacity??1)<1,t.depthTest=e.depthTest,t.depthWrite=e.depthWrite,t}resolveLineBasicMaterial(e,t){let i=this.lineBasicMaterialCache.get(e);i||(i=new Map,this.lineBasicMaterialCache.set(e,i));let r=i.get(t);r||(r=new lr({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 na(1,1,1),opacity:1},primitiveTopology:t,depthTest:e.depthTest,depthWrite:e.depthWrite}),i.set(t,r));const n=e;return n.color&&r.uniforms.color.value.copy(n.color),r.uniforms.opacity.value=n.opacity??1,r.transparent=e.transparent||(n.opacity??1)<1,r.depthTest=e.depthTest,r.depthWrite=e.depthWrite,r}resolveSkinnedMaterial(e){const t=this.resolveMaterial(e);return null===t?null:function(e){const t=rl.get(e);if(t?.version===e.version&&t.shader===e.vertexShader&&t.attributes===e.vertexAttributes)return t.result;const i=e.vertexAttributes.find(e=>"skinIndex"===e.name),r=e.vertexAttributes.find(e=>"skinWeight"===e.name),n=e.vertexShader.includes("USE_SKINNING")||"uint32x4"===i?.format&&"float32x4"===r?.format&&e.vertexShader.includes("rendererSkinPosition(");return rl.set(e,{version:e.version,shader:e.vertexShader,attributes:e.vertexAttributes,result:n}),n}(t)?t:this.fallbackSkinnedMaterial}hasRenderCallbacks(e){return null!==e&&this.invokeObjectRenderCallbacks&&function(e){return null!==e&&(e.onBeforeRender!==rr.prototype.onBeforeRender||e.onAfterRender!==rr.prototype.onAfterRender)}(e)}async initialize(t){if(!("gpu"in navigator))throw new Error("WebGPU is not available in this browser.");const i=t??await navigator.gpu.requestAdapter({powerPreference:this.powerPreference});if(!i)throw new Error("A WebGPU adapter could not be created.");const r=[];i.features.has("indirect-first-instance")&&r.push("indirect-first-instance"),i.features.has("timestamp-query")&&r.push("timestamp-query"),i.features.has("texture-compression-bc")&&r.push("texture-compression-bc"),i.features.has("texture-compression-etc2")&&r.push("texture-compression-etc2"),i.features.has("texture-compression-astc")&&r.push("texture-compression-astc"),i.features.has("float32-filterable")&&r.push("float32-filterable"),i.features.has(Qo)&&r.push(Qo);const l=i.limits;try{this.state.device=await i.requestDevice({requiredFeatures:r,requiredLimits:{maxTextureArrayLayers:l.maxTextureArrayLayers,maxBufferSize:l.maxBufferSize,maxStorageBufferBindingSize:l.maxStorageBufferBindingSize,maxStorageBuffersPerShaderStage:l.maxStorageBuffersPerShaderStage}})}catch(e){throw new Error("A WebGPU device could not be created.")}!function(t){if(e.has(t))return;const i={loadingStartedAt:performance.now(),loadingRequests:[],loading:!0,phase:"initializing",objects:new WeakMap,origins:new Map,descriptorOrigins:new WeakMap,history:new Map};e.set(t,i);for(const e of["createShaderModule","createBindGroupLayout","createPipelineLayout"]){const r=t[e];t[e]=function(s){const o=r.call(t,s);return i.objects.set(o,"createShaderModule"===e?{shaderHash:n(s.code),codeLength:s.code.length}:a(s,i)),o}}for(const e of["createRenderPipeline","createRenderPipelineAsync","createComputePipeline","createComputePipelineAsync"]){const r=t[e];"function"==typeof r&&(t[e]=function(n){const l=i.descriptorOrigins.get(n)??i.origins.get(n.label),c=e.includes("Render")?"render":"compute",u=c+":"+(l?.key??n.label??"unlabelled"),d=a(n,i),h=i.history.get(u)??[],p=JSON.stringify(d);let f;for(let e=h.length-1;e>=0;e--)if(h[e].signature===p){f=h[e];break}const m=f??h[h.length-1],g={signature:p,state:d,origin:l,label:n.label,phase:i.phase,status:"pending"},v=!i.loading,x=v?void 0:{kind:c,signature:p,state:d,shaders:o(d),label:n.label,origin:l,status:"pending",durationMs:0,async:e.endsWith("Async")};x&&i.loadingRequests.push(x);let w=0;v&&console.warn("[WebGPU pipeline] Created after loading",{method:e,label:n.label,phase:i.phase,origin:l,reason:"failed"===f?.status?"retry after a failed creation request":"pending"===f?.status?"identical descriptor requested while prior compilation is pending":f?"identical descriptor requested again; cache miss, eviction, or another owner":m?"new variant or changed shader/layout/render state":"first recorded pipeline for this origin",previous:m?{label:m.label,phase:m.phase,status:m.status,origin:m.origin}:null,changes:m?s(m.state,d):[],originChanges:m?s(m.origin,l):[],descriptor:d,stack:new Error("Pipeline creation request").stack,historyLimit:"last 16 requests per origin; up to 4096 origins"}),h.push(g),h.length>16&&h.shift(),i.history.size>=4096&&!i.history.has(u)&&i.history.delete(i.history.keys().next().value),i.history.set(u,h);const b=(t,i)=>{g.status=t,x&&(x.status=t,x.durationMs=performance.now()-w),v&&console.info("[WebGPU pipeline] Creation result",{method:e,label:n.label,status:t,[e.endsWith("Async")?"readyAfterMs":"creationCallMs"]:performance.now()-w,error:i,timingMeaning:e.endsWith("Async")?"time until pipeline ready":"handle creation only; GPU compilation may stall at first use"})};w=performance.now();try{const i=r.call(t,n);return e.endsWith("Async")?i.then(e=>(b("ready"),e),e=>{throw b("failed",e),e}):(b("handle returned"),i)}catch(e){throw b("failed",e),e}})}}(this.state.device);let c=!1;if("function"==typeof this.state.device.addEventListener&&this.state.device.addEventListener("uncapturederror",e=>{c||(console.error("Uncaptured WebGPU device error",e.error.message,e.error),c=!0)}),this.state.device.lost.then(e=>{"destroyed"!==e.reason&&console.error("WebGPU device lost",e.reason,e.message)}),this.indirectFirstInstanceSupported=r.includes("indirect-first-instance"),this.timestampQuerySupported=r.includes("timestamp-query"),this.multiDrawIndirectSupported=r.includes(Qo),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:416,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:16016,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST});const u=[];u.push(Qn.createAsync(this.state.device,this.state.cameraBuffer,this.state.lightBuffer).then(e=>{this.tiledPointLights=e,e.resize(this.state.width,this.state.height)})),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"}},{binding:9,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float",viewDimension:"2d"}},{binding:11,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"uint",viewDimension:"2d"}}]}),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"}},{binding:10,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float",viewDimension:"2d"}},{binding:11,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"uint",viewDimension:"2d"}}]}),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"}},{binding:9,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float",viewDimension:"2d"}},{binding:11,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"uint",viewDimension:"2d"}}]}),this.state.visibleDepthSceneBindGroupLayout=this.state.device.createBindGroupLayout({label:"renderer-visible-depth-scene-layout",entries:[{binding:0,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}},{binding:1,visibility:GPUShaderStage.VERTEX|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"}}]}),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"}},{binding:2,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"read-only-storage"}}]}),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,u.push(this.directionalShadowGpu.initialize(this.state.device,this.state.directShadowBindGroupLayout)),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.transmissionSampler=this.state.device.createSampler({label:"physical-transmission-sampler",magFilter:"linear",minFilter:"linear",mipmapFilter:"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"}),u.push(_.createAsync(this.state.device,{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"}}]}).then(e=>{this.state.hizCopyKernel=e})),u.push(_.createAsync(this.state.device,{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"}}]}).then(e=>{this.state.hizReduceKernel=e})),u.push(_.createAsync(this.state.device,{label:"renderer-visibility-cull",code:Un,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"}}]}).then(e=>{this.state.visibilityKernel=e})),u.push(_.createAsync(this.state.device,{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 // Bit 2 is persistent detail hysteresis; bit 0 is frame-local visibility.\n atomicStore(&visibleInstanceMask[index], atomicLoad(&visibleInstanceMask[index]) & 4u);\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"}}]}).then(e=>{this.state.staticVisibilityClearKernel=e})),u.push(_.createAsync(this.state.device,{label:"renderer-static-visibility-cull",code:An,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"}},{binding:10,visibility:GPUShaderStage.COMPUTE,buffer:{type:"storage"}},{binding:11,visibility:GPUShaderStage.COMPUTE,buffer:{type:"storage"}}]}).then(e=>{this.state.staticVisibilityCullKernel=e})),u.push(_.createAsync(this.state.device,{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"}}]}).then(e=>{this.state.staticVisibilityIndirectBuildKernel=e})),this.state.visibilityParamsBuffer=this.state.device.createBuffer({label:"renderer-visibility-params-buffer",size:16,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),u.push(this.createStaticPipelines()),await Promise.all(u),this.setSize(this.canvas.clientWidth||this.canvas.width||1,this.canvas.clientHeight||this.canvas.height||1),this.state.initialized=!0}createComputeKernel(e){if(!this.state.device)throw new Error("WebGpuRenderer.initialize() must complete before creating compute kernels.");return new _(this.state.device,e)}getDevice(){return this.state.device??null}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)}setDirectionalShadowMapSize(e){const t=Math.max(1,Math.floor(e));t!==this.shadowMapSize&&(this.shadowMapSize=t,t!==this.state.directionalShadowTextureSize&&(this.state.directionalShadowTextureSize=t,this.recreateDirectionalShadowResources()))}setDirectionalShadowUpdateOptions(e){this.directionalShadowScheduler.setOptions(e)}invalidateDirectionalShadows(){this.directionalShadowScheduler.invalidate()}setDirectionalShadowGpuCullingEnabled(e){this.directionalShadowGpu.enabled=e,this.invalidateDirectionalShadows()}setDirectionalShadowsEnabled(e){this.directionalShadowsEnabled=e}setRenderGraphProfilingEnabled(e){this.renderGraphProfilingEnabled=e,e||xs(this.state)}getRenderGraphProfilingEnabled(){return this.renderGraphProfilingEnabled}getTimestampQuerySupported(){return this.timestampQuerySupported}getSampleCount(){return this.sampleCount}setSampleCount(e){const t=dn(e);t!==this.sampleCount&&(this.sampleCount=t,this.destroyMsaaResources(),this.clearIndirectBundleCache(),this.clearStaticDrawSetBundleCaches())}setRenderScale(e){const t=sl(e);if(t===this.renderScale)return;this.renderScale=t;const i=this.state.pixelRatio;this.setSize(this.state.presentationWidth/i,this.state.presentationHeight/i,i)}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)}setMotionVectorProjection(e){this.motionVectorProjection.copy(e),this.motionVectorProjectionPending=!0}invalidateObjectMotion(e){this.objectMotionHistory.delete(e);const t=this.staticSceneSpatialIndex.getMeshSnapshot(e),i=t&&this.staticMeshDraws.get(t);i&&(i.motionHistory=this.getObjectMotionHistory(e,e.matrixWorld.elements),i.motionFrames=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}resetViewHistory(){this.state.temporalHiZHistoryValid=!1,this.motionVectorHistoryValid=!1,this.motionVectorHistoryGeneration+=1}setHiZOcclusionCullingEnabled(e){this.hiZOcclusionCullingEnabled!==e&&(this.state.temporalHiZHistoryValid=!1),this.hiZOcclusionCullingEnabled=e}getHiZOcclusionCullingEnabled(){return this.hiZOcclusionCullingEnabled}getHiZOcclusionCullingActive(){return this.hiZOcclusionCullingEnabled&&this.indirectFirstInstanceSupported&&this.frameHiZOcclusionCullingNeeded}isStaticDrawSetCameraVisible(e){return null!==this.sceneCaptureOptions||e.cameraVisible}getCameraStaticDrawSets(){return null!==this.sceneCaptureOptions||this.spatialIncludeOffscreen?this.staticDrawSets:this.staticDrawSetManager.cameraCandidates}queryStaticShadowResources(e){return this.staticDrawSetManager.queryShadowResources(e)}updateVisibilityWorkload(e){this.staticDrawSetManager.updateCameraVisibility(this.testSpatialCamera);let t=e.gpuOpaqueDraws.length>=64;for(const e of this.staticDrawSetManager.cameraCandidates){if(!e.publicSet.enabled||"opaque"!==e.drawStage)continue;if(!e.cpuVisibility){t||=e.cameraVisible;continue}const i=e.draws[0],r=i.detailCulling;e.cameraDetailVisible=g(i.boundsCenter,i.boundsRadius,this.cameraViewProjScratch,this.state.width,this.state.height,this.transparentSortCameraPositionScratch,(r?.minScreenSize??0)*(e.cameraDetailVisible?.85:1.15),r?.maxDistance??0,this.cameraDetailProjectionScratch),e.cameraVisible=e.cameraDetailVisible&&an(this.cameraFrustumPlanesScratch,i.boundsCenter.x,i.boundsCenter.y,i.boundsCenter.z,i.boundsRadius)}t!==this.frameHiZOcclusionCullingNeeded&&(this.state.temporalHiZHistoryValid=!1),this.frameHiZOcclusionCullingNeeded=t}setMultiDrawIndirectEnabled(e){this.multiDrawIndirectEnabled=e}getMultiDrawIndirectEnabled(){return this.multiDrawIndirectEnabled}setTiledLightingEnabled(e){this.tiledLightingEnabled=e}setDynamicBatchingEnabled(e){this.dynamicBatchingEnabled=e}getDynamicBatchingEnabled(){return this.dynamicBatchingEnabled}getMultiDrawIndirectSupported(){return this.multiDrawIndirectSupported}getMultiDrawIndirectActive(){return this.multiDrawIndirectEnabled&&this.multiDrawIndirectSupported&&this.getHiZOcclusionCullingActive()}setSize(e,t,i=window.devicePixelRatio||1){if(this.state.pixelRatio=i,this.state.presentationWidth=Math.max(1,Math.floor(e*i)),this.state.presentationHeight=Math.max(1,Math.floor(t*i)),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 i="presentation"===t.resolution?this.state.presentationWidth:this.state.width,r="presentation"===t.resolution?this.state.presentationHeight:this.state.height,n=Math.max(1,Math.floor(i*t.scale)),a=Math.max(1,Math.floor(r*t.scale));t.width===n&&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:D,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:I,usage:GPUTextureUsage.RENDER_ATTACHMENT|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:D,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.invalidateGraphTextureBundles(),this.state.temporalHiZHistoryValid=!1,this.motionVectorHistoryValid=!1,this.motionVectorHistoryGeneration+=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,i=.001*performance.now()){this.renderFrame(e,t,i,!1)}async renderAsync(e,t,i=.001*performance.now()){await this.renderFrame(e,t,i,!0)}createSceneCapture(e,t=512,i=t){const r=this.state.device;if(!r||!this.state.initialized)throw new Error("Renderer is not initialized.");const n=e?.getContext("webgpu");if(e&&!n)throw new Error("The capture canvas does not provide WebGPU.");t=Math.max(1,Math.floor(t)),i=Math.max(1,Math.floor(i)),e&&(e.width=t,e.height=i),n?.configure({device:r,format:this.state.format,alphaMode:"premultiplied"});const a=n?void 0:r.createTexture({label:"scene-capture-output",size:[t,i],format:this.state.format,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING}),s=a?.createView(),o=r.createTexture({label:"scene-capture-color",size:[t,i],format:D,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING}),l=r.createTexture({label:"scene-capture-depth",size:[t,i],format:"depth32float",usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING}),c={colorView:o.createView(),depthView:l.createView(),width:t,height:i},u={drawCallCount:0,triangleCount:0};let d=!1;const h=()=>{d||(d=!0,n?.unconfigure(),a?.destroy(),o.destroy(),l.destroy(),this.sceneCaptureDisposers.delete(h))};return this.sceneCaptureDisposers.add(h),{format:this.state.format,textureView:s,get triangleCount(){return u.triangleCount},prepareAsync:async(e,t,i={})=>{if(d||this.sceneCaptureOptions)throw new Error("Scene capture is unavailable.");if(await this.prepareSceneCaptureAsync(e,t,i),d)throw new Error("Scene capture was disposed during preparation.")},capture:(e,t,i={})=>{if(d||this.sceneCaptureOptions)throw new Error("Scene capture is unavailable.");this.sceneCaptureOptions=i;try{e.matrixWorldAutoUpdate&&e.updateMatrixWorld(),t.updateWorldMatrix(!0,!1);const a=this.extractScene(e,t);this.ensureShadowTextureSizes(a),this.uploadInstanceData(a.instanceData),this.uploadResidentInstanceData(a.residentInstanceUploads),this.ensureTiledLightingSize(),this.state.spotLightMapView||this.updateSpotLightMapAtlas([]),this.updateCameraUniforms(t,e,c),this.updateLightUniforms(a);const o=r.createCommandEncoder({label:"scene-capture-encoder"});u.drawCallCount=0,u.triangleCount=0,this.executeMaterialPass(o,["sceneColor"],this.getSharedSceneBindGroup(),a,u,{clearColor:i.clearColor,overrideMaterial:null==i.overrideMaterial?void 0:(e,t)=>i.overrideMaterial(this.staticDrawSetManager.getSourceMaterial(e),t),objectFilter:e=>i.objectFilter?.(e)??!0},c);const l=s??n.getCurrentTexture().createView();i.postProcess?i.postProcess({device:r,encoder:o,colorView:c.colorView,depthView:c.depthView,sampler:this.state.linearClampSampler,targetView:l,targetFormat:this.state.format,width:c.width,height:c.height,camera:t}):this.executePresentPass(o,c.colorView,l),r.queue.submit([o.finish()]),this.releaseRetiredGeometryResourcesAfterSubmit()}finally{this.sceneCaptureOptions=null}},dispose:h}}async prepareSceneCaptureAsync(e,t,i){const r=[];this.sceneCaptureOptions=i;try{e.matrixWorldAutoUpdate&&e.updateMatrixWorld(),t.updateWorldMatrix(!0,!1);const n=this.extractScene(e,t),a=e=>{if(!this.isSphereVisibleScratch(e.boundsCenter.x,e.boundsCenter.y,e.boundsCenter.z,e.boundsRadius,!0)||e.material.requiresLatePass())return;if(e.sourceRanges?!e.sourceRanges.some(e=>!1!==i.objectFilter?.(e.sourceObject)):!1===i.objectFilter?.(e.sourceObject))return;const t=i.overrideMaterial?i.overrideMaterial(this.staticDrawSetManager.getSourceMaterial(e.material),null!==e.skinning):e.material;t&&r.push({...e,material:t,receiveShadow:!1,materialResource:null})};for(const e of this.getCameraStaticDrawSets())if(e.publicSet.enabled&&"opaque"===e.drawStage)for(const t of e.draws)a(t);for(const e of n.gpuOpaqueDraws)a(e);for(const e of n.directOpaqueDraws)a(e);for(const e of this.staticDrawSets)if(e.publicSet.enabled&&"late"===e.drawStage)for(const t of e.draws)a(t);for(const e of n.transparentDraws)a(e)}finally{this.sceneCaptureOptions=null}const n=Jn(),a=new Set,s=[];for(const e of r){const t=n();t&&await t;const i=null!==e.skinning;this.prepareGeometryVertexBuffers(e.geometry,e.geometryResource,this.getMaterialVertexAttributes(e.material,i),e.instanceStart,e.instanceCount);const r=this.getDrawInstanceAccessMode(e),o=this.drawUsesBatching(e),l=Zr(e),c=`${e.material.uuid}:${r}:${i}:${o}:${l}`;if(a.has(c))continue;a.add(c);const u=this.getMaterialResourceAsync(e.material,r,!1,tl,i,o,1,l);u.catch(()=>{}),s.push(u)}await Promise.all(s)}compile(e,t){this.prepareSceneForCompilation(e,t,!1)}async compileAsync(e,t){this.state.initialized||await this.initialize();const i={startedAt:performance.now(),preparationMs:0,phases:{},drawCount:0,materialRequestCount:0,cpuTotalsMs:{},slowTextureLookups:[],pipelines:[]};this.pipelineCompilationDiagnostics=i;try{await this.prepareSceneGeometryAsync(e,t);const r=this.prepareSceneForCompilation(e,t,!0);i.preparationMs=performance.now()-i.startedAt,await r}finally{this.pipelineCompilationDiagnostics===i&&(this.pipelineCompilationDiagnostics=void 0);const e=performance.now()-i.startedAt,t=i.pipelines,r=[...t].sort((e,t)=>t.durationMs-e.durationMs).slice(0,12);console.info("[WebGPU] Scene compilation",{elapsedMs:Math.round(e),preparationMs:Math.round(i.preparationMs),phasesMs:i.phases,drawCount:i.drawCount,materialRequestCount:i.materialRequestCount,cpuTotalsMs:Object.fromEntries(Object.entries(i.cpuTotalsMs).map(([e,t])=>[e,Math.round(t)])),slowTextureLookups:i.slowTextureLookups.sort((e,t)=>t.durationMs-e.durationMs).slice(0,12).map(e=>({...e,durationMs:Math.round(e.durationMs)})),pipelineCount:t.length,forwardCount:t.filter(e=>"forward"===e.kind).length,depthCount:t.filter(e=>"depth"===e.kind).length,slowestPipelines:r.map(e=>({kind:e.kind,material:e.material,durationMs:Math.round(e.durationMs),vertexCodeLength:e.vertexCodeLength,fragmentCodeLength:e.fragmentCodeLength}))})}}async prepareSceneGeometryAsync(e,t){const i=Jn(),r=[e];for(;r.length;){const e=r.pop();if(!e.visible||!1===this.sceneCaptureOptions?.objectFilter?.(e)||null!==this.sceneCaptureOptions&&!1===e.userData.sceneCapture)continue;e instanceof da&&t.layers.test(e.layers)&&e.geometry?.getAttribute("position")&&(this.getGeometryResource(e.geometry,!0),e instanceof fa&&this.getSkinnedGeometryResource(e));for(let t=e.children.length-1;t>=0;t--)r.push(e.children[t]);const n=i();n&&await n}}createPMREMGenerator(e=20){if(!this.state.device)throw new Error("WebGpuRenderer.initialize() must complete before creating a PMREM generator.");return new Ja({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)}registerStaticSpatialObject(e){return this.staticSceneSpatialIndex.register(e)}disposeStaticDrawSetResource(e){this.staticDrawSetManager.disposeStaticDrawSetResource(e)}renderFrame(e,t,i,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 render().");const n=i-this.lastMotionVectorTimeSeconds;Number.isFinite(this.lastMotionVectorTimeSeconds)&&(!Number.isFinite(n)||n<=0||n>.25)&&(this.motionVectorHistoryValid=!1,this.motionVectorHistoryGeneration+=1),this.lastMotionVectorTimeSeconds=i,this.state.frameTimeSeconds=i,this.staticFrameToken+=1,e.matrixWorldAutoUpdate&&e.updateMatrixWorld(),null===t.parent&&t.matrixWorldAutoUpdate&&t.updateMatrixWorld(),this.opaqueSortMs=0;const a=performance.now(),s=this.extractScene(e,t);this.updateVisibilityWorkload(s);for(const e of s.gpuOpaqueDraws)this.prepareDrawGeometryVertexBuffers(e,!0);for(const e of s.directOpaqueDraws)this.prepareDrawGeometryVertexBuffers(e,!0);for(const e of s.transparentDraws)this.prepareDrawGeometryVertexBuffers(e,!0);this.ensureShadowTextureSizes(s);const o=performance.now()-a;this.renderGraphProfilingEnabled&&(this.opaqueSortSampleTotal-=this.opaqueSortSamples[this.opaqueSortSampleIndex],this.opaqueSortSamples[this.opaqueSortSampleIndex]=this.opaqueSortMs,this.opaqueSortSampleTotal+=this.opaqueSortMs,this.opaqueSortSampleIndex=(this.opaqueSortSampleIndex+1)%this.opaqueSortSamples.length,this.opaqueSortSampleCount=Math.min(this.opaqueSortSampleCount+1,this.opaqueSortSamples.length));const l={drawCallCount:0,triangleCount:0},c=performance.now();this.uploadInstanceData(s.instanceData),this.uploadResidentInstanceData(s.residentInstanceUploads);const u=this.getHiZOcclusionCullingActive();this.uploadDrawMetadata(u?s.gpuOpaqueDraws:[]),this.ensureTiledLightingSize(),this.updateCameraUniforms(t,e),this.updateTemporalVisibilityUniforms(t),this.updateLightUniforms(s);const d=performance.now()-c,h=this.state.device.createCommandEncoder({label:"renderer-command-encoder"}),p=this.state.context.getCurrentTexture().createView(),f=this.getSharedSceneBindGroup(),m=this.getSharedShadowBindGroup();let g=null;const v=this.state.drawMetadataResource;u&&v&&v.count>0&&this.state.hizView&&(this.state.visibilityBindGroup&&this.state.visibilityBindGroupMetadataResource===v||(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:v.metadataBuffer}},{binding:5,resource:{buffer:v.indirectBuffer}}],"renderer-visibility-bind-group"),this.state.visibilityBindGroupMetadataResource=v),g=this.state.visibilityBindGroup),this.renderGraph.reset();const x=this.createGraphBuilderContext(this.renderGraph,h,f,m,g,p,s,l);this.graphBuilder(this.renderGraph,x);const w={device:this.state.device,encoder:h},b=function(e,t,i,r,n){if(!t.renderGraphProfilingEnabled||!e.device)return null;let a=ms.get(e);a&&a.device===e.device||(a?.dispose(),a=new fs(e.device),ms.set(e,a));const s=a,o={frameIndex:e.frameIndex+=1,renderWidth:e.width,renderHeight:e.height,presentationWidth:e.presentationWidth,presentationHeight:e.presentationHeight,cpuTimeMs:0,gpuTimeMs:null,drawCallCount:r.drawCallCount,triangleCount:r.triangleCount,cpuPhases:{extractSceneMs:n.extractSceneMs,opaqueSortMs:n.opaqueSortMs,opaqueSortAverageMs:n.opaqueSortAverageMs,uploadMs:n.uploadMs,renderGraphMs:0},passes:[],timestampQuerySupported:t.timestampQuerySupported,timestampQueryActive:t.timestampQuerySupported,gpuProfilingReason:null,hiZOcclusionCullingEnabled:t.hiZOcclusionCullingEnabled,hiZOcclusionCullingActive:i,visibility:null};let l=null,c=0,u=0;const d={begin:(e,i)=>{if(o.passes=e.map(e=>({name:e.name,cpuTimeMs:0,gpuTimeMs:null})),!t.timestampQuerySupported)return o.timestampQueryActive=!1,void(o.gpuProfilingReason="timestamp-query is not supported by this adapter/device");if(0===e.length)return o.timestampQueryActive=!1,void(o.gpuProfilingReason="no render graph passes were recorded");const r=2*e.length,n=s.acquire(r,!0);if(!n)return vs.add(h),o.timestampQueryActive=!1,void(o.gpuProfilingReason="GPU profiling readbacks are still pending");l={profile:o,querySet:n.querySet,resolveBuffer:n.resolveBuffer,readBuffer:n.readBuffer,queryCount:r,release:e=>s.release(n,e)}},beforePass:(e,t,i)=>{c=r.triangleCount,u=r.drawCallCount,l&&0===t&&(Tr(i.encoder,l.querySet,{endOfPassWriteIndex:2*t})||(o.timestampQueryActive=!1,o.gpuProfilingReason="timestampWrites marker pass is not available on this browser/runtime",l.release(!1),l=null))},afterPass:(e,t,i,n)=>{o.passes[t].cpuTimeMs=i,o.passes[t].triangleCount=r.triangleCount-c,o.passes[t].drawCallCount=r.drawCallCount-u,l&&(Tr(n.encoder,l.querySet,{beginningOfPassWriteIndex:2*t+1,...t+1<o.passes.length?{endOfPassWriteIndex:2*t+2}:{}})||(o.timestampQueryActive=!1,o.gpuProfilingReason="timestampWrites marker pass is not available on this browser/runtime",l.release(!1),l=null))},end:(t,i,n)=>{if(!vs.has(h)){if(o.cpuPhases.renderGraphMs=i,o.cpuTimeMs=o.cpuPhases.extractSceneMs+o.cpuPhases.uploadMs+o.cpuPhases.renderGraphMs,o.drawCallCount=r.drawCallCount,o.triangleCount=r.triangleCount,o.directionalShadows={updatedLayers:r.directionalShadowUpdates??0,reusedLayers:r.directionalShadowReused??0,forcedLayers:r.directionalShadowForced??0,updateMask:r.directionalShadowUpdateMask??0,gpuIndirectDraws:r.directionalShadowGpuDraws??0},!l){const t=Ss(o);return e.latestFrameProfile=t,void(e.latestCompletedFrameProfile=t)}n.encoder.resolveQuerySet(l.querySet,0,l.queryCount,l.resolveBuffer,0),n.encoder.copyBufferToBuffer(l.resolveBuffer,0,l.readBuffer,0,8*l.queryCount),e.latestFrameProfile=Ss(o)}}},h={profile:o,observer:d,pendingVisibilityRead:null,get pendingGpuRead(){return l},set pendingGpuRead(e){l=e}};return gs.set(h,s),h}(this.state,{renderGraphProfilingEnabled:this.renderGraphProfilingEnabled,timestampQuerySupported:this.timestampQuerySupported,hiZOcclusionCullingEnabled:this.hiZOcclusionCullingEnabled},u,l,{extractSceneMs:o,opaqueSortMs:this.opaqueSortMs,opaqueSortAverageMs:this.opaqueSortSampleTotal/Math.max(1,this.opaqueSortSampleCount),uploadMs:d}),y=()=>{if(!b||!u)return;const e=[];v&&v.count>0&&e.push({buffer:v.indirectBuffer,drawCount:v.count,totalInstances:s.gpuOpaqueDraws.reduce((e,t)=>e+Math.max(0,t.instanceCount),0),kind:"dynamic"});for(const t of this.getCameraStaticDrawSets())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,i,r){if(vs.has(e))return;const n=r.filter(e=>e.drawCount>0);if(0===n.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=n.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=gs.get(e),l=o?.acquire(a,!1);if(o&&!l)return;const c=l?.readBuffer??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<n.length;e+=1){const t=n[e];i.copyBufferToBuffer(t.buffer,0,c,s[e].byteOffset,5*t.drawCount*Uint32Array.BYTES_PER_ELEMENT)}e.pendingVisibilityRead={readBuffer:c,regions:s,release:l&&o?e=>o.release(l,e):void 0}}(b,this.state.device,h,e)};if(r)return this.renderGraph.executeAsync(w,b?.observer).then(()=>{y(),null==this.nativePostSubmit&&this.recordPresentationOverlay(h,p),this.state.device.queue.submit([h.finish()]),this.nativePostSubmit?.({device:this.state.device,presentationView:p,presentationWidth:this.state.presentationWidth,presentationHeight:this.state.presentationHeight,present:e=>{const t=this.state.device.createCommandEncoder({label:"native-present-encoder"});this.executePresentPass(t,e,p),this.recordPresentationOverlay(t,p),this.state.device.queue.submit([t.finish()])}}),this.commitTemporalHiZHistory(),this.releaseRetiredGeometryResourcesAfterSubmit(),b&&ws(this.state,b)});this.renderGraph.execute(w,b?.observer),y(),null==this.nativePostSubmit&&this.recordPresentationOverlay(h,p),this.state.device.queue.submit([h.finish()]),this.nativePostSubmit?.({device:this.state.device,presentationView:p,presentationWidth:this.state.presentationWidth,presentationHeight:this.state.presentationHeight,present:e=>{const t=this.state.device.createCommandEncoder({label:"native-present-encoder"});this.executePresentPass(t,e,p),this.recordPresentationOverlay(t,p),this.state.device.queue.submit([t.finish()])}}),this.commitTemporalHiZHistory(),this.releaseRetiredGeometryResourcesAfterSubmit(),b&&ws(this.state,b)}recordPresentationOverlay(e,t){if(null==this.presentationOverlay)return;const i=this.presentationOverlayContext;i.device=this.state.device,i.encoder=e,i.targetView=t,i.targetFormat=this.state.format,i.presentationWidth=this.state.presentationWidth,i.presentationHeight=this.state.presentationHeight,this.presentationOverlay(i)}renderPresentationOnly(){const{device:e,context:t}=this.state;if(!e||!t)throw new Error("Renderer is not initialized.");const i=t.getCurrentTexture().createView(),r=e.createCommandEncoder({label:"application-presentation-encoder"});r.beginRenderPass({colorAttachments:[{view:i,loadOp:"clear",storeOp:"store",clearValue:{r:0,g:0,b:0,a:1}}]}).end(),this.recordPresentationOverlay(r,i),e.queue.submit([r.finish()])}destroy(){this.sharedVertexAttributeLayouts.clear(),this.staticSceneSpatialIndex.dispose(),this.staticInstanceSlots.dispose(),this.retiredStaticInstanceSlots.length=0;for(const e of this.sceneCaptureDisposers)e();xs(this.state),this.directionalShadowGpu.dispose();for(const e of this.repeatedInstanceResources.values())e();this.skeletonPalettes.dispose(),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.skinnedRenderRecords.keys())this.releaseSkinnedRenderRecord(e);this.skinnedInstanceSlots.dispose();for(const e of this.skinnedGeometryCache.values())e.skinning.releaseInstance(),e.skinning.bindUniformBuffer.destroy();this.skinnedGeometryCache.clear();for(const e of this.skinPaletteResources)e.releaseExternal?.(),e.standaloneBuffer?.destroy();this.skinPaletteResources.clear(),this.skinningPaletteArena?.dispose(),this.skinningPaletteArena=void 0;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.transmissionSnapshotTexture?.destroy(),this.transmissionSnapshotTexture=null,this.state.sceneDepthSnapshotTexture?.destroy(),this.state.postProcessColorTexture?.destroy(),this.directionalShadowScheduler.invalidate(),this.state.directionalShadowTexture?.destroy(),this.state.pointShadowTexture?.destroy(),this.state.pointShadowDepthTexture?.destroy(),this.state.spotShadowTexture?.destroy(),this.state.spotLightMapTexture?.destroy(),this.state.hizTexture?.destroy(),this.state.cameraBuffer?.destroy(),this.state.temporalVisibilityBuffer?.destroy(),this.state.lightBuffer?.destroy(),this.tiledPointLights?.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.defaultVertexAttributeBuffers.values())for(const t of e.values())t.destroy();this.defaultVertexAttributeBuffers.clear(),this.state.visibilityParamsBuffer?.destroy(),this.state.drawMetadataResource?.metadataBuffer.destroy(),this.state.drawMetadataResource?.indirectBuffer.destroy(),this.state.drawMetadataResource?.postIndirectBuffer.destroy(),this.state.initialized=!1;const e=this.state.device?.destroy;"function"==typeof e&&e.call(this.state.device),this.state.device=null}async 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=[],t=this.state.device.createPipelineLayout({label:"renderer-depth-prepass-layout",bindGroupLayouts:[this.state.sceneBindGroupLayout]});e.push(W(this.state.device,{label:"renderer-depth-prepass-pipeline",layout:t,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 previousModel0: vec4<f32>,\n previousModel1: vec4<f32>,\n previousModel2: vec4<f32>,\n previousModel3: 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) @invariant 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"}}).then(e=>{this.state.depthPrepassPipeline=e}));const i=this.state.device.createPipelineLayout({label:"renderer-depth-prepass-visible-layout",bindGroupLayouts:[this.state.visibleDepthSceneBindGroupLayout]});e.push(W(this.state.device,{label:"renderer-depth-prepass-visible-pipeline",layout:i,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 previousModel0: vec4<f32>,\n previousModel1: vec4<f32>,\n previousModel2: vec4<f32>,\n previousModel3: 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) @invariant 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"}}).then(e=>{this.state.depthPrepassPipelineVisible=e}));const r=this.state.device.createPipelineLayout({label:"renderer-depth-prepass-direct-layout",bindGroupLayouts:[this.state.directSceneBindGroupLayout]});e.push(W(this.state.device,{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) @invariant 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"}}).then(e=>{this.state.depthPrepassPipelineDirect=e}));const n=this.state.device.createPipelineLayout({label:"renderer-skinned-depth-prepass-layout",bindGroupLayouts:[this.state.sceneBindGroupLayout,this.state.emptyBindGroupLayout,this.state.skinningBindGroupLayout]});e.push(W(this.state.device,{label:"renderer-skinned-depth-prepass-pipeline",layout:n,vertex:{module:this.state.device.createShaderModule({label:"renderer-skinned-depth-prepass-module",code:jn}),entryPoint:"vsMain",buffers:this.createVertexBufferLayouts(L)},primitive:{topology:"triangle-list",cullMode:"back",frontFace:"ccw"},depthStencil:{format:"depth32float",depthWriteEnabled:!0,depthCompare:"less"}}).then(e=>{this.state.skinnedDepthPrepassPipeline=e}));const a=this.state.device.createPipelineLayout({label:"renderer-shadow-layout",bindGroupLayouts:[this.state.shadowBindGroupLayout]}),s=this.state.device.createPipelineLayout({label:"renderer-direct-shadow-pipeline-layout",bindGroupLayouts:[this.state.directShadowBindGroupLayout]});e.push(W(this.state.device,{label:"renderer-directional-shadow-pipeline",layout:a,vertex:{module:this.state.device.createShaderModule({label:"renderer-directional-shadow-module",code:kn}),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",depthBias:1,depthBiasSlopeScale:2,depthBiasClamp:0}}).then(e=>{this.state.shadowDepthPipeline=e})),e.push(W(this.state.device,{label:"renderer-directional-shadow-direct-pipeline",layout:s,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:"back",frontFace:"ccw"},depthStencil:{format:"depth32float",depthWriteEnabled:!0,depthCompare:"less",depthBias:1,depthBiasSlopeScale:2,depthBiasClamp:0}}).then(e=>{this.state.shadowDepthPipelineDirect=e}));const o=this.state.device.createPipelineLayout({label:"renderer-skinned-shadow-layout",bindGroupLayouts:[this.state.shadowBindGroupLayout,this.state.emptyBindGroupLayout,this.state.skinningBindGroupLayout]});e.push(W(this.state.device,{label:"renderer-skinned-directional-shadow-pipeline",layout:o,vertex:{module:this.state.device.createShaderModule({label:"renderer-skinned-directional-shadow-module",code:$n}),entryPoint:"vsMain",buffers:this.createVertexBufferLayouts(L)},primitive:{topology:"triangle-list",cullMode:"back",frontFace:"ccw"},depthStencil:{format:"depth32float",depthWriteEnabled:!0,depthCompare:"less",depthBias:1,depthBiasSlopeScale:2,depthBiasClamp:0}}).then(e=>{this.state.skinnedShadowDepthPipeline=e})),e.push(W(this.state.device,{label:"renderer-point-shadow-pipeline",layout:a,vertex:{module:this.state.device.createShaderModule({label:"renderer-point-shadow-module",code:Fn}),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:Fn}),entryPoint:"fsMain",targets:[{format:"rgba16float"}]},primitive:{topology:"triangle-list",cullMode:"back",frontFace:"ccw"},depthStencil:{format:"depth32float",depthWriteEnabled:!0,depthCompare:"less"}}).then(e=>{this.state.pointShadowPipeline=e})),e.push(W(this.state.device,{label:"renderer-point-shadow-direct-pipeline",layout:s,vertex:{module:this.state.device.createShaderModule({label:"renderer-point-shadow-direct-module",code:On}),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:On}),entryPoint:"fsMain",targets:[{format:"rgba16float"}]},primitive:{topology:"triangle-list",cullMode:"back",frontFace:"ccw"},depthStencil:{format:"depth32float",depthWriteEnabled:!0,depthCompare:"less"}}).then(e=>{this.state.pointShadowPipelineDirect=e})),e.push(W(this.state.device,{label:"renderer-skinned-point-shadow-pipeline",layout:o,vertex:{module:this.state.device.createShaderModule({label:"renderer-skinned-point-shadow-module",code:Wn}),entryPoint:"vsMain",buffers:this.createVertexBufferLayouts(L)},fragment:{module:this.state.device.createShaderModule({label:"renderer-skinned-point-shadow-fragment-module",code:Wn}),entryPoint:"fsMain",targets:[{format:"rgba16float"}]},primitive:{topology:"triangle-list",cullMode:"back",frontFace:"ccw"},depthStencil:{format:"depth32float",depthWriteEnabled:!0,depthCompare:"less"}}).then(e=>{this.state.skinnedPointShadowPipeline=e}));const l=this.state.device.createPipelineLayout({label:"renderer-present-layout",bindGroupLayouts:[this.state.fullscreenTextureBindGroupLayout]});e.push(W(this.state.device,{label:"renderer-present-pipeline",layout:l,vertex:{module:this.state.device.createShaderModule({label:"renderer-present-module",code:Nn}),entryPoint:"vsMain"},fragment:{module:this.state.device.createShaderModule({label:"renderer-present-fragment-module",code:Nn}),entryPoint:"fsMain",targets:[{format:this.state.format}]},primitive:{topology:"triangle-list"}}).then(e=>{this.state.presentPipeline=e}));const c=this.state.device.createShaderModule({label:"renderer-scene-color-snapshot-module",code:Hn});e.push(W(this.state.device,{label:"renderer-scene-color-snapshot-pipeline",layout:l,vertex:{module:c,entryPoint:"vsMain"},fragment:{module:c,entryPoint:"fsMain",targets:[{format:I}]},primitive:{topology:"triangle-list"}}).then(e=>{this.state.sceneColorSnapshotPipeline=e}));const u=this.state.device.createShaderModule({label:"physical-transmission-snapshot-module",code:qn});e.push(W(this.state.device,{label:"physical-transmission-snapshot-pipeline",layout:l,vertex:{module:u,entryPoint:"vsMain"},fragment:{module:u,entryPoint:"fsMain",targets:[{format:D}]},primitive:{topology:"triangle-list"}}).then(e=>{this.transmissionSnapshotPipeline=e})),await Promise.all(e)}ensureTransmissionSnapshot(){if(this.transmissionSnapshotTexture&&this.transmissionSnapshotSize.width===this.state.width&&this.transmissionSnapshotSize.height===this.state.height)return;this.transmissionSnapshotTexture?.destroy(),this.transmissionSnapshotSize.width=this.state.width,this.transmissionSnapshotSize.height=this.state.height;const e=1+Math.floor(Math.log2(Math.max(this.state.width,this.state.height)));this.transmissionSnapshotTexture=this.state.device.createTexture({label:"physical-transmission-snapshot",size:this.transmissionSnapshotSize,format:D,mipLevelCount:e,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING}),this.transmissionSnapshotView=this.transmissionSnapshotTexture.createView(),this.transmissionMipViews=[],this.transmissionMipBindGroups=[],this.transmissionSourceBindGroups=new WeakMap;for(let t=0;t<e;t++)this.transmissionMipViews.push(this.transmissionSnapshotTexture.createView({baseMipLevel:t,mipLevelCount:1})),t>0&&this.transmissionMipBindGroups.push(this.state.device.createBindGroup({layout:this.state.fullscreenTextureBindGroupLayout,entries:[{binding:0,resource:this.transmissionSampler},{binding:1,resource:this.transmissionMipViews[t-1]}]}));this.invalidateGraphTextureBundles()}copyTransmissionSnapshot(e,t){let i=this.transmissionSourceBindGroups.get(t);i||(i=this.state.device.createBindGroup({layout:this.state.fullscreenTextureBindGroupLayout,entries:[{binding:0,resource:this.transmissionSampler},{binding:1,resource:t}]}),this.transmissionSourceBindGroups.set(t,i));for(let t=0;t<this.transmissionMipViews.length;t++){const r=e.beginRenderPass({label:"physical-transmission-snapshot-mip",colorAttachments:[{view:this.transmissionMipViews[t],loadOp:"clear",storeOp:"store",clearValue:{r:0,g:0,b:0,a:1}}]});r.setPipeline(this.transmissionSnapshotPipeline),r.setBindGroup(0,0===t?i:this.transmissionMipBindGroups[t-1]),r.draw(3),r.end()}}recreateShadowResources(){if(this.state.device){this.recreateDirectionalShadowResources(),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}))}}recreateDirectionalShadowResources(){if(this.state.device){this.state.residentSceneBindGroupVersion+=1,this.state.sharedSceneBindGroup=null,this.clearIndirectBundleCache(),this.clearStaticDrawSetBundleCaches(),this.directionalShadowScheduler.invalidate(),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}))}}ensureShadowTextureSizes(e){let t=this.shadowMapSize;for(const i of e.lights.directionals)t=Math.max(t,Math.ceil(i.shadowMapSize));let i=this.pointShadowMapSize;for(const t of e.lights.points)i=Math.max(i,Math.ceil(t.shadowMapSize));let r=this.spotShadowMapSize;for(const t of e.lights.spots)r=Math.max(r,Math.ceil(t.shadowMapSize));t===this.state.directionalShadowTextureSize&&i===this.state.pointShadowTextureSize&&r===this.state.spotShadowTextureSize||(this.state.directionalShadowTextureSize=t,this.state.pointShadowTextureSize=i,this.state.spotShadowTextureSize=r,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 i=t.scale??1,r=t.resolution??"render",n=t.format??D,a="presentation"===r?this.state.presentationWidth:this.state.width,s="presentation"===r?this.state.presentationHeight:this.state.height,o=Math.max(1,Math.floor(a*i)),l=Math.max(1,Math.floor(s*i)),c=this.colorTargetCache.get(e);if(c&&c.format===n&&c.width===o&&c.height===l&&c.scale===i&&c.resolution===r)return c;c?.texture.destroy();const u=this.state.device.createTexture({label:`renderer-color-target-${e}`,size:{width:o,height:l},format:n,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_SRC}),d={name:e,format:n,width:o,height:l,scale:i,resolution:r,texture:u,view:u.createView()};return this.colorTargetCache.set(e,d),this.invalidateGraphTextureBundles(),d}ensureMsaaColorTarget(e){if(!this.state.device)throw new Error("Renderer is not initialized.");const t=this.getColorTargetDimensions(e),i=this.getColorTargetFormat(e),r=this.msaaColorTargetCache.get(e);if(r&&r.format===i&&r.width===t.width&&r.height===t.height&&1===r.scale)return r;r?.texture.destroy();const n=this.state.device.createTexture({label:`renderer-msaa-color-target-${e}`,size:{width:t.width,height:t.height},sampleCount:this.sampleCount,format:i,usage:GPUTextureUsage.RENDER_ATTACHMENT}),a={name:e,format:i,width:t.width,height:t.height,scale:1,texture:n,view:n.createView()};return this.msaaColorTargetCache.set(e,a),a}ensureMsaaDepthTarget(e,t){if(!this.state.device)throw new Error("Renderer is not initialized.");const i=`${e}x${t}`,r=this.msaaDepthTargetCache.get(i);if(r&&r.width===e&&r.height===t&&r.sampleCount===this.sampleCount)return r;r?.texture.destroy();const n=this.state.device.createTexture({label:`renderer-msaa-depth-${i}`,size:{width:e,height:t},sampleCount:this.sampleCount,format:"depth32float",usage:GPUTextureUsage.RENDER_ATTACHMENT}),a={width:e,height:t,sampleCount:this.sampleCount,texture:n,view:n.createView()};return this.msaaDepthTargetCache.set(i,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 i=t.scale??1,r=t.resolution??"render",n="presentation"===r?this.state.presentationWidth:this.state.width,a="presentation"===r?this.state.presentationHeight:this.state.height,s=Math.max(1,Math.floor(n*i)),o=Math.max(1,Math.floor(a*i)),l=Math.max(1,t.depthOrArrayLayers??1),c=t.format??D,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===r&&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:i,resolution:r,dimension:d,depthOrArrayLayers:l,usage:h,texture:p,view:p.createView({dimension:d})};return this.colorTargetCache.set(e,f),this.invalidateGraphTextureBundles(),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 D;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 i=e.getGraphTextureInputs(),r=[];for(const e in i){const t=i[e].resource;r.includes(t)||r.push(t)}return this.materialGraphTextureReadCache.set(e,{materialVersion:e.version,resources:r}),r}createGraphBuilderContext(e,t,i,r,n,a,s,o,l){let c=!1;const u=()=>{c||(c=!0,e.addPass(new ps("TiledPointLightsPass",()=>{this.tiledLightingEnabled&&s.lights.points.length>0&&this.tiledPointLights.execute(t)},{writes:["tiledPointLights"]})))};let d=!1,h=!1;const p=e=>{const t=new Set;for(let i=0;i<e.length;i+=1){const r=this.getMaterialGraphTextureReads(e[i].material);for(let e=0;e<r.length;e+=1)t.add(r[e])}return Array.from(t)},f={device:this.state.device,encoder:t,camera:s.camera,sceneColorView:this.state.sceneColorView,postProcessColorView:this.state.postProcessColorView,presentationColorView:a,depthView:this.state.mainDepthView,colorFormat:D,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}},getGeometryVertexBuffer:(e,t)=>this.getGeometryResource(e)[t],getSkeletonBoneBuffer:this.getSkeletonBoneBufferForPass,getSkeletonBoneBinding:this.getSkeletonBoneBindingForPass,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:Math.min(4,s.lights.points.length),activeLayerCount:6*Math.min(4,s.lights.points.length)},spot:{view:this.state.spotShadowView,size:this.state.spotShadowTextureSize,layerCount:4,activeLightCount:Math.min(4,s.lights.spots.length),activeLayerCount:Math.min(4,s.lights.spots.length)}}),getSceneLightingResources:()=>{if(!(this.state.cameraBuffer&&this.state.lightBuffer&&this.state.shadowComparisonSampler&&this.state.linearClampSampler&&this.state.directionalShadowView&&this.state.pointShadowArrayView&&this.state.spotShadowView&&this.state.spotLightMapView))throw new Error("Renderer scene lighting resources are not initialized.");return{cameraBuffer:this.state.cameraBuffer,lightBuffer:this.state.lightBuffer,shadowSampler:this.state.shadowComparisonSampler,linearSampler:this.state.linearClampSampler,directionalShadowView:this.state.directionalShadowView,pointShadowView:this.state.pointShadowArrayView,spotShadowView:this.state.spotShadowView,spotLightMapView:this.state.spotLightMapView}}};return{fogVolumeObjects:s.fogVolumeObjects,extractedLights:s.lights,addDirectionalShadowPass:()=>{e.addPass(new ps("DirectionalShadowPass",()=>{this.executeDirectionalShadowPass(t,r,s,o)},{writes:["directionalShadow"]}))},addPointShadowPass:()=>{s.lights.points.some(e=>e.castShadow)&&e.addPass(new ps("PointShadowPass",()=>{this.executePointShadowPass(t,r,s,o)},{writes:["pointShadow"]}))},addSpotShadowPass:()=>{s.lights.spots.some(e=>e.castShadow)&&e.addPass(new ps("SpotShadowPass",()=>{this.executeSpotShadowPass(t,r,s,o)},{writes:["spotShadow"]}))},addDepthPrepass:()=>{d=!0,this.getHiZOcclusionCullingActive()&&this.hasEnabledStaticDrawSets()&&e.addPass(new ps("TemporalStaticVisibilityPrepass",()=>{this.executeStaticVisibilityPasses(t,"prepass")},{reads:["hiz"],writes:["staticIndirectArgs"]})),e.addPass(new ps("DepthPrepass",()=>{this.executeDepthPrepass(t,i,s,o)},{writes:["mainDepth"]}))},addHiZPasses:()=>{this.getHiZOcclusionCullingActive()&&e.addPass(new ps("HiZPasses",()=>{this.executeHiZPasses(t)},{reads:["mainDepth"],writes:["hiz"]}))},addVisibilityPass:()=>{this.getHiZOcclusionCullingActive()&&(n||this.hasEnabledStaticDrawSets())&&(e.addPass(new ps("VisibilityPass",()=>{n&&this.executeVisibilityPass(t,n),this.executeStaticVisibilityPasses(t,"postpass")},{reads:["hiz"],writes:["indirectArgs","staticIndirectArgs"]})),this.sampleCount>1&&this.hasEnabledStaticDrawSets()&&e.addPass(new ps("TemporalStaticDepthResolvePass",()=>{this.executeStaticTemporalDepthResolvePass(t)},{reads:["staticIndirectArgs"],writes:["mainDepth"]})))},defineColorTarget:(e,t={})=>{this.ensureColorTarget(e,t)},defineTextureTarget:(e,t={})=>{this.ensureTextureTarget(e,t)},addForwardPass:(r="sceneColor")=>{u();const n=!d,a=[...s.gpuOpaqueDraws,...s.directOpaqueDraws,...s.transparentDraws],c=p(a);if(l?.push({draws:a,colorTargetFormats:[this.getColorTargetFormat(r)],sampleCount:this.sampleCount,staticDrawStage:"all"}),c.includes("mainDepth")){if(!d)throw new Error("Materials that sample mainDepth require a depth prepass.");e.addPass(new ps("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"]})),h=!0}e.addPass(new ps("ForwardPass",()=>{this.executeForwardPass(t,r,this.getColorTargetView(r),i,s,o,n)},{reads:["tiledPointLights","directionalShadow","pointShadow","spotShadow","mainDepth","indirectArgs",...c.map(e=>"mainDepth"===e?"sceneDepthSnapshot":e)],writes:[r]})),this.getHiZOcclusionCullingActive()&&this.hasEnabledStaticDrawSets()&&e.addPass(new ps("TemporalHiZHistoryPass",()=>{this.executeHiZPasses(t,!0)},{reads:["mainDepth"],writes:["hiz"],dependsOn:["ForwardPass"]}))},addOpaquePass:(r="sceneColor")=>{u();const n=!d,a=[...s.gpuOpaqueDraws,...s.directOpaqueDraws],c=p(a);if(l?.push({draws:a,colorTargetFormats:[this.getColorTargetFormat(r)],sampleCount:this.sampleCount,staticDrawStage:"opaque"}),c.includes("mainDepth")){if(!d)throw new Error("Materials that sample mainDepth require a depth prepass.");e.addPass(new ps("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"]})),h=!0}e.addPass(new ps("OpaquePass",()=>{this.executeForwardPass(t,r,this.getColorTargetView(r),i,s,o,n,"opaque")},{reads:["tiledPointLights","directionalShadow","pointShadow","spotShadow","mainDepth","indirectArgs",...c.map(e=>"mainDepth"===e?"sceneDepthSnapshot":e)],writes:[r]}))},addSceneTextureCopyPass:(i="sceneColor",r)=>{const n=this.getCameraStaticDrawSets().filter(e=>e.publicSet.enabled&&"late"===e.drawStage).flatMap(e=>e.draws),a=[...s.transparentDraws,...n],o=p(a),l=o.includes("physicalTransmissionSnapshot");l&&this.ensureTransmissionSnapshot();const c=!0===r?.sceneColor||a.some(e=>e.material.usesSceneColor()),u=!0===r?.sceneDepth||a.some(e=>e.material.usesSceneDepth()),d=o.includes("mainDepth");if(!(l||c||u||d))return;const f=this.getColorTargetDimensions(i);if(f.width!==this.state.width||f.height!==this.state.height||this.getColorTargetFormat(i)!==D)throw new Error("Scene texture snapshots currently require a full-resolution rgba16float source.");e.addPass(new ps("SceneTextureCopyPass",()=>{if(l&&this.copyTransmissionSnapshot(t,this.getColorTargetView(i)),c){const e=this.getColorTargetView(i);let r=this.state.sceneColorSnapshotBindGroups.get(e);r||(r=this.state.device.createBindGroup({label:"renderer-scene-color-snapshot-bind-group",layout:this.state.fullscreenTextureBindGroupLayout,entries:[{binding:0,resource:this.state.linearClampSampler},{binding:1,resource:e}]}),this.state.sceneColorSnapshotBindGroups.set(e,r));const n=t.beginRenderPass({label:"renderer-scene-color-snapshot-pass",colorAttachments:[{view:this.state.sceneColorSnapshotView,loadOp:"clear",storeOp:"store",clearValue:{r:0,g:0,b:0,a:0}}]});n.setPipeline(this.state.sceneColorSnapshotPipeline),n.setBindGroup(0,r),n.draw(3),n.end()}u&&this.executeHiZPasses(t,!1,!0),d&&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:[...c||l?[i]:[],...u||d?["mainDepth"]:[]],writes:[...c?["sceneColorSnapshot"]:[],...l?["physicalTransmissionSnapshot"]:[],...u||d?["sceneDepthSnapshot"]:[]]})),(u||d)&&(h=!0)},addLatePass:(r="sceneColor")=>{const n=this.getCameraStaticDrawSets().filter(e=>e.publicSet.enabled&&"late"===e.drawStage).flatMap(e=>e.draws);if(0===s.transparentDraws.length&&0===n.length)return;l?.push({draws:s.transparentDraws,colorTargetFormats:[this.getColorTargetFormat(r)],sampleCount:1,staticDrawStage:"late"});const a=[...s.transparentDraws,...n],c=[r,"mainDepth",...p(a)];a.some(e=>e.material.usesSceneColor())&&c.push("sceneColorSnapshot"),a.some(e=>e.material.usesSceneDepth())&&c.push("sceneDepthSnapshot"),e.addPass(new ps("LatePass",()=>{this.executeForwardPass(t,r,this.getColorTargetView(r),i,s,o,!1,"late",!0,1)},{reads:c,writes:[r,"mainDepth"]}))},addHiZHistoryPass:(i="ForwardPass")=>{if(!this.getHiZOcclusionCullingActive()||!this.hasEnabledStaticDrawSets())return;const r="LatePass"===i&&0===s.transparentDraws.length?"OpaquePass":i;e.addPass(new ps("TemporalHiZHistoryPass",()=>{this.executeHiZPasses(t,!0)},{reads:["mainDepth"],writes:["hiz"],dependsOn:[r]}))},addMaterialPass:(r={})=>{u();const n="string"==typeof r.outputs?[r.outputs]:Array.from(r.outputs??["sceneColor"]);if(l){const e=r.drawStage??"all",t="opaque"===e?[...s.gpuOpaqueDraws,...s.directOpaqueDraws]:"late"===e?s.transparentDraws:[...s.gpuOpaqueDraws,...s.directOpaqueDraws,...s.transparentDraws],i=r.objectFilter?t.filter(e=>r.objectFilter(e.sourceObject)||!0===e.sourceRanges?.some(e=>r.objectFilter(e.sourceObject))):t,a=e=>"function"==typeof r.overrideMaterial?r.overrideMaterial(e.material,null!==e.skinning):r.overrideMaterial,o=r.overrideMaterial?i.flatMap(e=>{const t=a(e);return null==t?[]:[{...e,material:t}]}):i;l.push({draws:o,colorTargetFormats:n.map(e=>this.getColorTargetFormat(e)),sampleCount:this.sampleCount,staticDrawStage:e})}const a=r.drawStage??"all";e.addPass(new ps(r.name??"MaterialPass",()=>{this.executeMaterialPass(t,n,i,s,o,r)},{dependsOn:r.dependsOn,reads:["tiledPointLights","directionalShadow","pointShadow","spotShadow",..."late"!==a?["indirectArgs","staticIndirectArgs"]:[],...r.loadDepth?["mainDepth"]:[],...r.loadColor?n:[]],writes:this.sampleCount>1?n:[...n,"mainDepth"]}))},addCustomPass:t=>{e.addPass(new ps(t.name,()=>{t.execute(f)},{reads:t.reads,writes:t.writes,dependsOn:t.dependsOn}))},addPresentPass:(i="sceneColor")=>{e.addPass(new ps("PresentPass",()=>{const e=this.getColorTargetView(i);this.executePresentPass(t,e,a)},{reads:[i],writes:["mainColor"]}))}}}transparentDraws=[];opaqueBatches=new Map;acquireDrawCall(){const e=this.drawCallPoolCount;this.drawCallPoolCount+=1;let t=this.drawCallPool[e];return t||(t=this.createDrawCall(),this.drawCallPool[e]=t),t}createDrawCall(){return{geometry:null,geometryKey:{},geometryResource:null,material:null,customDepthMaterial:null,residentInstanceBinding:null,sourceObject:null,frontFaceCW:!1,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 xa,boundsRadius:0,sortDepth:0,transparentSortGroup:0,transparentSortOrder:0}}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 xa,boundsMax:new xa},this.opaqueBatchPool[e]=t),t}populateDrawCall(e,t,i,r,n,a,s,o,l){const c=t.wireframe;c&&this.ensureWireframeIndex(t.geometry,t.geometryResource);const u=t.sourceObject?Boolean(t.sourceObject.receiveShadow):t.receiveShadow;return this.shouldInvalidateDrawMaterialResource(e,t.material,u,t.usesBatching,null)&&(e.materialResource=null),e.geometry=t.geometry,e.geometryKey=c?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.cameraDetailRejected=t.cameraDetailRejected,e.detailCulling=l?.detailCulling??f(t.sourceObject),e.frontFaceCW=l?.frontFaceCW??(null!==t.sourceObject&&!0===t.sourceObject.isMesh?t.sourceObject.matrixWorld.determinant()<0:t.frontFaceCW),e.usesBatching=t.usesBatching,e.geometryGroup=t.geometryGroup,e.batchKey=t.batchKey,e.batchHash=t.batchHash,e.indexed=c||t.indexed,e.wireframe=c,e.start=c?2*t.start:t.start,e.count=c?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=u,e.sortMaterialId=t.sortMaterialId,e.sortGeometryId=t.sortGeometryId,e.sortCustomDepthMaterialId=t.sortCustomDepthMaterialId,e.skinning=null,e.instanceStart=i,e.instanceCount=r,e.boundsCenter.set(n,a,s),e.boundsRadius=o,e.sortDepth=0,e.transparentSortGroup=0,e.transparentSortOrder=0,e.sourceRanges=void 0,e}populateDynamicDrawCall(e,t,i,r,n,a,s,o,l,c,u,d,h,p,m,g,v,x,w,b,y,S,C,M,P,B,D,I,T=null){const R=!0===o?.isBatchedMesh,V=n.wireframe&&"triangle-list"===n.primitiveTopology;return V&&this.ensureWireframeIndex(t,r),this.shouldInvalidateDrawMaterialResource(e,n,w,R,T)&&(e.materialResource=null),e.geometry=t,e.geometryKey=V?r.wireframeIndex:i,e.geometryResource=r,e.material=n,e.customDepthMaterial=a,e.residentInstanceBinding=s,e.sourceObject=o,e.cameraDetailRejected=void 0,e.detailCulling=f(o),e.frontFaceCW=null!==o&&!0===o.isMesh&&o.matrixWorld.determinant()<0,e.usesBatching=R,e.geometryGroup=l,e.batchKey=c,e.batchHash=u,e.indexed=V||d,e.wireframe=V,e.start=V?2*h:h,e.count=V?2*p:p,e.transparent=m,e.renderOrder=g,e.hasRenderCallbacks=v,e.castShadow=x,e.receiveShadow=w,e.sortMaterialId=b,e.sortGeometryId=y,e.sortCustomDepthMaterialId=S,e.skinning=T,e.instanceStart=C,e.instanceCount=M,e.boundsCenter.set(P,B,D),e.boundsRadius=I,e.sortDepth=0,e.transparentSortGroup=0,e.transparentSortOrder=0,e.sourceRanges=void 0,e}pushOpaqueDrawTemplate(e,t,i,r,n,a,s){e.detailCulling=f(e.sourceObject),e.cameraDetailRejected=null===this.sceneCaptureOptions&&!g(F.set(r,n,a),s,this.cameraViewProjScratch,this.state.width,this.state.height,this.transparentSortCameraPositionScratch,e.detailCulling.minScreenSize*(e.sourceObject&&this.cameraDetailHistory.get(e.sourceObject)?.85:1.15),e.detailCulling.maxDistance,this.cameraDetailProjectionScratch),e.sourceObject&&null===this.sceneCaptureOptions&&this.cameraDetailHistory.set(e.sourceObject,!e.cameraDetailRejected);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 i=l[t];if(Kr(i.template,e)){c=i;break}}else Kr(l.template,e)&&(c=l);if(c){if(c.totalInstanceCount+=i,1===c.rangePairCount){const e=c.sourceRanges;e.length=4,e[0]=c.firstInstanceStart,e[1]=c.firstInstanceCount,e[2]=t,e[3]=i}else{const e=c.sourceRanges,r=2*c.rangePairCount;e[r]=t,e[r+1]=i}c.rangePairCount+=1;const e=c.boundsMin,o=c.boundsMax,l=r-s,u=n-s,d=a-s,h=r+s,p=n+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=i,u.rangePairCount=1,u.firstInstanceStart=t,u.firstInstanceCount=i,u.sourceRanges.length=0,u.boundsMin.set(r-s,n-s,a-s),u.boundsMax.set(r+s,n+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){let i=this.preparedOutlineFrameCache.get(e);i?i.extraction!==this.extractionVersion&&(i.extraction=this.extractionVersion,i.regular=i.skinned=void 0):(i={extraction:this.extractionVersion},this.preparedOutlineFrameCache.set(e,i));const r=t?"skinned":"regular";return void 0===i[r]&&(i[r]=this.prepareToonOutlineMaterial(e,t)),i[r]}prepareToonOutlineMaterial(e,t){const i=this.getToonOutlineParameters(e);if(!i)return null;if("darkenedAlbedo"===i.colorMode){let t=this.outlineResolvedFrameCache.get(e);if(!t||t.extractionVersion!==this.extractionVersion){const i=this.materialResolver?.(e,"outline");t?(t.extractionVersion=this.extractionVersion,t.material=i):(t={extractionVersion:this.extractionVersion,material:i},this.outlineResolvedFrameCache.set(e,t))}const i=t.material;if(i)return i}let r=this.toonOutlineMaterialCache.get(e);if(!r){const t=t=>new lr({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?il:[{name:"position",shaderLocation:0,format:"float32x3"},{name:"normal",shaderLocation:1,format:"float32x3",defaultValue:[0,0,1]}],uniforms:{outlineThickness:i.thickness??.003,outlineColor:(new na).fromArray(i.color??[0,0,0]),outlineAlpha:i.alpha??e.opacity},side:ta,depthTest:!0,depthWrite:!0,transparent:!0,uniformValuesAutoUpdate:!1});r={regular:t(!1),skinned:t(!0)},this.toonOutlineMaterialCache.set(e,r)}const n=t?r.skinned:r.regular,a=i.thickness??.003,s=i.alpha??e.opacity,o=n.uniforms.outlineColor.value,l=i.color?.[0]??0,c=i.color?.[1]??0,u=i.color?.[2]??0;return n.uniforms.outlineThickness.value===a&&n.uniforms.outlineAlpha.value===s&&o.r===l&&o.g===c&&o.b===u||(n.uniforms.outlineThickness.value=a,n.uniforms.outlineAlpha.value=s,o.setRGB(l,c,u),n.uniformValuesNeedsUpdate=!0),n}pushToonOutlineDraw(e,t,i,r=0){const n=t?this.getToonOutlineMaterial(t,null!==e.skinning):null;if(!n||e.usesBatching)return;const a=e.transparent||(this.getToonOutlineParameters(t)?.alpha??t.opacity)<1||n.requiresLatePass(),s=i?.[r];if(s&&s.geometry===e.geometry&&s.geometryKey===e.geometryKey&&s.geometryResource===e.geometryResource&&s.material===n&&s.skinning===e.skinning&&s.start===e.start&&s.count===e.count&&s.indexed===e.indexed)return s.boundsCenter.copy(e.boundsCenter),s.boundsRadius=e.boundsRadius,s.geometryGroup=e.geometryGroup,s.instanceStart=e.instanceStart,s.residentInstanceBinding=e.residentInstanceBinding,s.transparent=a,s.renderOrder=e.renderOrder,s.frontFaceCW=e.frontFaceCW,s.detailCulling=e.detailCulling,s.cameraDetailRejected=void 0,s.sortDepth=0,s.transparentSortGroup=0,s.transparentSortOrder=0,void this.pushDraw(s);const o=this.populateDynamicDrawCall(s??(i?this.createDrawCall():this.acquireDrawCall()),e.geometry,e.geometryKey,e.geometryResource,n,null,e.residentInstanceBinding,e.sourceObject,e.geometryGroup,"",0,e.indexed,e.start,e.count,a,e.renderOrder,!1,!1,!1,jr(n),e.sortGeometryId,0,e.instanceStart,e.instanceCount,e.boundsCenter.x,e.boundsCenter.y,e.boundsCenter.z,e.boundsRadius,e.skinning);i&&(i[r]=o),this.pushDraw(o)}updateTransparentDrawSortDepths(e,t,i){for(let r=0;r<e.length;r+=1){const n=e[r];0===n.transparentSortGroup&&(n.sortDepth=(n.boundsCenter.x-t.x)*i.x+(n.boundsCenter.y-t.y)*i.y+(n.boundsCenter.z-t.z)*i.z)}}selectTransientPointLight(e,t){if(!(e.intensity>0&&e.distance>0))return;if(F.setFromMatrixPosition(e.matrixWorld),!an(this.cameraFrustumPlanesScratch,F.x,F.y,F.z,e.distance))return;const i=e.intensity*e.distance*e.distance/Math.max(1,F.distanceToSquared(t));if(!Number.isFinite(i))return;const r=this.transientPointLightsScratch,n=this.transientPointScoresScratch;let a=0;for(;a<r.length&&(n[a]>i||n[a]===i&&r[a].id<e.id);)a++;if(a>=n.length)return;for(let e=Math.min(r.length,n.length-1);e>a;e--)r[e]=r[e-1],n[e]=n[e-1];r[a]=e,n[a]=i}extractPointLight(e,t){const i=e.shadow,r=i.camera;F.setFromMatrixPosition(e.matrixWorld);const n=e.distance>0?e.distance:Math.max(r.far,25);if(!an(this.cameraFrustumPlanesScratch,F.x,F.y,F.z,n))return;const a=this.extractedPointLightsScratch[t.length];a.sourceLight=e,a.position.copy(F),a.color.set(e.color.r,e.color.g,e.color.b),a.intensity=e.intensity,a.volumetricIntensity=e.userData?.volumetricIntensity??0,a.distance=e.distance,a.range=n,a.decay=e.decay,a.castShadow=e.castShadow,a.shadowBias=i.bias,a.shadowNormalBias=i.normalBias,a.shadowRadius=i.radius,a.shadowIntensity=i.intensity,a.shadowMapSize=Math.max(1,i.mapSize.width,i.mapSize.height),a.shadowCameraNear=r.near,a.shadowCameraFar=e.distance>0?e.distance:r.far,t.push(a)}extractScene(e,t,i=!1){this.extractionVersion+=1,this.state.indirectForwardBundleCache.prune(this.extractionVersion),null===this.sceneCaptureOptions&&(this.motionHistoryExtractionVersion+=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 a=this.sourceInstanceDataScratch;a.reset();const s=this.gpuOpaqueDrawsScratch;s.length=0;const o=this.directOpaqueDrawsScratch;o.length=0;const l=this.stagedOpaqueDrawsScratch;l.length=0;const c=this.residentOpaqueDrawsScratch;c.length=0;const u=this.opaqueInstanceDataScratch;u.reset();const d=this.dynamicBatchingEnabled?this.finalInstanceDataScratch:a;this.finalInstanceDataScratch.reset();const h=this.extractedAmbientScratch;h.set(0,0,0,0);let p=null;const m=this.activeDirectionalLightsScratch,v=this.activePointLightsScratch,x=this.activeSpotLightsScratch,w=this.fogVolumeObjectsScratch;m.length=0,v.length=0,this.transientPointLightsScratch.length=0,x.length=0,w.length=0;const b=this.extractedBoundsMinScratch;b.set(1/0,1/0,1/0);const C=this.extractedBoundsMaxScratch;C.set(-1/0,-1/0,-1/0),rn(tn(t,this.cameraViewProjScratch),this.cameraFrustumPlanesScratch),this.cameraDetailProjectionScratch.update(this.cameraViewProjScratch);const M=this.transparentSortCameraPositionScratch,P=this.transparentSortCameraForwardScratch;t.getWorldPosition(M),t.getWorldDirection(P);const B=i?this.isSphereVisibleForCompilationScratch:this.isSphereVisibleScratch,D=this.updateExtractedBoundsFromMatrixScratch,I=this.objectTraversalStackScratch;I.length=0,I.push(e);for(let e=this.csmCascadeLights.length-1;e>=0;e-=1)I.push(this.csmCascadeLights[e]);for(;;){if(0===I.length){for(const e of this.transientPointLightsScratch){if(v.length>=y)break;this.extractPointLight(e,v)}if(this.csmCascadeLights.length>0&&m.sort((e,t)=>{const i=e.sourceLight?this.csmCascadeLights.indexOf(e.sourceLight):-1,r=t.sourceLight?this.csmCascadeLights.indexOf(t.sourceLight):-1;return(i<0?4:i)-(r<0?4:r)}),!i&&null===this.sceneCaptureOptions){const e=this.staticDrawSetManager.revision;this.directionalShadowScheduler.prepare(m,t,this.csmCascadeRanges,this.csmCascadeCount,performance.now(),e)}if(this.spatialShadowCount=0,this.spatialLocalShadowCount=0,null===this.sceneCaptureOptions)for(let e=0;e<m.length;e++)m[e].castShadow&&rn(tn(this.directionalShadowCameras[e],this.spatialShadowMatrix),this.spatialShadowPlanes[this.spatialShadowCount++]);for(const e of v){if(!e.castShadow)continue;const t=4*this.spatialLocalShadowCount++,i=this.spatialLocalShadowSpheres;i[t]=e.position.x,i[t+1]=e.position.y,i[t+2]=e.position.z,i[t+3]=e.shadowCameraFar*Math.sqrt(3)}for(const e of x){if(!e.castShadow)continue;const t=4*this.spatialLocalShadowCount++,i=this.spatialLocalShadowSpheres;i[t]=e.position.x,i[t+1]=e.position.y,i[t+2]=e.position.z;const r=Math.tan(e.shadowCameraFov*Math.PI/360);i[t+3]=e.shadowCameraFar*Math.sqrt(1+2*r*r)}for(this.spatialIncludeOffscreen=i,this.spatialCameraLayers=t.layers.mask,this.staticSceneSpatialIndex.queryWithState(e,this.testSpatialScene,this.pushSpatialRoot,63);I.length;)this.collectSpatialRoot(I.pop());break}const r=I.pop();if(this.extractingCaster=r.castShadow,!r.visible)continue;if(!1===this.sceneCaptureOptions?.objectFilter?.(r))continue;if(null!==this.sceneCaptureOptions&&!1===r.userData.sceneCapture)continue;if(r.isBone){const e=this.staticSceneSpatialIndex.traversalChildren(r);for(let t=e.length-1;t>=0;t--)I.push(e[t]);continue}const n=0!==(r.layers.mask&t.layers.mask);if(!0===r.isFogVolumeObject&&null!=r.volume)w.push(r);else if(r.isAmbientLight){if(n){const e=r;h.x+=e.color.r*e.intensity,h.y+=e.color.g*e.intensity,h.z+=e.color.b*e.intensity,h.w=1}}else if(r.isHemisphereLight){if(n&&null==p){const e=r,t=this.extractedHemisphereScratch;F.setFromMatrixPosition(e.matrixWorld),t.direction.copy(F),t.direction.lengthSq()<=1e-10?t.direction.set(0,1,0):t.direction.normalize(),t.skyColor.set(e.color.r,e.color.g,e.color.b),t.groundColor.set(e.groundColor.r,e.groundColor.g,e.groundColor.b),t.intensity=e.intensity,p=t}}else if(r.isDirectionalLight){if(n&&m.length<4&&!this.hasExtractedDirectionalLight(m,r)){const e=r,t=e.shadow,i=t.camera,n=this.extractedDirectionalLightsScratch[m.length];n.sourceLight=e,e.target.matrixWorldAutoUpdate&&e.target.updateMatrixWorld(!0),F.setFromMatrixPosition(e.matrixWorld),O.setFromMatrixPosition(e.target.matrixWorld),n.position.copy(F),n.target.copy(O),n.direction.copy(O).sub(F).normalize(),n.color.set(e.color.r,e.color.g,e.color.b),n.intensity=e.intensity,n.volumetricIntensity=e.userData?.volumetricIntensity??0,n.castShadow=e.castShadow&&this.directionalShadowsEnabled,n.shadowBias=t.bias,n.shadowNormalBias=t.normalBias,n.shadowRadius=t.radius,n.shadowIntensity=t.intensity,n.shadowMapSize=Math.max(1,t.mapSize.width,t.mapSize.height),n.shadowCameraLeft=i.left,n.shadowCameraRight=i.right,n.shadowCameraTop=i.top,n.shadowCameraBottom=i.bottom,n.shadowCameraNear=i.near,n.shadowCameraFar=i.far,m.push(n)}}else if(r.isPointLight){if(n&&!1!==this.sceneCaptureOptions?.includeLocalLights){const e=r;!0===e.userData.vfxTransientLight?this.selectTransientPointLight(e,M):v.length<y&&this.extractPointLight(e,v)}}else if(r.isSpotLight){if(n&&!1!==this.sceneCaptureOptions?.includeLocalLights&&x.length<S){const e=r,t=e.shadow,i=t.camera,n=this.extractedSpotLightsScratch[x.length];n.sourceLight=e,e.target.matrixWorldAutoUpdate&&e.target.updateMatrixWorld(!0),F.setFromMatrixPosition(e.matrixWorld),O.setFromMatrixPosition(e.target.matrixWorld);const a=e.distance>0?e.distance:i.far;if(!an(this.cameraFrustumPlanesScratch,F.x,F.y,F.z,a))continue;n.position.copy(F),n.direction.copy(O).sub(F).normalize(),n.color.set(e.color.r,e.color.g,e.color.b),n.intensity=e.intensity,n.volumetricIntensity=e.userData?.volumetricIntensity??0,n.range=a,n.angle=e.angle,n.penumbra=e.penumbra,n.decay=e.decay,n.castShadow=e.castShadow,n.shadowBias=t.bias,n.shadowNormalBias=t.normalBias,n.shadowRadius=t.radius,n.shadowIntensity=t.intensity,n.shadowMapSize=Math.max(1,t.mapSize.width,t.mapSize.height),n.shadowCameraNear=i.near,n.shadowCameraFar=e.distance>0?e.distance:i.far,n.shadowCameraFov=e.angle*(360/Math.PI)*t.focus,n.map=e.map??null,x.push(n)}}else n&&r.isBatchedMesh?this.collectBatchedMesh(r,a,D,B,t,M,P):n&&r.isInstancedMesh?this.collectInstancedMesh(r,a,D,B):n&&r.isSkinnedMesh?this.collectSkinnedMesh(r,a,D,B):n&&r.isLine?this.collectLine(r,a,D,B):n&&r.isSprite?this.collectSprite(r,a,D,B):n&&r.isMesh&&this.collectMesh(r,a,D,B);const s=this.staticSceneSpatialIndex.traversalChildren(r);for(let e=s.length-1;e>=0;e-=1)I.push(s[e])}const T=this.dynamicBatchingEnabled?o.length:0;this.updateTransparentDrawSortDepths(r,M,P),r.sort(_r),Number.isFinite(b.x)||(b.set(-6,-6,-6),C.set(6,6,6)),this.dynamicBatchingEnabled&&this.sortOpaqueDraws(l);for(let e=0;e<l.length;){const t=l[e];if(!this.dynamicBatchingEnabled){t.sourceRanges=void 0,t.indexed&&!t.hasRenderCallbacks?s.push(t):o.push(t),e++;continue}const i=u.instanceCount;u.appendRange(a,t.instanceStart,t.instanceCount);let r,n=t.instanceCount,c=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<l.length&&Yr(t,l[g]);){const e=l[g];u.appendRange(a,e.instanceStart,e.instanceCount),r??=[{sourceObject:t.sourceObject,instanceStart:i,instanceCount:t.instanceCount}],r.push({sourceObject:e.sourceObject,instanceStart:i+n,instanceCount:e.instanceCount}),n+=e.instanceCount;const s=e.boundsCenter.x-e.boundsRadius,o=e.boundsCenter.y-e.boundsRadius,v=e.boundsCenter.z-e.boundsRadius,x=e.boundsCenter.x+e.boundsRadius,w=e.boundsCenter.y+e.boundsRadius,b=e.boundsCenter.z+e.boundsRadius;s<c&&(c=s),o<d&&(d=o),v<h&&(h=v),x>p&&(p=x),w>f&&(f=w),b>m&&(m=b),g+=1}const v=.5*(c+p),x=.5*(d+f),w=.5*(h+m),b=p-v,y=f-x,S=m-w;t.instanceStart=i,t.instanceCount=n,t.sourceRanges=r,t.boundsCenter.set(v,x,w),t.boundsRadius=Math.sqrt(b*b+y*y+S*S),t.indexed&&!t.hasRenderCallbacks?s.push(t):o.push(t),e=g}this.sortOpaqueDraws(c,Zo);for(let e=0;e<c.length;){const t=c[e];let i=t,r=e+1;if(this.dynamicBatchingEnabled&&!t.wireframe&&this.staticSpatialDraws.has(t)){let n=t.instanceCount;for(;r<c.length;){const e=c[r];if(!this.staticSpatialDraws.has(e)||e.wireframe||e.residentInstanceBinding!==t.residentInstanceBinding||e.instanceStart!==t.instanceStart+n||!Yr(t,e))break;n+=e.instanceCount,r++}if(r>e+1){let a=this.staticSpatialBatches.get(t);if(a||(a={draw:this.createDrawCall(),ranges:[],last:null,revision:-1},this.staticSpatialBatches.set(t,a)),a.revision!==this.staticSpatialDrawRevision||a.last!==c[r-1]||a.ranges.length!==r-e||!Yr(a.draw,t)){let i=1/0,s=1/0,o=1/0,l=-1/0,u=-1/0,d=-1/0;for(let t=e;t<r;t++){const r=c[t],n=t-e,h=a.ranges[n]??={sourceObject:null,instanceStart:0,instanceCount:0};h.sourceObject=r.sourceObject,h.instanceStart=r.instanceStart,h.instanceCount=r.instanceCount,i=Math.min(i,r.boundsCenter.x-r.boundsRadius),s=Math.min(s,r.boundsCenter.y-r.boundsRadius),o=Math.min(o,r.boundsCenter.z-r.boundsRadius),l=Math.max(l,r.boundsCenter.x+r.boundsRadius),u=Math.max(u,r.boundsCenter.y+r.boundsRadius),d=Math.max(d,r.boundsCenter.z+r.boundsRadius)}const h=.5*(i+l),p=.5*(s+u),f=.5*(o+d);this.populateDrawCall(a.draw,t,t.instanceStart,n,h,p,f,Math.hypot(l-h,u-p,d-f)),a.ranges.length=r-e,a.draw.sourceObject=null,a.draw.sourceRanges=a.ranges,a.last=c[r-1],a.revision=this.staticSpatialDrawRevision}i=a.draw}}i.indexed&&!i.hasRenderCallbacks?s.push(i):o.push(i),e=r}d.appendBuilder(u);for(let e=0;e<T;e+=1){const t=o[e];if(t.residentInstanceBinding)continue;const i=d.instanceCount;d.appendRange(a,t.instanceStart,t.instanceCount),t.instanceStart=i}this.sortOpaqueDraws(s),this.sortOpaqueDraws(o);for(let e=0;this.dynamicBatchingEnabled&&e<r.length;e+=1){const t=r[e];if(t.residentInstanceBinding)continue;const i=d.instanceCount;d.appendRange(a,t.instanceStart,t.instanceCount),t.instanceStart=i}v.sort(el),x.sort(el);for(let e=4;e<v.length;e+=1)v[e].castShadow=!1;for(let e=4;e<x.length;e+=1)x[e].castShadow=!1;const R=this.extractedLightsScratch;R.hemisphere=p,R.directional=m[0]??null,R.point=v[0]??null,R.spot=x[0]??null;const V=this.extractedFrameScratch;V.scene=e,V.camera=t,V.fogVolumeObjects=w,V.transparentDraws=r,V.instanceData=d,V.residentInstanceUploads=n,this.extractingCaster=!1;const G=this.shadowDrawsScratch;G.length=0;for(const e of[s,o,r]){for(const t of e)t.castShadow&&!t.transparent&&G.push(t);if(!i){let t=0;for(const i of e){const r=i.detailCulling??f(i.sourceObject);i.cameraDetailRejected||!this.isSphereVisibleScratch(i.boundsCenter.x,i.boundsCenter.y,i.boundsCenter.z,i.boundsRadius,i.sourceObject?.frustumCulled??!0)||null===this.sceneCaptureOptions&&!g(i.boundsCenter,i.boundsRadius,this.cameraViewProjScratch,this.state.width,this.state.height,M,!1===i.cameraDetailRejected?0:r.minScreenSize,r.maxDistance,this.cameraDetailProjectionScratch)||(e[t++]=i)}e.length=t}}return V.shadowDraws=G,this.skinningPaletteArena?.flush(),V}collectLine(e,t,i,r){if(Array.isArray(e.material)||!e.geometry.getAttribute("position"))return;const n=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=`${xr(n)}:${s}`;let c=this.lineProxyCache.get(e);c&&c.sourceGeometry===n?c.signature!==l&&(c.signature=l):(c={signature:l,sourceGeometry:n,mesh:new da(n,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,i,r)}const s=xr(n);let o=this.lineProxyCache.get(e);if(!o||o.sourceGeometry!==n||o.signature!==s){const t=n.getAttribute("position"),i=n.index,r=i?.count??t.count,a=Math.max(0,Math.min(r,n.drawRange.start)),l=Number.isFinite(n.drawRange.count)?n.drawRange.count:r-a,c=Math.max(a,Math.min(r,a+l)),u=e.isLineSegments?2:1,d=[],h=[],p=e=>i?i.getX(e):e;for(let e=a;e+1<c;e+=u){const i=p(e),r=p(e+1);d.push(t.getX(i),t.getY(i),t.getZ(i)),h.push(t.getX(r),t.getY(r),t.getZ(r))}const f=new ra;f.setIndex([0,2,1,2,3,1,2,4,3,4,5,3,4,6,5,6,7,5]),f.setAttribute("position",new ia(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 sa(new Float32Array(d),3)),f.setAttribute("instanceEnd",new sa(new Float32Array(h),3)),f.instanceCount=d.length/3;const m=sn(n);f.boundingSphere=new ma(m.center.clone(),m.radius),o={signature:s,sourceGeometry:n,mesh:new da(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,i,r)}collectSprite(e,t,i,r){let n=this.spriteProxyCache.get(e);if(!n){const t=e.geometry.clone();n={mesh:new da(t,e.material),centerX:Number.NaN,centerY:Number.NaN},this.spriteProxyCache.set(e,n)}if(n.centerX!==e.center.x||n.centerY!==e.center.y){const t=n.mesh.geometry.getAttribute("position"),i=e.geometry.getAttribute("position");for(let r=0;r<t.count;r+=1)t.setXYZ(r,i.getX(r)+.5-e.center.x,i.getY(r)+.5-e.center.y,i.getZ(r));t.needsUpdate=!0,n.mesh.geometry.computeBoundingSphere(),n.centerX=e.center.x,n.centerY=e.center.y}const a=n.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,i,r)}hasExtractedDirectionalLight(e,t){for(let i=0;i<e.length;i+=1)if(e[i].sourceLight===t)return!0;return!1}getObjectMotionHistory(e,t){if(null!==this.sceneCaptureOptions)return this.captureMotionHistory.matrix.set(t),this.captureMotionHistory;let i=this.objectMotionHistory.get(e);if(!i)return i={matrix:new Float32Array(16),generation:this.motionVectorHistoryGeneration,lastExtractionVersion:-1,valid:!1},i.matrix.set(t),this.objectMotionHistory.set(e,i),i;const r=!0===e.userData.motionBlurTeleported;r&&(e.userData.motionBlurTeleported=!1);const n=(t[12]??0)-i.matrix[12],a=(t[13]??0)-i.matrix[13],s=(t[14]??0)-i.matrix[14],o=Math.max(0,Number(e.userData.motionBlurTeleportDistance??10));return i.valid=this.motionVectorHistoryValid&&i.generation===this.motionVectorHistoryGeneration&&i.lastExtractionVersion===this.motionHistoryExtractionVersion-1&&!r&&n*n+a*a+s*s<=o*o,i}commitObjectMotionHistory(e,t){null===this.sceneCaptureOptions&&(e.matrix.set(t),e.generation=this.motionVectorHistoryGeneration,e.lastExtractionVersion=this.motionHistoryExtractionVersion)}createRepeatedMeshInstances(e,t){const i=new xn,r=()=>{t.removeEventListener("dispose",r),i.dispose(),this.repeatedInstanceResources.delete(i)};t.addEventListener("dispose",r),this.repeatedInstanceResources.set(i,r);const n={geometry:t,data:i};return this.repeatedMeshInstances.set(e,n),n}collectMesh(e,t,i,r){const n=e.geometry;if(void 0===n.attributes.position)return;const a=e.material,s=Array.isArray(a);if(s){let e=!0;for(let t=0;t<a.length;t+=1)if(t in a&&!1!==a[t].visible){e=!1;break}if(e)return}else if(!1===a.visible)return;const o=this.hasRenderCallbacks(e),l=o?void 0:this.staticSceneSpatialIndex.getMeshSnapshot(e);let c=l?null:this.getGeometryResource(n,!0);const u=this.meshExtractionCache.get(e),d=u?.geometryResource===c?u:null,h=l||d?null:sn(n),p=l?.boundsCenter??d?.localBoundsCenter??h.center,f=l?.boundsRadius??d?.localBoundsRadius??h.radius,m=e.matrixWorld.elements,v=p.x,x=p.y,w=p.z,b=l?.boundsCenter.x??m[0]*v+m[4]*x+m[8]*w+m[12],y=l?.boundsCenter.y??m[1]*v+m[5]*x+m[9]*w+m[13],S=l?.boundsCenter.z??m[2]*v+m[6]*x+m[10]*w+m[14];let C,M=l?.boundsRadius;if(void 0===M){const e=m[0]*m[0]+m[1]*m[1]+m[2]*m[2],t=m[4]*m[4]+m[5]*m[5]+m[6]*m[6],i=m[8]*m[8]+m[9]*m[9]+m[10]*m[10];M=f*Math.sqrt(Math.max(e,t,i,1e-10))}if(!r(b,y,S,M,e.frustumCulled))return;if(l&&null===this.sceneCaptureOptions&&r!==this.isSphereVisibleForCompilationScratch){const t=l.detailCulling;if(C=!g(l.boundsCenter,M,this.cameraViewProjScratch,this.state.width,this.state.height,this.transparentSortCameraPositionScratch,t.minScreenSize*(this.cameraDetailHistory.get(e)?.85:1.15),t.maxDistance,this.cameraDetailProjectionScratch),this.cameraDetailHistory.set(e,!C),C&&(!e.castShadow||!this.isSpatialShadowSphereVisible(b,y,S,M)))return}c??=this.getGeometryResource(n,!0);const P=this.resolvedMeshMaterialsScratch;P.length=0;let B=null;if(s)for(let e=0;e<a.length;e+=1)P[e]=this.resolveMaterial(a[e]);else{if(!a.visible)return;B=this.resolveMaterial(a)}const D=hn(e),I=u&&u.customDepthMaterial===D&&u.geometryResource.lastValidatedExtractionVersion===this.extractionVersion&&(!s&&u.material===a&&u.resolvedMaterial===B||s&&null!==u.materials&&null!==u.resolvedMaterials&&Mr(u.materials,a)&&Dr(u.resolvedMaterials,P))?u:this.getMeshExtractionCacheEntry(e,a,B,P,D,c),T=I.templates.length;if(0===T)return;if(l&&null===this.sceneCaptureOptions&&!(n instanceof oa))return this.collectStaticMeshDraws(e,l,I.templates,C),void i(m);const R=function(e){const t=e.attributes;let i=!1,r=1/0;for(const e in t){const n=t[e];!0!==n.isInstancedBufferAttribute&&!0!==n.data?.isInstancedInterleavedBuffer||(i=!0,n.count<r&&(r=n.count))}if(!i)return 1;const n=e.instanceCount;return Number.isFinite(n)?Math.max(0,Math.floor(n)):Math.max(0,r)}(n),V=this.getObjectMotionHistory(e,m),G=Xo(e),z=Jo(e);let L=0,U=null;if(!(n instanceof oa&&R>1)||e instanceof fa||o)for(let e=0;e<R;e+=1){const i=Fr(t,m,1,1,1,1,void 0,V.matrix,G,z,V.valid?1:0);0===e&&(L=i)}else{let t=this.repeatedMeshInstances.get(e);t&&t.geometry===n&&!t.data.disposed||(t&&this.repeatedInstanceResources.get(t.data)?.(),t=this.createRepeatedMeshInstances(e,n)),U=t.data,U.update(R,m,V.matrix,G,z,V.valid?1:0),!U.residentBufferDirty&&U.residentInstanceBinding.buffer||this.residentInstanceUploadsScratch.push(U)}this.commitObjectMotionHistory(V,m),i(m);for(let e=0;e<T;e+=1){const t=I.templates[e],i=this.populateDrawCall(this.acquireDrawCall(),t,L,R,b,y,S,M,l);i.cameraDetailRejected=C,i.residentInstanceBinding=U?.residentInstanceBinding??t.residentInstanceBinding,t.transparent?this.transparentDraws.push(i):this.pushDraw(i);const r=s?a[t.geometryGroup?.materialIndex??0]:a;this.pushToonOutlineDraw(i,r)}}collectStaticMeshDraws(e,t,i,r){let n=this.staticMeshDraws.get(t);if(n)n.templates!==i&&(this.staticSpatialDrawRevision++,n.templates=i,n.draws.length=0,n.outlines.length=0);else{n={templates:i,draws:[],outlines:[],slot:this.staticInstanceSlots.allocate(),motionHistory:this.getObjectMotionHistory(e,e.matrixWorld.elements),motionMode:NaN,motionScale:NaN,historyValid:-1,motionFrames:0},this.staticMeshDraws.set(t,n);const r=n.slot;t.onInvalidate=()=>{t.onInvalidate=void 0,this.staticSpatialDrawRevision++,this.staticMeshDraws.delete(t),this.retiredStaticInstanceSlots.push(r),this.clearIndirectBundleCache()}}const a=n.motionHistory,s=!0===e.userData.motionBlurTeleported;s&&(e.userData.motionBlurTeleported=!1);const o=this.motionVectorHistoryValid&&!s&&a.generation===this.motionVectorHistoryGeneration&&a.lastExtractionVersion===this.motionHistoryExtractionVersion-1?1:0,l=Xo(e),c=Jo(e);n.motionFrames<2||n.motionMode!==l||n.motionScale!==c||n.historyValid!==o?(this.staticInstanceSlots.write(n.slot,e.matrixWorld.elements,0===n.motionFrames?a.matrix:e.matrixWorld.elements,l,c,o,this.extractionVersion,this.residentInstanceUploadsScratch),0===n.motionFrames&&a.matrix.set(e.matrixWorld.elements),n.motionFrames=Math.min(2,n.motionFrames+1),n.motionMode=l,n.motionScale=c,n.historyValid=o):this.staticInstanceSlots.queueUpload(n.slot,this.extractionVersion,this.residentInstanceUploadsScratch),a.generation=this.motionVectorHistoryGeneration,a.lastExtractionVersion=this.motionHistoryExtractionVersion;const u=Array.isArray(e.material)?e.material:null;for(let a=0;a<i.length;a++){const s=i[a];let o=n.draws[a];const l=s.material.wireframe&&"triangle-list"===s.material.primitiveTopology;if(!o||o.wireframe!==l){const e=s.wireframe===l?s:{...s,wireframe:l};o=this.populateDrawCall(o??this.createDrawCall(),e,n.slot.index,1,t.boundsCenter.x,t.boundsCenter.y,t.boundsCenter.z,t.boundsRadius,t),n.draws[a]=o,this.staticSpatialDraws.add(o)}o.receiveShadow!==e.receiveShadow&&(o.materialResource=null),o.receiveShadow=e.receiveShadow,o.castShadow=e.castShadow,o.renderOrder=e.renderOrder,o.transparent=s.material.transparent||s.material.requiresLatePass(),o.cameraDetailRejected=r,o.residentInstanceBinding=n.slot.page.residentInstanceBinding,this.pushDraw(o),this.pushToonOutlineDraw(o,u?u[s.geometryGroup?.materialIndex??0]:e.material,n.outlines,a)}}prepareSceneForCompilation(e,t,i){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().");const r=i?this.pipelineCompilationDiagnostics:void 0;let n=performance.now();const a=e=>{r&&(r.phases[e]=Math.round(performance.now()-n)),n=performance.now()};e.matrixWorldAutoUpdate&&e.updateMatrixWorld(),null===t.parent&&t.matrixWorldAutoUpdate&&t.updateMatrixWorld(),a("worldMatrices");const s=this.extractScene(e,t,!0);a("extractScene"),this.ensureShadowTextureSizes(s),this.uploadInstanceData(s.instanceData),this.uploadResidentInstanceData(s.residentInstanceUploads),this.uploadDrawMetadata(this.getHiZOcclusionCullingActive()?s.gpuOpaqueDraws:[]),this.ensureTiledLightingSize(),this.updateCameraUniforms(t,e),this.updateLightUniforms(s),a("sceneUploads");const o=this.compileDrawScratch;o.length=0,o.push(...s.gpuOpaqueDraws,...s.directOpaqueDraws,...s.transparentDraws);for(const e of o)this.prepareDrawGeometryVertexBuffers(e);if(r&&(r.drawCount=o.length),a("geometryBuffers"),i){const e=[];this.renderGraph.reset();const t=this.state.device.createCommandEncoder({label:"renderer-graph-compilation-encoder"}),i=this.createGraphBuilderContext(this.renderGraph,t,this.getSharedSceneBindGroup(),this.getSharedShadowBindGroup(),null,this.state.sceneColorView,s,{drawCallCount:0,triangleCount:0},e);this.graphBuilder(this.renderGraph,i),r&&(r.materialRequestCount=e.length),a("renderGraph");const n=[],o=new Set;for(const t of e){n.push(this.compileDrawMaterialsAsync(t.draws,t.colorTargetFormats,t.sampleCount));const e=`${t.sampleCount}:${t.colorTargetFormats.join("|")}:${t.staticDrawStage}`;o.has(e)||(o.add(e),n.push(this.compileStaticDrawMaterialsAsync(t.colorTargetFormats,t.sampleCount,t.staticDrawStage)))}return a("scheduleMaterials"),Promise.all(n).then(()=>{})}this.compileDrawMaterials(o)}collectInstancedMesh(e,t,i,r){if(void 0===e.geometry?.getAttribute("position"))return;const n=e.material;if(!1===n.visible)return;const a=this.instancedMeshExtractionCache.get(e),s=!0===e.userData.webGpuCacheMaterial&&a?.sourceMaterial===n&&a.sourceMaterialVersion===n.version&&a.material!==this.fallbackMaterial?a.material:this.resolveMaterial(n);if(!s)return;const o=hn(e),l=this.getGeometryResource(e.geometry,!0),c=this.getInstancedMeshExtractionCacheEntry(e,s,o,l),u=e.instanceMatrix.array,d=e.instanceMatrix.version,h=e.instanceColor?.array,p=e.instanceColor?.itemSize??0,m=e.instanceColor?.version??-1,g=Qr(e.matrixWorld.elements),v=f(e),x=g&&!e.frustumCulled&&v.minScreenSize<=0&&v.maxDistance<=0;if(!(c.cacheValid&&(x||c.cachedBoundsValid)&&c.cachedCount===e.count&&c.cachedInstanceMatrixVersion===d&&c.cachedInstanceColorVersion===m&&Jr(c.cachedMatrixWorld,e.matrixWorld.elements))){const t=c.cachedInstanceMatrixVersion!==d||c.cachedCount!==e.count,i=c.cachedInstanceColorVersion!==m||c.cachedCount!==e.count;if(x){c.cachedBoundsValid=!1;const r=e.matrixWorld.elements,n=r[12]??0,a=r[13]??0,s=r[14]??0;c.cachedDrawBoundsCenter.set(n,a,s),c.cachedDrawBoundsRadius=0,c.cachedBoundsMin.set(n,a,s),c.cachedBoundsMax.set(n,a,s),c.cachedInstanceMatrixVersion=d,c.cachedInstanceColorVersion=m,c.cachedCount=e.count,c.cachedDefaultColorData=null,Xr(e.matrixWorld.elements,c.cachedMatrixWorld),c.residentBufferDirty||=t,c.residentColorBufferDirty||=i,c.cacheValid=!0}else{c.cachedBoundsValid=!0;const t=c.cachedInstanceData.beginWriteInstances(e.count),i=c.cachedBoundsMin,r=c.cachedBoundsMax;i.set(1/0,1/0,1/0),r.set(-1/0,-1/0,-1/0);const n=c.localBoundsCenter,a=c.localBoundsRadius,s=e.matrixWorld.elements,o=Qr(s),l=n.x,f=n.y,g=n.z,v=s[0],x=s[4],w=s[8],b=s[12],y=s[1],S=s[5],M=s[9],P=s[13],B=s[2],D=s[6],I=s[10],T=s[14],R=s[3],V=s[7],G=s[11],z=s[15];for(let n=0;n<e.count;n+=1){const e=16*n,s=n*C,c=u[e+0]??0,d=u[e+1]??0,m=u[e+2]??0,L=u[e+3]??0,U=u[e+4]??0,A=u[e+5]??0,k=u[e+6]??0,O=u[e+7]??0,E=u[e+8]??0,j=u[e+9]??0,$=u[e+10]??0,W=u[e+11]??0,N=u[e+12]??0,_=u[e+13]??0,H=u[e+14]??0,q=u[e+15]??0;let K,Y,Z,X,J,Q,ee,te,ie,re,ne,ae,se,oe,le,ce;o?(K=c,Y=d,Z=m,X=L,J=U,Q=A,ee=k,te=O,ie=E,re=j,ne=$,ae=W,se=N,oe=_,le=H,ce=q):(K=v*c+x*d+w*m+b*L,J=v*U+x*A+w*k+b*O,ie=v*E+x*j+w*$+b*W,se=v*N+x*_+w*H+b*q,Y=y*c+S*d+M*m+P*L,Q=y*U+S*A+M*k+P*O,re=y*E+S*j+M*$+P*W,oe=y*N+S*_+M*H+P*q,Z=B*c+D*d+I*m+T*L,ee=B*U+D*A+I*k+T*O,ne=B*E+D*j+I*$+T*W,le=B*N+D*_+I*H+T*q,X=R*c+V*d+G*m+z*L,te=R*U+V*A+G*k+z*O,ae=R*E+V*j+G*$+z*W,ce=R*N+V*_+G*H+z*q),t[s+0]=K,t[s+1]=Y,t[s+2]=Z,t[s+3]=X,t[s+4]=J,t[s+5]=Q,t[s+6]=ee,t[s+7]=te,t[s+8]=ie,t[s+9]=re,t[s+10]=ne,t[s+11]=ae,t[s+12]=se,t[s+13]=oe,t[s+14]=le,t[s+15]=ce;const ue=n*p;t[s+16]=h?h[ue+0]??1:1,t[s+17]=h?h[ue+1]??1:1,t[s+18]=h?h[ue+2]??1:1,t[s+19]=h&&p>=4?h[ue+3]??1:1,t[s+20]=n,t[s+21]=1,t[s+22]=1,t[s+23]=0;for(let e=0;e<16;e+=1)t[s+24+e]=t[s+e];const de=K*l+J*f+ie*g+se,he=Y*l+Q*f+re*g+oe,pe=Z*l+ee*f+ne*g+le,fe=Math.sqrt(K*K+Y*Y+Z*Z),me=Math.sqrt(J*J+Q*Q+ee*ee),ge=Math.sqrt(ie*ie+re*re+ne*ne),ve=a*Math.max(fe,me,ge,1e-5);cn(i,r,F.set(de,he,pe),ve)}c.cachedDrawBoundsCenter.copy(i).add(r).multiplyScalar(.5);const L=r.x-c.cachedDrawBoundsCenter.x,U=r.y-c.cachedDrawBoundsCenter.y,A=r.z-c.cachedDrawBoundsCenter.z;c.cachedDrawBoundsRadius=Math.sqrt(L*L+U*U+A*A),c.cachedInstanceMatrixVersion=d,c.cachedInstanceColorVersion=m,c.cachedCount=e.count,c.cachedDefaultColorData=null,Xr(e.matrixWorld.elements,c.cachedMatrixWorld),c.residentBufferDirty=!0,c.residentColorBufferDirty=!0,c.cacheValid=!0}}if(!r(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),en(this.extractedBoundsMinScratch,this.extractedBoundsMaxScratch,c.cachedBoundsMin,c.cachedBoundsMax);const w=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&&!w.transparent?this.directOpaqueDrawsScratch.push(w):this.pushDraw(w)}getSkinnedRenderRecord(e){let t=this.skinnedRenderRecords.get(e);return t?t.geometry!==e.geometry&&(t.geometry.removeEventListener("dispose",t.onGeometryDispose),t.geometry=e.geometry,t.geometry.addEventListener("dispose",t.onGeometryDispose)):(t={slot:this.skinnedInstanceSlots.allocate(),draws:[],outlines:[],geometry:e.geometry,onGeometryDispose:()=>{const t=this.skinnedRenderRecords.get(e);t&&(t.geometry!==e.geometry?this.getSkinnedRenderRecord(e):this.releaseSkinnedMeshResources(e))}},this.skinnedRenderRecords.set(e,t),e.geometry.addEventListener("dispose",t.onGeometryDispose)),t}releaseSkinnedRenderRecord(e){const t=this.skinnedRenderRecords.get(e);if(!t)return;t.geometry.removeEventListener("dispose",t.onGeometryDispose),this.skinnedInstanceSlots.release(t.slot),this.skinnedRenderRecords.delete(e);const i=this.skinnedGeometryCache.get(e);i?.skinning.releaseInstance(),i?.skinning.bindUniformBuffer.destroy(),this.skinnedGeometryCache.delete(e)}releaseSkinnedMeshResources(e){const t=this.skinnedGeometryCache.get(e);if(this.releaseSkinnedRenderRecord(e),t&&this.skinnedGeometryCache.delete(e)&&(t.skinning.releaseInstance(),t.skinning.bindUniformBuffer.destroy()),t){for(const e of this.skinnedGeometryCache.values())if(e.skinning.palette===t.skinning.palette)return;this.releaseSkinningPalette(t.skinning.palette)}}collectSkinnedMesh(e,t,i,r){if(void 0===e.geometry?.getAttribute("position"))return;const n=e.boundingSphere,a=F;let s=0;if(null!==n){const t=n.center,i=e.matrixWorld.elements,a=i[0]*t.x+i[4]*t.y+i[8]*t.z+i[12],o=i[1]*t.x+i[5]*t.y+i[9]*t.z+i[13],l=i[2]*t.x+i[6]*t.y+i[10]*t.z+i[14];if(s=n.radius*on(e.matrixWorld),e.frustumCulled&&!r(a,o,l,s,!0))return}const o=Array.isArray(e.material)?e.material:null,l=o?o[0]:e.material,c=hn(e),u=null!==e.geometry.index,d=this.getSkinnedGeometryResource(e);if(this.refreshSkinningPalette(d.skinning.palette),this.refreshSkinningBindMatrices(e,d.skinning),null===n){if(this.updateSkinnedBounds(e,d),a.copy(d.localBoundsCenter).applyMatrix4(e.matrixWorld),s=d.localBoundsRadius*on(e.matrixWorld),!r(a.x,a.y,a.z,s,e.frustumCulled))return}else a.copy(n.center).applyMatrix4(e.matrixWorld);this.uploadSkinningResources(d.skinning);const h=this.getObjectMotionHistory(e,e.matrixWorld.elements),p=this.getSkinnedRenderRecord(e),m=p.slot.index;this.skinnedInstanceSlots.write(p.slot,e.matrixWorld.elements,h.matrix,Xo(e),Jo(e),h.valid?1:0,this.extractionVersion,this.residentInstanceUploadsScratch),this.commitObjectMotionHistory(h,e.matrixWorld.elements),i(e.matrixWorld.elements);const g=e.geometry.groups,v=g.length>0&&(null===o||o.length>0),x=v?g.length:1;p.draws.length=Math.min(p.draws.length,x),p.outlines.length=Math.min(p.outlines.length,x);for(let t=0;t<x;t++){const i=v?g[t]:null,r=i&&o?o[i.materialIndex??0]??l:l,n=this.resolveSkinnedMaterial(r);if(!n)continue;const h=i?i.start:e.geometry.drawRange.start,x=Gr(e.geometry,u,h,i?i.count:e.geometry.drawRange.count),w=this.skinnedDrawKeys.get(e,t,n,u,h,x,c);let b=p.draws[t];b||(p.draws[t]=b=this.createDrawCall());const y=n.wireframe&&"triangle-list"===n.primitiveTopology;b.geometry===e.geometry&&b.geometryResource===d.resource&&b.skinning===d.skinning&&b.material===n&&b.batchKey===w.batchKey&&b.geometryGroup===i&&b.wireframe===y||this.populateDynamicDrawCall(b,e.geometry,e,d.resource,n,c,p.slot.page.residentInstanceBinding,e,i,w.batchKey,w.batchHash,u,h,x,n.transparent,e.renderOrder,this.hasRenderCallbacks(e),e.castShadow,e.receiveShadow,w.materialId,w.geometryId,w.depthMaterialId,m,1,a.x,a.y,a.z,s,d.skinning),b.receiveShadow!==e.receiveShadow&&(b.materialResource=null),b.receiveShadow=e.receiveShadow,b.castShadow=e.castShadow,b.renderOrder=e.renderOrder,b.hasRenderCallbacks=this.hasRenderCallbacks(e),b.frontFaceCW=e.matrixWorld.determinant()<0,b.detailCulling=f(e),b.cameraDetailRejected=void 0,b.transparent=n.transparent,b.boundsCenter.copy(a),b.boundsRadius=s,b.sortDepth=0,b.transparentSortGroup=0,b.transparentSortOrder=0,this.pushDraw(b),this.pushToonOutlineDraw(b,r,p.outlines,t)}}collectBatchedMesh(e,t,i,r,n,a,s){if(void 0===e.geometry?.getAttribute("position"))return;const o=this.resolveMaterial(e.material);if(!o)return;const l=hn(e),c=(e.geometry.index,this.getGeometryResource(e.geometry,!0)),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,v=u._matricesTexture?.version??0,x=u._colorsTexture?.version??-1;if(m.cacheValid&&!o.transparent&&m.cachedMatricesVersion===v&&m.cachedColorsVersion===x&&m.cachedInstanceInfoLength===d.length&&m.cachedGeometryCount===(u._geometryCount??0)&&Jr(m.cachedMatrixWorld,g)&&this.batchedGeometryIdsMatchSnapshot(m.geometryIdsSnapshot,d)){let t=!1;for(let i=0;i<m.cachedDraws.length;i+=1){const n=m.cachedDraws[i];r(n.boundsCenter.x,n.boundsCenter.y,n.boundsCenter.z,n.boundsRadius,e.frustumCulled)&&(t=!0,this.pushDraw(this.populateDynamicDrawCall(this.acquireDrawCall(),n.template.geometry,n.template.geometryKey,n.template.geometryResource,n.template.material,n.template.customDepthMaterial,m.residentInstanceBinding,n.template.sourceObject,n.template.geometryGroup,n.template.batchKey,n.template.batchHash,n.template.indexed,n.template.start,n.template.count,n.template.transparent,n.template.sourceObject?.renderOrder??n.template.renderOrder,this.hasRenderCallbacks(n.template.sourceObject),n.template.sourceObject?Boolean(n.template.sourceObject.castShadow):n.template.castShadow,n.template.sourceObject?Boolean(n.template.sourceObject.receiveShadow):n.template.receiveShadow,n.template.sortMaterialId,n.template.sortGeometryId,n.template.sortCustomDepthMaterialId,n.instanceStart,n.instanceCount,n.boundsCenter.x,n.boundsCenter.y,n.boundsCenter.z,n.boundsRadius)))}if(!t)return;return!m.residentBufferDirty&&m.residentInstanceBinding||this.residentInstanceUploadsScratch.push(m),void en(this.extractedBoundsMinScratch,this.extractedBoundsMaxScratch,m.cachedBoundsMin,m.cachedBoundsMax)}if(o.transparent){const o=[],l=!e.sortObjects||null!==e.customSort;for(let n=0;n<h;n+=1){const c=d[n];if(!c?.active||!c.visible)continue;const u=m.templates[c.geometryIndex];if(!u)continue;p?U.fromArray(p,16*n):e.getMatrixAt(n,U),A.multiplyMatrices(e.matrixWorld,U);const h=u.localBoundsCenter,g=A.elements,v=g[0]*h.x+g[4]*h.y+g[8]*h.z+g[12],x=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(!r(v,x,w,C,e.frustumCulled&&e.perObjectFrustumCulled))continue;const M=f?f[4*n+0]??1:1,P=f?f[4*n+1]??1:1,B=f?f[4*n+2]??1:1,D=f?f[4*n+3]??1:1,I=Or(t,A,M,P,B,D,n);i(A.elements);const T=this.populateDrawCall(this.acquireDrawCall(),u,I,1,v,x,w,C),R=(v-a.x)*s.x+(x-a.y)*s.y+(w-a.z)*s.z;l?o.push({start:u.start,count:u.count,z:R,index:n,draw:T}):(T.sortDepth=R,this.transparentDraws.push(T))}if(l&&o.length>0){e.sortObjects&&e.customSort?e.customSort.call(e,o,n):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 i=jr(e);for(let e=0;e<o.length;e+=1){const r=o[e].draw;r.sortDepth=t,r.transparentSortGroup=i,r.transparentSortOrder=e,this.transparentDraws.push(r)}}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 i=m.groups[t.geometryIndex];i?(m.geometryIdsSnapshot[e]=t.geometryIndex,i.activeInFrame||(i.activeInFrame=!0,i.activeCount=0,i.boundsMin.set(1/0,1/0,1/0),i.boundsMax.set(-1/0,-1/0,-1/0),w.push(i)),i.activeCount+=1,S+=1):m.geometryIdsSnapshot[e]=-1}const M=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*C,P+=t.activeCount}const B=Qr(g),D=g[0],I=g[4],T=g[8],R=g[12],V=g[1],G=g[5],z=g[9],L=g[13],k=g[2],F=g[6],O=g[10],E=g[14],j=g[3],$=g[7],W=g[11],N=g[15];for(let t=0;t<h;t+=1){const i=m.geometryIdsSnapshot[t]??-1;if(i<0)continue;const r=m.groups[i];if(!r)continue;let n,a,s,o,l,c,u,d,h,g,v,x,w,S,P,A,_,H,q,K,Y,Z,X,J,Q,ee,te,ie,re,ne,ae,se;if(p){const e=16*t;n=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,v=p[e+10]??0,x=p[e+11]??0,w=p[e+12]??0,S=p[e+13]??0,P=p[e+14]??0,A=p[e+15]??0}else{e.getMatrixAt(t,U);const i=U.elements;n=i[0]??0,a=i[1]??0,s=i[2]??0,o=i[3]??0,l=i[4]??0,c=i[5]??0,u=i[6]??0,d=i[7]??0,h=i[8]??0,g=i[9]??0,v=i[10]??0,x=i[11]??0,w=i[12]??0,S=i[13]??0,P=i[14]??0,A=i[15]??0}B?(_=n,H=a,q=s,K=o,Y=l,Z=c,X=u,J=d,Q=h,ee=g,te=v,ie=x,re=w,ne=S,ae=P,se=A):(_=D*n+I*a+T*s+R*o,Y=D*l+I*c+T*u+R*d,Q=D*h+I*g+T*v+R*x,re=D*w+I*S+T*P+R*A,H=V*n+G*a+z*s+L*o,Z=V*l+G*c+z*u+L*d,ee=V*h+G*g+z*v+L*x,ne=V*w+G*S+z*P+L*A,q=k*n+F*a+O*s+E*o,X=k*l+F*c+O*u+E*d,te=k*h+F*g+O*v+E*x,ae=k*w+F*S+O*P+E*A,K=j*n+$*a+W*s+N*o,J=j*l+$*c+W*u+N*d,ie=j*h+$*g+W*v+N*x,se=j*w+$*S+W*P+N*A);const oe=f?f[4*t+0]??1:1,le=f?f[4*t+1]??1:1,ce=f?f[4*t+2]??1:1,ue=f?f[4*t+3]??1:1,de=r.writeOffset;M[de+0]=_,M[de+1]=H,M[de+2]=q,M[de+3]=K,M[de+4]=Y,M[de+5]=Z,M[de+6]=X,M[de+7]=J,M[de+8]=Q,M[de+9]=ee,M[de+10]=te,M[de+11]=ie,M[de+12]=re,M[de+13]=ne,M[de+14]=ae,M[de+15]=se,M[de+16]=oe,M[de+17]=le,M[de+18]=ce,M[de+19]=ue,M[de+20]=t,M[de+21]=1,M[de+22]=1,M[de+23]=0;for(let e=0;e<16;e+=1)M[de+24+e]=M[de+e];r.writeOffset+=C;const he=r.template.localBoundsCenter,pe=_*he.x+Y*he.y+Q*he.z+re,fe=H*he.x+Z*he.y+ee*he.z+ne,me=q*he.x+X*he.y+te*he.z+ae,ge=Math.sqrt(_*_+H*H+q*q),ve=Math.sqrt(Y*Y+Z*Z+X*X),xe=Math.sqrt(Q*Q+ee*ee+te*te),we=r.template.localBoundsRadius*Math.max(ge,ve,xe,1e-5),be=pe-we,ye=fe-we,Se=me-we,Ce=pe+we,Me=fe+we,Pe=me+we;be<r.boundsMin.x&&(r.boundsMin.x=be),ye<r.boundsMin.y&&(r.boundsMin.y=ye),Se<r.boundsMin.z&&(r.boundsMin.z=Se),Ce>r.boundsMax.x&&(r.boundsMax.x=Ce),Me>r.boundsMax.y&&(r.boundsMax.y=Me),Pe>r.boundsMax.z&&(r.boundsMax.z=Pe),be<b.x&&(b.x=be),ye<b.y&&(b.y=ye),Se<b.z&&(b.z=Se),Ce>y.x&&(y.x=Ce),Me>y.y&&(y.y=Me),Pe>y.z&&(y.z=Pe)}const _=m.cachedDraws;let H=0;for(let e=0;e<w.length;e+=1){const t=w[e],i=.5*(t.boundsMin.x+t.boundsMax.x),r=.5*(t.boundsMin.y+t.boundsMax.y),n=.5*(t.boundsMin.z+t.boundsMax.z),a=t.boundsMax.x-i,s=t.boundsMax.y-r,o=t.boundsMax.z-n,l=Math.sqrt(a*a+s*s+o*o);let c=_[H];c||(c={template:t.template,instanceStart:0,instanceCount:0,boundsCenter:new xa,boundsRadius:0},_[H]=c),c.template=t.template,c.instanceStart=t.instanceStart,c.instanceCount=t.activeCount,c.boundsCenter.set(i,r,n),c.boundsRadius=l,H+=1}_.length=H,m.cachedMatricesVersion=v,m.cachedColorsVersion=x,m.cachedInstanceInfoLength=d.length,m.cachedGeometryCount=u._geometryCount??0,Xr(g,m.cachedMatrixWorld),m.residentBufferDirty=!0,m.cacheValid=!0;let q=!1;for(let t=0;t<_.length;t+=1){const i=_[t];r(i.boundsCenter.x,i.boundsCenter.y,i.boundsCenter.z,i.boundsRadius,e.frustumCulled)&&(q=!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)))}q&&(this.residentInstanceUploadsScratch.push(m),en(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,P,0,C)}uploadResidentInstanceData(e){if(this.state.device)for(let t=0;t<e.length;t+=1){const i=e[t],r=i.residentInstanceBinding;if(!r)continue;if("instanced-direct"===r.mode){const e=i,t=e.sourceMesh,n=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((!r.buffer||a>i.residentBufferSize)&&(r.buffer?.destroy(),i.residentBufferSize=256*Math.ceil(a/256),r.buffer=this.state.device.createBuffer({label:"renderer-instanced-mesh-matrix-buffer",size:i.residentBufferSize,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST}),r.sceneBindGroup=null,r.shadowBindGroup=null,r.shadowBindGroups.clear(),r.sceneBindGroupVersion=0,r.shadowBindGroupVersion=0,i.residentBufferDirty=!0),(!r.colorBuffer||o>i.residentColorBufferSize)&&(r.colorBuffer?.destroy(),i.residentColorBufferSize=256*Math.ceil(o/256),r.colorBuffer=this.state.device.createBuffer({label:"renderer-instanced-mesh-color-buffer",size:i.residentColorBufferSize,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST}),r.sceneBindGroup=null,r.shadowBindGroup=null,r.shadowBindGroups.clear(),r.sceneBindGroupVersion=0,r.shadowBindGroupVersion=0,i.residentColorBufferDirty=!0),i.residentBufferDirty&&r.buffer&&(t.count>0?this.state.device.queue.writeBuffer(r.buffer,0,kr(n),0,16*t.count):this.state.device.queue.writeBuffer(r.buffer,0,B,0,4),i.residentBufferDirty=!1),i.residentColorBufferDirty&&r.colorBuffer){if(t.instanceColor&&4===t.instanceColor.itemSize&&t.instanceColor.array instanceof Float32Array)this.state.device.queue.writeBuffer(r.colorBuffer,0,kr(t.instanceColor.array),0,4*s);else{let i=e.cachedDefaultColorData;i&&i.length===4*s||(i=new Float32Array(4*s),e.cachedDefaultColorData=i);for(let e=0;e<s;e+=1){const r=4*e;t.instanceColor?(i[r+0]=t.instanceColor.getComponent(e,0),i[r+1]=t.instanceColor.itemSize>1?t.instanceColor.getComponent(e,1):1,i[r+2]=t.instanceColor.itemSize>2?t.instanceColor.getComponent(e,2):1,i[r+3]=t.instanceColor.itemSize>3?t.instanceColor.getComponent(e,3):1):(i[r+0]=1,i[r+1]=1,i[r+2]=1,i[r+3]=1)}this.state.device.queue.writeBuffer(r.colorBuffer,0,kr(i),0,i.length)}i.residentColorBufferDirty=!1}continue}const n=Math.max(4,i.cachedInstanceData.byteLength);let a=!1;if((!r.buffer||n>i.residentBufferSize)&&(r.buffer?.destroy(),i.residentBufferSize=256*Math.ceil(n/256),r.buffer=this.state.device.createBuffer({label:"renderer-instanced-mesh-buffer",size:i.residentBufferSize,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST}),r.sceneBindGroup=null,r.shadowBindGroup=null,r.shadowBindGroups.clear(),r.sceneBindGroupVersion=0,r.shadowBindGroupVersion=0,i.residentBufferDirty=!0,a=!0),i.residentBufferDirty){if(!r.buffer)continue;if(i.cachedInstanceData.floatLength>0){const e=a?void 0:i.residentBufferDirtyRange,t=e?e.start*C*4:0,n=e?(e.end-e.start)*C*4:i.cachedInstanceData.byteLength;this.state.device.queue.writeBuffer(r.buffer,t,i.cachedInstanceData.rawData.buffer,t,n)}else this.state.device.queue.writeBuffer(r.buffer,0,P,0,C);i.residentBufferDirty=!1,i.residentBufferDirtyRange&&(i.residentBufferDirtyRange.start=1/0,i.residentBufferDirtyRange.end=0)}}}invalidateGraphTextureBundles(){this.graphTextureResourceVersion+=1,this.clearIndirectBundleCache(),this.materialPassStaticBundleCache=new WeakMap;for(const e of this.staticDrawSets)e.indirectForwardBundleCache.clear(),e.directForwardBundle=null,e.directForwardBundleSceneBindGroup=null}clearIndirectBundleCache(){this.state.indirectForwardBundleCache.clear(),this.state.directForwardBundleCache.clear(),this.indirectBundleInvalidationVersion+=1}clearStaticDrawSetBundleCaches(){this.materialPassStaticBundleCache=new WeakMap;for(const e of this.staticDrawSets){for(const t of e.visibleIndirectSubmissionStreams??[])t.forwardBundleEntry=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;for(const t of e.shadowChunks)t.bundles=new WeakMap;e.depthMaterialResources.clear(),e.temporalDepthSupported=Vs(e.draws)}}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&&this.state.spotLightMapView))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},{binding:9,resource:this.state.spotLightMapView},{binding:11,resource:this.tiledPointLights.view}]})),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 i=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,i),i}buildIndirectSubmissionStreams(e,t,i,r){let n=this.dynamicIndirectSubmissionCache.get(e);n||(n=[],this.dynamicIndirectSubmissionCache.set(e,n));const a=void 0!==r;let s=n.find(e=>e.lastUsedExtractionVersion!==this.extractionVersion&&e.sceneBindGroup===t&&e.instanceAccessMode===i&&e.usesExplicitMaterialResources===a);s||(s={sceneBindGroup:t,instanceAccessMode:i,usesExplicitMaterialResources:a,lastUsedExtractionVersion:-1,streams:[]},n.push(s)),s.lastUsedExtractionVersion=this.extractionVersion;const o=s.streams;let l=0,c=null,u=0;for(let n=0;n<e.length;n+=1){const a=e[n],s=r?.[n]??(i?this.getMaterialResource(a.material,i,a.receiveShadow,void 0,null!==a.skinning,this.drawUsesBatching(a)):this.getMaterialResourceForDraw(a)),d=i?t:this.resolveSceneBindGroupForDraw(a,t),h=this.getIndirectStreamKey(s.pipeline,s.bindGroup,d,a.geometryKey),p=un(a);if(c&&c.key===h&&c.indirectStartIndex+c.indirectCount===n){c.indirectCount+=1,c.drawCallCount+=1,c.triangleCount+=p;continue}c&&c.indirectCount!==u&&(c.forwardBundleEntry=null,c.forwardBundleColorFormatsId=0,c.forwardBundleDrawMetadataResource=null,c.forwardBundleCandidateExtractionVersion=-1),c=o[l],u=c?.indirectCount??0;const f=void 0!==c&&c.key===h&&c.material===a.material&&c.materialResource===s&&c.sceneBindGroup===d&&c.geometry===a.geometry&&c.geometryKey===a.geometryKey&&c.geometryResource===a.geometryResource&&c.indirectStartIndex===n;c?(f||(c.forwardBundleEntry=null,c.forwardBundleColorFormatsId=0,c.forwardBundleDrawMetadataResource=null,c.forwardBundleCandidateExtractionVersion=-1),c.key=h,c.material=a.material,c.materialResource=s,c.sceneBindGroup=d,c.geometry=a.geometry,c.geometryKey=a.geometryKey,c.geometryResource=a.geometryResource,c.indirectStartIndex=n,c.indirectCount=1,c.drawCallCount=1,c.triangleCount=p):(c={key:h,material:a.material,materialResource:s,sceneBindGroup:d,geometry:a.geometry,geometryKey:a.geometryKey,geometryResource:a.geometryResource,indirectStartIndex:n,indirectCount:1,drawCallCount:1,triangleCount:p,forwardBundleEntry:null,forwardBundleMaterialVersion:-1,forwardBundleGraphTextureResourceVersion:-1,forwardBundleInvalidationVersion:-1,forwardBundleDrawMetadataResource:null,forwardBundleSampleCount:0,forwardBundleColorFormatsId:0,forwardBundleCandidateExtractionVersion:-1},o[l]=c),l+=1}return c&&c.indirectCount!==u&&(c.forwardBundleEntry=null,c.forwardBundleColorFormatsId=0,c.forwardBundleDrawMetadataResource=null,c.forwardBundleCandidateExtractionVersion=-1),o.length!==l&&(o.length=l),o}getIndirectStreamKey(e,t,i,r){let n=this.indirectStreamKeyCache.get(e);n||(n=new WeakMap,this.indirectStreamKeyCache.set(e,n));let a=n.get(t);a||(a=new WeakMap,n.set(t,a));let s=a.get(i);s||(s=new WeakMap,a.set(i,s));let o=s.get(r);return void 0===o&&(o=this.nextIndirectStreamKey,this.nextIndirectStreamKey+=1,s.set(r,o)),o}getOrCreateStaticIndirectSubmissionStreams(e,t,i=tl){const r=i.join("|"),n=null!==e.visibleIndirectSubmissionStreams&&e.visibleIndirectStreamsSceneBindGroup===t&&e.visibleIndirectStreamsSampleCount===this.sampleCount&&e.visibleIndirectStreamsColorFormatsKey===r;if(n)return e.visibleIndirectSubmissionStreams;let a=!n;for(const t of e.visibleMaterialBindings){const r=this.getMaterialResource(t.material,"packed-visible",t.receiveShadow,i,!1,t.usesBatching),n=t.resource;t.resource=r,n!==r&&(a=!0);for(const i of t.drawIndices)e.visibleDrawMaterialResources[i]!==r&&(a=!0),e.visibleDrawMaterialResources[i]=r}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=r,e.indirectForwardBundleCache.clear()),e.visibleIndirectSubmissionStreams}getOrCreateIndirectForwardBundle(e,t=this.state.drawMetadataResource,i=this.state.indirectForwardBundleCache,r="renderer-indirect-forward-bundle",n=tl,a=!1,s=this.getColorFormatsId(n)){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.");i.prune(this.extractionVersion);if(null!=e.forwardBundleEntry?.bundle&&e.forwardBundleMaterialVersion===e.material.version&&e.forwardBundleGraphTextureResourceVersion===this.graphTextureResourceVersion&&e.forwardBundleInvalidationVersion===this.indirectBundleInvalidationVersion&&e.forwardBundleDrawMetadataResource===t&&e.forwardBundleSampleCount===this.sampleCount&&e.forwardBundleColorFormatsId===s)return i.touch(e.forwardBundleEntry,this.extractionVersion),e.forwardBundleEntry.bundle;e.forwardBundleEntry=null;const o=this.getIndirectBundleHash(e,t,s),l=i.get(o),c=l?.find(i=>i.streamKey===e.key&&i.positionBuffer===e.geometryResource.position&&i.indexBuffer===e.geometryResource.index&&i.indirectBuffer===t.indirectBuffer&&i.indirectStartIndex===e.indirectStartIndex&&i.indirectCount===e.indirectCount&&i.sampleCount===this.sampleCount&&i.materialVersion===e.material.version&&i.graphTextureResourceVersion===this.graphTextureResourceVersion&&i.colorFormatsId===s);if(c)return i.touch(c,this.extractionVersion),this.setRetainedIndirectBundleState(e,c,t,s),c.bundle;if(a&&e.forwardBundleCandidateExtractionVersion<0)return e.forwardBundleCandidateExtractionVersion=this.extractionVersion,null;if(a&&e.forwardBundleCandidateExtractionVersion===this.extractionVersion)return null;const u=this.state.device.createRenderBundleEncoder({label:`${r}-${o}`,colorFormats:n,depthStencilFormat:"depth32float",sampleCount:this.sampleCount});if(u.setPipeline(e.materialResource.pipeline),this.bindGeometryVertexBuffers(u,e.geometry,e.geometryResource,e.materialResource.vertexAttributes,0,1,e.material.wireframe),u.setBindGroup(0,e.sceneBindGroup),u.setBindGroup(1,e.materialResource.bindGroup),!e.materialResource.graphTextureBindGroupLayout)throw new Error("Graph texture layout is missing.");u.setBindGroup(3,this.createGraphTextureBindGroup(e.material,e.materialResource.graphTextureBindGroupLayout));for(let i=0;i<e.indirectCount;i+=1)u.drawIndexedIndirect(t.indirectBuffer,20*(e.indirectStartIndex+i));const d=u.finish({label:`${r}-${o}`}),h={hash:this.getIndirectBundleHash(e,t,s),lastUsedExtractionVersion:this.extractionVersion,previous:null,next:null,streamKey:e.key,positionBuffer:e.geometryResource.position,indexBuffer:e.geometryResource.index,indirectBuffer:t.indirectBuffer,indirectStartIndex:e.indirectStartIndex,indirectCount:e.indirectCount,sampleCount:this.sampleCount,materialVersion:e.material.version,graphTextureResourceVersion:this.graphTextureResourceVersion,colorFormatsId:s,bundle:d};return i.add(h.hash,h,this.extractionVersion),this.setRetainedIndirectBundleState(e,h,t,s),d}submitIndirectStreamDirect(e,t,i){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);const r=t.materialResource.graphTextureBindGroupLayout;if(!r)throw new Error("Graph texture layout is missing.");e.setBindGroup(3,this.createGraphTextureBindGroup(t.material,r));for(let r=0;r<t.indirectCount;r+=1)e.drawIndexedIndirect(i.indirectBuffer,20*(t.indirectStartIndex+r))}setRetainedIndirectBundleState(e,t,i,r){e.forwardBundleEntry=t,e.forwardBundleMaterialVersion=e.material.version,e.forwardBundleGraphTextureResourceVersion=this.graphTextureResourceVersion,e.forwardBundleInvalidationVersion=this.indirectBundleInvalidationVersion,e.forwardBundleDrawMetadataResource=i,e.forwardBundleSampleCount=this.sampleCount,e.forwardBundleColorFormatsId=r}getIndirectBundleHash(e,t,i){let r=2166136261;return r=qr(r,e.key),r=qr(r,jr(e.geometryResource.position)),r=qr(r,e.geometryResource.index?jr(e.geometryResource.index):0),r=qr(r,jr(t.indirectBuffer)),r=qr(r,e.indirectStartIndex),r=qr(r,e.indirectCount),r=qr(r,this.sampleCount),r=qr(r,e.material.version),r=qr(r,this.graphTextureResourceVersion),r=qr(r,i),r>>>0}getColorFormatsId(e){if(e===tl)return 1;const t=this.colorFormatsIdentityCache.get(e);if(void 0!==t)return t;const i=1===e.length?e[0]:e.join("|");let r=this.colorFormatsValueCache.get(i);return void 0===r&&(r=this.nextColorFormatsId,this.nextColorFormatsId+=1,this.colorFormatsValueCache.set(i,r)),this.colorFormatsIdentityCache.set(e,r),r}getDirectForwardBundleKey(e,t,i){let r=2166136261;r=qr(r,e.length),r=qr(r,this.sampleCount),r=qr(r,jr(t));for(let n=0;n<e.length;n+=1){const a=e[n],s=this.getMaterialResourceForDraw(a,i),o=this.resolveSceneBindGroupForDraw(a,t);r=qr(r,jr(a.material)),r=qr(r,a.receiveShadow?1:0),r=qr(r,a.material.version??0),r=qr(r,jr(s.pipeline)),r=qr(r,jr(s.bindGroup)),r=qr(r,jr(o)),r=qr(r,jr(a.geometryKey)),r=qr(r,jr(a.geometryResource.position)),r=qr(r,jr(a.geometryResource.normal)),r=qr(r,jr(a.geometryResource.uv)),r=qr(r,jr(a.geometryResource.color)),r=qr(r,a.geometryResource.index?jr(a.geometryResource.index):0);for(const e of a.geometryResource.extraAttributeBuffers.values())r=qr(r,jr(e));r=qr(r,a.indexed?1:0),r=qr(r,a.start),r=qr(r,a.count),r=qr(r,a.instanceStart),r=qr(r,a.instanceCount);const l=a.material.getTexturesList();r=qr(r,l.length);for(let e=0;e<l.length;e+=1){const t=l[e];r=qr(r,jr(t)),r=qr(r,t.version)}}return`forward-direct:${r}:${e.length}:samples=${this.sampleCount}:formats=${i.join("|")}`}getOrCreateDirectForwardBundle(e,t,i,r=tl){if(!this.state.device||!this.state.format||0===e.length)return null;const n=this.getDirectForwardBundleKey(e,t,r),a=this.state.directForwardBundleCache.get(n);if(a){for(let t=0;t<e.length;t+=1){const r=e[t];r.materialResource&&this.updateMaterialUniformBuffer(r.material,r.materialResource),this.recordDraw(r,i)}return a}const s=this.state.device.createRenderBundleEncoder({label:`renderer-direct-forward-bundle-${n}`,colorFormats:r,depthStencilFormat:"depth32float",sampleCount:this.sampleCount});let o=null,l=null,c=null,u=null;for(let n=0;n<e.length;n+=1){const a=e[n],d=a.geometryResource,h=this.getMaterialResourceForDraw(a,r),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,i)}const d=s.finish({label:`renderer-direct-forward-bundle-${n}`});return this.state.directForwardBundleCache.set(n,d),d}getOrCreateStaticMaterialBundle(e,t,i,r){const n=`${jr(t)}:${this.sampleCount}:${r.join("|")}`,a=this.materialPassStaticBundleCache.get(e)?.get(n);if(a)return this.recordStaticDrawStats(e,i),a;const s=this.getOrCreateDirectForwardBundle(e.draws,t,i,r);if(!s)return null;let o=this.materialPassStaticBundleCache.get(e);return o||(o=new Map,this.materialPassStaticBundleCache.set(e,o)),o.set(n,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 i=e.residentInstanceBinding,r=i.buffer,n=i.colorBuffer??i.buffer;return r&&n?(i.sceneBindGroup&&i.sceneBindGroupVersion===this.state.residentSceneBindGroupVersion||(i.sceneBindGroup=this.state.device.createBindGroup("instanced-direct"===i.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:r}},{binding:3,resource:{buffer:n}},{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},{binding:10,resource:this.state.spotLightMapView},{binding:11,resource:this.tiledPointLights.view}]}:{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:r}},{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:9,resource:this.state.spotLightMapView},{binding:11,resource:this.tiledPointLights.view}]}),i.sceneBindGroupVersion=this.state.residentSceneBindGroupVersion),i.sceneBindGroup):t}resolveShadowBindGroupForDraw(e,t,i=this.state.shadowCameraBuffer){if(!(e.residentInstanceBinding&&this.state.device&&this.state.shadowBindGroupLayout&&this.state.directShadowBindGroupLayout&&i&&e.residentInstanceBinding.buffer))return t;const r=e.residentInstanceBinding,n=r.buffer,a=r.colorBuffer??r.buffer;if(!n||!a)return t;if(r.shadowBindGroupVersion!==this.state.residentShadowBindGroupVersion&&(r.shadowBindGroup=null,r.shadowBindGroups.clear(),r.shadowBindGroupVersion=this.state.residentShadowBindGroupVersion),i===this.state.shadowCameraBuffer&&r.shadowBindGroup)return r.shadowBindGroup;const s=r.shadowBindGroups.get(i);if(s)return s;const o=this.state.device.createBindGroup("instanced-direct"===r.mode?{label:"renderer-resident-direct-shadow-bind-group",layout:this.state.directShadowBindGroupLayout,entries:[{binding:0,resource:{buffer:i}},{binding:1,resource:{buffer:n}},{binding:2,resource:{buffer:a}}]}:{label:"renderer-resident-shadow-bind-group",layout:this.state.shadowBindGroupLayout,entries:[{binding:0,resource:{buffer:i}},{binding:1,resource:{buffer:n}}]});return r.shadowBindGroups.set(i,o),i===this.state.shadowCameraBuffer&&(r.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*M;this.drawMetadataUpload.length<t&&(this.drawMetadataUpload=new Float32Array(Math.max(t,2*this.drawMetadataUpload.length,768)));const i=5*e.length;this.indirectDrawUpload.length<i&&(this.indirectDrawUpload=new Uint32Array(Math.max(i,2*this.indirectDrawUpload.length,320)));const r=this.drawMetadataUpload,n=this.indirectDrawUpload;for(let t=0;t<e.length;t+=1){const i=e[t],a=t*M;r[a+0]=i.boundsCenter.x,r[a+1]=i.boundsCenter.y,r[a+2]=i.boundsCenter.z,r[a+3]=i.boundsRadius,r[a+4]=i.count,r[a+5]=i.start,r[a+6]=i.instanceStart,r[a+7]=i.instanceCount,r[a+8]=1,r[a+9]=0,r[a+10]=0,r[a+11]=0;const s=5*t;n[s+0]=i.count,n[s+1]=i.instanceCount,n[s+2]=i.start,n[s+3]=0,n[s+4]=i.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*M*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,r,0,t),this.state.device.queue.writeBuffer(this.state.drawMetadataResource.indirectBuffer,0,n,0,i),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+=un(e)}executeVisibilityPass(e,t){qs.call(this,e,t)}executeStaticVisibilityPasses(e,t){Zs.call(this,e,t)}getOrCreateStaticVisibilityBindGroup(e,t){return Xs.call(this,e,t)}executeDirectionalShadowPass(e,t,i,r){Js.call(this,e,t,i,r)}executePointShadowPass(e,t,i,r){eo.call(this,e,t,i,r)}executeSpotShadowPass(e,t,i,r){to.call(this,e,t,i,r)}executeDepthPrepass(e,t,i,r){ro.call(this,e,t,i,r)}executeStaticDepthPrepass(e,t,i){no.call(this,e,t,i)}executeStaticTemporalDepthResolvePass(e){so.call(this,e)}getOrCreateStaticDepthPrepassBundle(e,t){return lo.call(this,e,t)}executeHiZPasses(e,t=!1,i=!1){ho.call(this,e,t,i)}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&&this.state.spotLightMapView))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}},{binding:9,resource:this.state.spotLightMapView},{binding:11,resource:this.tiledPointLights.view}]}),e.visibleSceneBindGroupVersion=this.state.residentSceneBindGroupVersion),e.visibleSceneBindGroup}getOrCreateStaticVisibleDepthSceneBindGroup(e){if(!(this.state.device&&this.state.visibleDepthSceneBindGroupLayout&&this.state.cameraBuffer&&this.state.lightBuffer))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:1,resource:{buffer:this.state.lightBuffer}},{binding:2,resource:{buffer:e.instanceBuffer}},{binding:3,resource:{buffer:e.instanceVisibilityResource.visibleInstanceIndicesBuffer}}]}),e.visibleDepthSceneBindGroupVersion=this.state.residentSceneBindGroupVersion),e.visibleDepthSceneBindGroup}executeMaterialPass(e,t,i,r,n,a={},s){if(!this.state.mainDepthView||0===t.length)return;const o=t.map(e=>this.getColorTargetFormat(e)),l=this.getColorFormatsId(o),c=t.map(e=>s?.colorView??this.getColorTargetView(e)),u=!s&&this.sampleCount>1,d=u?t.map(e=>this.ensureMsaaColorTarget(e)):[],h=this.getColorTargetDimensions(t[0]),p=u?this.ensureMsaaDepthTarget(h.width,h.height):null,f=e.beginRenderPass({label:"renderer-material-pass",colorAttachments:t.map((e,t)=>({view:d[t]?.view??c[t],resolveTarget:d[t]?c[t]:void 0,clearValue:1===t?{r:.5,g:.5,b:1,a:1}:t>=2?{r:0,g:0,b:0,a:1}:{r:a.clearColor?.[0]??this.clearColor[0],g:a.clearColor?.[1]??this.clearColor[1],b:a.clearColor?.[2]??this.clearColor[2],a:a.clearColor?.[3]??this.clearColor[3]},loadOp:a.loadColor?"load":"clear",storeOp:d[t]?"discard":"store"})),depthStencilAttachment:{view:s?.depthView??p?.view??this.state.mainDepthView,depthClearValue:1,depthLoadOp:p?"clear":a.loadDepth?"load":"clear",depthStoreOp:p?"discard":"store"}});let m=null,g=null,v=null,x=null,w=null;const b=e=>{e.sourceObject&&e.hasRenderCallbacks&&e.sourceObject.onBeforeRender(this,r.scene,r.camera,e.geometry,e.material,e.geometryGroup);const t=e.geometryResource;let a=e.material;const l=this.getMaterialResourceForDraw(e,o,s?1:this.sampleCount),c=this.resolveSceneBindGroupForDraw(e,i);if(m!==l.pipeline&&(m=l.pipeline,v=null,w=null,f.setPipeline(m)),v!==e.geometryKey&&(v=e.geometryKey,this.bindGeometryVertexBuffers(f,e.geometry,t,l.vertexAttributes,e.instanceStart,e.instanceCount,e.wireframe)),x!==c&&(x=c,f.setBindGroup(0,c)),g!==a){if(g=a,f.setBindGroup(1,l.bindGroup),!l.graphTextureBindGroupLayout)throw new Error("Graph texture layout is missing.");f.setBindGroup(3,this.createGraphTextureBindGroup(a,l.graphTextureBindGroupLayout))}l.usesSkinning&&e.skinning&&w!==e.skinning.bindGroup&&(w=e.skinning.bindGroup,f.setBindGroup(2,w)),e.indexed&&(e.wireframe?t.wireframeIndex:t.index)?f.drawIndexed(e.count,e.instanceCount,e.start,0,e.instanceStart):f.draw(e.count,e.instanceCount,e.start,e.instanceStart),this.recordDraw(e,n),e.sourceObject&&e.hasRenderCallbacks&&e.sourceObject.onAfterRender(this,r.scene,r.camera,e.geometry,e.material,e.geometryGroup)},y=a.drawStage??"all";if(a.objectFilter||a.overrideMaterial){const e=e=>{if(s){if(!this.isSphereVisibleScratch(e.boundsCenter.x,e.boundsCenter.y,e.boundsCenter.z,e.boundsRadius,!0))return;if(e.material.requiresLatePass())return;this.prepareDrawGeometryVertexBuffers(e),e={...e,receiveShadow:!1,materialResource:null}}if(a.objectFilter){const t=e.sourceRanges?.filter(e=>a.objectFilter(e.sourceObject));if(0===t?.length)return;if(null!=t&&t.length<e.sourceRanges.length){const i="function"==typeof a.overrideMaterial?a.overrideMaterial(e.material,null!==e.skinning):a.overrideMaterial;if(null===i)return;for(const r of t)b({...e,sourceObject:r.sourceObject,instanceStart:r.instanceStart,instanceCount:r.instanceCount,material:i??e.material,sourceRanges:void 0});return}if(null==t&&!a.objectFilter(e.sourceObject))return}const t="function"==typeof a.overrideMaterial?a.overrideMaterial(e.material,null!==e.skinning):a.overrideMaterial;null!==t&&b(t?{...e,material:t}:e)};if("late"!==y){for(const t of this.getCameraStaticDrawSets())if(t.publicSet.enabled&&"opaque"===t.drawStage)for(const i of t.draws)e(i);for(const t of r.gpuOpaqueDraws)e(t);for(const t of r.directOpaqueDraws)e(t)}if("opaque"!==y){if(s)for(const t of this.staticDrawSets)if(t.publicSet.enabled&&"late"===t.drawStage)for(const i of t.draws)e(i);for(const t of r.transparentDraws)e(t)}return void f.end()}if("late"!==y){const e=this.renderBundleScratch;e.length=0;for(const t of this.getCameraStaticDrawSets()){if(!t.publicSet.enabled||!this.isStaticDrawSetCameraVisible(t)||0===t.draws.length||"opaque"!==t.drawStage)continue;if(this.getHiZOcclusionCullingActive()&&t.lastVisibilityFrameToken===this.staticFrameToken){const i=this.getOrCreateStaticVisibleSceneBindGroup(t),r=this.getOrCreateStaticIndirectSubmissionStreams(t,i,o);for(const i of r){if(this.getMultiDrawIndirectActive()){if(e.length&&(f.executeBundles(e),e.length=0),f.setPipeline(i.materialResource.pipeline),this.bindGeometryVertexBuffers(f,i.geometry,i.geometryResource,i.materialResource.vertexAttributes,0,1,i.material.wireframe),f.setBindGroup(0,i.sceneBindGroup),f.setBindGroup(1,i.materialResource.bindGroup),!i.materialResource.graphTextureBindGroupLayout)throw new Error("Graph texture layout is missing.");f.setBindGroup(3,this.createGraphTextureBindGroup(i.material,i.materialResource.graphTextureBindGroupLayout)),f.multiDrawIndexedIndirect(t.drawMetadataResource.indirectBuffer,5*i.indirectStartIndex*Uint32Array.BYTES_PER_ELEMENT,i.indirectCount)}else e.push(this.getOrCreateIndirectForwardBundle(i,t.drawMetadataResource,t.indirectForwardBundleCache,`${t.label}-static-indirect-material-bundle`,o,!1,l));n.drawCallCount+=i.drawCallCount,n.triangleCount+=i.triangleCount}continue}const r=this.getOrCreateStaticMaterialBundle(t,i,n,o);r&&e.push(r)}if(e.length&&f.executeBundles(e),e.length=0,this.getHiZOcclusionCullingActive()&&this.state.drawMetadataResource){const e=this.indirectMaterialResourcesScratch;e.length=r.gpuOpaqueDraws.length;for(let t=0;t<r.gpuOpaqueDraws.length;t+=1)e[t]=this.getMaterialResourceForDraw(r.gpuOpaqueDraws[t],o);const t=this.buildIndirectSubmissionStreams(r.gpuOpaqueDraws,i,void 0,e);for(const e of t){const t=this.getOrCreateIndirectForwardBundle(e,this.state.drawMetadataResource,this.state.indirectForwardBundleCache,"renderer-indirect-material-bundle",o,!0,l);t?(this.renderBundleScratch[0]=t,f.executeBundles(this.renderBundleScratch)):this.submitIndirectStreamDirect(f,e,this.state.drawMetadataResource),n.drawCallCount+=e.drawCallCount,n.triangleCount+=e.triangleCount}}else{const e=Hr(r.gpuOpaqueDraws)||r.gpuOpaqueDraws.some(e=>null!==e.skinning)?null:this.getOrCreateDirectForwardBundle(r.gpuOpaqueDraws,i,n,o);if(e)this.renderBundleScratch[0]=e,f.executeBundles(this.renderBundleScratch);else for(const e of r.gpuOpaqueDraws)b(e)}const t=Hr(r.directOpaqueDraws)||r.directOpaqueDraws.some(e=>null!==e.skinning)?null:this.getOrCreateDirectForwardBundle(r.directOpaqueDraws,i,n,o);if(t)this.renderBundleScratch[0]=t,f.executeBundles(this.renderBundleScratch);else for(const e of r.directOpaqueDraws)b(e)}if("opaque"!==y)for(const e of r.transparentDraws)b(e);f.end()}executeForwardPass(e,t,i,r,n,a,s=!1,o="all",l=!1,c=this.sampleCount){po.call(this,e,t,i,r,n,a,s,o,l,c)}executeStaticForwardPass(e,t,i,r="all",n=this.sampleCount){fo.call(this,e,t,i,r,n)}getOrCreateStaticDirectForwardBundle(e,t,i=this.sampleCount){return mo.call(this,e,t,i)}refreshStaticDrawMaterialResources(e){vo.call(this,e)}syncStaticVisibleMaterialBindingCaches(e){go.call(this,e)}recordStaticDrawStats(e,t){xo.call(this,e,t)}hasEnabledStaticDrawSets(){return wo.call(this)}executePresentPass(e,t,i){bo.call(this,e,t,i)}clearDirectionalShadow(e){yo.call(this,e)}clearPointShadow(e){So.call(this,e)}clearSpotShadow(e){Co.call(this,e)}drawDepthLike(e,t,i,r){Mo.call(this,e,t,i,r)}getGeometryResource(e,t=!1){if(!this.state.device)throw new Error("Renderer is not initialized.");const i=this.geometryCache.get(e);if((t||!this.invokeObjectRenderCallbacks)&&i&&i.lastValidatedExtractionVersion===this.extractionVersion)return i;if(i&&this.updateDynamicGeometryAttributes(e,i))return i.lastValidatedExtractionVersion=this.extractionVersion,i;if(i&&i.lastValidatedExtractionVersion===this.extractionVersion)return i;if(i&&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 i=0;i<t.groups.length;i+=1){const r=t.groups[i],n=e.groups[i];if(r.start!==n?.start||r.count!==n?.count||r.materialIndex!==(n?.materialIndex??0))return!1}for(let i=0;i<t.attributes.length;i+=1){const r=t.attributes[i],n=e.getAttribute(r.name);if(n?n!==r.source||vr(n)!==r.version||n.itemSize!==r.itemSize||n.count!==r.count:0!==r.version||0!==r.itemSize||0!==r.count)return!1}return!0}(e,i))return i.lastValidatedExtractionVersion=this.extractionVersion,i;i&&(this.clearIndirectBundleCache(),this.retireGeometryResource(i));const r=e.getAttribute("position");if(!r)throw new Error("BufferGeometry is missing the required position attribute.");const n=r.count,a=Rr(r,n,3,[0,0,0]),s=Rr(e.getAttribute("normal"),n,3,[0,0,1]),o=Rr(e.getAttribute("uv"),n,2,[0,0]),l=Rr(e.getAttribute("color"),n,4,[1,1,1,1]),c=e.getAttribute("skinIndex"),u=e.getAttribute("skinWeight"),d=c?Vr(c,n,"uint32x4",[]):void 0,h=u?Vr(u,n,"float32x4",[]):void 0,p={signature:xr(e),indexVersion:e.index?.version??0,drawRangeStart:e.drawRange.start,drawRangeCount:e.drawRange.count,vertexCount:n,attributes:["position","normal","uv","color",...c?["skinIndex"]:[],...u?["skinWeight"]:[]].map(t=>{const i=e.getAttribute(t);return{name:t,source:i,version:vr(i),itemSize:i?.itemSize??0,count:i?.count??0}}),lastValidatedExtractionVersion:this.extractionVersion,groups:e.groups.map(e=>({start:e.start,count:e.count,materialIndex:e.materialIndex??0})),...this.createGeometryBuffers(e.uuid,a,s,o,l,d,h,e.index?.array),extraAttributeBuffers:new Map,extraAttributeBufferVersions:new Map,wireframeIndex:null,wireframeIndexFormat:null};return this.geometryCache.set(e,p),p}updateDynamicGeometryAttributes(e,t){if(!this.state.device)return!1;let i=!1;for(const r of t.attributes){const t=e.getAttribute(r.name),n=t?.itemSize??0,a=t?.count??0;if(n!==r.itemSize||a!==r.count)return!1;i||=t!==r.source||vr(t)!==r.version}if(!i)return!1;if(t.indexVersion!==(e.index?.version??0)||t.drawRangeStart!==e.drawRange.start||t.drawRangeCount!==e.drawRange.count||t.groups.length!==e.groups.length)return!1;for(let i=0;i<t.groups.length;i++){const r=t.groups[i],n=e.groups[i];if(r.start!==n?.start||r.count!==n?.count||r.materialIndex!==(n?.materialIndex??0))return!1}const r={position:{buffer:t.position,format:"float32x3",defaults:[0,0,0]},normal:{buffer:t.normal,format:"float32x3",defaults:[0,0,1]},uv:{buffer:t.uv,format:"float32x2",defaults:[0,0]},color:{buffer:t.color,format:"float32x4",defaults:[1,1,1,1]},skinIndex:{buffer:t.skinIndex,format:"uint32x4",defaults:[0,0,0,0]},skinWeight:{buffer:t.skinWeight,format:"float32x4",defaults:[0,0,0,0]}};for(const i of t.attributes){const t=e.getAttribute(i.name),n=vr(t),a=t!==i.source;if(!a&&n===i.version)continue;const s=r[i.name];if(!t||!s?.buffer)return!1;const o=Number(s.format.at(-1)),l=!a&&"updateRanges"in t&&t.updateRanges.length>0?t.updateRanges:[{start:0,count:t.count*t.itemSize}];for(const e of l){const i=Math.max(0,Math.floor(e.start/t.itemSize)),r=Math.min(t.count,Math.ceil((e.start+e.count)/t.itemSize));if(r<=i)continue;if(t instanceof ia&&!t.normalized&&t.itemSize===o&&("uint32x4"===s.format&&t.array instanceof Uint32Array||"uint32x4"!==s.format&&t.array instanceof Float32Array)){this.state.device.queue.writeBuffer(s.buffer,i*o*4,t.array.buffer,t.array.byteOffset+i*o*4,(r-i)*o*4);continue}const n="uint32x4"===s.format?new Uint32Array((r-i)*o):new Float32Array((r-i)*o);for(let e=i;e<r;e++){const r=(e-i)*o;for(let i=0;i<o;i++){const a=0===i?t.getX(e):1===i&&t.itemSize>1?t.getY(e):2===i&&t.itemSize>2?t.getZ(e):3===i&&t.itemSize>3?t.getW(e):void 0;n[r+i]=a??s.defaults[i]??0}}this.state.device.queue.writeBuffer(s.buffer,i*o*4,n)}"clearUpdateRanges"in t&&t.clearUpdateRanges(),i.version=n,i.source=t}return t.signature=xr(e),!0}getSkinnedGeometryResource(e){if(!this.state.device)throw new Error("Renderer is not initialized.");const t=e.geometry.getAttribute("skinIndex"),i=e.geometry.getAttribute("skinWeight"),r=e.geometry.getAttribute("position");if(!t||!i||!r)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 n=this.getGeometryResource(e.geometry);let a=this.skinnedGeometryCache.get(e);if(!a||a.resource!==n||a.positionAttribute!==r||a.positionVersion!==vr(r)||a.skinIndexAttribute!==t||a.skinIndexVersion!==vr(t)||a.skinWeightAttribute!==i||a.skinWeightVersion!==vr(i)||a.boneCount!==e.skeleton.bones.length||a.skinning.palette.skeleton!==e.skeleton){a&&(a.skinning.releaseInstance(),a.skinning.bindUniformBuffer.destroy());const s=this.getSkinningPalette(e.skeleton),o=this.state.device.createBuffer({label:`${e.uuid}-skinning-bind-matrices`,size:64*Float32Array.BYTES_PER_ELEMENT,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),l=new Float32Array(64);l.set(e.bindMatrix.elements,0),l.set(e.bindMatrixInverse.elements,16),l.copyWithin(32,0,32);const c={releaseInstance:mn(e,()=>this.releaseSkinnedMeshResources(e)),bindGroup:this.state.device.createBindGroup({label:`${e.uuid}-skinning-bind-group`,layout:this.state.skinningBindGroupLayout,entries:[{binding:0,resource:s.allocation.currentBinding},{binding:1,resource:{buffer:o}},{binding:2,resource:s.allocation.previousBinding}]}),bindUniformBuffer:o,bindMatrices:l,bindMatrixHistory:new Float32Array(32),lastBindRefreshExtractionVersion:-1,palette:s,bindUniformDirty:!0},u={positionAttribute:r,positionVersion:vr(r),skinIndexAttribute:t,skinIndexVersion:vr(t),skinWeightAttribute:i,skinWeightVersion:vr(i),boneCount:e.skeleton.bones.length,resource:n,skinning:c,boneBounds:this.createSkinningBoneBounds(e,r,t,i),localBoundsMin:new xa,localBoundsMax:new xa,localBoundsCenter:new xa,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&&t.previousMatrices.length===16*e.bones.length)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 i=16*e.bones.length;t&&(t.releaseExternal?.(),this.skinningPaletteArena.release(t.allocation),t.standaloneBuffer?.destroy(),this.skinPaletteResources.delete(t)),e.boneMatrices.length<i&&(e.boneMatrices=new Float32Array(i)),this.skeletonPalettes.update(e);const r=new Float32Array(i);for(let t=0;t<i;t++)r[t]=e.boneMatrices[t];const n=(this.skinningPaletteArena??=new Yn(this.state.device)).allocate(e.bones.length),a={skeleton:e,allocation:n,standaloneDirty:!0,matrixBuffer:n.page.current,previousMatrixBuffer:n.page.previous,previousMatrices:r,dirty:!0,previousDirty:!0,previousNeedsAdvance:!1,lastRefreshExtractionVersion:-1};this.skinPaletteCache.set(e,a),this.skinPaletteResources.add(a);const s=$i(e);return s&&(a.releaseExternal=function(e,t){let i=Oi.get(e);return i||(i=new Set,Oi.set(e,i)),i.add(t),()=>i.delete(t)}(s,()=>this.releaseSkinningPalette(a))),a}releaseSkinningPalette(e){if(this.skinPaletteResources.delete(e)){e.releaseExternal?.(),this.skinningPaletteArena.release(e.allocation),e.standaloneBuffer?.destroy(),this.skinPaletteCache.delete(e.skeleton);for(const[t,i]of this.skinnedGeometryCache)i.skinning.palette===e&&(this.releaseSkinnedRenderRecord(t),this.skinnedGeometryCache.delete(t)&&(i.skinning.releaseInstance(),i.skinning.bindUniformBuffer.destroy()))}}refreshSkinningPalette(e){if(null!==this.sceneCaptureOptions)return;if(e.lastRefreshExtractionVersion===this.extractionVersion)return;e.lastRefreshExtractionVersion=this.extractionVersion;const t=this.skeletonPalettes.update(e.skeleton);e.dirty||=t,e.standaloneDirty||=t,e.previousDirty||=t||e.previousNeedsAdvance,e.previousNeedsAdvance=t}refreshSkinningBindMatrices(e,t){const i=t.bindMatrices,r=null===this.sceneCaptureOptions&&t.lastBindRefreshExtractionVersion!==this.extractionVersion,n=t.lastBindRefreshExtractionVersion>=0,a=$i(e.skeleton),s=a?U.copy(e.matrixWorld).invert().multiply(a.root.matrixWorld).elements:e.bindMatrixInverse.elements;let o=!1;for(let a=0;a<16;a+=1){const l=Math.fround(e.bindMatrix.elements[a]),c=Math.fround(s[a]);if(i[a]===l&&i[a+16]===c||(o=!0),i[a]=l,i[a+16]=c,r){const e=n?t.bindMatrixHistory[a]:l,r=n?t.bindMatrixHistory[a+16]:c;o||=i[a+32]!==e||i[a+48]!==r,i[a+32]=e,i[a+48]=r,t.bindMatrixHistory[a]=l,t.bindMatrixHistory[a+16]=c}}r&&(t.lastBindRefreshExtractionVersion=this.extractionVersion),t.bindUniformDirty||=o}uploadSkinningPalette(e,t=!1){if(!this.state.device)return;const i=this.skinningPaletteArena;if(e.previousDirty&&(i.stage(e.allocation,e.previousMatrices,!0),e.previousDirty=!1),e.dirty){const t=e.skeleton.boneMatrices;i.stage(e.allocation,t,!1);const r=e.previousMatrices;if(t.length===r.length)r.set(t);else for(let e=0;e<r.length;e++)r[e]=t[e];e.dirty=!1}t||i.flush()}uploadSkinningResources(e){this.state.device&&(this.uploadSkinningPalette(e.palette,!0),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,i,r){const n=Array.from({length:e.skeleton.bones.length},()=>new xa(1/0,1/0,1/0)),a=Array.from({length:e.skeleton.bones.length},()=>new xa(-1/0,-1/0,-1/0));for(let e=0;e<t.count;e+=1){F.set(t.getX(e),t.getY(e),t.getZ(e));for(let t=0;t<4;t+=1){if(r.getComponent(e,t)<=0)continue;const s=Math.round(i.getComponent(e,t)),o=n[s],l=a[s];o&&l&&(o.min(F),l.max(F))}}return n.map((e,t)=>{if(!Number.isFinite(e.x))return null;const i=a[t],r=e.clone().add(i).multiplyScalar(.5);return{center:r,radius:i.distanceTo(r)}})}updateSkinnedBounds(e,t){const i=t.localBoundsMin,r=t.localBoundsMax,n=$i(e.skeleton),a=n?U.copy(e.matrixWorld).invert().multiply(n.root.matrixWorld):e.bindMatrixInverse,s=sn(e.geometry);i.set(s.center.x-s.radius,s.center.y-s.radius,s.center.z-s.radius),r.set(s.center.x+s.radius,s.center.y+s.radius,s.center.z+s.radius);for(let n=0;n<t.boneBounds.length;n+=1){const s=t.boneBounds[n];if(!s)continue;const o=ln(s.center,s.radius,e.bindMatrix,t.skinning.palette.skeleton.boneMatrices,16*n,a,F);i.min(O.copy(F).addScalar(-o)),r.max(O.copy(F).addScalar(o))}t.localBoundsCenter.copy(i).add(r).multiplyScalar(.5),t.localBoundsRadius=r.distanceTo(t.localBoundsCenter)}createGeometryBuffers(e,t,i,r,n,a,s,o,l=GPUBufferUsage.VERTEX,c=GPUBufferUsage.VERTEX){if(!this.state.device)throw new Error("Renderer is not initialized.");let u=null,d=null;if(o){const t=o instanceof Uint32Array?o:new Uint16Array(o);d=o instanceof Uint32Array?"uint32":"uint16",u=Pr(this.state.device,t,GPUBufferUsage.INDEX,`${e}-index`)}return{position:Pr(this.state.device,t,l|GPUBufferUsage.COPY_DST,`${e}-position`),normal:Pr(this.state.device,i,c|GPUBufferUsage.COPY_DST,`${e}-normal`),uv:Pr(this.state.device,r,GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST,`${e}-uv`),color:Pr(this.state.device,n,GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST,`${e}-color`),skinIndex:a?Pr(this.state.device,a,GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST,`${e}-skin-index`):null,skinWeight:s?Pr(this.state.device,s,GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST,`${e}-skin-weight`):null,index:u,indexFormat:d}}createVertexBufferLayouts(e){return this.getVertexAttributeGroups(e).map(e=>{let t=0;const i=e.map(e=>{const i={shaderLocation:e.shaderLocation,offset:t,format:e.format};return t+=4*wr(e.format),i});return{arrayStride:t,stepMode:e[0].stepMode??"vertex",attributes:i}})}getVertexAttributeGroups(e){const t=this.vertexAttributeGroupCache.get(e);if(t)return t;const i=this.state.device?.limits.maxVertexBuffers??8;if(e.length<=i){const t=e.map(e=>[e]);return this.vertexAttributeGroupCache.set(e,t),t}let r=e.length-i;const n=[],a=new Set;for(const t of["vertex","instance"]){if(0===r)break;const i=e.filter(e=>(e.stepMode??"vertex")===t),s=Math.min(i.length,r+1);if(s<2)continue;const o=i.slice(0,s);n.push(o);for(const e of o)a.add(e);r-=s-1}if(r>0)throw new Error(`Vertex attributes cannot be packed into the device's ${i} vertex-buffer slots.`);const s=[];for(const t of e){if(!a.has(t)){s.push([t]);continue}const e=n.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 i=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,i),i}getGeometryAttributeGroupBufferKey(e){const t=this.vertexAttributeGroupBufferKeyCache.get(e);if(void 0!==t)return t;const i=e.map(e=>this.getGeometryAttributeBufferKey(e)).join("|");return this.vertexAttributeGroupBufferKeyCache.set(e,i),i}getMaterialVertexAttributes(e,t){let i=this.materialVertexAttributeCache.get(e);if(i&&i.version===e.version||(i={version:e.version,unskinned:this.getSharedVertexAttributeLayout(e.vertexAttributes)},this.materialVertexAttributeCache.set(e,i)),!t)return i.unskinned;if(i.skinned)return i.skinned;const r=i.unskinned.slice(),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 i=r.find(t=>t.shaderLocation===e.shaderLocation);if(i)throw new Error(`Skinned material requires location ${e.shaderLocation} for "${e.name}", but it is used by "${i.name}".`);r.push(e)}return i.skinned=this.getSharedVertexAttributeLayout(r),i.skinned}getSharedVertexAttributeLayout(e){const t=JSON.stringify(e.map(e=>[e.name,e.shaderLocation,e.format,e.stepMode??"vertex",e.defaultValue??null]));let i=this.sharedVertexAttributeLayouts.get(t);return i||(i=e.map(e=>({...e,defaultValue:e.defaultValue?.slice()})),this.sharedVertexAttributeLayouts.set(t,i)),i}getGeometryVertexBuffer(e,t,i,r=0,n=1){if(!this.state.device)throw new Error("Renderer is not initialized.");const a=this.getStandardVertexAttribute(i);if(a){const e=t[a];if(e)return e}const s=e.getAttribute(i.name),o="instance"===i.stepMode,l=o?Math.max(0,Math.trunc(r)):0;if(!s&&(o||i.defaultValue)){const e=this.getDefaultVertexAttributeBuffer(i,o?l+Math.max(1,n):t.vertexCount);return this.cacheGeometryVertexBufferFast(t,i,l,void 0,0,e),e}const c=vr(s),u=this.geometryVertexBufferFastCache.get(t),d=u?.get(i),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(i)}${o?`:instance-start=${l}`:""}`,f=s?`${c}:${s.itemSize}:${s.count}`:"default",m=t.extraAttributeBuffers.get(p);if(m&&h?.source===s&&t.extraAttributeBufferVersions.get(p)===f)return this.cacheGeometryVertexBufferFast(t,i,l,s,c,m),m;if(!s&&!i.defaultValue)throw new Error(`Geometry "${e.uuid}" is missing required vertex attribute "${i.name}".`);const g=Vr(s,o?l+Math.max(1,s?.count??1,n):t.vertexCount,i.format,i.defaultValue??[],o?l:0,h?.staging);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,i,l,s,c,m,g),m;const v=Pr(this.state.device,g,GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST,`${e.uuid}-${i.name}-${i.format}`);return m&&(this.clearIndirectBundleCache(),this.retiredGeometryBuffers.push(m)),t.extraAttributeBuffers.set(p,v),t.extraAttributeBufferVersions.set(p,f),this.cacheGeometryVertexBufferFast(t,i,l,s,c,v,g),v}cacheGeometryVertexBufferFast(e,t,i,r,n,a,s){let o=this.geometryVertexBufferFastCache.get(e);o||(o=new WeakMap,this.geometryVertexBufferFastCache.set(e,o));let l=o.get(t);l||(l=new Map,o.set(t,l));const c=r,u=l.get(i);u&&u.buffer!==a&&this.clearIndirectBundleCache(),l.set(i,{source:r,version:n,itemSize:c?.itemSize??0,count:c?.count??0,buffer:a,staging:s&&s.buffer!==(c?.array??c?.data?.array)?.buffer?s:void 0})}packedVertexGroups=new WeakMap;getInterleavedGeometryVertexBuffer(e,t,i,r,n){if(!this.state.device)throw new Error("Renderer is not initialized.");const a=i[0].stepMode??"vertex",s="instance"===a?Math.max(0,Math.trunc(r)):0,o=`interleaved:${this.getGeometryAttributeGroupBufferKey(i)}:instance-start=${s}`;let l=this.packedVertexGroups.get(t);l||(l=new Map,this.packedVertexGroups.set(t,l));let c=l.get(o);c||(c=new yn(i),l.set(o,c));const u=c.update(e,t.vertexCount,s,n,"instance"===a?this.getInstanceVertexCapacity():0),d=t.extraAttributeBuffers.get(o);if(!u&&d)return d;const h=c.data;if(d&&d.size>=Math.max(4,h.byteLength))return this.state.device.queue.writeBuffer(d,0,h.buffer,h.byteOffset,h.byteLength),d;const p=Pr(this.state.device,h,GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST,`${e.uuid}-interleaved-${a}`);return d&&(this.clearIndirectBundleCache(),this.retiredGeometryBuffers.push(d)),t.extraAttributeBuffers.set(o,p),p}ensureWireframeIndex(e,t){if(t.wireframeIndex)return;if(!this.state.device)throw new Error("Renderer is not initialized.");const i=e.index?.array,r=i?.length??t.vertexCount,n=Math.floor(r/3),a=t.vertexCount>65535,s=a?new Uint32Array(6*n):new Uint16Array(6*n);for(let e=0;e<n;e+=1){const t=3*e,r=6*e,n=i?i[t]:t,a=i?i[t+1]:t+1,o=i?i[t+2]:t+2;s[r]=n,s[r+1]=a,s[r+2]=a,s[r+3]=o,s[r+4]=o,s[r+5]=n}t.wireframeIndexFormat=a?"uint32":"uint16",t.wireframeIndex=Pr(this.state.device,s,GPUBufferUsage.INDEX,`${e.uuid}-wireframe-index`)}bindGeometryVertexBuffers(e,t,i,r,n=0,a=1,s=!1){const o=this.prepareGeometryVertexBuffers(t,i,r,n,a);for(let t=0;t<o.length;t+=1)e.setVertexBuffer(t,o[t]);s&&i.wireframeIndex&&i.wireframeIndexFormat?e.setIndexBuffer(i.wireframeIndex,i.wireframeIndexFormat):i.index&&i.indexFormat&&e.setIndexBuffer(i.index,i.indexFormat)}prepareGeometryVertexBuffers(e,t,i,r,n,a=!1){let s=this.preparedVertexBufferCache.get(t);s||(s=new WeakMap,this.preparedVertexBufferCache.set(t,s));let o=s.get(i);o||(o={instanced:i.some(e=>"instance"===e.stepMode),ranges:new Map},s.set(i,o));const l=o.instanced?Math.max(0,Math.trunc(r)):0,c=o.instanced?n:1,u=o.instanced?this.getInstanceVertexCapacity():0;let d=o.ranges.get(l);if((a||!this.invokeObjectRenderCallbacks)&&d&&d.extractionVersion===this.extractionVersion&&d.instanceCount===c&&d.instanceCapacity===u&&d.instanceBufferSize===this.state.instanceBufferSize)return d.buffers;d||(d={extractionVersion:-1,instanceCount:c,instanceBufferSize:0,instanceCapacity:0,buffers:[]},o.ranges.set(l,d));let h=this.vertexBufferBindingPlanCache.get(i);h||(h=this.getVertexAttributeGroups(i).map(e=>({group:e,standardAttribute:1===e.length?this.getStandardVertexAttribute(e[0]):null})),this.vertexBufferBindingPlanCache.set(i,h));for(let i=0;i<h.length;i+=1){const{group:a,standardAttribute:s}=h[i],o=s?t[s]:null;d.buffers[i]=o??(1===a.length?this.getGeometryVertexBuffer(e,t,a[0],r,n):this.getInterleavedGeometryVertexBuffer(e,t,a,r,n))}return d.extractionVersion=this.extractionVersion,d.instanceCount=c,d.instanceBufferSize=this.state.instanceBufferSize,d.instanceCapacity=u,d.buffers}getStandardVertexAttribute(e){let t=this.standardVertexAttributeCache.get(e);return void 0!==t||(t="position"===e.name&&"float32x3"===e.format?"position":"normal"!==e.name||"float32x3"!==e.format||void 0!==e.defaultValue&&!Ir(e.defaultValue,cl)?"uv"!==e.name||"float32x2"!==e.format||void 0!==e.defaultValue&&!Ir(e.defaultValue,ll)?"color"!==e.name||"float32x4"!==e.format||void 0!==e.defaultValue&&!Ir(e.defaultValue,ul)?"skinIndex"===e.name&&"uint32x4"===e.format?"skinIndex":"skinWeight"===e.name&&"float32x4"===e.format?"skinWeight":null:"color":"uv":"normal",this.standardVertexAttributeCache.set(e,t)),t}prepareDrawGeometryVertexBuffers(e,t=!1){for(let i=0;i<(e.customDepthMaterial?2:1);i++){const r=0===i?e.material:e.customDepthMaterial,n=this.getMaterialVertexAttributes(r,null!==e.skinning);this.prepareGeometryVertexBuffers(e.geometry,e.geometryResource,n,e.instanceStart,e.instanceCount,t)}}getInstanceVertexCapacity(){return Math.max(Math.ceil(this.state.instanceBufferSize/(Float32Array.BYTES_PER_ELEMENT*C)),this.staticInstanceSlots.instanceCapacity,this.skinnedInstanceSlots.instanceCapacity)}getDefaultVertexAttributeBuffer(e,t){if(!this.state.device)throw new Error("Renderer is not initialized.");const i=Math.max(1,t,"instance"===e.stepMode?this.getInstanceVertexCapacity():0),r=2**Math.ceil(Math.log2(i)),n=`${e.format}:${(e.defaultValue??[]).join(",")}`;let a=this.defaultVertexAttributeBuffers.get(n);a||(a=new Map,this.defaultVertexAttributeBuffers.set(n,a));const s=a.get(r);if(s)return s;const o=Pr(this.state.device,Vr(void 0,r,e.format,e.defaultValue??[]),GPUBufferUsage.VERTEX,`renderer-default-attribute-${e.format}`);return a.set(r,o),o}getMeshExtractionCacheEntry(e,t,i,r,n,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===n&&(null!==l&&s.material===l&&s.resolvedMaterial===i||null!==o&&null!==s.materials&&null!==s.resolvedMaterials&&Mr(s.materials,o)&&Dr(s.resolvedMaterials,r)))return s;const c=null!==e.geometry.index,u=sn(e.geometry),d=[];if(e.geometry.groups.length>0)for(const t of e.geometry.groups){const s=o?r[t.materialIndex??0]??r[0]:i;if(!s)continue;const l=Gr(e.geometry,c,t.start,t.count),u=$r(s,e.geometry,c,t.start,l,n),h=jr(s),p=jr(e.geometry),f=n?jr(n):0;d.push({geometry:e.geometry,geometryKey:e.geometry,geometryResource:a,material:s,customDepthMaterial:n,residentInstanceBinding:null,sourceObject:e,frontFaceCW:e.matrixWorld.determinant()<0,usesBatching:!1,geometryGroup:t,batchKey:u,batchHash:Wr(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=i??r?.[0]??null;if(t){const i=zr(e.geometry,c),r=$r(t,e.geometry,c,i.start,i.count,n),s=jr(t),o=jr(e.geometry),l=n?jr(n):0;d.push({geometry:e.geometry,geometryKey:e.geometry,geometryResource:a,material:t,customDepthMaterial:n,residentInstanceBinding:null,sourceObject:e,frontFaceCW:e.matrixWorld.determinant()<0,usesBatching:!1,geometryGroup:null,batchKey:r,batchHash:Wr(s,o,c,i.start,i.count,l),indexed:c,wireframe:t.wireframe&&"triangle-list"===t.primitiveTopology,start:i.start,count:i.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:i,resolvedMaterials:o?r.slice():null,customDepthMaterial:n,indexed:c,templates:d,localBoundsCenter:u.center.clone(),localBoundsRadius:u.radius};return this.meshExtractionCache.set(e,h),h}getInstancedMeshExtractionCacheEntry(e,t,i,r){const n=null!==e.geometry.index,a=zr(e.geometry,n),s=sn(e.geometry),o=this.instancedMeshExtractionCache.get(e);if(o&&o.geometryResource===r&&o.material===t&&o.customDepthMaterial===i&&o.indexed===n&&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=jr(t),c=jr(e.geometry),u=i?jr(i):0,d={geometryResource:r,sourceMesh:e,sourceMaterial:e.material,sourceMaterialVersion:e.material.version,material:t,customDepthMaterial:i,indexed:n,drawRangeStart:a.start,drawRangeCount:a.count,batchKey:$r(t,e,n,a.start,a.count,i),batchHash:Wr(l,c,n,a.start,a.count,u),sortMaterialId:l,sortGeometryId:c,sortCustomDepthMaterialId:u,localBoundsCenter:s.center.clone(),localBoundsRadius:s.radius,cachedInstanceData:new vn(1024),cachedBoundsMin:new xa,cachedBoundsMax:new xa,cachedDrawBoundsCenter:new xa,cachedDrawBoundsRadius:0,cachedMatrixWorld:new Float64Array(16),cachedInstanceMatrixVersion:-1,cachedInstanceColorVersion:-1,cachedCount:0,cachedBoundsValid:!1,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,i,r,n){const a=n._geometryCount??0,s=this.batchedMeshExtractionCache.get(e);if(s&&s.geometryResource===r&&s.material===t&&s.customDepthMaterial===i&&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 n=0;n<a;n+=1){const a=e.getGeometryRangeAt(n);if(!a||a.count<=0)continue;const s=Gr(e.geometry,o,a.start,a.count),u=$r(t,e.geometry,o,a.start,s,i),d=jr(t),h=jr(e.geometry),p=i?jr(i):0,f=e.getBoundingSphereAt(n,k),m={geometry:e.geometry,geometryKey:e.geometry,geometryResource:r,material:t,customDepthMaterial:i,residentInstanceBinding:null,sourceObject:e,frontFaceCW:!1,usesBatching:!0,geometryGroup:null,batchKey:u,batchHash:Wr(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:n,localBoundsCenter:f?f.center.clone():new xa,localBoundsRadius:f?.radius??1};l[n]=m,c[n]={template:m,boundsMin:new xa,boundsMax:new xa,activeInFrame:!1,activeCount:0,instanceStart:0,writeOffset:0}}const u={geometryResource:r,material:t,customDepthMaterial:i,indexed:o,templates:l,groups:c,activeGroups:[],cachedInstanceData:new vn(1024),cachedDraws:[],cachedBoundsMin:new xa,cachedBoundsMax:new xa,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 i=0;i<t.length;i+=1){const r=t[i];if((e[i]??-1)!==(r?.active&&r.visible?r.geometryIndex:-1))return!1}return!0}destroyGeometryResource(e){e.position.destroy(),e.normal.destroy(),e.uv.destroy(),e.color.destroy(),e.skinIndex?.destroy(),e.skinWeight?.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(){if(0===this.retiredGeometryResources.length&&0===this.retiredGeometryBuffers.length&&0===this.retiredStaticInstanceSlots.length)return;const e=this.retiredGeometryResources.splice(0),t=this.retiredGeometryBuffers.splice(0),i=this.retiredStaticInstanceSlots.splice(0);if(this.state.device)this.state.device.queue.onSubmittedWorkDone().then(()=>{for(const e of i)this.staticInstanceSlots.release(e);for(const t of e)this.destroyGeometryResource(t);for(const e of t)e.destroy()},()=>{for(const e of i)this.staticInstanceSlots.release(e);for(const t of e)this.destroyGeometryResource(t);for(const e of t)e.destroy()});else{for(const e of i)this.staticInstanceSlots.release(e);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,i){this.textureManager.uploadDataTextureResource(e,t,i)}uploadCompressedTextureResource(e,t,i){this.textureManager.uploadCompressedTextureResource(e,t,i)}uploadExternalTextureResource(e,t,i){this.textureManager.uploadExternalTextureResource(e,t,i)}uploadTextureResource(e,t,i){this.textureManager.uploadTextureResource(e,t,i)}getTextureResource(e){return this.textureManager.getTextureResource(e)}updateMaterialUniformBuffer(e,t){if(!this.state.device||!t.uniformBuffer)return;const i=e.getUniformLayout();if(0===i.entries.length)return;let r=t.uniformValueHash;if(e.uniformValuesAutoUpdate){if(r=e.getUniformValueHash(),t.uniformValueHash===r)return}else if(t.uniformValuesAutoVersion===e.uniformValuesAutoVersion)return;if(i.byteLength>t.uniformBuffer.size)return;let n=this.materialUniformData.get(i);n||(n=new vi(i),this.materialUniformData.set(i,n));const a=n.update(e.uniforms);t.uniformValueHash=r,t.uniformValuesAutoVersion=e.uniformValuesAutoVersion,this.state.device.queue.writeBuffer(t.uniformBuffer,0,a)}materialResourceMatches(e,t,i,r=this.sampleCount){if(e.key!==i)return!1;if(e.materialVersion===t.version&&e.textureVersionHash===t.getTextureVersionHash()&&e.rendererSampleCount===r&&e.uniformBufferSize===t.getUniformLayout().byteLength)return!0;const n=Dr(e.textures,t.getTexturesList())&&Ir(e.textureVersions,t.getTextureVersionsList())&&Dr(e.storageBuffers,t.getStorageBufferList())&&e.rendererSampleCount===r&&e.uniformBufferSize===t.getUniformLayout().byteLength;return n&&(e.materialVersion=t.version,e.textureVersionHash=t.getTextureVersionHash()),n}destroyMaterialResource(e){e?.uniformBuffer?.destroy()}createMaterialBindGroupData(e,t,i){if(!this.state.device)throw new Error("Renderer is not initialized.");const r=this.pipelineCompilationDiagnostics,n=r?performance.now():0,a=[],s=[],o=Array.from(e.getTexturesList()),l=Array.from(e.getTextureVersionsList()),c=e.getStorageBufferBindingList();let u=null;const d=r?performance.now():0;if(Object.keys(e.uniforms).length>0){const i=function(e,t){const i=new ArrayBuffer(t.byteLength);return xi(e,t,new DataView(i),new Float32Array(i)),i}(e.uniforms,e.getUniformLayout());u=this.state.device.createBuffer({label:`${t}-uniforms`,size:i.byteLength,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this.state.device.queue.writeBuffer(u,0,i),a.push({binding:0,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}}),s.push({binding:0,resource:{buffer:u}})}r&&(r.cpuTotalsMs.uniformBuffer=(r.cpuTotalsMs.uniformBuffer??0)+performance.now()-d);for(const[t,n]of o.entries()){const o=1+2*t,l=r?performance.now():0,c=this.getTextureResource(n);if(r){const t=performance.now()-l;r.cpuTotalsMs.textureLookup=(r.cpuTotalsMs.textureLookup??0)+t,t>=1&&r.slowTextureLookups.push({material:e.name||e.uuid,texture:n.name||n.uuid,durationMs:t})}a.push({binding:o,visibility:i,sampler:{type:c.samplerBindingType}},{binding:o+1,visibility:i,texture:{sampleType:c.sampleType,viewDimension:c.viewDimension}}),s.push({binding:o,resource:c.sampler},{binding:o+1,resource:c.view})}const h=1+2*o.length,p=Array.from(e.getStorageBufferList());for(const[e,t]of c.entries()){const i=h+e;a.push({binding:i,visibility:Br(t.visibility),buffer:{type:"read_write"===t.access?"storage":"read-only-storage"}}),s.push({binding:i,resource:{buffer:t.buffer}})}return r&&(r.cpuTotalsMs.bindGroupData=(r.cpuTotalsMs.bindGroupData??0)+performance.now()-n),{bindGroupLayoutEntries:a,bindGroupEntries:s,uniformBuffer:u,textures:o,textureVersions:l,storageBuffers:p}}createGraphTextureBindGroupLayout(e){if(!this.state.device)throw new Error("Renderer is not initialized.");const t=[];return Object.values(e.getGraphTextureInputs()).forEach((e,i)=>{t.push({binding:2*i,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,sampler:{type:e.sampler??("depth-2d"===e.dimension?"non-filtering":"filtering")}},{binding:2*i+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 i=this.graphTextureBindGroupCache.get(e);const r=i?.get(t);if(r&&r.materialVersion===e.version&&r.resourceVersion===this.graphTextureResourceVersion)return r.bindGroup;const n=[];Object.values(e.getGraphTextureInputs()).forEach((e,t)=>{const i="comparison"===e.sampler?this.state.shadowComparisonSampler:"non-filtering"===e.sampler||"depth-2d"===e.dimension?this.state.nearestClampSampler:"physicalTransmissionSnapshot"===e.resource?this.transmissionSampler:this.state.linearClampSampler,r="mainDepth"===e.resource?this.state.sceneDepthSnapshotView:this.getGraphTextureView(e.resource);n.push({binding:2*t,resource:i},{binding:2*t+1,resource:r})});const a=this.state.device.createBindGroup({label:`${e.uuid}-graph-textures`,layout:t,entries:n});return i||(i=new WeakMap,this.graphTextureBindGroupCache.set(e,i)),i.set(t,{materialVersion:e.version,resourceVersion:this.graphTextureResourceVersion,bindGroup:a}),a}getGraphTextureView(e){return"physicalTransmissionSnapshot"===e?this.transmissionSnapshotView:"mainDepth"===e?this.state.mainDepthView:"sceneColorSnapshot"===e?this.state.sceneColorSnapshotView:"sceneDepthSnapshot"===e?this.state.hizMipViews[0]:this.getColorTargetView(e)}compileDrawMaterials(e){const t=new Set;for(const i of e){const e=this.getDrawInstanceAccessMode(i),r=null!==i.skinning,n=this.drawUsesBatching(i),a=`${i.material.uuid}:${e}:receiveShadow=${i.receiveShadow?1:0}:skinning=${r?1:0}:batching=${n?1:0}`;t.has(a)||(i.materialResource=this.getMaterialResource(i.material,e,i.receiveShadow,void 0,r,n),t.add(a))}}async compileDrawMaterialsAsync(e,t=tl,i=this.sampleCount,r=!0){const n=new Set,a=new Set,s=[],o=[],l=Jn();for(const c of e){const e=l();e&&await e;const u=this.getDrawInstanceAccessMode(c);r&&c.residentInstanceBinding&&c.sourceObject instanceof la&&o.push({...c,materialResource:null,residentInstanceBinding:{...c.residentInstanceBinding,mode:"packed"===u?"instanced-direct":"packed"}});const d=null!==c.skinning,h=this.drawUsesBatching(c),p=`${c.material.uuid}:${u}:receiveShadow=${c.receiveShadow?1:0}:skinning=${d?1:0}:batching=${h?1:0}`;if(n.has(p)||(s.push(this.getMaterialResourceAsync(c.material,u,c.receiveShadow,t,d,h,i).then(e=>(c.materialResource=e,e))),n.add(p)),c.customDepthMaterial){const e=`${c.customDepthMaterial.uuid}:${u}:skinning=${d?1:0}`;a.has(e)||(s.push(this.getDepthPassMaterialResourceAsyncForDraw(c.customDepthMaterial,"directionalShadow",c)),a.add(e))}if(null!==c.material.depthVertexShader||h){const e=null!==c.material.depthVertexShader?["prepass","directionalShadow","pointShadow"]:["prepass","directionalShadow"];for(const t of e){const e=`${c.material.uuid}:${t}:${u}:skinning=${d?1:0}:batching=${h?1:0}`;a.has(e)||(s.push(this.getDepthPassMaterialResourceAsyncForDraw(c.material,t,c)),a.add(e))}}}o.length>0&&s.push(this.compileDrawMaterialsAsync(o,t,i,!1)),await Promise.all(s)}async compileStaticDrawMaterialsAsync(e,t=this.sampleCount,i="all"){const r=[],n=new Set;for(const a of this.staticDrawSets)if(a.publicSet.enabled&&("all"===i||a.drawStage===i)){r.push(this.compileDrawMaterialsAsync(a.draws,e,t));for(const i of a.visibleMaterialBindings){const a=`${i.material.uuid}:receiveShadow=${i.receiveShadow?1:0}:batching=${i.usesBatching?1:0}`;n.has(a)||(n.add(a),r.push(this.getMaterialResourceAsync(i.material,"packed-visible",i.receiveShadow,e,!1,i.usesBatching,t)))}for(const e of a.draws){if(e.customDepthMaterial||null===e.material.depthVertexShader||e.material.vertexAttributes.some(e=>"instance"===e.stepMode))continue;const t=`prepass-visible:${e.material.uuid}:${this.drawUsesBatching(e)}:${Zr(e)}`;n.has(t)||(n.add(t),r.push(this.getDepthPassMaterialResourceAsync(e.material,"prepass","packed-visible",!1,this.drawUsesBatching(e),Zr(e))))}if(this.directionalShadowGpu.available)for(const e of a.draws){const t=e.customDepthMaterial??(null!==e.material.depthVertexShader?e.material:null);if(!t||t.vertexAttributes.some(e=>"instance"===e.stepMode))continue;const i=`shadow-visible:${t.uuid}:${this.drawUsesBatching(e)}:${Zr(e)}`;n.has(i)||(n.add(i),r.push(this.getDepthPassMaterialResourceAsync(t,"directionalShadow","packed-visible",!1,this.drawUsesBatching(e),Zr(e))))}}await Promise.all(r)}getDepthPassMaterialKey(e,t,i,r,n,a=!1){if(!this.state.device)throw new Error("Renderer is not initialized.");return`${e.getDepthProgramCacheKey("pointShadow"===t)}:${t}:instance=${i}:skinning=${r?1:0}:batching=${n?1:0}:frontFace=${a?"cw":"ccw"}:textures=${e.getTextureLayoutKey(this.state.device)}`}getForwardMaterialKey(e,t,i,r,n,a,s=!1,o=this.sampleCount){return`${e.customProgramCacheKey()}:instance=${t}:receiveShadow=${i?1:0}:skinning=${n?1:0}:batching=${a?1:0}:frontFace=${s?"cw":"ccw"}:textures=${e.getTextureLayoutKey(this.state.device)}:samples=${o}:targets=${r.join("|")}`}getInstanceAccessModeIndex(e){return"packed"===e?0:"packed-visible"===e?1:2}getForwardMaterialFastCacheIndex(e,t,i,r,n=!1){return this.getInstanceAccessModeIndex(e)|(t?4:0)|(i?8:0)|(r?16:0)|(n?32:0)}getDepthMaterialFastCacheIndex(e,t,i,r,n=!1){return("prepass"===e?0:"directionalShadow"===e?1:2)+3*this.getInstanceAccessModeIndex(t)+(i?9:0)+(r?18:0)+(n?36:0)}fastMaterialResourceMatches(e,t,i=this.sampleCount){return e.materialVersion===t.version&&e.textureVersionHash===t.getTextureVersionHash()&&e.rendererSampleCount===i}setForwardMaterialFastCache(e,t,i){let r=this.forwardMaterialFastCache.get(e);r||(r=[],this.forwardMaterialFastCache.set(e,r)),r[t]=i}getForwardMaterialTargetFastCacheKey(e,t){return 32*this.getColorFormatsId(e)+t}setForwardMaterialTargetFastCache(e,t,i){let r=this.forwardMaterialTargetFastCache.get(e);r||(r=new Map,this.forwardMaterialTargetFastCache.set(e,r)),r.set(t,i)}setForwardMaterialFrameCache(e,t,i){let r=this.forwardMaterialFrameCache.get(e);r||(r=[],this.forwardMaterialFrameCache.set(e,r)),r[t]={extractionVersion:this.extractionVersion,resource:i}}setDepthMaterialFastCache(e,t,i){let r=this.depthMaterialFastCache.get(e);r||(r=[],this.depthMaterialFastCache.set(e,r)),r[t]=i}getDrawInstanceAccessMode(e){return"instanced-direct"===e.residentInstanceBinding?.mode?"instanced-direct":"packed"}drawUsesBatching(e){return e.usesBatching}buildMaterialShaderCode(e,t,i,r,n=!1,a=!1){const s=this.pipelineCompilationDiagnostics,o=s?performance.now():0,l=Sa(`${t}\n${i}`,this.createMaterialPreprocessorDefines(e,r,n,a),{sourceName:r}),c=r.includes("vertex")?function(e){let t=0,i=0,r=null;for(;;){const n=e.indexOf("@builtin",t);if(n<0)break;t=n+8;let a=t;for(;ja(e.charCodeAt(a));)a++;if("("!==e[a++])continue;for(;ja(e.charCodeAt(a));)a++;if(!e.startsWith("position",a))continue;for(a+=8;ja(e.charCodeAt(a));)a++;if(")"!==e[a++])continue;Ea.lastIndex=a;const s=Ea.exec(e);s&&(r??=[],r.push(e.slice(i,n),"@builtin(position) @invariant "),i=a+s[0].length,t=i)}return null===r?e:(r.push(e.slice(i)),r.join(""))}(l):l;return s&&(s.cpuTotalsMs.shaderPreprocess=(s.cpuTotalsMs.shaderPreprocess??0)+performance.now()-o),c}createMaterialPreprocessorDefines(e,t,i=!1,r=!1){const n={HIGH_PRECISION:!0,WEBGPU_RENDERER:!0,WGSL_SHADER_MATERIAL:!0,USE_BATCHING:r,USE_COLOR:!0,USE_COLOR_ALPHA:!0,NUM_DIR_LIGHTS:4,NUM_POINT_LIGHTS:y,NUM_SPOT_LIGHTS:S,NUM_DIR_LIGHT_SHADOWS:4,NUM_POINT_LIGHT_SHADOWS:y,NUM_SPOT_LIGHT_SHADOWS:S,NUM_CLIPPING_PLANES:0,UNION_CLIPPING_PLANES:0,USE_SKINNING:i,RENDERER_MOTION_VECTORS:!t.includes("shared-depth"),...this.createTexturePreprocessorDefines(e)};return e.side===aa?n.DOUBLE_SIDED=!0:e.side===ta&&(n.FLIP_SIDED=!0),!t.includes("receiveShadow=1")&&t.includes("receiveShadow=0")||(n.USE_SHADOWMAP=!0,n.SHADOWMAP_TYPE_PCF=!0),{...n,...e.defines,USE_BATCHING:r}}createTexturePreprocessorDefines(e){const t={},i={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[r,n]of Object.entries(i))e.textures[r]&&(t[n]=!0);return t}shouldInvalidateDrawMaterialResource(e,t,i,r,n){return!!e.materialResource&&(e.material!==t||e.receiveShadow!==i||e.usesBatching!==r||e.skinning!==n)}cachedDrawMaterialResourceMatches(e,t,i,r=this.sampleCount){const n=this.getDrawInstanceAccessMode(e),a=null!==e.skinning,s=this.drawUsesBatching(e),o=this.getColorFormatsId(i);return t.instanceAccessMode===n&&t.receiveShadow===e.receiveShadow&&t.useBatching===s&&t.frontFaceCW===Zr(e)&&t.usesSkinning===a&&t.rendererSampleCount===r&&t.colorTargetFormatsId===o&&(this.drawMaterialResourceFrameValidation.get(t)===this.extractionVersion||(t.materialVersion===e.material.version&&t.textureVersionHash===e.material.getTextureVersionHash()||this.materialResourceMatches(t,e.material,t.key,r)))}getMaterialResourceForDraw(e,t=tl,i=this.sampleCount){const r=e.materialResource;if(r&&this.cachedDrawMaterialResourceMatches(e,r,t,i))return this.drawMaterialResourceFrameValidation.get(r)!==this.extractionVersion&&(this.updateMaterialUniformBuffer(e.material,r),this.drawMaterialResourceFrameValidation.set(r,this.extractionVersion)),r;const n=this.getDrawInstanceAccessMode(e),a=null!==e.skinning,s=this.drawUsesBatching(e),o=this.getMaterialResource(e.material,n,e.receiveShadow,t,a,s,i,Zr(e));return e.materialResource=o,this.drawMaterialResourceFrameValidation.set(o,this.extractionVersion),o}getMaterialResourceAsyncForDraw(e){return this.getMaterialResourceAsync(e.material,this.getDrawInstanceAccessMode(e),e.receiveShadow,void 0,null!==e.skinning,this.drawUsesBatching(e),this.sampleCount,Zr(e))}resolveForwardMaterialResources(e){for(let t=0;t<e.length;t+=1){const i=e[t];i.materialResource=this.getMaterialResource(i.material,this.getDrawInstanceAccessMode(i),i.receiveShadow,void 0,null!==i.skinning,this.drawUsesBatching(i),this.sampleCount,Zr(i))}}getDepthPassMaterialResourceForDraw(e,t,i,r){return this.getDepthPassMaterialResource(e,t,r??this.getDrawInstanceAccessMode(i),null!==i.skinning,this.drawUsesBatching(i),Zr(i))}getDepthPassMaterialResourceAsyncForDraw(e,t,i){return this.getDepthPassMaterialResourceAsync(e,t,this.getDrawInstanceAccessMode(i),null!==i.skinning,this.drawUsesBatching(i),Zr(i))}getOrCreateSharedDepthPipeline(e,t,r,n,a,s,o,l){if(!(this.state.device&&this.state.shadowBindGroupLayout&&this.state.directShadowBindGroupLayout&&this.state.skinningBindGroupLayout))throw new Error("Renderer is not initialized.");const c=this.sharedDepthPipelineCache.get(e);if(c)return c;const u=`${t.uuid}-shared-depth-${r}-${n}`;i(this.state.device,u+"-pipeline",{key:String(t.userData.pipelineOrigin?.assetId??t.userData.assetId??t.userData.pipelineOrigin?.sourceUuid??t.uuid)+":depth:"+r,material:{name:t.name,uuid:t.uuid,version:t.version,assetId:t.userData.assetId,assetName:t.userData.assetName,...t.userData.pipelineOrigin},variant:{instanceAccessMode:n,useSkinning:s,useBatching:o,passKind:r,frontFaceCW:l},defines:{...t.defines}});const d=this.state.device.createBindGroupLayout({label:`${u}-material-layout`,entries:a}),h="prepass"===r?"instanced-direct"===n?this.state.directSceneBindGroupLayout:"packed-visible"===n?this.state.visibleDepthSceneBindGroupLayout:this.state.sceneBindGroupLayout:"packed"!==n?this.state.directShadowBindGroupLayout:this.state.shadowBindGroupLayout,p=this.state.device.createPipelineLayout({label:`${u}-pipeline-layout`,bindGroupLayouts:[h,d,...s?[this.state.skinningBindGroupLayout]:[]]}),f=hs(t,"prepass"===r?"camera":"shadow",this.state.device,n,s),m=this.buildMaterialShaderCode(t,f,"pointShadow"===r?t.pointShadowVertexShader??t.vertexShader:t.depthVertexShader??t.vertexShader,`${u}-vertex`,s,o),g="pointShadow"===r?t.pointShadowFragmentShader:t.depthFragmentShader,v=g?this.buildMaterialShaderCode(t,f,g,`${u}-fragment`,s,o):null,x={bindGroupLayout:d,pipeline:this.state.device.createRenderPipeline({label:`${u}-pipeline`,layout:p,vertex:{module:this.state.device.createShaderModule({label:`${u}-vertex`,code:m}),entryPoint:"vsMain",buffers:this.createVertexBufferLayouts(this.getMaterialVertexAttributes(t,s))},...v?{fragment:{module:this.state.device.createShaderModule({label:`${u}-fragment`,code:v}),entryPoint:"fsMain",targets:"pointShadow"===r?[{format:"rgba16float"}]:[]}}:{},primitive:{topology:nl(t),cullMode:al(t,r,o),frontFace:l?"cw":"ccw"},depthStencil:{format:"depth32float",depthWriteEnabled:!0,depthCompare:"less",...ki(t,"directionalShadow"===r)}})};return this.sharedDepthPipelineCache.set(e,x),x}async getOrCreateSharedDepthPipelineAsync(e,t,r,n,a,s,o,l){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 c=this.sharedDepthPipelineCache.get(e);if(c)return c;const u=this.sharedDepthPipelinePromiseCache.get(e);if(u)return u;const d=`${t.uuid}-shared-depth-${r}-${n}`;i(this.state.device,d+"-pipeline",{key:String(t.userData.pipelineOrigin?.assetId??t.userData.assetId??t.userData.pipelineOrigin?.sourceUuid??t.uuid)+":depth:"+r,material:{name:t.name,uuid:t.uuid,version:t.version,assetId:t.userData.assetId,assetName:t.userData.assetName,...t.userData.pipelineOrigin},variant:{instanceAccessMode:n,useSkinning:s,useBatching:o,passKind:r,frontFaceCW:l},defines:{...t.defines}});const h=(async()=>{const i=this.state.device.createBindGroupLayout({label:`${d}-material-layout`,entries:a}),c="prepass"===r?"instanced-direct"===n?this.state.directSceneBindGroupLayout:"packed-visible"===n?this.state.visibleDepthSceneBindGroupLayout:this.state.sceneBindGroupLayout:"packed"!==n?this.state.directShadowBindGroupLayout:this.state.shadowBindGroupLayout,u=this.state.device.createPipelineLayout({label:`${d}-pipeline-layout`,bindGroupLayouts:[c,i,...s?[this.state.skinningBindGroupLayout]:[]]}),h=hs(t,"prepass"===r?"camera":"shadow",this.state.device,n,s),p=this.buildMaterialShaderCode(t,h,"pointShadow"===r?t.pointShadowVertexShader??t.vertexShader:t.depthVertexShader??t.vertexShader,`${d}-vertex`,s,o),f="pointShadow"===r?t.pointShadowFragmentShader:t.depthFragmentShader,m=f?this.buildMaterialShaderCode(t,h,f,`${d}-fragment`,s,o):null,g={bindGroupLayout:i,pipeline:await dl(this.state.device,{label:`${d}-pipeline`,layout:u,vertex:{module:this.state.device.createShaderModule({label:`${d}-vertex`,code:p}),entryPoint:"vsMain",buffers:this.createVertexBufferLayouts(this.getMaterialVertexAttributes(t,s))},...m?{fragment:{module:this.state.device.createShaderModule({label:`${d}-fragment`,code:m}),entryPoint:"fsMain",targets:"pointShadow"===r?[{format:"rgba16float"}]:[]}}:{},primitive:{topology:nl(t),cullMode:al(t,r,o),frontFace:l?"cw":"ccw"},depthStencil:{format:"depth32float",depthWriteEnabled:!0,depthCompare:"less",...ki(t,"directionalShadow"===r)}},this.pipelineCompilationDiagnostics,"depth",`${t.name||"unnamed"} [${t.uuid}] (${r}, ${n})`,p.length,m?.length??0)};return this.sharedDepthPipelineCache.set(e,g),this.sharedDepthPipelinePromiseCache.delete(e),g})();return this.sharedDepthPipelinePromiseCache.set(e,h),h}getOrCreateSharedForwardPipeline(e,t,r,n,a,s,o,l,c,u=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 d=this.sharedForwardPipelineCache.get(e);if(d)return d;const h=`${t.uuid}-shared-forward-${r}-${u}-receiveShadow=${a?1:0}`;i(this.state.device,h+"-pipeline",{key:String(t.userData.pipelineOrigin?.assetId??t.userData.assetId??t.userData.pipelineOrigin?.sourceUuid??t.uuid)+":forward",material:{name:t.name,uuid:t.uuid,version:t.version,assetId:t.userData.assetId,assetName:t.userData.assetName,...t.userData.pipelineOrigin},variant:{instanceAccessMode:r,useSkinning:o,useBatching:l,receiveShadow:a,sampleCount:u,colorTargetFormats:s},defines:{...t.defines}});const p=this.state.device.createBindGroupLayout({label:`${h}-material-layout`,entries:n}),f=this.createGraphTextureBindGroupLayout(t),m=this.state.device.createPipelineLayout({label:`${h}-pipeline-layout`,bindGroupLayouts:["instanced-direct"===r?this.state.directSceneBindGroupLayout:"packed-visible"===r?this.state.visibleSceneBindGroupLayout:this.state.sceneBindGroupLayout,p,o?this.state.skinningBindGroupLayout:this.state.emptyBindGroupLayout,f]}),g=us(t,this.state.device,r,a,o),v=this.buildMaterialShaderCode(t,g,t.vertexShader,`${h}-vertex`,o,l),x=this.buildMaterialShaderCode(t,g,t.fragmentShader,`${h}-fragment`,o,l),w={bindGroupLayout:p,graphTextureBindGroupLayout:f,pipeline:this.state.device.createRenderPipeline({label:`${h}-pipeline`,layout:m,vertex:{module:this.state.device.createShaderModule({label:`${h}-vertex`,code:v}),entryPoint:"vsMain",buffers:this.createVertexBufferLayouts(this.getMaterialVertexAttributes(t,o))},fragment:{module:this.state.device.createShaderModule({label:`${h}-fragment`,code:x}),entryPoint:"fsMain",targets:Yo(x,s,qo(t))},primitive:{topology:nl(t),cullMode:nl(t).startsWith("triangle")&&t.side!==aa?t.side===ta?"front":"back":"none",frontFace:c?"cw":"ccw"},multisample:{count:u},depthStencil:{format:"depth32float",depthWriteEnabled:t.depthWrite,depthCompare:t.depthTest?"less-equal":"always",...ki(t)}})};return this.sharedForwardPipelineCache.set(e,w),w}async getOrCreateSharedForwardPipelineAsync(e,t,r,n,a,s,o,l,c,u=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 d=this.sharedForwardPipelineCache.get(e);if(d)return d;const h=this.sharedForwardPipelinePromiseCache.get(e);if(h)return h;const p=`${t.uuid}-shared-forward-${r}-${u}-receiveShadow=${a?1:0}`;i(this.state.device,p+"-pipeline",{key:String(t.userData.pipelineOrigin?.assetId??t.userData.assetId??t.userData.pipelineOrigin?.sourceUuid??t.uuid)+":forward",material:{name:t.name,uuid:t.uuid,version:t.version,assetId:t.userData.assetId,assetName:t.userData.assetName,...t.userData.pipelineOrigin},variant:{instanceAccessMode:r,useSkinning:o,useBatching:l,receiveShadow:a,sampleCount:u,colorTargetFormats:s},defines:{...t.defines}});const f=(async()=>{const i=this.state.device.createBindGroupLayout({label:`${p}-material-layout`,entries:n}),d=this.createGraphTextureBindGroupLayout(t),h=this.state.device.createPipelineLayout({label:`${p}-pipeline-layout`,bindGroupLayouts:["instanced-direct"===r?this.state.directSceneBindGroupLayout:"packed-visible"===r?this.state.visibleSceneBindGroupLayout:this.state.sceneBindGroupLayout,i,o?this.state.skinningBindGroupLayout:this.state.emptyBindGroupLayout,d]}),f=us(t,this.state.device,r,a,o),m=this.buildMaterialShaderCode(t,f,t.vertexShader,`${p}-vertex`,o,l),g=this.buildMaterialShaderCode(t,f,t.fragmentShader,`${p}-fragment`,o,l),v={bindGroupLayout:i,graphTextureBindGroupLayout:d,pipeline:await dl(this.state.device,{label:`${p}-pipeline`,layout:h,vertex:{module:this.state.device.createShaderModule({label:`${p}-vertex`,code:m}),entryPoint:"vsMain",buffers:this.createVertexBufferLayouts(this.getMaterialVertexAttributes(t,o))},fragment:{module:this.state.device.createShaderModule({label:`${p}-fragment`,code:g}),entryPoint:"fsMain",targets:Yo(g,s,qo(t))},primitive:{topology:nl(t),cullMode:nl(t).startsWith("triangle")&&t.side!==aa?t.side===ta?"front":"back":"none",frontFace:c?"cw":"ccw"},multisample:{count:u},depthStencil:{format:"depth32float",depthWriteEnabled:t.depthWrite,depthCompare:t.depthTest?"less-equal":"always",...ki(t)}},this.pipelineCompilationDiagnostics,"forward",`${t.name||"unnamed"} [${t.uuid}] (${r}, ${u}x)`,m.length,g.length)};return this.sharedForwardPipelineCache.set(e,v),this.sharedForwardPipelinePromiseCache.delete(e),v})();return this.sharedForwardPipelinePromiseCache.set(e,f),f}getDepthPassMaterialResource(e,t,i,r,n,a=!1){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||"pointShadow"===t&&(null===e.pointShadowVertexShader||null===e.pointShadowFragmentShader))return null;const s=this.getDepthMaterialFastCacheIndex(t,i,r,n,a),o=this.depthMaterialFrameCache.get(e)?.[s];if(o?.extractionVersion===this.extractionVersion)return o.resource;const l=this.depthMaterialFastCache.get(e)?.[s];if(l&&this.fastMaterialResourceMatches(l,e))return this.updateMaterialUniformBuffer(e,l),this.setDepthMaterialFrameCache(e,s,l),l;const c="prepass"===t?this.depthPrepassMaterialCache:r?this.skinnedDirectionalShadowMaterialCache:"instanced-direct"===i?this.directionalShadowMaterialCacheDirect:this.directionalShadowMaterialCache,u=this.getDepthPassMaterialKey(e,t,i,r,n,a),d=c.get(e),h=d?.get(u);if(h&&this.materialResourceMatches(h,e,u))return this.setDepthMaterialFastCache(e,s,h),this.updateMaterialUniformBuffer(e,h),this.setDepthMaterialFrameCache(e,s,h),h;this.destroyMaterialResource(h),d&&d.delete(u);const{bindGroupLayoutEntries:p,bindGroupEntries:f,uniformBuffer:m,textures:g,textureVersions:v,storageBuffers:x}=this.createMaterialBindGroupData(e,`${e.uuid}-${t}-${i}-material`,GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT),w=this.getOrCreateSharedDepthPipeline(u,e,t,i,p,r,n,a),b=this.state.device.createBindGroup({label:`${e.uuid}-${t}-${i}-material-bind-group`,layout:w.bindGroupLayout,entries:f}),y={key:u,materialVersion:e.version,textureVersionHash:e.getTextureVersionHash(),rendererSampleCount:this.sampleCount,instanceAccessMode:i,receiveShadow:!0,useBatching:n,frontFaceCW:a,colorTargetFormatsId:0,pipeline:w.pipeline,graphTextureBindGroupLayout:w.graphTextureBindGroupLayout,bindGroup:b,uniformBuffer:m,uniformBufferSize:m?.size??0,uniformValueHash:e.uniformValuesAutoUpdate?e.getUniformValueHash():0,uniformValuesAutoVersion:e.uniformValuesAutoVersion,textures:g,textureVersions:v,storageBuffers:x,vertexAttributes:this.getMaterialVertexAttributes(e,r),usesSkinning:r};let S=c.get(e);return S||(S=new Map,c.set(e,S)),S.set(u,y),this.setDepthMaterialFastCache(e,s,y),this.setDepthMaterialFrameCache(e,s,y),y}setDepthMaterialFrameCache(e,t,i){let r=this.depthMaterialFrameCache.get(e);r||(r=[],this.depthMaterialFrameCache.set(e,r)),r[t]={extractionVersion:this.extractionVersion,resource:i}}async getDepthPassMaterialResourceAsync(e,t,i,r,n,a=!1){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||"pointShadow"===t&&(null===e.pointShadowVertexShader||null===e.pointShadowFragmentShader))return null;const s=this.getDepthMaterialFastCacheIndex(t,i,r,n,a),o=this.depthMaterialFastCache.get(e)?.[s];if(o&&this.fastMaterialResourceMatches(o,e))return this.updateMaterialUniformBuffer(e,o),o;const l="prepass"===t?this.depthPrepassMaterialCache:r?this.skinnedDirectionalShadowMaterialCache:"instanced-direct"===i?this.directionalShadowMaterialCacheDirect:this.directionalShadowMaterialCache,c=this.getDepthPassMaterialKey(e,t,i,r,n,a),u=l.get(e),d=u?.get(c);if(d&&this.materialResourceMatches(d,e,c))return this.setDepthMaterialFastCache(e,s,d),this.updateMaterialUniformBuffer(e,d),d;this.destroyMaterialResource(d),u&&u.delete(c);const{bindGroupLayoutEntries:h,bindGroupEntries:p,uniformBuffer:f,textures:m,textureVersions:g,storageBuffers:v}=this.createMaterialBindGroupData(e,`${e.uuid}-${t}-${i}-material`,GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT),x=await this.getOrCreateSharedDepthPipelineAsync(c,e,t,i,h,r,n,a),w=this.state.device.createBindGroup({label:`${e.uuid}-${t}-${i}-material-bind-group`,layout:x.bindGroupLayout,entries:p}),b={key:c,materialVersion:e.version,textureVersionHash:e.getTextureVersionHash(),rendererSampleCount:this.sampleCount,instanceAccessMode:i,receiveShadow:!0,useBatching:n,frontFaceCW:a,colorTargetFormatsId:0,pipeline:x.pipeline,graphTextureBindGroupLayout:x.graphTextureBindGroupLayout,bindGroup:w,uniformBuffer:f,uniformBufferSize:f?.size??0,uniformValueHash:e.uniformValuesAutoUpdate?e.getUniformValueHash():0,uniformValuesAutoVersion:e.uniformValuesAutoVersion,textures:m,textureVersions:g,storageBuffers:v,vertexAttributes:this.getMaterialVertexAttributes(e,r),usesSkinning:r};let y=l.get(e);return y||(y=new Map,l.set(e,y)),y.set(c,b),this.setDepthMaterialFastCache(e,s,b),b}getMaterialResource(e,t,i=!0,r,n=!1,a=!1,s=this.sampleCount,o=!1){if(!(this.state.device&&this.state.format&&this.state.sceneBindGroupLayout&&this.state.visibleSceneBindGroupLayout&&this.state.directSceneBindGroupLayout))throw new Error("Renderer is not initialized.");const l=n?i?this.skinnedMaterialCache:this.skinnedMaterialNoReceiveShadowCache:i?"instanced-direct"===t?this.materialCacheDirect:"packed-visible"===t?this.materialCacheVisible:this.materialCache:"instanced-direct"===t?this.materialNoReceiveShadowCacheDirect:"packed-visible"===t?this.materialNoReceiveShadowCacheVisible:this.materialNoReceiveShadowCache,c=r??tl,u=void 0===r||1===r.length&&r[0]===D,d=this.getForwardMaterialFastCacheIndex(t,i,n,a,o),h=u?null:this.getForwardMaterialTargetFastCacheKey(c,d);if(u){const t=this.forwardMaterialFrameCache.get(e)?.[d];if(t?.extractionVersion===this.extractionVersion&&t.resource.rendererSampleCount===s)return t.resource;const i=this.forwardMaterialFastCache.get(e)?.[d];if(i&&this.fastMaterialResourceMatches(i,e,s))return this.updateMaterialUniformBuffer(e,i),this.setForwardMaterialFrameCache(e,d,i),i}else{const t=this.forwardMaterialTargetFastCache.get(e)?.get(h);if(t&&this.fastMaterialResourceMatches(t,e,s))return this.updateMaterialUniformBuffer(e,t),t}const p=this.getForwardMaterialKey(e,t,i,c,n,a,o,s),f=l.get(e),m=f?.get(p);if(m&&this.materialResourceMatches(m,e,p,s))return u?(this.setForwardMaterialFastCache(e,d,m),this.setForwardMaterialFrameCache(e,d,m)):this.setForwardMaterialTargetFastCache(e,h,m),this.updateMaterialUniformBuffer(e,m),m;this.destroyMaterialResource(m),f&&f.delete(p);const{bindGroupLayoutEntries:g,bindGroupEntries:v,uniformBuffer:x,textures:w,textureVersions:b,storageBuffers:y}=this.createMaterialBindGroupData(e,`${e.uuid}-${t}-material`,GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT),S=this.getOrCreateSharedForwardPipeline(p,e,t,g,i,c,n,a,o,s),C=this.state.device.createBindGroup({label:`${e.uuid}-${t}-material-bind-group`,layout:S.bindGroupLayout,entries:v}),M={key:p,materialVersion:e.version,textureVersionHash:e.getTextureVersionHash(),rendererSampleCount:s,instanceAccessMode:t,receiveShadow:i,useBatching:a,frontFaceCW:o,colorTargetFormatsId:this.getColorFormatsId(c),pipeline:S.pipeline,graphTextureBindGroupLayout:S.graphTextureBindGroupLayout,bindGroup:C,uniformBuffer:x,uniformBufferSize:x?.size??0,uniformValueHash:e.uniformValuesAutoUpdate?e.getUniformValueHash():0,uniformValuesAutoVersion:e.uniformValuesAutoVersion,textures:w,textureVersions:b,storageBuffers:y,vertexAttributes:this.getMaterialVertexAttributes(e,n),usesSkinning:n};let P=l.get(e);return P||(P=new Map,l.set(e,P)),P.set(p,M),u?(this.setForwardMaterialFastCache(e,d,M),this.setForwardMaterialFrameCache(e,d,M)):this.setForwardMaterialTargetFastCache(e,h,M),M}async getMaterialResourceAsync(e,t,i=!0,r,n=!1,a=!1,s=this.sampleCount,o=!1){if(!(this.state.device&&this.state.format&&this.state.sceneBindGroupLayout&&this.state.visibleSceneBindGroupLayout&&this.state.directSceneBindGroupLayout))throw new Error("Renderer is not initialized.");const l=n?i?this.skinnedMaterialCache:this.skinnedMaterialNoReceiveShadowCache:i?"instanced-direct"===t?this.materialCacheDirect:"packed-visible"===t?this.materialCacheVisible:this.materialCache:"instanced-direct"===t?this.materialNoReceiveShadowCacheDirect:"packed-visible"===t?this.materialNoReceiveShadowCacheVisible:this.materialNoReceiveShadowCache,c=r??tl,u=void 0===r||1===r.length&&r[0]===D,d=this.getForwardMaterialFastCacheIndex(t,i,n,a,o);if(u){const t=this.forwardMaterialFrameCache.get(e)?.[d];if(t?.extractionVersion===this.extractionVersion&&t.resource.rendererSampleCount===s)return t.resource;const i=this.forwardMaterialFastCache.get(e)?.[d];if(i&&this.fastMaterialResourceMatches(i,e,s))return this.updateMaterialUniformBuffer(e,i),this.setForwardMaterialFrameCache(e,d,i),i}const h=this.getForwardMaterialKey(e,t,i,c,n,a,o,s),p=l.get(e),f=p?.get(h);if(f&&this.materialResourceMatches(f,e,h,s))return u&&(this.setForwardMaterialFastCache(e,d,f),this.setForwardMaterialFrameCache(e,d,f)),this.updateMaterialUniformBuffer(e,f),f;this.destroyMaterialResource(f),p&&p.delete(h);const{bindGroupLayoutEntries:m,bindGroupEntries:g,uniformBuffer:v,textures:x,textureVersions:w,storageBuffers:b}=this.createMaterialBindGroupData(e,`${e.uuid}-${t}-material`,GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT),y=await this.getOrCreateSharedForwardPipelineAsync(h,e,t,m,i,c,n,a,o,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:i,useBatching:a,frontFaceCW:o,colorTargetFormatsId:this.getColorFormatsId(c),pipeline:y.pipeline,graphTextureBindGroupLayout:y.graphTextureBindGroupLayout,bindGroup:S,uniformBuffer:v,uniformBufferSize:v?.size??0,uniformValueHash:e.uniformValuesAutoUpdate?e.getUniformValueHash():0,uniformValuesAutoVersion:e.uniformValuesAutoVersion,textures:x,textureVersions:w,storageBuffers:b,vertexAttributes:this.getMaterialVertexAttributes(e,n),usesSkinning:n};let M=l.get(e);return M||(M=new Map,l.set(e,M)),M.set(h,C),u&&(this.setForwardMaterialFastCache(e,d,C),this.setForwardMaterialFrameCache(e,d,C)),C}ensureTiledLightingSize(){this.tiledPointLights?.resize(this.state.width,this.state.height)&&(this.state.sharedSceneBindGroup=null,this.state.residentSceneBindGroupVersion+=1,this.clearIndirectBundleCache(),this.clearStaticDrawSetBundleCaches())}updateCameraUniforms(e,t,i){if(!this.state.device||!this.state.cameraBuffer)return;const r=this.cameraProjectionScratch.copy(e.projectionMatrix);i||0===this.projectionJitterPixels.x&&0===this.projectionJitterPixels.y||(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(T).multiply(r).multiply(e.matrixWorldInverse);this.cameraDetailProjectionScratch.update(n),e.getWorldPosition(F);const a=this.cameraUniformScratch;a.set(n.elements,0),a[16]=F.x,a[17]=F.y,a[18]=F.z,a[19]=1,a[20]=i?.width??this.state.width,a[21]=i?.height??this.state.height,a[22]=i?1:this.state.pixelRatio,a[23]=this.state.frameTimeSeconds,a.set(e.matrixWorldInverse.elements,24),a.set(A.multiplyMatrices(T,r).elements,40),a[56]=e.near,a[57]=e.far,a[58]=1/Math.max(e.far-e.near,1e-4),a[59]=!i&&this.tiledLightingEnabled?1:0;const s=i?null:t.fog;null!=s?(a[60]=s.color.r,a[61]=s.color.g,a[62]=s.color.b,a[63]=1,"density"in s?(a[64]=0,a[65]=0,a[66]=s.density,a[67]=1):(a[64]=s.near,a[65]=s.far,a[66]=0,a[67]=0)):(a.fill(0,60,68),a[67]=-1);const o=!i&&this.motionVectorProjectionPending?this.motionVectorProjection:e.projectionMatrix,l=(i?U:this.motionVectorCurrentViewProj).copy(T).multiply(o).multiply(e.matrixWorldInverse);a.set(l.elements,68),a.set((!i&&this.motionVectorHistoryValid?this.motionVectorPreviousViewProj:l).elements,84),a[100]=!i&&this.motionVectorHistoryValid?1:0,a[101]=i?.width??this.state.width,a[102]=i?.height??this.state.height,a[103]=0,i||(this.motionVectorProjectionPending=!1),this.state.device.queue.writeBuffer(this.state.cameraBuffer,0,a,0,104)}updateTemporalVisibilityUniforms(e){if(!this.state.device||!this.state.temporalVisibilityBuffer)return;const t=tn(e,this.temporalVisibilityCurrentViewProj);e.getWorldPosition(this.temporalVisibilityCurrentCameraPosition);const i=this.temporalVisibilityUniformScratch;i.set(t.elements,0),i.set((this.state.temporalHiZHistoryValid?this.temporalVisibilityPreviousViewProj:t).elements,16),i[32]=this.temporalVisibilityCurrentCameraPosition.x,i[33]=this.temporalVisibilityCurrentCameraPosition.y,i[34]=this.temporalVisibilityCurrentCameraPosition.z,i[35]=1;const r=this.state.temporalHiZHistoryValid?this.temporalVisibilityPreviousCameraPosition:this.temporalVisibilityCurrentCameraPosition;i[36]=r.x,i[37]=r.y,i[38]=r.z,i[39]=1,i[40]=this.state.width,i[41]=this.state.height,i[42]=this.state.pixelRatio,i[43]=this.state.frameTimeSeconds,this.state.device.queue.writeBuffer(this.state.temporalVisibilityBuffer,0,i,0,44)}commitTemporalHiZHistory(){this.temporalVisibilityPreviousViewProj.copy(this.temporalVisibilityCurrentViewProj),this.temporalVisibilityPreviousCameraPosition.copy(this.temporalVisibilityCurrentCameraPosition),this.state.temporalHiZHistoryValid=!0,this.motionVectorPreviousViewProj.copy(this.motionVectorCurrentViewProj),this.motionVectorHistoryValid=!0}updateLightUniforms(e){if(!this.state.device||!this.state.lightBuffer)return;const t=this.lightUniformScratch;null===this.sceneCaptureOptions&&this.updateSpotLightMapAtlas(e.lights.spots),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 i=this.csmCascadeRanges[e],r=3976+4*e;t[r+0]=i.x,t[r+1]=i.y}const i=e.lights.hemisphere;null!=i&&(t[3992]=i.skyColor.x,t[3993]=i.skyColor.y,t[3994]=i.skyColor.z,t[3995]=i.intensity,t[3996]=i.groundColor.x,t[3997]=i.groundColor.y,t[3998]=i.groundColor.z,t[3999]=i.intensity,t[4e3]=i.direction.x,t[4001]=i.direction.y,t[4002]=i.direction.z,t[4003]=1);for(let i=0;i<e.lights.directionals.length;i+=1){const r=e.lights.directionals[i],n=this.directionalShadowCameras[i],a=8+4*i;t[a+0]=r.direction.x,t[a+1]=r.direction.y,t[a+2]=r.direction.z,t[a+3]=1;const s=24+4*i;t[s+0]=r.color.x,t[s+1]=r.color.y,t[s+2]=r.color.z,t[s+3]=r.intensity;const o=40+4*i;t[o+0]=r.shadowBias,t[o+1]=r.castShadow?1:0,t[o+2]=this.state.directionalShadowTextureSize,t[o+3]=r.shadowNormalBias;const l=56+4*i;t[l+0]=r.shadowRadius,t[l+1]=r.shadowIntensity;const c=r.shadowViewProjection??=new ua;t.set(tn(n,c).elements,72+16*i)}for(let i=0;i<e.lights.points.length;i+=1){const r=e.lights.points[i],n=136+4*i;t[n+0]=r.position.x,t[n+1]=r.position.y,t[n+2]=r.position.z,t[n+3]=r.range;const a=392+4*i;t[a+0]=r.color.x,t[a+1]=r.color.y,t[a+2]=r.color.z,t[a+3]=r.intensity;const s=648+4*i;t[s+0]=r.distance,t[s+1]=r.decay;const o=904+4*i;t[o+0]=r.shadowBias,t[o+1]=r.castShadow?1:0,t[o+2]=this.state.pointShadowTextureSize,t[o+3]=r.shadowNormalBias;const l=1160+4*i;t[l+0]=r.shadowRadius,t[l+1]=r.shadowIntensity,t[l+2]=r.shadowCameraNear,t[l+3]=r.shadowCameraFar}for(let i=0;i<e.lights.spots.length;i+=1){const r=e.lights.spots[i],n=1416+4*i;t[n+0]=r.position.x,t[n+1]=r.position.y,t[n+2]=r.position.z,t[n+3]=r.range;const a=1672+4*i;t[a+0]=r.direction.x,t[a+1]=r.direction.y,t[a+2]=r.direction.z,t[a+3]=Math.cos(r.angle);const s=1928+4*i;t[s+0]=r.color.x,t[s+1]=r.color.y,t[s+2]=r.color.z,t[s+3]=r.intensity;const o=2184+4*i;t[o+0]=r.shadowBias,t[o+1]=r.castShadow?1:0,t[o+2]=this.state.spotShadowTextureSize,t[o+3]=r.shadowNormalBias;const l=2440+4*i;t[l+0]=r.shadowRadius,t[l+1]=r.shadowIntensity;const c=2696+4*i;if(t[c+0]=r.range,t[c+1]=Math.cos(r.angle*(1-r.penumbra)),t[c+2]=r.decay,t[c+3]=null!=r.map?1:0,r.castShadow||null!=r.map){const e=this.spotShadowCameras[i];e.near=r.shadowCameraNear,e.far=r.shadowCameraFar,e.fov=r.shadowCameraFov,e.aspect=1,e.position.copy(r.position),O.copy(r.position).add(r.direction),e.lookAt(O),e.updateMatrixWorld(!0),e.updateProjectionMatrix(),t.set(tn(e,this.shadowViewProjScratch).elements,2952+16*i)}}this.state.device.queue.writeBuffer(this.state.lightBuffer,0,t,0,G)}updateSpotLightMapAtlas(e){const t=this.state.device;if(null==t)return;const i=e.some(e=>null!=e.map),r=i?2048:1,n=i?r/8:1,a=i?e.map(e=>null==e.map?"-":`${e.map.uuid}:${e.map.version}`).join("|"):"fallback";if(null!=this.state.spotLightMapTexture&&r===this.spotLightMapAtlasSize&&a===this.spotLightMapAtlasSignature)return;if(null==this.state.spotLightMapTexture||r!==this.spotLightMapAtlasSize){const e=this.state.spotLightMapTexture,n=t.createTexture({label:i?"spot-light-map-atlas":"spot-light-map-fallback",size:{width:r,height:r},format:"rgba8unorm",usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_DST});this.state.spotLightMapTexture=n,this.state.spotLightMapView=n.createView(),this.spotLightMapAtlasSize=r,e?.destroy(),this.state.sharedSceneBindGroup=null,this.state.residentSceneBindGroupVersion+=1,this.clearIndirectBundleCache(),this.clearStaticDrawSetBundleCaches()}if(!i)return t.queue.writeTexture({texture:this.state.spotLightMapTexture},new Uint8Array([255,255,255,255]),{},{width:1,height:1}),void(this.spotLightMapAtlasSignature=a);if(null==this.spotLightMapAtlasLayout||null==this.spotLightMapAtlasPipeline){this.spotLightMapAtlasLayout=t.createBindGroupLayout({label:"spot-light-map-atlas-layout",entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}},{binding:1,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float"}}]});const e=t.createShaderModule({label:"spot-light-map-atlas-shader",code:"\n struct VertexOutput { @builtin(position) position: vec4<f32>, @location(0) uv: vec2<f32> };\n @vertex fn vertexMain(@builtin(vertex_index) index: u32) -> VertexOutput {\n let positions = array<vec2<f32>, 3>(vec2(-1.0, -1.0), vec2(3.0, -1.0), vec2(-1.0, 3.0));\n var output: VertexOutput;\n output.position = vec4(positions[index], 0.0, 1.0);\n output.uv = positions[index] * vec2(0.5, -0.5) + vec2(0.5);\n return output;\n }\n @group(0) @binding(0) var mapSampler: sampler;\n @group(0) @binding(1) var mapTexture: texture_2d<f32>;\n @fragment fn fragmentMain(input: VertexOutput) -> @location(0) vec4<f32> {\n return textureSample(mapTexture, mapSampler, input.uv);\n }\n "});this.spotLightMapAtlasPipeline=t.createRenderPipeline({label:"spot-light-map-atlas-pipeline",layout:t.createPipelineLayout({bindGroupLayouts:[this.spotLightMapAtlasLayout]}),vertex:{module:e,entryPoint:"vertexMain"},fragment:{module:e,entryPoint:"fragmentMain",targets:[{format:"rgba8unorm"}]}})}const s=t.createCommandEncoder({label:"spot-light-map-atlas-upload"}),o=s.beginRenderPass({colorAttachments:[{view:this.state.spotLightMapView,clearValue:{r:1,g:1,b:1,a:1},loadOp:"clear",storeOp:"store"}]});o.setPipeline(this.spotLightMapAtlasPipeline);for(let i=0;i<e.length;i+=1){const r=e[i].map;if(null==r)continue;const a=this.getTextureResource(r),s=i%8*n,l=Math.floor(i/8)*n;o.setViewport(s,l,n,n,0,1),o.setScissorRect(s,l,n,n),o.setBindGroup(0,t.createBindGroup({layout:this.spotLightMapAtlasLayout,entries:[{binding:0,resource:this.state.linearClampSampler},{binding:1,resource:a.view}]})),o.draw(3)}o.end(),t.queue.submit([s.finish()]),this.spotLightMapAtlasSignature=a}writeShadowCameraBuffer(e,t,i,r,n,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]=i,o[18]=r,o[19]=n,o[60]=this.state.frameTimeSeconds,o[61]=this.state.width,o[62]=this.state.height,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)}};var ll=[0,0],cl=[0,0,1],ul=[1,1,1,1];async function dl(e,t,i,r,n,a=0,s=0){if(null==e)throw new Error("WebGPU device is not initialized");const o=performance.now();try{return await W(e,t)}finally{i&&r&&n&&i.pipelines.push({kind:r,material:n,durationMs:performance.now()-o,vertexCodeLength:a,fragmentCodeLength:s})}}import{DataTexture as hl,Matrix4 as pl,RepeatWrapping as fl}from"three";var ml={off:{enabled:!1,temporal:{}},low:{enabled:!0,resolutionScale:.35,directions:2,steps:3,temporal:{historyWeight:.92,depthRejection:.1},denoise:{samples:4,radius:4}},medium:{enabled:!0,resolutionScale:.5,directions:2,steps:4,temporal:{historyWeight:.9,depthRejection:.08},denoise:{samples:8,radius:6}},high:{enabled:!0,resolutionScale:.5,directions:3,steps:5,temporal:{historyWeight:.88,depthRejection:.06},denoise:{samples:12,radius:8}}},gl=class{options;noiseTexture=function(){const e=new Array(25).fill(0);let t=Math.floor(2.5),i=4;for(let r=1;r<=25;){-1===t&&5===i?(t=0,i=3):(5===i&&(i=0),t<0&&(t=4));const n=5*t+i;0===e[n]?(e[n]=r++,t-=1,i+=1):(t+=1,i-=2)}const r=new Uint8Array(100);for(let t=0;t<e.length;t+=1){const i=2*Math.PI*e[t]/e.length;r[4*t]=Math.round(255*(.5*Math.cos(i)+.5)),r[4*t+1]=Math.round(255*(.5*Math.sin(i)+.5)),r[4*t+2]=127,r[4*t+3]=255}const n=new hl(r,5,5);return n.wrapS=fl,n.wrapT=fl,n.needsUpdate=!0,n}();gtaoPasses=new Map;temporalPasses=new Map;denoisePasses=new Map;compositePasses=new Map;writeIndex=0;frameIndex=0;historyValid=!1;constructor(e={}){this.options=Cl(e)}get enabled(){return this.options.enabled}get temporalEnabled(){return!1!==this.options.temporal}setOptions(e){Object.assign(this.options,Cl({...this.options,...e,denoise:e.denoise??this.options.denoise,temporal:e.temporal??this.options.temporal,targetPrefix:this.options.targetPrefix})),this.gtaoPasses.clear(),this.temporalPasses.clear(),this.denoisePasses.clear(),this.compositePasses.clear(),this.reset()}applyPreset(e){this.setOptions(ml[e])}reset(){this.writeIndex=0,this.frameIndex=0,this.historyValid=!1}addPasses(e,t){const i=e.createColorTarget(`${this.options.targetPrefix}Raw`,{format:"r16float",scale:this.options.resolutionScale}),r=`${t.depth}:${t.normal}:${i}`;let n=this.gtaoPasses.get(r);n||(n=new vl(t.depth,t.normal,i,this.noiseTexture,this.options),this.gtaoPasses.set(r,n));const a=!1!==this.options.temporal&&null!=t.velocity;n.frameIndex=a?this.frameIndex:0,e.addFullscreenPass(n);let s=i;if(a&&!1!==this.options.temporal&&null!=t.velocity){const r=e.createColorTarget(`${this.options.targetPrefix}TemporalA`,{format:"r16float",scale:this.options.resolutionScale}),n=e.createColorTarget(`${this.options.targetPrefix}TemporalB`,{format:"r16float",scale:this.options.resolutionScale}),a=e.createColorTarget(`${this.options.targetPrefix}TemporalDepthA`,{format:"r16float",scale:this.options.resolutionScale}),o=e.createColorTarget(`${this.options.targetPrefix}TemporalDepthB`,{format:"r16float",scale:this.options.resolutionScale}),l=0===this.writeIndex?n:r,c=0===this.writeIndex?r:n,u=0===this.writeIndex?o:a,d=0===this.writeIndex?a:o,h=`${i}:${t.depth}:${t.velocity}:${l}:${u}:${c}:${d}`;let p=this.temporalPasses.get(h);p||(p=new xl(i,t.depth,t.velocity,l,u,c,d,this.options.temporal,this),this.temporalPasses.set(h,p)),e.addFullscreenPass(p),s=c,this.writeIndex=1-this.writeIndex}if(a&&(this.frameIndex+=1),!1===this.options.denoise)return s;const o=e.createColorTarget(`${this.options.targetPrefix}Denoised`,{format:"r16float",scale:this.options.resolutionScale}),l=`${s}:${t.depth}:${t.normal}:${o}`;let c=this.denoisePasses.get(l);return c||(c=new wl(s,t.depth,t.normal,o,this.options.normalSpace,this.options.denoise),this.denoisePasses.set(l,c)),e.addFullscreenPass(c),o}addCompositePass(e,t,i,r={}){const n=r.output??e.createColorTarget(`${this.options.targetPrefix}Composite`,{format:"rgba16float"}),a=Math.max(0,r.intensity??this.options.intensity),s=Math.max(1e-4,r.power??this.options.power),o=`${t}:${i}:${n}:${a}:${s}`;let l=this.compositePasses.get(o);return l||(l=new bl(t,i,n,a,s),this.compositePasses.set(o,l)),e.addFullscreenPass(l),n}dispose(){this.noiseTexture.dispose(),this.gtaoPasses.clear(),this.temporalPasses.clear(),this.denoisePasses.clear(),this.compositePasses.clear()}consumeHistoryValid(){const e=this.historyValid;return this.historyValid=!0,e}},vl=class{constructor(e,t,i,r,n){this.options=n,this.inputs={sceneDepth:e,sceneNormal:t},this.outputs=i,this.textures={gtaoNoise:r},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 baseTangent = normalize(noiseTexel.xy * 2.0 - vec2<f32>(1.0));\n let temporalAngle = f32(i32(fullscreenUniforms[13].x) & 7) * 2.39996323;\n let temporalRotation = mat2x2<f32>(\n vec2<f32>(cos(temporalAngle), sin(temporalAngle)),\n vec2<f32>(-sin(temporalAngle), cos(temporalAngle))\n );\n let rotatedTangent = temporalRotation * baseTangent;\n let tangent = vec3<f32>(rotatedTangent, 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`}(n)}options;name="GTAOPass";sampler="nearest";uniformBufferSize=224;inputs;outputs;textures;fragmentShader;uniforms=new Float32Array(this.uniformBufferSize/4);webGpuProjection=new pl;webGpuProjectionInverse=new pl;frameIndex=0;updateUniforms=e=>(this.webGpuProjection.copy(yl).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.set([this.frameIndex,0,0,0],52),this.uniforms)},xl=class{constructor(e,t,i,r,n,a,s,o,l){this.options=o,this.state=l,this.inputs={currentAo:e,sceneDepth:t,velocity:i,historyAo:r,historyDepth:n},this.outputs=[a,s]}options;state;name="GTAOTemporalPass";sampler="linear";uniformBufferSize=80;inputs;outputs;fragmentShader=Sl;uniforms=new Float32Array(this.uniformBufferSize/4);inverseProjection=new pl;updateUniforms=e=>(this.inverseProjection.copy(yl).multiply(e.camera.projectionMatrix).invert(),this.uniforms.set(this.inverseProjection.elements,0),this.uniforms.set([this.options.historyWeight,this.options.depthRejection,this.options.neighborhoodClamp?1:0,this.state.consumeHistoryValid()?1:0],16),this.uniforms)},wl=class{constructor(e,t,i,r,n,a){this.options=a,this.inputs={aoInput:e,sceneDepth:t,sceneNormal:i},this.outputs=r,this.fragmentShader=function(e,t){const i="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 ${i};\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 < ${t}; i += 1) {\n let sampleIndex = (i * 16) / ${t};\n let sample = POISSON_DISK[sampleIndex];\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`}(n,a.samples)}options;name="GTAODenoisePass";sampler="nearest";uniformBufferSize=144;inputs;outputs;fragmentShader;uniforms=new Float32Array(this.uniformBufferSize/4);webGpuProjectionInverse=new pl;updateUniforms=e=>(this.webGpuProjectionInverse.copy(yl).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)},bl=class{name="GTAOCompositePass";sampler="nearest";uniformBufferSize=16;inputs;outputs;uniforms;constructor(e,t,i,r,n){this.inputs={sceneColor:e,ambientOcclusion:t},this.outputs=i,this.uniforms=new Float32Array([r,n,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 materialFlags = u32(round(color.a));\n let isAlphaTested = (materialFlags & 1u) != 0u;\n let visibility = select(mix(1.0, pow(clamp(ao, 0.0, 1.0), fullscreenUniforms[0].y), fullscreenUniforms[0].x), 1.0, isAlphaTested);\n return vec4<f32>(color.rgb * visibility, color.a);\n}\n"},yl=(new pl).set(1,0,0,0,0,1,0,0,0,0,.5,.5,0,0,0,1);var Sl="\nstruct GTAOTemporalOutput {\n @location(0) ao: vec4<f32>,\n @location(1) depth: vec4<f32>,\n};\n\nfn inverseProjectionMatrix() -> mat4x4<f32> {\n return mat4x4<f32>(\n fullscreenUniforms[0], fullscreenUniforms[1],\n fullscreenUniforms[2], fullscreenUniforms[3]\n );\n}\n\nfn loadSceneDepth(uv: vec2<f32>) -> f32 {\n let size = vec2<i32>(textureDimensions(sceneDepthTexture));\n let pixel = clamp(\n vec2<i32>(uv * vec2<f32>(size)),\n vec2<i32>(0),\n size - vec2<i32>(1)\n );\n return textureLoad(sceneDepthTexture, pixel, 0);\n}\n\nfn linearViewDepth(uv: vec2<f32>, depth: f32) -> f32 {\n let clip = vec4<f32>(\n uv.x * 2.0 - 1.0,\n 1.0 - uv.y * 2.0,\n depth,\n 1.0\n );\n let view = inverseProjectionMatrix() * clip;\n return abs(view.z / max(abs(view.w), 1e-6));\n}\n\nfn loadVelocity(uv: vec2<f32>) -> vec2<f32> {\n let size = vec2<i32>(textureDimensions(velocityTexture));\n let pixel = clamp(\n vec2<i32>(uv * vec2<f32>(size)),\n vec2<i32>(0),\n size - vec2<i32>(1)\n );\n return textureLoad(velocityTexture, pixel, 0).xy;\n}\n\nfn loadCurrentAo(pixel: vec2<i32>, size: vec2<i32>) -> f32 {\n return textureLoad(\n currentAoTexture,\n clamp(pixel, vec2<i32>(0), size - vec2<i32>(1)),\n 0\n ).r;\n}\n\n@fragment\nfn fsMain(input: FullscreenVertexOutput) -> GTAOTemporalOutput {\n let aoSize = vec2<i32>(textureDimensions(currentAoTexture));\n let pixel = clamp(\n vec2<i32>(input.position.xy),\n vec2<i32>(0),\n aoSize - vec2<i32>(1)\n );\n let currentAo = loadCurrentAo(pixel, aoSize);\n let currentDepthRaw = loadSceneDepth(input.uv);\n let currentDepth = linearViewDepth(input.uv, currentDepthRaw);\n let previousUv = input.uv - loadVelocity(input.uv);\n let inBounds =\n all(previousUv >= vec2<f32>(0.0)) &&\n all(previousUv <= vec2<f32>(1.0));\n let historySize = vec2<i32>(textureDimensions(historyDepthTexture));\n let historyPixel = clamp(\n vec2<i32>(previousUv * vec2<f32>(historySize)),\n vec2<i32>(0),\n historySize - vec2<i32>(1)\n );\n let previousDepth = textureLoad(historyDepthTexture, historyPixel, 0).r;\n let relativeDepthDifference =\n abs(previousDepth - currentDepth) / max(currentDepth, 1e-3);\n let historyAccepted =\n fullscreenUniforms[4].w > 0.5 &&\n inBounds &&\n currentDepthRaw < 1.0 &&\n relativeDepthDifference <= fullscreenUniforms[4].y;\n\n var historyAo = textureSampleLevel(\n historyAoTexture,\n fullscreenSampler,\n clamp(previousUv, vec2<f32>(0.0), vec2<f32>(1.0)),\n 0.0\n ).r;\n if (fullscreenUniforms[4].z > 0.5) {\n let left = loadCurrentAo(pixel + vec2<i32>(-1, 0), aoSize);\n let right = loadCurrentAo(pixel + vec2<i32>(1, 0), aoSize);\n let up = loadCurrentAo(pixel + vec2<i32>(0, -1), aoSize);\n let down = loadCurrentAo(pixel + vec2<i32>(0, 1), aoSize);\n let neighborhoodMin = min(currentAo, min(min(left, right), min(up, down)));\n let neighborhoodMax = max(currentAo, max(max(left, right), max(up, down)));\n historyAo = clamp(historyAo, neighborhoodMin, neighborhoodMax);\n }\n let historyWeight = select(\n 0.0,\n fullscreenUniforms[4].x,\n historyAccepted\n );\n let accumulated = mix(currentAo, historyAo, historyWeight);\n\n var output: GTAOTemporalOutput;\n output.ao = vec4<f32>(accumulated);\n output.depth = vec4<f32>(currentDepth);\n return output;\n}\n";function Cl(e){return{intensity:Math.max(0,e.intensity??.6),power:Math.max(1e-4,e.power??1),enabled:e.enabled??!0,radius:Math.max(.001,e.radius??.25),resolutionScale:Pl(e.resolutionScale??1,.25,1),thickness:Math.max(.001,e.thickness??1),distanceExponent:Math.max(.01,e.distanceExponent??1),distanceFalloff:Pl(e.distanceFalloff??1,0,1),directions:Bl(e.directions??3,1,8),steps:Bl(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),samples:Ml(e.denoise?.samples??16),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)},temporal:!1!==e.temporal&&{historyWeight:Pl(e.temporal?.historyWeight??.9,0,.98),depthRejection:Pl(e.temporal?.depthRejection??.08,.001,1),neighborhoodClamp:e.temporal?.neighborhoodClamp??!0}}}function Ml(e){return e<=4?4:e<=8?8:e<=12?12:16}function Pl(e,t,i){return Math.min(i,Math.max(t,e))}function Bl(e,t,i){return Math.floor(Pl(e,t,i))}import{Matrix4 as Dl}from"three";var Il=class{options;passes=new Map;constructor(e={}){this.options=Ul(e)}get enabled(){return this.options.enabled}get surfaceRaySteps(){return this.options.surfaceSteps}setOptions(e){const t=Ul({...this.options,...e});Object.keys(t).every(e=>t[e]===this.options[e])||(Object.assign(this.options,t),this.passes.clear())}addPasses(e,t){if(!this.enabled)return t.sceneColor;const i=e.createColorTarget(`${this.options.targetPrefix}Raw`,{format:"rgba16float",scale:this.options.resolutionScale}),r=`trace:${t.sceneColor}:${t.depth}:${t.normalRoughness}:${i}`;let n=this.passes.get(r);n||(n=new Tl(t,i,this.options),this.passes.set(r,n)),e.addFullscreenPass(n);let a=i;if(this.options.blur)for(let i=0;i<2;i++){const r=e.createColorTarget(`${this.options.targetPrefix}Blur${i}`,{format:"rgba16float",scale:this.options.resolutionScale}),n=`blur:${a}:${t.depth}:${t.normalRoughness}:${r}:${i}:${this.options.blurRadius}`;let s=this.passes.get(n);s||(s=new Rl(a,t.depth,t.normalRoughness,r,i,this.options.blurRadius),this.passes.set(n,s)),e.addFullscreenPass(s),a=r}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 Vl(t.sceneColor,a,s,this.options.intensity),this.passes.set(o,l)),e.addFullscreenPass(l),s}},Tl=class{constructor(e,t,i){this.options=i,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",i=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 = ${i};\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}`}(i)}options;name="SSRTracePass";sampler="linear";uniformBufferSize=224;inputs;outputs;fragmentShader;uniforms=new Float32Array(56);projection=new Dl;inverseProjection=new Dl;updateUniforms=e=>(this.projection.copy(Gl).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)},Rl=class{name;sampler="linear";uniformBufferSize=16;inputs;outputs;uniforms;constructor(e,t,i,r,n,a){this.name=0===n?"SSRBlurHorizontalPass":"SSRBlurVerticalPass",this.inputs={reflection:e,sceneDepth:t,normalRoughness:i},this.outputs=r,this.uniforms=new Float32Array([0===n?1:0,1===n?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}"},Vl=class{name="SSRCompositePass";sampler="linear";uniformBufferSize=16;inputs;outputs;uniforms;constructor(e,t,i,r){this.inputs={sceneColor:e,reflection:t},this.outputs=i,this.uniforms=new Float32Array([r,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 Gl=(new Dl).set(1,0,0,0,0,1,0,0,0,0,.5,.5,0,0,0,1);function zl(e,t,i){return Math.min(i,Math.max(t,e))}function Ll(e,t,i){return Math.round(zl(e,t,i))}function Ul(e){return{enabled:e.enabled??!0,surfaceSteps:Ll(e.surfaceSteps??0,0,32),resolutionScale:zl(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:zl(e.maxRoughness??.8,.01,1),steps:Ll(e.steps??2048,8,2048),pixelStride:zl(e.pixelStride??1,1,4),normalSpace:e.normalSpace??"world",blur:e.blur??!0,blurRadius:zl(e.blurRadius??6,1,12),targetPrefix:e.targetPrefix??"ssr"}}import{Matrix4 as Al,Vector2 as kl}from"three";var Fl=(new Al).set(1,0,0,0,0,1,0,0,0,0,.5,.5,0,0,0,1),Ol=class{renderScale;sampleCount;minCurrentWeight;motionWeightScale;depthThreshold;relativeDepthThreshold;targetPrefix;writeIndex=0;historyValid=!1;frameIndex=0;renderWidth=1;renderHeight=1;outputWidth=1;outputHeight=1;jitter=new kl;unjitteredProjection=new Al;previousJitterUv=new kl;currentJitterUv=new kl;previousViewProjection=new Al;resolvePasses=new Map;constructor(e={}){this.renderScale=$l(e.renderScale??1,.25,1),this.sampleCount=Math.max(1,Math.floor(e.sampleCount??32)),this.minCurrentWeight=$l(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,i){this.setSize(t,i),e.updateProjectionMatrix(),this.unjitteredProjection.copy(e.projectionMatrix),this.jitter.set(jl(this.frameIndex%this.sampleCount+1,2)-.5,jl(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,i=e.mainDepth,r){const n=e.createColorTarget(`${this.targetPrefix}HistoryColorA`,{format:"rgba16float",resolution:"presentation"}),a=e.createColorTarget(`${this.targetPrefix}HistoryColorB`,{format:"rgba16float",resolution:"presentation"}),s=e.createColorTarget(`${this.targetPrefix}HistoryDepthA`,{format:"r32float",resolution:"presentation"}),o=e.createColorTarget(`${this.targetPrefix}HistoryDepthB`,{format:"r32float",resolution:"presentation"}),l=0===this.writeIndex?a:n,c=0===this.writeIndex?n:a,u=0===this.writeIndex?o:s,d=0===this.writeIndex?s:o,h=`${t}:${i}:${r??"camera"}:${l}:${u}:${c}:${d}`;let p=this.resolvePasses.get(h);return p||(p=new El(t,i,r,l,u,c,d,this),this.resolvePasses.set(h,p)),e.addFullscreenPass(p),this.writeIndex=1-this.writeIndex,this.frameIndex+=1,c}reset(){this.frameIndex=0,this.writeIndex=0,this.historyValid=!1,this.previousViewProjection.identity(),this.currentJitterUv.set(0,0),this.previousJitterUv.set(0,0)}setRenderScale(e){const t=$l(e,.25,1);t!==this.renderScale&&(this.renderScale=t,this.renderWidth=Math.max(1,Math.floor(this.outputWidth*this.renderScale)),this.renderHeight=Math.max(1,Math.floor(this.outputHeight*this.renderScale)),this.reset())}setSize(e,t){const i=Math.max(1,Math.floor(e)),r=Math.max(1,Math.floor(t));i===this.outputWidth&&r===this.outputHeight||(this.outputWidth=i,this.outputHeight=r,this.renderWidth=Math.max(1,Math.floor(i*this.renderScale)),this.renderHeight=Math.max(1,Math.floor(r*this.renderScale)),this.reset())}updateResolveUniforms(e,t,i,r){t.copy(Fl).multiply(r.camera.projectionMatrix).multiply(r.camera.matrixWorldInverse),i.copy(t).invert(),e.set(i.elements,0),e.set((this.historyValid?this.previousViewProjection:t).elements,16),e.set([r.presentationWidth,r.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}},El=class{constructor(e,t,i,r,n,a,s,o){var l;this.state=o,this.inputs=null==i?{currentColor:e,currentDepth:t,historyColor:r,historyDepth:n}:{currentColor:e,currentDepth:t,historyColor:r,historyDepth:n,velocity:i},this.outputs=[a,s],this.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${(l=null!=i)?"\nfn loadPackedVelocity(pixel: vec2<i32>, renderSize: vec2<i32>) -> vec4<f32> {\n let velocitySize = vec2<i32>(textureDimensions(velocityTexture));\n let velocityPixel = clamp(\n vec2<i32>((vec2<f32>(pixel) + 0.5) * vec2<f32>(velocitySize) / vec2<f32>(renderSize)),\n vec2<i32>(0),\n velocitySize - vec2<i32>(1)\n );\n return textureLoad(velocityTexture, velocityPixel, 0);\n}\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 cameraHistoryUv = centerUv - (closestOutputUv - closestHistoryUv);\n${l?"\n // RG stores unjittered previous-to-current displacement in top-left-origin\n // UV units. History therefore lies opposite the velocity. Sampling at the\n // closest-depth pixel avoids borrowing background motion at silhouettes.\n let packedVelocity = loadPackedVelocity(closestPixel, renderSize);\n let rawVelocity = packedVelocity.xy;\n let finiteVelocity = all(rawVelocity == rawVelocity) && all(abs(rawVelocity) < vec2<f32>(2.0));\n // B=CameraOnly with exactly zero RG is the explicit fallback emitted by a\n // custom-position material that did not provide previous-frame deformation.\n let needsCameraFallback =\n abs(packedVelocity.z - 1.0) < 0.25 &&\n dot(rawVelocity, rawVelocity) < 1e-12;\n let historyUv = select(\n cameraHistoryUv,\n centerUv - rawVelocity,\n finiteVelocity && !needsCameraFallback\n );\n":"\n let historyUv = cameraHistoryUv;\n"}\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>(closestUv.x * 2.0 - 1.0, 1.0 - closestUv.y * 2.0, closestDepth, 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`}state;name="TemporalAAResolvePass";sampler="nearest";uniformBufferSize=176;inputs;outputs;fragmentShader;uniforms=new Float32Array(this.uniformBufferSize/4);currentViewProjection=new Al;currentViewProjectionInverse=new Al;updateUniforms=e=>(this.state.updateResolveUniforms(this.uniforms,this.currentViewProjection,this.currentViewProjectionInverse,e),this.uniforms)};function jl(e,t){let i=1,r=0;for(;e>0;)i/=t,r+=i*(e%t),e=Math.floor(e/t);return r}function $l(e,t,i){return Math.min(i,Math.max(t,e))}var Wl=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=_l(e.subpixelBlending??.75,0,1),this.targetPrefix=e.targetPrefix??"fxaa"}addPass(e,t,i={}){const r=i.output??e.createColorTarget(`${this.targetPrefix}Color`,{format:"rgba16float",resolution:"presentation"}),n=`${t}:${r}`;let a=this.passes.get(n);return a||(a=new Nl(t,r,this),this.passes.set(n,a)),e.addFullscreenPass(a),r}},Nl=class{constructor(e,t,i){this.state=i,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),_l(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 _l(e,t,i){return Math.min(i,Math.max(t,e))}import{ClampToEdgeWrapping as Hl,DataTexture as ql,LinearFilter as Kl,NoColorSpace as Yl,RGFormat as Zl,UnsignedByteType as Xl}from"three";var Jl={low:{searchSteps:4,diagonalSteps:0},medium:{searchSteps:8,diagonalSteps:0},high:{searchSteps:16,diagonalSteps:8},ultra:{searchSteps:32,diagonalSteps:16}},Ql=class{threshold;localContrastAdaptation;edgeDetection;cornerRounding;sharpness;quality;targetPrefix;areaTexture;edgePasses=new Map;weightPasses=new Map;blendPasses=new Map;constructor(e={}){this.threshold=Math.max(0,e.threshold??.08),this.localContrastAdaptation=Math.max(0,e.localContrastAdaptation??.5),this.edgeDetection=e.edgeDetection??"color",this.cornerRounding=dc(e.cornerRounding??.25,0,1),this.sharpness=dc(e.sharpness??0,0,1),this.quality=Jl[e.quality??"high"],this.targetPrefix=e.targetPrefix??"smaa",this.areaTexture=function(){const e=new ql(function(){if(rc)return rc;const e=new Uint8Array(25600),t=[[0,0],[3,0],[0,3],[3,3],[1,0],[4,0],[1,3],[4,3],[0,1],[3,1],[0,4],[3,4],[1,1],[4,1],[1,4],[4,4]],i=[[0,0],[1,0],[0,2],[1,2],[2,0],[3,0],[2,2],[3,2],[0,1],[1,1],[0,3],[1,3],[2,1],[3,1],[2,3],[3,3]];for(let r=0;r<16;r+=1){const[n,a]=t[r];for(let t=0;t<16;t+=1)for(let i=0;i<16;i+=1){nc(e,16*n+i,16*a+t,ac(r,i*i,t*t))}const[s,o]=i[r];for(let t=0;t<20;t+=1)for(let i=0;i<20;i+=1){nc(e,80+20*s+i,20*o+t,lc(r,i,t))}}return rc=e,e}(),160,80,Zl,Xl);return e.name="SMAA-Area-Lookup",e.colorSpace=Yl,e.minFilter=Kl,e.magFilter=Kl,e.wrapS=Hl,e.wrapT=Hl,e.generateMipmaps=!1,e.needsUpdate=!0,e}()}addPass(e,t,i={}){const r=e.createColorTarget(`${this.targetPrefix}Edges`,{format:"rg8unorm",resolution:"render"}),n=e.createColorTarget(`${this.targetPrefix}Weights`,{format:"rgba8unorm",resolution:"render"}),a=i.output??e.createColorTarget(`${this.targetPrefix}Color`,{format:"rgba16float",resolution:"render"}),s=`${t}:${r}`;let o=this.edgePasses.get(s);o||(o=new ec(t,r,this),this.edgePasses.set(s,o));const l=`${r}:${n}`;let c=this.weightPasses.get(l);c||(c=new tc(r,n,this.areaTexture,this),this.weightPasses.set(l,c));const u=`${t}:${n}:${a}`;let d=this.blendPasses.get(u);return d||(d=new ic(t,n,a,this),this.blendPasses.set(u,d)),e.addFullscreenPass(o),e.addFullscreenPass(c),e.addFullscreenPass(d),a}dispose(){this.areaTexture.dispose()}get searchSteps(){return this.quality.searchSteps}get diagonalSteps(){return this.quality.diagonalSteps}},ec=class{constructor(e,t,i){this.state=i,this.inputs={source:e},this.outputs=t}state;name="SMAAEdgeDetectionPass";sampler="nearest";uniformBufferSize=16;inputs;outputs;uniforms=new Float32Array(4);updateUniforms=()=>(this.uniforms.set([Math.max(0,this.state.threshold),Math.max(0,this.state.localContrastAdaptation),"color"===this.state.edgeDetection?1:0,0]),this.uniforms);fragmentShader="\nfn loadColor(pixel: vec2<i32>, size: vec2<i32>) -> vec3<f32> {\n let color = textureLoad(sourceTexture, clamp(pixel, vec2<i32>(0), size - vec2<i32>(1)), 0).rgb;\n // Intermediate buffers are linear. This inexpensive transfer makes the\n // threshold perceptual and keeps black toon strokes from being missed.\n return sqrt(max(color, vec3<f32>(0.0)));\n}\n\nfn colorDelta(a: vec3<f32>, b: vec3<f32>) -> f32 {\n let difference = abs(a - b);\n let colorDelta = max(difference.r, max(difference.g, difference.b));\n let lumaDelta = abs(dot(a - b, vec3<f32>(0.299, 0.587, 0.114)));\n return select(lumaDelta, colorDelta, fullscreenUniforms[0].z > 0.5);\n}\n\n@fragment\nfn fsMain(input: FullscreenVertexOutput) -> @location(0) vec4<f32> {\n let size = vec2<i32>(textureDimensions(sourceTexture));\n let pixel = clamp(vec2<i32>(input.position.xy), vec2<i32>(0), size - vec2<i32>(1));\n let center = loadColor(pixel, size);\n let leftColor = loadColor(pixel + vec2<i32>(-1, 0), size);\n let topColor = loadColor(pixel + vec2<i32>(0, -1), size);\n let left = colorDelta(center, leftColor);\n let top = colorDelta(center, topColor);\n let right = colorDelta(center, loadColor(pixel + vec2<i32>(1, 0), size));\n let bottom = colorDelta(center, loadColor(pixel + vec2<i32>(0, 1), size));\n let left2 = colorDelta(leftColor, loadColor(pixel + vec2<i32>(-2, 0), size));\n let top2 = colorDelta(topColor, loadColor(pixel + vec2<i32>(0, -2), size));\n let maximum = max(max(max(left, top), max(right, bottom)), max(left2, top2));\n let threshold = fullscreenUniforms[0].x;\n let adaptation = fullscreenUniforms[0].y * maximum;\n let westEdge = left >= threshold && left >= adaptation;\n let northEdge = top >= threshold && top >= adaptation;\n return vec4<f32>(\n select(0.0, 1.0, westEdge),\n select(0.0, 1.0, northEdge),\n 0.0,\n 0.0\n );\n}\n"},tc=class{constructor(e,t,i,r){this.state=r,this.inputs={edges:e},this.outputs=t,this.textures={area:i}}state;name="SMAABlendingWeightPass";sampler="nearest";uniformBufferSize=16;inputs;outputs;textures;uniforms=new Float32Array(4);updateUniforms=()=>(this.uniforms.set([this.state.searchSteps,this.state.diagonalSteps,dc(this.state.cornerRounding,0,1),0]),this.uniforms);fragmentShader="\nconst MAX_SEARCH_STEPS: i32 = 32;\nconst MAX_DIAGONAL_STEPS: i32 = 16;\n\nfn edgeAt(pixel: vec2<i32>, size: vec2<i32>) -> vec2<f32> {\n if (any(pixel < vec2<i32>(0)) || any(pixel >= size)) {\n return vec2<f32>(0.0);\n }\n return textureLoad(edgesTexture, pixel, 0).rg;\n}\n\nfn areaOrthogonal(distance: vec2<f32>, e1: f32, e2: f32) -> vec2<f32> {\n let pattern = vec2<f32>(round(4.0 * vec2<f32>(e1, e2)));\n let texel = vec2<f32>(16.0) * pattern + sqrt(max(distance, vec2<f32>(0.0)));\n let uv = (texel + vec2<f32>(0.5)) / vec2<f32>(160.0, 80.0);\n return textureSampleLevel(areaTexture, areaSampler, uv, 0.0).rg;\n}\n\nfn areaDiagonal(distance: vec2<f32>, e: vec2<f32>) -> vec2<f32> {\n let pattern = round(e);\n let texel = vec2<f32>(80.0, 0.0) + vec2<f32>(20.0) * pattern + distance;\n let uv = (texel + vec2<f32>(0.5)) / vec2<f32>(160.0, 80.0);\n return textureSampleLevel(areaTexture, areaSampler, uv, 0.0).rg;\n}\n\nfn searchHorizontal(pixel: vec2<i32>, direction: i32, size: vec2<i32>) -> i32 {\n var distance = 0;\n let limit = i32(fullscreenUniforms[0].x);\n for (var step = 1; step <= MAX_SEARCH_STEPS; step += 1) {\n if (step > limit) { break; }\n let candidate = pixel + vec2<i32>(direction * step, 0);\n let edge = edgeAt(candidate, size);\n if (edge.g < 0.5 || (step > 1 && edge.r > 0.5)) { break; }\n distance = step;\n }\n return distance;\n}\n\nfn searchVertical(pixel: vec2<i32>, direction: i32, size: vec2<i32>) -> i32 {\n var distance = 0;\n let limit = i32(fullscreenUniforms[0].x);\n for (var step = 1; step <= MAX_SEARCH_STEPS; step += 1) {\n if (step > limit) { break; }\n let candidate = pixel + vec2<i32>(0, direction * step);\n let edge = edgeAt(candidate, size);\n if (edge.r < 0.5 || (step > 1 && edge.g > 0.5)) { break; }\n distance = step;\n }\n return distance;\n}\n\nfn horizontalCrossing(pixel: vec2<i32>, size: vec2<i32>) -> f32 {\n let near = edgeAt(pixel, size).r;\n let far = edgeAt(pixel + vec2<i32>(0, -1), size).r;\n return (3.0 * near + far) * 0.25;\n}\n\nfn verticalCrossing(pixel: vec2<i32>, size: vec2<i32>) -> f32 {\n let near = edgeAt(pixel, size).g;\n let far = edgeAt(pixel + vec2<i32>(-1, 0), size).g;\n return (3.0 * near + far) * 0.25;\n}\n\nfn attenuateHorizontalCorners(\n weights: vec2<f32>,\n leftPixel: vec2<i32>,\n rightPixel: vec2<i32>,\n leftDistance: i32,\n rightDistance: i32,\n size: vec2<i32>\n) -> vec2<f32> {\n let rounding = fullscreenUniforms[0].z;\n var result = weights;\n if (leftDistance <= rightDistance) {\n let extended = max(edgeAt(leftPixel + vec2<i32>(0, 1), size).r, edgeAt(leftPixel + vec2<i32>(0, -2), size).r);\n result *= clamp(vec2<f32>(rounding + 1.0 - extended), vec2<f32>(0.0), vec2<f32>(1.0));\n } else {\n let extended = max(edgeAt(rightPixel + vec2<i32>(1, 1), size).r, edgeAt(rightPixel + vec2<i32>(1, -2), size).r);\n result *= clamp(vec2<f32>(rounding + 1.0 - extended), vec2<f32>(0.0), vec2<f32>(1.0));\n }\n return result;\n}\n\nfn attenuateVerticalCorners(\n weights: vec2<f32>,\n topPixel: vec2<i32>,\n bottomPixel: vec2<i32>,\n topDistance: i32,\n bottomDistance: i32,\n size: vec2<i32>\n) -> vec2<f32> {\n let rounding = fullscreenUniforms[0].z;\n var result = weights;\n if (topDistance <= bottomDistance) {\n let extended = max(edgeAt(topPixel + vec2<i32>(1, 0), size).g, edgeAt(topPixel + vec2<i32>(-2, 0), size).g);\n result *= clamp(vec2<f32>(rounding + 1.0 - extended), vec2<f32>(0.0), vec2<f32>(1.0));\n } else {\n let extended = max(edgeAt(bottomPixel + vec2<i32>(1, 1), size).g, edgeAt(bottomPixel + vec2<i32>(-2, 1), size).g);\n result *= clamp(vec2<f32>(rounding + 1.0 - extended), vec2<f32>(0.0), vec2<f32>(1.0));\n }\n return result;\n}\n\nfn searchDiagonal(\n pixel: vec2<i32>,\n direction: vec2<i32>,\n size: vec2<i32>\n) -> vec2<f32> {\n var distance = 0;\n var lastEdge = vec2<f32>(0.0);\n let limit = i32(fullscreenUniforms[0].y);\n for (var step = 1; step <= MAX_DIAGONAL_STEPS; step += 1) {\n if (step > limit) { break; }\n let candidate = pixel + direction * step;\n let edge = edgeAt(candidate, size);\n let adjacent = edgeAt(candidate + vec2<i32>(1, 0), size).r;\n lastEdge = vec2<f32>(edge.g, adjacent);\n if (edge.g + adjacent < 1.5) { break; }\n distance = step;\n }\n return vec2<f32>(f32(distance), lastEdge.g);\n}\n\nfn diagonalWeights(pixel: vec2<i32>, edges: vec2<f32>, size: vec2<i32>) -> vec2<f32> {\n if (fullscreenUniforms[0].y < 1.0 || edges.g < 0.5) {\n return vec2<f32>(0.0);\n }\n var result = vec2<f32>(0.0);\n var negative = vec2<f32>(0.0);\n if (edges.r > 0.5) {\n negative = searchDiagonal(pixel, vec2<i32>(-1, 1), size);\n }\n let positive = searchDiagonal(pixel, vec2<i32>(1, -1), size);\n if (negative.x + positive.x >= 2.0) {\n let leftPixel = pixel + vec2<i32>(-i32(negative.x), i32(negative.x));\n let rightPixel = pixel + vec2<i32>(i32(positive.x), -i32(positive.x));\n let c1 = edgeAt(leftPixel + vec2<i32>(-1, 0), size).g;\n let c2 = edgeAt(leftPixel, size).r;\n let c3 = edgeAt(rightPixel + vec2<i32>(1, 0), size).g;\n let c4 = edgeAt(rightPixel + vec2<i32>(1, -1), size).r;\n result += areaDiagonal(vec2<f32>(negative.x, positive.x), vec2<f32>(2.0 * c1 + c2, 2.0 * c3 + c4));\n }\n\n let negativeOpposite = searchDiagonal(pixel, vec2<i32>(-1, -1), size);\n var positiveOpposite = vec2<f32>(0.0);\n if (edgeAt(pixel + vec2<i32>(1, 0), size).r > 0.5) {\n positiveOpposite = searchDiagonal(pixel, vec2<i32>(1, 1), size);\n }\n if (negativeOpposite.x + positiveOpposite.x >= 2.0) {\n let leftPixel = pixel + vec2<i32>(-i32(negativeOpposite.x), -i32(negativeOpposite.x));\n let rightPixel = pixel + vec2<i32>(i32(positiveOpposite.x), i32(positiveOpposite.x));\n let c1 = edgeAt(leftPixel + vec2<i32>(-1, 0), size).g;\n let c2 = edgeAt(leftPixel + vec2<i32>(0, -1), size).r;\n let rightEdges = edgeAt(rightPixel + vec2<i32>(1, 0), size);\n result += areaDiagonal(\n vec2<f32>(negativeOpposite.x, positiveOpposite.x),\n vec2<f32>(2.0 * c1 + c2, 2.0 * rightEdges.g + rightEdges.r)\n ).gr;\n }\n return result;\n}\n\n@fragment\nfn fsMain(input: FullscreenVertexOutput) -> @location(0) vec4<f32> {\n let size = vec2<i32>(textureDimensions(edgesTexture));\n let pixel = clamp(vec2<i32>(input.position.xy), vec2<i32>(0), size - vec2<i32>(1));\n let edges = edgeAt(pixel, size);\n var weights = vec4<f32>(0.0);\n\n if (edges.g > 0.5) {\n let diagonal = diagonalWeights(pixel, edges, size);\n if (dot(diagonal, vec2<f32>(1.0)) > 1e-5) {\n weights.r = diagonal.x;\n weights.g = diagonal.y;\n } else {\n let leftDistance = searchHorizontal(pixel, -1, size);\n let rightDistance = searchHorizontal(pixel, 1, size);\n let leftPixel = pixel + vec2<i32>(-leftDistance, 0);\n let rightPixel = pixel + vec2<i32>(rightDistance, 0);\n let e1 = horizontalCrossing(leftPixel, size);\n let e2 = horizontalCrossing(rightPixel + vec2<i32>(1, 0), size);\n let area = areaOrthogonal(vec2<f32>(f32(leftDistance), f32(rightDistance)), e1, e2);\n let a = attenuateHorizontalCorners(area, leftPixel, rightPixel, leftDistance, rightDistance, size);\n weights.r = a.x;\n weights.g = a.y;\n }\n }\n\n if (edges.r > 0.5) {\n let topDistance = searchVertical(pixel, -1, size);\n let bottomDistance = searchVertical(pixel, 1, size);\n let topPixel = pixel + vec2<i32>(0, -topDistance);\n let bottomPixel = pixel + vec2<i32>(0, bottomDistance);\n let e1 = verticalCrossing(topPixel, size);\n let e2 = verticalCrossing(bottomPixel + vec2<i32>(0, 1), size);\n let area = areaOrthogonal(vec2<f32>(f32(topDistance), f32(bottomDistance)), e1, e2);\n let a = attenuateVerticalCorners(area, topPixel, bottomPixel, topDistance, bottomDistance, size);\n weights.b = a.x;\n weights.a = a.y;\n }\n\n return weights;\n}\n"},ic=class{constructor(e,t,i,r){this.state=r,this.inputs={source:e,weights:t},this.outputs=i}state;name="SMAANeighborhoodBlendPass";sampler="linear";uniformBufferSize=16;inputs;outputs;uniforms=new Float32Array(4);updateUniforms=()=>(this.uniforms.set([dc(this.state.sharpness,0,1),0,0,0]),this.uniforms);fragmentShader="\nfn loadSource(pixel: vec2<i32>, size: vec2<i32>) -> vec4<f32> {\n return textureLoad(sourceTexture, clamp(pixel, vec2<i32>(0), size - vec2<i32>(1)), 0);\n}\n\nfn loadWeights(pixel: vec2<i32>, size: vec2<i32>) -> vec4<f32> {\n return textureLoad(weightsTexture, clamp(pixel, vec2<i32>(0), size - vec2<i32>(1)), 0);\n}\n\nfn sharpen(center: vec3<f32>, pixel: vec2<i32>, size: vec2<i32>, edgeAmount: f32) -> vec3<f32> {\n let strength = fullscreenUniforms[0].x * (1.0 - clamp(edgeAmount * 2.0, 0.0, 1.0));\n if (strength <= 1e-5) { return center; }\n let left = loadSource(pixel + vec2<i32>(-1, 0), size).rgb;\n let right = loadSource(pixel + vec2<i32>(1, 0), size).rgb;\n let top = loadSource(pixel + vec2<i32>(0, -1), size).rgb;\n let bottom = loadSource(pixel + vec2<i32>(0, 1), size).rgb;\n let minimum = min(center, min(min(left, right), min(top, bottom)));\n let maximum = max(center, max(max(left, right), max(top, bottom)));\n let average = (left + right + top + bottom) * 0.25;\n let contrast = max(maximum.r - minimum.r, max(maximum.g - minimum.g, maximum.b - minimum.b));\n let adaptive = strength * (1.0 - clamp(contrast, 0.0, 1.0)) * 0.5;\n return clamp(center + (center - average) * adaptive, minimum, maximum);\n}\n\n@fragment\nfn fsMain(input: FullscreenVertexOutput) -> @location(0) vec4<f32> {\n let size = vec2<i32>(textureDimensions(sourceTexture));\n let pixel = clamp(vec2<i32>(input.position.xy), vec2<i32>(0), size - vec2<i32>(1));\n let center = loadSource(pixel, size);\n let current = loadWeights(pixel, size);\n\n // SMAA stores right/bottom weights in adjacent texels and left/top weights\n // in the current texel. Preserve that exact channel convention.\n let right = loadWeights(pixel + vec2<i32>(1, 0), size).a;\n let bottom = loadWeights(pixel + vec2<i32>(0, 1), size).g;\n let left = current.b;\n let top = current.r;\n let edgeAmount = max(max(right, bottom), max(left, top));\n\n var color = center;\n if (edgeAmount > 1e-5) {\n let texel = 1.0 / vec2<f32>(size);\n if (max(right, left) > max(bottom, top)) {\n let total = max(right + left, 1e-5);\n let rightColor = textureSampleLevel(\n sourceTexture,\n fullscreenSampler,\n input.uv + vec2<f32>(right * texel.x, 0.0),\n 0.0\n );\n let leftColor = textureSampleLevel(\n sourceTexture,\n fullscreenSampler,\n input.uv - vec2<f32>(left * texel.x, 0.0),\n 0.0\n );\n color = (rightColor * right + leftColor * left) / total;\n } else {\n let total = max(bottom + top, 1e-5);\n let bottomColor = textureSampleLevel(\n sourceTexture,\n fullscreenSampler,\n input.uv + vec2<f32>(0.0, bottom * texel.y),\n 0.0\n );\n let topColor = textureSampleLevel(\n sourceTexture,\n fullscreenSampler,\n input.uv - vec2<f32>(0.0, top * texel.y),\n 0.0\n );\n color = (bottomColor * bottom + topColor * top) / total;\n }\n }\n\n color = vec4<f32>(sharpen(color.rgb, pixel, size, edgeAmount), color.a);\n return color;\n}\n"};var rc=null;function nc(e,t,i,r){const n=2*(160*i+t);e[n]=Math.floor(255*dc(r[0],0,1)),e[n+1]=Math.floor(255*dc(r[1],0,1))}function ac(e,t,i){const r=t+i+1,n=.5,a=-.5,s=()=>sc([0,a],[r/2,0],t),o=()=>sc([r/2,0],[r,a],t);switch(e){case 0:case 5:case 10:case 15:default:return[0,0];case 1:return t<=i?s():[0,0];case 2:return t>=i?o():[0,0];case 3:return oc(r,s(),o());case 4:return t<=i?sc([0,n],[r/2,0],t):[0,0];case 6:case 14:case 7:return sc([0,n],[r,a],t);case 8:return t>=i?sc([r/2,0],[r,n],t):[0,0];case 9:case 11:case 13:return sc([0,a],[r,n],t);case 12:return oc(r,sc([0,n],[r/2,0],t),sc([r/2,0],[r,n],t))}}function sc(e,t,i){const r=t[0]-e[0],n=t[1]-e[1];if(Math.abs(r)<1e-6)return[0,0];const a=i,s=i+1,o=e[1]+n*(a-e[0])/r,l=e[1]+n*(s-e[0])/r;if(!(a>=e[0]&&a<t[0]||s>e[0]&&s<=t[0]))return[0,0];if(Math.sign(o)===Math.sign(l)||Math.abs(o)<1e-4||Math.abs(l)<1e-4){const e=.5*(o+l);return e<0?[-e,0]:[0,e]}const c=-e[1]*r/n+e[0],u=c-Math.floor(c),d=c>e[0]?o*u*.5:0,h=c<t[0]?l*(1-u)*.5:0;return(Math.abs(d)>Math.abs(h)?d:-h)<0?[Math.abs(d),Math.abs(h)]:[Math.abs(h),Math.abs(d)]}function oc(e,t,i){const r=e=>[.5*Math.sqrt(2*e[0]),.5*Math.sqrt(2*e[1])],n=dc(e/32,0,1),a=r(t),s=r(i);return[uc(a[0],t[0],n)+uc(s[0],i[0],n),uc(a[1],t[1],n)+uc(s[1],i[1],n)]}function lc(e,t,i){const r=t+i+1,[n,a]=[[0,0],[1,0],[0,2],[1,2],[2,0],[3,0],[2,2],[3,2],[0,1],[1,1],[0,3],[1,3],[2,1],[3,1],[2,3],[3,3]][e],s=(e,i)=>function(e,t,i){const r=30;let n=0,a=0;if(e[0]===t[0]&&e[1]===t[1])return[0,1];const s=.5*(e[0]+t[0]),o=.5*(e[1]+t[1]),l=t[1]-e[1],c=e[0]-t[0],u=(e,t)=>l*(e-s)+c*(t-o)>0;for(let e=0;e<r;e+=1)for(let t=0;t<r;t+=1){const s=t/(r-1),o=e/(r-1);u(1+i+s,i+o)&&(n+=1),u(1+i+s,1+i+o)&&(a+=1)}const d=r*r;return[1-n/d,a/d]}(n>0?[e[0],e[1]]:e,a>0?[i[0],i[1]]:i,t),o=(e,t)=>s([1,e],[1+r,t+r]);switch(e){case 0:return cc(o(1,1),o(0,0));case 1:return cc(s([1,0],[r,r]),o(0,0));case 2:return cc(s([0,0],[1+r,r]),o(0,0));case 3:return o(0,0);case 4:return cc(s([1,1],[r,r]),s([1,1],[1+r,r]));case 5:return cc(s([1,1],[r,r]),o(0,0));case 6:return s([1,1],[1+r,r]);case 7:return cc(s([1,1],[1+r,r]),o(0,0));case 8:return cc(s([0,0],[1+r,1+r]),s([1,0],[1+r,1+r]));case 9:return s([1,0],[1+r,1+r]);case 10:return cc(s([0,0],[1+r,1+r]),o(0,0));case 11:return cc(s([1,0],[1+r,1+r]),o(0,0));case 12:return s([1,1],[1+r,1+r]);case 13:return cc(s([1,1],[1+r,1+r]),s([1,0],[1+r,1+r]));case 14:return cc(s([1,1],[1+r,1+r]),s([1,1],[1+r,r]));case 15:return cc(s([1,1],[1+r,1+r]),o(0,0));default:return[0,0]}}function cc(e,t){return[.5*(e[0]+t[0]),.5*(e[1]+t[1])]}function uc(e,t,i){return e+(t-e)*i}function dc(e,t,i){return Math.min(i,Math.max(t,e))}var hc=class{strength;threshold;knee;radius;levels;targetPrefix;passes=new Map;constructor(e={}){var t,i,r;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=gc(e.radius??.2,0,1),this.levels=(t=e.levels??5,i=1,r=5,Math.floor(gc(t,i,r))),this.targetPrefix=e.targetPrefix??"bloom"}addPass(e,t,i={}){const r=[];let n=t;for(let t=0;t<this.levels;t+=1){const i=1/2**(t+1),a=e.createColorTarget(`${this.targetPrefix}Horizontal${t}`,{format:"rgba16float",scale:i}),s=e.createColorTarget(`${this.targetPrefix}Vertical${t}`,{format:"rgba16float",scale:i}),o=n,l=`h:${t}:${o}:${a}`;let c=this.passes.get(l);c||(c=0===t?new pc(o,a,this):new fc(`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 fc(`BloomVertical${t}`,a,s,!1,t),this.passes.set(u,d)),e.addFullscreenPass(d),r.push(s),n=s}const a=i.output??e.createColorTarget(`${this.targetPrefix}Color`,{format:"rgba16float"}),s=Object.fromEntries(r.map((e,t)=>[`blur${t}`,e])),o=`composite:${t}:${r.join(":")}:${a}`;let l=this.passes.get(o);return l||(l=new mc(t,s,a,this,this.levels),this.passes.set(o,l)),e.addFullscreenPass(l),a}},pc=class{constructor(e,t,i){this.state=i,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}"},fc=class{constructor(e,t,i,r,n){this.name=e,this.inputs={source:t},this.outputs=i;const a=r?"vec2<f32>(texel.x, 0.0)":"vec2<f32>(0.0, texel.y)",s=(1+.35*n).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},mc=class{constructor(e,t,i,r,n){this.state=r,this.inputs={source:e,...t},this.outputs=i;const a=[1,.8,.6,.4,.2],s=Array.from({length:n},(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,gc(this.state.radius,0,1),0,0]),this.uniforms);fragmentShader};function gc(e,t,i){return Math.min(i,Math.max(t,e))}var vc=[1,1,1],xc=[0,0,0],wc=class{options;passes=new Map;targetPrefix;constructor(e={}){this.options=e,this.targetPrefix=e.targetPrefix??"colorGrading"}addPass(e,t){if(!1===this.options.enabled)return t;const i=e.createColorTarget(`${this.targetPrefix}Color`,{format:"rgba16float"}),r=`${t}:${i}`;let n=this.passes.get(r);return n||(n=new bc(t,i,this.options),this.passes.set(r,n)),e.addFullscreenPass(n),i}},bc=class{constructor(e,t,i){this.state=i,this.inputs={source:e},this.outputs=t}state;name="ColorGrading";sampler="linear";uniformBufferSize=384;inputs;outputs;uniforms=new Float32Array(this.uniformBufferSize/4);writeVector(e,t){this.uniforms[e]=t[0],this.uniforms[e+1]=t[1],this.uniforms[e+2]=t[2],this.uniforms[e+3]=0}writeRange(e,t){this.writeVector(e,t?.saturation??vc),this.writeVector(e+4,t?.contrast??vc),this.writeVector(e+8,t?.gamma??vc),this.writeVector(e+12,t?.gain??vc),this.writeVector(e+16,t?.offset??xc)}updateUniforms=()=>(this.writeVector(0,this.state.whiteBalance??vc),this.writeVector(4,this.state.tint??vc),this.writeRange(8,this.state),this.writeRange(28,this.state.shadows),this.writeRange(48,this.state.midtones),this.writeRange(68,this.state.highlights),this.uniforms[88]=this.state.exposure??1,this.uniforms[89]={none:0,linear:1,reinhard:2,cineon:3,aces:4,agx:5,neutral:6}[this.state.toneMapping??"none"],this.uniforms[90]=Math.max(0,this.state.vignetteIntensity??0),this.uniforms[91]=Math.min(1,Math.max(0,this.state.tintIntensity??0)),this.uniforms[92]=this.state.shadowsMax??.09,this.uniforms[93]=this.state.highlightsMin??.5,this.uniforms[94]=!1===this.state.enabled?0:1,this.uniforms[95]=0,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 yc}from"three";var Sc=class{options;passes=new Map;targetPrefix;constructor(e={}){this.options=e,this.targetPrefix=e.targetPrefix??"depthOfField"}addPass(e,t,i){if(!1===this.options.enabled)return t;const r=e.createColorTarget(`${this.targetPrefix}Color`,{format:"rgba16float"}),n=`${t}:${i}:${r}`;let a=this.passes.get(n);return a||(a=new Cc(t,i,r,this.options),this.passes.set(n,a)),e.addFullscreenPass(a),r}},Cc=class{constructor(e,t,i,r){this.state=r,this.inputs={source:e,sceneDepth:t},this.outputs=i}state;name="DepthOfField";sampler="linear";uniformBufferSize=80;inputs;outputs;uniforms=new Float32Array(20);inverseProjection=new yc;updateUniforms=e=>(this.inverseProjection.copy(Mc).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); }"},Mc=(new yc).set(1,0,0,0,0,1,0,0,0,0,.5,.5,0,0,0,1);import{Matrix4 as Pc,Vector2 as Bc,Vector3 as Dc}from"three";var Ic=(new Pc).set(1,0,0,0,0,1,0,0,0,0,.5,.5,0,0,0,1),Tc=(e=>(e[e.Disabled=0]="Disabled",e[e.CameraOnly=1]="CameraOnly",e[e.ObjectAndCamera=2]="ObjectAndCamera",e[e.ForceObjectBlur=3]="ForceObjectBlur",e))(Tc||{}),Rc={off:{enabled:!1,sampleCount:0},low:{enabled:!0,sampleCount:4,shutterScale:.65,maxBlurPixels:10,cameraBlurScale:.08,objectBlurScale:.8,depthRejectionStrength:28,velocityThresholdPixels:.75,dilation:!1},medium:{enabled:!0,sampleCount:8,shutterScale:.75,maxBlurPixels:18,cameraBlurScale:.1,objectBlurScale:1,depthRejectionStrength:24,velocityThresholdPixels:.6,dilation:!0},high:{enabled:!0,sampleCount:12,shutterScale:.85,maxBlurPixels:24,cameraBlurScale:.12,objectBlurScale:1.1,depthRejectionStrength:20,velocityThresholdPixels:.45,dilation:!0}},Vc=class{options;targetPrefix;currentViewProjection=new Pc;currentInverseViewProjection=new Pc;currentInverseProjection=new Pc;previousViewProjection=new Pc;pendingViewProjection=new Pc;previousProjection=new Pc;previousCameraWorld=new Pc;previousCameraPosition=new Dc;currentCameraPosition=new Dc;currentJitterUv=new Bc;historyValid=!1;pendingCamera=!1;width=1;height=1;timeSeconds=0;frameDuration=1/60;previousTimeSeconds=Number.NaN;nextOverrideId=1;overrides=[];passes=new Map;constructor(e={}){this.options={enabled:e.enabled??!0,sampleCount:zc(e.sampleCount??8),shutterScale:Lc(e.shutterScale??.75,0,4),maxBlurPixels:Lc(e.maxBlurPixels??18,0,128),cameraBlurScale:Lc(e.cameraBlurScale??.1,0,4),objectBlurScale:Lc(e.objectBlurScale??1,0,8),depthRejectionStrength:Lc(e.depthRejectionStrength??24,0,200),velocityThresholdPixels:Lc(e.velocityThresholdPixels??.6,0,16),dilation:e.dilation??!0,debugVelocity:e.debugVelocity??!1,targetFrameRate:Lc(e.targetFrameRate??60,15,240),maxFrameTime:Lc(e.maxFrameTime??.1,1/240,1),cameraCutDistance:Lc(e.cameraCutDistance??8,0,1e3),cameraCutRotationThreshold:Lc(e.cameraCutRotationThreshold??.75,0,2),projectionCutThreshold:Lc(e.projectionCutThreshold??.25,0,4)},this.targetPrefix=e.targetPrefix??"motionBlur"}applyPreset(e){Object.assign(this.options,Rc[e]),this.options.sampleCount=zc(this.options.sampleCount)}prepareCamera(e,t,i,r){t===this.width&&i===this.height||(this.width=Math.max(1,t),this.height=Math.max(1,i),this.reset());const n=r-this.previousTimeSeconds;Number.isFinite(n)&&n>0&&(this.frameDuration=Math.min(n,this.options.maxFrameTime),n>this.options.maxFrameTime&&this.reset()),this.previousTimeSeconds=r,this.timeSeconds=r,this.pruneOverrides(),e.getWorldPosition(this.currentCameraPosition),this.historyValid&&(this.currentCameraPosition.distanceTo(this.previousCameraPosition)>this.options.cameraCutDistance||function(e,t){let i=0;const r=[0,1,2,4,5,6,8,9,10];for(const n of r)i=Math.max(i,Math.abs(e.elements[n]-t.elements[n]));return i}(e.matrixWorld,this.previousCameraWorld)>this.options.cameraCutRotationThreshold||function(e,t){let i=0;for(let r=0;r<16;r+=1)i=Math.max(i,Math.abs(e.elements[r]-t.elements[r]));return i}(e.projectionMatrix,this.previousProjection)>this.options.projectionCutThreshold)&&this.reset(),this.pendingViewProjection.copy(Ic).multiply(e.projectionMatrix).multiply(e.matrixWorldInverse),this.currentViewProjection.copy(this.pendingViewProjection),this.currentInverseViewProjection.copy(this.currentViewProjection).invert(),this.currentInverseProjection.copy(Ic).multiply(e.projectionMatrix).invert(),this.historyValid||this.previousViewProjection.copy(this.currentViewProjection),this.pendingCamera=!0,this.previousProjection.copy(e.projectionMatrix),this.previousCameraWorld.copy(e.matrixWorld),this.previousCameraPosition.copy(this.currentCameraPosition)}commitCamera(){this.pendingCamera&&(this.previousViewProjection.copy(this.pendingViewProjection),this.historyValid=!0,this.pendingCamera=!1)}setJitterUv(e,t){this.currentJitterUv.set(Number.isFinite(e)?e:0,Number.isFinite(t)?t:0)}reset(){this.historyValid=!1,this.pendingCamera=!1}requiresRendererHistoryReset(){return!this.historyValid}pushOverride(e){const t=this.nextOverrideId++,i=Math.max(0,e.duration);return this.overrides.push({id:t,startTime:this.timeSeconds,endTime:this.timeSeconds+i,options:e}),{id:t,cancel:()=>{const e=this.overrides.findIndex(e=>e.id===t);e>=0&&this.overrides.splice(e,1)}}}addPass(e,t,i,r=e.mainDepth){const n=this.getResolvedSettings();if(!n.enabled||0===n.sampleCount)return t;const a=e.createColorTarget(`${this.targetPrefix}Color`,{format:"rgba16float"}),s=zc(n.sampleCount),o=`${t}:${i}:${r}:${a}:${s}`;let l=this.passes.get(o);return l||(l=new Gc(t,i,r,a,s,this),this.passes.set(o,l)),l.settings=n,e.addFullscreenPass(l),a}dispose(){this.passes.clear(),this.overrides.length=0}getTemporalMatrices(){return{currentInverseViewProjection:this.currentInverseViewProjection,currentInverseProjection:this.currentInverseProjection,previousViewProjection:this.previousViewProjection}}getFrameDuration(){return this.frameDuration}getJitterUv(){return this.currentJitterUv}pruneOverrides(){for(let e=this.overrides.length-1;e>=0;e-=1)this.overrides[e].endTime<=this.timeSeconds&&this.overrides.splice(e,1)}getResolvedSettings(){const e={...this.options};for(const t of this.overrides){const i=t.options;null!=i.enabled&&(e.enabled||=i.enabled),null!=i.sampleCount&&(e.sampleCount=Math.max(e.sampleCount,zc(i.sampleCount))),null!=i.shutterScale&&(e.shutterScale=Math.max(e.shutterScale,i.shutterScale)),null!=i.maxBlurPixels&&(e.maxBlurPixels=Math.max(e.maxBlurPixels,i.maxBlurPixels)),null!=i.cameraBlurScale&&(e.cameraBlurScale=Math.max(e.cameraBlurScale,i.cameraBlurScale)),null!=i.objectBlurScale&&(e.objectBlurScale=Math.max(e.objectBlurScale,i.objectBlurScale)),null!=i.dilation&&(e.dilation||=i.dilation),null!=i.debugVelocity&&(e.debugVelocity||=i.debugVelocity)}return e}},Gc=class{constructor(e,t,i,r,n,a){this.state=a,this.name=`MotionBlurResolve${n}`,this.inputs={source:e,velocity:t,depth:i},this.outputs=r,this.settings=a.options,this.fragmentShader=function(e){return`\nfn currentInverseViewProjection() -> mat4x4<f32> {\n return mat4x4<f32>(\n fullscreenUniforms[0], fullscreenUniforms[1],\n fullscreenUniforms[2], fullscreenUniforms[3]\n );\n}\n\nfn previousViewProjection() -> mat4x4<f32> {\n return mat4x4<f32>(\n fullscreenUniforms[4], fullscreenUniforms[5],\n fullscreenUniforms[6], fullscreenUniforms[7]\n );\n}\n\nfn currentInverseProjection() -> mat4x4<f32> {\n return mat4x4<f32>(\n fullscreenUniforms[8], fullscreenUniforms[9],\n fullscreenUniforms[10], fullscreenUniforms[11]\n );\n}\n\nfn uvToNdc(uv: vec2<f32>, depth: f32) -> vec4<f32> {\n let unjitteredUv = uv - fullscreenUniforms[14].xy;\n return vec4<f32>(\n unjitteredUv.x * 2.0 - 1.0,\n (0.5 - unjitteredUv.y) * 2.0,\n depth,\n 1.0\n );\n}\n\nfn viewDepth(uv: vec2<f32>, depth: f32) -> f32 {\n let view = currentInverseProjection() * uvToNdc(uv, depth);\n return abs(view.z / max(abs(view.w), 1e-6));\n}\n\nfn depthAt(uv: vec2<f32>) -> f32 {\n let dimensions = vec2<i32>(textureDimensions(depthTexture));\n let pixel = clamp(\n vec2<i32>(uv * vec2<f32>(dimensions)),\n vec2<i32>(0),\n dimensions - vec2<i32>(1)\n );\n return textureLoad(depthTexture, pixel, 0);\n}\n\nfn cameraVelocity(uv: vec2<f32>, depth: f32) -> vec2<f32> {\n let worldH = currentInverseViewProjection() * uvToNdc(uv, depth);\n let world = worldH / max(abs(worldH.w), 1e-6);\n let previousClip = previousViewProjection() * world;\n let previousNdc = previousClip.xy / max(abs(previousClip.w), 1e-6);\n let previousUv = previousNdc * vec2<f32>(0.5, -0.5) + vec2<f32>(0.5);\n return (uv - fullscreenUniforms[14].xy) - previousUv;\n}\n\nfn scaledVelocity(uv: vec2<f32>, packed: vec4<f32>, depth: f32) -> vec2<f32> {\n let camera = cameraVelocity(uv, depth);\n let objectRelative = packed.xy - camera;\n let mode = i32(round(packed.z));\n if (mode == 0) { return vec2<f32>(0.0); }\n if (mode == 1) {\n return camera * fullscreenUniforms[12].z;\n }\n let forceScale = select(1.0, 1.35, mode == 3);\n return camera * fullscreenUniforms[12].z +\n objectRelative * fullscreenUniforms[12].w * packed.w * forceScale;\n}\n\nfn chooseDilatedVelocity(\n uv: vec2<f32>,\n centerDepthRaw: f32,\n texel: vec2<f32>\n) -> vec2<f32> {\n let centerPacked = textureSampleLevel(velocityTexture, fullscreenSampler, uv, 0.0);\n var best = scaledVelocity(uv, centerPacked, centerDepthRaw);\n if (fullscreenUniforms[13].z < 0.5) { return best; }\n let centerDepth = viewDepth(uv, centerDepthRaw);\n for (var y = -1; y <= 1; y += 1) {\n for (var x = -1; x <= 1; x += 1) {\n let sampleUv = clamp(uv + vec2<f32>(f32(x), f32(y)) * texel, vec2<f32>(0.0), vec2<f32>(1.0));\n let sampleDepthRaw = depthAt(sampleUv);\n let sampleDepth = viewDepth(sampleUv, sampleDepthRaw);\n let depthSimilarity = abs(sampleDepth - centerDepth) / max(centerDepth, 1e-3);\n if (depthSimilarity < 0.025 || sampleDepth <= centerDepth) {\n let candidatePacked = textureSampleLevel(velocityTexture, fullscreenSampler, sampleUv, 0.0);\n let candidate = scaledVelocity(sampleUv, candidatePacked, sampleDepthRaw);\n if (dot(candidate, candidate) > dot(best, best)) { best = candidate; }\n }\n }\n }\n return best;\n}\n\n@fragment\nfn fsMain(input: FullscreenVertexOutput) -> @location(0) vec4<f32> {\n let centerColor = textureSampleLevel(sourceTexture, fullscreenSampler, input.uv, 0.0);\n let dimensions = vec2<f32>(textureDimensions(sourceTexture));\n let texel = 1.0 / dimensions;\n let centerDepthRaw = depthAt(input.uv);\n let centerDepth = viewDepth(input.uv, centerDepthRaw);\n var blurUv = chooseDilatedVelocity(input.uv, centerDepthRaw, texel) * fullscreenUniforms[12].x;\n let velocityPixels = length(blurUv * dimensions);\n\n if (fullscreenUniforms[13].w > 0.5) {\n let debugMagnitude = clamp(\n velocityPixels / max(fullscreenUniforms[12].y, 1.0),\n 0.0,\n 1.0\n );\n // Black means stationary. Moving pixels become brighter; R/G retain the\n // signed horizontal/vertical mapping around 0.5 and B shows magnitude.\n let directionColor = vec3<f32>(\n 0.5 + 0.5 * clamp(blurUv.x * 32.0, -1.0, 1.0),\n 0.5 + 0.5 * clamp(blurUv.y * 32.0, -1.0, 1.0),\n 1.0\n ) * debugMagnitude;\n return vec4<f32>(directionColor, 1.0);\n }\n\n let threshold = fullscreenUniforms[13].y;\n if (velocityPixels <= threshold) { return centerColor; }\n let maxBlurUv = fullscreenUniforms[12].y / max(dimensions.x, dimensions.y);\n let blurLength = length(blurUv);\n if (blurLength > maxBlurUv) { blurUv *= maxBlurUv / blurLength; }\n\n let activeSamples = clamp(\n i32(ceil(velocityPixels / max(threshold, 0.25))),\n 2,\n ${e}\n );\n var accumulated = centerColor;\n var totalWeight = 1.0;\n for (var sampleIndex = 0; sampleIndex < ${e}; sampleIndex += 1) {\n if (sampleIndex >= activeSamples) { continue; }\n let t = (f32(sampleIndex) + 0.5) / f32(activeSamples);\n let sampleUv = clamp(\n input.uv + mix(-0.5, 0.5, t) * blurUv,\n vec2<f32>(0.0),\n vec2<f32>(1.0)\n );\n let sampleDepthRaw = depthAt(sampleUv);\n let sampleDepth = viewDepth(sampleUv, sampleDepthRaw);\n let relativeDifference = abs(sampleDepth - centerDepth) / max(centerDepth, 1e-3);\n let depthWeight = exp(-relativeDifference * fullscreenUniforms[13].x);\n let sampleColor = textureSampleLevel(sourceTexture, fullscreenSampler, sampleUv, 0.0);\n accumulated += sampleColor * depthWeight;\n totalWeight += depthWeight;\n }\n return accumulated / max(totalWeight, 1e-4);\n}\n`}(n)}state;name;sampler="linear";uniformBufferSize=256;inputs;outputs;fragmentShader;settings;uniforms=new Float32Array(64);updateUniforms=()=>{const e=this.state.getTemporalMatrices();this.uniforms.set(e.currentInverseViewProjection.elements,0),this.uniforms.set(e.previousViewProjection.elements,16),this.uniforms.set(e.currentInverseProjection.elements,32);const t=1/this.settings.targetFrameRate/Math.max(this.state.getFrameDuration(),.001);this.uniforms.set([this.settings.shutterScale*t,this.settings.maxBlurPixels,this.settings.cameraBlurScale,this.settings.objectBlurScale,this.settings.depthRejectionStrength,this.settings.velocityThresholdPixels,this.settings.dilation?1:0,this.settings.debugVelocity?1:0],48);const i=this.state.getJitterUv();return this.uniforms[56]=i.x,this.uniforms[57]=i.y,this.uniforms}};function zc(e){return e<=0?0:e<=4?4:e<=8?8:e<=12?12:16}function Lc(e,t,i){return Math.min(i,Math.max(t,e))}var Uc=class{enabled;visibleEdgeColor;edgeStrength;edgeThickness;edgeSoftness;selectedObjects=new Set;selectionMembers=new Set;addSelectionMember=e=>{this.selectionMembers.add(e)};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??.6),this.edgeSoftness=Math.max(0,e.edgeSoftness??.6),this.targetPrefix=e.targetPrefix??"outline",this.maskMaterial=Ac(!1),this.skinnedMaskMaterial=Ac(!0)}setSelectedObjects(e){this.selectionMembers.clear(),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 i=e.createColorTarget(`${this.targetPrefix}Mask`,{format:"rgba8unorm"}),r=this.selectionMembers;r.clear();for(const e of this.selectedObjects)r.has(e)||e.traverse(this.addSelectionMember);e.addMaterialPass({name:"OutlineMask",outputs:i,clearColor:[0,0,0,0],loadDepth:!0,objectFilter:e=>null!==e&&r.has(e),overrideMaterial:(e,t)=>t?this.skinnedMaskMaterial:this.maskMaterial});for(let t=0;t<this.selectedInstances.length;t+=1){const r=this.selectedInstances[t];let n=this.instanceMaskMaterials.get(r.instanceIndex);n||(n=[Ac(!1,r.instanceIndex),Ac(!0,r.instanceIndex)],this.instanceMaskMaterials.set(r.instanceIndex,n)),e.addMaterialPass({name:`OutlineInstanceMask${t}-${r.instanceIndex}`,outputs:i,loadColor:!0,loadDepth:!0,objectFilter:e=>e===r.object,overrideMaterial:(e,t)=>t?n[1]:n[0]})}const n=e.createColorTarget(`${this.targetPrefix}Edge`,{format:"rgba16float"}),a=e.createColorTarget(`${this.targetPrefix}BlurHorizontal`,{format:"rgba16float"}),s=e.createColorTarget(`${this.targetPrefix}Blurred`,{format:"rgba16float"}),o=e.createColorTarget(`${this.targetPrefix}Color`,{format:"rgba16float"});return this.addCachedPass(e,`edge:${i}:${n}`,()=>new kc(i,n,this)),this.addCachedPass(e,`blur-h:${n}:${a}`,()=>new Fc("OutlineBlurHorizontal",n,a,!0,this)),this.addCachedPass(e,`blur-v:${a}:${s}`,()=>new Fc("OutlineBlurVertical",a,s,!1,this)),this.addCachedPass(e,`composite:${t}:${s}:${o}`,()=>new Oc(t,s,o,this)),o}addCachedPass(e,t,i){let r=this.passes.get(t);r||(r=i(),this.passes.set(t,r)),e.addFullscreenPass(r)}dispose(){this.selectionMembers.clear(),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 Ac(e,t=-1){return new lr({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:!1})}var kc=class{constructor(e,t,i){this.state=i,this.inputs={mask:e},this.outputs=t}state;name="OutlineEdge";sampler="linear";uniformBufferSize=16;inputs;outputs;uniforms=new Float32Array(4);updateUniforms=()=>(this.uniforms.set([this.state.edgeThickness,0,0,0]),this.uniforms);fragmentShader="\n@fragment fn fsMain(input: FullscreenVertexOutput) -> @location(0) vec4<f32> {\n let texel = 1.0 / vec2<f32>(textureDimensions(maskTexture));\n let radius = max(fullscreenUniforms[0].x, 0.5);\n let center = textureSample(maskTexture, fullscreenSampler, input.uv).r;\n let diagonalRadius = radius * 0.70710678;\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 let diagonalOffset = texel * diagonalRadius;\n around = max(around, textureSample(maskTexture, fullscreenSampler, input.uv + diagonalOffset).r);\n around = max(around, textureSample(maskTexture, fullscreenSampler, input.uv - diagonalOffset).r);\n around = max(around, textureSample(maskTexture, fullscreenSampler, input.uv + vec2(diagonalOffset.x, -diagonalOffset.y)).r);\n around = max(around, textureSample(maskTexture, fullscreenSampler, input.uv + vec2(-diagonalOffset.x, diagonalOffset.y)).r);\n let edge = clamp(around - center, 0.0, 1.0);\n return vec4(edge, edge, edge, 1.0);\n}"},Fc=class{constructor(e,t,i,r,n){this.name=e,this.horizontal=r,this.state=n,this.inputs={source:t},this.outputs=i}name;horizontal;state;sampler="linear";uniformBufferSize=16;inputs;outputs;uniforms=new Float32Array(4);updateUniforms=()=>(this.uniforms.set([this.state.edgeSoftness,this.horizontal?1:0,0,0]),this.uniforms);fragmentShader="\n@fragment fn fsMain(input: FullscreenVertexOutput) -> @location(0) vec4<f32> {\n let texel = 1.0 / vec2<f32>(textureDimensions(sourceTexture));\n let spread = max(fullscreenUniforms[0].x, 0.01);\n let axis = mix(vec2<f32>(0.0, texel.y), vec2<f32>(texel.x, 0.0), fullscreenUniforms[0].y) * spread;\n var value = textureSample(sourceTexture, fullscreenSampler, input.uv).r * 0.227027;\n value += textureSample(sourceTexture, fullscreenSampler, input.uv + axis * 1.384615).r * 0.316216;\n value += textureSample(sourceTexture, fullscreenSampler, input.uv - axis * 1.384615).r * 0.316216;\n value += textureSample(sourceTexture, fullscreenSampler, input.uv + axis * 3.230769).r * 0.070270;\n value += textureSample(sourceTexture, fullscreenSampler, input.uv - axis * 3.230769).r * 0.070270;\n return vec4(value, value, value, 1.0);\n}"},Oc=class{constructor(e,t,i,r){this.state=r,this.inputs={source:e,edge:t},this.outputs=i}state;name="OutlineComposite";sampler="linear";uniformBufferSize=16;inputs;outputs;uniforms=new Float32Array(4);updateUniforms=()=>(this.uniforms.set([this.state.visibleEdgeColor[0],this.state.visibleEdgeColor[1],this.state.visibleEdgeColor[2],this.state.edgeStrength]),this.uniforms);fragmentShader="\n@fragment fn fsMain(input: FullscreenVertexOutput) -> @location(0) vec4<f32> {\n let scene = textureSample(sourceTexture, fullscreenSampler, input.uv);\n let edge = textureSample(edgeTexture, fullscreenSampler, input.uv).r;\n let color = fullscreenUniforms[0].rgb * fullscreenUniforms[0].a;\n return vec4(scene.rgb + color * edge, scene.a);\n}"};import{AmbientLight as Ec,BackSide as jc,Bone as $c,BatchedMesh as Wc,BoxGeometry as Nc,BufferAttribute as _c,BufferGeometry as Hc,CanvasTexture as qc,Color as Kc,CompressedArrayTexture as Yc,CompressedArrayTexture as Zc,CompressedCubeTexture as Xc,CompressedTexture as Jc,CubeTexture as Qc,Data3DTexture as eu,DataArrayTexture as tu,DataTexture as iu,DepthTexture as ru,DirectionalLight as nu,DoubleSide as au,FrontSide as su,Group as ou,HemisphereLight as lu,InstancedMesh as cu,MathUtils as uu,Matrix4 as du,Mesh as hu,Object3D as pu,OrthographicCamera as fu,PerspectiveCamera as mu,PlaneGeometry as gu,PointLight as vu,RepeatWrapping as xu,Scene as wu,Skeleton as bu,SkinnedMesh as yu,SphereGeometry as Su,SpotLight as Cu,Texture as Mu,Vector2 as Pu,Vector3 as Bu,Vector4 as Du}from"three";export{Ec as AmbientLight,jc as BackSide,Wc as BatchedMesh,hc as BloomEffect,$c as Bone,Nc as BoxGeometry,_c as BufferAttribute,Hc as BufferGeometry,qc as CanvasTexture,Kc as Color,wc as ColorGradingEffect,Yc as CompressedArrayTexture,Xc as CompressedCubeTexture,Jc as CompressedTexture,Zc as CompressedTextureArray,_ as ComputeKernel,Qc as CubeTexture,or as DEFAULT_WGSL_VERTEX_ATTRIBUTES,eu as Data3DTexture,tu as DataArrayTexture,iu as DataTexture,Sc as DepthOfFieldEffect,ru as DepthTexture,nu as DirectionalLight,au as DoubleSide,Wl as FXAAEffect,Ai as FrameGraphBuilder,su as FrontSide,gl as GTAOEffect,ml as GTAO_PRESETS,ou as Group,lu as HemisphereLight,cu as InstancedMesh,Rc as MOTION_BLUR_PRESETS,uu as MathUtils,du as Matrix4,hu as Mesh,Vc as MotionBlurEffect,Tc as MotionBlurMode,pu as Object3D,fu as OrthographicCamera,Uc as OutlineEffect,mu as PerspectiveCamera,gu as PlaneGeometry,vu as PointLight,$a as RenderGraph,xu as RepeatWrapping,D as SCENE_COLOR_FORMAT,fe as SDFGI,ve as SDFGISurfaceCapture,Ql as SMAAEffect,Il as SSREffect,wu as Scene,bu as Skeleton,yu as SkinnedMesh,Su as SphereGeometry,Cu as SpotLight,Ol as TemporalAAEffect,Mu as Texture,We as VOLUMETRIC_FOG_MATERIAL_WGSL,De as VOLUMETRIC_FOG_PRESETS,Pu as Vector2,Bu as Vector3,Du as Vector4,Ae as VolumetricFogEffect,Be as VolumetricFogVolumeObject,lr as WGSLShaderMaterial,Ja as WebGpuPMREMGenerator,ol as WebGpuRenderer,ds as buildParticleLightingShaderHeader,Ne as configureVolumetricFogMaterial,N as createComputePipelineAsync,W as createRenderPipelineAsync,Ei as disposeExternalSkeletonPalette,gn as disposeSkinnedMeshResources,i as registerPipelineDiagnosticOrigin,f as resolveDetailCulling,ji as setExternalSkeletonPalette,d as setObjectDetailCulling,t as setPipelineDiagnosticLoading};
|
|
1
|
+
var e=new WeakMap;function t(t,i,r){const n=e.get(t);n&&(i?(n.loadingStartedAt=performance.now(),n.loadingRequests=[]):n.loading&&(!function(e,t){const i=e.loadingRequests,r=new Map;for(const e of i){const t=e.kind+":"+(e.origin?.key??e.label??"unlabelled"),i=r.get(t);i?i.push(e):r.set(t,[e])}const n=(console.groupCollapsed??console.info).bind(console),a=(console.table??console.info).bind(console);n("[Hology shaders] Loading compilation summary: "+t),console.info("New creation requests during this load (previously cached pipelines are excluded)",{elapsedMs:Math.round(performance.now()-e.loadingStartedAt),...l(i),render:l(i.filter(e=>"render"===e.kind)),compute:l(i.filter(e=>"compute"===e.kind)),gpuVfx:l(i.filter(e=>e.origin?.key.startsWith("gpu-vfx:")))}),a([...r].map(([e,t])=>({origin:e,...l(t)})).sort((e,t)=>t.uniquePipelineVariants-e.uniquePipelineVariants)),console.info("Slowest creation requests",[...i].sort((e,t)=>t.durationMs-e.durationMs).slice(0,20).map(({signature:e,shaders:t,state:i,...r})=>r));const s=u(i);a(s.map(({variants:e,...t})=>t)),console.info("GPU VFX variant report (copy this array)",s);const o=u(i,!1);a(o.map(({variants:e,...t})=>t)),console.info("Material variant report (copy this array)",o),console.info("VFX groups attribute each created pipeline to its first requester; cache-hit users are not enumerated. Difference fields compare against the first variant in each group and do not prove why shader source changed."),console.info("Counts use descriptor signatures and shader source fingerprints, not material counts. Async totals overlap; sync timings measure handle creation, not full GPU compilation. GPU VFX attribution excludes CPU-simulated VFX drawn through ordinary mesh pipelines."),console.groupEnd?.()}(n,r),n.loadingRequests=[]),n.loading=i,n.phase=r)}function i(t,i,r){const n=e.get(t);n&&(n.origins.size>=4096&&!n.origins.has(i)&&n.origins.delete(n.origins.keys().next().value),n.origins.set(i,r))}function r(t,i){const r=e.get(t),n=r?.origins.get(i.label??"");n&&r.descriptorOrigins.set(i,n)}function n(e){let t=2166136261;for(let i=0;i<e.length;i++)t=Math.imul(t^e.charCodeAt(i),16777619);return(t>>>0).toString(16)}function a(e,t){if(null==e||"object"!=typeof e)return e;const i=t.objects.get(e);if(null!=i)return i;if(Array.isArray(e))return e.map(e=>a(e,t));const r={};for(const i of Object.keys(e).sort())"label"!==i&&(r[i]=a(e[i],t));return r}function s(e,t,i=""){if(JSON.stringify(e)===JSON.stringify(t))return[];if(e&&t&&"object"==typeof e&&"object"==typeof t){const r=e,n=t;return[...new Set([...Object.keys(r),...Object.keys(n)])].flatMap(e=>s(r[e],n[e],i?i+"."+e:e))}return[{field:i,previous:e,current:t}]}function o(e){const t=[];for(const i of["vertex","fragment","compute"]){const r=e[i]?.module;r?.shaderHash&&t.push(r.shaderHash+":"+r.codeLength)}return t}function l(e){const t=new Set(e.map(e=>e.kind+":"+e.signature));return{requests:e.length,uniquePipelineVariants:t.size,uniqueShaderSources:new Set(e.flatMap(e=>e.shaders)).size,duplicateRequests:e.length-t.size,failed:e.filter(e=>"failed"===e.status).length,pending:e.filter(e=>"pending"===e.status).length,asyncReadyTotalMs:Math.round(e.reduce((e,t)=>e+(t.async?t.durationMs:0),0)),syncCreationTotalMs:Math.round(e.reduce((e,t)=>e+(t.async?0:t.durationMs),0))}}function c(e){const t={...e};for(const i of["vertex","fragment","compute"])if(null!=e[i]){const{module:r,...n}=e[i];t[i]=n}return t}function u(e,t=!0){const i=new Map;for(const r of e){if("render"!==r.kind||Boolean(r.origin?.key.startsWith("gpu-vfx:"))!==t)continue;const e=r.origin?.shader,n=r.origin?.material,a=t?e?.key??"unattributed":String(n?.assetId??n?.sourceUuid??r.origin?.key.replace(/:(forward|depth:.*)$/,"")??r.label??"unattributed"),s=i.get(a);s?s.push(r):i.set(a,[r])}return[...i].map(([e,i])=>{const r=[...new Map(i.map(e=>[e.signature,e])).values()],a=c(r[0].state),o=r[0].origin?.shader,u=r.map(e=>{const t=c(e.state);return{pipelineId:n(e.signature),origin:e.origin?.key,material:e.origin?.material,shaderSources:[...new Set(e.shaders)],stageSources:Object.fromEntries(["vertex","fragment"].filter(t=>null!=e.state[t]).map(t=>[t,e.state[t].module])),stateId:n(JSON.stringify(t)),layoutId:n(JSON.stringify(t.layout??null)),stateDifferenceFields:s(a,t).map(e=>e.field),shaderProfileDifferences:s(o,e.origin?.shader),shader:e.origin?.shader,features:e.origin?.variant,featureDifferences:s(r[0].origin?.variant,e.origin?.variant),defines:e.origin?.defines,bindings:e.origin?.bindings,assets:e.origin?.vfxAssets,pipelineState:t,readyAfterMs:Math.round(e.durationMs),status:e.status}});return{graph:e,name:t?i[0].origin?.shader?.name??e:i[0].origin?.material?.assetName||i[0].origin?.material?.name||e,...l(i),shaderCombinations:new Set(r.map(e=>JSON.stringify(e.shaders))).size,pipelineStates:new Set(u.map(e=>e.stateId)).size,layouts:new Set(u.map(e=>e.layoutId)).size,variants:u}}).sort((e,t)=>t.uniquePipelineVariants-e.uniquePipelineVariants)}function d(e,t){e.userData.detailCulling=t}var h=Object.freeze({minScreenSize:10,maxDistance:0,shadowMinScreenSize:2,shadowMaxDistance:0}),p=[];function f(e,t){let i=!!t;for(let t=e;t&&!i;t=t.parent)i=!!t.userData.detailCulling;if(!i)return h;let r=!0,{minScreenSize:n,maxDistance:a,shadowMinScreenSize:s,shadowMaxDistance:o}=h,l=!0;const c=e=>{e&&(r=e.enabled??r,n=e.minScreenSize??n,a=e.maxDistance??a,l=e.shadow?.enabled??l,s=e.shadow?.minScreenSize??s,o=e.shadow?.maxDistance??o)};c(t),p.length=0;for(let t=e;t;t=t.parent)p.push(t);for(let e=p.length-1;e>=0;e--)c(p[e].userData.detailCulling);const u=e=>Number.isFinite(e)&&e>0?e:0;return{minScreenSize:r?u(n):0,maxDistance:u(a),shadowMinScreenSize:l?u(s):0,shadowMaxDistance:u(o)}}var m=class{rowXLength=1;rowYLength=1;rowWLength=0;update(e){const t=e.elements;this.rowXLength=Math.hypot(t[0],t[4],t[8]),this.rowYLength=Math.hypot(t[1],t[5],t[9]),this.rowWLength=Math.hypot(t[3],t[7],t[11])}};function g(e,t,i,r,n,a,s,o,l){if(o>0&&e.distanceTo(a)-t>o)return!1;if(s<=0)return!0;const c=i.elements,u=e.x,d=e.y,h=e.z,p=c[3]*u+c[7]*d+c[11]*h+c[15],f=l?.rowWLength??Math.hypot(c[3],c[7],c[11]),m=p-t*f;if(m<=1e-4)return!0;const g=(c[0]*u+c[4]*d+c[8]*h+c[12])/p,v=(c[1]*u+c[5]*d+c[9]*h+c[13])/p,x=l?.rowXLength??Math.hypot(c[0],c[4],c[8]),w=l?.rowYLength??Math.hypot(c[1],c[5],c[9]);return t*Math.max((x+Math.abs(g)*f)*r,(w+Math.abs(v)*f)*n)/m>=s}function v(e,t,i,r,n,a){const s=e.boundsCenter,o=e.boundsRadius;if(e.maxDistance>0&&s.distanceTo(n)-o>e.maxDistance)return!1;if(e.minScreenSize<=0)return!0;const l=t.elements,c=s.x,u=s.y,d=s.z,h=a?.rowWLength??Math.hypot(l[3],l[7],l[11]),p=l[3]*c+l[7]*u+l[11]*d+l[15]-o*h;if(p<=1e-4)return!0;const f=a?.rowXLength??Math.hypot(l[0],l[4],l[8]),m=a?.rowYLength??Math.hypot(l[1],l[5],l[9]),g=(Math.abs(l[0]*c+l[4]*u+l[8]*d+l[12])+o*f)/p,v=(Math.abs(l[1]*c+l[5]*u+l[9]*d+l[13])+o*m)/p;return e.maxMemberRadius*Math.max((f+g*h)*i,(m+v*h)*r)/p>=.85*e.minScreenSize}import{Matrix4 as x,Sphere as w,Vector3 as b}from"three";var y=64,S=64,C=40,M=12,P=new Float32Array(C),B=new Float32Array([1,1,1,1]),D="rgba16float",I="rgba8unorm",T=(new x).set(1,0,0,0,0,1,0,0,0,0,.5,.5,0,0,0,1),R=[new b(0,-1,0),new b(0,-1,0),new b(0,0,1),new b(0,0,-1),new b(0,-1,0),new b(0,-1,0)],V=[new b(1,0,0),new b(-1,0,0),new b(0,1,0),new b(0,-1,0),new b(0,0,1),new b(0,0,-1)],G=4004,z=[{name:"position",shaderLocation:0,format:"float32x3"}],L=[{name:"position",shaderLocation:0,format:"float32x3"},{name:"skinIndex",shaderLocation:1,format:"uint32x4"},{name:"skinWeight",shaderLocation:2,format:"float32x4"}],U=new x,k=new x,A=(new x,new x,new w),F=new b,O=new b,E=new b,j=(new b,new b,new b,new b,new WeakMap);async function $(e,t){const i=j.get(e)??Promise.resolve();let r;const n=new Promise(e=>{r=e});j.set(e,i.catch(()=>{}).then(()=>n)),await i.catch(()=>{});try{return await new Promise(e=>requestAnimationFrame(()=>e())),t()}finally{r()}}function W(e,t){return r(e,t),"function"==typeof e.createRenderPipelineAsync?e.createRenderPipelineAsync(t):$(e,()=>e.createRenderPipeline(t))}function N(e,t){return r(e,t),"function"==typeof e.createComputePipelineAsync?e.createComputePipelineAsync(t):$(e,()=>e.createComputePipeline(t))}var _=class e{layout;pipeline;static async createAsync(t,i){const{pipelineDescriptor:r}=H(t,i),n=await N(t,r);return new e(t,i,n)}constructor(e,t,i){if(i)return this.layout=i.getBindGroupLayout(0),void(this.pipeline=i);const{layout:r,pipelineDescriptor:n}=H(e,t);this.layout=r,this.pipeline=e.createComputePipeline(n)}createBindGroup(e,t,i){return e.createBindGroup({label:i,layout:this.layout,entries:t})}};function H(e,t){const i=e.createBindGroupLayout({label:t.label?`${t.label}-layout`:void 0,entries:t.bindGroupLayoutEntries});return{layout:i,pipelineDescriptor:{label:t.label,layout:e.createPipelineLayout({label:t.label?`${t.label}-pipeline-layout`:void 0,bindGroupLayouts:[i]}),compute:{module:e.createShaderModule({label:t.label?`${t.label}-module`:void 0,code:t.code}),entryPoint:t.entryPoint??"main"}}}}import{DirectionalLight as q,DoubleSide as K,Light as Y,NoBlending as Z,PointLight as X,SpotLight as J,Vector3 as Q}from"three";var ee="\nfn rendererSdfgiSample(worldPosition: vec3<f32>, worldNormal: vec3<f32>, bank: u32) -> vec3<f32> {\n let originCell = sdfgiField[bank + 0];\n let settings = sdfgiField[bank + 1]; // spacing, probe count per axis, intensity, normal bias\n if (settings.z <= 0.0 || sdfgiField[bank + 2].x < 0.5) { return vec3<f32>(0.0); }\n let n = u32(settings.y);\n let normal = normalize(worldNormal);\n let position = worldPosition + normal * settings.w;\n let local = (position - originCell.xyz - vec3<f32>(originCell.w * 2.0)) / settings.x;\n let edge = min(local, vec3<f32>(f32(n - 1u)) - local);\n let fade = smoothstep(0.0, 1.0, min(edge.x, min(edge.y, edge.z)));\n if (fade <= 0.0) { return vec3<f32>(0.0); }\n // Quadratic B-spline support overlaps two probe planes at a cell boundary.\n // Trilinear's single shared plane can consist entirely of inactive probes\n // near geometry, causing a discontinuous normalized blend and square seams.\n let base = vec3<i32>(floor(local + vec3<f32>(0.5))) - vec3<i32>(1);\n var result = vec3<f32>(0.0);\n var weightSum = 0.0;\n var unoccludedWeightSum = 0.0;\n for (var neighbor = 0u; neighbor < 27u; neighbor++) {\n let cell = base + vec3<i32>(i32(neighbor % 3u), i32((neighbor / 3u) % 3u), i32(neighbor / 9u));\n if (any(cell < vec3<i32>(0)) || any(cell >= vec3<i32>(i32(n)))) { continue; }\n let distance = abs(local - vec3<f32>(cell));\n let tail = max(vec3<f32>(1.5) - distance, vec3<f32>(0.0));\n let spatial = select(0.5 * tail * tail, vec3<f32>(0.75) - distance * distance, distance <= vec3<f32>(0.5));\n let spatialWeight = spatial.x * spatial.y * spatial.z;\n if (spatialWeight <= 0.0) { continue; }\n let index = 4u + u32(cell.x + i32(n) * (cell.y + i32(n) * cell.z)) * 10u;\n if (sdfgiField[bank + index].w < 0.5) { continue; }\n let probePosition = originCell.xyz + vec3<f32>(originCell.w * 2.0) + vec3<f32>(cell) * settings.x;\n let delta = position - probePosition;\n let distanceToProbe = length(delta);\n let direction = delta / max(distanceToProbe, 0.0001);\n // Keep directional bounds separate. Averaging a nearby wall with an open\n // direction creates a large variance that incorrectly admits light through\n // the wall. Moments store distances projected onto each cardinal axis.\n var visibility = 1.0;\n for (var axis = 0u; axis < 3u; axis++) {\n let moment = sdfgiField[bank + index + 4u + axis * 2u + select(1u, 0u, delta[axis] >= 0.0)].xy;\n let variance = max(moment.y - moment.x * moment.x, originCell.w * originCell.w * 0.001);\n let difference = max(abs(delta[axis]) - moment.x - originCell.w * 0.05, 0.0);\n let bound = variance / (variance + difference * difference);\n visibility = min(visibility, bound * bound * bound);\n }\n let facing = max(0.05, dot(-direction, normal) * 0.5 + 0.5);\n let unoccludedWeight = spatialWeight * facing * facing;\n let weight = unoccludedWeight * visibility;\n let irradiance = sdfgiField[bank + index].xyz * 0.282095\n + sdfgiField[bank + index + 1u].xyz * (0.488603 * normal.x)\n + sdfgiField[bank + index + 2u].xyz * (0.488603 * normal.y)\n + sdfgiField[bank + index + 3u].xyz * (0.488603 * normal.z);\n result += max(irradiance, vec3<f32>(0.0)) * weight;\n weightSum += weight;\n unoccludedWeightSum += unoccludedWeight;\n }\n // Visibility and normal weights can be tiny near walls or inactive probes.\n // A large denominator floor turns those weights into dark lattice patches\n // instead of normalizing the remaining valid irradiance.\n // Normalization must not amplify an entirely occluded neighborhood back to\n // full brightness. Fade unsupported lighting continuously instead of using\n // a fixed denominator cutoff that would expose the probe lattice again.\n let support = weightSum / max(unoccludedWeightSum, 1e-8);\n let confidence = smoothstep(0.0, 0.1, support);\n return result / max(weightSum, 1e-8) * (fade * confidence);\n}\nfn rendererSdfgiIrradiance(worldPosition: vec3<f32>, worldNormal: vec3<f32>) -> vec3<f32> {\n let intensity = sdfgiField[1].z;\n if (intensity <= 0.0 || sdfgiField[2].x < 0.5) { return vec3<f32>(0.0); }\n let blend = sdfgiField[2].y;\n var previous = vec3<f32>(0.0);\n if (blend < 1.0 && sdfgiField[2].z > 0.5) {\n previous = rendererSdfgiSample(worldPosition, worldNormal, u32(sdfgiField[3].x));\n }\n if (blend <= 0.0) { return previous * intensity; }\n let current = rendererSdfgiSample(worldPosition, worldNormal, 0u);\n return mix(previous, current, blend) * intensity;\n}\n";var te="\nstruct Params {\n originCell: vec4<f32>,\n grid: vec4<u32>, // voxel resolution, probe resolution, ray count, frame\n settings: vec4<f32>, // probe spacing, history weight, bias, max ray distance\n sky: vec4<f32>,\n update: vec4<u32>, // first probe, probe count, reset history, maximum steps\n lights: vec4<u32>, // count\n};\nfn cellIndex(cell: vec3<u32>, n: u32) -> u32 { return cell.x + n * (cell.y + n * cell.z); }\nfn cellPosition(index: u32, n: u32) -> vec3<u32> { return vec3<u32>(index % n, (index / n) % n, index / (n * n)); }\n",ie=te+"\n@group(0) @binding(0) var<uniform> params: Params;\n@group(0) @binding(1) var<storage, read> surfaces: array<vec4<f32>>;\n@group(0) @binding(2) var<storage, read_write> output: array<vec4<i32>>;\n@compute @workgroup_size(64)\nfn main(@builtin(global_invocation_id) id: vec3<u32>) {\n let n = params.grid.x;\n if (id.x >= n * n * n) { return; }\n let cell = cellPosition(id.x, n);\n output[id.x] = vec4<i32>(vec3<i32>(cell), select(0, 1, surfaces[id.x * 3u].w > 0.0));\n}\n",re=te+"\n@group(0) @binding(0) var<uniform> params: Params;\n@group(0) @binding(1) var<uniform> jump: vec4<u32>;\n@group(0) @binding(2) var<storage, read> source: array<vec4<i32>>;\n@group(0) @binding(3) var<storage, read_write> output: array<vec4<i32>>;\n@compute @workgroup_size(64)\nfn main(@builtin(global_invocation_id) id: vec3<u32>) {\n let n = params.grid.x;\n if (id.x >= n * n * n) { return; }\n let position = vec3<i32>(cellPosition(id.x, n));\n var nearest = source[id.x];\n var best = 1e20;\n if (nearest.w != 0) { let delta = vec3<f32>(nearest.xyz - position); best = dot(delta, delta); }\n for (var z = -1; z <= 1; z++) { for (var y = -1; y <= 1; y++) { for (var x = -1; x <= 1; x++) {\n let cell = position + vec3<i32>(x, y, z) * i32(jump.x);\n if (any(cell < vec3<i32>(0)) || any(cell >= vec3<i32>(i32(n)))) { continue; }\n let candidate = source[cellIndex(vec3<u32>(cell), n)];\n if (candidate.w == 0) { continue; }\n let delta = vec3<f32>(candidate.xyz - position);\n let distanceSquared = dot(delta, delta);\n if (distanceSquared < best) { nearest = candidate; best = distanceSquared; }\n } } }\n output[id.x] = nearest;\n}\n",ne="\nfn distanceField(position: vec3<f32>) -> vec2<f32> {\n let local = (position - params.originCell.xyz) / params.originCell.w;\n let n = params.grid.x;\n if (any(local < vec3<f32>(0.0)) || any(local >= vec3<f32>(f32(n)))) { return vec2<f32>(params.settings.w, -1.0); }\n let seed = nearest[cellIndex(vec3<u32>(local), n)];\n if (seed.w == 0) { return vec2<f32>(params.settings.w, -1.0); }\n // Distance to the voxel box. A circumscribed sphere inflates its faces and\n // corners, making nearby receivers appear occluded even outside the voxel.\n let distance = length(max(abs(local - vec3<f32>(seed.xyz) - vec3<f32>(0.5)) - vec3<f32>(0.5), vec3<f32>(0.0)));\n return vec2<f32>(distance * params.originCell.w, f32(cellIndex(vec3<u32>(seed.xyz), n)));\n}\nfn trace(origin: vec3<f32>, direction: vec3<f32>, limit: f32) -> vec2<f32> {\n var distance = 0.0;\n for (var step = 0u; step < params.update.w; step++) {\n let sample = distanceField(origin + direction * distance);\n if (sample.y < 0.0) { return vec2<f32>(-1.0, limit); }\n if (sample.x < params.originCell.w * 0.2) { return vec2<f32>(sample.y, distance); }\n distance += max(sample.x * 0.8, params.originCell.w * 0.2);\n if (distance >= limit) { return vec2<f32>(-1.0, limit); }\n }\n // A step-budget miss is conservatively occluded, avoiding light leaks.\n return vec2<f32>(-2.0, distance);\n}\n",ae=te+"\n@group(0) @binding(0) var<uniform> params: Params;\n@group(0) @binding(1) var<storage, read> surfaces: array<vec4<f32>>;\n@group(0) @binding(2) var<storage, read> nearest: array<vec4<i32>>;\n@group(0) @binding(3) var<storage, read> lights: array<vec4<f32>>;\n@group(0) @binding(4) var<storage, read_write> radiance: array<vec4<f32>>;\n"+ne+"\n@compute @workgroup_size(64)\nfn main(@builtin(global_invocation_id) id: vec3<u32>) {\n let n = params.grid.x;\n if (id.x >= n * n * n) { return; }\n let albedo = surfaces[id.x * 3u];\n if (albedo.w == 0.0) { radiance[id.x * 2u] = vec4<f32>(0.0); radiance[id.x * 2u + 1u] = vec4<f32>(0.0); return; }\n let surface = surfaces[id.x * 3u + 1u];\n let position = params.originCell.xyz + (vec3<f32>(cellPosition(id.x, n)) + vec3<f32>(0.5)) * params.originCell.w;\n var illumination = vec3<f32>(0.0);\n var backIllumination = vec3<f32>(0.0);\n for (var light = 0u; light < params.lights.x; light++) {\n let source = lights[light * 4u]; // position/directional flag\n let color = lights[light * 4u + 1u].xyz;\n let directionRange = lights[light * 4u + 2u];\n let coneDecay = lights[light * 4u + 3u];\n var direction = directionRange.xyz;\n var limit = params.settings.w;\n var attenuation = 1.0;\n if (source.w > 0.5) {\n let delta = source.xyz - position;\n limit = length(delta);\n direction = delta / max(limit, 0.0001);\n attenuation = 1.0 / max(pow(limit, coneDecay.z), 0.01);\n if (directionRange.w > 0.0) {\n let ratio = limit / directionRange.w;\n attenuation *= pow(clamp(1.0 - pow(ratio, 4.0), 0.0, 1.0), 2.0);\n }\n if (source.w > 1.5) {\n let cone = dot(-direction, directionRange.xyz);\n if (coneDecay.y - coneDecay.x > 0.00001) { attenuation *= smoothstep(coneDecay.x, coneDecay.y, cone); }\n else { attenuation *= select(0.0, 1.0, cone >= coneDecay.x); }\n }\n }\n let cosine = select(max(dot(surface.xyz, direction), 0.0), abs(dot(surface.xyz, direction)), surface.w > 0.5);\n if (cosine * attenuation <= 0.00001) { continue; }\n let biasNormal = surface.xyz * select(1.0, -1.0, dot(surface.xyz, direction) < 0.0);\n let shadow = trace(position + biasNormal * params.originCell.w * 1.8, direction, limit);\n if (shadow.x == -1.0) {\n if (dot(surface.xyz, direction) >= 0.0) { illumination += color * (cosine * attenuation); }\n else { backIllumination += color * (cosine * attenuation); }\n }\n }\n // Keep both sides separate so a double-sided wall cannot transmit sunlight.\n let emission = surfaces[id.x * 3u + 2u].xyz;\n radiance[id.x * 2u] = vec4<f32>(emission + albedo.xyz * illumination * 0.318309886, 1.0);\n radiance[id.x * 2u + 1u] = vec4<f32>(emission + albedo.xyz * backIllumination * 0.318309886, 1.0);\n}\n",se=te+"\n@group(0) @binding(0) var<uniform> params: Params;\n@group(0) @binding(1) var<storage, read> surfaces: array<vec4<f32>>;\n@group(0) @binding(2) var<storage, read> nearest: array<vec4<i32>>;\n@group(0) @binding(3) var<storage, read> radiance: array<vec4<f32>>;\n@group(0) @binding(4) var<storage, read_write> field: array<vec4<f32>>;\n"+ne+"\n@compute @workgroup_size(32)\nfn main(@builtin(global_invocation_id) id: vec3<u32>) {\n if (id.x >= params.update.y) { return; }\n let p = params.grid.y;\n let probe = (params.update.x + id.x) % (p * p * p);\n let base = 4u + probe * 10u;\n let position = params.originCell.xyz + vec3<f32>(params.originCell.w * 2.0)\n + vec3<f32>(cellPosition(probe, p)) * params.settings.x;\n if (distanceField(position).x < params.originCell.w * 0.6) {\n for (var i = 0u; i < 10u; i++) { field[base + i] = vec4<f32>(0.0); }\n return;\n }\n var coefficients: array<vec3<f32>, 4>;\n var moments: array<vec3<f32>, 6>;\n let count = params.grid.z;\n // Keep each probe's integration directions stable. Rotating every update\n // repeatedly hits/misses small emissive surfaces and makes their light pulse,\n // including in a completely stationary scene. Different probes retain\n // different azimuths to avoid aligning sampling errors across the lattice.\n // Seed from the global lattice coordinate, never the index in the moving\n // volume, so a retained world probe traces the same rays after a scroll.\n let worldProbe = bitcast<vec3<u32>>(vec3<i32>(round((position - vec3<f32>(params.originCell.w * 2.0)) / params.settings.x)));\n var hash = (worldProbe.x * 73856093u) ^ (worldProbe.y * 19349663u) ^ (worldProbe.z * 83492791u);\n hash = hash ^ (hash >> 16u);\n let rotation = f32(hash & 65535u) * (6.283185307 / 65536.0);\n for (var ray = 0u; ray < count; ray++) {\n let y = 1.0 - 2.0 * (f32(ray) + 0.5) / f32(count);\n let radius = sqrt(max(0.0, 1.0 - y * y));\n let angle = f32(ray) * 2.39996323 + rotation;\n let direction = vec3<f32>(cos(angle) * radius, y, sin(angle) * radius);\n let hit = trace(position, direction, params.settings.w);\n var visibilityDistance = hit.y;\n var incoming = vec3<f32>(0.0);\n if (hit.x == -1.0) { incoming = params.sky.xyz; }\n if (hit.x >= 0.0) {\n let index = u32(hit.x);\n let normal = surfaces[index * 3u + 1u];\n // Trace conservatively against voxel boxes, but measure visibility to\n // the captured physical surface plane. Using the thick voxel shell here\n // falsely hides floor-adjacent receivers behind the floor's own voxels.\n let center = params.originCell.xyz + (vec3<f32>(cellPosition(index, params.grid.x)) + vec3<f32>(0.5)) * params.originCell.w;\n let plane = center + normal.xyz * surfaces[index * 3u + 2u].w;\n let denominator = dot(direction, normal.xyz);\n if (abs(denominator) > 0.0001) {\n let planeDistance = dot(plane - position, normal.xyz) / denominator;\n let intersection = position + direction * planeDistance;\n if (planeDistance >= 0.0 && all(abs(intersection - center) <= vec3<f32>(params.originCell.w * 1.5))) {\n visibilityDistance = planeDistance;\n }\n }\n let front = dot(normal.xyz, -direction) > 0.0;\n if (normal.w > 0.5 || front) { incoming = radiance[index * 2u + select(1u, 0u, front)].xyz; }\n }\n coefficients[0] += incoming * 0.282095;\n coefficients[1] += incoming * (0.488603 * direction.x);\n coefficients[2] += incoming * (0.488603 * direction.y);\n coefficients[3] += incoming * (0.488603 * direction.z);\n for (var axis = 0u; axis < 6u; axis++) {\n var axisDirection = vec3<f32>(0.0);\n axisDirection[axis / 2u] = select(-1.0, 1.0, axis % 2u == 0u);\n let projection = max(dot(direction, axisDirection), 0.0);\n let weight = pow(projection, 8.0);\n let distance = visibilityDistance * projection;\n moments[axis] += vec3<f32>(distance, distance * distance, 1.0) * weight;\n }\n }\n let history = select(0.0, params.settings.y, params.update.z == 0u && field[base].w > 0.5);\n for (var i = 0u; i < 4u; i++) {\n let convolution = select(2.094395102, 3.141592654, i == 0u);\n let value = coefficients[i] * (12.566370614 / f32(count)) * convolution;\n field[base + i] = vec4<f32>(mix(value, field[base + i].xyz, history), 1.0);\n }\n for (var i = 0u; i < 6u; i++) {\n let value = moments[i].xy / max(moments[i].z, 0.00001);\n field[base + 4u + i] = vec4<f32>(mix(value, field[base + 4u + i].xy, history), 0.0, 0.0);\n }\n}\n";function oe(e,t,i,r){return null!=e&&Number.isFinite(e)?Math.min(r,Math.max(i,e)):t}function le(e,t,i,r,n,a){e[t]=i,e[t+1]=r,e[t+2]=n,e[t+3]=a}var ce={label:"SDFGISeed"},ue={label:"SDFGIJumpFlood"},de={label:"SDFGILightInjection"},he={label:"SDFGIProbeUpdate"},pe={label:"SDFGIProbeSnapshot"},fe=class e{constructor(t,i={}){if(this.device=t,this.resolution=i.resolution??64,![32,64,128].includes(this.resolution))throw new Error("SDFGI resolution must be 32, 64, or 128.");this.extent=oe(i.extent,48,4,4096),this.probeResolution=Math.round(oe(i.probeResolution,12,4,24)),this.cellSize=this.extent/this.resolution,this.spacing=this.cellSize*Math.max(1,Math.floor((this.resolution-4)/(this.probeResolution-1))),this.setOptions(i);const r=this.resolution**3,n=(e,i,r=!1)=>{if(!r&&i>t.limits.maxStorageBufferBindingSize)throw new Error(`SDFGI ${e} exceeds the adapter's storage buffer limit.`);const n=t.createBuffer({label:`sdfgi-${e}`,size:i,usage:(r?GPUBufferUsage.UNIFORM:GPUBufferUsage.STORAGE)|GPUBufferUsage.COPY_DST|("probes"===e||"surfaces"===e||"surface-statistics"===e?GPUBufferUsage.COPY_SRC:0)});return this.buffers.push(n),this.stats.gpuBytes+=i,n};this.params=n("params",96,!0),this.surfaces=n("surfaces",48*r),this.fieldBankBytes=16*(4+this.probeResolution**3*10),this.field=n("probes",2*this.fieldBankBytes),this.lightBuffer=n("lights",this.lightData.byteLength),this.surfaceConfig=n("surface-config",32),this.surfaceAccum=n("surface-accum",32*r),this.surfaceStatistics=n("surface-statistics",16);const a=[n("nearest-a",16*r),n("nearest-b",16*r)],s=n("radiance",32*r),o=(e,i,r)=>new _(t,{label:`sdfgi-${e}`,code:i,bindGroupLayoutEntries:r.map((e,t)=>((e,t)=>({binding:e,visibility:GPUShaderStage.COMPUTE,buffer:{type:t}}))(t,e))}),l=(e,i)=>e.createBindGroup(t,i.map((e,t)=>({binding:t,resource:{buffer:e}})));this.snapshot=o("probe-snapshot","\n@group(0) @binding(0) var<storage, read_write> field: array<vec4<f32>>;\n@compute @workgroup_size(64)\nfn main(@builtin(global_invocation_id) id: vec3<u32>) {\n let bankSize = arrayLength(&field) / 2u;\n let index = id.x + 4u;\n if (index < bankSize) { field[bankSize + index] = field[index]; }\n}\n",["storage"]),this.snapshotBinding=l(this.snapshot,[this.field]),this.resolveSurface=o("resolve-surface","\n@group(0) @binding(0) var<storage, read> config: array<vec4<f32>>;\n@group(0) @binding(1) var<storage, read> accum: array<u32>;\n@group(0) @binding(2) var<storage, read_write> surfaces: array<vec4<f32>>;\n@group(0) @binding(3) var<storage, read_write> statistics: array<atomic<u32>>;\n@compute @workgroup_size(64)\nfn main(@builtin(global_invocation_id) id: vec3<u32>) {\n let n = u32(config[1].x);\n if (id.x >= n * n * n) { return; }\n let base = id.x * 8u;\n let count = accum[base];\n if (count == 0u) {\n surfaces[id.x * 3u] = vec4<f32>(0.0);\n surfaces[id.x * 3u + 1u] = vec4<f32>(0.0);\n surfaces[id.x * 3u + 2u] = vec4<f32>(0.0);\n return;\n }\n let inverseCount = 1.0 / f32(count);\n let color = vec3<f32>(f32(accum[base + 1u]), f32(accum[base + 2u]), f32(accum[base + 3u])) * (inverseCount / 4096.0);\n let emission = vec3<f32>(f32(accum[base + 4u]), f32(accum[base + 5u]), f32(accum[base + 6u])) * (inverseCount / 1024.0);\n let packed = accum[base + 7u];\n let packedNormal = unpack4x8snorm(packed & 0x00ffffffu);\n let metadata = packed >> 24u;\n let doubleSided = f32(metadata >> 7u);\n let planeOffset = (f32(metadata & 127u) / 127.0 - 0.5) * 3.0 * config[0].w;\n let normal = packedNormal.xyz * inverseSqrt(max(dot(packedNormal.xyz, packedNormal.xyz), 0.0001));\n surfaces[id.x * 3u] = vec4<f32>(color, 1.0);\n surfaces[id.x * 3u + 1u] = vec4<f32>(normal, doubleSided);\n surfaces[id.x * 3u + 2u] = vec4<f32>(emission, planeOffset);\n atomicAdd(&statistics[0], 1u);\n}\n",["read-only-storage","read-only-storage","storage","storage"]),this.resolveSurfaceBinding=l(this.resolveSurface,[this.surfaceConfig,this.surfaceAccum,this.surfaces,this.surfaceStatistics]),this.seed=o("seed",ie,["uniform","read-only-storage","storage"]),this.seedBinding=l(this.seed,[this.params,this.surfaces,a[0]]);const c=o("jump-flood",re,["uniform","uniform","read-only-storage","storage"]);let u=0;for(let e=this.resolution/2;e>=.5;e/=2){const i=n(`jump-${this.jumps.length}`,16,!0);t.queue.writeBuffer(i,0,new Uint32Array([Math.max(1,e),0,0,0])),this.jumps.push({kernel:c,binding:l(c,[this.params,i,a[u],a[1-u]])}),u=1-u}if(this.inject=o("light-injection",ae,["uniform","read-only-storage","read-only-storage","read-only-storage","storage"]),this.injectBinding=l(this.inject,[this.params,this.surfaces,a[u],this.lightBuffer,s]),this.probes=o("probe-update",se,["uniform","read-only-storage","read-only-storage","read-only-storage","storage"]),this.probeBinding=l(this.probes,[this.params,this.surfaces,a[u],s,this.field]),i.cascades){const r=i.cascades,n=Math.round(oe(r.count,2,2,3)),a=oe(r.extentScale,2,1.5,8),s=Math.round(oe(r.updateInterval,4,1,60)),o=Math.round(oe(r.raysPerProbe,32,16,256)),l=oe(r.updateFraction,.125,.01,1);this.distantVolumes=[];try{for(let c=1;c<n;c++){const n=this.extent*a**c;if(n>4096)throw new Error("SDFGI cascade extent exceeds 4096.");const u=new e(t,{...i,cascades:!1,extent:n,resolution:r.resolution??32,probeResolution:r.probeResolution??8,raysPerProbe:Math.min(this.rays,o),updateFraction:Math.min(this.fraction,l)});this.distantVolumes.push({volume:u,interval:s*2**(c-1),rays:o,fraction:l,scheduled:!1,settingsDirty:!1}),this.stats.gpuBytes+=u.stats.gpuBytes}}catch(e){throw this.dispose(),e}this.stats.cascadeCount=n}}device;stats={cascadeCount:1,ready:!1,building:!1,triangles:0,occupiedCells:0,geometryCpuMs:0,geometryBuildMs:0,gpuBytes:0,updatedProbes:0};resolution;extent;probeResolution;cellSize;spacing;enabled=!0;intensity=1;rays=64;fraction=.25;history=.85;steps=64;sky=[0,0,0];buffers=[];uniformData=new ArrayBuffer(96);floats=new Float32Array(this.uniformData);integers=new Uint32Array(this.uniformData);header=new Float32Array(16);lightData=new Float32Array(256);field;fieldBankBytes;snapshot;snapshotBinding;populatedProbes=0;blend=1;previousValid=!1;lastUpdateSeconds=0;params;surfaces;seed;seedBinding;jumps=[];inject;injectBinding;probes;probeBinding;lightBuffer;surfaceConfig;surfaceAccum;surfaceStatistics;surfaceConfigData=new Float32Array(8);resolveSurface;resolveSurfaceBinding;configuredSurfaces=new WeakSet;surfaceCapture=null;captureAxis=0;pendingTriangleCount=0;pendingCounts=0;configured=new WeakSet;materialCapabilities=new WeakMap;watched=new Set;lights=new Set;staticDrawRoots=new Map;cascadeDirectionalLights=[];scene=null;grid=null;pending=null;dirty=!0;upload=!1;frame=0;probeOffset=0;disposed=!1;cameraPosition=new Q;sourcePosition=new Q;targetPosition=new Q;direction=new Q;buildMs=0;lightCount=0;distantVolumes=null;cascadeFrame=0;setOptions(e){const t=this.enabled,i=this.intensity;if(this.enabled=e.enabled??this.enabled,t&&!this.enabled&&this.buffers.length>0&&(this.header[6]=this.header[8]=0,this.device.queue.writeBuffer(this.field,0,this.header),this.stats.updatedProbes=0,this.stats.geometryCpuMs=0),this.intensity=oe(e.intensity,this.intensity,0,10),this.rays=Math.round(oe(e.raysPerProbe,this.rays,16,256)),this.fraction=oe(e.updateFraction,this.fraction,.01,1),this.history=oe(e.historyWeight,this.history,0,.99),this.steps=Math.round(oe(e.maxSteps,this.steps,16,256)),e.skyColor)for(let t=0;t<3;t++)this.sky[t]=oe(e.skyColor[t],0,0,100);if(this.distantVolumes)for(const e of this.distantVolumes)e.volume.setOptions({enabled:this.enabled,intensity:this.intensity,historyWeight:this.history,maxSteps:this.steps,skyColor:this.sky,raysPerProbe:Math.min(this.rays,e.rays),updateFraction:Math.min(this.fraction,e.fraction)}),!e.volume.grid||t===this.enabled&&i===this.intensity||(e.settingsDirty=!0)}invalidate(){if(this.dirty=!0,this.distantVolumes)for(const e of this.distantVolumes)e.volume.invalidate()}get surfaceResolution(){return 2*this.resolution}setSurfaceCapture(e){this.surfaceCapture?.dispose(),this.surfaceCapture=e,this.invalidate()}setSurfaceCaptureFactory(e){if(this.setSurfaceCapture(e(this)),this.distantVolumes)for(const t of this.distantVolumes)t.volume.setSurfaceCapture(e(t.volume))}configureSurfaceMaterial(e){if(!this.configuredSurfaces.has(e)){if(!e.fragmentShader.includes("sdfgiWriteSurface("))throw new Error("SDFGI capture requires an attribute-only material graph.");this.configuredSurfaces.add(e),e.fragmentShader.includes("fn sdfgiWriteSurface(")||(e.fragmentShader+="\nfn sdfgiWriteSurface(position: vec3<f32>, normal: vec3<f32>, diffuse: vec3<f32>, emission: vec3<f32>, doubleSided: bool) {\n let originCell = sdfgiSurfaceConfig[0];\n let n = u32(sdfgiSurfaceConfig[1].x);\n let color = vec3<u32>(round(clamp(diffuse, vec3<f32>(0.0), vec3<f32>(1.0)) * 4096.0));\n let emissive = vec3<u32>(round(clamp(emission, vec3<f32>(0.0), vec3<f32>(64.0)) * 1024.0));\n let surfaceNormal = normalize(normal);\n let packedNormal = pack4x8snorm(vec4<f32>(surfaceNormal, 0.0)) & 0x00ffffffu;\n // Half-voxel coverage in each projection and a small normal extrusion keep\n // subpixel edges connected without relying on conservative-raster hardware.\n for (var offset = -1; offset <= 1; offset++) {\n let local = (position - originCell.xyz) / originCell.w + surfaceNormal * (f32(offset) * 0.5);\n if (any(local < vec3<f32>(0.0)) || any(local >= vec3<f32>(f32(n)))) { continue; }\n let cell = vec3<u32>(local);\n let center = originCell.xyz + (vec3<f32>(cell) + vec3<f32>(0.5)) * originCell.w;\n // The fourth normal byte carries a two-sided flag and a seven-bit plane\n // offset over +/-1.5 cells, including the conservative extrusion shell.\n let planeOffset = dot(position - center, surfaceNormal) / originCell.w;\n let planeBits = u32(round(clamp(planeOffset / 3.0 + 0.5, 0.0, 1.0) * 127.0));\n let metadata = planeBits | select(0u, 128u, doubleSided);\n let base = (cell.x + n * (cell.y + n * cell.z)) * 8u;\n atomicAdd(&sdfgiSurfaceAccum[base], 1u);\n atomicAdd(&sdfgiSurfaceAccum[base + 1u], color.x);\n atomicAdd(&sdfgiSurfaceAccum[base + 2u], color.y);\n atomicAdd(&sdfgiSurfaceAccum[base + 3u], color.z);\n atomicAdd(&sdfgiSurfaceAccum[base + 4u], emissive.x);\n atomicAdd(&sdfgiSurfaceAccum[base + 5u], emissive.y);\n atomicAdd(&sdfgiSurfaceAccum[base + 6u], emissive.z);\n // The normal and its plane offset stay atomic and refer to the same\n // captured surface, including where several surfaces share a voxel.\n atomicStore(&sdfgiSurfaceAccum[base + 7u], packedNormal | (metadata << 24u));\n }\n}\n"),e.depthTest=e.depthWrite=e.transparent=e.wireframe=!1,e.side=K,e.blending=Z,e.setStorageBuffer("sdfgiSurfaceAccum",{buffer:this.surfaceAccum,type:"array<atomic<u32>>",visibility:"fragment",access:"read_write"}),e.setStorageBuffer("sdfgiSurfaceConfig",{buffer:this.surfaceConfig,type:"array<vec4<f32>>",visibility:"fragment"})}}registerStaticDrawRoot(e){this.staticDrawRoots.set(e,(this.staticDrawRoots.get(e)??0)+1),this.invalidate();let t=!1;return()=>{if(t)return;t=!0;const i=(this.staticDrawRoots.get(e)??1)-1;i>0?this.staticDrawRoots.set(e,i):this.staticDrawRoots.delete(e),this.invalidate()}}setCascadedDirectionalLights(e){if(this.cascadeDirectionalLights=e,this.distantVolumes)for(const t of this.distantVolumes)t.volume.setCascadedDirectionalLights(e)}configureMaterial(e){let t=this.materialCapabilities.get(e);if(!t||t.vertex!==e.vertexShader||t.fragment!==e.fragmentShader){const i=e.vertexShader.includes("rendererDiffuseGIAt(");t={vertex:e.vertexShader,fragment:e.fragmentShader,visibility:i?"vertex-fragment":e.fragmentShader.includes("rendererIndirectDiffuseAt(")||e.fragmentShader.includes("rendererDiffuseGIAt(")?"fragment":null},this.materialCapabilities.set(e,t),this.configured.delete(e)}if(!1===e.userData.receiveGI)return void(!0===e.defines.USE_SDFGI&&e.setDefine("USE_SDFGI",!1));if(this.configured.has(e))return void(!0!==e.defines.USE_SDFGI&&e.setDefine("USE_SDFGI",!0));const i=t.visibility;if(null!==i){if(this.configured.add(e),e.setStorageBuffer("sdfgiField",{buffer:this.field,type:"array<vec4<f32>>",visibility:i}),this.distantVolumes){e.setDefine("SDFGI_CASCADE_COUNT",this.stats.cascadeCount);for(let t=0;t<this.distantVolumes.length;t++)e.setStorageBuffer(`sdfgiField${t+1}`,{buffer:this.distantVolumes[t].volume.field,type:"array<vec4<f32>>",visibility:i})}e.setDefine("USE_SDFGI",!0)}else!0===e.defines.USE_SDFGI&&e.setDefine("USE_SDFGI",!1)}added=e=>{this.watch(e.child),this.hasStaticGeometry(e.child)&&this.invalidate()};removed=e=>{const t=this.hasStaticGeometry(e.child);e.child.traverse(e=>{e.removeEventListener("childadded",this.added),e.removeEventListener("childremoved",this.removed),this.watched.delete(e),e instanceof Y&&this.lights.delete(e)}),t&&this.invalidate()};hasStaticGeometry(e){let t=!1;return e.traverse(e=>{if(!t&&e.isMesh&&!e.isSkinnedMesh){for(let t=e;t;t=t.parent)if(!1===t.userData.sdfgi||!0===t.userData.isSky)return;t=!0}}),t}watch(e){e.traverse(e=>{this.watched.has(e)||(this.watched.add(e),e.addEventListener("childadded",this.added),e.addEventListener("childremoved",this.removed),(e instanceof q||e instanceof X||e instanceof J)&&this.lights.add(e))})}unwatch(){for(const e of this.watched)e.removeEventListener("childadded",this.added),e.removeEventListener("childremoved",this.removed);this.watched.clear(),this.lights.clear()}prepare(e,t){if(this.disposed||!this.enabled)return;if(this.stats.geometryCpuMs=0,this.stats.updatedProbes=0,this.scene!==e&&(this.unwatch(),this.scene=e,this.watch(e),this.grid=null,this.pending=null,this.dirty=!0,this.stats.ready=!1,this.blend=1,this.previousValid=!1),!this.enabled||!this.surfaceCapture)return;t.getWorldPosition(this.cameraPosition);const i=this.pending??this.grid;if(i&&this.blend>=1){const e=i.origin;(Math.abs(this.cameraPosition.x-e.x-this.extent/2)>.25*this.extent||Math.abs(this.cameraPosition.y-e.y-this.extent/2)>.25*this.extent||Math.abs(this.cameraPosition.z-e.z-this.extent/2)>.25*this.extent)&&(this.dirty=!0)}const r=performance.now();if(this.dirty&&(!this.stats.ready||this.blend>=1)){this.dirty=!1;const e=this.spacing,t=this.cameraPosition.clone().addScalar(-this.extent/2);t.set(Math.floor(t.x/e)*e,Math.floor(t.y/e)*e,Math.floor(t.z/e)*e),this.pending={origin:t,resolution:this.resolution,extent:this.extent},le(this.surfaceConfigData,0,t.x,t.y,t.z,this.cellSize),le(this.surfaceConfigData,4,this.resolution,0,0,0),this.device.queue.writeBuffer(this.surfaceConfig,0,this.surfaceConfigData);const i=this.device.createCommandEncoder({label:"sdfgi-clear-surfaces"});i.clearBuffer(this.surfaceAccum),this.device.queue.submit([i.finish()]),this.captureAxis=0,this.pendingTriangleCount=0,this.buildMs=0}if(this.pending&&(this.pendingTriangleCount=Math.max(this.pendingTriangleCount,this.surfaceCapture.capture(e,this.pending,this.captureAxis++)),this.stats.geometryCpuMs=performance.now()-r,this.buildMs+=this.stats.geometryCpuMs,3===this.captureAxis&&(this.grid=this.pending,this.pending=null,this.upload=!0,this.stats.triangles=this.pendingTriangleCount,this.stats.geometryBuildMs=this.buildMs)),this.stats.building=this.dirty||null!=this.pending||this.pendingCounts>0,this.updateLights(),this.distantVolumes){this.cascadeFrame++;for(const i of this.distantVolumes){const r=i.volume;i.scheduled=i.settingsDirty||null!=r.scene&&r.scene!==e||null!=r.pending||r.upload||r.blend<1||this.cascadeFrame%i.interval===0,i.scheduled&&(r.prepare(e,t),this.stats.geometryCpuMs+=r.stats.geometryCpuMs),this.stats.building||=r.stats.building}}}updateLights(){let e=0;for(let t=0;t<2;t++)for(const i of 0===t?this.cascadeDirectionalLights:this.lights){if(0===t?i!==this.cascadeDirectionalLights[0]:this.cascadeDirectionalLights.includes(i))continue;let r=!0;for(let e=i;e;e=e.parent)if(!e.visible){r=!1;break}if(!r||i.intensity<=0||!1===i.userData.sdfgi)continue;if(16===e)break;const n=16*e++;i.getWorldPosition(this.sourcePosition);let a=0,s=0,o=0,l=-1,c=-1;i instanceof q||i instanceof J?(i.target.getWorldPosition(this.targetPosition),this.direction.subVectors(this.targetPosition,this.sourcePosition).normalize(),i instanceof q?this.direction.negate():(a=2,l=Math.cos(i.angle),c=Math.cos(i.angle*(1-i.penumbra)))):(a=1,this.direction.set(0,0,0)),(i instanceof X||i instanceof J)&&(s=i.distance,o=i.decay),le(this.lightData,n,this.sourcePosition.x,this.sourcePosition.y,this.sourcePosition.z,a),le(this.lightData,n+4,i.color.r*i.intensity,i.color.g*i.intensity,i.color.b*i.intensity,0),le(this.lightData,n+8,this.direction.x,this.direction.y,this.direction.z,s),le(this.lightData,n+12,l,c,o,0)}this.lightCount=e}addPasses(e){return!(!this.enabled||this.disposed)&&(e.addPass({name:"SDFGIUpdate",execute:e=>this.encode(e.encoder)}),!0)}encode(e,t=performance.now()/1e3){if(this.enabled&&!this.disposed&&(this.encodeVolume(e,t),this.distantVolumes))for(const i of this.distantVolumes)(i.scheduled||i.settingsDirty)&&(i.volume.encodeVolume(e,t),i.settingsDirty=!1,this.stats.updatedProbes+=i.volume.stats.updatedProbes)}encodeVolume(e,t){if(this.stats.updatedProbes=0,this.disposed)return;const i=this.grid,r=this.probeResolution**3,n=Math.ceil(r*this.fraction);if(this.upload&&this.enabled&&i)this.previousValid=this.stats.ready,this.previousValid&&(this.device.queue.writeBuffer(this.field,this.fieldBankBytes,this.header),this.dispatch(e,pe,this.snapshot,this.snapshotBinding,Math.ceil(10*r/64))),this.populatedProbes=0,this.probeOffset=0,this.blend=0;else if(this.enabled&&this.populatedProbes>=r){const e=Math.max(0,t-this.lastUpdateSeconds);this.blend=Math.min(1,this.blend+e/.4)}if(this.lastUpdateSeconds=t,this.header[0]=i?.origin.x??0,this.header[1]=i?.origin.y??0,this.header[2]=i?.origin.z??0,this.header[3]=this.cellSize,this.header[4]=this.spacing,this.header[5]=this.probeResolution,this.header[6]=this.enabled?this.intensity:0,this.header[7]=1.25*this.cellSize,this.header[8]=i&&this.enabled?1:0,this.header[9]=this.blend,this.header[10]=this.previousValid?1:0,this.header[12]=this.fieldBankBytes/16,this.device.queue.writeBuffer(this.field,0,this.header),!this.enabled||!i)return;le(this.floats,0,i.origin.x,i.origin.y,i.origin.z,this.cellSize),le(this.integers,4,this.resolution,this.probeResolution,this.rays,this.frame++),le(this.floats,8,this.spacing,this.history,this.cellSize,1.732051*this.extent),le(this.floats,12,this.sky[0],this.sky[1],this.sky[2],0),le(this.integers,16,this.probeOffset,n,this.upload?1:0,this.steps),le(this.integers,20,this.lightCount,0,0,0),this.device.queue.writeBuffer(this.params,0,this.uniformData),this.device.queue.writeBuffer(this.lightBuffer,0,this.lightData);const a=Math.ceil(this.resolution**3/64);if(this.upload){e.clearBuffer(this.field,64,this.fieldBankBytes-64),e.clearBuffer(this.surfaceStatistics),this.dispatch(e,{label:"SDFGIResolveSurface"},this.resolveSurface,this.resolveSurfaceBinding,a),this.readSurfaceCount(e,i),this.dispatch(e,ce,this.seed,this.seedBinding,a);for(const t of this.jumps)this.dispatch(e,ue,t.kernel,t.binding,a)}this.dispatch(e,de,this.inject,this.injectBinding,a),this.dispatch(e,he,this.probes,this.probeBinding,Math.ceil(n/32)),this.probeOffset=(this.probeOffset+n)%r,this.populatedProbes=Math.min(r,this.populatedProbes+n),this.upload=!1,this.stats.ready=!0,this.stats.updatedProbes=n}readSurfaceCount(e,t){const i=this.device.createBuffer({label:"sdfgi-cell-count",size:16,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});e.copyBufferToBuffer(this.surfaceStatistics,0,i,0,16),this.pendingCounts++,Promise.resolve().then(async()=>{try{await i.mapAsync(GPUMapMode.READ),this.disposed||this.grid!==t||(this.stats.occupiedCells=new Uint32Array(i.getMappedRange())[0]),i.unmap()}catch{}finally{i.destroy(),this.pendingCounts--}})}dispatch(e,t,i,r,n){const a=e.beginComputePass(t);a.setPipeline(i.pipeline),a.setBindGroup(0,r),a.dispatchWorkgroups(n),a.end()}dispose(){if(this.disposed=!0,this.unwatch(),this.surfaceCapture?.dispose(),this.distantVolumes)for(const e of this.distantVolumes)e.volume.dispose();this.staticDrawRoots.clear();for(const e of this.buffers)e.destroy()}};import{OrthographicCamera as me,Vector3 as ge}from"three";var ve=class{camera=new me;center=new ge;target;options;variants;constructor(e,t,i,r=!1){this.variants=r?new Map:null,this.target=e.createSceneCapture(null,t.surfaceResolution,t.surfaceResolution),this.options={objectFilter:e=>{if(e?.isSkinnedMesh)return!1;for(let t=e;t;t=t.parent)if(!1===t.userData.sdfgi||!0===t.userData.isSky)return!1;return!0},overrideMaterial:(e,r)=>{if(r||e.transparent||!1===e.userData.sdfgi)return null;let n=i(e);if(n&&this.variants){const e=n;let t=this.variants.get(e);t||(t=e.clone(),this.variants.set(e,t)),t.uniforms=e.uniforms,t.textures=e.textures,t.uniformValuesNeedsUpdate=!0,n=t}return n&&t.configureSurfaceMaterial(n),n},includeLocalLights:!1,postProcess:()=>{}}}capture(e,t,i){const{origin:r,extent:n}=t;this.center.copy(r).addScalar(n/2);const a=this.camera;return a.left=a.bottom=-n/2,a.right=a.top=n/2,a.near=.01,a.far=n+2,a.position.copy(this.center).setComponent(i,this.center.getComponent(i)+n/2+1),a.up.set(0,1===i?0:1,1===i?1:0),a.lookAt(this.center),a.updateProjectionMatrix(),this.target.capture(e,a,this.options),this.target.triangleCount}dispose(){if(this.target.dispose(),this.variants){for(const e of this.variants.values())e.dispose();this.variants.clear()}}};import{Color as xe,DirectionalLight as we,Matrix4 as be,Object3D as ye,PointLight as Se,Scene as Ce,SpotLight as Me,Vector3 as Pe}from"three";var Be=class extends ye{constructor(e){super(),this.volume=e}volume;isFogVolumeObject=!0},De={low:{froxelPixelSize:16,depthSlices:32,integrationSubsteps:1,shadowFilterTaps:1,temporalJitter:!0,temporal:{historyWeight:.88,depthRejection:.055,neighborhoodClamp:!0},blur:{scale:.25,radius:2,depthSigma:.06,spatialSigma:1.5,depthAwareUpsample:!1}},medium:{froxelPixelSize:12,depthSlices:40,integrationSubsteps:1,shadowFilterTaps:1,temporalJitter:!0,temporal:{historyWeight:.92,depthRejection:.045,neighborhoodClamp:!0},blur:{scale:.375,radius:2,depthSigma:.055,spatialSigma:1.75,depthAwareUpsample:!0}},high:{froxelPixelSize:8,depthSlices:64,integrationSubsteps:1,shadowFilterTaps:1,temporalJitter:!0,temporal:{historyWeight:.94,depthRejection:.04,neighborhoodClamp:!0},blur:{scale:.5,radius:3,depthSigma:.05,spatialSigma:2,depthAwareUpsample:!0}}},Ie=20,Te=16,Re=(new be).set(1,0,0,0,0,1,0,0,0,0,.5,.5,0,0,0,1),Ve=new Pe,Ge=new Pe,ze=new Pe,Le={label:"VolumetricFogFroxelPass"};function Ue(e,t,i,r,n,a){e[t]=i,e[t+1]=r,e[t+2]=n,e[t+3]=a}var ke=class{constructor(e=new Ce,t={}){this.scene=e,this.options=Ae(t),this.integratedVolume=`${this.options.targetPrefix}Integrated`,this.columnDepthBounds=`${this.options.targetPrefix}DepthBounds`,this.scatteringHistoryA=`${this.options.targetPrefix}ScatteringHistoryA`,this.scatteringHistoryB=`${this.options.targetPrefix}ScatteringHistoryB`,this.activeHistoryRead=this.scatteringHistoryB,this.activeHistoryWrite=this.scatteringHistoryA,this.volumeData=new Float32Array(this.options.maxVolumes*Ie);const i=this.options.maxDirectionalLights+this.options.maxPointLights+this.options.maxSpotLights;this.lightData=new Float32Array(i*Te),this.selectedPointIndices=new Int32Array(this.options.maxPointLights),this.selectedPointScores=new Float32Array(this.options.maxPointLights),this.selectedSpotIndices=new Int32Array(this.options.maxSpotLights),this.selectedSpotScores=new Float32Array(this.options.maxSpotLights)}scene;integratedVolume;columnDepthBounds;scatteringHistoryA;scatteringHistoryB;options;resources=new WeakMap;uniformStorage=new ArrayBuffer(256);uniforms=new Float32Array(this.uniformStorage);uniformIntegers=new Uint32Array(this.uniformStorage);volumeData;lightData;selectedPointIndices;selectedPointScores;selectedSpotIndices;selectedSpotScores;collectedVolumes=[];collectedDirectionals=[];collectedPoints=[];collectedSpots=[];volumeCount=0;directionalCount=0;pointCount=0;spotCount=0;collectionCamera=null;collectVolumeObject=e=>{const t=e;t.isFogVolumeObject&&t.volume&&!this.collectedVolumes.includes(t.volume)&&this.collectedVolumes.push(t.volume)};collectLightObject=e=>{const t=this.collectionCamera;e instanceof we&&e.layers.test(t.layers)&&!this.collectedDirectionals.includes(e)?this.collectedDirectionals.push(e):e instanceof Se&&e.layers.test(t.layers)?this.collectedPoints.push(e):e instanceof Me&&e.layers.test(t.layers)&&this.collectedSpots.push(e)};executeFroxelPass=e=>{this.executeFroxels(e)};projectionInverse=new be;viewProjectionInverse=new be;previousTemporalViewProjection=new be;previousFroxelViewProjection=new be;previousFroxelCameraPosition=new Pe;previousFroxelNear=.1;previousFroxelFar=1;previousFroxelWidth=0;previousFroxelHeight=0;froxelHistoryValid=!1;froxelHistoryWriteIndex=0;activeHistoryRead;activeHistoryWrite;explicitVolumes=[];volumeObjects;extractedLights;cascadeDirectionalLights=[];compositePass=null;blurPassCache=new Map;temporalPassCache=new Map;temporalWriteIndex=0;temporalHistoryValid=!1;activeLastFrame=!1;frameIndex=0;setScene(e){this.scene=e}get enabled(){return this.options.enabled}setOptions(e){const t=Ae({...this.options,...e,ambientColor:e.ambientColor??this.options.ambientColor,blur:void 0===e.blur?this.options.blur:e.blur,temporal:void 0===e.temporal?this.options.temporal:e.temporal,targetPrefix:this.options.targetPrefix,maxVolumes:this.options.maxVolumes,maxDirectionalLights:this.options.maxDirectionalLights,maxPointLights:this.options.maxPointLights,maxSpotLights:this.options.maxSpotLights});Object.assign(this.options,t),this.compositePass=null,this.blurPassCache.clear(),this.temporalPassCache.clear(),this.reset()}applyPreset(e){this.setOptions(De[e])}reset(){this.frameIndex=0,this.temporalWriteIndex=0,this.temporalHistoryValid=!1,this.froxelHistoryValid=!1,this.froxelHistoryWriteIndex=0,this.previousFroxelWidth=0,this.previousFroxelHeight=0,this.activeLastFrame=!1,this.previousTemporalViewProjection.identity()}setCascadedDirectionalLights(e){this.cascadeDirectionalLights=e}addPasses(e,t){if(this.explicitVolumes=t.volumes??[],this.volumeObjects=t.volumeObjects,this.extractedLights=t.lights,!this.options.enabled||0===this.explicitVolumes.length&&0===this.volumeObjects?.length)return this.activeLastFrame&&this.reset(),t.sceneColor;this.activeLastFrame=!0,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});for(const t of[this.scatteringHistoryA,this.scatteringHistoryB])e.createTextureTarget(t,{dimension:"3d",depthOrArrayLayers:this.options.depthSlices,scale:1/this.options.froxelPixelSize,format:"rgba16float",usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.STORAGE_BINDING});this.activeHistoryRead=0===this.froxelHistoryWriteIndex?this.scatteringHistoryB:this.scatteringHistoryA,this.activeHistoryWrite=0===this.froxelHistoryWriteIndex?this.scatteringHistoryA:this.scatteringHistoryB,e.addPass({name:"VolumetricFogFroxelPass",inputs:{sceneDepth:t.depth,scatteringHistory:this.activeHistoryRead},outputs:[this.integratedVolume,this.columnDepthBounds,this.activeHistoryWrite],execute:this.executeFroxelPass}),this.froxelHistoryWriteIndex=1-this.froxelHistoryWriteIndex;const i=e.createColorTarget(`${this.options.targetPrefix}Composite`,{format:"rgba16float"});return!1!==this.options.blur?this.addBlurredComposite(e,t,i):(this.compositePass&&this.compositePass.matches(t.sceneColor,t.depth,i)||(this.compositePass=new Fe(t.sceneColor,t.depth,this.integratedVolume,this.columnDepthBounds,i,this.options.maxDistance,this.options.fogDitherStrength)),this.compositePass.setFrameIndex(this.frameIndex),e.addFullscreenPass(this.compositePass),i)}addBlurredComposite(e,t,i){const r=this.options.blur;if(!1===r)return i;const n=e.createColorTarget(`${this.options.targetPrefix}Resolved`,{format:"rgba16float",scale:r.scale}),a=e.createColorTarget(`${this.options.targetPrefix}BlurTemporary`,{format:"rgba16float",scale:r.scale}),s=e.createColorTarget(`${this.options.targetPrefix}Blurred`,{format:"rgba16float",scale:r.scale}),o=`resolve:${t.depth}:${n}`;let l=this.blurPassCache.get(o);l||(l=new Oe(t.depth,this.integratedVolume,this.columnDepthBounds,n,this.options.maxDistance,this.options.fogDitherStrength),this.blurPassCache.set(o,l)),l.setFrameIndex(this.frameIndex),e.addFullscreenPass(l);const c=n;for(const[i,n,o]of[[c,a,[1,0]],[a,s,[0,1]]]){const a=`blur:${i}:${n}:${o[0]}:${r.radius}:${r.depthSigma}:${r.spatialSigma}`;let s=this.blurPassCache.get(a);s||(s=new je(i,t.depth,n,o,r),this.blurPassCache.set(a,s)),e.addFullscreenPass(s)}const u=`blurComposite:${t.sceneColor}:${t.depth}:${s}:${i}:${r.depthAwareUpsample}`;let d=this.blurPassCache.get(u);return d||(d=new $e(t.sceneColor,t.depth,s,this.integratedVolume,this.columnDepthBounds,i,r.depthAwareUpsample),this.blurPassCache.set(u,d)),e.addFullscreenPass(d),i}addTemporalPass(e,t,i,r){const n=this.options.temporal;if(!1===n)return i;const a=e.createColorTarget(`${this.options.targetPrefix}TemporalA`,{format:"rgba16float",scale:r}),s=e.createColorTarget(`${this.options.targetPrefix}TemporalB`,{format:"rgba16float",scale:r}),o=e.createColorTarget(`${this.options.targetPrefix}TemporalDepthA`,{format:"r16float",scale:r}),l=e.createColorTarget(`${this.options.targetPrefix}TemporalDepthB`,{format:"r16float",scale:r}),c=0===this.temporalWriteIndex?s:a,u=0===this.temporalWriteIndex?a:s,d=0===this.temporalWriteIndex?l:o,h=0===this.temporalWriteIndex?o:l,p=[i,t.depth,t.velocity??"camera",c,d,u,h].join(":");let f=this.temporalPassCache.get(p);return f||(f=new Ee(i,t.depth,t.velocity,c,d,u,h,n,this),this.temporalPassCache.set(p,f)),e.addFullscreenPass(f),this.temporalWriteIndex=1-this.temporalWriteIndex,u}consumeTemporalHistoryValid(){const e=this.temporalHistoryValid;return this.temporalHistoryValid=!0,e}updateTemporalUniforms(e,t,i,r,n){t.copy(Re).multiply(n.camera.projectionMatrix).multiply(n.camera.matrixWorldInverse),i.copy(t).invert();const a=this.consumeTemporalHistoryValid();e.set(i.elements,0),e.set((a?this.previousTemporalViewProjection:t).elements,16),Ue(e,32,r.historyWeight,r.depthRejection,r.neighborhoodClamp?1:0,a?1:0),this.previousTemporalViewProjection.copy(t)}dispose(){this.compositePass=null,this.blurPassCache.clear(),this.temporalPassCache.clear()}executeFroxels(e){const t=this.getResources(e.device);this.collectSceneData(e.camera);const i=Math.max(.01,e.camera.near),r=Math.min(e.camera.far,this.options.maxDistance);e.camera.getWorldPosition(Ge);let n=i+.01;for(let e=0;e<this.volumeCount;e++){const t=e*Ie,i=this.volumeData[t]-Ge.x,r=this.volumeData[t+1]-Ge.y,a=this.volumeData[t+2]-Ge.z;n=Math.max(n,Math.sqrt(i*i+r*r+a*a)+this.volumeData[t+3])}const a=Math.max(i+.01,Math.min(r,n));let s=a;for(let e=0;e<this.volumeCount;e++)s=Math.min(s,Math.max(this.volumeData[e*Ie+10],i));s=Math.min(s,a);const o=Math.max(1,Math.floor(e.width/this.options.froxelPixelSize)),l=Math.max(1,Math.floor(e.height/this.options.froxelPixelSize));o===this.previousFroxelWidth&&l===this.previousFroxelHeight||(this.froxelHistoryValid=!1),this.projectionInverse.copy(Re).multiply(e.camera.projectionMatrix).multiply(e.camera.matrixWorldInverse),this.viewProjectionInverse.copy(this.projectionInverse).invert(),this.uniforms.set(this.viewProjectionInverse.elements,0),this.uniforms[16]=e.camera.position.x,this.uniforms[17]=e.camera.position.y,this.uniforms[18]=e.camera.position.z,this.uniforms[19]=i,Ue(this.uniforms,20,o,l,this.options.depthSlices,a),this.uniformIntegers[24]=this.volumeCount,this.uniformIntegers[25]=this.directionalCount,this.uniformIntegers[26]=this.pointCount,this.uniformIntegers[27]=this.spotCount,Ue(this.uniforms,28,this.options.ambientColor.r,this.options.ambientColor.g,this.options.ambientColor.b,this.options.temporalJitter?this.frameIndex++%1024+1:0),e.camera.getWorldDirection(Ge),Ue(this.uniforms,32,Ge.x,Ge.y,Ge.z,Math.max(e.camera.far-i,1e-4)),Ue(this.uniforms,36,this.options.scatteringIntensity,this.options.spatialJitter?1:0,0,0),this.uniforms.set((this.froxelHistoryValid?this.previousFroxelViewProjection:this.projectionInverse).elements,40),Ue(this.uniforms,56,this.previousFroxelCameraPosition.x,this.previousFroxelCameraPosition.y,this.previousFroxelCameraPosition.z,this.froxelHistoryValid&&!1!==this.options.temporal?1:0),Ue(this.uniforms,60,this.previousFroxelNear,this.previousFroxelFar,!1===this.options.temporal?0:this.options.temporal.historyWeight,0),e.device.queue.writeBuffer(t.uniformBuffer,0,this.uniforms),this.volumeCount>0&&e.device.queue.writeBuffer(t.volumeBuffer,0,this.volumeData.buffer,this.volumeData.byteOffset,this.volumeCount*Ie*4);const c=this.directionalCount+this.pointCount+this.spotCount;c>0&&e.device.queue.writeBuffer(t.lightBuffer,0,this.lightData.buffer,this.lightData.byteOffset,c*Te*4);const u=e.getSceneLightingResources(),d=e.getTextureView(this.integratedVolume),h=e.getTextureView(this.columnDepthBounds),p=e.getTextureView(this.activeHistoryRead),f=e.getTextureView(this.activeHistoryWrite),m=e.depthView,g=t.bindGroupResources;t.bindGroup&&g&&g.integratedVolumeView===d&&g.historyReadView===p&&g.historyWriteView===f&&g.lightBuffer===u.lightBuffer&&g.comparisonSampler===e.comparisonSampler&&g.directionalShadowView===u.directionalShadowView&&g.pointShadowView===u.pointShadowView&&g.spotShadowView===u.spotShadowView&&g.spotLightMapView===u.spotLightMapView&&g.depthView===m&&g.columnDepthBoundsView===h||(t.bindGroup=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:d},{binding:4,resource:{buffer:u.lightBuffer}},{binding:5,resource:e.comparisonSampler},{binding:6,resource:u.directionalShadowView},{binding:7,resource:u.pointShadowView},{binding:8,resource:u.spotShadowView},{binding:9,resource:m},{binding:10,resource:h},{binding:11,resource:e.linearClampSampler},{binding:12,resource:p},{binding:13,resource:f},{binding:14,resource:u.spotLightMapView}]}),t.bindGroupResources={integratedVolumeView:d,historyReadView:p,historyWriteView:f,lightBuffer:u.lightBuffer,comparisonSampler:e.comparisonSampler,directionalShadowView:u.directionalShadowView,pointShadowView:u.pointShadowView,spotShadowView:u.spotShadowView,spotLightMapView:u.spotLightMapView,depthView:m,columnDepthBoundsView:h});const v=e.encoder.beginComputePass(Le);v.setPipeline(t.pipeline),v.setBindGroup(0,t.bindGroup),v.dispatchWorkgroups(Math.ceil(o/8),Math.ceil(l/8)),v.end(),this.previousFroxelViewProjection.copy(this.projectionInverse),this.previousFroxelCameraPosition.set(this.uniforms[16],this.uniforms[17],this.uniforms[18]),this.previousFroxelNear=s,this.previousFroxelFar=a,this.previousFroxelWidth=o,this.previousFroxelHeight=l,this.froxelHistoryValid=!0}collectSceneData(e){const t=this.collectedVolumes,i=this.collectedDirectionals,r=this.collectedPoints,n=this.collectedSpots;t.length=0,i.length=0,r.length=0,n.length=0;for(const e of this.explicitVolumes)t.push(e);for(const t of this.cascadeDirectionalLights)t.visible&&t.layers.test(e.layers)&&!i.includes(t)&&i.push(t);if(void 0===this.volumeObjects)this.scene.traverseVisible(this.collectVolumeObject);else for(const e of this.volumeObjects)this.collectVolumeObject(e);void 0===this.extractedLights&&(this.collectionCamera=e,this.scene.traverseVisible(this.collectLightObject),this.collectionCamera=null);const a=Math.min(t.length,this.options.maxVolumes);this.volumeData.fill(0,0,a*Ie);for(let e=0;e<a;e++)this.writeVolume(e,t[e]);const s=Math.min(this.extractedLights?.directionals.length??i.length,this.options.maxDirectionalLights),o=this.extractedLights?.points,l=this.extractedLights?.spots,c=this.selectClosestLights(o??r,e,this.selectedPointIndices,this.selectedPointScores),u=this.selectClosestLights(l??n,e,this.selectedSpotIndices,this.selectedSpotScores);this.lightData.fill(0,0,(s+c+u)*Te);let d=0;for(let e=0;e<s;e++){const t=this.extractedLights?.directionals[e];t?this.writeExtractedDirectional(d++,t):this.writeDirectional(d++,i[e])}for(let e=0;e<c;e++){const t=this.selectedPointIndices[e];o?this.writeExtractedPoint(d++,o[t],t):this.writePoint(d++,r[t])}for(let e=0;e<u;e++){const t=this.selectedSpotIndices[e];l?this.writeExtractedSpot(d++,l[t],t):this.writeSpot(d++,n[t])}this.volumeCount=a,this.directionalCount=s,this.pointCount=c,this.spotCount=u}selectClosestLights(e,t,i,r){const n=i.length;if(0===n)return 0;t.getWorldPosition(Ge);let a=0;for(let t=0;t<e.length;t+=1){const s=e[t],o=Number(s instanceof ye?s.userData?.volumetricIntensity??0:s.volumetricIntensity);if(!Number.isFinite(o)||o<=0)continue;const l=s instanceof ye?s.getWorldPosition(Ve):s.position,c=Ge.distanceToSquared(l);if(a===n&&c>=r[n-1])continue;let u=Math.min(a,n-1);for(;u>0&&c<r[u-1];)u<n&&(r[u]=r[u-1],i[u]=i[u-1]),u-=1;r[u]=c,i[u]=t,a<n&&(a+=1)}return a}writeVolume(e,t){const i=e*Ie;t.object.getWorldPosition(Ve),t.object.getWorldScale(ze),Ue(this.volumeData,i,Ve.x,Ve.y,Ve.z,5*Math.max(ze.x,ze.y,ze.z)),Ue(this.volumeData,i+4,t.albedo.r,t.albedo.g,t.albedo.b,Math.max(0,t.baseDensity)),Ue(this.volumeData,i+8,t.heightFalloff,t.heightOffset,t.startDistance??3,-Math.max(-.99,Math.min(.99,t.scatteringDistribution))),Ue(this.volumeData,i+12,t.emissive.r,t.emissive.g,t.emissive.b,t.ambientIntensity??1),this.volumeData[i+16]="lightShaft"===t.scatteringMode?1:0}writeDirectional(e,t){const i=e*Te;t.getWorldPosition(Ve),t.target.getWorldPosition(Ge),Ge.sub(Ve).normalize(),Ue(this.lightData,i,Ge.x,Ge.y,Ge.z,0);const r=t.intensity*(t.userData?.volumetricIntensity??1);Ue(this.lightData,i+4,t.color.r*r,t.color.g*r,t.color.b*r,0)}writeExtractedDirectional(e,t){const i=e*Te;Ue(this.lightData,i,t.direction.x,t.direction.y,t.direction.z,0);const r=t.intensity*t.volumetricIntensity;Ue(this.lightData,i+4,t.color.x*r,t.color.y*r,t.color.z*r,0)}writePoint(e,t,i=e){const r=e*Te;t.getWorldPosition(Ve),Ue(this.lightData,r,Ve.x,Ve.y,Ve.z,Math.max(.001,t.distance||this.options.maxDistance));const n=t.intensity*(t.userData?.volumetricIntensity??1);Ue(this.lightData,r+4,t.color.r*n,t.color.g*n,t.color.b*n,Math.max(0,t.decay)),this.lightData[r+13]=i}writeExtractedPoint(e,t,i){const r=e*Te;Ue(this.lightData,r,t.position.x,t.position.y,t.position.z,Math.max(.001,t.range||this.options.maxDistance));const n=t.intensity*t.volumetricIntensity;Ue(this.lightData,r+4,t.color.x*n,t.color.y*n,t.color.z*n,Math.max(0,t.decay)),this.lightData[r+13]=i,this.lightData[r+14]=1}writeSpot(e,t,i=e){const r=e*Te;t.getWorldPosition(Ve),t.target.getWorldPosition(Ge),Ge.sub(Ve).normalize(),Ue(this.lightData,r,Ve.x,Ve.y,Ve.z,Math.max(.001,t.distance||this.options.maxDistance));const n=t.intensity*(t.userData?.volumetricIntensity??1);Ue(this.lightData,r+4,t.color.r*n,t.color.g*n,t.color.b*n,Math.max(0,t.decay)),Ue(this.lightData,r+8,Ge.x,Ge.y,Ge.z,Math.cos(t.angle)),this.lightData[r+12]=Math.cos(t.angle*(1-t.penumbra)),this.lightData[r+13]=i}writeExtractedSpot(e,t,i){const r=e*Te;Ue(this.lightData,r,t.position.x,t.position.y,t.position.z,Math.max(.001,t.range||this.options.maxDistance));const n=t.intensity*t.volumetricIntensity;Ue(this.lightData,r+4,t.color.x*n,t.color.y*n,t.color.z*n,Math.max(0,t.decay)),Ue(this.lightData,r+8,t.direction.x,t.direction.y,t.direction.z,Math.cos(t.angle)),this.lightData[r+12]=Math.cos(t.angle*(1-t.penumbra)),this.lightData[r+13]=i,this.lightData[r+14]=1}getResources(e){let t=this.resources.get(e);t||(t=new Map,this.resources.set(e,t));const i=[this.options.shadowFilterTaps,this.options.integrationSubsteps,this.options.maxVolumes,this.options.maxDirectionalLights,this.options.maxPointLights,this.options.maxSpotLights].join(":"),r=t.get(i);if(r)return r;const n=e.createBuffer({size:256,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),a=e.createBuffer({size:this.volumeData.byteLength,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST}),s=e.createBuffer({size:this.lightData.byteLength,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST}),o=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"}},{binding:11,visibility:GPUShaderStage.COMPUTE,sampler:{type:"filtering"}},{binding:12,visibility:GPUShaderStage.COMPUTE,texture:{sampleType:"float",viewDimension:"3d"}},{binding:13,visibility:GPUShaderStage.COMPUTE,storageTexture:{access:"write-only",format:"rgba16float",viewDimension:"3d"}},{binding:14,visibility:GPUShaderStage.COMPUTE,texture:{sampleType:"float",viewDimension:"2d"}}]}),l=e.createShaderModule({label:"volumetric-fog-compute",code:_e.replace("__SHADOW_TAPS__",String(this.options.shadowFilterTaps)).replace("__INTEGRATION_SUBSTEPS__",String(this.options.integrationSubsteps))}),c={uniformBuffer:n,volumeBuffer:a,lightBuffer:s,layout:o,pipeline:e.createComputePipeline({layout:e.createPipelineLayout({bindGroupLayouts:[o]}),compute:{module:l,entryPoint:"main"}})};return t.set(i,c),c}};function Ae(e){return{enabled:e.enabled??!0,froxelPixelSize:Math.max(2,Math.floor(e.froxelPixelSize??8)),depthSlices:Math.max(8,Math.floor(e.depthSlices??64)),integrationSubsteps:e.integrationSubsteps??1,maxDistance:Math.max(1,e.maxDistance??256),targetPrefix:e.targetPrefix??"volumetricFog",maxVolumes:Math.max(1,Math.floor(e.maxVolumes??32)),maxDirectionalLights:Math.min(4,Math.max(1,Math.floor(e.maxDirectionalLights??4))),maxPointLights:Math.min(4,Math.max(0,Math.floor(e.maxPointLights??4))),maxSpotLights:Math.min(4,Math.max(0,Math.floor(e.maxSpotLights??4))),ambientColor:e.ambientColor?.clone()??new xe(.03,.035,.045),shadowFilterTaps:e.shadowFilterTaps??1,temporalJitter:e.temporalJitter??!0,temporal:!1!==e.temporal&&{historyWeight:Math.min(.98,Math.max(0,e.temporal?.historyWeight??.92)),depthRejection:Math.max(1e-4,e.temporal?.depthRejection??.04),neighborhoodClamp:e.temporal?.neighborhoodClamp??!0},spatialJitter:e.spatialJitter??!0,fogDitherStrength:Math.max(0,e.fogDitherStrength??.75),scatteringIntensity:Math.max(0,e.scatteringIntensity??1),blur:!1!==e.blur&&{scale:Math.max(.125,Math.min(1,e.blur?.scale??.5)),radius:Math.max(1,Math.min(12,Math.floor(e.blur?.radius??3))),depthSigma:Math.max(1e-4,e.blur?.depthSigma??.05),spatialSigma:Math.max(.1,e.blur?.spatialSigma??2),depthAwareUpsample:e.blur?.depthAwareUpsample??!0}}}var Fe=class{constructor(e,t,i,r,n,a,s){this.maxDistance=a,this.ditherStrength=s,this.inputs={sceneColor:e,sceneDepth:t,fogVolume:i,fogBounds:r},this.outputs=n}maxDistance;ditherStrength;name="VolumetricFogCompositePass";sampler="linear";uniformBufferSize=80;inputs;inputDimensions={fogVolume:"3d"};outputs;fragmentShader=He;data=new Float32Array(20);inverseProjection=new be;frameIndex=0;setFrameIndex(e){this.frameIndex=e}matches(e,t,i){return this.inputs.sceneColor===e&&this.inputs.sceneDepth===t&&this.outputs===i}updateUniforms=e=>(this.inverseProjection.copy(Re).multiply(e.camera.projectionMatrix).invert(),this.data.set(this.inverseProjection.elements,0),Ue(this.data,16,Math.max(.01,e.camera.near),Math.min(e.camera.far,this.maxDistance),this.frameIndex>0?this.frameIndex%1024:-1,this.ditherStrength),this.data)},Oe=class{constructor(e,t,i,r,n,a){this.maxDistance=n,this.ditherStrength=a,this.inputs={sceneDepth:e,fogVolume:t,fogBounds:i},this.outputs=r}maxDistance;ditherStrength;name="VolumetricFogResolvePass";sampler="linear";uniformBufferSize=80;inputDimensions={fogVolume:"3d"};inputs;outputs;fragmentShader=qe;data=new Float32Array(20);inverseProjection=new be;frameIndex=0;setFrameIndex(e){this.frameIndex=e}updateUniforms=e=>(this.inverseProjection.copy(Re).multiply(e.camera.projectionMatrix).invert(),this.data.set(this.inverseProjection.elements,0),Ue(this.data,16,Math.max(.01,e.camera.near),Math.min(e.camera.far,this.maxDistance),this.frameIndex>0?this.frameIndex%1024:-1,this.ditherStrength),this.data)},Ee=class{constructor(e,t,i,r,n,a,s,o,l){var c;this.temporal=o,this.state=l,this.inputs=null==i?{currentFog:e,sceneDepth:t,historyFog:r,historyDepth:n}:{currentFog:e,sceneDepth:t,historyFog:r,historyDepth:n,velocity:i},this.outputs=[a,s],this.fragmentShader=`\nstruct FogTemporalOutput{\n @location(0) fog:vec4<f32>,\n @location(1) depth:vec4<f32>,\n};\nfn currentViewProjectionInverse()->mat4x4<f32>{\n return mat4x4<f32>(fullscreenUniforms[0],fullscreenUniforms[1],fullscreenUniforms[2],fullscreenUniforms[3]);\n}\nfn previousViewProjection()->mat4x4<f32>{\n return mat4x4<f32>(fullscreenUniforms[4],fullscreenUniforms[5],fullscreenUniforms[6],fullscreenUniforms[7]);\n}\nfn loadCurrentFog(pixel:vec2<i32>,size:vec2<i32>)->vec4<f32>{\n return textureLoad(currentFogTexture,clamp(pixel,vec2<i32>(0),size-vec2<i32>(1)),0);\n}\nfn loadHistoryFog(pixel:vec2<i32>,size:vec2<i32>)->vec4<f32>{\n return textureLoad(historyFogTexture,clamp(pixel,vec2<i32>(0),size-vec2<i32>(1)),0);\n}\nfn sampleHistoryBilinear(uv:vec2<f32>)->vec4<f32>{\n let size=vec2<i32>(textureDimensions(historyFogTexture));\n let position=uv*vec2<f32>(size)-0.5;\n let base=vec2<i32>(floor(position));\n let f=fract(position);\n let a=mix(loadHistoryFog(base,size),loadHistoryFog(base+vec2<i32>(1,0),size),f.x);\n let b=mix(loadHistoryFog(base+vec2<i32>(0,1),size),loadHistoryFog(base+vec2<i32>(1,1),size),f.x);\n return mix(a,b,f.y);\n}\nfn loadSceneDepth(uv:vec2<f32>)->f32{\n let size=vec2<i32>(textureDimensions(sceneDepthTexture));\n let pixel=clamp(vec2<i32>(uv*vec2<f32>(size)),vec2<i32>(0),size-vec2<i32>(1));\n return textureLoad(sceneDepthTexture,pixel,0);\n}\nfn loadHistoryDepth(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${(c=null!=i)?"\nfn loadVelocity(uv:vec2<f32>)->vec2<f32>{\n let size=vec2<i32>(textureDimensions(velocityTexture));\n let pixel=clamp(vec2<i32>(uv*vec2<f32>(size)),vec2<i32>(0),size-vec2<i32>(1));\n return textureLoad(velocityTexture,pixel,0).xy;\n}\n":""}\n@fragment fn fsMain(input:FullscreenVertexOutput)->FogTemporalOutput{\n let size=vec2<i32>(textureDimensions(currentFogTexture));\n let pixel=clamp(vec2<i32>(input.position.xy),vec2<i32>(0),size-vec2<i32>(1));\n let uv=(vec2<f32>(pixel)+0.5)/vec2<f32>(size);\n let current=textureLoad(currentFogTexture,pixel,0);\n var neighborhoodMin=current;\n var neighborhoodMax=current;\n for(var y=-1;y<=1;y+=1){\n for(var x=-1;x<=1;x+=1){\n let value=loadCurrentFog(pixel+vec2<i32>(x,y),size);\n neighborhoodMin=min(neighborhoodMin,value);\n neighborhoodMax=max(neighborhoodMax,value);\n }\n }\n let rawDepth=loadSceneDepth(uv);\n let clip=vec4<f32>(uv.x*2.0-1.0,1.0-uv.y*2.0,rawDepth,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 cameraHistoryUv=vec2<f32>(previousNdc.x*0.5+0.5,0.5-previousNdc.y*0.5);\n${c?"\n let velocity=loadVelocity(uv);\n let finiteVelocity=all(velocity==velocity)&&all(abs(velocity)<vec2<f32>(2.0));\n let hasUsefulVelocity=finiteVelocity&&dot(velocity,velocity)>1e-12;\n let historyUv=select(cameraHistoryUv,uv-velocity,hasUsefulVelocity);\n":"\n let historyUv=cameraHistoryUv;\n"}\n let validUv=all(historyUv>=vec2<f32>(0.0))&&all(historyUv<=vec2<f32>(1.0));\n let historyValid=fullscreenUniforms[8].w>0.5&&validUv;\n let history=sampleHistoryBilinear(clamp(historyUv,vec2<f32>(0.0),vec2<f32>(1.0)));\n let previousDistance=loadHistoryDepth(clamp(historyUv,vec2<f32>(0.0),vec2<f32>(1.0)));\n let currentDistance=length(world.xyz-fullscreenUniforms[9].xyz);\n let relativeDepthDelta=abs(log(max(previousDistance,0.001)/max(currentDistance,0.001)));\n let rejection=max(fullscreenUniforms[8].y,0.0001);\n let depthWeight=exp(-relativeDepthDelta*relativeDepthDelta/(rejection*rejection));\n let clampedHistory=select(history,clamp(history,neighborhoodMin,neighborhoodMax),fullscreenUniforms[8].z>0.5);\n let historyWeight=select(0.0,fullscreenUniforms[8].x*depthWeight,historyValid);\n var output:FogTemporalOutput;\n output.fog=mix(current,clampedHistory,clamp(historyWeight,0.0,0.98));\n output.depth=vec4<f32>(min(currentDistance,65504.0),0.0,0.0,1.0);\n return output;\n}`}temporal;state;name="VolumetricFogTemporalPass";sampler="nearest";uniformBufferSize=160;inputs;outputs;fragmentShader;uniforms=new Float32Array(this.uniformBufferSize/4);currentViewProjection=new be;currentViewProjectionInverse=new be;updateUniforms=e=>(this.state.updateTemporalUniforms(this.uniforms,this.currentViewProjection,this.currentViewProjectionInverse,this.temporal,e),Ue(this.uniforms,36,e.camera.position.x,e.camera.position.y,e.camera.position.z,e.camera.far),this.uniforms)},je=class{name;sampler="linear";uniformBufferSize=80;inputs;outputs;fragmentShader;data=new Float32Array(20);inverseProjection=new be;constructor(e,t,i,r,n){this.name=r[0]?"VolumetricFogBlurHorizontalPass":"VolumetricFogBlurVerticalPass",this.inputs={fogInput:e,sceneDepth:t},this.outputs=i,this.data.set([r[0],r[1],n.depthSigma,n.spatialSigma],16),this.fragmentShader=`\nconst BLUR_RADIUS:i32=${n.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(Re).multiply(e.camera.projectionMatrix).invert(),this.data.set(this.inverseProjection.elements,0),this.data)},$e=class{name="VolumetricFogBlurCompositePass";sampler="linear";uniformBufferSize=64;inputs;inputDimensions={};outputs;fragmentShader;data=new Float32Array(16);inverseProjection=new be;constructor(e,t,i,r,n,a,s){this.inputs=s?{sceneColor:e,sceneDepth:t,fogInput:i}:{sceneColor:e,fogInput:i},this.outputs=a,this.fragmentShader=s?Ke:Ye}updateUniforms=e=>(this.inverseProjection.copy(Re).multiply(e.camera.projectionMatrix).invert(),this.data.set(this.inverseProjection.elements),this.data)},We="\nfn rendererSampleIntegratedFogRaw(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 rendererSampleIntegratedFog(uv: vec2<f32>, normalizedDepth: f32) -> vec4<f32> {\n return rendererSampleIntegratedFogRaw(uv, normalizedDepth);\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(log(max(distance, bounds.x) / bounds.x) / max(log(bounds.y / bounds.x), 0.0001), 0.0, 1.0);\n let fog = rendererSampleIntegratedFog(uv, z);\n return vec4<f32>(fog.rgb + color.rgb * fog.a, color.a);\n}";function Ne(e,t="volumetricFogIntegrated",i=(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:i,dimension:"2d",sampleType:"float",sampler:"filtering",requiresLatePass:!0},e.needsUpdate=!0,e}var _e="\nstruct FogUniforms { inverseViewProjection: mat4x4<f32>, cameraNear: vec4<f32>, dimensionsFar: vec4<f32>, counts: vec4<u32>, ambient: vec4<f32>, cameraForwardDepthRange: vec4<f32>, scattering: vec4<f32>, previousViewProjection: mat4x4<f32>, historyCameraValid: vec4<f32>, historyNearFarWeight: 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>,64>, pointColorIntensities: array<vec4<f32>,64>, pointParams: array<vec4<f32>,64>, pointShadowParams: array<vec4<f32>,64>, pointShadowParams2: array<vec4<f32>,64>,\n spotPositionRanges: array<vec4<f32>,64>, spotDirectionCones: array<vec4<f32>,64>, spotColorIntensities: array<vec4<f32>,64>,\n spotShadowParams: array<vec4<f32>,64>, spotShadowParams2: array<vec4<f32>,64>, spotParams: array<vec4<f32>,64>, spotShadowMatrices: array<mat4x4<f32>,64>,\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>;\n@group(0) @binding(11) var historySampler: sampler;\n@group(0) @binding(12) var scatteringHistory: texture_3d<f32>;\n@group(0) @binding(13) var outputScatteringHistory: texture_storage_3d<rgba16float, write>;\n@group(0) @binding(14) var spotLightMapAtlas: texture_2d<f32>;\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 spotConeAttenuation(angleCos: f32, coneCos: f32, penumbraCos: f32) -> f32 {\n // Three.js spotlights default to a zero-width penumbra. smoothstep() is\n // undefined when both edges are equal, so use a hard cutoff in that case.\n let width = penumbraCos - coneCos;\n if (width <= 0.000001) { return select(0.0, 1.0, angleCos >= coneCos); }\n return smoothstep(coneCos, penumbraCos, angleCos);\n}\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 halton(index:u32,base:u32)->f32{var i=index;var fraction=1.0;var result=0.0;loop{if(i==0u){break;}fraction/=f32(base);result+=fraction*f32(i%base);i/=base;}return result;}\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 fogPointVisibility(light:FogLight,p:vec3<f32>)->f32 { if(light.penumbra.z<0.5){return 1.0;} return pointVisibility(u32(round(light.penumbra.y)),p); }\nfn fogSpotVisibility(light:FogLight,p:vec3<f32>)->f32 { if(light.penumbra.z<0.5){return 1.0;} return spotVisibility(u32(round(light.penumbra.y)),p); }\nfn fogSpotMap(light:FogLight,p:vec3<f32>)->vec3<f32> { let index=u32(round(light.penumbra.y)); if(rendererLights.spotParams[index].w<0.5){return vec3<f32>(1.0);} let clip=rendererLights.spotShadowMatrices[index]*vec4<f32>(p,1.0); if(clip.w<=0.0){return vec3<f32>(1.0);} let ndc=clip.xyz/clip.w; if(any(ndc<vec3<f32>(-1.0,-1.0,0.0))||any(ndc>vec3<f32>(1.0))){return vec3<f32>(1.0);} let uv=ndc.xy*vec2<f32>(0.5,-0.5)+vec2<f32>(0.5);let cell=vec2<f32>(f32(index%8u),f32(index/8u));let cellUv=clamp(uv,vec2<f32>(0.0),vec2<f32>(1.0))*(255.0/256.0)+vec2<f32>(0.5/256.0);return textureSampleLevel(spotLightMapAtlas,historySampler,(cell+cellUv)/8.0,0.0).rgb; }\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 // Keep the froxel lattice fixed. Moving the complete XY grid with a Halton\n // offset makes high-contrast shaft boundaries alternate between adjacent\n // froxels, which reads as the entire shadow edge blinking. We still use a\n // temporal Z offset to integrate within-slice variation over time without\n // moving the grid or the shadow-classification position sideways.\n let frameIndex=u32(max(uniforms.ambient.w,1.0));\n let temporal=vec2<f32>(0.5);\n let rayJitter=select(hash12(vec2<f32>(id.xy)+vec2<f32>(17.17,43.43)),halton(frameIndex,5u),uniforms.ambient.w>0.0);\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 centerUv=(vec2<f32>(id.xy)+vec2<f32>(0.5))/vec2<f32>(dims.xy);\n let centerFarPoint4=uniforms.inverseViewProjection*vec4<f32>(centerUv.x*2.0-1.0,1.0-centerUv.y*2.0,1.0,1.0);\n let centerRay=normalize(centerFarPoint4.xyz/centerFarPoint4.w-camera);\n let nearPlane = uniforms.cameraNear.w; let farPlane = uniforms.dimensionsFar.w;\n 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,farPlane);let columnFar=max(farPlane,columnNear+0.001);textureStore(outputDepthBounds,vec2<i32>(id.xy),vec4<f32>(columnNear,columnFar,0.0,0.0));\n let sliceRatio=pow(columnFar/columnNear,1.0/f32(dims.z));\n var transmittance = 1.0; var scattering = vec3<f32>(0.0); var previousDistance = columnNear; var sliceEnd=columnNear;\n for (var z=0u; z<dims.z; z+=1u) {\n // Every column uses the same logarithmic Z coordinate, so XY filtering\n // blends cumulative fog evaluated at the same physical distance.\n sliceEnd*=sliceRatio; let stepSize = sliceEnd-previousDistance;\n var localScattering=vec3<f32>(0.0);var localExtinction=0.0;\n if(stepSize>0.0){\n // Resizing recreates the 3D history. Use a few stratified samples only on\n // that first frame so the raw one-sample slice pattern is never exposed.\n let integrationSubsteps=max(INTEGRATION_SUBSTEPS,select(4u,INTEGRATION_SUBSTEPS,uniforms.historyCameraValid.w>0.5));\n let substepSize=stepSize/f32(integrationSubsteps);\n for(var substep=0u;substep<integrationSubsteps;substep+=1u){\n let sampleOffset=select(0.5,fract(rayJitter+f32(substep)/f32(integrationSubsteps)),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 // Follow the temporally stratified Z sample so history integrates shadow\n // transitions within a slice. XY remains fixed, preventing the complete\n // edge from oscillating sideways between neighboring froxels.\n let shadowP=p;\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));}filteredDirectionalVisibility[d]=directionalVisibility(d,shadowP)*cascadeWeight;}\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 shaftVisibility=0.0; var li=0u;\n for (var d=0u; d<uniforms.counts.y; d+=1u) {\n let l=lights[li]; li+=1u;\n shaftVisibility=max(shaftVisibility,filteredDirectionalVisibility[d]);\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)*fogPointVisibility(l,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=spotConeAttenuation(cd,l.directionCone.w,l.penumbra.x); direct += l.colorDecay.rgb*fogSpotMap(l,p)*attenuation(dist,l.positionRange.w,l.colorDecay.w)*cone*phaseHG(dot(ray,normalize(delta)),volume.heightStartPhase.w)*fogSpotVisibility(l,p); }\n direct*=uniforms.scattering.x;\n if (volume.mode.x < 0.5) { lighting += direct; } else { lighting = direct; }\n // Preserve fractional filtered visibility at shaft boundaries. A hard\n // threshold produces a temporally moving saw-tooth edge as jittered\n // froxels alternate between lit and shadowed. Direct lighting already\n // contains this visibility, while extinction must be scaled explicitly.\n if (volume.mode.x < 0.5) {\n sigma += density; source += lighting*volume.albedoDensity.rgb*density;\n } else {\n let visibleDensity=density*clamp(shaftVisibility,0.0,1.0);\n sigma += visibleDensity; source += lighting*volume.albedoDensity.rgb*density;\n }\n }\n }\n localScattering+=source/f32(integrationSubsteps);localExtinction+=sigma/f32(integrationSubsteps);\n }\n let historyPosition=camera+ray*(previousDistance+0.5*stepSize);\n let previousClip=uniforms.previousViewProjection*vec4<f32>(historyPosition,1.0);\n let previousUv=previousClip.xy/previousClip.w*vec2<f32>(0.5,-0.5)+vec2<f32>(0.5);\n let previousDistanceToCamera=length(historyPosition-uniforms.historyCameraValid.xyz);\n let previousNear=uniforms.historyNearFarWeight.x;let previousFar=uniforms.historyNearFarWeight.y;\n let previousZ=log(max(previousDistanceToCamera,previousNear)/previousNear)/max(log(previousFar/previousNear),0.0001);\n let validHistory=uniforms.historyCameraValid.w>0.5&&previousClip.w>0.0&&all(previousUv>=vec2<f32>(0.0))&&all(previousUv<=vec2<f32>(1.0))&&previousZ>=0.0&&previousZ<=1.0;\n if(validHistory){let history=textureSampleLevel(scatteringHistory,historySampler,vec3<f32>(previousUv,previousZ),0.0);let weight=uniforms.historyNearFarWeight.z;localScattering=mix(localScattering,history.rgb,weight);localExtinction=mix(localExtinction,history.a,weight);}\n }\n textureStore(outputScatteringHistory,vec3<i32>(i32(id.x),i32(id.y),i32(z)),vec4<f32>(localScattering,localExtinction));\n if(localExtinction>0.000001){let extinction=exp(-localExtinction*stepSize);scattering+=transmittance*localScattering*((1.0-extinction)/localExtinction);transmittance*=extinction;}\n textureStore(outputFog, vec3<i32>(i32(id.x),i32(id.y),i32(z)), vec4<f32>(scattering,transmittance)); previousDistance=sliceEnd;\n }\n}",He="\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 sampleIntegratedFogRaw(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}\nfn sampleIntegratedFog(uv:vec2<f32>,normalizedDepth:f32)->vec4<f32>{return sampleIntegratedFogRaw(uv,normalizedDepth);}\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(log(max(distance,bounds.x)/bounds.x)/max(log(bounds.y/bounds.x),0.0001),0.0,1.0);\n let frame=fullscreenUniforms[4].z; let ditherStrength=fullscreenUniforms[4].w;\n let noise=fogDither(input.position.xy,max(frame,0.0));\n let fog=sampleIntegratedFog(input.uv,z);\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}",qe="\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 sampleIntegratedFogRaw(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}\nfn sampleIntegratedFog(uv:vec2<f32>,normalizedDepth:f32)->vec4<f32>{return sampleIntegratedFogRaw(uv,normalizedDepth);}\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(log(max(distance,bounds.x)/bounds.x)/max(log(bounds.y/bounds.x),0.0001),0.0,1.0);var fog=sampleIntegratedFog(input.uv,z);let frame=fullscreenUniforms[4].z; let noise=fogDither(input.position.xy,max(frame,0.0));\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 Ke="\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);}\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 centerDepth=loadDepth(input.uv);var bestUv=clamp(candidates[0],vec2<f32>(0.0),vec2<f32>(1.0));var bestDifference=abs(centerDepth-loadDepth(bestUv));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(centerDepth-loadDepth(uv));maxDifference=max(maxDifference,difference);if(difference<bestDifference){bestDifference=difference;bestUv=uv;}}\n let sampleUv=select(input.uv,bestUv,maxDifference>0.001);let fog=textureSampleLevel(fogInputTexture,fullscreenSampler,sampleUv,0.0);return vec4<f32>(fog.rgb+color.rgb*fog.a,color.a);\n}",Ye="\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 Ze,DepthFormat as Xe,DepthStencilFormat as Je,FloatType as Qe,HalfFloatType as et,IntType as tt,RED_GREEN_RGTC2_Format as it,RED_RGTC1_Format as rt,RGBA_ASTC_10x10_Format as nt,RGBA_ASTC_10x5_Format as at,RGBA_ASTC_10x6_Format as st,RGBA_ASTC_10x8_Format as ot,RGBA_ASTC_12x10_Format as lt,RGBA_ASTC_12x12_Format as ct,RGBA_ASTC_4x4_Format as ut,RGBA_ASTC_5x4_Format as dt,RGBA_ASTC_5x5_Format as ht,RGBA_ASTC_6x5_Format as pt,RGBA_ASTC_6x6_Format as ft,RGBA_ASTC_8x5_Format as mt,RGBA_ASTC_8x6_Format as gt,RGBA_ASTC_8x8_Format as vt,RGBA_BPTC_Format as xt,RGBA_ETC2_EAC_Format as wt,RGBA_S3TC_DXT1_Format as bt,RGBA_S3TC_DXT3_Format as yt,RGBA_S3TC_DXT5_Format as St,RGBAFormat as Ct,RGBAIntegerFormat as Mt,RGFormat as Pt,RGIntegerFormat as Bt,RGB_ETC1_Format as Dt,RGB_ETC2_Format as It,RGB_S3TC_DXT1_Format as Tt,RGBFormat as Rt,RedFormat as Vt,RedIntegerFormat as Gt,ShortType as zt,SIGNED_RED_GREEN_RGTC2_Format as Lt,SIGNED_RED_RGTC1_Format as Ut,SRGBColorSpace as kt,UnsignedByteType as At,UnsignedInt248Type as Ft,UnsignedInt5999Type as Ot,UnsignedIntType as Et,UnsignedShortType as jt}from"three";function $t(e,t){const i=function(e){if(!0===e.isCubeTexture){const t=e.image,i=t?.[0],r=i?.image??i;return{width:r?.width??1,height:r?.height??1,depthOrArrayLayers:6}}const t=e.image;return{width:t?.width??1,height:t?.height??1,depthOrArrayLayers:t?.depth??1}}(e),r=Ht(e,t),n=Xt(e),a=function(e){return"3d"===Zt(e)?"3d":"2d"}(e),s=qt(e,r,t),o=Kt(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:r,textureDimension:a,viewDimension:n,sampleType:s,samplerBindingType:o,wgslTextureType:Yt(n,s),wgslSamplerType:"comparison"===o?"sampler_comparison":"sampler",width:i.width,height:i.height,depthOrArrayLayers:i.depthOrArrayLayers,mipLevelCount:l,compressed:Jt(e)}}function Wt(e,t){const i=$t(e,t);return[i.format,i.textureDimension,i.viewDimension,i.sampleType,i.samplerBindingType,i.width,i.height,i.depthOrArrayLayers,i.mipLevelCount].join(":")}function Nt(e){const t=qt(e,Ht(e,void 0,!1));return[Yt(Xt(e),t),"comparison"===Kt(e,t)?"sampler_comparison":"sampler"].join(":")}function _t(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}}function Ht(e,t,i=!0){const r=e.format,n=e.type,a=e.colorSpace===kt;let s=null;if(Jt(e))switch(r){case Tt:case bt:s=a?"bc1-rgba-unorm-srgb":"bc1-rgba-unorm";break;case yt:s=a?"bc2-rgba-unorm-srgb":"bc2-rgba-unorm";break;case St:s=a?"bc3-rgba-unorm-srgb":"bc3-rgba-unorm";break;case rt:s="bc4-r-unorm";break;case Ut:s="bc4-r-snorm";break;case it:s="bc5-rg-unorm";break;case Lt:s="bc5-rg-snorm";break;case xt:s=a?"bc7-rgba-unorm-srgb":"bc7-rgba-unorm";break;case It:case Dt:s=a?"etc2-rgb8unorm-srgb":"etc2-rgb8unorm";break;case wt:s=a?"etc2-rgba8unorm-srgb":"etc2-rgba8unorm";break;case ut:s=a?"astc-4x4-unorm-srgb":"astc-4x4-unorm";break;case dt:s=a?"astc-5x4-unorm-srgb":"astc-5x4-unorm";break;case ht:s=a?"astc-5x5-unorm-srgb":"astc-5x5-unorm";break;case pt:s=a?"astc-6x5-unorm-srgb":"astc-6x5-unorm";break;case ft:s=a?"astc-6x6-unorm-srgb":"astc-6x6-unorm";break;case mt:s=a?"astc-8x5-unorm-srgb":"astc-8x5-unorm";break;case gt:s=a?"astc-8x6-unorm-srgb":"astc-8x6-unorm";break;case vt:s=a?"astc-8x8-unorm-srgb":"astc-8x8-unorm";break;case at:s=a?"astc-10x5-unorm-srgb":"astc-10x5-unorm";break;case st:s=a?"astc-10x6-unorm-srgb":"astc-10x6-unorm";break;case ot:s=a?"astc-10x8-unorm-srgb":"astc-10x8-unorm";break;case nt:s=a?"astc-10x10-unorm-srgb":"astc-10x10-unorm";break;case lt:s=a?"astc-12x10-unorm-srgb":"astc-12x10-unorm";break;case ct:s=a?"astc-12x12-unorm-srgb":"astc-12x12-unorm";break;case Ct:s=a?"rgba8unorm-srgb":"rgba8unorm"}else switch(r){case Ct:switch(n){case Ze:s="rgba8snorm";break;case zt:s="rgba16sint";break;case jt:s="rgba16uint";break;case Et:s="rgba32uint";break;case tt:s="rgba32sint";break;case At:s=a?"rgba8unorm-srgb":"rgba8unorm";break;case et:s="rgba16float";break;case Qe:s="rgba32float"}break;case Rt:switch(n){case Ot:s="rgb9e5ufloat";break;case 35899:s="rg11b10ufloat"}break;case Vt:switch(n){case Ze:s="r8snorm";break;case zt:s="r16sint";break;case jt:s="r16uint";break;case Et:s="r32uint";break;case tt:s="r32sint";break;case At:s="r8unorm";break;case et:s="r16float";break;case Qe:s="r32float"}break;case Pt:switch(n){case Ze:s="rg8snorm";break;case zt:s="rg16sint";break;case jt:s="rg16uint";break;case Et:s="rg32uint";break;case tt:s="rg32sint";break;case At:s="rg8unorm";break;case et:s="rg16float";break;case Qe:s="rg32float"}break;case Xe:switch(n){case jt:s="depth16unorm";break;case Et:s="depth24plus";break;case Qe:s="depth32float"}break;case Je:switch(n){case Ft:s="depth24plus-stencil8";break;case Qe:Qt("depth32float-stencil8",t,e,"DepthTexture with DepthStencilFormat + FloatType"),s="depth32float-stencil8"}break;case Gt:switch(n){case tt:s="r32sint";break;case Et:s="r32uint"}break;case Bt:switch(n){case tt:s="rg32sint";break;case Et:s="rg32uint"}break;case Mt:switch(n){case tt:s="rgba32sint";break;case Et:s="rgba32uint"}}if(!s)throw new Error(`Texture format "${r}" with type "${n}" from "${e.constructor.name}" is not supported by this renderer yet.`);const o=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}(s);return o&&i&&Qt(o,t,e,`Texture format "${s}"`),s}function qt(e,t,i){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===tt)return"sint";if(e.type===Et)return"uint";if(e.type===Qe&&!ei(i,"float32-filterable")&&("r32float"===t||"rg32float"===t||"rgba32float"===t))return"unfilterable-float"}return"float"}function Kt(e,t){const i=e.compareFunction;return"depth"===t&&null!=i?"comparison":"float"===t?"filtering":"non-filtering"}function Yt(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 i="uint"===t?"u32":"sint"===t?"i32":"f32";switch(e){case"2d-array":return`texture_2d_array<${i}>`;case"cube":return`texture_cube<${i}>`;case"3d":return`texture_3d<${i}>`;default:return`texture_2d<${i}>`}}function Zt(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 Xt(e){const t=Zt(e);return"cube"===t?"cube":"2d-array"===t?"2d-array":"3d"===t?"3d":"2d"}function Jt(e){return!0===e.isCompressedTexture||!0===e.isCompressedArrayTexture}function Qt(e,t,i,r){if(!ei(t,e))throw new Error(`${r} for "${i.name||i.uuid}" requires the WebGPU feature "${e}", which is not enabled on this device.`)}function ei(e,t){return!!e&&(e instanceof Set?e.has(t):"features"in e?e.features.has(t):e.has(t))}import{Color as ti,Matrix3 as ii,Matrix4 as ri,Vector2 as ni,Vector3 as ai,Vector4 as si}from"three";var oi=new ArrayBuffer(8),li=new Float64Array(oi),ci=new Uint32Array(oi),ui={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 di(e,t){return Math.ceil(e/t)*t}function hi(e,t,i,r){const n="boolean"==typeof r?r?1:0:Number(r);"i32"!==i?"u32"!==i?e.setFloat32(t,n,!0):e.setUint32(t,n,!0):e.setInt32(t,n,!0)}function pi(e,t,i,r){for(let n=0;n<r;n+=1)e[t+n]=fi(i,n,r)}function fi(e,t,i){if("number"==typeof e||"boolean"==typeof e)return 0===t?Number(e):0;if(Array.isArray(e))return e[t]??0;if(e instanceof ii||e instanceof ri)return e.elements[t]??0;if(e instanceof ti)return 0===t?e.r:1===t?e.g:2===t?e.b:3===t&&i>=4?1:0;if(e instanceof ni||e instanceof ai||e instanceof si){if(0===t)return e.x;if(1===t)return e.y;if(2===t&&(e instanceof ai||e instanceof si))return e.z;if(3===t&&e instanceof si)return e.w}return 0}function mi(e,t,i){for(let r=0;r<3;r+=1){const n=3*r,a=t+4*r;e[a+0]=fi(i,n+0,9),e[a+1]=fi(i,n+1,9),e[a+2]=fi(i,n+2,9),e[a+3]=0}}function gi(e){let t=0;const i=[];for(const[r,n]of Object.entries(e)){const e=ui[n.type];t=di(t,e.alignment),i.push({name:r,offset:t,type:n.type}),t+=e.size}return{byteLength:di(t,16),entries:i}}var vi=class{constructor(e){this.layout=e,this.buffer=new ArrayBuffer(e.byteLength),this.view=new DataView(this.buffer),this.floats=new Float32Array(this.buffer)}layout;buffer;view;floats;update(e){return xi(e,this.layout,this.view,this.floats),this.buffer}};function xi(e,t,i,r){r.fill(0);for(const n of t.entries){const t=e[n.name],a=n.offset/4;switch(n.type){case"f32":case"i32":case"u32":hi(i,n.offset,n.type,t.value);break;case"vec2<f32>":pi(r,a,t.value,2);break;case"vec3<f32>":pi(r,a,t.value,3);break;case"vec4<f32>":pi(r,a,t.value,4);break;case"mat3x3<f32>":mi(r,a,t.value);break;case"mat4x4<f32>":t.value instanceof ri?r.set(t.value.elements,a):pi(r,a,t.value,16)}}}function wi(e,t){let i=Math.imul(e^t,16777619);return i^=i>>>13,i>>>0}function bi(e,t){return li[0]=t,e=wi(e,ci[0]??0),e=wi(e,ci[1]??0)}function yi(e,t,i){const r="number"==typeof t||"boolean"==typeof t?1:Array.isArray(t)?Math.min(t.length,i):t instanceof ti?i>=4?4:3:t instanceof ni?2:t instanceof ai?3:t instanceof si?4:t instanceof ii?9:t instanceof ri?16:0;e=wi(e,r);for(let n=0;n<r;n+=1)e=bi(e,fi(t,n,i));return e}var Si="\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";function Ci(e,t,i,r){let n=e.execution;if(!n){const a=[];for(let e=0;e<t;e++)a.push({binding:e,resource:null});e.uniformBuffer&&a.push({binding:t,resource:{buffer:e.uniformBuffer}});const s=[];for(let e=0;e<i;e++)s.push({view:null,clearValue:{r:0,g:0,b:0,a:1},loadOp:"clear",storeOp:"store"});n={resources:[],entries:a,attachments:s,bindGroupDescriptor:{label:`${r}-bind-group`,layout:e.bindGroupLayout,entries:a},passDescriptor:{label:r,colorAttachments:s}},e.execution=n}return n.passDescriptor.label=r,n}var Mi=new WeakMap;function Pi(e){let t=Mi.get(e);return t||(t={outputFormats:[],inputDimensions:[]},Mi.set(e,t)),t}var Bi=new WeakMap;function Di(e,t,i,r,n){let a=Bi.get(e);a||Bi.set(e,a=new Map);let s=a.get(t);s||(s={module:e.createShaderModule({label:i,code:t}),variants:new Map},a.set(t,s));let o=s.variants.get(r);return o||s.variants.set(r,o=n(s.module)),o}function Ii(){return{children:new WeakMap}}function Ti(e,t,i,r){let n=e;for(const e of t){let t=n.children.get(e);t||(t=Ii(),n.children.set(e,t)),n=t}return n.bindGroup??=i.createBindGroup(r),n.bindGroup}var Ri=new WeakMap,Vi=new WeakMap;function Gi(e){return e?"string"==typeof e?[e]:Array.from(e):[]}var zi=new WeakMap;function Li(e,t){let i=0;if(e)for(const r in e){if(!Object.hasOwn(e,r))continue;const n=t[i];if(!n||n[0]!==r||n[1]!==e[r])return!1;i+=1}return i===t.length}function Ui(e){return e.replace(/[^A-Za-z0-9_]/g,"_")}var ki=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,t){this.context.addSceneTextureCopyPass(e,t)}addLatePass(e=this.sceneColor){this.context.addLatePass(e)}addHiZHistoryPass(e="ForwardPass"){this.context.addHiZHistoryPass(e)}addMaterialPass(e={}){const t={name:e.name,dependsOn:e.dependsOn,outputs:e.outputs??this.sceneColor,drawStage:e.drawStage,loadColor:e.loadColor,clearColor:e.clearColor,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,i=Gi(e.outputs),r={name:e.name,reads:t,writes:i.length>0?i:void 0,dependsOn:e.dependsOn,execute:e.execute};this.context.addCustomPass(r)}addFullscreenPass(e){const t=zi.get(e);if(t&&t.pass.name===e.name&&Li(e.inputs,t.inputs)&&Li(e.textures,t.textures)&&function(e,t){if("string"==typeof e)return 1===t.length&&t[0]===e;if(e.length!==t.length)return!1;for(let i=0;i<e.length;i+=1)if(e[i]!==t[i])return!1;return!0}(e.outputs,t.outputs))return void this.context.addCustomPass(t.pass);const i=Gi(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 a=r.map(([,e])=>e===this.mainDepth?"depth":"color"),s={name:e.name,reads:r.map(([,e])=>e),writes:i.length>0?i:void 0,execute:t=>{const{outputFormats:s,inputDimensions:o}=Pi(e);s.length=i.length;for(let e=0;e<i.length;e++)s[e]=t.getColorFormat(i[e]);const l=n.map(([,e])=>Wt(e,t.device)).join("|");o.length=r.length;for(let t=0;t<r.length;t++)o[t]=e.inputDimensions?.[r[t][0]]??"2d";const c=`${s.join("|")}:${a.map((e,t)=>`${e}-${o[t]}`).join("|")}:${l}:${e.uniformBufferSize??0}`,u=c,d=function(e,t){let i=Ri.get(e);i||(i=new WeakMap,Ri.set(e,i));let r=i.get(t);return r||(r=new Map,i.set(t,r)),r}(e,t.device);let h=d.get(u);if(!h){const i=n.map(([,e])=>$t(e,t.device)),l=[Si,"@group(0) @binding(0) var fullscreenSampler: sampler;",r.map(([e],t)=>`@group(0) @binding(${t+1}) var ${e}Texture: ${"depth"===a[t]?"texture_depth_2d":"3d"===o[t]?"texture_3d<f32>":"texture_2d<f32>"};`).join("\n"),n.map(([e],t)=>{const n=r.length+1+2*t,a=i[t];return`@group(0) @binding(${n}) var ${e}Sampler: ${a.wgslSamplerType};\n@group(0) @binding(${n+1}) var ${e}Texture: ${a.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"),p=`${c}:sampler=${"nearest"===e.sampler?"non-filtering":"filtering"}`,{bindGroupLayout:f,pipeline:m}=Di(t.device,l,`${e.name}-shader-module`,p,l=>{const c=t.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"===a[t]?"depth":"float",viewDimension:"3d"===o[t]?"3d":"2d"}})),...i.flatMap((e,t)=>{const i=r.length+1+2*t;return[{binding:i,visibility:GPUShaderStage.FRAGMENT,sampler:{type:e.samplerBindingType}},{binding:i+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"}}]:[]]}),u=t.device.createPipelineLayout({label:`${e.name}-pipeline-layout`,bindGroupLayouts:[c]});return{bindGroupLayout:c,pipeline:t.device.createRenderPipeline({label:`${e.name}-pipeline`,layout:u,vertex:{module:l,entryPoint:"vsMain"},fragment:{module:l,entryPoint:"fsMain",targets:s.map(e=>({format:e}))},primitive:{topology:"triangle-list"}})}});h={bindGroupLayout:f,pipeline:m,uniformBuffer:e.uniformBufferSize?t.device.createBuffer({label:`${e.name}-uniform-buffer`,size:16*Math.ceil(Math.max(16,e.uniformBufferSize)/16),usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}):null,bindGroupCache:Ii()},d.set(u,h)}const{pipeline:p,uniformBuffer:f}=h,m=e.updateUniforms?.(t)??null;f&&m&&t.device.queue.writeBuffer(f,0,m.buffer,m.byteOffset,m.byteLength);const g=Ci(h,r.length+1+2*n.length,i.length,e.name),v=g.resources;v[0]="nearest"===e.sampler||"linear"!==e.sampler&&a.includes("depth")?t.nearestClampSampler:t.linearClampSampler;for(let e=0;e<r.length;e++)v[e+1]="depth"===a[e]?t.depthView:t.getColorView(r[e][1]);for(let e=0;e<n.length;e++){const i=t.getExternalTexture(n[e][1]),a=r.length+1+2*e;v[a]=i.sampler,v[a+1]=i.view}const x=r.length+1+2*n.length;for(let e=0;e<x;e++)g.entries[e].resource=v[e];f&&(v[x]=f);const w=Ti(h.bindGroupCache,v,t.device,g.bindGroupDescriptor);for(let e=0;e<i.length;e++)g.attachments[e].view=t.getColorView(i[e]);const b=t.encoder.beginRenderPass(g.passDescriptor);b.setPipeline(p),b.setBindGroup(0,w),b.draw(3),b.end()}};zi.set(e,{inputs:r,textures:n,outputs:i,pass:s}),this.context.addCustomPass(s)}addNodeFullscreenPass(e){const t=Gi(e.outputs),r=Object.entries(function(e){const t={};for(const[i,r]of Object.entries(e.sceneTextures??{}))t[i]="sceneDepth"===r?{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,i])=>[t,null!=e.inputOverrides?.[t]?{...i,resource:e.inputOverrides[t]}:i]),n=Object.entries(e.shader.textures??{}),a=Object.fromEntries(r.map(([e,t])=>[e,t.resource])),s=gi(e.shader.uniforms);this.addPass({name:e.name,inputs:a,outputs:t,execute:a=>{const{outputFormats:o}=Pi(e);o.length=t.length;for(let e=0;e<t.length;e++)o[e]=a.getColorFormat(t[e]);const l=r.map(([e,t])=>`${e}:${t.dimension}:${t.sampleType}:${t.sampler??"filtering"}`).join("|"),c=n.map(([,e])=>Wt(e,a.device)).join("|"),u=s.entries.map(e=>`${e.name}:${e.type}:${e.offset}`).join("|"),d=`${o.join("|")}:${l}:${c}:${u}`,h=function(e,t){let i=Vi.get(e);i||(i=new WeakMap,Vi.set(e,i));let r=i.get(t);return r||(r=new Map,i.set(t,r)),r}(e.shader,a.device);let p=h.get(d);if(!p){const t=n.map(([,e])=>$t(e,a.device)),l=[];for(const[,e]of r){const t=l.length;l.push({binding:t,visibility:GPUShaderStage.FRAGMENT,sampler:{type:e.sampler??("depth-2d"===e.dimension?"non-filtering":"filtering")}},{binding:t+1,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:e.sampleType??("depth-2d"===e.dimension?"depth":"float"),viewDimension:"3d"===e.dimension?"3d":"2d"}})}for(const[e,i]of t.entries()){const e=l.length;l.push({binding:e,visibility:GPUShaderStage.FRAGMENT,sampler:{type:i.samplerBindingType}},{binding:e+1,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:i.sampleType,viewDimension:i.viewDimension}})}const c=2*(r.length+n.length);s.byteLength>0&&l.push({binding:c,visibility:GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}});const u=r.map(([e,t],i)=>{const r=Ui(e);return`@group(0) @binding(${2*i}) var ${r}Sampler: ${"comparison"===t.sampler?"sampler_comparison":"sampler"};\n@group(0) @binding(${2*i+1}) var ${r}Texture: ${"depth-2d"===t.dimension?"texture_depth_2d":"3d"===t.dimension?"texture_3d<f32>":"texture_2d<f32>"};`}).join("\n"),f=n.map(([e],i)=>{const n=2*(r.length+i),a=t[i],s=Ui(e);return`@group(0) @binding(${n}) var ${s}Sampler: ${a.wgslSamplerType};\n@group(0) @binding(${n+1}) var ${s}Texture: ${a.wgslTextureType};`}).join("\n"),m=s.entries.map(e=>` ${Ui(e.name)}: ${e.type},`).join("\n"),g=s.byteLength>0?`struct MaterialUniforms {\n${m}\n};\n@group(0) @binding(${c}) var<uniform> materialUniforms: MaterialUniforms;`:"",v=[Si,u,f,g,e.shader.fragmentShader].filter(Boolean).join("\n\n"),x=JSON.stringify([o,l]),{bindGroupLayout:w,pipeline:b}=Di(a.device,v,`${e.name}-node-shader-module`,x,t=>{const r=a.device.createBindGroupLayout({label:`${e.name}-node-layout`,entries:l}),n=a.device.createPipelineLayout({label:`${e.name}-node-pipeline-layout`,bindGroupLayouts:[r]});e.diagnosticOrigin&&i(a.device,`${e.name}-node-pipeline`,e.diagnosticOrigin);return{bindGroupLayout:r,pipeline:a.device.createRenderPipeline({label:`${e.name}-node-pipeline`,layout:n,vertex:{module:t,entryPoint:"vsMain"},fragment:{module:t,entryPoint:"fsMain",targets:o.map(e=>({format:e}))},primitive:{topology:"triangle-list"}})}});p={bindGroupLayout:w,pipeline:b,uniformBuffer:s.byteLength>0?a.device.createBuffer({label:`${e.name}-node-uniforms`,size:s.byteLength,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}):null,bindGroupCache:Ii()},h.set(d,p)}const{pipeline:f,uniformBuffer:m}=p;e.shader.syncLiveUniforms(e.shader.uniforms),m&&a.device.queue.writeBuffer(m,0,(p.uniformData??=new vi(s)).update(e.shader.uniforms));const g=2*(r.length+n.length),v=Ci(p,g,t.length,e.name),x=v.resources;for(let e=0;e<r.length;e++){const t=r[e][1];x[2*e]="comparison"===t.sampler?a.comparisonSampler:"non-filtering"===t.sampler||"depth-2d"===t.dimension?a.nearestClampSampler:a.linearClampSampler,x[2*e+1]=a.getTextureView(t.resource)}for(let e=0;e<n.length;e++){const t=a.getExternalTexture(n[e][1]),i=2*(r.length+e);x[i]=t.sampler,x[i+1]=t.view}for(let e=0;e<g;e++)v.entries[e].resource=x[e];m&&(x[g]=m);const w=Ti(p.bindGroupCache,x,a.device,v.bindGroupDescriptor);for(let e=0;e<t.length;e++)v.attachments[e].view=a.getColorView(t[e]);const b=a.encoder.beginRenderPass(v.passDescriptor);b.setPipeline(f),b.setBindGroup(0,w),b.draw(3),b.end()}})}present(e=this.sceneColor){this.context.addPresentPass(e)}},Ai=new WeakMap;function Fi(e,t,i){let r=Ai.get(e);r||(r=[],Ai.set(e,r)),r[t]!==i&&(e.setBindGroup(t,i),r[t]=i)}var Oi=new WeakMap;function Ei(e,t,i,r){let n=Oi.get(e);n||(n={vertices:[],index:null,indexFormat:null},Oi.set(e,n));for(let i=0;i<t.length;i++){const r=t[i];n.vertices[i]!==r&&(e.setVertexBuffer(i,r),n.vertices[i]=r)}i&&r&&(n.index!==i||n.indexFormat!==r)&&(e.setIndexBuffer(i,r),n.index=i,n.indexFormat=r)}function ji(e,t){e.executeBundles(t),function(e){const t=Ai.get(e);t&&(t.length=0)}(e),Oi.delete(e)}function $i(e,t=!1){return e.wireframe||!e.primitiveTopology.startsWith("triangle")?{depthBias:0,depthBiasSlopeScale:0,depthBiasClamp:0}:{depthBias:(t?1:0)+(e.polygonOffset?Math.trunc(e.polygonOffsetUnits):0),depthBiasSlopeScale:(t?2:0)+(e.polygonOffset?e.polygonOffsetFactor:0),depthBiasClamp:0}}var Wi=new WeakMap,Ni=new WeakMap;function _i(e){const t=Ni.get(e);if(t){for(const e of t)e();t.clear(),Ni.delete(e)}}function Hi(e,t){t?Wi.set(e,t):Wi.delete(e)}function qi(e){return Wi.get(e)}import{AlwaysCompare as Ki,BufferAttribute as Yi,EqualCompare as Zi,GreaterCompare as Xi,GreaterEqualCompare as Ji,InterleavedBufferAttribute as Qi,LessCompare as er,LessEqualCompare as tr,MirroredRepeatWrapping as ir,NearestFilter as rr,NearestMipmapLinearFilter as nr,NearestMipmapNearestFilter as ar,NeverCompare as sr,NotEqualCompare as or,Object3D as lr,RepeatWrapping as cr,Vector3 as ur}from"three";import{Material as dr}from"three";var hr=[{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]}],pr=class e extends dr{isWGSLShaderMaterial=!0;vertexShader;fragmentShader;depthVertexShader;depthFragmentShader;pointShadowVertexShader;pointShadowFragmentShader;defines;uniforms;textures;sceneTextures;graphTextures;storageBuffers;vertexAttributes;primitiveTopology;wireframe;uniformLayoutCache=null;programCacheKeyCache=null;depthProgramCacheKeyCache=null;pointShadowProgramCacheKeyCache=null;textureListCache=null;textureVersionsCache=[];textureVersionHashCache=0;storageBufferBindingListCache=null;storageBufferListCache=null;textureLayoutKeyDeviceCache=null;textureLayoutKeyCache=null;uniformValuesAutoUpdate=!0;uniformValuesAutoVersion=0;set uniformValuesNeedsUpdate(e){e&&this.uniformValuesAutoVersion++}constructor(e){super();const{vertexShader:t,fragmentShader:i,depthVertexShader:r,depthFragmentShader:n,pointShadowVertexShader:a,pointShadowFragmentShader:s,defines:o,uniforms:l,textures:c,sceneTextures:u,graphTextures:d,storageBuffers:h,vertexAttributes:p,primitiveTopology:f,uniformValuesAutoUpdate:m,wireframe:g,...v}=e,x=function(e,t){const i={},r={...t};for(const[t,n]of Object.entries(e)){const e=vr(t,n);"texture"!==e.kind?i[t]=e.uniform:r[t]=e.texture}return{uniforms:i,textures:r}}(l??{},c??{});this.type="WGSLShaderMaterial",this.vertexShader=t,this.fragmentShader=i,this.depthVertexShader=r??null,this.depthFragmentShader=n??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=mr(p??hr),this.primitiveTopology=f??"triangle-list",this.uniformValuesAutoUpdate=m??!0,this.wireframe=g??!1,this.transparent=v.transparent??!1,this.depthTest=v.depthTest??!0,this.depthWrite=v.depthWrite??!0,this.setValues(v)}getUniformLayout(){return null===this.uniformLayoutCache&&(this.uniformLayoutCache=gi(this.uniforms)),this.uniformLayoutCache}setUniform(e,t){const i=vr(e,t);return"texture"===i.kind?(delete this.uniforms[e],this.textures[e]=i.texture,this.uniformLayoutCache=null,this.invalidateBindingCache(),this.invalidateProgramStructureCache(),this.needsUpdate=!0,this):(delete this.textures[e],this.uniforms[e]=i.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=mr(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:gr(t.value)}])),this.textures={...e.textures},this.sceneTextures={...e.sceneTextures},this.graphTextures={...e.graphTextures},this.storageBuffers={...e.storageBuffers},this.vertexAttributes=mr(e.vertexAttributes),this.primitiveTopology=e.primitiveTopology,this.wireframe=e.wireframe,this.uniformValuesAutoUpdate=e.uniformValuesAutoUpdate,this.uniformValuesAutoVersion=e.uniformValuesAutoVersion,this.uniformLayoutCache=null,this.invalidateBindingCache(),this.invalidateProgramStructureCache(),this}clone(){return new e({vertexShader:this.vertexShader,fragmentShader:this.fragmentShader}).copy(this)}customProgramCacheKey(){return null!==this.programCacheKeyCache||(this.programCacheKeyCache=this.createProgramCacheKey(`vertex:${this.vertexShader};fragment:${this.fragmentShader};depthVertex:${this.depthVertexShader??""};depthFragment:${this.depthFragmentShader??""};pointShadowVertex:${this.pointShadowVertexShader??""};pointShadowFragment:${this.pointShadowFragmentShader??""};`)),this.programCacheKeyCache+this.getPolygonOffsetCacheKey()}getDepthProgramCacheKey(e=!1){const t=e?this.pointShadowProgramCacheKeyCache:this.depthProgramCacheKeyCache;if(null!==t)return t+this.getPolygonOffsetCacheKey();const i=(e?this.pointShadowVertexShader:this.depthVertexShader)??this.vertexShader,r=e?this.pointShadowFragmentShader:this.depthFragmentShader,n=this.createProgramCacheKey(`vertex:${i};fragment:${r??""};`);return e?this.pointShadowProgramCacheKeyCache=n:this.depthProgramCacheKeyCache=n,n+this.getPolygonOffsetCacheKey()}getPolygonOffsetCacheKey(){return this.polygonOffset&&!this.wireframe&&this.primitiveTopology.startsWith("triangle")?`polygonOffset:${Math.trunc(this.polygonOffsetUnits)}:${this.polygonOffsetFactor};`:""}createProgramCacheKey(e){const t=Object.keys(this.defines).sort((e,t)=>e.localeCompare(t));let i=e;for(const e of t)i+=`${e}:${String(this.defines[e])};`;for(const e in this.uniforms)i+=`uniform:${e}:${this.uniforms[e].type};`;for(const[e,t]of Object.entries(this.textures))i+=`texture:${e}:${Nt(t)};`;for(const[e,t]of Object.entries(this.sceneTextures))i+=`sceneTexture:${e}:${t};`;for(const[e,t]of Object.entries(this.getGraphTextureInputs()))i+=`graphTexture:${e}:${t.resource}:${t.dimension}:${t.sampleType??"float"}:${t.sampler??"filtering"}:${Number(t.requiresLatePass??!1)};`;for(const[e,t]of Object.entries(this.storageBuffers))i+=`storage:${e}:${t.type}:${t.visibility??"fragment"}:${t.access??"read"};`;for(const e of this.vertexAttributes){const t=e.defaultValue?e.defaultValue.join(","):"";i+=`attribute:${e.name}:${e.shaderLocation}:${e.format}:${e.stepMode??"vertex"}:${t};`}return i+=`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)};`,i}getTexturesList(){return null===this.textureListCache&&(this.textureListCache=Object.values(this.textures)),this.textureListCache}usesSceneTextures(){return this.usesSceneColor()||this.usesSceneDepth()}usesSceneColor(){return Object.values(this.sceneTextures).includes("sceneColor")||Object.values(this.graphTextures).some(e=>"sceneColorSnapshot"===e.resource)}usesSceneDepth(){return Object.values(this.sceneTextures).includes("sceneDepth")||Object.values(this.graphTextures).some(e=>"sceneDepthSnapshot"===e.resource)}getGraphTextureInputs(){const e={...this.graphTextures};for(const[t,i]of Object.entries(this.sceneTextures))e[t]="sceneDepth"===i?{resource:"sceneDepthSnapshot",dimension:"2d",sampleType:"unfilterable-float",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 i=2166136261;for(let r=0;r<t.entries.length;r+=1){const n=t.entries[r],a=e[n.name];if(a)switch(i=wi(i,n.offset),n.type){case"f32":case"i32":case"u32":i=bi(i,"boolean"==typeof a.value?a.value?1:0:Number(a.value));break;case"vec2<f32>":i=yi(i,a.value,2);break;case"vec3<f32>":i=yi(i,a.value,3);break;case"vec4<f32>":i=yi(i,a.value,4);break;case"mat3x3<f32>":i=yi(i,a.value,9);break;case"mat4x4<f32>":i=yi(i,a.value,16);break;default:i=wi(i,r+17)}else i=wi(i,r+1)}return i>>>0}(this.uniforms,this.getUniformLayout())}getTextureVersionsList(){const e=this.getTexturesList(),t=this.textureVersionsCache;t.length=e.length;let i=2166136261;for(let r=0;r<e.length;r+=1){const n=e[r].version;t[r]=n,i=Math.imul((i^n)>>>0,16777619)>>>0}return this.textureVersionHashCache=i,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=>function(e,t){const i=$t(e,t);return[i.viewDimension,i.sampleType,i.samplerBindingType].join(":")}(t,e)).join("|")),this.textureLayoutKeyCache}invalidateProgramStructureCache(){this.programCacheKeyCache=null,this.depthProgramCacheKeyCache=null,this.pointShadowProgramCacheKeyCache=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 fr(e){return!0===e.isWGSLShaderMaterial}function mr(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 gr(e){return Array.isArray(e)?Array.from(e):"number"==typeof e||"boolean"==typeof e?e:e.clone()}function vr(e,t){const i=wr(t)?t:null,r=null!==i&&"value"in i?i.value:t;if(function(e){return xr(e,"isTexture")}(r))return{kind:"texture",texture:r};if(!function(e){return"number"==typeof e||"boolean"==typeof e||Array.isArray(e)||xr(e,"isColor")||xr(e,"isVector2")||xr(e,"isVector3")||xr(e,"isVector4")||xr(e,"isMatrix3")||xr(e,"isMatrix4")}(r))throw new Error(`Unsupported WGSLShaderMaterial uniform "${e}". Use a number, boolean, vector, color, matrix, numeric array, or Texture.`);const n=i?.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}(n)?n: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(xr(t,"isColor"))return"vec3<f32>";if(xr(t,"isVector2"))return"vec2<f32>";if(xr(t,"isVector3"))return"vec3<f32>";if(xr(t,"isVector4"))return"vec4<f32>";if(xr(t,"isMatrix3"))return"mat3x3<f32>";if(xr(t,"isMatrix4"))return"mat4x4<f32>";throw new Error(`Cannot infer WGSL type for uniform "${e}". Provide an explicit type.`)}(e,r);return{kind:"uniform",uniform:{type:a,value:r}}}function xr(e,t){return wr(e)&&!0===e[t]}function wr(e){return"object"==typeof e&&null!==e}var br=new WeakMap,yr=1;function Sr(e){return e?"version"in e?e.version:e.data.version:0}function Cr(e){const t=Object.keys(e.attributes).sort().map(t=>{const i=e.getAttribute(t);return[t,Sr(i),i?.itemSize??0,i?.count??0].join(":")}).join("|"),i=e.index?.version??0,r=e.groups.map(e=>`${e.start}:${e.count}:${e.materialIndex??0}`).join("|");return[t,i,e.drawRange.start,e.drawRange.count,r].join(";")}function Mr(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 Pr(e){return e.startsWith("uint32")?"uint32":e.startsWith("sint32")?"sint32":"float32"}function Br(e,t){switch(t){case"uint32":return new Uint32Array(e);case"sint32":return new Int32Array(e);default:return new Float32Array(e)}}function Dr(e,t,i,r){switch(i){case"uint32":e[t]=Math.max(0,Math.round(r));break;case"sint32":e[t]=Math.trunc(r);break;default:e[t]=r}}function Ir(e,t){const i=e[0]??0;for(let r=1;r<t;r++)if((e[r]??0)!==i)return!1;return!0}function Tr(e,t){if(e.length!==t.length)return!1;for(let i=0;i<e.length;i+=1)if(e[i]!==t[i])return!1;return!0}function Rr(e,t,i,r){const n=Math.max(4,t.byteLength),a=e.createBuffer({label:r,size:4*Math.ceil(n/4),usage:i,mappedAtCreation:!0});return new Uint8Array(a.getMappedRange()).set(new Uint8Array(t.buffer,t.byteOffset,t.byteLength)),a.unmap(),a}function Vr(e){switch(e){case"vertex":return GPUShaderStage.VERTEX;case"vertex-fragment":return GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT;default:return GPUShaderStage.FRAGMENT}}function Gr(e,t){if(e.length!==t.length)return!1;for(let i=0;i<e.length;i+=1)if(e[i]!==t[i])return!1;return!0}function zr(e,t){if(!e)return!1;if(e.length!==t.length)return!1;for(let i=0;i<e.length;i+=1)if(e[i]!==t[i])return!1;return!0}function Lr(e,t,i){try{return e.beginComputePass({timestampWrites:{querySet:t,...i}}).end(),!0}catch{return!1}}function Ur(e,t,i,r){if(e instanceof Yi&&!e.normalized&&e.itemSize===i&&e.count===t&&e.array instanceof Float32Array)return e.array;const n=new Float32Array(t*i);if(!e){if(Ir(r,i))return 0!==(r[0]??0)&&n.fill(r[0]),n;for(let e=0;e<t;e+=1)n.set(r,e*i);return n}if(!e.normalized&&(e instanceof Yi?e.getComponent===Yi.prototype.getComponent:e.getComponent===Qi.prototype.getComponent)){const a=e instanceof Qi,s=a?e.data.array:e.array,o=a?e.data.stride:e.itemSize,l=a?e.offset:0,c=Math.min(e.itemSize,i);for(let a=0;a<t;a++){const t=a*o+l,u=a*i;for(let e=0;e<i;e++)n[u+e]=e<c?s[t+e]:r[e]??0;3===e.itemSize&&4===i&&(n[u+3]=r[3]??1)}return n}for(let a=0;a<t;a+=1){for(let t=0;t<i;t+=1)t<e.itemSize?n[a*i+t]=e.getComponent(a,t):n[a*i+t]=r[t]??0;3===e.itemSize&&4===i&&(n[a*i+3]=r[3]??1)}return n}function kr(e,t,i,r,n=0,a){const s=Mr(i),o=Pr(i);if(!e)return function(e,t,i,r,n,a){const s=Br(i*r,a);if(!e&&Ir(n,r)){const e=n[0]??0;if(0!==e){const t="uint32"===a?Math.max(0,Math.round(e)):"sint32"===a?Math.trunc(e):e;s.fill(t)}return s}for(let o=0;o<i;o+=1){const i=o*t,l=o*r;for(let o=0;o<r;o+=1)Dr(s,l+o,a,e&&o<t?e[i+o]??n[o]??0:n[o]??0)}return s}(void 0,0,t,s,r,o);if(0===n&&e instanceof Yi&&!e.normalized&&e.itemSize===s&&e.count===t){const t=e.array;if("float32"===o&&t instanceof Float32Array||"uint32"===o&&t instanceof Uint32Array||"sint32"===o&&t instanceof Int32Array)return t}const l=t*s,c=a?.length===l&&("float32"===o?a instanceof Float32Array:"uint32"===o?a instanceof Uint32Array:a instanceof Int32Array)?a:Br(l,o);if("float32"===o&&!e.normalized&&(e instanceof Yi?e.getComponent===Yi.prototype.getComponent:e.getComponent===Qi.prototype.getComponent)){const i=e instanceof Qi,a=i?e.data.array:e.array,o=i?e.data.stride:e.itemSize,l=i?e.offset:0,u=Math.min(s,e.itemSize);for(let i=0;i<t;i++){const t=i*s,d=i-n,h=d>=0&&d<e.count,p=d*o+l;for(let e=0;e<s;e++)c[t+e]=h&&e<u?a[p+e]:r[e]??0}return c}for(let i=0;i<t;i+=1){const t=i*s,a=i-n,l=a>=0&&a<e.count;for(let i=0;i<s;i+=1){Dr(c,t+i,o,l&&i<e.itemSize?e.getComponent(a,i):r[i]??0)}}return c}function Ar(e,t,i,r){return Number.isFinite(r)&&r>0?r:t?Math.max(0,(e.index?.count??0)-i):Math.max(0,e.getAttribute("position").count-i)}function Fr(e,t){return{start:e.drawRange.start,count:Ar(e,t,e.drawRange.start,e.drawRange.count)}}function Or(e){return e===cr?"repeat":e===ir?"mirror-repeat":"clamp-to-edge"}function Er(e){return e===rr||e===ar||e===nr?"nearest":"linear"}function jr(e){return"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap||"undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas||"undefined"!=typeof HTMLVideoElement&&e instanceof HTMLVideoElement?e:null}function $r(e){return e}function Wr(e,t,i,r,n,a,s,o,l,c,u){return e.appendMatrixAndColorValues(t,i,r,n,a,s,o,l,c,u)}function Nr(e,t,i,r,n,a,s,o,l,c,u){return e.appendMatrixAndColorValues(t.elements,i,r,n,a,s,o,l,c,u)}function _r(e,t,i){const r=e.elements;for(let e=0;e<16;e+=1)r[e]=t[i+e]??0;return e}function Hr(e){const t=br.get(e);if(void 0!==t)return t;const i=yr+=1;return br.set(e,i),i}function qr(e,t,i,r,n,a){return[Hr(e),Hr(t),i?1:0,r,n,a?Hr(a):0].join(":")}function Kr(e,t,i,r,n,a){let s=2166136261;return s=Jr(s,e),s=Jr(s,t),s=Jr(s,i?1:0),s=Jr(s,r),s=Jr(s,n),s=Jr(s,a),s}function Yr(e,t){return e.renderOrder!==t.renderOrder?e.renderOrder-t.renderOrder:(i=e.sortMaterialId,r=e.sortGeometryId,n=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,i!==l?i-l:r!==c?r-c:n!==u?n?-1:1:a!==d?a-d:s!==h?s-h:o-p);var i,r,n,a,s,o,l,c,u,d,h,p}function Zr(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:Yr(e,t)}function Xr(e){for(let t=0;t<e.length;t+=1)if(e[t].hasRenderCallbacks)return!0;return!1}function Jr(e,t){let i=Math.imul((e^t)>>>0,16777619);return i^=i>>>13,i>>>0}function Qr(e,t){return e.cameraDetailRejected===t.cameraDetailRejected&&e.detailCulling?.minScreenSize===t.detailCulling?.minScreenSize&&e.detailCulling?.maxDistance===t.detailCulling?.maxDistance&&e.detailCulling?.shadowMinScreenSize===t.detailCulling?.shadowMinScreenSize&&e.detailCulling?.shadowMaxDistance===t.detailCulling?.shadowMaxDistance&&e.renderOrder===t.renderOrder&&!e.hasRenderCallbacks&&!t.hasRenderCallbacks&&e.castShadow===t.castShadow&&e.receiveShadow===t.receiveShadow&&tn(e)===tn(t)&&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 en(e,t){return e.cameraDetailRejected===t.cameraDetailRejected&&e.detailCulling?.minScreenSize===t.detailCulling?.minScreenSize&&e.detailCulling?.maxDistance===t.detailCulling?.maxDistance&&e.detailCulling?.shadowMinScreenSize===t.detailCulling?.shadowMinScreenSize&&e.detailCulling?.shadowMaxDistance===t.detailCulling?.shadowMaxDistance&&e.renderOrder===t.renderOrder&&!e.hasRenderCallbacks&&!t.hasRenderCallbacks&&e.castShadow===t.castShadow&&e.receiveShadow===t.receiveShadow&&tn(e)===tn(t)&&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 tn(e){return e.frontFaceCW}function rn(e,t){for(let i=0;i<16;i+=1)t[i]=e[i]??0}function nn(e,t){for(let i=0;i<16;i+=1)if((e[i]??0)!==(t[i]??0))return!1;return!0}function an(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 sn(e,t,i,r){i.x<e.x&&(e.x=i.x),i.y<e.y&&(e.y=i.y),i.z<e.z&&(e.z=i.z),r.x>t.x&&(t.x=r.x),r.y>t.y&&(t.y=r.y),r.z>t.z&&(t.z=r.z)}function on(e,t){return t.multiplyMatrices(k.multiplyMatrices(T,e.projectionMatrix),e.matrixWorldInverse)}function ln(e,t){const i=e.elements,r=i[0],n=i[1],a=i[2],s=i[3],o=i[4],l=i[5],c=i[6],u=i[7],d=i[8],h=i[9],p=i[10],f=i[11],m=i[12],g=i[13],v=i[14],x=i[15];return cn(t,0,s-r,u-o,f-d,x-m),cn(t,4,s+r,u+o,f+d,x+m),cn(t,8,s+n,u+l,f+h,x+g),cn(t,12,s-n,u-l,f-h,x-g),cn(t,16,s-a,u-c,f-p,x-v),cn(t,20,a,c,p,v),t}function cn(e,t,i,r,n,a){const s=Math.hypot(i,r,n)||1;e[t+0]=i/s,e[t+1]=r/s,e[t+2]=n/s,e[t+3]=a/s}function un(e,t,i,r,n){const a=-n;for(let n=0;n<24;n+=4){if(e[n+0]*t+e[n+1]*i+e[n+2]*r+e[n+3]<a)return!1}return!0}function dn(e){return null===e.boundingSphere&&e.computeBoundingSphere(),e.boundingSphere?{center:e.boundingSphere.center.clone(),radius:e.boundingSphere.radius}:{center:new ur,radius:1}}function hn(e){const t=e.elements,i=Math.hypot(t[0],t[1],t[2]),r=Math.hypot(t[4],t[5],t[6]),n=Math.hypot(t[8],t[9],t[10]);return Math.max(i,r,n,1e-5)}function pn(e,t,i,r,n,a,s){const o=i.elements,l=a.elements,c=e.x,u=e.y,d=e.z,h=o[0]*c+o[4]*u+o[8]*d+o[12],p=o[1]*c+o[5]*u+o[9]*d+o[13],f=o[2]*c+o[6]*u+o[10]*d+o[14],m=r[n]*h+r[n+4]*p+r[n+8]*f+r[n+12],g=r[n+1]*h+r[n+5]*p+r[n+9]*f+r[n+13],v=r[n+2]*h+r[n+6]*p+r[n+10]*f+r[n+14];s.set(l[0]*m+l[4]*g+l[8]*v+l[12],l[1]*m+l[5]*g+l[9]*v+l[13],l[2]*m+l[6]*g+l[10]*v+l[14]);const x=r[n],w=r[n+4],b=r[n+8],y=r[n+1],S=r[n+5],C=r[n+9],M=r[n+2],P=r[n+6],B=r[n+10],D=x*o[0]+w*o[1]+b*o[2],I=x*o[4]+w*o[5]+b*o[6],T=x*o[8]+w*o[9]+b*o[10],R=y*o[0]+S*o[1]+C*o[2],V=y*o[4]+S*o[5]+C*o[6],G=y*o[8]+S*o[9]+C*o[10],z=M*o[0]+P*o[1]+B*o[2],L=M*o[4]+P*o[5]+B*o[6],U=M*o[8]+P*o[9]+B*o[10],k=l[0]*D+l[4]*R+l[8]*z,A=l[0]*I+l[4]*V+l[8]*L,F=l[0]*T+l[4]*G+l[8]*U,O=l[1]*D+l[5]*R+l[9]*z,E=l[1]*I+l[5]*V+l[9]*L,j=l[1]*T+l[5]*G+l[9]*U,$=l[2]*D+l[6]*R+l[10]*z,W=l[2]*I+l[6]*V+l[10]*L,N=l[2]*T+l[6]*G+l[10]*U,_=Math.hypot(k,O,$),H=Math.hypot(A,E,W),q=Math.hypot(F,j,N);return t*Math.max(_,H,q,1e-5)}function fn(e,t,i,r){const n=i.x-r,a=i.y-r,s=i.z-r,o=i.x+r,l=i.y+r,c=i.z+r;n<e.x&&(e.x=n),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 mn(e){return Math.floor(Math.max(0,e.count)/3)*Math.max(0,e.instanceCount)}function gn(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 vn(e){const t=e.customDepthMaterial;return t&&fr(t)?t:null}var xn=class{external=new WeakMap;palettes=new WeakMap;dispose(){this.palettes=new WeakMap,this.external=new WeakMap}update(e){const t=qi(e);if(t){const i=this.external.get(e);return(i?.source!==t||i.version!==t.version)&&(i?(i.source=t,i.version=t.version):this.external.set(e,{source:t,version:t.version}),!0)}const i=this.external.delete(e);i&&this.palettes.delete(e);const r=16*e.bones.length;if(e.boneInverses.length!==e.bones.length)throw new Error("Skeleton inverse-bind count does not match bones");let n=this.palettes.get(e);n&&n.values.length===r||(n={values:new Float32Array(r),published:null,source:null},this.palettes.set(e,n)),e.boneMatrices.length<r&&(e.boneMatrices=new Float32Array(r)),n.published!==e.boneMatrices&&(n.source=e.boneMatrices.length===r?e.boneMatrices:new Float32Array(e.boneMatrices.buffer,e.boneMatrices.byteOffset,r)),function(e,t=!0){const i=e.bones,r=e.boneInverses,n=e.boneMatrices;for(let e=0;e<i.length;e+=1){const t=i[e],a=t?.matrixWorld.elements,s=r[e].elements,o=16*e;if(!a){n.set(s,o);continue}const l=a[0],c=a[4],u=a[8],d=a[12],h=a[1],p=a[5],f=a[9],m=a[13],g=a[2],v=a[6],x=a[10],w=a[14],b=a[3],y=a[7],S=a[11],C=a[15],M=s[0],P=s[4],B=s[8],D=s[12],I=s[1],T=s[5],R=s[9],V=s[13],G=s[2],z=s[6],L=s[10],U=s[14],k=s[3],A=s[7],F=s[11],O=s[15];n[o]=l*M+c*I+u*G+d*k,n[o+4]=l*P+c*T+u*z+d*A,n[o+8]=l*B+c*R+u*L+d*F,n[o+12]=l*D+c*V+u*U+d*O,n[o+1]=h*M+p*I+f*G+m*k,n[o+5]=h*P+p*T+f*z+m*A,n[o+9]=h*B+p*R+f*L+m*F,n[o+13]=h*D+p*V+f*U+m*O,n[o+2]=g*M+v*I+x*G+w*k,n[o+6]=g*P+v*T+x*z+w*A,n[o+10]=g*B+v*R+x*L+w*F,n[o+14]=g*D+v*V+x*U+w*O,n[o+3]=b*M+y*I+S*G+C*k,n[o+7]=b*P+y*T+S*z+C*A,n[o+11]=b*B+y*R+S*L+C*F,n[o+15]=b*D+y*V+S*U+C*O}t&&null!==e.boneTexture&&(e.boneTexture.needsUpdate=!0)}(e,!1);let a=i;for(let t=0;t<r;t++)if(n.values[t]!==e.boneMatrices[t]){a=!0;break}return a&&n.values.set(n.source),!a&&n.published===e.boneMatrices||null===e.boneTexture||(e.boneTexture.needsUpdate=!0),n.published=e.boneMatrices,a}},wn=new WeakMap;function bn(e,t){let i=wn.get(e);return i||(i=new Set,wn.set(e,i)),i.add(t),()=>i.delete(t)}function yn(e){const t=wn.get(e);if(t){for(const e of t)e();t.clear(),wn.delete(e)}}var Sn=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/C}reset(){this.lengthFloats=0}appendMatrixAndColor(e,t,i=e,r=2,n=1,a=0){return this.appendMatrixAndColorValues(e,t[0]??1,t[1]??1,t[2]??1,t[3]??1,void 0,i,r,n,a)}appendMatrixAndColorValues(e,t,i,r,n,a=this.instanceCount,s=e,o=2,l=1,c=0){const u=this.instanceCount;this.ensureCapacity(this.lengthFloats+C);const d=this.lengthFloats;for(let t=0;t<16;t+=1)this.data[d+t]=e[t]??0;this.data[d+16]=t,this.data[d+17]=i,this.data[d+18]=r,this.data[d+19]=n,this.data[d+20]=a,this.data[d+21]=o,this.data[d+22]=l,this.data[d+23]=c;for(let t=0;t<16;t+=1)this.data[d+24+t]=s[t]??e[t]??0;return this.lengthFloats+=C,u}appendRange(e,t,i){if(i<=0)return;const r=t*C,n=r+i*C;this.ensureCapacity(this.lengthFloats+(n-r)),this.data.set(e.data.subarray(r,n),this.lengthFloats),this.lengthFloats+=n-r}appendBuilder(e){this.appendRange(e,0,e.instanceCount)}beginWriteInstances(e){const t=e*C;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 i=new Float32Array(t);i.set(this.data.subarray(0,this.lengthFloats),0),this.data=i}},Cn=class{disposed=!1;cachedInstanceData=new Sn;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;count=-1;update(e,t,i,r,n,a){const s=this.cachedInstanceData.rawData;let o=e!==this.count||s[21]!==Math.fround(r)||s[22]!==Math.fround(n)||s[23]!==a;for(let e=0;!o&&e<16;e++)o=s[e]!==Math.fround(t[e])||s[24+e]!==Math.fround(i[e]);if(o){this.cachedInstanceData.reset();for(let s=0;s<e;s++)this.cachedInstanceData.appendMatrixAndColorValues(t,1,1,1,1,s,i,r,n,a);this.count=e,this.residentBufferDirty=!0}}dispose(){this.disposed=!0;const e=this.residentInstanceBinding;e.buffer?.destroy(),e.buffer=null,e.sceneBindGroup=null,e.shadowBindGroup=null,e.shadowBindGroups.clear(),this.residentBufferSize=0,this.count=-1}};import{BufferAttribute as Mn,InterleavedBufferAttribute as Pn}from"three";var Bn=class{constructor(e){this.attributes=e;let t=0;for(const i of e){this.offsets.push(t);const e=Mr(i.format);this.components.push(e),this.kinds.push(Pr(i.format)),t+=e}this.stride=t}attributes;sources=[];versions=[];counts=[];itemSizes=[];components=[];offsets=[];kinds=[];stride;count=-1;floats=new Float32Array(0);unsigned=new Uint32Array(0);signed=new Int32Array(0);data=new Uint8Array(0);update(e,t,i,r,n=0){const a="instance"===this.attributes[0].stepMode;let s=a?Math.max(1,r):t,o=this.count<0,l=!1;for(let t=0;t<this.attributes.length;t++){const i=e.getAttribute(this.attributes[t].name);l||=void 0!==i;const r=Sr(i);a&&(s=Math.max(s,i?.count??1)),o||=this.sources[t]!==i||this.versions[t]!==r||this.counts[t]!==(i?.count??0)||this.itemSizes[t]!==(i?.itemSize??0),this.sources[t]=i,this.versions[t]=r,this.counts[t]=i?.count??0,this.itemSizes[t]=i?.itemSize??0}if(a&&(s+=i,l||(s=Math.max(s,n))),o||=this.count!==s,!o)return!1;this.count=s;const c=s*this.stride;if(this.floats.length<c){const e=new ArrayBuffer(4*c);this.floats=new Float32Array(e),this.unsigned=new Uint32Array(e),this.signed=new Int32Array(e)}this.data.buffer===this.floats.buffer&&this.data.byteLength===4*c||(this.data=new Uint8Array(this.floats.buffer,0,4*c));for(let e=0;e<this.attributes.length;e++){const t=this.sources[e],r=this.attributes[e],n=this.components[e],o=this.kinds[e],l="uint32"===o?this.unsigned:"sint32"===o?this.signed:this.floats,c=t instanceof Pn,u=t&&!t.normalized&&(c?t.getComponent===Pn.prototype.getComponent:t.getComponent===Mn.prototype.getComponent),d=t?c?t.data.array:t.array:void 0,h=t?c?t.data.stride:t.itemSize:0,p=c?t.offset:0;for(let c=0;c<s;c++){const s=c-(a?i:0),f=t&&s>=0&&s<t.count,m=c*this.stride+this.offsets[e];for(let e=0;e<n;e++){const i=f&&e<t.itemSize?u?d[s*h+p+e]:t.getComponent(s,e):r.defaultValue?.[e]??0;l[m+e]="uint32"===o?Math.max(0,Math.round(i)):"sint32"===o?Math.trunc(i):i}}}return!0}};import{FloatNode as Dn,compileNodeWebGpuExpression as In}from"three-shader-graph";var Tn=class extends Dn{constructor(e){super(),this.name=e}name;compile(){return{out:this.name}}},Rn=new Tn("radius"),Vn=new Tn("scale"),Gn=new Tn("threshold"),zn=new Tn("boundary"),Ln=new Tn("maxDistance"),Un=new Tn("distanceSquared"),kn=Ln.add(Rn),An=In(Gn.lte(0).or(Rn.multiply(Vn).gte(Gn.multiply(zn))).and(Ln.lte(0).or(Un.lte(kn.multiply(kn))))),Fn=`\nstruct ShadowCullParams {\n planes: array<vec4<f32>, 6>,\n viewer: vec4<f32>,\n diameterPerRadius: f32,\n instanceCount: u32,\n drawCount: u32,\n padding: u32,\n};\nstruct ShadowInstance { centerRadius: vec4<f32>, drawAndSource: vec4<u32> };\n@group(0) @binding(0) var<uniform> params: ShadowCullParams;\n@group(0) @binding(1) var<storage, read> metadata: array<ShadowInstance>;\n@group(0) @binding(2) var<storage, read> policies: array<vec4<f32>>;\n@group(0) @binding(3) var<storage, read_write> indirect: array<atomic<u32>>;\n@group(0) @binding(4) var<storage, read_write> indices: array<u32>;\n@group(0) @binding(5) var<storage, read_write> history: array<u32>;\n${`${An.definitions}\nfn shadowDetailVisible(radius: f32, scale: f32, threshold: f32, boundary: f32,\n maxDistance: f32, distanceSquared: f32) -> bool {\n ${An.statements}\n return ${An.expression};\n}`}\n\n@compute @workgroup_size(64)\nfn clear(@builtin(global_invocation_id) id: vec3<u32>) {\n if (id.x < params.drawCount) { atomicStore(&indirect[id.x * 5u + 1u], 0u); }\n}\n\n@compute @workgroup_size(64)\nfn main(@builtin(global_invocation_id) id: vec3<u32>) {\n if (id.x >= params.instanceCount) { return; }\n let instance = metadata[id.x];\n let draw = instance.drawAndSource.x;\n if (draw >= params.drawCount) { return; }\n let policy = policies[draw];\n if (policy.z < 0.5 || policy.w < 0.5) { history[id.x] = 0u; return; }\n let sphere = instance.centerRadius;\n let delta = sphere.xyz - params.viewer.xyz;\n let boundary = select(1.15, 0.85, history[id.x] != 0u);\n var visible = shadowDetailVisible(sphere.w, params.diameterPerRadius, policy.x,\n boundary, policy.y, dot(delta, delta));\n for (var plane = 0u; plane < 6u && visible; plane++) {\n visible = dot(params.planes[plane].xyz, sphere.xyz) + params.planes[plane].w >= -sphere.w;\n }\n history[id.x] = select(0u, 1u, visible);\n if (!visible) { return; }\n let destination = atomicLoad(&indirect[draw * 5u + 4u]);\n let slot = atomicAdd(&indirect[draw * 5u + 1u], 1u);\n indices[destination + slot] = instance.drawAndSource.y;\n}\n`,On="\n// Roughly eight f32 ULPs near depth 1. A 0.001 bias spans hundreds of\n// world units at distance with conventional perspective depth.\nconst OCCLUSION_DEPTH_BIAS: f32 = 0.000001;\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 nearestW = clip.w - radius * length(rowW);\n if (nearestW <= 0.0001) { return 0.0; }\n let depth = clip.z / clip.w;\n // For any sphere offset u, depth(u) - depth(center) equals\n // dot(rowZ - depth * rowW, u) / (clip.w + dot(rowW, u)).\n // Bound that difference, preserving the correlation of clip Z and W.\n // Independently minimizing Z and maximizing W grossly underestimates\n // distant depths and makes hidden buildings pass the occlusion test.\n let depthRadius = radius * length(rowZ - depth * rowW) / nearestW;\n return max(0.0, depth - depthRadius);\n}\n",En=`\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\n${On}\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 + OCCLUSION_DEPTH_BIAS;\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`,jn=`\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\n${On}\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 + OCCLUSION_DEPTH_BIAS;\n}\n\nfn cullInstance(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]) & 1u) != 0u) {\n return;\n }\n let drawIndex = instance.drawAndSourceIndex.x;\n let threshold = bitcast<f32>(instance.drawAndSourceIndex.z);\n let maxDistance = bitcast<f32>(instance.drawAndSourceIndex.w);\n let center = instance.centerRadius.xyz;\n let radius = instance.centerRadius.w;\n if (maxDistance > 0.0 && distance(center, temporalVisibility.currentCameraPosition.xyz) - radius > maxDistance) {\n return;\n }\n if (threshold > 0.0) {\n let vp = temporalVisibility.currentViewProj;\n let clip = vp * vec4(center, 1.0);\n let wRadius = radius * length(vec3(vp[0].w, vp[1].w, vp[2].w));\n if (clip.w - wRadius > 0.0001) {\n let projected = projectedSphereRadius(vp, clip.xyz / clip.w, clip.w, radius);\n let diameter = max(projected.x * temporalVisibility.viewportAndTime.x, projected.y * temporalVisibility.viewportAndTime.y);\n let wasDetailed = (atomicLoad(&visibleInstanceMask[instanceIndex]) & 4u) != 0u;\n let boundary = threshold * select(1.15, 0.85, wasDetailed);\n if (diameter < boundary) {\n atomicAnd(&visibleInstanceMask[instanceIndex], ~4u);\n return;\n }\n }\n }\n atomicOr(&visibleInstanceMask[instanceIndex], 4u);\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 atomicOr(&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// Only sets fitting in one workgroup may use fused clear/cull/build.\nstruct CompactIndirectArgs {\n indexCount: u32,\n instanceCount: u32,\n firstIndex: u32,\n baseVertex: i32,\n firstInstance: u32,\n};\n@group(0) @binding(10) var<storage, read_write> compactIndirectArgs: array<CompactIndirectArgs>;\n@group(0) @binding(11) var<storage, read_write> compactPostIndirectArgs: array<CompactIndirectArgs>;\n\n@compute @workgroup_size(64, 1, 1)\nfn main(@builtin(global_invocation_id) globalId: vec3<u32>) {\n let compact = (visibilityParams.flags & 8u) != 0u;\n let postpass = (visibilityParams.flags & 4u) != 0u;\n let index = globalId.x;\n if (compact && !postpass) {\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], atomicLoad(&visibleInstanceMask[index]) & 4u);\n }\n }\n if (compact) { storageBarrier(); }\n cullInstance(globalId);\n if (compact) {\n storageBarrier();\n if (index < visibilityParams.drawCount) {\n let primaryCount = atomicLoad(&visibleCounts[index]);\n let postCount = atomicLoad(&postVisibleCounts[index]);\n compactIndirectArgs[index].instanceCount = primaryCount + postCount;\n if (postpass) {\n compactPostIndirectArgs[index].instanceCount = postCount;\n compactPostIndirectArgs[index].firstInstance = compactIndirectArgs[index].firstInstance + primaryCount;\n }\n }\n }\n}\n`,$n="\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 previousModel0: vec4<f32>,\n previousModel1: vec4<f32>,\n previousModel2: vec4<f32>,\n previousModel3: 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) @invariant vec4<f32> {\n let world = rendererInstanceModelMatrix(instanceIndex) * vec4(position, 1.0);\n return shadowCamera.viewProj * world;\n}\n",Wn="\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 previousModel0: vec4<f32>,\n previousModel1: vec4<f32>,\n previousModel2: vec4<f32>,\n previousModel3: 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",Nn="\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",_n="\nstruct RendererSkinningUniforms {\n bindMatrix: mat4x4<f32>,\n bindMatrixInverse: mat4x4<f32>,\n previousBindMatrix: mat4x4<f32>,\n previousBindMatrixInverse: 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",Hn=`\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 previousModel0: vec4<f32>,\n previousModel1: vec4<f32>,\n previousModel2: vec4<f32>,\n previousModel3: 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${_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\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) @invariant vec4<f32> {\n let world = rendererInstanceModelMatrix(instanceIndex) * vec4(rendererSkinPosition(position, skinIndex, skinWeight), 1.0);\n return rendererCamera.viewProj * world;\n}\n`,qn=`\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 previousModel0: vec4<f32>,\n previousModel1: vec4<f32>,\n previousModel2: vec4<f32>,\n previousModel3: 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${_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\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`,Kn=`\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 previousModel0: vec4<f32>,\n previousModel1: vec4<f32>,\n previousModel2: vec4<f32>,\n previousModel3: 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${_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\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`,Yn="\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 Zn(e){return`\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\n fn fsMain(input: FullscreenVertexOutput) -> @location(0) vec4<f32> {\n let source = textureSample(sourceTexture, sourceSampler, input.uv);\n ${e?"return vec4(source.rgb, 1.0);":"return vec4(clamp(source.rgb, vec3(0.0), vec3(1.0)), clamp(source.a / 3.0, 0.0, 1.0));"}\n }\n`}var Xn=Zn(!1),Jn=Zn(!0),Qn=class{enabled=!0;available=!1;sets=new Map;device=null;layout=null;clear=null;cull=null;pipeline=null;frame=0;paramData=new Float32Array(32);paramInts=new Uint32Array(this.paramData.buffer);async initialize(e,t){if(!e.features.has("indirect-first-instance"))return;this.device=e,this.layout=t;const i=Array.from({length:6},(e,t)=>({binding:t,visibility:GPUShaderStage.COMPUTE,buffer:{type:0===t?"uniform":t<3?"read-only-storage":"storage"}})),r=Fn,n=$n.replace("let instance = rendererInstances[instanceIndex];","let instance = rendererInstances[rendererVisibleInstanceIndices[instanceIndex]];").replace("@vertex","@group(0) @binding(2) var<storage, read> rendererVisibleInstanceIndices: array<u32>;\n@vertex");[this.clear,this.cull,this.pipeline]=await Promise.all([_.createAsync(e,{label:"directional-shadow-clear",code:r,entryPoint:"clear",bindGroupLayoutEntries:i}),_.createAsync(e,{label:"directional-shadow-cull",code:r,bindGroupLayoutEntries:i}),W(e,{label:"directional-shadow-visible-depth",layout:e.createPipelineLayout({bindGroupLayouts:[t]}),vertex:{module:e.createShaderModule({code: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",depthBias:1,depthBiasSlopeScale:2,depthBiasClamp:0}})]),this.available=!0}buffer(e,t,i){return this.device.createBuffer({label:e,size:256*Math.ceil(Math.max(4,t)/256),usage:i})}getSet(e){let t=this.sets.get(e);if(!t){const i=new Uint32Array(5*e.draws.length);for(let t=0;t<e.draws.length;t++){const r=e.draws[t];i.set([r.count,0,r.start,0,r.instanceStart],5*t)}t={materials:[],depthDrawIndices:[],materialVersion:0,preparedFrame:-1,eligibleDrawCount:0,triangleCount:0,commands:i,policies:this.buffer(`${e.label}-shadow-policies`,16*e.draws.length,GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST),policyData:new Float32Array(4*e.draws.length),eligibility:new Uint8Array(e.draws.length),eligibilityVersion:0,layers:new Map},this.sets.set(e,t),e.disposeDirectionalGpuShadows=()=>this.disposeSet(e)}return t}eligible(e){if(!e.indexed||e.wireframe||e.skinning||e.hasRenderCallbacks||"triangle-list"!==e.material.primitiveTopology||"packed"!==e.residentInstanceBinding?.mode)return!1;const t=e.customDepthMaterial??(null!==e.material.depthVertexShader?e.material:null);return!t||"triangle-list"===t.primitiveTopology&&!t.vertexAttributes.some(e=>"instance"===e.stepMode)}beginFrame(){this.frame++}prepareCascade(e,t,i,r){for(let t=0;t<6;t++){const i=e.planes[t],r=4*t;this.paramData[r]=i.normal.x,this.paramData[r+1]=i.normal.y,this.paramData[r+2]=i.normal.z,this.paramData[r+3]=i.constant}this.paramData[24]=i.x,this.paramData[25]=i.y,this.paramData[26]=i.z,this.paramData[28]=Math.max(Math.abs(t.projectionMatrix.elements[0]),Math.abs(t.projectionMatrix.elements[5]))*r}prepareSet(e,t,i){if(i.preparedFrame===this.frame)return;if(-1===i.preparedFrame){for(let e=0;e<t.draws.length;e++){const r=t.draws[e],n=r.detailCulling,a=this.eligible(r)?1:0,s=4*e;i.eligibility[e]=a,a&&(i.eligibleDrawCount++,r.castShadow&&(i.triangleCount+=mn(r)),(r.customDepthMaterial||null!==r.material.depthVertexShader)&&i.depthDrawIndices.push(e)),i.policyData[s]=n.shadowMinScreenSize,i.policyData[s+1]=n.shadowMaxDistance,i.policyData[s+2]=r.castShadow?1:0,i.policyData[s+3]=a,i.materials[e]=null}this.device.queue.writeBuffer(i.policies,0,i.policyData)}let r=!1;for(const n of i.depthDrawIndices){const a=t.draws[n],s=a.customDepthMaterial??a.material,o=e.getDepthPassMaterialResourceForDraw(s,"directionalShadow",a,"packed-visible");i.materials[n]!==o&&(r=!0),i.materials[n]=o}r&&i.materialVersion++,i.preparedFrame=this.frame}prepare(e,t,i,r,n){if(!this.enabled||!this.available||i.instanceCount>64*this.device.limits.maxComputeWorkgroupsPerDimension)return null;const a=this.getSet(i);this.prepareSet(e,i,a);let s=a.layers.get(r);if(!s){const e=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST|GPUBufferUsage.COPY_SRC,t=this.buffer(`${i.label}-shadow-cull-params`,128,GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST),n=this.buffer(`${i.label}-shadow-indirect`,a.commands.byteLength,e|GPUBufferUsage.INDIRECT),o=this.buffer(`${i.label}-shadow-indices`,4*i.instanceCount,e),l=this.buffer(`${i.label}-shadow-history`,4*i.instanceCount,e);this.device.queue.writeBuffer(n,0,a.commands);const c=[t,i.instanceVisibilityResource.instanceMetadataBuffer,a.policies,n,o,l].map((e,t)=>({binding:t,resource:{buffer:e}}));s={params:t,indirect:n,indices:o,history:l,clearGroup:this.clear.createBindGroup(this.device,c),cullGroup:this.cull.createBindGroup(this.device,c),shadowGroup:this.device.createBindGroup({layout:this.layout,entries:[{binding:0,resource:{buffer:r}},{binding:1,resource:{buffer:i.instanceBuffer}},{binding:2,resource:{buffer:o}}]}),bundle:null,materials:[],eligibilityVersion:-1,materialVersion:-1,bundles:[],materialCacheKey:`directional-shadow-gpu-${a.layers.size}`},a.layers.set(r,s),i.depthMaterialResources.set(s.materialCacheKey,s.materials)}this.paramInts[29]=i.instanceCount,this.paramInts[30]=i.draws.length,this.device.queue.writeBuffer(s.params,0,this.paramData);const o=s.materialVersion!==a.materialVersion;if(o){for(let e=0;e<a.materials.length;e++)s.materials[e]=a.materials[e];s.materialVersion=a.materialVersion}s.bundle&&s.eligibilityVersion===a.eligibilityVersion&&!o||this.buildBundle(e,i,a,s);const l=n??t.beginComputePass({label:`${i.label}-directional-shadow-selection`});return l.setPipeline(this.clear.pipeline),l.setBindGroup(0,s.clearGroup),l.dispatchWorkgroups(Math.ceil(i.draws.length/64)),l.setPipeline(this.cull.pipeline),l.setBindGroup(0,s.cullGroup),l.dispatchWorkgroups(Math.ceil(i.instanceCount/64)),n||l.end(),a.eligibility}buildBundle(e,t,i,r){const n=this.device.createRenderBundleEncoder({colorFormats:[],depthStencilFormat:"depth32float",sampleCount:1});let a=null,s=null,o=null;for(let l=0;l<t.draws.length;l++){if(!i.eligibility[l])continue;const c=t.draws[l],u=r.materials[l],d=u?.pipeline??this.pipeline;d!==a&&(n.setPipeline(d),Fi(n,0,r.shadowGroup),a=d,s=null,o=null),u&&s!==u.bindGroup&&(n.setBindGroup(1,u.bindGroup),s=u.bindGroup),o!==c.geometryKey&&(e.bindGeometryVertexBuffers(n,c.geometry,c.geometryResource,u?.vertexAttributes??z,c.instanceStart,c.instanceCount,!1),o=c.geometryKey),n.drawIndexedIndirect(r.indirect,20*l)}r.bundle=n.finish(),r.bundles[0]=r.bundle,r.eligibilityVersion=i.eligibilityVersion}submit(e,t,i,r){const n=this.sets.get(t),a=n?.layers.get(i);return!!(this.enabled&&this.available&&n&&a)&&(ji(e,a.bundles),r.drawCallCount+=n.eligibleDrawCount,r.directionalShadowGpuDraws=(r.directionalShadowGpuDraws??0)+n.eligibleDrawCount,r.triangleCount+=n.triangleCount,!0)}disposeSet(e){const t=this.sets.get(e);if(t){t.policies.destroy();for(const e of t.layers.values())e.params.destroy(),e.indirect.destroy(),e.indices.destroy(),e.history.destroy();t.layers.clear(),this.sets.delete(e),e.disposeDirectionalGpuShadows=void 0}}dispose(){for(const e of this.sets.keys())this.disposeSet(e);this.available=!1}},ea=class{constructor(e,t=1048576){this.device=e,this.alignment=Math.max(64,e.limits.minStorageBufferOffsetAlignment??256),this.maxBytes=Math.min(e.limits.maxStorageBufferBindingSize??134217728,e.limits.maxBufferSize??268435456),this.pageBytes=Math.floor(Math.min(t,this.maxBytes)/this.alignment)*this.alignment}device;pages=new Set;dirtyPages=new Set;alignment;pageBytes;maxBytes;allocate(e){const t=64*e,i=Math.ceil(t/this.alignment)*this.alignment;if(!e||i>this.maxBytes)throw new Error("Skeleton exceeds GPU palette buffer limits");let r,n=-1;for(const e of this.pages)if(n=e.free.findIndex(e=>e.size>=i),n>=0){r=e;break}if(!r){const e=Math.max(this.pageBytes,i),t=t=>this.device.createBuffer({label:t,size:e,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST});r={current:t("renderer-skinning-current-page"),previous:t("renderer-skinning-previous-page"),currentData:new Float32Array(e/4),previousData:new Float32Array(e/4),currentStart:1/0,currentEnd:0,previousStart:1/0,previousEnd:0,free:[{offset:0,size:e}],count:0},this.pages.add(r),n=0}const a=r.free[n],s=a.offset;return a.offset+=i,a.size-=i,a.size||r.free.splice(n,1),r.count++,{page:r,offset:s,byteLength:t,reservedBytes:i,currentBinding:{buffer:r.current,offset:s,size:t},previousBinding:{buffer:r.previous,offset:s,size:t}}}stage(e,t,i){const{page:r,offset:n,byteLength:a}=e;this.dirtyPages.add(r);const s=i?r.previousData:r.currentData,o=n/4,l=a/4;if(t.length===l)s.set(t,o);else for(let e=0;e<l;e++)s[o+e]=t[e];i?(r.previousStart=Math.min(r.previousStart,n),r.previousEnd=Math.max(r.previousEnd,n+a)):(r.currentStart=Math.min(r.currentStart,n),r.currentEnd=Math.max(r.currentEnd,n+a))}flush(){for(const e of this.dirtyPages)e.previousEnd>e.previousStart&&(this.device.queue.writeBuffer(e.previous,e.previousStart,e.previousData.buffer,e.previousStart,e.previousEnd-e.previousStart),e.previousStart=1/0,e.previousEnd=0),e.currentEnd>e.currentStart&&(this.device.queue.writeBuffer(e.current,e.currentStart,e.currentData.buffer,e.currentStart,e.currentEnd-e.currentStart),e.currentStart=1/0,e.currentEnd=0);this.dirtyPages.clear()}release(e){const{page:t,offset:i,reservedBytes:r}=e;if(0===--t.count)return t.current.destroy(),t.previous.destroy(),this.pages.delete(t),void this.dirtyPages.delete(t);const n=t.free;let a=0;for(;a<n.length&&n[a].offset<i;)a++;n.splice(a,0,{offset:i,size:r}),a>0&&n[a-1].offset+n[a-1].size===n[a].offset&&(n[a-1].size+=n[a].size,n.splice(a,1),a--),a+1<n.length&&n[a].offset+n[a].size===n[a+1].offset&&(n[a].size+=n[a+1].size,n.splice(a+1,1))}dispose(){for(const e of this.pages)e.current.destroy(),e.previous.destroy();this.pages.clear(),this.dirtyPages.clear()}},ta=class{records=new WeakMap;get(e,t,i,r,n,a,s){let o=this.records.get(e);o||(o=[],this.records.set(e,o));let l=o[t];if(!l||l.material!==i||l.customDepthMaterial!==s||l.indexed!==r||l.start!==n||l.count!==a){const c=Hr(i),u=Hr(e),d=s?Hr(s):0;l={material:i,customDepthMaterial:s,indexed:r,start:n,count:a,materialId:c,geometryId:u,depthMaterialId:d,batchKey:qr(i,e,r,n,a,s),batchHash:Kr(c,u,r,n,a,d)},o[t]=l}return l}},ia=class{constructor(e=128){this.pageCapacity=e}pageCapacity;pages=new Set;get instanceCapacity(){return this.pages.size>0?this.pageCapacity:0}allocate(){let e;for(const t of this.pages)if(t.free.length){e=t;break}if(!e){const t=new Sn(this.pageCapacity*C);t.beginWriteInstances(this.pageCapacity),e={cachedInstanceData:t,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,residentBufferDirtyRange:{start:1/0,end:0},free:Array.from({length:this.pageCapacity},(e,t)=>this.pageCapacity-t-1),count:0,queuedExtraction:-1},this.pages.add(e)}return e.count++,{page:e,index:e.free.pop()}}write(e,t,i,r,n,a,s,o){const l=e.page,c=l.cachedInstanceData.rawData,u=e.index*C;let d=!1;for(let s=0;s<C;s++){const o=Math.fround(s<16?t[s]:s>=24?i[s-24]:s<20?1:20===s?e.index:21===s?r:22===s?n:a);c[u+s]!==o&&(c[u+s]=o,d=!0)}d&&(l.residentBufferDirty=!0,l.residentBufferDirtyRange.start=Math.min(l.residentBufferDirtyRange.start,e.index),l.residentBufferDirtyRange.end=Math.max(l.residentBufferDirtyRange.end,e.index+1)),this.queueUpload(e,s,o)}queueUpload(e,t,i){const r=e.page;!r.residentBufferDirty&&r.residentInstanceBinding.buffer||r.queuedExtraction===t||(r.queuedExtraction=t,i.push(r))}release(e){const t=e.page;t.free.push(e.index),0===--t.count&&(t.residentInstanceBinding.buffer?.destroy(),t.residentInstanceBinding.buffer=null,t.residentInstanceBinding.sceneBindGroup=null,t.residentInstanceBinding.shadowBindGroup=null,t.residentInstanceBinding.shadowBindGroups.clear(),this.pages.delete(t))}dispose(){for(const e of this.pages)e.residentInstanceBinding.buffer?.destroy();this.pages.clear()}};function ra(e=4){let t=performance.now()+e;return()=>{if(!(performance.now()<t))return new Promise(i=>setTimeout(()=>{t=performance.now()+e,i()},0))}}var na=class e{constructor(e,t,i,r){this.device=e,this.camera=t,this.lights=i,this.pipeline=r}device;camera;lights;pipeline;texture=null;textureView=null;bindGroup=null;columns=0;rows=0;static async createAsync(t,i,r){const n=await N(t,{label:"tiled-point-lights",layout:"auto",compute:{module:t.createShaderModule({label:"tiled-point-lights",code:"\nstruct Camera {\n viewProj: mat4x4<f32>,\n position: vec4<f32>,\n viewport: vec4<f32>,\n};\n@group(0) @binding(0) var<uniform> camera: Camera;\n@group(0) @binding(1) var<uniform> lights: array<vec4<f32>, 1001>;\n@group(0) @binding(2) var masks: texture_storage_2d<rg32uint, write>;\n\nfn normalizePlane(plane: vec4<f32>) -> vec4<f32> {\n return plane / max(length(plane.xyz), 1e-20);\n}\n\n@compute @workgroup_size(8, 8)\nfn main(@builtin(global_invocation_id) id: vec3<u32>) {\n if (any(id.xy >= textureDimensions(masks))) { return; }\n let lo = vec2<f32>(id.xy * 16u) / camera.viewport.xy;\n let hi = min(vec2<f32>((id.xy + 1u) * 16u), camera.viewport.xy) / camera.viewport.xy;\n let rows = transpose(camera.viewProj);\n let left = normalizePlane(rows[0] - (lo.x * 2.0 - 1.0) * rows[3]);\n let right = normalizePlane((hi.x * 2.0 - 1.0) * rows[3] - rows[0]);\n let top = normalizePlane((1.0 - lo.y * 2.0) * rows[3] - rows[1]);\n let bottom = normalizePlane(rows[1] - (1.0 - hi.y * 2.0) * rows[3]);\n var mask = vec2<u32>(0u);\n let count = min(u32(lights[1].y), 64u);\n for (var i = 0u; i < count; i++) {\n let center = vec4<f32>(lights[34u + i].xyz, 1.0);\n // Use the authored attenuation cutoff, NOT the finite shadow-camera range.\n let radius = lights[162u + i].x;\n let distance = min(min(dot(left, center), dot(right, center)), min(dot(top, center), dot(bottom, center)));\n // A small conservative tolerance avoids precision cracks on tile boundaries.\n if (radius <= 0.0 || distance >= -radius - max(0.001, radius * 1e-5)) {\n mask[i >> 5u] |= 1u << (i & 31u);\n }\n }\n textureStore(masks, vec2<i32>(id.xy), vec4<u32>(mask, 0u, 0u));\n}\n"}),entryPoint:"main"}});return new e(t,i,r,n)}get view(){if(!this.textureView)throw new Error("Tiled lighting has not been sized.");return this.textureView}resize(e,t){const i=Math.max(1,Math.ceil(e/16)),r=Math.max(1,Math.ceil(t/16));return(i!==this.columns||r!==this.rows)&&(this.texture?.destroy(),this.columns=i,this.rows=r,this.texture=this.device.createTexture({label:"tiled-point-light-masks",size:[i,r],format:"rg32uint",usage:GPUTextureUsage.STORAGE_BINDING|GPUTextureUsage.TEXTURE_BINDING}),this.textureView=this.texture.createView(),this.bindGroup=this.device.createBindGroup({layout:this.pipeline.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:this.camera}},{binding:1,resource:{buffer:this.lights}},{binding:2,resource:this.textureView}]}),!0)}execute(e){const t=e.beginComputePass({label:"TiledPointLightsPass"});t.setPipeline(this.pipeline),t.setBindGroup(0,this.bindGroup),t.dispatchWorkgroups(Math.ceil(this.columns/8),Math.ceil(this.rows/8)),t.end()}destroy(){this.texture?.destroy()}};import{AdditiveBlending as aa,BackSide as sa,BufferAttribute as oa,BufferGeometry as la,Color as ca,DoubleSide as ua,InstancedBufferAttribute as da,InstancedBufferGeometry as ha,InstancedMesh as pa,MultiplyBlending as fa,Matrix4 as ma,Mesh as ga,OrthographicCamera as va,PerspectiveCamera as xa,SkinnedMesh as wa,Sphere as ba,SubtractiveBlending as ya,Vector2 as Sa,Vector3 as Ca,Vector4 as Ma,ShaderMaterial as Pa}from"three";var Ba=/^[A-Za-z_][A-Za-z0-9_]*$/;function Da(e,t={},i={}){const r=function(e){const t=new Map;for(const[i,r]of Object.entries(e))Ba.test(i)&&!1!==r&&null!=r&&t.set(i,{name:i,parameters:null,body:Ia(r)});return t}(t),n=new Map,a=[],s=[],o=e.split(/\r?\n/),l=i.sourceName??"shader";for(let e=0;e<o.length;e+=1){const t=o[e],i=Ta(t),c=Va(a);if(!i){s.push(c?za(t,r,n):"");continue}const{name:u,rest:d}=i;switch(u){case"define":if(c){const t=Ra(d,r,l,e+1),i=r.get(t);null===i.parameters?n.delete(t):n.set(t,i)}s.push("");break;case"undef":c&&(r.delete(d.trim()),n.delete(d.trim())),s.push("");break;case"ifdef":{const e=c,t=e&&r.has(d.trim());a.push({parentActive:e,active:t,branchTaken:t,elseSeen:!1}),s.push("");break}case"ifndef":{const e=c,t=e&&!r.has(d.trim());a.push({parentActive:e,active:t,branchTaken:t,elseSeen:!1}),s.push("");break}case"if":{const e=c,t=e&&ja(d,r);a.push({parentActive:e,active:t,branchTaken:t,elseSeen:!1}),s.push("");break}case"elif":{const t=Ga(a,l,e+1,u);if(t.elseSeen)throw new Error(`${l}:${e+1}: #elif after #else`);const i=t.parentActive&&!t.branchTaken&&ja(d,r);t.active=i,t.branchTaken=t.branchTaken||i,s.push("");break}case"else":{const t=Ga(a,l,e+1,u);if(t.elseSeen)throw new Error(`${l}:${e+1}: duplicate #else`);t.active=t.parentActive&&!t.branchTaken,t.branchTaken=!0,t.elseSeen=!0,s.push("");break}case"endif":Ga(a,l,e+1,u),a.pop(),s.push("");break;case"error":if(c)throw new Error(`${l}:${e+1}: ${d.trim()||"#error"}`);s.push("");break;case"warning":case"line":case"version":case"pragma":s.push("");break;default:if(c)throw new Error(`${l}:${e+1}: unsupported preprocessor directive #${u}`);s.push("")}}if(a.length>0)throw new Error(`${l}: unterminated preprocessor conditional`);return s.join("\n")}function Ia(e){return"boolean"==typeof e?e?"1":"0":String(e)}function Ta(e){const t=/^\s*#\s*([A-Za-z_][A-Za-z0-9_]*)(.*)$/.exec(e);return t?{name:t[1],rest:t[2]??""}:null}function Ra(e,t,i,r){const n=/^\s*([A-Za-z_][A-Za-z0-9_]*)(.*)$/.exec(e);if(!n)throw new Error(`${i}:${r}: invalid #define`);const a=n[1],s=n[2]??"";if(s.startsWith("(")){const e=Ea(s,0);if(e<0)throw new Error(`${i}:${r}: invalid function-like #define ${a}`);const n=s.slice(1,e).trim(),o=0===n.length?[]:n.split(",").map(e=>e.trim());for(const e of o)if(!Ba.test(e))throw new Error(`${i}:${r}: invalid macro parameter "${e}"`);return t.set(a,{name:a,parameters:o,body:Wa(s.slice(e+1)).trim()||"1"}),a}return t.set(a,{name:a,parameters:null,body:Wa(s).trim()||"1"}),a}function Va(e){for(const t of e)if(!t.active)return!1;return!0}function Ga(e,t,i,r){const n=e[e.length-1];if(!n)throw new Error(`${t}:${i}: #${r} without matching #if`);return n}function za(e,t,i){let r=e;for(let e=0;e<8;e+=1){const e=r;if(r=Ua(r,i),r=La(r,t),r===e)return r}return r}function La(e,t){let i=null,r=0;for(let n=0;n<e.length;){let a=e.charCodeAt(n);if(a>=65&&a<=90||a>=97&&a<=122||95===a){const s=n++;let o=a>=65&&a<=90;for(;n<e.length;)if(a=e.charCodeAt(n),a>=65&&a<=90)n++;else if(a>=97&&a<=122)o=!1,n++;else{if(!(a>=48&&a<=57||95===a))break;n++}if(!o)continue;const l=e.slice(s,n),c=t.get(l);null===c?.parameters&&(i??=[],i.push(e.slice(r,s),c.body),r=n)}else n++}return null===i?e:(i.push(e.slice(r)),i.join(""))}function Ua(e,t){if(0===t.size||!e.includes("("))return e;let i=e;for(const e of t.values())null!==e.parameters&&(i=ka(i,e));return i}function ka(e,t){let i="",r=0;for(;r<e.length;){const n=Aa(e,t.name,r);if(n<0){i+=e.slice(r);break}let a=n+t.name.length;for(;/\s/.test(e[a]??"");)a+=1;if("("!==e[a]){i+=e.slice(r,n+t.name.length),r=n+t.name.length;continue}const s=Ea(e,a);if(s<0){i+=e.slice(r);break}const o=Oa(e.slice(a+1,s));i+=e.slice(r,n),i+=Fa(t,o),r=s+1}return i}function Aa(e,t,i){let r=e.indexOf(t,i);for(;r>=0;){const i=r>0?e[r-1]:"",n=e[r+t.length]??"";if(!/[A-Za-z0-9_]/.test(i)&&!/[A-Za-z0-9_]/.test(n))return r;r=e.indexOf(t,r+t.length)}return-1}function Fa(e,t){let i=e.body;const r=e.parameters??[];for(let e=0;e<r.length;e+=1){const n=r[e],a=t[e]?.trim()??"";i=i.replace(new RegExp(`\\b${Na(n)}\\b`,"g"),a)}return i}function Oa(e){const t=[];let i=0,r=0;for(let n=0;n<e.length;n+=1){const a=e[n];"("===a?i+=1:")"===a?i-=1:","===a&&0===i&&(t.push(e.slice(r,n)),r=n+1)}return(e.length>0||r>0)&&t.push(e.slice(r)),t}function Ea(e,t){let i=0;for(let r=t;r<e.length;r+=1){const t=e[r];if("("===t)i+=1;else if(")"===t&&(i-=1,0===i))return r}return-1}function ja(e,t){const i=function(e){const t=[];let i=0;for(;i<e.length;){const r=e[i];if(/\s/.test(r)){i+=1;continue}const n=e.slice(i,i+2);if(["&&","||","==","!=","<=",">="].includes(n)){t.push({type:"operator",value:n}),i+=2;continue}if("!<>+-*/%".includes(r)){t.push({type:"operator",value:r}),i+=1;continue}if("("===r||")"===r){t.push({type:"paren",value:r}),i+=1;continue}const a=/^(?:0x[0-9A-Fa-f]+|\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)/.exec(e.slice(i));if(a){t.push({type:"number",value:a[0]}),i+=a[0].length;continue}const s=/^[A-Za-z_][A-Za-z0-9_]*/.exec(e.slice(i));s?(t.push({type:"identifier",value:s[0]}),i+=s[0].length):i+=1}return t}(Wa(e));return 0!==new $a(i,t).parseExpression()}var $a=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 i=t.startsWith("0x")?Number.parseInt(t,16):Number.parseFloat(t);return Number.isFinite(i)?i: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 Wa(e){const t=e.indexOf("//");return t>=0?e.slice(0,t):e}function Na(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var _a=/(?!\s*@invariant)\s+(?=(?:[A-Za-z_]\w*\s*:|vec4(?:\s*<\s*f32\s*>|f)\b))/y;function Ha(e){return 32===e||9===e||10===e||13===e}var qa=class{passes=[];topologies=[];executionSnapshots=[];matchesTopology(e){if(e.passes.length!==this.passes.length)return!1;for(let t=0;t<this.passes.length;t+=1){const i=this.passes[t],r=e.passes[t];if(i.name!==r.name||!this.matchesResources(i.reads,r.reads)||!this.matchesResources(i.writes,r.writes)||!this.matchesResources(i.dependsOn,r.dependsOn))return!1}return!0}matchesResources(e,t){if((e?.length??0)!==t.length)return!1;for(let i=0;i<t.length;i+=1)if(e[i]!==t[i])return!1;return!0}addPass(e){this.passes.push(e)}async executeAsync(e,t){const i=this.createExecutionSnapshot(t),r=t?.end?performance.now():0;try{t?.begin?.(i,e);for(let r=0;r<i.length;r+=1){const n=i[r];t?.beforePass?.(n,r,e);const a=t?.afterPass?performance.now():0;n.prepare&&await n.prepare(e),n.execute(e),t?.afterPass?.(n,r,performance.now()-a,e)}t?.end?.(i,performance.now()-r,e)}finally{this.releaseExecutionSnapshot(i,t)}}execute(e,t){const i=this.createExecutionSnapshot(t),r=t?.end?performance.now():0;try{t?.begin?.(i,e);for(let r=0;r<i.length;r+=1){const n=i[r];t?.beforePass?.(n,r,e);const a=t?.afterPass?performance.now():0;n.execute(e),t?.afterPass?.(n,r,performance.now()-a,e)}t?.end?.(i,performance.now()-r,e)}finally{this.releaseExecutionSnapshot(i,t)}}reset(){this.passes.length=0}createExecutionSnapshot(e){const t=this.resolveExecutionOrder(),i=e?[]:this.executionSnapshots.pop()??[];i.length=t.length;for(let e=0;e<t.length;e+=1)i[e]=this.passes[t[e]];return i}releaseExecutionSnapshot(e,t){if(t)return;const i=e;i.fill(void 0),this.executionSnapshots.push(i)}resolveExecutionOrder(){for(let e=0;e<this.topologies.length;e+=1){const t=this.topologies[e];if(this.matchesTopology(t)){for(let t=e;t>0;t-=1)this.topologies[t]=this.topologies[t-1];return this.topologies[0]=t,t.executionOrder}}const e=new Map,t=new Map,i=new Map,r=new Map;for(let r=0;r<this.passes.length;r+=1){const n=this.passes[r];e.set(n.name,r),t.set(n.name,new Set(n.dependsOn??[])),i.set(n.name,new Set)}for(const e of this.passes){const i=t.get(e.name);for(const t of e.reads??[]){const n=r.get(t);n&&n!==e.name&&i.add(n)}for(const t of e.writes??[]){const n=r.get(t);n&&n!==e.name&&i.add(n),r.set(t,e.name)}}for(const[e,r]of t)for(const t of r){const r=i.get(t);if(!r)throw new Error(`RenderGraph dependency "${t}" for pass "${e}" is missing.`);r.add(e)}const n=Array.from(t.entries()).filter(([,e])=>0===e.size).map(([e])=>e),a=[];for(let r=0;r<n.length;r+=1){const s=n[r];a.push(e.get(s));for(const e of i.get(s)){const i=t.get(e);i.delete(s),0===i.size&&n.push(e)}}if(a.length!==this.passes.length)throw new Error("RenderGraph contains a dependency cycle.");const s={passes:this.passes.map(e=>({name:e.name,reads:Array.from(e.reads??[]),writes:Array.from(e.writes??[]),dependsOn:Array.from(e.dependsOn??[])})),executionOrder:a};return this.topologies.unshift(s),this.topologies.length>8&&this.topologies.pop(),a}};import{CubeUVReflectionMapping as Ka,HalfFloatType as Ya,LinearFilter as Za,LinearSRGBColorSpace as Xa,RGBAFormat as Ja,Texture as Qa}from"three";var es=[.125,.215,.35,.446,.526,.582],ts=20,is=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]]}(),rs=class{constructor(e,t=20){this.context=e;const{device:i}=e,r=Math.max(1,Math.min(20,Math.floor(t)));this.maxBlurSamples=r,this.equirectBindGroupLayout=i.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}},{binding:1,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"unfilterable-float",viewDimension:"2d"}}]}),this.blurBindGroupLayout=i.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=ns(i,this.equirectBindGroupLayout,os,"pmrem-equirectangular"),this.blurPipeline=ns(i,this.blurBindGroupLayout,ls.replaceAll("PMREM_MAX_SAMPLES",String(r)),"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 i=2**Math.floor(Math.log2(Math.max(16,Math.floor(t.width/4)))),r=Math.floor(Math.log2(i)),n=function(e){const t=[];for(let i=e;i>=4;i-=1){const r=2**i;t.push({mip:i,size:r,sigma:i===e?0:1/r})}for(let e=0;e<es.length;e+=1)t.push({mip:4-e-1,size:16,sigma:es[e]});return t}(r),a=3*Math.max(i,112),s=4*i,{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=as(o,new Float32Array([t.width,t.height,i,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*i,2*i,0,1),g.setScissorRect(0,0,3*i,2*i),g.setPipeline(this.equirectPipeline),g.setBindGroup(0,m),g.draw(36),g.end();for(let e=1;e<n.length;e+=1){const t=n[e-1],i=n[e],o=Math.sqrt(i.sigma*i.sigma-t.sigma*t.sigma),l=is[(n.length-e-1)%is.length];this.encodeBlurPass({encoder:h,source:c,target:u,sampler:d,atlasWidth:a,atlasHeight:s,maxMip:r,inputLevel:t,outputLevel:i,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:r,inputLevel:i,outputLevel:i,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 v=new Qa;return v.image={width:a,height:s},v.name="PMREM.cubeUv",v.mapping=Ka,v.format=Ja,v.type=Ya,v.colorSpace=Xa,v.minFilter=Za,v.magFilter=Za,v.generateMipmaps=!1,v.needsUpdate=!0,this.context.registerTextureResource(v,{version:v.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:v,dispose:()=>{c.destroy(),v.dispose()}}}encodeBlurPass(e){const{encoder:t,source:i,target:r,sampler:n,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),v=u/g,x=Math.min(this.maxBlurSamples,1+Math.floor(3*v)),w=function(e,t){const i=new Float32Array(ts);let r=0;for(let n=0;n<ts;n+=1){const a=n/e,s=Math.exp(-a*a/2);i[n]=s,0===n?r+=s:n<t&&(r+=2*s)}for(let e=0;e<i.length;e+=1)i[e]/=r;return i}(v,x),b=as(this.context.device,function(e){const t=new ArrayBuffer(144),i=new DataView(t);return i.setFloat32(0,e.atlasWidth,!0),i.setFloat32(4,e.atlasHeight,!0),i.setFloat32(8,e.outputFaceSize,!0),i.setFloat32(12,e.inputMip,!0),i.setFloat32(16,e.dTheta,!0),i.setUint32(20,e.sampleCount,!0),i.setUint32(24,e.latitudinal?1:0,!0),i.setFloat32(28,e.maxMip,!0),i.setFloat32(32,e.poleAxis[0],!0),i.setFloat32(36,e.poleAxis[1],!0),i.setFloat32(40,e.poleAxis[2],!0),new Float32Array(t,48,ts).set(e.weights),new Float32Array(t)}({atlasWidth:a,atlasHeight:s,outputFaceSize:c.size,inputMip:l.mip,dTheta:g,sampleCount:x,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:i.createView()},{binding:2,resource:n}]}),S=3*c.size*Math.max(0,4-c.mip),C=4*(2**o-c.size),M=t.beginRenderPass({colorAttachments:[{view:r.createView(),loadOp:p?"clear":"load",storeOp:"store",clearValue:[0,0,0,1]}]});M.setViewport(S,C,3*c.size,2*c.size,0,1),M.setScissorRect(S,C,3*c.size,2*c.size),M.setPipeline(this.blurPipeline),M.setBindGroup(0,y),M.draw(36),M.end()}};function ns(e,t,i,r){const n=e.createShaderModule({code:i,label:`${r}-shader`});return"function"==typeof n.getCompilationInfo&&n.getCompilationInfo().then(e=>{const t=e.messages.filter(e=>"error"===e.type);t.length>0&&console.error(`[WebGpuPMREMGenerator] ${r} WGSL compilation failed.`,t)}),e.createRenderPipeline({label:r,layout:e.createPipelineLayout({bindGroupLayouts:[t]}),vertex:{module:n,entryPoint:"vs"},fragment:{module:n,entryPoint:"fs",targets:[{format:"rgba16float"}]},primitive:{topology:"triangle-list"}})}function as(e,t){const i=e.createBuffer({size:t.byteLength,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST});return e.queue.writeBuffer(i,0,t.buffer,t.byteOffset,t.byteLength),i}var ss="\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",os=`${ss}\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`,ls=`${ss}\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`;var cs="\n let offset0 = vec2(-filterOffset.x, 0.0);\n let offset1 = vec2(filterOffset.x, 0.0);\n let offset2 = vec2(0.0, -filterOffset.y);\n let offset3 = vec2(0.0, filterOffset.y);";function us(e,t,i){if("basic"===e)return`\n let pixel = vec2<i32>(clamp(uv * dims, vec2(0.0), dims - vec2(1.0)));\n let closestDepth = textureLoad(${t}, pixel, i32(lightIndex), 0);\n let shadow = select(0.0, 1.0, depth <= closestDepth);`;const r=`\n let center = textureSampleCompareLevel(${t}, rendererShadowSampler, uv, i32(lightIndex), depth);`;if("pcf-2x2"===e)return r+"\n let shadow = center;";const n=[0,1,2,3].map(e=>`\n let uv${e} = clamp(uv + offset${e}, vec2(0.0), vec2(1.0));\n let tap${e} = textureSampleCompareLevel(${t}, rendererShadowSampler, uv${e}, i32(lightIndex),\n depth${i?` + dot(depthGradient, uv${e} - uv)`:""});`).join("\n");return`${r}\n let filterOffset = texel * radius;\n${"pcf-poisson-5tap"===e?"\n let seed = floor(uv * dims);\n let angle = fract(52.9829189 * fract(dot(seed, vec2(0.06711056, 0.00583715)))) * 6.28318530718;\n let rotation = mat2x2<f32>(vec2(cos(angle), sin(angle)), vec2(-sin(angle), cos(angle)));\n let offset0 = (rotation * vec2(-0.94201624, -0.39906216)) * filterOffset;\n let offset1 = (rotation * vec2(0.94558609, -0.76890725)) * filterOffset;\n let offset2 = (rotation * vec2(-0.09418410, -0.92938870)) * filterOffset;\n let offset3 = (rotation * vec2(0.34495938, 0.29387760)) * filterOffset;":cs}\n${n}\n let shadow = ${"renderer"===e?"(center * 4.0 + tap0 + tap1 + tap2 + tap3) * 0.125":"(center + tap0 + tap1 + tap2 + tap3) * 0.2"};`}function ds(e){return e.replace(/[^A-Za-z0-9_]/g,"_")}function hs(e,t){const i=Object.entries(e.uniforms).map(([e,t])=>` ${ds(e)}: ${t.type},`).join("\n"),r=i?`\nstruct MaterialUniforms {\n${i}\n};\n\n@group(1) @binding(0) var<uniform> materialUniforms: MaterialUniforms;\n`:"",n=Object.entries(e.textures).map(([e,i],r)=>{const n=1+2*r,a=ds(e),s=$t(i,t);return[`@group(1) @binding(${n}) var ${a}Sampler: ${s.wgslSamplerType};`,`@group(1) @binding(${n+1}) var ${a}Texture: ${s.wgslTextureType};`].join("\n")}).join("\n"),a=1+2*Object.keys(e.textures).length;return`${r}\n${n}\n${Object.entries(e.storageBuffers).map(([e,t],i)=>{const r=ds(e);return`@group(1) @binding(${a+i}) var<storage, ${t.access??"read"}> ${r}: ${t.type};`}).join("\n")}`}function ps(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 rendererViewportSize() -> vec2<f32> {\n return ${"rendererCamera"===e?"rendererCamera.viewportAndTime.xy":"shadowCamera"===e?"shadowCamera.timeAndPadding.yz":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 fs(e){return e?"\nstruct RendererSkinningUniforms {\n bindMatrix: mat4x4<f32>,\n bindMatrixInverse: mat4x4<f32>,\n previousBindMatrix: mat4x4<f32>,\n previousBindMatrixInverse: 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@group(2) @binding(2) var<storage, read> rendererPreviousBoneMatrixColumns: array<vec4<f32>>;\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 rendererPreviousBoneMatrix(index: u32) -> mat4x4<f32> {\n let base = index * 4u;\n return mat4x4<f32>(\n rendererPreviousBoneMatrixColumns[base + 0u],\n rendererPreviousBoneMatrixColumns[base + 1u],\n rendererPreviousBoneMatrixColumns[base + 2u],\n rendererPreviousBoneMatrixColumns[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 rendererPreviousSkinPosition(position: vec3<f32>, skinIndex: vec4<u32>, skinWeight: vec4<f32>) -> vec3<f32> {\n let boundPosition = rendererSkinning.previousBindMatrix * 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 (rendererPreviousBoneMatrix(skinIndex.x) * boundPosition) * skinWeight.x +\n (rendererPreviousBoneMatrix(skinIndex.y) * boundPosition) * skinWeight.y +\n (rendererPreviousBoneMatrix(skinIndex.z) * boundPosition) * skinWeight.z +\n (rendererPreviousBoneMatrix(skinIndex.w) * boundPosition) * skinWeight.w;\n let fallbackWeight = max(0.0, 1.0 - weightSum);\n return (rendererSkinning.previousBindMatrixInverse * (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 ms(e,t,i="packed",r=!0,n=!1,a){const s="particle"!==i&&!e.transparent&&!e.requiresLatePass(),o=!0===e.defines?.USE_SDFGI,l=e.defines?.SDFGI_CASCADE_COUNT,c=(u=e.defines).TSG_SHADOWMAP_TYPE_BASIC?"basic":u.TSG_SHADOWMAP_TYPE_PCF_2X2?"pcf-2x2":u.TSG_SHADOWMAP_TYPE_PCF_POISSON_5TAP?"pcf-poisson-5tap":u.TSG_SHADOWMAP_TYPE_PCF_5TAP?"pcf-5tap":"renderer";var u;const d=hs(e,t),h=function(e){return Object.entries(e.getGraphTextureInputs()).map(([e,t],i)=>{const r=ds(e);return`@group(3) @binding(${2*i}) var ${r}Sampler: ${"comparison"===t.sampler?"sampler_comparison":"sampler"};\n@group(3) @binding(${2*i+1}) var ${r}Texture: ${"depth-2d"===t.dimension?"texture_depth_2d":"3d"===t.dimension?"texture_3d<f32>":"texture_2d<f32>"};`}).join("\n")}(e),p="packed-visible"===i,f="particle"===i?`\n@group(1) @binding(0) var<uniform> rendererCamera: RendererCameraUniforms;\n@group(1) @binding(1) var<uniform> rendererLights: RendererLightUniforms;\n@group(1) @binding(2) var rendererShadowSampler: sampler_comparison;\n@group(1) @binding(3) var rendererDirectionalShadowTexture: texture_depth_2d_array;\n@group(1) @binding(4) var rendererLinearClampSampler: sampler;\n@group(1) @binding(5) var rendererPointShadowTexture: texture_2d_array<f32>;\n@group(1) @binding(6) var rendererSpotShadowTexture: texture_depth_2d_array;\n@group(1) @binding(7) var rendererSpotLightMapAtlas: texture_2d<f32>;\n\nfn rendererBatchingId(instanceIndex: u32) -> u32 { return instanceIndex; }\nfn rendererInstanceModelMatrix(instanceIndex: u32) -> mat4x4<f32> {\n ${a??"_ = instanceIndex;\n return mat4x4<f32>(vec4(1.0, 0.0, 0.0, 0.0), vec4(0.0, 1.0, 0.0, 0.0), vec4(0.0, 0.0, 1.0, 0.0), vec4(0.0, 0.0, 0.0, 1.0));"}\n}\nfn rendererPreviousInstanceModelMatrix(instanceIndex: u32) -> mat4x4<f32> { return rendererInstanceModelMatrix(instanceIndex); }\nfn rendererMotionBlurParams(instanceIndex: u32) -> vec4<f32> { _ = instanceIndex; return vec4<f32>(1.0, 1.0, 0.0, 0.0); }\nfn rendererObjectColor(instanceIndex: u32) -> vec4<f32> { _ = instanceIndex; return vec4<f32>(1.0); }\n`:"instanced-direct"===i?"\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@group(0) @binding(10) var rendererSpotLightMapAtlas: texture_2d<f32>;\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 rendererPreviousInstanceModelMatrix(instanceIndex: u32) -> mat4x4<f32> {\n return rendererInstanceModelMatrix(instanceIndex);\n}\n\nfn rendererMotionBlurParams(instanceIndex: u32) -> vec4<f32> {\n _ = instanceIndex;\n return vec4<f32>(1.0, 1.0, 0.0, 0.0);\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 previousModel0: vec4<f32>,\n previousModel1: vec4<f32>,\n previousModel2: vec4<f32>,\n previousModel3: 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@group(0) @binding(9) var rendererSpotLightMapAtlas: texture_2d<f32>;\n${p?"@group(0) @binding(8) var<storage, read> rendererVisibleInstanceIndices: array<u32>;":""}\n\nfn rendererResolveInstanceIndex(instanceIndex: u32) -> u32 {\n ${p?"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 rendererPreviousInstanceModelMatrix(instanceIndex: u32) -> mat4x4<f32> {\n let instance = rendererInstances[rendererResolveInstanceIndex(instanceIndex)];\n return mat4x4<f32>(instance.previousModel0, instance.previousModel1, instance.previousModel2, instance.previousModel3);\n}\n\nfn rendererMotionBlurParams(instanceIndex: u32) -> vec4<f32> {\n return vec4<f32>(rendererInstances[rendererResolveInstanceIndex(instanceIndex)].batching.yzw, 0.0);\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`,m=r?`\nfn rendererDirectionalReceiverDepthGradient(matrix: mat4x4<f32>, worldNormal: vec3<f32>) -> vec2<f32> {\n // Directional shadow projections are orthographic. Transform the receiver\n // plane normal with the inverse transpose of the orthogonal matrix rows;\n // multiplying it as a direction would be wrong for unequal cascade extents.\n let x = vec3(matrix[0].x, matrix[1].x, matrix[2].x);\n let y = vec3(matrix[0].y, matrix[1].y, matrix[2].y);\n let z = vec3(matrix[0].z, matrix[1].z, matrix[2].z);\n let normal = vec3(\n dot(worldNormal, x) / max(dot(x, x), 1e-20),\n dot(worldNormal, y) / max(dot(y, y), 1e-20),\n dot(worldNormal, z) / max(dot(z, z), 1e-20)\n );\n // A plane parallel to the light has no usable depth gradient. Keep the\n // existing raster bias there instead of dividing by a near-zero value.\n if (abs(normal.z) <= length(normal) * 1e-4) {\n return vec2(0.0);\n }\n // NDC X/Y span two units; texture Y is inverted.\n return vec2(-2.0 * normal.x, 2.0 * normal.y) / normal.z;\n}\n\nfn rendererSampleDirectionalShadowOnPlane(lightIndex: u32, worldPosition: vec3<f32>, depthGradient: vec2<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 // Hardware PCF compares a 2x2 footprint with one reference depth. Cover\n // only that half-texel footprint; wider taps are corrected individually.\n let footprintBias = ${"basic"===c?"0.0":"dot(abs(depthGradient), texel * 0.5)"};\n let depth = ndc.z + rendererDirectionalShadowBiasForLight(lightIndex) - footprintBias;\n // Comparison-level sampling provides hardware 2x2 PCF and remains legal\n // inside non-uniform light loops. The default keeps the existing tent filter.\n${us(c,"rendererDirectionalShadowTexture",!0)}\n return mix(1.0, shadow, rendererDirectionalShadowIntensityForLight(lightIndex));\n}\n\nfn rendererSampleDirectionalShadowForLight(lightIndex: u32, worldPosition: vec3<f32>) -> f32 {\n return rendererSampleDirectionalShadowOnPlane(lightIndex, worldPosition, vec2(0.0));\n}\n\nfn rendererSampleDirectionalShadowForLightWithNormal(lightIndex: u32, worldPosition: vec3<f32>, worldNormal: vec3<f32>) -> f32 {\n let params = rendererLights.directionalShadowParams[lightIndex];\n let gradient = rendererDirectionalReceiverDepthGradient(rendererDirectionalShadowMatrixForLight(lightIndex), worldNormal);\n return rendererSampleDirectionalShadowOnPlane(lightIndex, worldPosition + normalize(worldNormal) * params.w, gradient);\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 // WebGPU's framebuffer/texture Y axis points down. The face-local value\n // above is NDC (Y up), so mirror Y just like the projected directional and\n // spot shadow paths do before sampling their render targets.\n let textureUv = uv * vec2(0.5, -0.5) + vec2(0.5, 0.5);\n return vec3<f32>(textureUv, f32(pointIndex * 6u + face));\n}\n\nfn rendererComparePointShadow(lightIndex: u32, direction: vec3<f32>, depth: f32) -> f32 {\n let uvLayer = rendererPointShadowUvLayer(direction, lightIndex);\n let dims = vec2<f32>(textureDimensions(rendererPointShadowTexture));\n let sampleUv = clamp(uvLayer.xy, vec2(0.0), vec2(1.0));\n let pixel = vec2<i32>(clamp(sampleUv * dims, vec2(0.0), dims - vec2(1.0)));\n let closestDepth = textureLoad(rendererPointShadowTexture, pixel, i32(round(uvLayer.z)), 0).r;\n return select(0.0, 1.0, depth <= closestDepth);\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 = rendererPointLightShadowRangeForLight(lightIndex);\n let toFragment = worldPosition - lightPosition;\n let distanceToLight = length(toFragment);\n if (distanceToLight >= range) {\n return 1.0;\n }\n let currentDepth = clamp(distanceToLight / max(range, 0.0001), 0.0, 1.0) - rendererPointShadowBiasForLight(lightIndex);\n${g=c,"pcf-5tap"!==g&&"pcf-poisson-5tap"!==g?" let shadow = rendererComparePointShadow(lightIndex, toFragment, currentDepth);":`\n let direction = normalize(toFragment);\n let up = select(vec3(1.0, 0.0, 0.0), vec3(0.0, 1.0, 0.0), abs(direction.y) < 0.999);\n let tangent = normalize(cross(up, direction));\n let bitangent = cross(direction, tangent);\n let dims = vec2<f32>(textureDimensions(rendererPointShadowTexture));\n let uv = rendererPointShadowUvLayer(direction, lightIndex).xy;\n let filterOffset = max(rendererLights.pointShadowParams2[lightIndex].x, 0.0) / max(dims, vec2(1.0));\n${"pcf-poisson-5tap"===g?"\n let seed = floor(uv * dims);\n let angle = fract(52.9829189 * fract(dot(seed, vec2(0.06711056, 0.00583715)))) * 6.28318530718;\n let rotation = mat2x2<f32>(vec2(cos(angle), sin(angle)), vec2(-sin(angle), cos(angle)));\n let offset0 = (rotation * vec2(-0.94201624, -0.39906216)) * filterOffset;\n let offset1 = (rotation * vec2(0.94558609, -0.76890725)) * filterOffset;\n let offset2 = (rotation * vec2(-0.09418410, -0.92938870)) * filterOffset;\n let offset3 = (rotation * vec2(0.34495938, 0.29387760)) * filterOffset;":cs}\n let center = rendererComparePointShadow(lightIndex, direction, currentDepth);\n${[0,1,2,3].map(e=>`\n let tap${e} = rendererComparePointShadow(lightIndex, direction + tangent * offset${e}.x + bitangent * offset${e}.y, currentDepth);`).join("\n")}\n let shadow = (center + tap0 + tap1 + tap2 + tap3) * 0.2;`}\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, ${"renderer"===c?"1.0":"0.0"});\n let depth = ndc.z - rendererSpotShadowBiasForLight(lightIndex);\n${"renderer"===c?"\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 let shadow = sum / 9.0;\n":us(c,"rendererSpotShadowTexture",!1)}\n return mix(1.0, shadow, 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";var g;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 motionCurrentViewProj: mat4x4<f32>,\n motionPreviousViewProj: mat4x4<f32>,\n motionParams: 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>, 64>,\n pointColorIntensities: array<vec4<f32>, 64>,\n pointParams: array<vec4<f32>, 64>,\n pointShadowParams: array<vec4<f32>, 64>,\n pointShadowParams2: array<vec4<f32>, 64>,\n spotPositionRanges: array<vec4<f32>, 64>,\n spotDirectionCones: array<vec4<f32>, 64>,\n spotColorIntensities: array<vec4<f32>, 64>,\n spotShadowParams: array<vec4<f32>, 64>,\n spotShadowParams2: array<vec4<f32>, 64>,\n spotParams: array<vec4<f32>, 64>,\n spotShadowMatrices: array<mat4x4<f32>, 64>,\n csmCascadeRanges: array<vec4<f32>, 4>,\n hemisphereSkyColorIntensity: vec4<f32>,\n hemisphereGroundColorIntensity: vec4<f32>,\n hemisphereDirection: vec4<f32>,\n};\n\n${f}\n\n${s?"@group(0) @binding(11) var rendererPointLightTiles: texture_2d<u32>;":""}\n\nfn rendererFullPointLightMask() -> vec2<u32> {\n let count = min(rendererPointLightCount(), 64u);\n // Shifts by 32 wrap to zero in WGSL; explicitly handle empty words.\n let low = 0xffffffffu >> (32u - min(count, 32u));\n let high = 0xffffffffu >> (32u - min(count - min(count, 32u), 32u));\n return vec2<u32>(select(low, 0u, count == 0u), select(high, 0u, count <= 32u));\n}\n\nfn rendererPointLightMask(pixel: vec2<f32>) -> vec2<u32> {\n ${s?"\n if (rendererCamera.nearFar.w > 0.5 && rendererPointLightCount() > 0u) {\n // Tile boundaries align to derivative quads; clamp edge helpers.\n let tile = min(vec2<u32>(max(pixel, vec2<f32>(0.0))) / 16u, textureDimensions(rendererPointLightTiles) - 1u);\n return textureLoad(rendererPointLightTiles, vec2<i32>(tile), 0).xy;\n }":"_ = pixel;"}\n return rendererFullPointLightMask();\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 rendererMotionCurrentClip(localPosition: vec3<f32>, instanceIndex: u32) -> vec4<f32> {\n let world = rendererInstanceModelMatrix(instanceIndex) * vec4(localPosition, 1.0);\n return rendererCamera.motionCurrentViewProj * world;\n}\n\nfn rendererMotionPreviousClip(\n currentLocalPosition: vec3<f32>,\n previousLocalPosition: vec3<f32>,\n instanceIndex: u32\n) -> vec4<f32> {\n let params = rendererMotionBlurParams(instanceIndex);\n let useObjectHistory = params.x >= 1.5 && params.z >= 0.5;\n var previousModel = rendererInstanceModelMatrix(instanceIndex);\n var previousLocal = currentLocalPosition;\n if (useObjectHistory) {\n previousModel = rendererPreviousInstanceModelMatrix(instanceIndex);\n previousLocal = previousLocalPosition;\n }\n return rendererCamera.motionPreviousViewProj * previousModel * vec4(previousLocal, 1.0);\n}\n\nfn rendererWorldNormal(localNormal: vec3<f32>, instanceIndex: u32) -> vec3<f32> {\n return normalize(rendererInstanceNormalMatrix(instanceIndex) * localNormal);\n}\n\n${ps("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\n// Probe GI can be interpolated from vertices without exposing the fragment-only\n// direct/ambient light uniform block to the vertex stage.\nfn rendererDiffuseGIAt(worldPosition: vec3<f32>, worldNormal: vec3<f32>) -> vec3<f32> {\n return ${o?"rendererSdfgiIrradiance(worldPosition, worldNormal)":"vec3<f32>(0.0)"};\n}\n\nfn rendererIndirectDiffuseAt(worldPosition: vec3<f32>, worldNormal: vec3<f32>) -> vec3<f32> {\n return rendererIndirectDiffuse(worldNormal) + rendererDiffuseGIAt(worldPosition, worldNormal);\n}\n\n${o?2===l||3===l?function(e){let t="",i="var result = vec3<f32>(0.0);\nvar remaining = 1.0;\n";for(let r=0;r<e;r++){const e=0===r?"sdfgiField":`sdfgiField${r}`;t+=ee.replace(/\bsdfgiField\b/g,e).replace(/rendererSdfgiSample/g,`rendererSdfgiSample${r}`).replace(/rendererSdfgiIrradiance/g,`rendererSdfgiIrradiance${r}`),t+=`\nfn rendererSdfgiBankCoverage${r}(position: vec3<f32>, normal: vec3<f32>, bank: u32) -> f32 {\n let origin = ${e}[bank];\n let settings = ${e}[bank + 1u];\n if (settings.z <= 0.0 || ${e}[bank + 2u].x < 0.5) { return 0.0; }\n let local = (position + normalize(normal) * settings.w - origin.xyz - vec3<f32>(origin.w * 2.0)) / settings.x;\n let edge = min(local, vec3<f32>(settings.y - 1.0) - local);\n return smoothstep(0.0, 1.0, min(edge.x, min(edge.y, edge.z)));\n}\nfn rendererSdfgiCoverage${r}(position: vec3<f32>, normal: vec3<f32>) -> f32 {\n if (${e}[1].z <= 0.0 || ${e}[2].x < 0.5) { return 0.0; }\n let blend = ${e}[2].y;\n var previous = 0.0;\n if (blend < 1.0 && ${e}[2].z > 0.5) {\n previous = rendererSdfgiBankCoverage${r}(position, normal, u32(${e}[3].x));\n }\n return mix(previous, rendererSdfgiBankCoverage${r}(position, normal, 0u), blend);\n}\n`,i+=`\n if (remaining > 0.0) {\n let coverage = rendererSdfgiCoverage${r}(worldPosition, worldNormal);\n if (coverage > 0.0) {\n result += rendererSdfgiIrradiance${r}(worldPosition, worldNormal) * remaining;\n remaining *= 1.0 - coverage;\n }\n }\n`}return t+`\nfn rendererSdfgiIrradiance(worldPosition: vec3<f32>, worldNormal: vec3<f32>) -> vec3<f32> {\n ${i}\n return result;\n}\n`}(l):ee:""}\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.pointParams[lightIndex].x;\n}\n\nfn rendererPointLightShadowRangeForLight(lightIndex: u32) -> f32 {\n return rendererLights.pointPositionRanges[lightIndex].w;\n}\n\nfn rendererPointLightDecayForLight(lightIndex: u32) -> f32 {\n return rendererLights.pointParams[lightIndex].y;\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 rendererPointLightDecayForLight(lightIndex)\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\nfn rendererSampleSpotLightMapForLight(lightIndex: u32, worldPosition: vec3<f32>) -> vec3<f32> {\n if (lightIndex >= rendererSpotLightCount() || rendererLights.spotParams[lightIndex].w < 0.5) {\n return vec3<f32>(1.0);\n }\n let clip = rendererSpotShadowMatrixForLight(lightIndex) * vec4<f32>(worldPosition, 1.0);\n if (clip.w <= 0.0) { return vec3<f32>(1.0); }\n let ndc = clip.xyz / clip.w;\n if (any(ndc < vec3<f32>(-1.0, -1.0, 0.0)) || any(ndc > vec3<f32>(1.0))) {\n return vec3<f32>(1.0);\n }\n let projectedUv = ndc.xy * vec2<f32>(0.5, -0.5) + vec2<f32>(0.5);\n let cell = vec2<f32>(f32(lightIndex % 8u), f32(lightIndex / 8u));\n let cellUv = clamp(projectedUv, vec2<f32>(0.0), vec2<f32>(1.0)) * (255.0 / 256.0) + vec2<f32>(0.5 / 256.0);\n let atlasUv = (cell + cellUv) / 8.0;\n return textureSampleLevel(rendererSpotLightMapAtlas, rendererLinearClampSampler, atlasUv, 0.0).rgb;\n}\n\n${m}\n${fs(n)}\n${d}\n${h}\n`}function gs(e=!0,t){return ms({uniforms:{},textures:{},storageBuffers:{},defines:{},getGraphTextureInputs:()=>({})},void 0,"particle",e,!1,t)}function vs(e,t,i,r="packed",n=!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"===r?"@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"===r?"@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=hs(e,i),o="instanced-direct"===r?"\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 previousModel0: vec4<f32>,\n previousModel1: vec4<f32>,\n previousModel2: vec4<f32>,\n previousModel3: 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",l="packed-visible"===r;return`\n${a}\n${l?`@group(0) @binding(${"shadow"===t?2:3}) var<storage, read> rendererVisibleInstanceIndices: array<u32>;\nfn rendererResolveInstanceIndex(instanceIndex: u32) -> u32 { return rendererVisibleInstanceIndices[instanceIndex]; }`:""}\n\n${l?o.replaceAll("rendererInstances[instanceIndex]","rendererInstances[rendererResolveInstanceIndex(instanceIndex)]"):o}\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${ps("camera"===t?"rendererCamera":"shadowCamera")}\n${fs(n)}\n${s}\n`}var xs=class{constructor(e,t,i={}){this.name=e,this.callback=t,this.reads=i.reads,this.writes=i.writes,this.dependsOn=i.dependsOn}name;callback;reads;writes;dependsOn;execute(e){this.callback(e)}},ws=class{constructor(e){this.device=e}device;timestamps=[];visibility=[];disposed=!1;acquire(e,t){if(this.disposed)return null;const i=t?this.timestamps:this.visibility;let r=i.find(t=>!t.busy&&t.capacity>=e);if(!r){const n=i.findIndex(e=>!e.busy);if(n<0&&i.length>=3)return null;n>=0&&this.destroy(i[n]);const a=Math.max(8,t?8*e:e);r={busy:!1,capacity:e,readBuffer:this.device.createBuffer({label:"renderer-profile-read",size:a,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ})},t&&(r.querySet=this.device.createQuerySet({label:"renderer-profile-timestamps",type:"timestamp",count:e}),r.resolveBuffer=this.device.createBuffer({label:"renderer-profile-resolve",size:a,usage:GPUBufferUsage.QUERY_RESOLVE|GPUBufferUsage.COPY_SRC})),n>=0?i[n]=r:i.push(r)}return r.busy=!0,r}release(e,t){if(this.disposed)return;if(t)return void(e.busy=!1);this.destroy(e);const i=e.querySet?this.timestamps:this.visibility,r=i.indexOf(e);r>=0&&i.splice(r,1)}dispose(){this.disposed=!0;for(const e of this.timestamps)this.destroy(e);for(const e of this.visibility)this.destroy(e);this.timestamps.length=this.visibility.length=0}destroy(e){e.readBuffer.destroy(),e.querySet?.destroy(),e.resolveBuffer?.destroy()}},bs=new WeakMap,ys=new WeakMap,Ss=new WeakSet;function Cs(e){bs.get(e)?.dispose(),bs.delete(e)}function Ms(e,t){Ss.has(t)||((!e.latestFrameProfile||t.profile.frameIndex>=e.latestFrameProfile.frameIndex)&&(e.latestFrameProfile=Ds(t.profile)),(t.pendingGpuRead||t.pendingVisibilityRead)&&Promise.all([t.pendingGpuRead?Ps(t.profile,t.pendingGpuRead):Promise.resolve(),t.pendingVisibilityRead?Bs(t.profile,t.pendingVisibilityRead):Promise.resolve()]).then(()=>{if(ys.get(t)!==bs.get(e))return;const i=Ds(t.profile);(!e.latestFrameProfile||i.frameIndex>=e.latestFrameProfile.frameIndex)&&(e.latestFrameProfile=i),(!e.latestCompletedFrameProfile||i.frameIndex>=e.latestCompletedFrameProfile.frameIndex)&&(e.latestCompletedFrameProfile=i)}))}async function Ps(e,t){let i=!1;try{await t.readBuffer.mapAsync(GPUMapMode.READ);const r=t.readBuffer.getMappedRange(),n=new BigUint64Array(r);let a=0;const s=t.profile.passes.map((e,t)=>{const i=Number(n[2*t]??0n),r=Number(n[2*t+1]??0n),s=Math.max(0,r-i)/1e6;return a+=s,{...e,gpuTimeMs:s}});e.gpuTimeMs=a,e.gpuProfilingReason=null,e.passes=s,i=!0}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.release?t.release(i):(t.querySet.destroy(),t.resolveBuffer.destroy(),t.readBuffer.destroy())}}async function Bs(e,t){let i=!1;try{await t.readBuffer.mapAsync(GPUMapMode.READ);const r=new Uint32Array(t.readBuffer.getMappedRange());let n=0,a=0,s=0,o=0,l=0;for(const e of t.regions){let t=0;const i=e.byteOffset/Uint32Array.BYTES_PER_ELEMENT;for(let n=0;n<e.drawCount;n+=1)t+=r[i+5*n+1]??0,l+=Math.floor((r[i+5*n]??0)/3)*(r[i+5*n+1]??0);"dynamic"===e.kind?(n+=e.totalInstances,a+=t):(s+=e.totalInstances,o+=t)}const c=n+s,u=a+o;e.visibility={visibleTriangles:l,totalInstances:c,visibleInstances:u,culledInstances:Math.max(0,c-u),dynamicTotalInstances:n,dynamicVisibleInstances:a,staticTotalInstances:s,staticVisibleInstances:o},i=!0}catch{e.visibility=null}finally{"mapped"===t.readBuffer.mapState&&t.readBuffer.unmap(),t.release?t.release(i):t.readBuffer.destroy()}}function Ds(e){return{...e,cpuPhases:{...e.cpuPhases},passes:e.passes.map(e=>({...e})),visibility:e.visibility?{...e.visibility}:null}}import{Frustum as Is,Matrix4 as Ts,Sphere as Rs}from"three";function Vs(e,t,i,r,n,a,s,o){const l=e[t+3];if(n>0&&!(l*r>=n*(s?.85:1.15)))return!1;const c=e[t],u=e[t+1],d=e[t+2];if(a>0){const e=c-o.x,t=u-o.y,i=d-o.z,r=a+l;if(!(e*e+t*t+i*i<=r*r))return!1}for(let e=0;e<6;e++){const t=i.planes[e],r=t.normal;if(r.x*c+r.y*u+r.z*d+t.constant<-l)return!1}return!0}var Gs=class{draws=[];directDraws=[];bundles=[];signatures=[];count=-1;bindGroup=null;pipeline=null;invalidation=null;matches(e,t,i){let r=this.count===this.draws.length&&this.bindGroup===e&&this.pipeline===t&&this.invalidation===i;for(let e=0;e<this.draws.length;e++){const t=this.draws[e],i=t.geometryResource,n=this.signatures[e];n&&n.geometry===t.geometryKey&&n.position===i.position&&n.index===i.index&&n.binding===t.residentInstanceBinding&&n.start===t.start&&n.count===t.count&&n.firstInstance===t.instanceStart&&n.instances===t.instanceCount||(r=!1)}return r}store(e,t,i,r){for(let e=0;e<this.draws.length;e++){const t=this.draws[e],i=t.geometryResource;let r=this.signatures[e];r||(r={},this.signatures[e]=r),r.geometry=t.geometryKey,r.position=i.position,r.index=i.index,r.binding=t.residentInstanceBinding,r.start=t.start,r.count=t.count,r.firstInstance=t.instanceStart,r.instances=t.instanceCount}this.count=this.draws.length,this.bindGroup=t,this.pipeline=i,this.invalidation=r,e?this.bundles[0]=e:this.bundles.length=0}},zs=class{valid=!1;matrix=new Float64Array(16);policies=new Float64Array(0);size=0;x=0;y=0;z=0;update(e,t,i,r){let n=!this.valid||this.size!==t;for(let t=0;t<16;t++)this.matrix[t]!==e.elements[t]&&(n=!0);this.policies.length!==3*i.length&&(this.policies=new Float64Array(3*i.length),n=!0);let a=!1;for(let e=0;e<i.length;e++){const t=i[e],r=t.detailCulling,s=3*e,o=t.castShadow?1:0;this.policies[s]===r.shadowMinScreenSize&&this.policies[s+1]===r.shadowMaxDistance&&this.policies[s+2]===o||(n=!0),this.policies[s]=r.shadowMinScreenSize,this.policies[s+1]=r.shadowMaxDistance,this.policies[s+2]=o,a||=0!==o&&r.shadowMaxDistance>0}return!a||this.x===r.x&&this.y===r.y&&this.z===r.z||(n=!0),this.matrix.set(e.elements),this.size=t,this.x=r.x,this.y=r.y,this.z=r.z,this.valid=!0,n}},Ls=new WeakMap;function Us(e){if(e.transparent||e.polygonOffset)return!0;let t=Ls.get(e);return void 0===t&&(t=e.alphaTest>0||/\bdiscard\b/.test(e.fragmentShader),Ls.set(e,t)),t}function ks(e){for(const t of e)if(t.customDepthMaterial||null!==t.skinning||t.material.vertexAttributes.some(e=>"instance"===e.stepMode)||null===t.material.depthVertexShader&&(Us(t.material)||t.wireframe||!t.material.primitiveTopology.startsWith("triangle")))return!1;return!0}var As=new WeakMap,Fs={drawCallCount:0,triangleCount:0},Os=new Is,Es=new Ts,js=new Is,$s=new Ts,Ws=new m,Ns=new Rs,_s=new WeakMap,Hs=new WeakMap,qs=F.clone();function Ks(e,t,i,r,n=0){let a=_s.get(e);a||(a=new WeakMap,_s.set(e,a));let s=a.get(t);s||(s={pool:[],draws:[],key:new zs},a.set(t,s));if(!s.key.update($s,i,e.draws,qs)&&s.excluded===r&&s.exclusionVersion===n)return this.directionalShadowSubmissionStats.selectionHits++,s.draws;s.excluded=r,s.exclusionVersion=n,this.directionalShadowSubmissionStats.selections++;const o=s.pool,l=s.draws;l.length=0;const c=e.instanceVisibilityResource.metadata,u=Math.max(Math.abs(t.projectionMatrix.elements[0])*i,Math.abs(t.projectionMatrix.elements[5])*i);let d=Hs.get(e);d||(d=new WeakMap,Hs.set(e,d));let h=d.get(t);h||(h=new Uint8Array(e.instanceCount),d.set(t,h));let p=0;for(const t of e.shadowChunks)if(Ns.center.copy(t.boundsCenter),Ns.radius=t.boundsRadius,js.intersectsSphere(Ns))for(const i of t.drawIndices){if(r?.[i])continue;const t=e.draws[i];if(!t.castShadow)continue;const n=t.detailCulling;let a=-1;const s=t.instanceStart+t.instanceCount;for(let e=t.instanceStart;e<=s;e++){let i=!1;if(e<s){i=Vs(c,8*e,js,u,n.shadowMinScreenSize,n.shadowMaxDistance,0!==h[e],qs),h[e]=i?1:0}if(i&&a<0&&(a=e),!i&&a>=0){let i=o[p];i?i.source!==t&&(Object.assign(i.draw,t),i.source=t):(i={source:t,draw:{...t}},o[p]=i);const r=i.draw;r.instanceStart=a,r.instanceCount=e-a,l.push(r),p++,a=-1}}}return l}function Ys(e){return e.usesBatching}function Zs(e){return!e.wireframe&&e.material.primitiveTopology.startsWith("triangle")}function Xs(e,t){return"pointShadow"===t?null!==e.material.pointShadowVertexShader&&null!==e.material.pointShadowFragmentShader:null!==e.material.depthVertexShader}function Js(e,t){if(!this.state.visibilityKernel||!this.state.drawMetadataResource||0===this.state.drawMetadataResource.count)return;const i=e.beginComputePass({label:"renderer-visibility-pass"});i.setPipeline(this.state.visibilityKernel.pipeline),i.setBindGroup(0,t),i.dispatchWorkgroups(Math.ceil(this.state.drawMetadataResource.count/64)),i.end()}function Qs(e){return e.instanceVisibilityResource.instanceCount<=64&&e.drawMetadataResource.count<=64}var eo=new WeakMap;function to(e,t){if(!(this.state.staticVisibilityClearKernel&&this.state.staticVisibilityCullKernel&&this.state.staticVisibilityIndirectBuildKernel&&this.getHiZOcclusionCullingActive()&&this.state.device))return;let i=eo.get(this);i||(i=[],eo.set(this,i)),i.length=0;for(const e of this.getCameraStaticDrawSets()){if(!e.publicSet.enabled||!this.isStaticDrawSetCameraVisible(e)||e.cpuVisibility||0===e.drawMetadataResource.count)continue;if("postpass"===t&&e.lastPreVisibilityFrameToken!==this.staticFrameToken)continue;if(!this.state.device)continue;const r="prepass"===t?e.visibilityParamsUpload:e.postVisibilityParamsUpload,n="prepass"===t?e.visibilityParamsBuffer:e.postVisibilityParamsBuffer,a=("prepass"===t?this.state.temporalHiZHistoryValid?3:0:5)|(Qs(e)?8:0);r[1]===this.state.hizMipCount&&r[3]===a||(r[1]=this.state.hizMipCount,r[3]=a,this.state.device.queue.writeBuffer(n,0,$r(r),0,4));this.getOrCreateStaticVisibilityBindGroup(e,t)&&("prepass"!==t||Qs(e)||e.visibilityClearBindGroup&&e.visibilityIndirectBuildBindGroup&&e.postVisibilityIndirectBuildBindGroup||(e.visibilityClearBindGroup=this.state.staticVisibilityClearKernel.createBindGroup(this.state.device,[{binding:0,resource:{buffer:e.visibilityParamsBuffer}},{binding:1,resource:{buffer:e.instanceVisibilityResource.visibleCountsBuffer}},{binding:2,resource:{buffer:e.instanceVisibilityResource.postVisibleCountsBuffer}},{binding:3,resource:{buffer:e.instanceVisibilityResource.visibleInstanceMaskBuffer}}],`${e.label}-visibility-clear-bind-group`),e.visibilityIndirectBuildBindGroup=this.state.staticVisibilityIndirectBuildKernel.createBindGroup(this.state.device,[{binding:0,resource:{buffer:e.visibilityParamsBuffer}},{binding:1,resource:{buffer:e.instanceVisibilityResource.visibleCountsBuffer}},{binding:2,resource:{buffer:e.instanceVisibilityResource.postVisibleCountsBuffer}},{binding:3,resource:{buffer:e.drawMetadataResource.indirectBuffer}},{binding:4,resource:{buffer:e.drawMetadataResource.postIndirectBuffer}}],`${e.label}-visibility-indirect-build-bind-group`),e.postVisibilityIndirectBuildBindGroup=this.state.staticVisibilityIndirectBuildKernel.createBindGroup(this.state.device,[{binding:0,resource:{buffer:e.postVisibilityParamsBuffer}},{binding:1,resource:{buffer:e.instanceVisibilityResource.visibleCountsBuffer}},{binding:2,resource:{buffer:e.instanceVisibilityResource.postVisibleCountsBuffer}},{binding:3,resource:{buffer:e.drawMetadataResource.indirectBuffer}},{binding:4,resource:{buffer:e.drawMetadataResource.postIndirectBuffer}}],`${e.label}-post-visibility-indirect-build-bind-group`)),i.push(e))}if(0===i.length)return;let r=!1;for(const e of i)if(!Qs(e)){r=!0;break}if("prepass"===t&&r){const t=e.beginComputePass({label:"static-temporal-visibility-clear-pass"});t.setPipeline(this.state.staticVisibilityClearKernel.pipeline);for(const e of i)Qs(e)||(t.setBindGroup(0,e.visibilityClearBindGroup),t.dispatchWorkgroups(Math.ceil(Math.max(e.drawMetadataResource.count,e.instanceVisibilityResource.instanceCount)/64)));t.end()}const n=e.beginComputePass({label:`static-temporal-visibility-${t}-cull-pass`});n.setPipeline(this.state.staticVisibilityCullKernel.pipeline);for(const e of i)n.setBindGroup(0,"prepass"===t?e.visibilityBindGroup:e.postVisibilityBindGroup),n.dispatchWorkgroups(Math.ceil(e.instanceVisibilityResource.instanceCount/64));n.end();const a=r?e.beginComputePass({label:`static-temporal-visibility-${t}-indirect-build-pass`}):null;a?.setPipeline(this.state.staticVisibilityIndirectBuildKernel.pipeline);for(const e of i)!Qs(e)&&a&&(a.setBindGroup(0,"prepass"===t?e.visibilityIndirectBuildBindGroup:e.postVisibilityIndirectBuildBindGroup),a.dispatchWorkgroups(Math.ceil(e.drawMetadataResource.count/64))),"prepass"===t?e.lastPreVisibilityFrameToken=this.staticFrameToken:e.lastVisibilityFrameToken=this.staticFrameToken;a?.end(),i.length=0}function io(e,t){if(!(this.state.device&&this.state.staticVisibilityCullKernel&&this.state.hizTexture&&this.state.temporalVisibilityBuffer&&this.state.nearestClampSampler))return null;const i="prepass"===t?e.visibilityBindGroup:e.postVisibilityBindGroup;if(i&&e.visibilityBindGroupHizVersion===this.hizResourceVersion)return i;const r=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}},{binding:10,resource:{buffer:e.drawMetadataResource.indirectBuffer}},{binding:11,resource:{buffer:e.drawMetadataResource.postIndirectBuffer}}],`${e.label}-temporal-visibility-${t}-bind-group`);return"prepass"===t?e.visibilityBindGroup=r:e.postVisibilityBindGroup=r,e.visibilityBindGroupHizVersion=this.hizResourceVersion,r}function ro(e,t,i,r){if(!this.state.shadowDepthPipeline||0===this.state.directionalShadowLayerViews.length)return void this.clearDirectionalShadow(e);this.directionalShadowGpu.beginFrame();let n=!1;i.camera.getWorldPosition(qs);for(let t=0;t<i.lights.directionals.length;t+=1){const a=i.lights.directionals[t],s=this.state.directionalShadowLayerViews[t];if(!a.castShadow||!s)continue;n=!0;const o=this.directionalShadowCameras[t];if(!(this.directionalShadowScheduler.updateMask&1<<t)){r.directionalShadowReused=(r.directionalShadowReused??0)+1;continue}r.directionalShadowUpdates=(r.directionalShadowUpdates??0)+1,r.directionalShadowUpdateMask=(r.directionalShadowUpdateMask??0)|1<<t,this.directionalShadowScheduler.forcedMask&1<<t&&(r.directionalShadowForced=(r.directionalShadowForced??0)+1),js.setFromProjectionMatrix($s.multiplyMatrices(o.projectionMatrix,o.matrixWorldInverse)),Ws.update($s);const l=this.queryStaticShadowResources(js),c=this.getShadowCameraBuffer(t);this.writeShadowCameraBuffer(on(o,this.shadowViewProjScratch),0,0,0,1,c,o);const u=this.getSharedShadowBindGroupForCameraBuffer(c);let d;this.directionalShadowGpu.prepareCascade(js,o,qs,this.state.directionalShadowTextureSize);for(const i of l)i.publicSet.enabled&&0!==i.draws.length&&"late"!==i.drawStage&&(Ns.center.copy(i.spatialBounds.boundsCenter),Ns.radius=i.spatialBounds.boundsRadius,js.intersectsSphere(Ns)&&(!d&&this.directionalShadowGpu.enabled&&this.directionalShadowGpu.available&&(d=e.beginComputePass({label:`renderer-directional-shadow-selection-${t}`})),this.directionalShadowGpu.prepare(this,e,i,c,d)));d?.end();const h=e.beginRenderPass({label:`renderer-directional-shadow-pass-${t}`,colorAttachments:[],depthStencilAttachment:{view:s,depthClearValue:1,depthLoadOp:"clear",depthStoreOp:"store"}});h.setPipeline(this.state.shadowDepthPipeline),Fi(h,0,u);const p=this.directionalDynamicCastersScratch;p.length=0;for(const e of i.shadowDraws??[...i.gpuOpaqueDraws,...i.directOpaqueDraws])e.castShadow&&To(e,this.state.directionalShadowTextureSize)&&p.push(e);this.tryExecuteDynamicDepthBundle(h,p,u,r,c)||this.drawDepthLike(h,p,r,{fallbackPipeline:this.state.shadowDepthPipeline,fallbackPipelineDirect:this.state.shadowDepthPipelineDirect,fallbackSkinnedPipeline:this.state.skinnedShadowDepthPipeline,fallbackBindGroup:u,shadowCameraBuffer:c,passKind:"directionalShadow",customDepthMode:"use",preculled:!0}),p.length=0;for(const e of l){if(!e.publicSet.enabled||0===e.draws.length||"late"===e.drawStage)continue;if(Ns.center.copy(e.spatialBounds.boundsCenter),Ns.radius=e.spatialBounds.boundsRadius,!js.intersectsSphere(Ns))continue;const t=this.directionalShadowGpu.submit(h,e,c,r)?this.directionalShadowGpu.sets.get(e):void 0;t?.eligibleDrawCount!==e.draws.length&&no.call(this,h,e,o,Ks.call(this,e,o,this.state.directionalShadowTextureSize,t?.eligibility,t?.eligibilityVersion),u,c,r)}h.end(),this.directionalShadowScheduler.commit(t)}n||this.clearDirectionalShadow(e)}function no(e,t,i,r,n,a,s){let o=As.get(t);o||(o=new WeakMap,As.set(t,o));let l=o.get(i);l||(l=new Gs,o.set(i,l)),l.draws.length=0,l.directDraws.length=0;let c=0;for(const e of r)e.customDepthMaterial||Xs(e,"directionalShadow")||e.hasRenderCallbacks||e.skinning||!e.indexed||e.wireframe||!Zs(e)||"packed"!==this.getDrawInstanceAccessMode(e)?l.directDraws.push(e):(l.draws.push(e),c+=mn(e));if(l.draws.length>0){const i=this.state.shadowDepthPipeline,r=this.resolveShadowBindGroupForDraw(l.draws[0],n,a),o=l.matches(r,i,t.shadowBundles);if(o)if(0===l.bundles.length){const e=this.state.device.createRenderBundleEncoder({label:`${t.label}-directional-selected-runs`,colorFormats:[],depthStencilFormat:"depth32float",sampleCount:1});Fs.drawCallCount=0,Fs.triangleCount=0,Ro.call(this,e,l.draws,Fs,{fallbackPipeline:i,fallbackBindGroup:n,shadowCameraBuffer:a,passKind:"directionalShadow",customDepthMode:"ignore",preculled:!0}),l.store(e.finish(),r,i,t.shadowBundles),this.directionalShadowSubmissionStats.bundleBuilds++}else this.directionalShadowSubmissionStats.bundleHits++;else l.store(null,r,i,t.shadowBundles),Fs.drawCallCount=0,Fs.triangleCount=0,Ro.call(this,e,l.draws,Fs,{fallbackPipeline:i,fallbackBindGroup:n,shadowCameraBuffer:a,passKind:"directionalShadow",customDepthMode:"ignore",preculled:!0});o&&ji(e,l.bundles),s.drawCallCount+=l.draws.length,s.triangleCount+=c}l.directDraws.length>0&&this.drawDepthLike(e,l.directDraws,s,{fallbackPipeline:this.state.shadowDepthPipeline,fallbackPipelineDirect:this.state.shadowDepthPipelineDirect,fallbackBindGroup:n,shadowCameraBuffer:a,passKind:"directionalShadow",customDepthMode:"use"})}function ao(e,t,i,r){if(!i.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 n=!1;for(let t=0;t<i.lights.points.length;t+=1){const a=i.lights.points[t];if(a.castShadow){n=!0;for(let n=0;n<6;n+=1){const s=6*t+n,o=this.pointShadowCameras[t][n];o.near=a.shadowCameraNear,o.far=a.shadowCameraFar,o.position.copy(a.position),F.copy(a.position).add(V[n]),o.up.copy(R[n]),o.lookAt(F),o.updateMatrixWorld(!0),o.updateProjectionMatrix();const l=this.getShadowCameraBuffer(4+s);this.writeShadowCameraBuffer(on(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}-${n}`,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),Fi(u,0,c),this.drawDepthLike(u,i.gpuOpaqueDraws,r,{fallbackPipeline:this.state.pointShadowPipeline,fallbackPipelineDirect:this.state.pointShadowPipelineDirect,fallbackSkinnedPipeline:this.state.skinnedPointShadowPipeline,fallbackBindGroup:c,shadowCameraBuffer:l,passKind:"pointShadow",customDepthMode:"use"}),this.drawDepthLike(u,i.directOpaqueDraws,r,{fallbackPipeline:this.state.pointShadowPipeline,fallbackPipelineDirect:this.state.pointShadowPipelineDirect,fallbackSkinnedPipeline:this.state.skinnedPointShadowPipeline,fallbackBindGroup:c,shadowCameraBuffer:l,passKind:"pointShadow",customDepthMode:"use"}),oo.call(this,u,o,c,l,"pointShadow",this.state.pointShadowPipeline,this.state.pointShadowPipelineDirect,r),u.end()}}}n||this.clearPointShadow(e)}function so(e,t,i,r){if(!i.lights.spots.some(e=>e.castShadow))return;if(!this.state.shadowDepthPipeline||0===this.state.spotShadowLayerViews.length)return void this.clearSpotShadow(e);let n=!1;for(let t=0;t<i.lights.spots.length;t+=1){const a=i.lights.spots[t],s=this.state.spotShadowLayerViews[t];if(!a.castShadow||!s)continue;n=!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),F.copy(a.position).add(a.direction),o.lookAt(F),o.updateMatrixWorld(!0),o.updateProjectionMatrix();const l=this.getShadowCameraBuffer(28+t);this.writeShadowCameraBuffer(on(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),Fi(u,0,c),this.drawDepthLike(u,i.gpuOpaqueDraws,r,{fallbackPipeline:this.state.shadowDepthPipeline,fallbackPipelineDirect:this.state.shadowDepthPipelineDirect,fallbackSkinnedPipeline:this.state.skinnedShadowDepthPipeline,fallbackBindGroup:c,shadowCameraBuffer:l,passKind:"directionalShadow",customDepthMode:"use"}),this.drawDepthLike(u,i.directOpaqueDraws,r,{fallbackPipeline:this.state.shadowDepthPipeline,fallbackPipelineDirect:this.state.shadowDepthPipelineDirect,fallbackSkinnedPipeline:this.state.skinnedShadowDepthPipeline,fallbackBindGroup:c,shadowCameraBuffer:l,passKind:"directionalShadow",customDepthMode:"use"}),oo.call(this,u,o,c,l,"directionalShadow",this.state.shadowDepthPipeline,this.state.shadowDepthPipelineDirect,r),u.end()}n||this.clearSpotShadow(e)}function oo(e,t,i,r,n,a,s,o){Os.setFromProjectionMatrix(Es.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse));const l=this.renderBundleScratch;l.length=0;for(const e of this.queryStaticShadowResources(Os))for(const t of e.shadowChunks)Ns.center.copy(t.boundsCenter),Ns.radius=t.boundsRadius,Os.intersectsSphere(Ns)&&(l.push(go.call(this,e,i,r,n,a,s,t)),o.drawCallCount+=t.drawCallCount,o.triangleCount+=t.triangleCount);l.length&&ji(e,l),l.length=0}function lo(e,t,i,r){if(!this.state.depthPrepassPipeline||!this.state.mainDepthView)return;const n=e.beginRenderPass({label:"renderer-depth-prepass",colorAttachments:[],depthStencilAttachment:{view:this.state.mainDepthView,depthClearValue:1,depthLoadOp:"clear",depthStoreOp:"store"}});n.setPipeline(this.state.depthPrepassPipeline),Fi(n,0,t),this.executeStaticDepthPrepass(n,t,r),this.drawDepthLike(n,i.gpuOpaqueDraws,r,{fallbackPipeline:this.state.depthPrepassPipeline,fallbackPipelineDirect:this.state.depthPrepassPipelineDirect,fallbackSkinnedPipeline:this.state.skinnedDepthPrepassPipeline,fallbackBindGroup:t,passKind:"prepass",customDepthMode:"skip"}),this.tryExecuteDynamicDepthBundle(n,i.directOpaqueDraws,t,r)||this.drawDepthLike(n,i.directOpaqueDraws,r,{fallbackPipeline:this.state.depthPrepassPipeline,fallbackPipelineDirect:this.state.depthPrepassPipelineDirect,fallbackSkinnedPipeline:this.state.skinnedDepthPrepassPipeline,fallbackBindGroup:t,passKind:"prepass",customDepthMode:"skip"}),n.end()}function co(e,t,i){const r=this.renderBundleScratch;r.length=0;for(const e of this.getCameraStaticDrawSets()){if(!e.publicSet.enabled||!this.isStaticDrawSetCameraVisible(e)||0===e.draws.length||"late"===e.drawStage)continue;if(this.getHiZOcclusionCullingActive()&&e.lastPreVisibilityFrameToken===this.staticFrameToken&&po(e)){const t=this.getOrCreateStaticVisibleDepthSceneBindGroup(e);r.push(uo.call(this,e,t))}else r.push(this.getOrCreateStaticDepthPrepassBundle(e,t));this.recordStaticDrawStats(e,i)}r.length&&ji(e,r),r.length=0}function uo(e,t,i=e.drawMetadataResource.indirectBuffer,r="prepass"){if(!this.state.device||!this.state.depthPrepassPipelineVisible)throw new Error("Renderer visible depth prepass resources are not initialized.");const n=e.indirectDepthPrepassBundles[r];if(n?.sceneBindGroup===t&&n.indirectBuffer===i)return n.bundle;const a=`${e.label}-static-temporal-depth-${r}-bundle-${e.id}`,s=this.state.device.createRenderBundleEncoder({label:a,colorFormats:[],depthStencilFormat:"depth32float",sampleCount:1}),o=mo.call(this,e,"prepass","packed-visible");Fi(s,0,t);let l=null,c=null,u=null;for(let t=0;t<e.draws.length;t+=1){const r=e.draws[t],n=o[t];if(r.customDepthMaterial||!n&&(Xs(r,"prepass")||Us(r.material)||!Zs(r)))continue;const a=n?.pipeline??this.state.depthPrepassPipelineVisible;l!==a&&(l=a,u=null,c=null,s.setPipeline(a)),n&&c!==n.bindGroup&&(c=n.bindGroup,s.setBindGroup(1,c)),u!==r.geometryKey&&(u=r.geometryKey,this.bindGeometryVertexBuffers(s,r.geometry,r.geometryResource,n?.vertexAttributes??z,0,1,r.wireframe)),s.drawIndexedIndirect(i,5*t*Uint32Array.BYTES_PER_ELEMENT)}const d=s.finish({label:a});return e.indirectDepthPrepassBundles[r]={sceneBindGroup:t,indirectBuffer:i,bundle:d},d}function ho(e){if(this.sampleCount<=1||!this.state.mainDepthView||!this.getHiZOcclusionCullingActive())return;let t=null;const i=this.renderBundleScratch;i.length=0;for(const r of this.getCameraStaticDrawSets()){if(!r.publicSet.enabled||!this.isStaticDrawSetCameraVisible(r)||0===r.draws.length||"late"===r.drawStage||r.lastVisibilityFrameToken!==this.staticFrameToken||!po(r))continue;t||(t=e.beginRenderPass({label:"renderer-static-temporal-depth-resolve",colorAttachments:[],depthStencilAttachment:{view:this.state.mainDepthView,depthLoadOp:"load",depthStoreOp:"store"}}));const n=this.getOrCreateStaticVisibleDepthSceneBindGroup(r);i.push(uo.call(this,r,n,r.drawMetadataResource.postIndirectBuffer,"postpass"))}i.length&&ji(t,i),i.length=0,t?.end()}function po(e){return e.temporalDepthSupported??ks(e.draws)}function fo(e,t){if(!this.state.device||!this.state.depthPrepassPipeline)throw new Error("Renderer is not initialized.");const i=this.resolveSceneBindGroupForDraw(e.draws[0],t);if(e.depthPrepassBundle&&e.depthPrepassBundleSceneBindGroup===i)return e.depthPrepassBundle;const r=mo.call(this,e,"prepass"),n=`${e.label}-static-depth-prepass-bundle-${e.id}`,a=this.state.device.createRenderBundleEncoder({label:n,colorFormats:[],depthStencilFormat:"depth32float",sampleCount:1});Fi(a,0,i);let s=null,o=null,l=null;for(let t=0;t<e.draws.length;t+=1){const i=e.draws[t],n=r[t];if(i.customDepthMaterial||!n&&(Us(i.material)||!Zs(i)))continue;const c=n?.pipeline??this.state.depthPrepassPipeline;s!==c&&(s=c,o=null,l=null,a.setPipeline(c)),n&&o!==n.bindGroup&&(o=n.bindGroup,a.setBindGroup(1,o)),l!==i.geometryKey&&(l=i.geometryKey,this.bindGeometryVertexBuffers(a,i.geometry,i.geometryResource,n?.vertexAttributes??z,i.instanceStart,i.instanceCount,i.wireframe)),a.drawIndexed(i.count,i.instanceCount,i.start,0,i.instanceStart)}const c=a.finish({label:n});return e.depthPrepassBundle=c,e.depthPrepassBundleSceneBindGroup=i,c}function mo(e,t,i){const r=i?`${t}:${i}`:t,n=e.depthMaterialResources.get(r);if(n)return n;const a=e.draws.map(e=>{const r=Xs(e,t);if(e.customDepthMaterial||!r)return null;return this.getDepthPassMaterialResourceForDraw(e.material,t,e,i)});return e.depthMaterialResources.set(r,a),a}function go(e,t,i,r,n,a,s){if(!this.state.device)throw new Error("Renderer is not initialized.");const o=this.resolveShadowBindGroupForDraw(e.draws[0],t,i),l=s?null:e.shadowBundles.get(o),c=s?s.bundles.get(o):l?.[r];if(c)return c;const u=mo.call(this,e,r),d=`${e.label}-static-${r}-bundle-${e.id}`,h=this.state.device.createRenderBundleEncoder({label:d,colorFormats:"pointShadow"===r?["rgba16float"]:[],depthStencilFormat:"depth32float",sampleCount:1});Fi(h,0,o);let p=null,f=null,m=null;const g=s?.drawIndices;for(let t=0;t<(g?.length??e.draws.length);t+=1){const i=g?.[t]??t,r=e.draws[i];if(!r.castShadow)continue;const s=u[i],o=s?.pipeline??("instanced-direct"===this.getDrawInstanceAccessMode(r)&&a?a:n);p!==o&&(p=o,f=null,m=null,h.setPipeline(o)),s&&f!==s.bindGroup&&(f=s.bindGroup,h.setBindGroup(1,f)),m!==r.geometryKey&&(m=r.geometryKey,this.bindGeometryVertexBuffers(h,r.geometry,r.geometryResource,s?.vertexAttributes??z,r.instanceStart,r.instanceCount,r.wireframe)),h.drawIndexed(r.count,r.instanceCount,r.start,0,r.instanceStart)}const v=h.finish({label:d});return s?s.bundles.set(o,v):e.shadowBundles.set(o,{...l,[r]:v}),v}function vo(e,t=!1,i=!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"});if(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(),!i){for(let t=1;t<this.state.hizMipCount;t+=1){const i=Math.max(1,this.state.width>>t),r=Math.max(1,this.state.height>>t);let n=this.state.hizReduceBindGroups[t];n||(n=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]=n);const a=e.beginComputePass({label:`renderer-hiz-reduce-pass-${t}`});a.setPipeline(this.state.hizReduceKernel.pipeline),a.setBindGroup(0,n),a.dispatchWorkgroups(Math.ceil(i/8),Math.ceil(r/8)),a.end()}t&&this.commitTemporalHiZHistory()}}function xo(e,t,i,r,n,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??i,resolveTarget:d?i: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,v=null,x=null;const w=e=>{e.sourceObject&&e.hasRenderCallbacks&&e.sourceObject.onBeforeRender(this,n.scene,n.camera,e.geometry,e.material,e.geometryGroup);const t=e.geometryResource,i=this.getMaterialResourceForDraw(e,[D],c),s=this.resolveSceneBindGroupForDraw(e,r);if(f!==i.pipeline&&(f=i.pipeline,g=null,x=null,p.setPipeline(f)),g!==e.geometryKey&&(g=e.geometryKey,this.bindGeometryVertexBuffers(p,e.geometry,t,i.vertexAttributes,e.instanceStart,e.instanceCount,e.wireframe)),v!==s&&(v=s,Fi(p,0,s)),m!==e.material){if(m=e.material,p.setBindGroup(1,i.bindGroup),!i.graphTextureBindGroupLayout)throw new Error("Graph texture layout is missing.");p.setBindGroup(3,this.createGraphTextureBindGroup(e.material,i.graphTextureBindGroupLayout))}i.usesSkinning&&e.skinning&&x!==e.skinning.bindGroup&&(x=e.skinning.bindGroup,Fi(p,2,x)),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,n.scene,n.camera,e.geometry,e.material,e.geometryGroup)};if(this.executeStaticForwardPass(p,r,a,o,c),f=null,m=null,g=null,v=null,x=null,"late"!==o&&this.getHiZOcclusionCullingActive()&&this.state.drawMetadataResource){const e=this.buildIndirectSubmissionStreams(n.gpuOpaqueDraws,r),t=this.renderBundleScratch;t.length=0;for(let i=0;i<e.length;i+=1){const r=e[i];t[0]=this.getOrCreateIndirectForwardBundle(r),ji(p,t),a.drawCallCount+=r.drawCallCount,a.triangleCount+=r.triangleCount}f=null,m=null,g=null,v=null}else if("late"!==o){const e=Xr(n.gpuOpaqueDraws)||n.gpuOpaqueDraws.some(e=>null!==e.skinning)?null:this.getOrCreateDirectForwardBundle(n.gpuOpaqueDraws,r,a);if(e)this.renderBundleScratch[0]=e,ji(p,this.renderBundleScratch);else for(const e of n.gpuOpaqueDraws)w(e)}const b="late"===o||Xr(n.directOpaqueDraws)||n.directOpaqueDraws.some(e=>null!==e.skinning)?null:this.getOrCreateDirectForwardBundle(n.directOpaqueDraws,r,a);if(b)this.renderBundleScratch[0]=b,ji(p,this.renderBundleScratch);else if("late"!==o)for(const e of n.directOpaqueDraws)w(e);if("opaque"!==o)for(const e of n.transparentDraws)w(e);p.end()}function wo(e,t,i,r="all",n=this.sampleCount){const a=this.renderBundleScratch;a.length=0;for(const s of this.getCameraStaticDrawSets())if(s.publicSet.enabled&&this.isStaticDrawSetCameraVisible(s)&&0!==s.draws.length&&("all"===r||s.drawStage===r)){if("opaque"===s.drawStage&&this.getHiZOcclusionCullingActive()&&s.lastVisibilityFrameToken===this.staticFrameToken){const t=this.getOrCreateStaticVisibleSceneBindGroup(s),r=this.getOrCreateStaticIndirectSubmissionStreams(s,t);for(const t of r)if(this.getMultiDrawIndirectActive()){if(a.length&&(ji(e,a),a.length=0),e.setPipeline(t.materialResource.pipeline),this.bindGeometryVertexBuffers(e,t.geometry,t.geometryResource,t.materialResource.vertexAttributes,0,1,t.material.wireframe),Fi(e,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(s.drawMetadataResource.indirectBuffer,5*t.indirectStartIndex*Uint32Array.BYTES_PER_ELEMENT,t.indirectCount),i.drawCallCount+=t.drawCallCount,i.triangleCount+=t.triangleCount}else a.push(this.getOrCreateIndirectForwardBundle(t,s.drawMetadataResource,s.indirectForwardBundleCache,`${s.label}-static-indirect-forward-bundle`)),i.drawCallCount+=t.drawCallCount,i.triangleCount+=t.triangleCount;continue}a.push(this.getOrCreateStaticDirectForwardBundle(s,t,n)),this.recordStaticDrawStats(s,i)}a.length&&ji(e,a),a.length=0}function bo(e,t,i=this.sampleCount){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&&e.directForwardBundleSampleCount===i)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}`,a=this.state.device.createRenderBundleEncoder({label:n,colorFormats:[D],depthStencilFormat:"depth32float",sampleCount:i});let s=null,o=null,l=null;Fi(a,0,r);for(const t of e.draws){const r=("opaque"===e.drawStage?t.materialResource:null)??this.getMaterialResource(t.material,this.getDrawInstanceAccessMode(t),t.receiveShadow,void 0,null!==t.skinning,Ys(t),i);if(s!==r.pipeline&&(s=r.pipeline,l=null,a.setPipeline(s)),l!==t.geometryKey&&(l=t.geometryKey,this.bindGeometryVertexBuffers(a,t.geometry,t.geometryResource,r.vertexAttributes,t.instanceStart,t.instanceCount,t.wireframe)),o!==r.bindGroup){if(o=r.bindGroup,a.setBindGroup(1,o),!r.graphTextureBindGroupLayout)throw new Error("Graph texture layout is missing.");a.setBindGroup(3,this.createGraphTextureBindGroup(t.material,r.graphTextureBindGroupLayout))}a.drawIndexed(t.count,t.instanceCount,t.start,0,t.instanceStart)}const c=a.finish({label:n});return e.directForwardBundle=c,e.directForwardBundleSceneBindGroup=r,e.directForwardBundleSampleCount=i,c}function yo(e){for(const t of e.visibleMaterialBindings){const i=t.drawIndices[0];t.resource=e.draws[i]?.materialResource??e.visibleDrawMaterialResources[i]??null}}function So(e){for(const t of e)t.materialResource=this.getMaterialResource(t.material,this.getDrawInstanceAccessMode(t),t.receiveShadow,void 0,null!==t.skinning,Ys(t))}function Co(e,t){t.drawCallCount+=e.drawCallCount,t.triangleCount+=e.triangleCount}function Mo(){return this.getCameraStaticDrawSets().some(e=>e.publicSet.enabled&&this.isStaticDrawSetCameraVisible(e)&&!e.cpuVisibility&&"opaque"===e.drawStage&&e.draws.length>0)}function Po(e,t,i){if(!(this.state.device&&this.state.presentPipeline&&this.state.fullscreenTextureBindGroupLayout&&this.state.linearClampSampler))return;let r=this.state.presentBindGroups.get(t);r||(r=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,r));const n=e.beginRenderPass({label:"renderer-present-pass",colorAttachments:[{view:i,clearValue:{r:this.clearColor[0],g:this.clearColor[1],b:this.clearColor[2],a:this.clearColor[3]},loadOp:"clear",storeOp:"store"}]});n.setPipeline(this.state.presentPipeline),Fi(n,0,r),n.draw(3),n.end()}function Bo(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 Do(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 Io(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 To(e,t){if(Ns.center.copy(e.boundsCenter),Ns.radius=e.boundsRadius,!js.intersectsSphere(Ns))return!1;if(e.staticLocalBoundsCenter)return!0;const i=e.detailCulling??f(e.sourceObject);return g(e.boundsCenter,e.boundsRadius,$s,t,t,qs,.85*i.shadowMinScreenSize,i.shadowMaxDistance,Ws)}function Ro(e,t,i,r){let n=null,a=null,s=null,o=!1,l=0,c=0,u=null,d=null,h=null,p=null;for(const f of t){if("directionalShadow"===r.passKind&&!r.preculled&&!To(f,this.state.directionalShadowTextureSize))continue;if("prepass"!==r.passKind&&!f.castShadow)continue;if("prepass"===r.passKind&&null===f.material.depthVertexShader&&Us(f.material))continue;if("skip"===r.customDepthMode&&f.customDepthMaterial)continue;const t="use"===r.customDepthMode&&f.customDepthMaterial?f.customDepthMaterial:"ignore"!==r.customDepthMode&&Xs(f,r.passKind)?f.material:null,m=t?this.getDepthPassMaterialResourceForDraw(t,r.passKind,f):null;if(!m&&!Zs(f))continue;const g=null!==f.skinning,v=m?.pipeline??(g&&r.fallbackSkinnedPipeline?r.fallbackSkinnedPipeline:"instanced-direct"===this.getDrawInstanceAccessMode(f)&&r.fallbackPipelineDirect?r.fallbackPipelineDirect:r.fallbackPipeline);u!==v&&(u=v,e.setPipeline(v));const x="prepass"===r.passKind?this.resolveSceneBindGroupForDraw(f,r.fallbackBindGroup):this.resolveShadowBindGroupForDraw(f,r.fallbackBindGroup,r.shadowCameraBuffer);d!==x&&(d=x,Fi(e,0,x)),m&&h!==m.bindGroup&&(h=m.bindGroup,e.setBindGroup(1,h)),(m?.usesSkinning??g)&&f.skinning&&p!==f.skinning.bindGroup&&(p=f.skinning.bindGroup,Fi(e,2,p));const w=f.geometryResource,b=m?.vertexAttributes??(g?L:z),y=s!==b;y&&(s=b,o=b.some(e=>"instance"===e.stepMode)),(y||n!==f.geometryKey||a!==w||o&&(l!==f.instanceStart||c!==f.instanceCount))&&(n=f.geometryKey,a=w,l=f.instanceStart,c=f.instanceCount,this.bindGeometryVertexBuffers(e,f.geometry,w,b,f.instanceStart,f.instanceCount,f.wireframe)),f.indexed&&(f.wireframe?w.wireframeIndex:w.index)?e.drawIndexed(f.count,f.instanceCount,f.start,0,f.instanceStart):e.draw(f.count,f.instanceCount,f.start,f.instanceStart),this.recordDraw(f,i)}}var Vo=class extends Map{oldest=null;newest=null;touch(e,t){e.lastUsedExtractionVersion=t,this.newest!==e&&(this.unlink(e),e.previous=this.newest,this.newest?this.newest.next=e:this.oldest=e,this.newest=e)}add(e,t,i){const r=this.get(e);r?r.push(t):this.set(e,[t]),this.touch(t,i)}prune(e){for(;this.oldest&&e-this.oldest.lastUsedExtractionVersion>120;){const e=this.oldest,t=this.get(e.hash),i=t.indexOf(e);t.splice(i,1),0===t.length&&this.delete(e.hash),this.unlink(e),e.bundle=null}}clear(){let e=this.oldest;for(;e;){const t=e.next;e.bundle=null,e.previous=null,e.next=null,e=t}this.oldest=this.newest=null,super.clear()}unlink(e){e.previous?e.previous.next=e.next:this.oldest===e&&(this.oldest=e.next),e.next?e.next.previous=e.previous:this.newest===e&&(this.newest=e.previous),e.previous=e.next=null}};import{Box3 as Go,Mesh as zo,Sphere as Lo}from"three";import{Vector3 as Uo}from"three";var ko=class{entries=[];pending=[];root=null;stack=[];stateStack=[];retired=0;add(e,t){const i={...t,boundsCenter:t.boundsCenter.clone(),value:e,active:!0};return this.pending.push(i),i}remove(e){e.active&&(e.active=!1,this.retired++)}clear(){this.entries.length=this.pending.length=this.stack.length=this.stateStack.length=0,this.root=null,this.retired=0}prepareQuery(){if(!this.root||this.pending.length+this.retired>Math.max(128,this.entries.length/4)){this.entries=this.entries.filter(e=>e.active);for(const e of this.pending)e.active&&this.entries.push(e);this.pending.length=0,this.retired=0,this.root=this.entries.length?this.build(0,this.entries.length):null}}query(e,t){if(!this.entries.length&&!this.pending.length)return;this.prepareQuery();const i=this.stack;for(i.length=0,this.root&&i.push(this.root);i.length;){const r=i.pop();if(e(r))if(r.left&&r.right)i.push(r.left,r.right);else for(let i=r.start;i<r.end;i++){const r=this.entries[i];r.active&&e(r)&&t(r.value)}}for(const i of this.pending)i.active&&e(i)&&t(i.value)}queryWithState(e,t,i){if(!this.entries.length&&!this.pending.length)return;this.prepareQuery();const r=this.stack,n=this.stateStack;for(r.length=n.length=0,this.root&&(r.push(this.root),n.push(i));r.length;){const i=r.pop(),a=e(i,n.pop());if(!(a<0))if(i.left&&i.right)r.push(i.left,i.right),n.push(a,a);else for(let r=i.start;r<i.end;r++){const i=this.entries[r];i.active&&e(i,a)>=0&&t(i.value)}}for(const r of this.pending)r.active&&e(r,i)>=0&&t(r.value)}build(e,t){let i=1/0,r=1/0,n=1/0,a=-1/0,s=-1/0,o=-1/0,l=0,c=1/0,u=0,d=!1,h=!1;for(let p=e;p<t;p++){const e=this.entries[p],t=e.boundsCenter,f=e.boundsRadius;i=Math.min(i,t.x-f),a=Math.max(a,t.x+f),r=Math.min(r,t.y-f),s=Math.max(s,t.y+f),n=Math.min(n,t.z-f),o=Math.max(o,t.z+f),l=Math.max(l,e.maxMemberRadius),c=Math.min(c,e.minScreenSize),d||=0===e.maxDistance,u=Math.max(u,e.maxDistance),h||=e.castShadow}const p=new Uo((i+a)/2,(r+s)/2,(n+o)/2),f={start:e,end:t,boundsCenter:p,boundsRadius:Math.hypot(a-p.x,s-p.y,o-p.z),maxMemberRadius:l,minScreenSize:c,maxDistance:d?0:u,castShadow:h,left:null,right:null};if(t-e>16){const l=a-i>=s-r&&a-i>=o-n?"x":s-r>=o-n?"y":"z",c=this.entries.slice(e,t).sort((e,t)=>e.boundsCenter[l]-t.boundsCenter[l]);for(let t=0;t<c.length;t++)this.entries[e+t]=c[t];const u=e+t>>>1;f.left=this.build(e,u),f.right=this.build(u,t)}return f}},Ao=class{index=new ko;roots=new Set;children=new Map;invalidateChildren=e=>{e.target&&this.children.delete(e.target)};observed=new Set;indexedParents=new Map;registrations=new Set;registrationByRoot=new Map;meshSnapshots=new WeakMap;traversals=new WeakMap;getMeshSnapshot(e){return this.meshSnapshots.get(e)}queryScene=null;queryVisit=null;visitRoot=e=>{let t=e;for(;t&&t!==this.queryScene;t=t.parent)if(!t.visible)return;t===this.queryScene&&t?.visible&&this.queryVisit(e)};register(e){let t;this.registrationByRoot.get(e)?.dispose();let i=!1,r=!1,n=null;const a=new Set,s=[],o=()=>l(),l=()=>{if(t&&this.index.remove(t),t=void 0,this.roots.delete(e),this.traversals.delete(e),n){this.children.delete(n);const e=this.indexedParents.get(n)-1;e>0?this.indexedParents.set(n,e):(this.indexedParents.delete(n),this.observed.delete(n),n.removeEventListener("childadded",this.invalidateChildren),n.removeEventListener("childremoved",this.invalidateChildren)),n=null}for(const e of a)e.removeEventListener("childadded",o),e.removeEventListener("childremoved",o);a.clear();for(const e of s)this.meshSnapshots.get(e)?.onInvalidate?.(),this.meshSnapshots.delete(e);if(s.length=0,i||r)return;let l=!0,c=0,u=1/0,d=0,h=!1,p=!1;const m=new Go,g=new Lo,v=new Go;if(e.updateWorldMatrix(!0,!0),e.traverse(e=>{if(a.add(e),e.addEventListener("childadded",o),e.addEventListener("childremoved",o),e.isFogVolumeObject&&(l=!1),!(e instanceof zo))return void("Group"!==e.type&&"Object3D"!==e.type&&(l=!1));(e.isSkinnedMesh||e.isInstancedMesh||e.isBatchedMesh||!e.frustumCulled||e.morphTargetInfluences?.length)&&(l=!1);const t=f(e);e.geometry.boundingSphere||e.geometry.computeBoundingSphere(),e.geometry.boundingSphere?(g.copy(e.geometry.boundingSphere).applyMatrix4(e.matrixWorld),m.union(g.getBoundingBox(v))):l=!1,u=Math.min(u,t.minScreenSize),h||=0===t.maxDistance,p||=e.castShadow,d=Math.max(d,t.maxDistance),c++}),!l||!c)return;if(m.getBoundingSphere(g),!Number.isFinite(g.radius)||!Number.isFinite(g.center.lengthSq()))return;for(const e of a)e instanceof zo&&(g.copy(e.geometry.boundingSphere).applyMatrix4(e.matrixWorld),this.meshSnapshots.set(e,{boundsCenter:g.center.clone(),boundsRadius:g.radius,frontFaceCW:e.matrixWorld.determinant()<0,detailCulling:f(e)}),s.push(e));m.getBoundingSphere(g),this.roots.add(e);const x=Array.from(a),w=new Uint32Array(x.length),b=new Uint8Array(x.length),y=[];for(let e=0;e<x.length;e++){for(;y.length&&x[y[y.length-1]]!==x[e].parent;)w[y.pop()]=e;b[e]=x[e]instanceof zo?1:0,y.push(e)}for(;y.length;)w[y.pop()]=x.length;this.traversals.set(e,{objects:x,subtreeEnds:w,meshes:b}),n=e.parent,n&&(this.indexedParents.set(n,(this.indexedParents.get(n)??0)+1),this.children.delete(n)),t=this.index.add(e,{boundsCenter:g.center,boundsRadius:g.radius,maxMemberRadius:g.radius,minScreenSize:u,maxDistance:h?0:d,castShadow:p})},c=()=>l();e.addEventListener("added",c),e.addEventListener("removed",c),l();const u={update:()=>{r||l()},setEditing:e=>{r||e===i||(i=e,l())},dispose:()=>{r||(r=!0,l(),e.removeEventListener("added",c),e.removeEventListener("removed",c),this.registrations.delete(u),this.registrationByRoot.delete(e))}};return this.registrations.add(u),this.registrationByRoot.set(e,u),u}traversalChildren(e){if(!this.indexedParents.has(e))return e.children;let t=this.children.get(e);return t||(t=e.children.filter(e=>!this.roots.has(e)),this.children.set(e,t),this.observed.has(e)||(this.observed.add(e),e.addEventListener("childadded",this.invalidateChildren),e.addEventListener("childremoved",this.invalidateChildren))),t}visitMeshes(e,t,i){const r=this.traversals.get(e);if(!r)return;const{objects:n,subtreeEnds:a,meshes:s}=r;for(let e=0;e<n.length;){const r=n[e];!r.visible||i&&!i(r)?e=a[e]:(s[e]&&t(r),e++)}}query(e,t,i){this.queryScene=e,this.queryVisit=i;try{this.index.query(t,this.visitRoot)}finally{this.queryScene=null,this.queryVisit=null}}queryWithState(e,t,i,r){this.queryScene=e,this.queryVisit=i;try{this.index.queryWithState(t,this.visitRoot,r)}finally{this.queryScene=null,this.queryVisit=null}}dispose(){for(const e of this.registrations)e.dispose();for(const e of this.observed)e.removeEventListener("childadded",this.invalidateChildren),e.removeEventListener("childremoved",this.invalidateChildren);this.observed.clear(),this.indexedParents.clear(),this.children.clear(),this.roots.clear(),this.index.clear()}};import{Matrix4 as Fo,OrthographicCamera as Oo,Vector3 as Eo}from"three";var jo=(e,t)=>void 0!==e&&Number.isFinite(e)&&e>0?e:t,$o=class{constructor(e){this.cameras=e,this.layers=e.map(()=>({valid:!1,source:null,direction:new Eo,rangeX:0,rangeY:0,nextUpdateMs:0,lastUpdateMs:-1/0,candidate:new Oo}))}cameras;layers;updateMask=0;forcedMask=0;settings={enabled:!1,maxUpdateHz:60,cascadeUpdateHz:[60,30,15,7.5],maxUpdatesPerFrame:2,coverageMargin:.05,teleportDistance:10};previousProjection=new Fo;previousPosition=new Eo;viewerPosition=new Eo;corner=new Eo;viewerValid=!1;revision=-1;timeMs=0;setOptions(e){this.settings={enabled:e.enabled??!1,maxUpdateHz:jo(e.maxUpdateHz,60),cascadeUpdateHz:(e.cascadeUpdateHz?.length?e.cascadeUpdateHz:[60,30,15,7.5]).map(e=>jo(e,60)),maxUpdatesPerFrame:Math.max(1,Math.floor(jo(e.maxUpdatesPerFrame,2))),coverageMargin:Number.isFinite(e.coverageMargin)?Math.max(0,Math.min(.5,e.coverageMargin)):.05,teleportDistance:jo(e.teleportDistance,10)},this.invalidate()}invalidate(){for(const e of this.layers)e.valid=!1}interval(e){const t=this.settings.cascadeUpdateHz;return 1e3/Math.min(this.settings.maxUpdateHz,t[Math.min(e,t.length-1)])}prepare(e,t,i,r,n,a){this.timeMs=n,this.updateMask=this.forcedMask=0,t.getWorldPosition(this.viewerPosition);let s=this.revision!==a;if(this.viewerValid){s||=this.viewerPosition.distanceToSquared(this.previousPosition)>this.settings.teleportDistance**2;const e=t.projectionMatrix.elements,i=this.previousProjection.elements,r=!0===t.isPerspectiveCamera;for(let t=0;t<16;t++)if((r?8!==t&&9!==t:12!==t&&13!==t)&&Math.abs(e[t]-i[t])>1e-6){s=!0;break}}this.revision=a,this.previousPosition.copy(this.viewerPosition),this.previousProjection.copy(t.projectionMatrix),this.viewerValid=!0,s&&this.invalidate();for(let t=0;t<this.layers.length;t++){const n=this.layers[t],a=e[t];if(!a?.castShadow){n.valid=!1;continue}const s=n.candidate;s.left=a.shadowCameraLeft,s.right=a.shadowCameraRight,s.top=a.shadowCameraTop,s.bottom=a.shadowCameraBottom,s.near=a.shadowCameraNear,s.far=a.shadowCameraFar,s.position.copy(a.position),s.lookAt(a.target),s.updateMatrixWorld(!0),s.updateProjectionMatrix();const o=t<r?i[t].x:0,l=t<r?i[t].y:0,c=!n.valid||n.source!==a.sourceLight||n.direction.distanceToSquared(a.direction)>1e-12||n.rangeX!==o||n.rangeY!==l||!this.containsCandidate(this.cameras[t],s);this.settings.enabled&&!c||(this.updateMask|=1<<t,c&&(this.forcedMask|=1<<t))}let o=this.settings.maxUpdatesPerFrame;for(;this.settings.enabled&&o-- >0;){let t=-1,i=1/0;for(let r=0;r<e.length;r++){if(!e[r].castShadow||this.updateMask&1<<r)continue;const a=this.layers[r].nextUpdateMs;n+1e-6>=a&&a<i&&(i=a,t=r)}if(t<0)break;this.updateMask|=1<<t}for(let t=0;t<e.length;t++){if(!(this.updateMask&1<<t))continue;const n=e[t],a=this.layers[t],s=this.cameras[t];if(s.copy(a.candidate),this.settings.enabled){const e=this.settings.coverageMargin,t=s.right-s.left,i=s.top-s.bottom,r=s.far-s.near;s.left-=t*e,s.right+=t*e,s.bottom-=i*e,s.top+=i*e,s.near-=r*e,s.far+=r*e,s.updateProjectionMatrix()}a.source=n.sourceLight,a.direction.copy(n.direction),a.rangeX=t<r?i[t].x:0,a.rangeY=t<r?i[t].y:0}}commit(e){const t=this.layers[e],i=this.interval(e);!t.valid||this.forcedMask&1<<e||!Number.isFinite(t.nextUpdateMs)?t.nextUpdateMs=this.timeMs+i+e*(1e3/this.settings.maxUpdateHz)/this.layers.length:(t.nextUpdateMs+=Math.max(1,Math.floor((this.timeMs-t.nextUpdateMs)/i)+1)*i,t.nextUpdateMs<=this.timeMs&&(t.nextUpdateMs=this.timeMs+i)),t.lastUpdateMs=this.timeMs,t.valid=!0}containsCandidate(e,t){for(let i=0;i<2;i++)for(let r=0;r<2;r++)for(let n=0;n<2;n++){this.corner.set(i?t.right:t.left,r?t.top:t.bottom,-(n?t.far:t.near)).applyMatrix4(t.matrixWorld).applyMatrix4(e.matrixWorldInverse);const a=1e-5;if(this.corner.x<e.left-a||this.corner.x>e.right+a||this.corner.y<e.bottom-a||this.corner.y>e.top+a||this.corner.z<-e.far-a||this.corner.z>-e.near+a)return!1}return!0}};import{Sphere as Wo,Vector3 as No}from"three";function _o(e,t){return e.id-t.id}function Ho(e){return`${Math.floor(e.x/32)}:${Math.floor(e.y/32)}:${Math.floor(e.z/32)}`}function qo(e,t){if(!t)return[e];const i=new Map;for(const t of e){const e=Ho(t.boundsCenter);let r=i.get(e);r||(r=[],i.set(e,r)),r.push(t)}return[...i.values()]}var Ko=class{constructor(e,t,i,r,n){this.state=e,this.staticDrawSets=t,this.getGeometryResourceForGeometry=i,this.resolveMaterial=r,this.ensureWireframeIndex=n}state;staticDrawSets;getGeometryResourceForGeometry;resolveMaterial;ensureWireframeIndex;revision=0;spatialIndex=new ko;spatialEntries=new Map;cameraCandidates=[];shadowCandidates=[];shadowFrustum=null;shadowSphere=new Wo;testShadow=e=>!!e.castShadow&&(this.shadowSphere.center.copy(e.boundsCenter),this.shadowSphere.radius=e.boundsRadius,this.shadowFrustum.intersectsSphere(this.shadowSphere));collectShadow=e=>{e.publicSet.enabled&&"late"!==e.drawStage&&this.shadowCandidates.push(e)};markCameraVisible=e=>{e.publicSet.enabled&&(e.cameraVisible=!0,this.cameraCandidates.push(e))};updateCameraVisibility(e){for(const e of this.cameraCandidates)e.cameraVisible=!1;this.cameraCandidates.length=0,this.spatialIndex.query(e,this.markCameraVisible),this.cameraCandidates.sort(_o)}queryShadowResources(e){return this.shadowCandidates.length=0,this.shadowFrustum=e,this.spatialIndex.query(this.testShadow,this.collectShadow),this.shadowFrustum=null,this.shadowCandidates}nextStaticDrawSetId=1;activeMutableTransforms=!1;activeObject=null;activeDetailDefaults;activeMaterialSnapshots=null;snapshotSources=new WeakMap;getSourceMaterial(e){return this.snapshotSources.get(e)??e}getGeometryResource(e){return this.getGeometryResourceForGeometry(e)}resolveStaticMaterial(e){const t=this.resolveMaterial(e);if(!t||!this.activeMaterialSnapshots)return t;let i=this.activeMaterialSnapshots.get(t);return i||(i=t.clone(),this.snapshotSources.set(i,t),i.name=t.name?`${t.name} (static snapshot)`:"Static draw-set material snapshot",this.activeMaterialSnapshots.set(t,i)),i}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 i=t.label??`static-draw-set-${this.nextStaticDrawSetId}`,r=t.onUnsupported??"throw",n=t.allowUnsortedLateDraws??!1,a=[],s=new Sn(4096),o=(e,t)=>{if("skip"!==r)throw new Error(`StaticDrawSet "${i}" does not support ${e.type||"Object3D"} "${e.name||e.uuid}": ${t}.`)};this.activeMutableTransforms=!0===t.mutableTransforms,this.activeDetailDefaults=t.detailCulling,e.updateMatrixWorld(!0);const l=new Map;this.activeMaterialSnapshots=l;try{e.traverseVisible(e=>{this.activeObject=e,e.isSkinnedMesh?o(e,"skinned meshes are dynamic"):e.isBatchedMesh?this.collectStaticBatchedMesh(e,s,a,i,o,n):e.isInstancedMesh?this.collectStaticInstancedMesh(e,s,a,i,o,n):e.isMesh&&this.collectStaticMesh(e,s,a,i,o,n)})}catch(e){for(const e of l.values())e.dispose();throw e}finally{this.activeMutableTransforms=!1,this.activeMaterialSnapshots=null,this.activeObject=null,this.activeDetailDefaults=void 0}const c=new Map;if(!(s.instanceCount>=512&&!a.some(e=>e.transparent)))return this.createResource(i,a,s,l,!0===t.mutableTransforms);let u=1/0,d=1/0,h=1/0;for(const e of a)u=Math.min(u,e.boundsCenter.x),d=Math.min(d,e.boundsCenter.y),h=Math.min(h,e.boundsCenter.z);for(const e of a){const t=e.boundsCenter,i=`${Math.floor((t.x-u)/256)}:${Math.floor((t.y-d)/256)}:${Math.floor((t.z-h)/256)}`;let r=c.get(i);r||c.set(i,r=[]),r.push(e)}if(c.size<=1)return this.createResource(i,a,s,l,!0===t.mutableTransforms);const p=[];try{for(const[e,r]of c)p.push(this.createResource(`${i}-${e}`,r,s,0===p.length?l:new Map,!0===t.mutableTransforms))}catch(e){for(const e of p)e.dispose();if(!p.length)for(const e of l.values())e.dispose();throw e}let f=!0,m=!1;return{label:i,get enabled(){return f},set enabled(e){f=e;for(const t of p)t.enabled=e},get drawCount(){return p.reduce((e,t)=>e+t.drawCount,0)},get instanceCount(){return p.reduce((e,t)=>e+t.instanceCount,0)},updateTransforms(){if(!m)for(const e of p)e.updateTransforms()},dispose(){if(!m){m=!0;for(const e of p)e.dispose()}}}}createResource(e,t,i,r,n){if(!this.state.device)throw new Error("Renderer is not initialized.");const{draws:a,instanceData:s}=this.mergeStaticDraws(t,i),o=a.some(e=>e.transparent),l=a.some(e=>!e.transparent);if(o&&l)throw new Error(`StaticDrawSet "${e}" cannot mix opaque and late materials; register them as separate sets.`);const c=this.createVisibleMaterialBindings(a),u=this.createShadowChunks(a),d=Math.max(4,s.byteLength),h=this.state.device.createBuffer({label:`${e}-static-instance-buffer`,size:256*Math.ceil(d/256),usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST});s.floatLength>0?this.state.device.queue.writeBuffer(h,0,s.rawData.buffer,0,s.byteLength):this.state.device.queue.writeBuffer(h,0,P,0,C);const p={mode:"packed",buffer:h,colorBuffer:null,sceneBindGroup:null,shadowBindGroup:null,shadowBindGroups:new Map,sceneBindGroupVersion:0,shadowBindGroupVersion:0};for(const e of a)e.residentInstanceBinding=p;const f=this.createStaticDrawMetadataResource(e,a),m=this.createStaticInstanceVisibilityResource(e,a,s),g=new No(1/0,1/0,1/0),v=new No(-1/0,-1/0,-1/0);let x=0,w=1/0,b=0,y=!1;const S=m.metadata;for(let e=0;e<s.instanceCount;e++){const t=8*e,i=S[t+3];F.set(S[t],S[t+1],S[t+2]),fn(g,v,F,i),x=Math.max(x,i),w=Math.min(w,S[t+6]),y||=0===S[t+7],b=Math.max(b,S[t+7])}const M=(new No).addVectors(g,v).multiplyScalar(.5),B={boundsCenter:M,boundsRadius:M.distanceTo(v),maxMemberRadius:x,minScreenSize:w,maxDistance:y?0:b,castShadow:a.some(e=>e.castShadow)},D=new Uint32Array([a.length,this.state.hizMipCount,s.instanceCount,0]),I=this.state.device.createBuffer({label:`${e}-visibility-params-buffer`,size:16,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),T=new Uint32Array([a.length,this.state.hizMipCount,s.instanceCount,0]),R=this.state.device.createBuffer({label:`${e}-post-visibility-params-buffer`,size:16,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST});this.state.device.queue.writeBuffer(I,0,D,0,4),this.state.device.queue.writeBuffer(R,0,T,0,4);const V={temporalDepthSupported:ks(a),spatialBounds:B,cpuVisibility:!o&&1===a.length&&1===s.instanceCount,cameraVisible:!1,cameraDetailVisible:!1,id:this.nextStaticDrawSetId++,label:e,publicSet:null,ownedMaterials:[...r.values()],draws:a,shadowChunks:u,drawStage:o?"late":"opaque",drawCallCount:a.length,triangleCount:a.reduce((e,t)=>e+Math.floor(Math.max(0,t.count)/3)*Math.max(0,t.instanceCount),0),instanceCount:s.instanceCount,instanceBuffer:h,residentInstanceBinding:p,drawMetadataResource:f,instanceVisibilityResource:m,visibilityParamsBuffer:I,visibilityParamsUpload:D,postVisibilityParamsBuffer:R,postVisibilityParamsUpload:T,visibilityBindGroup:null,postVisibilityBindGroup:null,visibilityClearBindGroup:null,visibilityIndirectBuildBindGroup:null,postVisibilityIndirectBuildBindGroup:null,visibleSceneBindGroup:null,visibleSceneBindGroupVersion:0,visibleDepthSceneBindGroup:null,visibleDepthSceneBindGroupVersion:0,visibleMaterialBindings:c,visibleDrawMaterialResources:new Array(a.length),visibleIndirectSubmissionStreams:null,visibleIndirectStreamsSceneBindGroup:null,visibleIndirectStreamsSampleCount:-1,visibleIndirectStreamsColorFormatsKey:"",visibilityBindGroupHizVersion:0,lastPreVisibilityFrameToken:0,lastVisibilityFrameToken:0,indirectForwardBundleCache:new Vo,directForwardBundle:null,directForwardBundleSampleCount:-1,directForwardBundleSceneBindGroup:null,depthPrepassBundle:null,depthPrepassBundleSceneBindGroup:null,indirectDepthPrepassBundles:{prepass:null,postpass:null},shadowBundles:new WeakMap,depthMaterialResources:new Map},G=n?s:null;let z=!0;const L=this,U={label:e,get enabled(){return z},set enabled(e){z!==e&&(z=e,L.revision++)},get drawCount(){return V.draws.length},get instanceCount(){return V.instanceCount},updateTransforms:()=>{if(!G)throw new Error("StaticDrawSet requires mutableTransforms to refresh transforms.");this.staticDrawSets.includes(V)&&this.updateTransforms(V,G)},dispose:()=>{this.disposeStaticDrawSetResource(V)}};return V.publicSet=U,this.staticDrawSets.push(V),this.revision++,s.instanceCount>0&&this.spatialEntries.set(V,this.spatialIndex.add(V,B)),U}updateTransforms(e,t){const i=this.state.device,r=e.instanceVisibilityResource.metadata,n=t.rawData,a=new Float32Array(4),s=new No,o=new No,l=new No(1/0,1/0,1/0),c=new No(-1/0,-1/0,-1/0);let u=0;for(let t=0;t<e.draws.length;t++){const d=e.draws[t];s.set(1/0,1/0,1/0),o.set(-1/0,-1/0,-1/0);for(const e of d.sourceRanges){const t=e.sourceObject;t.updateWorldMatrix(!0,!1);for(let i=0;i<e.instanceCount;i++){const a=e.sourceInstanceIds?.[i]??0;if(t.isBatchedMesh){const e=t._instanceInfo?.[a]??t._drawInfo?.[a];e?.active&&e.visible?t.getMatrixAt(a,U):U.makeScale(0,0,0),k.multiplyMatrices(t.matrixWorld,U)}else t.isInstancedMesh?(a<t.count?t.getMatrixAt(a,U):U.makeScale(0,0,0),k.multiplyMatrices(t.matrixWorld,U)):k.copy(t.matrixWorld);const l=e.instanceStart+i,c=l*C;k.toArray(n,c),k.toArray(n,c+24),n[c+23]=0;const h=E.copy(d.staticLocalBoundsCenter).applyMatrix4(k),p=d.staticLocalBoundsRadius*hn(k),f=8*l;r[f]=h.x,r[f+1]=h.y,r[f+2]=h.z,r[f+3]=p,fn(s,o,h,p),u=Math.max(u,p)}}d.boundsCenter.addVectors(s,o).multiplyScalar(.5),d.boundsRadius=d.boundsCenter.distanceTo(o),fn(l,c,d.boundsCenter,d.boundsRadius),a[0]=d.boundsCenter.x,a[1]=d.boundsCenter.y,a[2]=d.boundsCenter.z,a[3]=d.boundsRadius,i.queue.writeBuffer(e.drawMetadataResource.metadataBuffer,t*M*4,a)}if(t.instanceCount){i.queue.writeBuffer(e.instanceBuffer,0,n.buffer,0,t.byteLength),i.queue.writeBuffer(e.instanceVisibilityResource.instanceMetadataBuffer,0,r.buffer);const a=e.spatialBounds;a.boundsCenter.addVectors(l,c).multiplyScalar(.5),a.boundsRadius=a.boundsCenter.distanceTo(c),a.maxMemberRadius=u;const s=this.spatialEntries.get(e);s&&this.spatialIndex.remove(s),this.spatialEntries.set(e,this.spatialIndex.add(e,a))}for(const t of e.shadowChunks){s.set(1/0,1/0,1/0),o.set(-1/0,-1/0,-1/0);for(const i of t.drawIndices){const t=e.draws[i];fn(s,o,t.boundsCenter,t.boundsRadius)}t.boundsCenter.addVectors(s,o).multiplyScalar(.5),t.boundsRadius=t.boundsCenter.distanceTo(o)}e.lastPreVisibilityFrameToken=e.lastVisibilityFrameToken=0,this.state.temporalHiZHistoryValid=!1,this.revision++}createVisibleMaterialBindings(e){const t=new Map;for(let i=0;i<e.length;i+=1){const r=e[i],n=`${Hr(r.material)}:${r.receiveShadow?1:0}:${r.usesBatching?1:0}`;let a=t.get(n);a||(a={material:r.material,receiveShadow:r.receiveShadow,usesBatching:r.usesBatching,drawIndices:[],resource:null},t.set(n,a)),a.drawIndices.push(i)}return[...t.values()]}createShadowChunks(e){const t=new Map;for(let i=0;i<e.length;i+=1){const r=e[i];if(!r.castShadow||r.transparent)continue;const n=Ho(r.boundsCenter);let a=t.get(n);a||(a=[],t.set(n,a)),a.push(i)}const i=[];for(const r of t.values())for(let t=0;t<r.length;t+=64){const n=r.slice(t,t+64);let a=1/0,s=1/0,o=1/0,l=-1/0,c=-1/0,u=-1/0;for(const t of n){const i=e[t],r=i.boundsCenter,n=i.boundsRadius;a=Math.min(a,r.x-n),s=Math.min(s,r.y-n),o=Math.min(o,r.z-n),l=Math.max(l,r.x+n),c=Math.max(c,r.y+n),u=Math.max(u,r.z+n)}const d=new No(.5*(a+l),.5*(s+c),.5*(o+u)),h=l-d.x,p=c-d.y,f=u-d.z;i.push({drawIndices:n,drawCallCount:n.length,triangleCount:n.reduce((t,i)=>{const r=e[i];return t+Math.floor(Math.max(0,r.count)/3)*Math.max(0,r.instanceCount)},0),boundsCenter:d,boundsRadius:Math.sqrt(h*h+p*p+f*f),bundles:new WeakMap})}return i}mergeStaticDraws(e,t){e.sort(Yr);const i=[],r=e.reduce((e,t)=>e+t.instanceCount*C,0),n=new Sn(Math.max(1024,r));for(let r=0;r<e.length;){const a=e[r],s=n.instanceCount;n.appendRange(t,a.instanceStart,a.instanceCount);const o=a.sourceRanges;for(const e of o)e.instanceStart+=s-a.instanceStart;let l=a.instanceCount,c=a.boundsCenter.x-a.boundsRadius,u=a.boundsCenter.y-a.boundsRadius,d=a.boundsCenter.z-a.boundsRadius,h=a.boundsCenter.x+a.boundsRadius,p=a.boundsCenter.y+a.boundsRadius,f=a.boundsCenter.z+a.boundsRadius,m=r+1;for(;m<e.length&&en(a,e[m]);){const i=e[m];n.appendRange(t,i.instanceStart,i.instanceCount);for(const e of i.sourceRanges)o.push({...e,instanceStart:s+l+e.instanceStart-i.instanceStart});l+=i.instanceCount;const r=i.boundsCenter.x-i.boundsRadius,a=i.boundsCenter.y-i.boundsRadius,g=i.boundsCenter.z-i.boundsRadius,v=i.boundsCenter.x+i.boundsRadius,x=i.boundsCenter.y+i.boundsRadius,w=i.boundsCenter.z+i.boundsRadius;r<c&&(c=r),a<u&&(u=a),g<d&&(d=g),v>h&&(h=v),x>p&&(p=x),w>f&&(f=w),m+=1}const g=.5*(c+h),v=.5*(u+p),x=.5*(d+f),w=h-g,b=p-v,y=f-x;a.instanceStart=s,a.instanceCount=l,a.boundsCenter.set(g,v,x),a.boundsRadius=Math.sqrt(w*w+b*b+y*y),i.push(a),r=m}return{draws:i,instanceData:n}}collectStaticMesh(e,t,i,r,n,a){if(!(null!==e.geometry.index))return void n(e,"non-indexed geometry cannot use the v1 indirect static path");if(vn(e))return void n(e,"custom depth materials are not supported by StaticDrawSet v1");const s=this.getGeometryResource(e.geometry),o=dn(e.geometry),l=F.copy(o.center).applyMatrix4(e.matrixWorld),c=o.radius*hn(e.matrixWorld),u=Nr(t,e.matrixWorld,1,1,1,1),d=Array.isArray(e.material)?e.material:null,h=Array.isArray(e.material)?null:e.material;if(e.geometry.groups.length>0){for(const t of e.geometry.groups){const r=d?d[t.materialIndex??0]??d[0]:h,p=this.resolveStaticMaterial(r);if(!p){n(e,"all static mesh materials must be WGSLShaderMaterial");continue}if(p.transparent&&!a){n(e,"transparent materials are not supported by StaticDrawSet v1");continue}if(Object.keys(p.getGraphTextureInputs()).length>0&&!a){n(e,"scene-texture materials are not supported by StaticDrawSet v1");continue}const f=Ar(e.geometry,!0,t.start,t.count);f<=0||i.push(this.createStaticDrawRecord(e.geometry,e.geometry,s,p,!1,t.start,f,u,1,l.x,l.y,l.z,c,o.center,o.radius,e.matrixWorld.determinant()<0))}return}const p=h??d?.[0]??null,f=this.resolveStaticMaterial(p);if(!f)return void n(e,"all static mesh materials must be WGSLShaderMaterial");if(f.transparent&&!a)return void n(e,"transparent materials are not supported by StaticDrawSet v1");if(Object.keys(f.getGraphTextureInputs()).length>0&&!a)return void n(e,"scene-texture materials are not supported by StaticDrawSet v1");const m=Fr(e.geometry,!0);m.count<=0||i.push(this.createStaticDrawRecord(e.geometry,e.geometry,s,f,!1,m.start,m.count,u,1,l.x,l.y,l.z,c,o.center,o.radius,e.matrixWorld.determinant()<0))}collectStaticInstancedMesh(e,t,i,r,n,a){const s=this.resolveStaticMaterial(e.material);if(!s)return void n(e,"static instanced meshes must use WGSLShaderMaterial");if(s.transparent&&!a)return void n(e,"transparent materials are not supported by StaticDrawSet v1");if(Object.keys(s.getGraphTextureInputs()).length>0&&!a)return void n(e,"scene-texture materials are not supported by StaticDrawSet v1");if(vn(e))return void n(e,"custom depth materials are not supported by StaticDrawSet v1");if(null===e.geometry.index)return void n(e,"non-indexed geometry cannot use the v1 indirect static path");const o=Fr(e.geometry,!0);if(o.count<=0||e.count<=0)return;const l=dn(e.geometry),c=this.getGeometryResource(e.geometry),u=[];for(let t=0;t<e.count;t+=1){e.getMatrixAt(t,U),k.multiplyMatrices(e.matrixWorld,U);const i=e.instanceColor?e.instanceColor.getComponent(t,0):1,r=e.instanceColor&&e.instanceColor.itemSize>1?e.instanceColor.getComponent(t,1):1,n=e.instanceColor&&e.instanceColor.itemSize>2?e.instanceColor.getComponent(t,2):1,a=e.instanceColor&&e.instanceColor.itemSize>3?e.instanceColor.getComponent(t,3):1,s=E.copy(l.center).applyMatrix4(k),o=l.radius*hn(k);u.push({matrix:new Float32Array(k.elements),color0:i,color1:r,color2:n,color3:a,batchingId:t,boundsCenter:s.clone(),boundsRadius:o})}for(const r of qo(u,!s.transparent&&!s.requiresLatePass())){const n=F.set(1/0,1/0,1/0),a=O.set(-1/0,-1/0,-1/0),u=t.instanceCount;for(const e of r)t.appendMatrixAndColorValues(e.matrix,e.color0,e.color1,e.color2,e.color3),fn(n,a,e.boundsCenter,e.boundsRadius);const d=.5*(n.x+a.x),h=.5*(n.y+a.y),p=.5*(n.z+a.z),f=a.x-d,m=a.y-h,g=a.z-p;i.push(this.createStaticDrawRecord(e.geometry,e.geometry,c,s,!1,o.start,o.count,u,r.length,d,h,p,Math.sqrt(f*f+m*m+g*g),l.center,l.radius)),this.activeMutableTransforms&&(i[i.length-1].sourceRanges[0].sourceInstanceIds=r.map(e=>e.batchingId))}}collectStaticBatchedMesh(e,t,i,r,n,a){const s=this.resolveStaticMaterial(e.material);if(!s)return void n(e,"static batched meshes must use WGSLShaderMaterial");if(s.transparent&&!a)return void n(e,"transparent materials are not supported by StaticDrawSet v1");if(Object.keys(s.getGraphTextureInputs()).length>0&&!a)return void n(e,"scene-texture materials are not supported by StaticDrawSet v1");if(vn(e))return void n(e,"custom depth materials are not supported by StaticDrawSet v1");if(null===e.geometry.index)return void n(e,"non-indexed geometry cannot use the v1 indirect static path");const o=e,l=this.getGeometryResource(e.geometry),c=o._geometryCount??0,u=[],d=new Map;for(let t=0;t<c;t+=1){const i=e.getGeometryRangeAt(t);if(!i||i.count<=0)continue;const r=Ar(e.geometry,!0,i.start,i.count);if(r<=0)continue;const n=e.getBoundingSphereAt(t,A),a={geometryId:t,start:i.start,count:r,localBoundsCenter:n?n.center.clone():new No,localBoundsRadius:n?.radius??1,instances:[]};d.set(t,a),u.push(a)}const h=o._instanceInfo??o._drawInfo??[],p=o._matricesTexture?.image.data,f=o._colorsTexture?.image.data;for(let t=0;t<h.length;t+=1){const i=h[t];if(!i?.active||!i.visible&&!this.activeMutableTransforms)continue;const r=d.get(i.geometryIndex);if(!r)continue;p?_r(U,p,16*t):e.getMatrixAt(t,U),k.multiplyMatrices(e.matrixWorld,U);const n=4*t;i.visible||k.makeScale(0,0,0);const a=f?f[n+0]??1:1,s=f?f[n+1]??1:1,o=f?f[n+2]??1:1,l=f?f[n+3]??1:1,c=E.copy(r.localBoundsCenter).applyMatrix4(k),u=r.localBoundsRadius*hn(k);r.instances.push({matrix:new Float32Array(k.elements),color0:a,color1:s,color2:o,color3:l,batchingId:t,boundsCenter:c.clone(),boundsRadius:u})}for(const r of u)if(0!==r.instances.length)for(const n of qo(r.instances,!s.transparent&&!s.requiresLatePass())){const a=F.set(1/0,1/0,1/0),o=O.set(-1/0,-1/0,-1/0),c=t.instanceCount;for(const e of n)t.appendMatrixAndColorValues(e.matrix,e.color0,e.color1,e.color2,e.color3,e.batchingId),fn(a,o,e.boundsCenter,e.boundsRadius);const u=.5*(a.x+o.x),d=.5*(a.y+o.y),h=.5*(a.z+o.z),p=o.x-u,f=o.y-d,m=o.z-h,g=Math.sqrt(p*p+f*f+m*m);i.push(this.createStaticDrawRecord(e.geometry,e.geometry,l,s,!0,r.start,r.count,c,n.length,u,d,h,g,r.localBoundsCenter,r.localBoundsRadius)),this.activeMutableTransforms&&(i[i.length-1].sourceRanges[0].sourceInstanceIds=n.map(e=>e.batchingId))}}createStaticDrawRecord(e,t,i,r,n,a,s,o,l,c,u,d,h,p,m,g=!1){const v=Hr(r),x=r.wireframe&&"triangle-list"===r.primitiveTopology;x&&this.ensureWireframeIndex(e,i);const w=Hr(t);return{geometry:e,geometryKey:x?i.wireframeIndex:t,geometryResource:i,material:r,customDepthMaterial:null,residentInstanceBinding:null,sourceObject:null,sourceRanges:[{sourceObject:this.activeObject,instanceStart:o,instanceCount:l}],detailCulling:f(this.activeObject,this.activeDetailDefaults),frontFaceCW:g,usesBatching:n,geometryGroup:null,batchKey:qr(r,t,!0,a,s,null),batchHash:Kr(v,w,!0,a,s,0),indexed:!0,wireframe:x,start:x?2*a:a,count:x?2*s:s,transparent:r.transparent||r.requiresLatePass(),renderOrder:0,hasRenderCallbacks:!1,castShadow:this.activeObject?.castShadow??!1,receiveShadow:this.activeObject?.receiveShadow??!1,sortMaterialId:v,sortGeometryId:w,sortCustomDepthMaterialId:0,skinning:null,materialResource:null,instanceStart:o,instanceCount:l,boundsCenter:new No(c,u,d),boundsRadius:h,sortDepth:0,transparentSortGroup:0,transparentSortOrder:0,staticLocalBoundsCenter:p.clone(),staticLocalBoundsRadius:m}}createStaticDrawMetadataResource(e,t){if(!this.state.device)throw new Error("Renderer is not initialized.");const i=Math.max(1,t.length),r=new Float32Array(i*M),n=new Uint32Array(5*i),a=new Uint32Array(5*i);for(let e=0;e<t.length;e+=1){const i=t[e],s=e*M;r[s+0]=i.boundsCenter.x,r[s+1]=i.boundsCenter.y,r[s+2]=i.boundsCenter.z,r[s+3]=i.boundsRadius,r[s+4]=i.count,r[s+5]=i.start,r[s+6]=i.instanceStart,r[s+7]=i.instanceCount,r[s+8]=1,r[s+9]=0,r[s+10]=0,r[s+11]=0;const o=5*e;n[o+0]=i.count,n[o+1]=i.instanceCount,n[o+2]=i.start,n[o+3]=0,n[o+4]=i.instanceStart,a[o+0]=i.count,a[o+1]=0,a[o+2]=i.start,a[o+3]=0,a[o+4]=i.instanceStart}const s=this.state.device.createBuffer({label:`${e}-static-draw-metadata-buffer`,size:i*M*4,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST}),o=this.state.device.createBuffer({label:`${e}-static-indirect-draw-buffer`,size:5*i*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*i*4,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.INDIRECT|GPUBufferUsage.COPY_DST});return this.state.device.queue.writeBuffer(s,0,r,0,r.length),this.state.device.queue.writeBuffer(o,0,n,0,n.length),this.state.device.queue.writeBuffer(l,0,a,0,a.length),{count:t.length,capacity:i,metadataBuffer:s,indirectBuffer:o,postIndirectBuffer:l}}createStaticInstanceVisibilityResource(e,t,i){if(!this.state.device)throw new Error("Renderer is not initialized.");const r=i.instanceCount,n=Math.max(32,32*r),a=new ArrayBuffer(n),s=new Float32Array(a),o=new Uint32Array(a);for(let e=0;e<t.length;e+=1){const r=t[e],n=r.staticLocalBoundsCenter??dn(r.geometry).center,a=r.staticLocalBoundsRadius??dn(r.geometry).radius;for(let t=0;t<r.instanceCount;t+=1){const l=r.instanceStart+t,c=l*C,u=8*l;U.fromArray(i.rawData,c);const d=F.copy(n).applyMatrix4(U),h=a*hn(U);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,s[u+6]=r.detailCulling?.minScreenSize??0,s[u+7]=r.detailCulling?.maxDistance??0}}const l=this.state.device.createBuffer({label:`${e}-static-instance-visibility-metadata`,size:256*Math.ceil(n/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*r)/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*r)/256),usage:GPUBufferUsage.STORAGE});return r>0&&this.state.device.queue.writeBuffer(l,0,a),{metadata:s,instanceMetadataBuffer:l,visibleInstanceIndicesBuffer:c,visibleCountsBuffer:u,postVisibleCountsBuffer:d,visibleInstanceMaskBuffer:h,instanceCount:r}}disposeStaticDrawSetResource(e){const t=this.staticDrawSets.indexOf(e);if(t<0)return;const i=this.spatialEntries.get(e);i&&this.spatialIndex.remove(i),this.spatialEntries.delete(e),e.disposeDirectionalGpuShadows?.(),this.staticDrawSets.splice(t,1);const r=this.cameraCandidates.indexOf(e);r>=0&&this.cameraCandidates.splice(r,1),this.shadowCandidates.length=0,e.cameraVisible=!1,this.revision++;const n=new Set;for(const t of e.draws)t.materialResource&&n.add(t.materialResource);for(const t of e.visibleMaterialBindings)t.resource&&n.add(t.resource);for(const t of e.visibleDrawMaterialResources)t&&n.add(t);for(const t of e.depthMaterialResources.values())for(const e of t)e&&n.add(e);for(const e of n)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()}};import{RGBAFormat as Yo}from"three";function Zo(e,t,i,r){const n=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),a=new Uint8Array(n.byteLength);for(let e=0;e<r;e++){const r=e*t*i;for(let e=0;e<i;e++){const s=r+e*t;a.set(n.subarray(s,s+t),r+(i-e-1)*t)}}return a}var Xo=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 i="non-filtering"===t,r=i?"nearest":Er(e.magFilter),n=i?"nearest":Er(e.minFilter),a=i?"nearest":Er(e.minFilter),s="comparison"===t?function(e){switch(e){case sr:return"never";case er:return"less";case Zi:return"equal";case tr:return"less-equal";case Xi:return"greater";case or:return"not-equal";case Ji:return"greater-equal";case Ki:return"always";default:return}}(e.compareFunction):void 0,o=i||"linear"!==r||"linear"!==n||"linear"!==a?1:Math.max(1,e.anisotropy);return this.state.device.createSampler({label:`${e.uuid}-sampler`,addressModeU:Or(e.wrapS),addressModeV:Or(e.wrapT),addressModeW:Or(e.wrapR??e.wrapT),magFilter:r,minFilter:n,mipmapFilter:a,maxAnisotropy:o,compare:s})}uploadDataTextureResource(e,t,i){if(!this.state.device)throw new Error("Renderer is not initialized.");const r=_t(i.format);if(null===r)throw new Error(`Texture format "${i.format}" from "${e.constructor.name}" cannot be uploaded with queue.writeTexture.`);const n=e.mipmaps;if(n&&n.length>0){for(let a=0;a<n.length;a+=1){const s=n[a];if(!s?.data)continue;const o=s.width??Math.max(1,i.width>>a),l=s.height??Math.max(1,i.height>>a),c=s.depth??i.depthOrArrayLayers;this.state.device.queue.writeTexture({texture:t,mipLevel:a},$r(e.flipY?Zo(s.data,o*r,l,c):s.data),{bytesPerRow:o*r,rowsPerImage:l},{width:o,height:l,depthOrArrayLayers:c})}return}const a=e.image;a?.data&&this.state.device.queue.writeTexture({texture:t},e.flipY?Zo(a.data,i.width*r,i.height,i.depthOrArrayLayers):a.data,{bytesPerRow:i.width*r,rowsPerImage:i.height},{width:i.width,height:i.height,depthOrArrayLayers:i.depthOrArrayLayers})}uploadCompressedTextureResource(e,t,i){if(!this.state.device)throw new Error("Renderer is not initialized.");let r="bc1-rgba-unorm"===(n=i.format)||"bc1-rgba-unorm-srgb"===n?{byteLength:8,width:4,height:4}:"bc2-rgba-unorm"===n||"bc2-rgba-unorm-srgb"===n||"bc3-rgba-unorm"===n||"bc3-rgba-unorm-srgb"===n?{byteLength:16,width:4,height:4}:"bc4-r-unorm"===n||"bc4-r-snorm"===n?{byteLength:8,width:4,height:4}:"bc5-rg-unorm"===n||"bc5-rg-snorm"===n||"bc6h-rgb-ufloat"===n||"bc6h-rgb-float"===n||"bc7-rgba-unorm"===n||"bc7-rgba-unorm-srgb"===n?{byteLength:16,width:4,height:4}:"etc2-rgb8unorm"===n||"etc2-rgb8unorm-srgb"===n||"etc2-rgb8a1unorm"===n||"etc2-rgb8a1unorm-srgb"===n?{byteLength:8,width:4,height:4}:"etc2-rgba8unorm"===n||"etc2-rgba8unorm-srgb"===n?{byteLength:16,width:4,height:4}:"eac-r11unorm"===n||"eac-r11snorm"===n?{byteLength:8,width:4,height:4}:"eac-rg11unorm"===n||"eac-rg11snorm"===n||"astc-4x4-unorm"===n||"astc-4x4-unorm-srgb"===n?{byteLength:16,width:4,height:4}:"astc-5x4-unorm"===n||"astc-5x4-unorm-srgb"===n?{byteLength:16,width:5,height:4}:"astc-5x5-unorm"===n||"astc-5x5-unorm-srgb"===n?{byteLength:16,width:5,height:5}:"astc-6x5-unorm"===n||"astc-6x5-unorm-srgb"===n?{byteLength:16,width:6,height:5}:"astc-6x6-unorm"===n||"astc-6x6-unorm-srgb"===n?{byteLength:16,width:6,height:6}:"astc-8x5-unorm"===n||"astc-8x5-unorm-srgb"===n?{byteLength:16,width:8,height:5}:"astc-8x6-unorm"===n||"astc-8x6-unorm-srgb"===n?{byteLength:16,width:8,height:6}:"astc-8x8-unorm"===n||"astc-8x8-unorm-srgb"===n?{byteLength:16,width:8,height:8}:"astc-10x5-unorm"===n||"astc-10x5-unorm-srgb"===n?{byteLength:16,width:10,height:5}:"astc-10x6-unorm"===n||"astc-10x6-unorm-srgb"===n?{byteLength:16,width:10,height:6}:"astc-10x8-unorm"===n||"astc-10x8-unorm-srgb"===n?{byteLength:16,width:10,height:8}:"astc-10x10-unorm"===n||"astc-10x10-unorm-srgb"===n?{byteLength:16,width:10,height:10}:"astc-12x10-unorm"===n||"astc-12x10-unorm-srgb"===n?{byteLength:16,width:12,height:10}:"astc-12x12-unorm"===n||"astc-12x12-unorm-srgb"===n?{byteLength:16,width:12,height:12}:null;var n;if(!r&&e.format===Yo){const e=_t(i.format);null!==e&&(r={width:1,height:1,byteLength:e})}if(!r)throw new Error(`Compressed texture format "${i.format}" is not supported for upload.`);if(!0===e.isCompressedCubeTexture){const n=e.image;for(let e=0;e<n.length;e+=1){const a=n[e]?.mipmaps??[];for(let n=0;n<a.length;n+=1){const s=a[n];if(!s?.data)continue;const o=s.width??Math.max(1,i.width>>n),l=s.height??Math.max(1,i.height>>n),c=Math.max(1,Math.ceil(o/r.width)),u=Math.max(1,Math.ceil(l/r.height));this.state.device.queue.writeTexture({texture:t,mipLevel:n,origin:{x:0,y:0,z:e}},$r(s.data),{bytesPerRow:c*r.byteLength,rowsPerImage:u},{width:c*r.width,height:u*r.height,depthOrArrayLayers:1})}}return}const a=e.mipmaps;for(let e=0;e<a.length;e+=1){const n=a[e];if(!n?.data)continue;const s=n.width??Math.max(1,i.width>>e),o=n.height??Math.max(1,i.height>>e),l=Math.max(1,Math.ceil(s/r.width)),c=Math.max(1,Math.ceil(o/r.height));this.state.device.queue.writeTexture({texture:t,mipLevel:e},$r(n.data),{bytesPerRow:l*r.byteLength,rowsPerImage:c},{width:l*r.width,height:c*r.height,depthOrArrayLayers:i.depthOrArrayLayers})}}uploadExternalTextureResource(e,t,i){if(!this.state.device)throw new Error("Renderer is not initialized.");if(!0===e.isCubeTexture){const r=e.image;if(!Array.isArray(r)||6!==r.length)return void this.warnSkippedExternalTextureUpload(e,i,"CubeTexture must provide exactly six face images.");for(let n=0;n<r.length;n+=1){const a=jr(r[n]);if(!a)return void this.warnSkippedExternalTextureUpload(e,i,`CubeTexture face ${n} 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:n}},{width:i.width,height:i.height,depthOrArrayLayers:1})}catch(t){return void this.warnSkippedExternalTextureUpload(e,i,`CubeTexture face ${n} could not be copied: ${Jo(t)}`)}}return}const r=function(e){return jr(e.image)}(e);if(r)try{this.state.device.queue.copyExternalImageToTexture({source:r,flipY:e.flipY},{texture:t},{width:i.width,height:i.height,depthOrArrayLayers:1})}catch(t){this.warnSkippedExternalTextureUpload(e,i,`copyExternalImageToTexture failed: ${Jo(t)}`)}else this.warnSkippedExternalTextureUpload(e,i,"Texture.image is not an HTML image, canvas, video, ImageBitmap, or OffscreenCanvas.")}warnSkippedExternalTextureUpload(e,t,i){if(this.skippedExternalTextureWarnings.has(e))return;this.skippedExternalTextureWarnings.add(e);const r=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. ${i}`,{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:r?.constructor?.name??typeof r,width:r?.width,height:r?.height,depth:r?.depth,src:r?.currentSrc??r?.src,hasData:null!=r?.data,keys:null==r?[]:Object.keys(r).slice(0,16)},userData:e.userData})}uploadTextureResource(e,t,i){!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,i):this.uploadDataTextureResource(e,t,i):this.uploadCompressedTextureResource(e,t,i)}getTextureResource(e){if(!this.state.device)throw new Error("Renderer is not initialized.");const t=this.textureCache.get(e),i=$t(e,this.state.device);if(t&&t.version===e.version&&t.width===i.width&&t.height===i.height&&t.depthOrArrayLayers===i.depthOrArrayLayers&&t.format===i.format&&t.textureDimension===i.textureDimension&&t.viewDimension===i.viewDimension&&t.sampleType===i.sampleType&&t.samplerBindingType===i.samplerBindingType&&t.mipLevelCount===i.mipLevelCount)return t;this.destroyTextureResource(t);const r=performance.now(),n=this.state.device.createTexture({label:`${e.uuid}-texture`,size:{width:i.width,height:i.height,depthOrArrayLayers:i.depthOrArrayLayers},dimension:i.textureDimension,format:i.format,mipLevelCount:i.mipLevelCount,usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|(i.compressed||"3d"===i.textureDimension?0:GPUTextureUsage.RENDER_ATTACHMENT)}),a=performance.now();this.uploadTextureResource(e,n,i);const s=performance.now()-a,o=a-r;(s>16||o>16)&&this.warnSlowTextureUpload(e,i,o,s,t?.version);const l=this.createTextureSampler(e,i.samplerBindingType),c={version:e.version,width:i.width,height:i.height,depthOrArrayLayers:i.depthOrArrayLayers,format:i.format,textureDimension:i.textureDimension,viewDimension:i.viewDimension,sampleType:i.sampleType,samplerBindingType:i.samplerBindingType,mipLevelCount:i.mipLevelCount,texture:n,view:n.createView("2d"===i.viewDimension?void 0:"2d-array"===i.viewDimension?{dimension:"2d-array",arrayLayerCount:i.depthOrArrayLayers}:{dimension:i.viewDimension}),sampler:l};return this.textureCache.set(e,c),c}warnSlowTextureUpload(e,t,i,r,n){let a=null;if(!0===e.isCompressedCubeTexture){a=0;for(const t of e.image)for(const e of t.mipmaps??[])a+=e.data?.byteLength??0}else if(e.mipmaps&&e.mipmaps.length>0){a=0;for(const t of e.mipmaps)a+=t.data?.byteLength??0}else a=e.image?.data?.byteLength??null;console.warn("[WebGPU] Slow texture upload",{textureName:e.name||void 0,textureUuid:e.uuid,assetId:e.userData.assetId,textureClass:e.constructor.name,format:t.format,width:t.width,height:t.height,depthOrArrayLayers:t.depthOrArrayLayers,mipLevelCount:t.mipLevelCount,sourceBytes:a,allocationMs:Math.round(100*i)/100,uploadMs:Math.round(100*r)/100,thresholdMs:16,version:e.version,previousVersion:n,timing:"CPU call duration, including browser waits; not GPU transfer time. sourceBytes is null for external images."})}};function Jo(e){return e instanceof Error?e.message:String(e)}function Qo(e){if(e.transparent)switch(e.blending){case aa:return{color:{srcFactor:"src-alpha",dstFactor:"one",operation:"add"},alpha:{srcFactor:"one",dstFactor:"one",operation:"add"}};case ya:return{color:{srcFactor:"zero",dstFactor:"one-minus-src",operation:"subtract"},alpha:{srcFactor:"one",dstFactor:"one",operation:"subtract"}};case fa: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 el(e,t,i,r){if(t<0||e[t]!==i)return-1;let n=0;for(let a=t;a<e.length;a+=1)if(e[a]===i&&(n+=1),e[a]===r&&(n-=1,0===n))return a;return-1}function tl(e,t,i){const r=function(e,t="fsMain"){const i=e.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/.*$/gm,""),r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),n=new RegExp(`@fragment\\s+fn\\s+${r}\\s*\\(`).exec(i);if(!n)return null;const a=i.indexOf("(",n.index),s=el(i,a,"(",")");if(s<0)return null;const o=i.indexOf("{",s+1);if(o<0)return null;const l=i.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(i);if(!h)return null;const p=i.indexOf("{",h.index),f=el(i,p,"{","}");if(f<0)return null;const m=new Set,g=/@location\s*\(\s*(\d+)\s*\)/g,v=i.slice(p+1,f);for(const e of v.matchAll(g))m.add(Number(e[1]));return m}(e);return t.map((e,t)=>null===r||r.has(t)?{format:e,blend:i}:{format:e,writeMask:0})}function il(e,t){const i=Yr(e,t);return 0!==i?i:e.residentInstanceBinding!==t.residentInstanceBinding?Hr(e.residentInstanceBinding)-Hr(t.residentInstanceBinding):e.instanceStart-t.instanceStart}function rl(e){const t=e.userData.motionBlurMode;if(null==t&&e.isSkinnedMesh)return 1;if("number"==typeof t&&Number.isFinite(t))return Math.max(0,Math.min(3,Math.round(t)));switch(t){case"disabled":case"Disabled":return 0;case"cameraOnly":case"CameraOnly":return 1;case"forceObjectBlur":case"ForceObjectBlur":return 3;default:return 2}}function nl(e){const t=Number(e.userData.motionBlurScale??1);return Number.isFinite(t)?Math.max(0,Math.min(t,8)):1}var al="chromium-experimental-multi-draw-indirect";function sl(e,t){return Number(t.castShadow)-Number(e.castShadow)}var ol=[D];var ll=[{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"}];var cl=new WeakMap;function ul(e){return e.wireframe&&"triangle-list"===e.primitiveTopology?"line-list":e.primitiveTopology}function dl(e,t,i){if(!ul(e).startsWith("triangle"))return"none";if("directionalShadow"===t){if(i&&null===e.shadowSide)return"none";const t=e.shadowSide??e.side;return t===ua?"none":t===sa?"front":"back"}return e.side===ua?"none":e.side===sa?"front":"back"}function hl(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 pl=class{pipelineCompilationDiagnostics;canvas;clearColor;powerPreference;shadowMapSize;directionalShadowsEnabled=!0;spotShadowMapSize;pointShadowMapSize;fallbackMaterial;materialResolver;getMaterialResolutionRevision;materialResolutionEpoch=0;toonOutlineMaterialCache=new WeakMap;fallbackSkinnedMaterial;invokeObjectRenderCallbacks;sampleCount;renderScale;hiZOcclusionCullingEnabled;frameHiZOcclusionCullingNeeded=!0;multiDrawIndirectEnabled;dynamicBatchingEnabled;multiDrawIndirectSupported=!1;tiledPointLights=null;tiledLightingEnabled;transientPointLightsScratch=[];transientPointScoresScratch=new Float64Array(16);renderGraphProfilingEnabled;indirectFirstInstanceSupported=!1;timestampQuerySupported=!1;geometryCache=new WeakMap;skinnedGeometryCache=new Map;skinPaletteCache=new WeakMap;skinPaletteResources=new Set;meshExtractionCache=new WeakMap;resolvedMaterialFrameCache=new WeakMap;repeatedMeshInstances=new WeakMap;repeatedInstanceResources=new Map;instancedMeshExtractionCache=new WeakMap;batchedMeshExtractionCache=new WeakMap;materialUniformData=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;drawMaterialResourceFrameValidation=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 Vo,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:[],spotLightMapTexture:null,spotLightMapView:null,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,sceneColorSnapshotPipeline:null,sceneColorSnapshotBindGroups:new WeakMap,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;defaultVertexAttributeBuffers=new Map;textureManager=new Xo(this.state,this.textureCache);renderGraph=new qa;nativePostSubmit;presentationOverlay;presentationOverlayContext={device:null,encoder:null,targetView:null,targetFormat:"bgra8unorm",presentationWidth:1,presentationHeight:1};directionalShadowCameras=Array.from({length:4},()=>new va(-10,10,10,-10,.1,80));directionalShadowScheduler=new $o(this.directionalShadowCameras);directionalShadowGpu=new Qn;directionalShadowSubmissionStats={bundleHits:0,bundleBuilds:0,selectionHits:0,selections:0};pointShadowCameras=Array.from({length:4},()=>V.map(()=>new xa(90,1,.1,25)));spotShadowCameras=Array.from({length:4},()=>new xa(60,1,.5,500));colorTargetCache=new Map;msaaColorTargetCache=new Map;msaaDepthTargetCache=new Map;sourceInstanceDataScratch=new Sn(4096);opaqueInstanceDataScratch=new Sn(4096);finalInstanceDataScratch=new Sn(4096);residentInstanceUploadsScratch=[];gpuOpaqueDrawsScratch=[];directOpaqueDrawsScratch=[];stagedOpaqueDrawsScratch=[];residentOpaqueDrawsScratch=[];retiredGeometryResources=[];retiredGeometryBuffers=[];vertexAttributeBufferKeyCache=new WeakMap;standardVertexAttributeCache=new WeakMap;geometryVertexBufferFastCache=new WeakMap;vertexAttributeGroupCache=new WeakMap;materialVertexAttributeCache=new WeakMap;sharedVertexAttributeLayouts=new Map;vertexBufferBindingPlanCache=new WeakMap;preparedVertexBufferCache=new WeakMap;vertexAttributeGroupBufferKeyCache=new WeakMap;compileDrawScratch=[];dynamicIndirectSubmissionCache=new WeakMap;indirectStreamKeyCache=new WeakMap;nextIndirectStreamKey=1;indirectBundleInvalidationVersion=0;colorFormatsIdentityCache=new WeakMap;colorFormatsValueCache=new Map([[D,1]]);nextColorFormatsId=2;renderBundleScratch=[];skinnedMaterialBundle=null;skinnedMaterialBundleKey=[];skinnedMaterialBundleKeyScratch=[];skinnedMaterialBundleStats={drawCallCount:0,triangleCount:0};skinnedDepthBundleCache={bundle:null,key:[],scratch:[],stats:{drawCallCount:0,triangleCount:0}};directionalDepthBundleCaches=new WeakMap;directionalDynamicCastersScratch=[];indirectMaterialResourcesScratch=[];directBundleDrawStatsScratch={drawCallCount:0,triangleCount:0};sortedOpaqueBatchesScratch=[];opaqueBatchPool=[];opaqueBatchPoolCount=0;drawCallPool=[];drawCallPoolCount=0;staticDrawSets=[];materialPassStaticBundleCache=new WeakMap;staticDrawSetManager=new Ko(this.state,this.staticDrawSets,e=>this.getGeometryResource(e),e=>this.resolveMaterial(e),(e,t)=>this.ensureWireframeIndex(e,t));staticFrameToken=0;hizResourceVersion=0;graphTextureResourceVersion=0;transmissionSnapshotTexture=null;transmissionSnapshotView=null;transmissionSnapshotSize={width:0,height:0};transmissionMipViews=[];transmissionMipBindGroups=[];transmissionSourceBindGroups=new WeakMap;transmissionSnapshotPipeline=null;transmissionSampler=null;visibilityParamsUpload=new Uint32Array(4);drawMetadataUpload=new Float32Array(0);indirectDrawUpload=new Uint32Array(0);extractedAmbientScratch=new Ma;extractedHemisphereScratch=this.createExtractedHemisphereLightScratch();extractedBoundsMinScratch=new Ca;extractedBoundsMaxScratch=new Ca;extractedDirectionalLightsScratch=Array.from({length:4},()=>this.createExtractedDirectionalLightScratch());extractedPointLightsScratch=Array.from({length:y},()=>this.createExtractedPointLightScratch());extractedSpotLightsScratch=Array.from({length:S},()=>this.createExtractedSpotLightScratch());activeDirectionalLightsScratch=[];activePointLightsScratch=[];activeSpotLightsScratch=[];fogVolumeObjectsScratch=[];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,fogVolumeObjects:this.fogVolumeObjectsScratch,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(104);temporalVisibilityUniformScratch=new Float32Array(44);lightUniformScratch=new Float32Array(G);spotLightMapAtlasSignature="";spotLightMapAtlasSize=0;spotLightMapAtlasLayout=null;spotLightMapAtlasPipeline=null;csmCascadeRanges=Array.from({length:4},()=>new Sa);csmCascadeCount=0;csmCascadeLights=[];shadowCameraUniformScratch=new Float32Array(64);cameraViewProjScratch=new ma;cameraDetailProjectionScratch=new m;cameraProjectionScratch=new ma;projectionJitterPixels=new Sa;temporalVisibilityCurrentViewProj=new ma;temporalVisibilityPreviousViewProj=new ma;motionVectorProjection=new ma;motionVectorCurrentViewProj=new ma;motionVectorPreviousViewProj=new ma;motionVectorProjectionPending=!1;motionVectorHistoryValid=!1;motionVectorHistoryGeneration=1;lastMotionVectorTimeSeconds=Number.NaN;objectMotionHistory=new WeakMap;cameraFrustumPlanesScratch=new Float32Array(24);objectTraversalStackScratch=[];staticSceneSpatialIndex=new Ao;staticMeshDraws=new WeakMap;staticInstanceSlots=new ia(1024);retiredStaticInstanceSlots=[];staticSpatialDraws=new WeakSet;staticSpatialDrawRevision=0;staticSpatialBatches=new WeakMap;spatialShadowPlanes=Array.from({length:4},()=>new Float32Array(24));spatialShadowCount=0;spatialLocalShadowSpheres=new Float64Array(512);spatialLocalShadowCount=0;spatialShadowMatrix=new ma;spatialIncludeOffscreen=!1;spatialCameraLayers=0;testSpatialCamera=e=>un(this.cameraFrustumPlanesScratch,e.boundsCenter.x,e.boundsCenter.y,e.boundsCenter.z,e.boundsRadius)&&v(e,this.cameraViewProjScratch,this.state.width,this.state.height,this.transparentSortCameraPositionScratch,this.cameraDetailProjectionScratch);testSpatialScene=(e,t)=>{if(this.spatialIncludeOffscreen)return 0;if(64!==t){if((t=function(e,t,i,r,n,a){for(let s=0,o=1;s<6;s++,o<<=1){if(!(a&o))continue;const l=4*s,c=e[l]*t+e[l+1]*i+e[l+2]*r+e[l+3];if(c<-n)return-1;c>=n&&(a&=~o)}return a}(this.cameraFrustumPlanesScratch,e.boundsCenter.x,e.boundsCenter.y,e.boundsCenter.z,e.boundsRadius,t))>=0&&v(e,this.cameraViewProjScratch,this.state.width,this.state.height,this.transparentSortCameraPositionScratch,this.cameraDetailProjectionScratch))return t;t=64}return e.castShadow&&this.isSpatialShadowSphereVisible(e.boundsCenter.x,e.boundsCenter.y,e.boundsCenter.z,e.boundsRadius)?t:-1};filterSpatialCaptureObject=e=>!1!==this.sceneCaptureOptions?.objectFilter?.(e)&&!1!==e.userData.sceneCapture;pushSpatialRoot=e=>{this.objectTraversalStackScratch.push(e)};collectSpatialMesh=e=>{0!==(e.layers.mask&this.spatialCameraLayers)&&(this.extractingCaster=e.castShadow,this.collectMesh(e,this.sourceInstanceDataScratch,this.updateExtractedBoundsFromMatrixScratch,this.spatialIncludeOffscreen?this.isSphereVisibleForCompilationScratch:this.isSpatialSphereVisible))};isSpatialSphereVisible=(e,t,i,r,n)=>!n||un(this.cameraFrustumPlanesScratch,e,t,i,r)||this.extractingCaster&&this.isSpatialShadowSphereVisible(e,t,i,r);isSpatialShadowSphereVisible(e,t,i,r){for(let n=0;n<this.spatialShadowCount;n++)if(un(this.spatialShadowPlanes[n],e,t,i,r))return!0;for(let n=0;n<this.spatialLocalShadowCount;n++){const a=4*n,s=this.spatialLocalShadowSpheres,o=e-s[a],l=t-s[a+1],c=i-s[a+2],u=r+s[a+3];if(o*o+l*l+c*c<=u*u)return!0}return!1}collectSpatialRoot=e=>{if(null!==this.sceneCaptureOptions)for(let t=e;t;t=t.parent)if(!1===this.sceneCaptureOptions.objectFilter?.(t)||!1===t.userData.sceneCapture)return;this.staticSceneSpatialIndex.visitMeshes(e,this.collectSpatialMesh,null===this.sceneCaptureOptions?void 0:this.filterSpatialCaptureObject)};shadowDrawsScratch=[];extractingCaster=!1;cameraDetailHistory=new WeakMap;isSphereVisibleScratch=(e,t,i,r,n)=>this.extractingCaster||!n||un(this.cameraFrustumPlanesScratch,e,t,i,r);isSphereVisibleForCompilationScratch=()=>!0;updateExtractedBoundsFromMatrixScratch=e=>{const t=this.extractedBoundsMinScratch,i=this.extractedBoundsMaxScratch,r=e[12],n=e[13],a=e[14];r<t.x&&(t.x=r),n<t.y&&(t.y=n),a<t.z&&(t.z=a),r>i.x&&(i.x=r),n>i.y&&(i.y=n),a>i.z&&(i.z=a)};transparentSortCameraPositionScratch=new Ca;transparentSortCameraForwardScratch=new Ca;temporalVisibilityCurrentCameraPosition=new Ca;temporalVisibilityPreviousCameraPosition=new Ca;shadowViewProjScratch=new ma;extractionVersion=0;motionHistoryExtractionVersion=0;sceneCaptureOptions=null;sceneCaptureDisposers=new Set;captureMotionHistory={matrix:new Float32Array(16),generation:0,lastExtractionVersion:-1,valid:!1};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 Ca,target:new Ca,direction:new Ca,color:new Ca,intensity:0,volumetricIntensity:1,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 Ca(0,1,0),skyColor:new Ca,groundColor:new Ca,intensity:0}}createExtractedPointLightScratch(){return{sourceLight:null,position:new Ca,color:new Ca,intensity:0,volumetricIntensity:1,distance:0,range:25,decay:2,castShadow:!1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowIntensity:1,shadowMapSize:this.pointShadowMapSize,shadowCameraNear:.5,shadowCameraFar:500}}createExtractedSpotLightScratch(){return{sourceLight:null,position:new Ca,direction:new Ca(0,-1,0),color:new Ca,intensity:0,volumetricIntensity:1,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,map:null}}skinnedDrawKeys=new ta;skinnedInstanceSlots=new ia;skinnedRenderRecords=new Map;skinningPaletteArena;skeletonPalettes=new xn;getSkeletonBoneBufferForPass=e=>{const t=this.getSkinningPalette(e);if(this.refreshSkinningPalette(t),this.uploadSkinningPalette(t),t.standaloneBuffer||(t.standaloneBuffer=this.state.device.createBuffer({label:"renderer-skinning-compatibility-palette",size:t.allocation.byteLength,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST}),t.standaloneDirty=!0),t.standaloneDirty){const i=e.boneMatrices;this.state.device.queue.writeBuffer(t.standaloneBuffer,0,i.buffer,i.byteOffset,t.allocation.byteLength),t.standaloneDirty=!1}return t.standaloneBuffer};getSkeletonBoneBindingForPass=e=>{const t=this.getSkinningPalette(e);return this.refreshSkinningPalette(t),this.uploadSkinningPalette(t),t.allocation.currentBinding};outlineResolvedFrameCache=new WeakMap;preparedOutlineFrameCache=new WeakMap;opaqueSortMs=0;opaqueSortSamples=new Float64Array(120);opaqueSortSampleIndex=0;opaqueSortSampleCount=0;opaqueSortSampleTotal=0;sortOpaqueDraws(e,t=Yr){const i=this.renderGraphProfilingEnabled?performance.now():0;e.sort(t),this.renderGraphProfilingEnabled&&(this.opaqueSortMs+=performance.now()-i)}constructor(e){this.canvas=e.canvas,this.nativePostSubmit=e.nativePostSubmit,this.presentationOverlay=e.presentationOverlay,this.clearColor=[...e.clearColor??[0,0,0,1]],this.powerPreference=e.powerPreference,this.directionalShadowScheduler.setOptions(e.directionalShadowUpdates??{}),this.directionalShadowGpu.enabled=e.directionalShadowGpuCulling??!0,this.shadowMapSize=e.shadowMapSize??2048,this.spotShadowMapSize=this.shadowMapSize,this.pointShadowMapSize=e.pointShadowMapSize??1024,this.fallbackMaterial=e.fallbackMaterial??null,this.materialResolver=e.materialResolver,this.getMaterialResolutionRevision=e.getMaterialResolutionRevision,this.fallbackSkinnedMaterial=e.fallbackSkinnedMaterial??new pr({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:ll}),this.invokeObjectRenderCallbacks=e.invokeObjectRenderCallbacks??!0,this.state.directionalShadowTextureSize=this.shadowMapSize,this.state.pointShadowTextureSize=this.pointShadowMapSize,this.state.spotShadowTextureSize=this.shadowMapSize,this.sampleCount=gn(e.sampleCount),this.renderScale=hl(e.renderScale),this.hiZOcclusionCullingEnabled=e.hiZOcclusionCulling??!1,this.multiDrawIndirectEnabled=e.multiDrawIndirect??!0,this.dynamicBatchingEnabled=e.dynamicBatching??!0,this.tiledLightingEnabled=e.tiledLighting??!0,this.renderGraphProfilingEnabled=e.renderGraphProfiling??!1}invalidateMaterialResolution(){this.materialResolutionEpoch++,this.extractionVersion+=1}resolveMaterial(e){if(!1===e?.visible)return null;if(e&&fr(e))return e;if(!e)return this.fallbackMaterial;if(!0===e.isLineMaterial)return this.resolveLineMaterial(e);const t=this.resolveAdaptedMaterial(e);return void 0===t?this.fallbackMaterial:t}resolveAdaptedMaterial(e,t){const i=t?this.outlineResolvedFrameCache:this.resolvedMaterialFrameCache,r=i.get(e);if(r?.extractionVersion===this.extractionVersion)return r.material;const n=this.getMaterialResolutionRevision?.(e),a=e.transmission,s=!t&&function(e){if(e.transparent||(e.transmission??0)>0)return!0;if(e instanceof Pa)return null!=e.uniforms.hology_depth_map||null!=e.uniforms.hology_scene_map||null!=e.uniforms.hology_transmission_map;if(e instanceof pr)return e.requiresLatePass();return!1}(e),o=t?.thickness,l=t?.darkening,c=t?t.alpha??e.opacity:void 0;if(void 0!==n&&r?.revision===n&&r.sourceVersion===e.version&&r.transparent===e.transparent&&r.transmission===a&&r.requiresLatePass===s&&r.outlineThickness===o&&r.outlineDarkening===l&&r.outlineAlpha===c&&r.epoch===this.materialResolutionEpoch)return r.extractionVersion=this.extractionVersion,r.material;const u=t?"outline":s?"late":"opaque";let d=this.materialResolver?.(e,u);"opaque"===u&&d?.requiresLatePass()&&(d=this.materialResolver?.(e,"late"));const h=r??{extractionVersion:this.extractionVersion,material:d},p=d&&void 0!==n;return!h.onDispose||p&&h.material===d||(e.removeEventListener("dispose",h.onDispose),h.material?.removeEventListener("dispose",h.onDispose),h.onDispose=void 0),h.extractionVersion=this.extractionVersion,h.material=d,h.revision=d?n:void 0,void 0!==h.revision&&(h.sourceVersion=e.version,h.transparent=e.transparent,h.transmission=a,h.requiresLatePass=s,h.outlineThickness=o,h.outlineDarkening=l,h.outlineAlpha=c,h.epoch=this.materialResolutionEpoch,h.onDispose||(h.onDispose=()=>{h.revision=void 0,h.extractionVersion=-1},e.addEventListener("dispose",h.onDispose),d?.addEventListener("dispose",h.onDispose))),r||i.set(e,h),d}resolveLineMaterial(e){let t=this.lineMaterialCache.get(e);t||(t=new pr({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 let offsetW = offset * clip.w;\n clip = vec4<f32>(clip.x + offsetW.x, clip.y + offsetW.y, clip.z, 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 ca(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:ua,depthTest:e.depthTest,depthWrite:e.depthWrite}),this.lineMaterialCache.set(e,t));const i=e,r=i.color;return r&&t.uniforms.color.value.copy(r),t.uniforms.opacity.value=i.opacity??1,t.uniforms.linewidth.value=i.linewidth??1,t.transparent=e.transparent||(i.opacity??1)<1,t.depthTest=e.depthTest,t.depthWrite=e.depthWrite,t}resolveLineBasicMaterial(e,t){let i=this.lineBasicMaterialCache.get(e);i||(i=new Map,this.lineBasicMaterialCache.set(e,i));let r=i.get(t);r||(r=new pr({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 ca(1,1,1),opacity:1},primitiveTopology:t,depthTest:e.depthTest,depthWrite:e.depthWrite}),i.set(t,r));const n=e;return n.color&&r.uniforms.color.value.copy(n.color),r.uniforms.opacity.value=n.opacity??1,r.transparent=e.transparent||(n.opacity??1)<1,r.depthTest=e.depthTest,r.depthWrite=e.depthWrite,r}resolveSkinnedMaterial(e){const t=this.resolveMaterial(e);return null===t?null:function(e){const t=cl.get(e);if(t?.version===e.version&&t.shader===e.vertexShader&&t.attributes===e.vertexAttributes)return t.result;const i=e.vertexAttributes.find(e=>"skinIndex"===e.name),r=e.vertexAttributes.find(e=>"skinWeight"===e.name),n=e.vertexShader.includes("USE_SKINNING")||"uint32x4"===i?.format&&"float32x4"===r?.format&&e.vertexShader.includes("rendererSkinPosition(");return cl.set(e,{version:e.version,shader:e.vertexShader,attributes:e.vertexAttributes,result:n}),n}(t)?t:this.fallbackSkinnedMaterial}hasRenderCallbacks(e){return null!==e&&this.invokeObjectRenderCallbacks&&function(e){return null!==e&&(e.onBeforeRender!==lr.prototype.onBeforeRender||e.onAfterRender!==lr.prototype.onAfterRender)}(e)}async initialize(t){if(!("gpu"in navigator))throw new Error("WebGPU is not available in this browser.");const i=t??await navigator.gpu.requestAdapter({powerPreference:this.powerPreference});if(!i)throw new Error("A WebGPU adapter could not be created.");const r=[];i.features.has("indirect-first-instance")&&r.push("indirect-first-instance"),i.features.has("timestamp-query")&&r.push("timestamp-query"),i.features.has("texture-compression-bc")&&r.push("texture-compression-bc"),i.features.has("texture-compression-etc2")&&r.push("texture-compression-etc2"),i.features.has("texture-compression-astc")&&r.push("texture-compression-astc"),i.features.has("float32-filterable")&&r.push("float32-filterable"),i.features.has(al)&&r.push(al);const l=i.limits;try{this.state.device=await i.requestDevice({requiredFeatures:r,requiredLimits:{maxTextureArrayLayers:l.maxTextureArrayLayers,maxBufferSize:l.maxBufferSize,maxStorageBufferBindingSize:l.maxStorageBufferBindingSize,maxStorageBuffersPerShaderStage:l.maxStorageBuffersPerShaderStage}})}catch(e){throw new Error("A WebGPU device could not be created.")}!function(t){if(e.has(t))return;const i={loadingStartedAt:performance.now(),loadingRequests:[],loading:!0,phase:"initializing",objects:new WeakMap,origins:new Map,descriptorOrigins:new WeakMap,history:new Map};e.set(t,i);for(const e of["createShaderModule","createBindGroupLayout","createPipelineLayout"]){const r=t[e];t[e]=function(s){const o=r.call(t,s);return i.objects.set(o,"createShaderModule"===e?{shaderHash:n(s.code),codeLength:s.code.length}:a(s,i)),o}}for(const e of["createRenderPipeline","createRenderPipelineAsync","createComputePipeline","createComputePipelineAsync"]){const r=t[e];"function"==typeof r&&(t[e]=function(n){const l=i.descriptorOrigins.get(n)??i.origins.get(n.label),c=e.includes("Render")?"render":"compute",u=c+":"+(l?.key??n.label??"unlabelled"),d=a(n,i),h=i.history.get(u)??[],p=JSON.stringify(d);let f;for(let e=h.length-1;e>=0;e--)if(h[e].signature===p){f=h[e];break}const m=f??h[h.length-1],g={signature:p,state:d,origin:l,label:n.label,phase:i.phase,status:"pending"},v=!i.loading,x=v?void 0:{kind:c,signature:p,state:d,shaders:o(d),label:n.label,origin:l,status:"pending",durationMs:0,async:e.endsWith("Async")};x&&i.loadingRequests.push(x);let w=0;v&&console.warn("[WebGPU pipeline] Created after loading",{method:e,label:n.label,phase:i.phase,origin:l,reason:"failed"===f?.status?"retry after a failed creation request":"pending"===f?.status?"identical descriptor requested while prior compilation is pending":f?"identical descriptor requested again; cache miss, eviction, or another owner":m?"new variant or changed shader/layout/render state":"first recorded pipeline for this origin",previous:m?{label:m.label,phase:m.phase,status:m.status,origin:m.origin}:null,changes:m?s(m.state,d):[],originChanges:m?s(m.origin,l):[],descriptor:d,stack:new Error("Pipeline creation request").stack,historyLimit:"last 16 requests per origin; up to 4096 origins"}),h.push(g),h.length>16&&h.shift(),i.history.size>=4096&&!i.history.has(u)&&i.history.delete(i.history.keys().next().value),i.history.set(u,h);const b=(t,i)=>{g.status=t,x&&(x.status=t,x.durationMs=performance.now()-w),v&&console.info("[WebGPU pipeline] Creation result",{method:e,label:n.label,status:t,[e.endsWith("Async")?"readyAfterMs":"creationCallMs"]:performance.now()-w,error:i,timingMeaning:e.endsWith("Async")?"time until pipeline ready":"handle creation only; GPU compilation may stall at first use"})};w=performance.now();try{const i=r.call(t,n);return e.endsWith("Async")?i.then(e=>(b("ready"),e),e=>{throw b("failed",e),e}):(b("handle returned"),i)}catch(e){throw b("failed",e),e}})}}(this.state.device);let c=!1;if("function"==typeof this.state.device.addEventListener&&this.state.device.addEventListener("uncapturederror",e=>{c||(console.error("Uncaptured WebGPU device error",e.error.message,e.error),c=!0)}),this.state.device.lost.then(e=>{"destroyed"!==e.reason&&console.error("WebGPU device lost",e.reason,e.message)}),this.indirectFirstInstanceSupported=r.includes("indirect-first-instance"),this.timestampQuerySupported=r.includes("timestamp-query"),this.multiDrawIndirectSupported=r.includes(al),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:416,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:16016,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST});const u=[];u.push(na.createAsync(this.state.device,this.state.cameraBuffer,this.state.lightBuffer).then(e=>{this.tiledPointLights=e,e.resize(this.state.width,this.state.height)})),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"}},{binding:9,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float",viewDimension:"2d"}},{binding:11,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"uint",viewDimension:"2d"}}]}),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"}},{binding:10,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float",viewDimension:"2d"}},{binding:11,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"uint",viewDimension:"2d"}}]}),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"}},{binding:9,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float",viewDimension:"2d"}},{binding:11,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"uint",viewDimension:"2d"}}]}),this.state.visibleDepthSceneBindGroupLayout=this.state.device.createBindGroupLayout({label:"renderer-visible-depth-scene-layout",entries:[{binding:0,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}},{binding:1,visibility:GPUShaderStage.VERTEX|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"}}]}),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"}},{binding:2,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"read-only-storage"}}]}),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,u.push(this.directionalShadowGpu.initialize(this.state.device,this.state.directShadowBindGroupLayout)),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.transmissionSampler=this.state.device.createSampler({label:"physical-transmission-sampler",magFilter:"linear",minFilter:"linear",mipmapFilter:"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"}),u.push(_.createAsync(this.state.device,{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"}}]}).then(e=>{this.state.hizCopyKernel=e})),u.push(_.createAsync(this.state.device,{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"}}]}).then(e=>{this.state.hizReduceKernel=e})),u.push(_.createAsync(this.state.device,{label:"renderer-visibility-cull",code:En,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"}}]}).then(e=>{this.state.visibilityKernel=e})),u.push(_.createAsync(this.state.device,{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 // Bit 2 is persistent detail hysteresis; bit 0 is frame-local visibility.\n atomicStore(&visibleInstanceMask[index], atomicLoad(&visibleInstanceMask[index]) & 4u);\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"}}]}).then(e=>{this.state.staticVisibilityClearKernel=e})),u.push(_.createAsync(this.state.device,{label:"renderer-static-visibility-cull",code:jn,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"}},{binding:10,visibility:GPUShaderStage.COMPUTE,buffer:{type:"storage"}},{binding:11,visibility:GPUShaderStage.COMPUTE,buffer:{type:"storage"}}]}).then(e=>{this.state.staticVisibilityCullKernel=e})),u.push(_.createAsync(this.state.device,{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"}}]}).then(e=>{this.state.staticVisibilityIndirectBuildKernel=e})),this.state.visibilityParamsBuffer=this.state.device.createBuffer({label:"renderer-visibility-params-buffer",size:16,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),u.push(this.createStaticPipelines()),await Promise.all(u),this.setSize(this.canvas.clientWidth||this.canvas.width||1,this.canvas.clientHeight||this.canvas.height||1),this.state.initialized=!0}createComputeKernel(e){if(!this.state.device)throw new Error("WebGpuRenderer.initialize() must complete before creating compute kernels.");return new _(this.state.device,e)}getDevice(){return this.state.device??null}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)}setDirectionalShadowMapSize(e){const t=Math.max(1,Math.floor(e));t!==this.shadowMapSize&&(this.shadowMapSize=t,t!==this.state.directionalShadowTextureSize&&(this.state.directionalShadowTextureSize=t,this.recreateDirectionalShadowResources()))}setDirectionalShadowUpdateOptions(e){this.directionalShadowScheduler.setOptions(e)}invalidateDirectionalShadows(){this.directionalShadowScheduler.invalidate()}setDirectionalShadowGpuCullingEnabled(e){this.directionalShadowGpu.enabled=e,this.invalidateDirectionalShadows()}setDirectionalShadowsEnabled(e){this.directionalShadowsEnabled=e}setRenderGraphProfilingEnabled(e){this.renderGraphProfilingEnabled=e,e||Cs(this.state)}getRenderGraphProfilingEnabled(){return this.renderGraphProfilingEnabled}getTimestampQuerySupported(){return this.timestampQuerySupported}getSampleCount(){return this.sampleCount}setSampleCount(e){const t=gn(e);t!==this.sampleCount&&(this.sampleCount=t,this.destroyMsaaResources(),this.clearIndirectBundleCache(),this.clearStaticDrawSetBundleCaches())}setRenderScale(e){const t=hl(e);if(t===this.renderScale)return;this.renderScale=t;const i=this.state.pixelRatio;this.setSize(this.state.presentationWidth/i,this.state.presentationHeight/i,i)}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)}setMotionVectorProjection(e){this.motionVectorProjection.copy(e),this.motionVectorProjectionPending=!0}invalidateObjectMotion(e){this.objectMotionHistory.delete(e);const t=this.staticSceneSpatialIndex.getMeshSnapshot(e),i=t&&this.staticMeshDraws.get(t);i&&(i.motionHistory=this.getObjectMotionHistory(e,e.matrixWorld.elements),i.motionFrames=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}resetViewHistory(){this.state.temporalHiZHistoryValid=!1,this.motionVectorHistoryValid=!1,this.motionVectorHistoryGeneration+=1}setHiZOcclusionCullingEnabled(e){this.hiZOcclusionCullingEnabled!==e&&(this.state.temporalHiZHistoryValid=!1),this.hiZOcclusionCullingEnabled=e}getHiZOcclusionCullingEnabled(){return this.hiZOcclusionCullingEnabled}getHiZOcclusionCullingActive(){return this.hiZOcclusionCullingEnabled&&this.indirectFirstInstanceSupported&&this.frameHiZOcclusionCullingNeeded}isStaticDrawSetCameraVisible(e){return null!==this.sceneCaptureOptions||e.cameraVisible}getCameraStaticDrawSets(){return null!==this.sceneCaptureOptions||this.spatialIncludeOffscreen?this.staticDrawSets:this.staticDrawSetManager.cameraCandidates}queryStaticShadowResources(e){return this.staticDrawSetManager.queryShadowResources(e)}updateVisibilityWorkload(e){this.staticDrawSetManager.updateCameraVisibility(this.testSpatialCamera);let t=e.gpuOpaqueDraws.length>=64;for(const e of this.staticDrawSetManager.cameraCandidates){if(!e.publicSet.enabled||"opaque"!==e.drawStage)continue;if(!e.cpuVisibility){t||=e.cameraVisible;continue}const i=e.draws[0],r=i.detailCulling;e.cameraDetailVisible=g(i.boundsCenter,i.boundsRadius,this.cameraViewProjScratch,this.state.width,this.state.height,this.transparentSortCameraPositionScratch,(r?.minScreenSize??0)*(e.cameraDetailVisible?.85:1.15),r?.maxDistance??0,this.cameraDetailProjectionScratch),e.cameraVisible=e.cameraDetailVisible&&un(this.cameraFrustumPlanesScratch,i.boundsCenter.x,i.boundsCenter.y,i.boundsCenter.z,i.boundsRadius)}t!==this.frameHiZOcclusionCullingNeeded&&(this.state.temporalHiZHistoryValid=!1),this.frameHiZOcclusionCullingNeeded=t}setMultiDrawIndirectEnabled(e){this.multiDrawIndirectEnabled=e}getMultiDrawIndirectEnabled(){return this.multiDrawIndirectEnabled}setTiledLightingEnabled(e){this.tiledLightingEnabled=e}setDynamicBatchingEnabled(e){this.dynamicBatchingEnabled=e}getDynamicBatchingEnabled(){return this.dynamicBatchingEnabled}getMultiDrawIndirectSupported(){return this.multiDrawIndirectSupported}getMultiDrawIndirectActive(){return this.multiDrawIndirectEnabled&&this.multiDrawIndirectSupported&&this.getHiZOcclusionCullingActive()}setSize(e,t,i=window.devicePixelRatio||1){if(this.state.pixelRatio=i,this.state.presentationWidth=Math.max(1,Math.floor(e*i)),this.state.presentationHeight=Math.max(1,Math.floor(t*i)),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 i="presentation"===t.resolution?this.state.presentationWidth:this.state.width,r="presentation"===t.resolution?this.state.presentationHeight:this.state.height,n=Math.max(1,Math.floor(i*t.scale)),a=Math.max(1,Math.floor(r*t.scale));t.width===n&&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:D,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:I,usage:GPUTextureUsage.RENDER_ATTACHMENT|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:D,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.invalidateGraphTextureBundles(),this.state.temporalHiZHistoryValid=!1,this.motionVectorHistoryValid=!1,this.motionVectorHistoryGeneration+=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,i=.001*performance.now()){this.renderFrame(e,t,i,!1)}async renderAsync(e,t,i=.001*performance.now()){await this.renderFrame(e,t,i,!0)}createSceneCapture(e,t=512,i=t){const r=this.state.device;if(!r||!this.state.initialized)throw new Error("Renderer is not initialized.");const n=e?.getContext("webgpu");if(e&&!n)throw new Error("The capture canvas does not provide WebGPU.");t=Math.max(1,Math.floor(t)),i=Math.max(1,Math.floor(i)),e&&(e.width=t,e.height=i),n?.configure({device:r,format:this.state.format,alphaMode:"premultiplied"});const a=n?void 0:r.createTexture({label:"scene-capture-output",size:[t,i],format:this.state.format,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING}),s=a?.createView(),o=r.createTexture({label:"scene-capture-color",size:[t,i],format:D,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING}),l=r.createTexture({label:"scene-capture-depth",size:[t,i],format:"depth32float",usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING}),c={colorView:o.createView(),depthView:l.createView(),width:t,height:i},u={drawCallCount:0,triangleCount:0};let d=!1;const h=()=>{d||(d=!0,n?.unconfigure(),a?.destroy(),o.destroy(),l.destroy(),this.sceneCaptureDisposers.delete(h))};return this.sceneCaptureDisposers.add(h),{format:this.state.format,textureView:s,get triangleCount(){return u.triangleCount},prepareAsync:async(e,t,i={})=>{if(d||this.sceneCaptureOptions)throw new Error("Scene capture is unavailable.");if(await this.prepareSceneCaptureAsync(e,t,i),d)throw new Error("Scene capture was disposed during preparation.")},capture:(e,t,i={})=>{if(d||this.sceneCaptureOptions)throw new Error("Scene capture is unavailable.");this.sceneCaptureOptions=i;try{e.matrixWorldAutoUpdate&&e.updateMatrixWorld(),t.updateWorldMatrix(!0,!1);const a=this.extractScene(e,t);this.ensureShadowTextureSizes(a),this.uploadInstanceData(a.instanceData),this.uploadResidentInstanceData(a.residentInstanceUploads),this.ensureTiledLightingSize(),this.state.spotLightMapView||this.updateSpotLightMapAtlas([]),this.updateCameraUniforms(t,e,c),this.updateLightUniforms(a);const o=r.createCommandEncoder({label:"scene-capture-encoder"});u.drawCallCount=0,u.triangleCount=0,this.executeMaterialPass(o,["sceneColor"],this.getSharedSceneBindGroup(),a,u,{clearColor:i.clearColor,overrideMaterial:null==i.overrideMaterial?void 0:(e,t)=>i.overrideMaterial(this.staticDrawSetManager.getSourceMaterial(e),t),objectFilter:e=>i.objectFilter?.(e)??!0},c);const l=s??n.getCurrentTexture().createView();i.postProcess?i.postProcess({device:r,encoder:o,colorView:c.colorView,depthView:c.depthView,sampler:this.state.linearClampSampler,targetView:l,targetFormat:this.state.format,width:c.width,height:c.height,camera:t}):this.executePresentPass(o,c.colorView,l),r.queue.submit([o.finish()]),this.releaseRetiredGeometryResourcesAfterSubmit()}finally{this.sceneCaptureOptions=null}},dispose:h}}async prepareSceneCaptureAsync(e,t,i){const r=[];this.sceneCaptureOptions=i;try{e.matrixWorldAutoUpdate&&e.updateMatrixWorld(),t.updateWorldMatrix(!0,!1);const n=this.extractScene(e,t),a=e=>{if(!this.isSphereVisibleScratch(e.boundsCenter.x,e.boundsCenter.y,e.boundsCenter.z,e.boundsRadius,!0)||e.material.requiresLatePass())return;if(e.sourceRanges?!e.sourceRanges.some(e=>!1!==i.objectFilter?.(e.sourceObject)):!1===i.objectFilter?.(e.sourceObject))return;const t=i.overrideMaterial?i.overrideMaterial(this.staticDrawSetManager.getSourceMaterial(e.material),null!==e.skinning):e.material;t&&r.push({...e,material:t,receiveShadow:!1,materialResource:null})};for(const e of this.getCameraStaticDrawSets())if(e.publicSet.enabled&&"opaque"===e.drawStage)for(const t of e.draws)a(t);for(const e of n.gpuOpaqueDraws)a(e);for(const e of n.directOpaqueDraws)a(e);for(const e of this.staticDrawSets)if(e.publicSet.enabled&&"late"===e.drawStage)for(const t of e.draws)a(t);for(const e of n.transparentDraws)a(e)}finally{this.sceneCaptureOptions=null}const n=ra(),a=new Set,s=[];for(const e of r){const t=n();t&&await t;const i=null!==e.skinning;this.prepareGeometryVertexBuffers(e.geometry,e.geometryResource,this.getMaterialVertexAttributes(e.material,i),e.instanceStart,e.instanceCount);const r=this.getDrawInstanceAccessMode(e),o=this.drawUsesBatching(e),l=tn(e),c=`${e.material.uuid}:${r}:${i}:${o}:${l}`;if(a.has(c))continue;a.add(c);const u=this.getMaterialResourceAsync(e.material,r,!1,ol,i,o,1,l);u.catch(()=>{}),s.push(u)}await Promise.all(s)}compile(e,t){this.prepareSceneForCompilation(e,t,!1)}async compileAsync(e,t){this.state.initialized||await this.initialize();const i={startedAt:performance.now(),preparationMs:0,phases:{},drawCount:0,materialRequestCount:0,cpuTotalsMs:{},slowTextureLookups:[],pipelines:[]};this.pipelineCompilationDiagnostics=i;try{await this.prepareSceneGeometryAsync(e,t);const r=this.prepareSceneForCompilation(e,t,!0);i.preparationMs=performance.now()-i.startedAt,await r}finally{this.pipelineCompilationDiagnostics===i&&(this.pipelineCompilationDiagnostics=void 0);const e=performance.now()-i.startedAt,t=i.pipelines,r=[...t].sort((e,t)=>t.durationMs-e.durationMs).slice(0,12);console.info("[WebGPU] Scene compilation",{elapsedMs:Math.round(e),preparationMs:Math.round(i.preparationMs),phasesMs:i.phases,drawCount:i.drawCount,materialRequestCount:i.materialRequestCount,cpuTotalsMs:Object.fromEntries(Object.entries(i.cpuTotalsMs).map(([e,t])=>[e,Math.round(t)])),slowTextureLookups:i.slowTextureLookups.sort((e,t)=>t.durationMs-e.durationMs).slice(0,12).map(e=>({...e,durationMs:Math.round(e.durationMs)})),pipelineCount:t.length,forwardCount:t.filter(e=>"forward"===e.kind).length,depthCount:t.filter(e=>"depth"===e.kind).length,slowestPipelines:r.map(e=>({kind:e.kind,material:e.material,durationMs:Math.round(e.durationMs),vertexCodeLength:e.vertexCodeLength,fragmentCodeLength:e.fragmentCodeLength}))})}}async prepareSceneGeometryAsync(e,t){const i=ra(),r=[e];for(;r.length;){const e=r.pop();if(!e.visible||!1===this.sceneCaptureOptions?.objectFilter?.(e)||null!==this.sceneCaptureOptions&&!1===e.userData.sceneCapture)continue;e instanceof ga&&t.layers.test(e.layers)&&e.geometry?.getAttribute("position")&&(this.getGeometryResource(e.geometry,!0),e instanceof wa&&this.getSkinnedGeometryResource(e));for(let t=e.children.length-1;t>=0;t--)r.push(e.children[t]);const n=i();n&&await n}}createPMREMGenerator(e=20){if(!this.state.device)throw new Error("WebGpuRenderer.initialize() must complete before creating a PMREM generator.");return new rs({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)}registerStaticSpatialObject(e){return this.staticSceneSpatialIndex.register(e)}disposeStaticDrawSetResource(e){this.staticDrawSetManager.disposeStaticDrawSetResource(e)}renderFrame(e,t,i,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 render().");const n=i-this.lastMotionVectorTimeSeconds;Number.isFinite(this.lastMotionVectorTimeSeconds)&&(!Number.isFinite(n)||n<=0||n>.25)&&(this.motionVectorHistoryValid=!1,this.motionVectorHistoryGeneration+=1),this.lastMotionVectorTimeSeconds=i,this.state.frameTimeSeconds=i,this.staticFrameToken+=1,e.matrixWorldAutoUpdate&&e.updateMatrixWorld(),null===t.parent&&t.matrixWorldAutoUpdate&&t.updateMatrixWorld(),this.opaqueSortMs=0;const a=performance.now(),s=this.extractScene(e,t);this.updateVisibilityWorkload(s);for(const e of s.gpuOpaqueDraws)this.prepareDrawGeometryVertexBuffers(e,!0);for(const e of s.directOpaqueDraws)this.prepareDrawGeometryVertexBuffers(e,!0);for(const e of s.transparentDraws)this.prepareDrawGeometryVertexBuffers(e,!0);this.ensureShadowTextureSizes(s);const o=performance.now()-a;this.renderGraphProfilingEnabled&&(this.opaqueSortSampleTotal-=this.opaqueSortSamples[this.opaqueSortSampleIndex],this.opaqueSortSamples[this.opaqueSortSampleIndex]=this.opaqueSortMs,this.opaqueSortSampleTotal+=this.opaqueSortMs,this.opaqueSortSampleIndex=(this.opaqueSortSampleIndex+1)%this.opaqueSortSamples.length,this.opaqueSortSampleCount=Math.min(this.opaqueSortSampleCount+1,this.opaqueSortSamples.length));const l={drawCallCount:0,triangleCount:0},c=performance.now();this.uploadInstanceData(s.instanceData),this.uploadResidentInstanceData(s.residentInstanceUploads);const u=this.getHiZOcclusionCullingActive();this.uploadDrawMetadata(u?s.gpuOpaqueDraws:[]),this.ensureTiledLightingSize(),this.updateCameraUniforms(t,e),this.updateTemporalVisibilityUniforms(t),this.updateLightUniforms(s);const d=performance.now()-c,h=this.state.device.createCommandEncoder({label:"renderer-command-encoder"}),p=this.state.context.getCurrentTexture().createView(),f=this.getSharedSceneBindGroup(),m=this.getSharedShadowBindGroup();let g=null;const v=this.state.drawMetadataResource;u&&v&&v.count>0&&this.state.hizView&&(this.state.visibilityBindGroup&&this.state.visibilityBindGroupMetadataResource===v||(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:v.metadataBuffer}},{binding:5,resource:{buffer:v.indirectBuffer}}],"renderer-visibility-bind-group"),this.state.visibilityBindGroupMetadataResource=v),g=this.state.visibilityBindGroup),this.renderGraph.reset();const x=this.createGraphBuilderContext(this.renderGraph,h,f,m,g,p,s,l);this.graphBuilder(this.renderGraph,x);const w={device:this.state.device,encoder:h},b=function(e,t,i,r,n){if(!t.renderGraphProfilingEnabled||!e.device)return null;let a=bs.get(e);a&&a.device===e.device||(a?.dispose(),a=new ws(e.device),bs.set(e,a));const s=a,o={frameIndex:e.frameIndex+=1,renderWidth:e.width,renderHeight:e.height,presentationWidth:e.presentationWidth,presentationHeight:e.presentationHeight,cpuTimeMs:0,gpuTimeMs:null,drawCallCount:r.drawCallCount,triangleCount:r.triangleCount,cpuPhases:{extractSceneMs:n.extractSceneMs,opaqueSortMs:n.opaqueSortMs,opaqueSortAverageMs:n.opaqueSortAverageMs,uploadMs:n.uploadMs,renderGraphMs:0},passes:[],timestampQuerySupported:t.timestampQuerySupported,timestampQueryActive:t.timestampQuerySupported,gpuProfilingReason:null,hiZOcclusionCullingEnabled:t.hiZOcclusionCullingEnabled,hiZOcclusionCullingActive:i,visibility:null};let l=null,c=0,u=0;const d={begin:(e,i)=>{if(o.passes=e.map(e=>({name:e.name,cpuTimeMs:0,gpuTimeMs:null})),!t.timestampQuerySupported)return o.timestampQueryActive=!1,void(o.gpuProfilingReason="timestamp-query is not supported by this adapter/device");if(0===e.length)return o.timestampQueryActive=!1,void(o.gpuProfilingReason="no render graph passes were recorded");const r=2*e.length,n=s.acquire(r,!0);if(!n)return Ss.add(h),o.timestampQueryActive=!1,void(o.gpuProfilingReason="GPU profiling readbacks are still pending");l={profile:o,querySet:n.querySet,resolveBuffer:n.resolveBuffer,readBuffer:n.readBuffer,queryCount:r,release:e=>s.release(n,e)}},beforePass:(e,t,i)=>{c=r.triangleCount,u=r.drawCallCount,l&&0===t&&(Lr(i.encoder,l.querySet,{endOfPassWriteIndex:2*t})||(o.timestampQueryActive=!1,o.gpuProfilingReason="timestampWrites marker pass is not available on this browser/runtime",l.release(!1),l=null))},afterPass:(e,t,i,n)=>{o.passes[t].cpuTimeMs=i,o.passes[t].triangleCount=r.triangleCount-c,o.passes[t].drawCallCount=r.drawCallCount-u,l&&(Lr(n.encoder,l.querySet,{beginningOfPassWriteIndex:2*t+1,...t+1<o.passes.length?{endOfPassWriteIndex:2*t+2}:{}})||(o.timestampQueryActive=!1,o.gpuProfilingReason="timestampWrites marker pass is not available on this browser/runtime",l.release(!1),l=null))},end:(t,i,n)=>{if(!Ss.has(h)){if(o.cpuPhases.renderGraphMs=i,o.cpuTimeMs=o.cpuPhases.extractSceneMs+o.cpuPhases.uploadMs+o.cpuPhases.renderGraphMs,o.drawCallCount=r.drawCallCount,o.triangleCount=r.triangleCount,o.directionalShadows={updatedLayers:r.directionalShadowUpdates??0,reusedLayers:r.directionalShadowReused??0,forcedLayers:r.directionalShadowForced??0,updateMask:r.directionalShadowUpdateMask??0,gpuIndirectDraws:r.directionalShadowGpuDraws??0},!l){const t=Ds(o);return e.latestFrameProfile=t,void(e.latestCompletedFrameProfile=t)}n.encoder.resolveQuerySet(l.querySet,0,l.queryCount,l.resolveBuffer,0),n.encoder.copyBufferToBuffer(l.resolveBuffer,0,l.readBuffer,0,8*l.queryCount),e.latestFrameProfile=Ds(o)}}},h={profile:o,observer:d,pendingVisibilityRead:null,get pendingGpuRead(){return l},set pendingGpuRead(e){l=e}};return ys.set(h,s),h}(this.state,{renderGraphProfilingEnabled:this.renderGraphProfilingEnabled,timestampQuerySupported:this.timestampQuerySupported,hiZOcclusionCullingEnabled:this.hiZOcclusionCullingEnabled},u,l,{extractSceneMs:o,opaqueSortMs:this.opaqueSortMs,opaqueSortAverageMs:this.opaqueSortSampleTotal/Math.max(1,this.opaqueSortSampleCount),uploadMs:d}),y=()=>{if(!b||!u)return;const e=[];v&&v.count>0&&e.push({buffer:v.indirectBuffer,drawCount:v.count,totalInstances:s.gpuOpaqueDraws.reduce((e,t)=>e+Math.max(0,t.instanceCount),0),kind:"dynamic"});for(const t of this.getCameraStaticDrawSets())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,i,r){if(Ss.has(e))return;const n=r.filter(e=>e.drawCount>0);if(0===n.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=n.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=ys.get(e),l=o?.acquire(a,!1);if(o&&!l)return;const c=l?.readBuffer??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<n.length;e+=1){const t=n[e];i.copyBufferToBuffer(t.buffer,0,c,s[e].byteOffset,5*t.drawCount*Uint32Array.BYTES_PER_ELEMENT)}e.pendingVisibilityRead={readBuffer:c,regions:s,release:l&&o?e=>o.release(l,e):void 0}}(b,this.state.device,h,e)};if(r)return this.renderGraph.executeAsync(w,b?.observer).then(()=>{y(),null==this.nativePostSubmit&&this.recordPresentationOverlay(h,p),this.state.device.queue.submit([h.finish()]),this.nativePostSubmit?.({device:this.state.device,presentationView:p,presentationWidth:this.state.presentationWidth,presentationHeight:this.state.presentationHeight,present:e=>{const t=this.state.device.createCommandEncoder({label:"native-present-encoder"});this.executePresentPass(t,e,p),this.recordPresentationOverlay(t,p),this.state.device.queue.submit([t.finish()])}}),this.commitTemporalHiZHistory(),this.releaseRetiredGeometryResourcesAfterSubmit(),b&&Ms(this.state,b)});this.renderGraph.execute(w,b?.observer),y(),null==this.nativePostSubmit&&this.recordPresentationOverlay(h,p),this.state.device.queue.submit([h.finish()]),this.nativePostSubmit?.({device:this.state.device,presentationView:p,presentationWidth:this.state.presentationWidth,presentationHeight:this.state.presentationHeight,present:e=>{const t=this.state.device.createCommandEncoder({label:"native-present-encoder"});this.executePresentPass(t,e,p),this.recordPresentationOverlay(t,p),this.state.device.queue.submit([t.finish()])}}),this.commitTemporalHiZHistory(),this.releaseRetiredGeometryResourcesAfterSubmit(),b&&Ms(this.state,b)}recordPresentationOverlay(e,t){if(null==this.presentationOverlay)return;const i=this.presentationOverlayContext;i.device=this.state.device,i.encoder=e,i.targetView=t,i.targetFormat=this.state.format,i.presentationWidth=this.state.presentationWidth,i.presentationHeight=this.state.presentationHeight,this.presentationOverlay(i)}renderPresentationOnly(){const{device:e,context:t}=this.state;if(!e||!t)throw new Error("Renderer is not initialized.");const i=t.getCurrentTexture().createView(),r=e.createCommandEncoder({label:"application-presentation-encoder"});r.beginRenderPass({colorAttachments:[{view:i,loadOp:"clear",storeOp:"store",clearValue:{r:0,g:0,b:0,a:1}}]}).end(),this.recordPresentationOverlay(r,i),e.queue.submit([r.finish()])}destroy(){this.sharedVertexAttributeLayouts.clear(),this.staticSceneSpatialIndex.dispose(),this.staticInstanceSlots.dispose(),this.retiredStaticInstanceSlots.length=0;for(const e of this.sceneCaptureDisposers)e();Cs(this.state),this.directionalShadowGpu.dispose();for(const e of this.repeatedInstanceResources.values())e();this.skeletonPalettes.dispose(),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.skinnedRenderRecords.keys())this.releaseSkinnedRenderRecord(e);this.skinnedInstanceSlots.dispose();for(const e of this.skinnedGeometryCache.values())e.skinning.releaseInstance(),e.skinning.bindUniformBuffer.destroy();this.skinnedGeometryCache.clear();for(const e of this.skinPaletteResources)e.releaseExternal?.(),e.standaloneBuffer?.destroy();this.skinPaletteResources.clear(),this.skinningPaletteArena?.dispose(),this.skinningPaletteArena=void 0;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.transmissionSnapshotTexture?.destroy(),this.transmissionSnapshotTexture=null,this.state.sceneDepthSnapshotTexture?.destroy(),this.state.postProcessColorTexture?.destroy(),this.directionalShadowScheduler.invalidate(),this.state.directionalShadowTexture?.destroy(),this.state.pointShadowTexture?.destroy(),this.state.pointShadowDepthTexture?.destroy(),this.state.spotShadowTexture?.destroy(),this.state.spotLightMapTexture?.destroy(),this.state.hizTexture?.destroy(),this.state.cameraBuffer?.destroy(),this.state.temporalVisibilityBuffer?.destroy(),this.state.lightBuffer?.destroy(),this.tiledPointLights?.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.defaultVertexAttributeBuffers.values())for(const t of e.values())t.destroy();this.defaultVertexAttributeBuffers.clear(),this.state.visibilityParamsBuffer?.destroy(),this.state.drawMetadataResource?.metadataBuffer.destroy(),this.state.drawMetadataResource?.indirectBuffer.destroy(),this.state.drawMetadataResource?.postIndirectBuffer.destroy(),this.state.initialized=!1;const e=this.state.device?.destroy;"function"==typeof e&&e.call(this.state.device),this.state.device=null}async 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=[],t=this.state.device.createPipelineLayout({label:"renderer-depth-prepass-layout",bindGroupLayouts:[this.state.sceneBindGroupLayout]});e.push(W(this.state.device,{label:"renderer-depth-prepass-pipeline",layout:t,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 previousModel0: vec4<f32>,\n previousModel1: vec4<f32>,\n previousModel2: vec4<f32>,\n previousModel3: 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) @invariant 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"}}).then(e=>{this.state.depthPrepassPipeline=e}));const i=this.state.device.createPipelineLayout({label:"renderer-depth-prepass-visible-layout",bindGroupLayouts:[this.state.visibleDepthSceneBindGroupLayout]});e.push(W(this.state.device,{label:"renderer-depth-prepass-visible-pipeline",layout:i,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 previousModel0: vec4<f32>,\n previousModel1: vec4<f32>,\n previousModel2: vec4<f32>,\n previousModel3: 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) @invariant 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"}}).then(e=>{this.state.depthPrepassPipelineVisible=e}));const r=this.state.device.createPipelineLayout({label:"renderer-depth-prepass-direct-layout",bindGroupLayouts:[this.state.directSceneBindGroupLayout]});e.push(W(this.state.device,{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) @invariant 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"}}).then(e=>{this.state.depthPrepassPipelineDirect=e}));const n=this.state.device.createPipelineLayout({label:"renderer-skinned-depth-prepass-layout",bindGroupLayouts:[this.state.sceneBindGroupLayout,this.state.emptyBindGroupLayout,this.state.skinningBindGroupLayout]});e.push(W(this.state.device,{label:"renderer-skinned-depth-prepass-pipeline",layout:n,vertex:{module:this.state.device.createShaderModule({label:"renderer-skinned-depth-prepass-module",code:Hn}),entryPoint:"vsMain",buffers:this.createVertexBufferLayouts(L)},primitive:{topology:"triangle-list",cullMode:"back",frontFace:"ccw"},depthStencil:{format:"depth32float",depthWriteEnabled:!0,depthCompare:"less"}}).then(e=>{this.state.skinnedDepthPrepassPipeline=e}));const a=this.state.device.createPipelineLayout({label:"renderer-shadow-layout",bindGroupLayouts:[this.state.shadowBindGroupLayout]}),s=this.state.device.createPipelineLayout({label:"renderer-direct-shadow-pipeline-layout",bindGroupLayouts:[this.state.directShadowBindGroupLayout]});e.push(W(this.state.device,{label:"renderer-directional-shadow-pipeline",layout:a,vertex:{module:this.state.device.createShaderModule({label:"renderer-directional-shadow-module",code:$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",depthBias:1,depthBiasSlopeScale:2,depthBiasClamp:0}}).then(e=>{this.state.shadowDepthPipeline=e})),e.push(W(this.state.device,{label:"renderer-directional-shadow-direct-pipeline",layout:s,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:"back",frontFace:"ccw"},depthStencil:{format:"depth32float",depthWriteEnabled:!0,depthCompare:"less",depthBias:1,depthBiasSlopeScale:2,depthBiasClamp:0}}).then(e=>{this.state.shadowDepthPipelineDirect=e}));const o=this.state.device.createPipelineLayout({label:"renderer-skinned-shadow-layout",bindGroupLayouts:[this.state.shadowBindGroupLayout,this.state.emptyBindGroupLayout,this.state.skinningBindGroupLayout]});e.push(W(this.state.device,{label:"renderer-skinned-directional-shadow-pipeline",layout:o,vertex:{module:this.state.device.createShaderModule({label:"renderer-skinned-directional-shadow-module",code:qn}),entryPoint:"vsMain",buffers:this.createVertexBufferLayouts(L)},primitive:{topology:"triangle-list",cullMode:"back",frontFace:"ccw"},depthStencil:{format:"depth32float",depthWriteEnabled:!0,depthCompare:"less",depthBias:1,depthBiasSlopeScale:2,depthBiasClamp:0}}).then(e=>{this.state.skinnedShadowDepthPipeline=e})),e.push(W(this.state.device,{label:"renderer-point-shadow-pipeline",layout:a,vertex:{module:this.state.device.createShaderModule({label:"renderer-point-shadow-module",code:Wn}),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:Wn}),entryPoint:"fsMain",targets:[{format:"rgba16float"}]},primitive:{topology:"triangle-list",cullMode:"back",frontFace:"ccw"},depthStencil:{format:"depth32float",depthWriteEnabled:!0,depthCompare:"less"}}).then(e=>{this.state.pointShadowPipeline=e})),e.push(W(this.state.device,{label:"renderer-point-shadow-direct-pipeline",layout:s,vertex:{module:this.state.device.createShaderModule({label:"renderer-point-shadow-direct-module",code:Nn}),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:Nn}),entryPoint:"fsMain",targets:[{format:"rgba16float"}]},primitive:{topology:"triangle-list",cullMode:"back",frontFace:"ccw"},depthStencil:{format:"depth32float",depthWriteEnabled:!0,depthCompare:"less"}}).then(e=>{this.state.pointShadowPipelineDirect=e})),e.push(W(this.state.device,{label:"renderer-skinned-point-shadow-pipeline",layout:o,vertex:{module:this.state.device.createShaderModule({label:"renderer-skinned-point-shadow-module",code:Kn}),entryPoint:"vsMain",buffers:this.createVertexBufferLayouts(L)},fragment:{module:this.state.device.createShaderModule({label:"renderer-skinned-point-shadow-fragment-module",code:Kn}),entryPoint:"fsMain",targets:[{format:"rgba16float"}]},primitive:{topology:"triangle-list",cullMode:"back",frontFace:"ccw"},depthStencil:{format:"depth32float",depthWriteEnabled:!0,depthCompare:"less"}}).then(e=>{this.state.skinnedPointShadowPipeline=e}));const l=this.state.device.createPipelineLayout({label:"renderer-present-layout",bindGroupLayouts:[this.state.fullscreenTextureBindGroupLayout]});e.push(W(this.state.device,{label:"renderer-present-pipeline",layout:l,vertex:{module:this.state.device.createShaderModule({label:"renderer-present-module",code:Yn}),entryPoint:"vsMain"},fragment:{module:this.state.device.createShaderModule({label:"renderer-present-fragment-module",code:Yn}),entryPoint:"fsMain",targets:[{format:this.state.format}]},primitive:{topology:"triangle-list"}}).then(e=>{this.state.presentPipeline=e}));const c=this.state.device.createShaderModule({label:"renderer-scene-color-snapshot-module",code:Xn});e.push(W(this.state.device,{label:"renderer-scene-color-snapshot-pipeline",layout:l,vertex:{module:c,entryPoint:"vsMain"},fragment:{module:c,entryPoint:"fsMain",targets:[{format:I}]},primitive:{topology:"triangle-list"}}).then(e=>{this.state.sceneColorSnapshotPipeline=e}));const u=this.state.device.createShaderModule({label:"physical-transmission-snapshot-module",code:Jn});e.push(W(this.state.device,{label:"physical-transmission-snapshot-pipeline",layout:l,vertex:{module:u,entryPoint:"vsMain"},fragment:{module:u,entryPoint:"fsMain",targets:[{format:D}]},primitive:{topology:"triangle-list"}}).then(e=>{this.transmissionSnapshotPipeline=e})),await Promise.all(e)}ensureTransmissionSnapshot(){if(this.transmissionSnapshotTexture&&this.transmissionSnapshotSize.width===this.state.width&&this.transmissionSnapshotSize.height===this.state.height)return;this.transmissionSnapshotTexture?.destroy(),this.transmissionSnapshotSize.width=this.state.width,this.transmissionSnapshotSize.height=this.state.height;const e=1+Math.floor(Math.log2(Math.max(this.state.width,this.state.height)));this.transmissionSnapshotTexture=this.state.device.createTexture({label:"physical-transmission-snapshot",size:this.transmissionSnapshotSize,format:D,mipLevelCount:e,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING}),this.transmissionSnapshotView=this.transmissionSnapshotTexture.createView(),this.transmissionMipViews=[],this.transmissionMipBindGroups=[],this.transmissionSourceBindGroups=new WeakMap;for(let t=0;t<e;t++)this.transmissionMipViews.push(this.transmissionSnapshotTexture.createView({baseMipLevel:t,mipLevelCount:1})),t>0&&this.transmissionMipBindGroups.push(this.state.device.createBindGroup({layout:this.state.fullscreenTextureBindGroupLayout,entries:[{binding:0,resource:this.transmissionSampler},{binding:1,resource:this.transmissionMipViews[t-1]}]}));this.invalidateGraphTextureBundles()}copyTransmissionSnapshot(e,t){let i=this.transmissionSourceBindGroups.get(t);i||(i=this.state.device.createBindGroup({layout:this.state.fullscreenTextureBindGroupLayout,entries:[{binding:0,resource:this.transmissionSampler},{binding:1,resource:t}]}),this.transmissionSourceBindGroups.set(t,i));for(let t=0;t<this.transmissionMipViews.length;t++){const r=e.beginRenderPass({label:"physical-transmission-snapshot-mip",colorAttachments:[{view:this.transmissionMipViews[t],loadOp:"clear",storeOp:"store",clearValue:{r:0,g:0,b:0,a:1}}]});r.setPipeline(this.transmissionSnapshotPipeline),Fi(r,0,0===t?i:this.transmissionMipBindGroups[t-1]),r.draw(3),r.end()}}recreateShadowResources(){if(this.state.device){this.recreateDirectionalShadowResources(),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}))}}recreateDirectionalShadowResources(){if(this.state.device){this.state.residentSceneBindGroupVersion+=1,this.state.sharedSceneBindGroup=null,this.clearIndirectBundleCache(),this.clearStaticDrawSetBundleCaches(),this.directionalShadowScheduler.invalidate(),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}))}}ensureShadowTextureSizes(e){let t=this.shadowMapSize;for(const i of e.lights.directionals)t=Math.max(t,Math.ceil(i.shadowMapSize));let i=this.pointShadowMapSize;for(const t of e.lights.points)i=Math.max(i,Math.ceil(t.shadowMapSize));let r=this.spotShadowMapSize;for(const t of e.lights.spots)r=Math.max(r,Math.ceil(t.shadowMapSize));t===this.state.directionalShadowTextureSize&&i===this.state.pointShadowTextureSize&&r===this.state.spotShadowTextureSize||(this.state.directionalShadowTextureSize=t,this.state.pointShadowTextureSize=i,this.state.spotShadowTextureSize=r,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 i=t.scale??1,r=t.resolution??"render",n=t.format??D,a="presentation"===r?this.state.presentationWidth:this.state.width,s="presentation"===r?this.state.presentationHeight:this.state.height,o=Math.max(1,Math.floor(a*i)),l=Math.max(1,Math.floor(s*i)),c=this.colorTargetCache.get(e);if(c&&c.format===n&&c.width===o&&c.height===l&&c.scale===i&&c.resolution===r)return c;c?.texture.destroy();const u=this.state.device.createTexture({label:`renderer-color-target-${e}`,size:{width:o,height:l},format:n,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_SRC}),d={name:e,format:n,width:o,height:l,scale:i,resolution:r,texture:u,view:u.createView()};return this.colorTargetCache.set(e,d),this.invalidateGraphTextureBundles(),d}ensureMsaaColorTarget(e){if(!this.state.device)throw new Error("Renderer is not initialized.");const t=this.getColorTargetDimensions(e),i=this.getColorTargetFormat(e),r=this.msaaColorTargetCache.get(e);if(r&&r.format===i&&r.width===t.width&&r.height===t.height&&1===r.scale)return r;r?.texture.destroy();const n=this.state.device.createTexture({label:`renderer-msaa-color-target-${e}`,size:{width:t.width,height:t.height},sampleCount:this.sampleCount,format:i,usage:GPUTextureUsage.RENDER_ATTACHMENT}),a={name:e,format:i,width:t.width,height:t.height,scale:1,texture:n,view:n.createView()};return this.msaaColorTargetCache.set(e,a),a}ensureMsaaDepthTarget(e,t){if(!this.state.device)throw new Error("Renderer is not initialized.");const i=`${e}x${t}`,r=this.msaaDepthTargetCache.get(i);if(r&&r.width===e&&r.height===t&&r.sampleCount===this.sampleCount)return r;r?.texture.destroy();const n=this.state.device.createTexture({label:`renderer-msaa-depth-${i}`,size:{width:e,height:t},sampleCount:this.sampleCount,format:"depth32float",usage:GPUTextureUsage.RENDER_ATTACHMENT}),a={width:e,height:t,sampleCount:this.sampleCount,texture:n,view:n.createView()};return this.msaaDepthTargetCache.set(i,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 i=t.scale??1,r=t.resolution??"render",n="presentation"===r?this.state.presentationWidth:this.state.width,a="presentation"===r?this.state.presentationHeight:this.state.height,s=Math.max(1,Math.floor(n*i)),o=Math.max(1,Math.floor(a*i)),l=Math.max(1,t.depthOrArrayLayers??1),c=t.format??D,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===r&&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:i,resolution:r,dimension:d,depthOrArrayLayers:l,usage:h,texture:p,view:p.createView({dimension:d})};return this.colorTargetCache.set(e,f),this.invalidateGraphTextureBundles(),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 D;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 i=e.getGraphTextureInputs(),r=[];for(const e in i){const t=i[e].resource;r.includes(t)||r.push(t)}return this.materialGraphTextureReadCache.set(e,{materialVersion:e.version,resources:r}),r}createGraphBuilderContext(e,t,i,r,n,a,s,o,l){let c=!1;const u=()=>{c||(c=!0,e.addPass(new xs("TiledPointLightsPass",()=>{this.tiledLightingEnabled&&s.lights.points.length>0&&this.tiledPointLights.execute(t)},{writes:["tiledPointLights"]})))};let d=!1,h=!1;const p=e=>{const t=new Set;for(let i=0;i<e.length;i+=1){const r=this.getMaterialGraphTextureReads(e[i].material);for(let e=0;e<r.length;e+=1)t.add(r[e])}return Array.from(t)},f={device:this.state.device,encoder:t,camera:s.camera,sceneColorView:this.state.sceneColorView,postProcessColorView:this.state.postProcessColorView,presentationColorView:a,depthView:this.state.mainDepthView,colorFormat:D,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}},getGeometryVertexBuffer:(e,t)=>this.getGeometryResource(e)[t],getSkeletonBoneBuffer:this.getSkeletonBoneBufferForPass,getSkeletonBoneBinding:this.getSkeletonBoneBindingForPass,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:Math.min(4,s.lights.points.length),activeLayerCount:6*Math.min(4,s.lights.points.length)},spot:{view:this.state.spotShadowView,size:this.state.spotShadowTextureSize,layerCount:4,activeLightCount:Math.min(4,s.lights.spots.length),activeLayerCount:Math.min(4,s.lights.spots.length)}}),getSceneLightingResources:()=>{if(!(this.state.cameraBuffer&&this.state.lightBuffer&&this.state.shadowComparisonSampler&&this.state.linearClampSampler&&this.state.directionalShadowView&&this.state.pointShadowArrayView&&this.state.spotShadowView&&this.state.spotLightMapView))throw new Error("Renderer scene lighting resources are not initialized.");return{cameraBuffer:this.state.cameraBuffer,lightBuffer:this.state.lightBuffer,shadowSampler:this.state.shadowComparisonSampler,linearSampler:this.state.linearClampSampler,directionalShadowView:this.state.directionalShadowView,pointShadowView:this.state.pointShadowArrayView,spotShadowView:this.state.spotShadowView,spotLightMapView:this.state.spotLightMapView}}};return{fogVolumeObjects:s.fogVolumeObjects,extractedLights:s.lights,addDirectionalShadowPass:()=>{e.addPass(new xs("DirectionalShadowPass",()=>{this.executeDirectionalShadowPass(t,r,s,o)},{writes:["directionalShadow"]}))},addPointShadowPass:()=>{s.lights.points.some(e=>e.castShadow)&&e.addPass(new xs("PointShadowPass",()=>{this.executePointShadowPass(t,r,s,o)},{writes:["pointShadow"]}))},addSpotShadowPass:()=>{s.lights.spots.some(e=>e.castShadow)&&e.addPass(new xs("SpotShadowPass",()=>{this.executeSpotShadowPass(t,r,s,o)},{writes:["spotShadow"]}))},addDepthPrepass:()=>{d=!0,this.getHiZOcclusionCullingActive()&&this.hasEnabledStaticDrawSets()&&e.addPass(new xs("TemporalStaticVisibilityPrepass",()=>{this.executeStaticVisibilityPasses(t,"prepass")},{reads:["hiz"],writes:["staticIndirectArgs"]})),e.addPass(new xs("DepthPrepass",()=>{this.executeDepthPrepass(t,i,s,o)},{writes:["mainDepth"]}))},addHiZPasses:()=>{this.getHiZOcclusionCullingActive()&&e.addPass(new xs("HiZPasses",()=>{this.executeHiZPasses(t)},{reads:["mainDepth"],writes:["hiz"]}))},addVisibilityPass:()=>{this.getHiZOcclusionCullingActive()&&(n||this.hasEnabledStaticDrawSets())&&(e.addPass(new xs("VisibilityPass",()=>{n&&this.executeVisibilityPass(t,n),this.executeStaticVisibilityPasses(t,"postpass")},{reads:["hiz"],writes:["indirectArgs","staticIndirectArgs"]})),this.sampleCount>1&&this.hasEnabledStaticDrawSets()&&e.addPass(new xs("TemporalStaticDepthResolvePass",()=>{this.executeStaticTemporalDepthResolvePass(t)},{reads:["staticIndirectArgs"],writes:["mainDepth"]})))},defineColorTarget:(e,t={})=>{this.ensureColorTarget(e,t)},defineTextureTarget:(e,t={})=>{this.ensureTextureTarget(e,t)},addForwardPass:(r="sceneColor")=>{u();const n=!d,a=[...s.gpuOpaqueDraws,...s.directOpaqueDraws,...s.transparentDraws],c=p(a);if(l?.push({draws:a,colorTargetFormats:[this.getColorTargetFormat(r)],sampleCount:this.sampleCount,staticDrawStage:"all"}),c.includes("mainDepth")){if(!d)throw new Error("Materials that sample mainDepth require a depth prepass.");e.addPass(new xs("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"]})),h=!0}e.addPass(new xs("ForwardPass",()=>{this.executeForwardPass(t,r,this.getColorTargetView(r),i,s,o,n)},{reads:["tiledPointLights","directionalShadow","pointShadow","spotShadow","mainDepth","indirectArgs",...c.map(e=>"mainDepth"===e?"sceneDepthSnapshot":e)],writes:[r]})),this.getHiZOcclusionCullingActive()&&this.hasEnabledStaticDrawSets()&&e.addPass(new xs("TemporalHiZHistoryPass",()=>{this.executeHiZPasses(t,!0)},{reads:["mainDepth"],writes:["hiz"],dependsOn:["ForwardPass"]}))},addOpaquePass:(r="sceneColor")=>{u();const n=!d,a=[...s.gpuOpaqueDraws,...s.directOpaqueDraws],c=p(a);if(l?.push({draws:a,colorTargetFormats:[this.getColorTargetFormat(r)],sampleCount:this.sampleCount,staticDrawStage:"opaque"}),c.includes("mainDepth")){if(!d)throw new Error("Materials that sample mainDepth require a depth prepass.");e.addPass(new xs("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"]})),h=!0}e.addPass(new xs("OpaquePass",()=>{this.executeForwardPass(t,r,this.getColorTargetView(r),i,s,o,n,"opaque")},{reads:["tiledPointLights","directionalShadow","pointShadow","spotShadow","mainDepth","indirectArgs",...c.map(e=>"mainDepth"===e?"sceneDepthSnapshot":e)],writes:[r]}))},addSceneTextureCopyPass:(i="sceneColor",r)=>{const n=this.getCameraStaticDrawSets().filter(e=>e.publicSet.enabled&&"late"===e.drawStage).flatMap(e=>e.draws),a=[...s.transparentDraws,...n],o=p(a),l=o.includes("physicalTransmissionSnapshot");l&&this.ensureTransmissionSnapshot();const c=!0===r?.sceneColor||a.some(e=>e.material.usesSceneColor()),u=!0===r?.sceneDepth||a.some(e=>e.material.usesSceneDepth()),d=o.includes("mainDepth");if(!(l||c||u||d))return;const f=this.getColorTargetDimensions(i);if(f.width!==this.state.width||f.height!==this.state.height||this.getColorTargetFormat(i)!==D)throw new Error("Scene texture snapshots currently require a full-resolution rgba16float source.");e.addPass(new xs("SceneTextureCopyPass",()=>{if(l&&this.copyTransmissionSnapshot(t,this.getColorTargetView(i)),c){const e=this.getColorTargetView(i);let r=this.state.sceneColorSnapshotBindGroups.get(e);r||(r=this.state.device.createBindGroup({label:"renderer-scene-color-snapshot-bind-group",layout:this.state.fullscreenTextureBindGroupLayout,entries:[{binding:0,resource:this.state.linearClampSampler},{binding:1,resource:e}]}),this.state.sceneColorSnapshotBindGroups.set(e,r));const n=t.beginRenderPass({label:"renderer-scene-color-snapshot-pass",colorAttachments:[{view:this.state.sceneColorSnapshotView,loadOp:"clear",storeOp:"store",clearValue:{r:0,g:0,b:0,a:0}}]});n.setPipeline(this.state.sceneColorSnapshotPipeline),Fi(n,0,r),n.draw(3),n.end()}u&&this.executeHiZPasses(t,!1,!0),d&&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:[...c||l?[i]:[],...u||d?["mainDepth"]:[]],writes:[...c?["sceneColorSnapshot"]:[],...l?["physicalTransmissionSnapshot"]:[],...u||d?["sceneDepthSnapshot"]:[]]})),(u||d)&&(h=!0)},addLatePass:(r="sceneColor")=>{const n=this.getCameraStaticDrawSets().filter(e=>e.publicSet.enabled&&"late"===e.drawStage).flatMap(e=>e.draws);if(0===s.transparentDraws.length&&0===n.length)return;l?.push({draws:s.transparentDraws,colorTargetFormats:[this.getColorTargetFormat(r)],sampleCount:1,staticDrawStage:"late"});const a=[...s.transparentDraws,...n],c=[r,"mainDepth",...p(a)];a.some(e=>e.material.usesSceneColor())&&c.push("sceneColorSnapshot"),a.some(e=>e.material.usesSceneDepth())&&c.push("sceneDepthSnapshot"),e.addPass(new xs("LatePass",()=>{this.executeForwardPass(t,r,this.getColorTargetView(r),i,s,o,!1,"late",!0,1)},{reads:c,writes:[r,"mainDepth"]}))},addHiZHistoryPass:(i="ForwardPass")=>{if(!this.getHiZOcclusionCullingActive()||!this.hasEnabledStaticDrawSets())return;const r="LatePass"===i&&0===s.transparentDraws.length?"OpaquePass":i;e.addPass(new xs("TemporalHiZHistoryPass",()=>{this.executeHiZPasses(t,!0)},{reads:["mainDepth"],writes:["hiz"],dependsOn:[r]}))},addMaterialPass:(r={})=>{u();const n="string"==typeof r.outputs?[r.outputs]:Array.from(r.outputs??["sceneColor"]);if(l){const e=r.drawStage??"all",t="opaque"===e?[...s.gpuOpaqueDraws,...s.directOpaqueDraws]:"late"===e?s.transparentDraws:[...s.gpuOpaqueDraws,...s.directOpaqueDraws,...s.transparentDraws],i=r.objectFilter?t.filter(e=>r.objectFilter(e.sourceObject)||!0===e.sourceRanges?.some(e=>r.objectFilter(e.sourceObject))):t,a=e=>"function"==typeof r.overrideMaterial?r.overrideMaterial(e.material,null!==e.skinning):r.overrideMaterial,o=r.overrideMaterial?i.flatMap(e=>{const t=a(e);return null==t?[]:[{...e,material:t}]}):i;l.push({draws:o,colorTargetFormats:n.map(e=>this.getColorTargetFormat(e)),sampleCount:this.sampleCount,staticDrawStage:e})}const a=r.drawStage??"all";e.addPass(new xs(r.name??"MaterialPass",()=>{this.executeMaterialPass(t,n,i,s,o,r)},{dependsOn:r.dependsOn,reads:["tiledPointLights","directionalShadow","pointShadow","spotShadow",..."late"!==a?["indirectArgs","staticIndirectArgs"]:[],...r.loadDepth?["mainDepth"]:[],...r.loadColor?n:[]],writes:this.sampleCount>1?n:[...n,"mainDepth"]}))},addCustomPass:t=>{e.addPass(new xs(t.name,()=>{t.execute(f)},{reads:t.reads,writes:t.writes,dependsOn:t.dependsOn}))},addPresentPass:(i="sceneColor")=>{e.addPass(new xs("PresentPass",()=>{const e=this.getColorTargetView(i);this.executePresentPass(t,e,a)},{reads:[i],writes:["mainColor"]}))}}}transparentDraws=[];opaqueBatches=new Map;acquireDrawCall(){const e=this.drawCallPoolCount;this.drawCallPoolCount+=1;let t=this.drawCallPool[e];return t||(t=this.createDrawCall(),this.drawCallPool[e]=t),t}createDrawCall(){return{geometry:null,geometryKey:{},geometryResource:null,material:null,customDepthMaterial:null,residentInstanceBinding:null,sourceObject:null,frontFaceCW:!1,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 Ca,boundsRadius:0,sortDepth:0,transparentSortGroup:0,transparentSortOrder:0}}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 Ca,boundsMax:new Ca},this.opaqueBatchPool[e]=t),t}populateDrawCall(e,t,i,r,n,a,s,o,l){const c=t.wireframe;c&&this.ensureWireframeIndex(t.geometry,t.geometryResource);const u=t.sourceObject?Boolean(t.sourceObject.receiveShadow):t.receiveShadow;return this.shouldInvalidateDrawMaterialResource(e,t.material,u,t.usesBatching,null)&&(e.materialResource=null),e.geometry=t.geometry,e.geometryKey=c?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.cameraDetailRejected=t.cameraDetailRejected,e.detailCulling=l?.detailCulling??f(t.sourceObject),e.frontFaceCW=l?.frontFaceCW??(null!==t.sourceObject&&!0===t.sourceObject.isMesh?t.sourceObject.matrixWorld.determinant()<0:t.frontFaceCW),e.usesBatching=t.usesBatching,e.geometryGroup=t.geometryGroup,e.batchKey=t.batchKey,e.batchHash=t.batchHash,e.indexed=c||t.indexed,e.wireframe=c,e.start=c?2*t.start:t.start,e.count=c?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=u,e.sortMaterialId=t.sortMaterialId,e.sortGeometryId=t.sortGeometryId,e.sortCustomDepthMaterialId=t.sortCustomDepthMaterialId,e.skinning=null,e.instanceStart=i,e.instanceCount=r,e.boundsCenter.set(n,a,s),e.boundsRadius=o,e.sortDepth=0,e.transparentSortGroup=0,e.transparentSortOrder=0,e.sourceRanges=void 0,e}populateDynamicDrawCall(e,t,i,r,n,a,s,o,l,c,u,d,h,p,m,g,v,x,w,b,y,S,C,M,P,B,D,I,T=null){const R=!0===o?.isBatchedMesh,V=n.wireframe&&"triangle-list"===n.primitiveTopology;return V&&this.ensureWireframeIndex(t,r),this.shouldInvalidateDrawMaterialResource(e,n,w,R,T)&&(e.materialResource=null),e.geometry=t,e.geometryKey=V?r.wireframeIndex:i,e.geometryResource=r,e.material=n,e.customDepthMaterial=a,e.residentInstanceBinding=s,e.sourceObject=o,e.cameraDetailRejected=void 0,e.detailCulling=f(o),e.frontFaceCW=null!==o&&!0===o.isMesh&&o.matrixWorld.determinant()<0,e.usesBatching=R,e.geometryGroup=l,e.batchKey=c,e.batchHash=u,e.indexed=V||d,e.wireframe=V,e.start=V?2*h:h,e.count=V?2*p:p,e.transparent=m,e.renderOrder=g,e.hasRenderCallbacks=v,e.castShadow=x,e.receiveShadow=w,e.sortMaterialId=b,e.sortGeometryId=y,e.sortCustomDepthMaterialId=S,e.skinning=T,e.instanceStart=C,e.instanceCount=M,e.boundsCenter.set(P,B,D),e.boundsRadius=I,e.sortDepth=0,e.transparentSortGroup=0,e.transparentSortOrder=0,e.sourceRanges=void 0,e}pushOpaqueDrawTemplate(e,t,i,r,n,a,s){e.detailCulling=f(e.sourceObject),e.cameraDetailRejected=null===this.sceneCaptureOptions&&!g(F.set(r,n,a),s,this.cameraViewProjScratch,this.state.width,this.state.height,this.transparentSortCameraPositionScratch,e.detailCulling.minScreenSize*(e.sourceObject&&this.cameraDetailHistory.get(e.sourceObject)?.85:1.15),e.detailCulling.maxDistance,this.cameraDetailProjectionScratch),e.sourceObject&&null===this.sceneCaptureOptions&&this.cameraDetailHistory.set(e.sourceObject,!e.cameraDetailRejected);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 i=l[t];if(Qr(i.template,e)){c=i;break}}else Qr(l.template,e)&&(c=l);if(c){if(c.totalInstanceCount+=i,1===c.rangePairCount){const e=c.sourceRanges;e.length=4,e[0]=c.firstInstanceStart,e[1]=c.firstInstanceCount,e[2]=t,e[3]=i}else{const e=c.sourceRanges,r=2*c.rangePairCount;e[r]=t,e[r+1]=i}c.rangePairCount+=1;const e=c.boundsMin,o=c.boundsMax,l=r-s,u=n-s,d=a-s,h=r+s,p=n+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=i,u.rangePairCount=1,u.firstInstanceStart=t,u.firstInstanceCount=i,u.sourceRanges.length=0,u.boundsMin.set(r-s,n-s,a-s),u.boundsMax.set(r+s,n+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){let i=this.preparedOutlineFrameCache.get(e);i?i.extraction!==this.extractionVersion&&(i.extraction=this.extractionVersion,i.regular=i.skinned=void 0):(i={extraction:this.extractionVersion},this.preparedOutlineFrameCache.set(e,i));const r=t?"skinned":"regular";return void 0===i[r]&&(i[r]=this.prepareToonOutlineMaterial(e,t)),i[r]}prepareToonOutlineMaterial(e,t){const i=this.getToonOutlineParameters(e);if(!i)return null;if("darkenedAlbedo"===i.colorMode){const t=this.resolveAdaptedMaterial(e,i);if(t)return t}let r=this.toonOutlineMaterialCache.get(e);if(!r){const t=t=>new pr({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?ll:[{name:"position",shaderLocation:0,format:"float32x3"},{name:"normal",shaderLocation:1,format:"float32x3",defaultValue:[0,0,1]}],uniforms:{outlineThickness:i.thickness??.003,outlineColor:(new ca).fromArray(i.color??[0,0,0]),outlineAlpha:i.alpha??e.opacity},side:sa,depthTest:!0,depthWrite:!0,transparent:!0,uniformValuesAutoUpdate:!1});r={regular:t(!1),skinned:t(!0)},this.toonOutlineMaterialCache.set(e,r)}const n=t?r.skinned:r.regular,a=i.thickness??.003,s=i.alpha??e.opacity,o=n.uniforms.outlineColor.value,l=i.color?.[0]??0,c=i.color?.[1]??0,u=i.color?.[2]??0;return n.uniforms.outlineThickness.value===a&&n.uniforms.outlineAlpha.value===s&&o.r===l&&o.g===c&&o.b===u||(n.uniforms.outlineThickness.value=a,n.uniforms.outlineAlpha.value=s,o.setRGB(l,c,u),n.uniformValuesNeedsUpdate=!0),n}pushToonOutlineDraw(e,t,i,r=0){const n=t?this.getToonOutlineMaterial(t,null!==e.skinning):null;if(!n||e.usesBatching)return;const a=e.transparent||(this.getToonOutlineParameters(t)?.alpha??t.opacity)<1||n.requiresLatePass(),s=i?.[r];if(s&&s.geometry===e.geometry&&s.geometryKey===e.geometryKey&&s.geometryResource===e.geometryResource&&s.material===n&&s.skinning===e.skinning&&s.start===e.start&&s.count===e.count&&s.indexed===e.indexed)return s.boundsCenter.copy(e.boundsCenter),s.boundsRadius=e.boundsRadius,s.geometryGroup=e.geometryGroup,s.instanceStart=e.instanceStart,s.residentInstanceBinding=e.residentInstanceBinding,s.transparent=a,s.renderOrder=e.renderOrder,s.frontFaceCW=e.frontFaceCW,s.detailCulling=e.detailCulling,s.cameraDetailRejected=void 0,s.sortDepth=0,s.transparentSortGroup=0,s.transparentSortOrder=0,void this.pushDraw(s);const o=this.populateDynamicDrawCall(s??(i?this.createDrawCall():this.acquireDrawCall()),e.geometry,e.geometryKey,e.geometryResource,n,null,e.residentInstanceBinding,e.sourceObject,e.geometryGroup,"",0,e.indexed,e.start,e.count,a,e.renderOrder,!1,!1,!1,Hr(n),e.sortGeometryId,0,e.instanceStart,e.instanceCount,e.boundsCenter.x,e.boundsCenter.y,e.boundsCenter.z,e.boundsRadius,e.skinning);i&&(i[r]=o),this.pushDraw(o)}updateTransparentDrawSortDepths(e,t,i){for(let r=0;r<e.length;r+=1){const n=e[r];0===n.transparentSortGroup&&(n.sortDepth=(n.boundsCenter.x-t.x)*i.x+(n.boundsCenter.y-t.y)*i.y+(n.boundsCenter.z-t.z)*i.z)}}selectTransientPointLight(e,t){if(!(e.intensity>0&&e.distance>0))return;if(F.setFromMatrixPosition(e.matrixWorld),!un(this.cameraFrustumPlanesScratch,F.x,F.y,F.z,e.distance))return;const i=e.intensity*e.distance*e.distance/Math.max(1,F.distanceToSquared(t));if(!Number.isFinite(i))return;const r=this.transientPointLightsScratch,n=this.transientPointScoresScratch;let a=0;for(;a<r.length&&(n[a]>i||n[a]===i&&r[a].id<e.id);)a++;if(a>=n.length)return;for(let e=Math.min(r.length,n.length-1);e>a;e--)r[e]=r[e-1],n[e]=n[e-1];r[a]=e,n[a]=i}extractPointLight(e,t){const i=e.shadow,r=i.camera;F.setFromMatrixPosition(e.matrixWorld);const n=e.distance>0?e.distance:Math.max(r.far,25);if(!un(this.cameraFrustumPlanesScratch,F.x,F.y,F.z,n))return;const a=this.extractedPointLightsScratch[t.length];a.sourceLight=e,a.position.copy(F),a.color.set(e.color.r,e.color.g,e.color.b),a.intensity=e.intensity,a.volumetricIntensity=e.userData?.volumetricIntensity??0,a.distance=e.distance,a.range=n,a.decay=e.decay,a.castShadow=e.castShadow,a.shadowBias=i.bias,a.shadowNormalBias=i.normalBias,a.shadowRadius=i.radius,a.shadowIntensity=i.intensity,a.shadowMapSize=Math.max(1,i.mapSize.width,i.mapSize.height),a.shadowCameraNear=r.near,a.shadowCameraFar=e.distance>0?e.distance:r.far,t.push(a)}extractScene(e,t,i=!1){this.extractionVersion+=1,this.state.indirectForwardBundleCache.prune(this.extractionVersion),null===this.sceneCaptureOptions&&(this.motionHistoryExtractionVersion+=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 a=this.sourceInstanceDataScratch;a.reset();const s=this.gpuOpaqueDrawsScratch;s.length=0;const o=this.directOpaqueDrawsScratch;o.length=0;const l=this.stagedOpaqueDrawsScratch;l.length=0;const c=this.residentOpaqueDrawsScratch;c.length=0;const u=this.opaqueInstanceDataScratch;u.reset();const d=this.dynamicBatchingEnabled?this.finalInstanceDataScratch:a;this.finalInstanceDataScratch.reset();const h=this.extractedAmbientScratch;h.set(0,0,0,0);let p=null;const m=this.activeDirectionalLightsScratch,v=this.activePointLightsScratch,x=this.activeSpotLightsScratch,w=this.fogVolumeObjectsScratch;m.length=0,v.length=0,this.transientPointLightsScratch.length=0,x.length=0,w.length=0;const b=this.extractedBoundsMinScratch;b.set(1/0,1/0,1/0);const C=this.extractedBoundsMaxScratch;C.set(-1/0,-1/0,-1/0),ln(on(t,this.cameraViewProjScratch),this.cameraFrustumPlanesScratch),this.cameraDetailProjectionScratch.update(this.cameraViewProjScratch);const M=this.transparentSortCameraPositionScratch,P=this.transparentSortCameraForwardScratch;t.getWorldPosition(M),t.getWorldDirection(P);const B=i?this.isSphereVisibleForCompilationScratch:this.isSphereVisibleScratch,D=this.updateExtractedBoundsFromMatrixScratch,I=this.objectTraversalStackScratch;I.length=0,I.push(e);for(let e=this.csmCascadeLights.length-1;e>=0;e-=1)I.push(this.csmCascadeLights[e]);for(;;){if(0===I.length){for(const e of this.transientPointLightsScratch){if(v.length>=y)break;this.extractPointLight(e,v)}if(this.csmCascadeLights.length>0&&m.sort((e,t)=>{const i=e.sourceLight?this.csmCascadeLights.indexOf(e.sourceLight):-1,r=t.sourceLight?this.csmCascadeLights.indexOf(t.sourceLight):-1;return(i<0?4:i)-(r<0?4:r)}),!i&&null===this.sceneCaptureOptions){const e=this.staticDrawSetManager.revision;this.directionalShadowScheduler.prepare(m,t,this.csmCascadeRanges,this.csmCascadeCount,performance.now(),e)}if(this.spatialShadowCount=0,this.spatialLocalShadowCount=0,null===this.sceneCaptureOptions)for(let e=0;e<m.length;e++)m[e].castShadow&&ln(on(this.directionalShadowCameras[e],this.spatialShadowMatrix),this.spatialShadowPlanes[this.spatialShadowCount++]);for(const e of v){if(!e.castShadow)continue;const t=4*this.spatialLocalShadowCount++,i=this.spatialLocalShadowSpheres;i[t]=e.position.x,i[t+1]=e.position.y,i[t+2]=e.position.z,i[t+3]=e.shadowCameraFar*Math.sqrt(3)}for(const e of x){if(!e.castShadow)continue;const t=4*this.spatialLocalShadowCount++,i=this.spatialLocalShadowSpheres;i[t]=e.position.x,i[t+1]=e.position.y,i[t+2]=e.position.z;const r=Math.tan(e.shadowCameraFov*Math.PI/360);i[t+3]=e.shadowCameraFar*Math.sqrt(1+2*r*r)}for(this.spatialIncludeOffscreen=i,this.spatialCameraLayers=t.layers.mask,this.staticSceneSpatialIndex.queryWithState(e,this.testSpatialScene,this.pushSpatialRoot,63);I.length;)this.collectSpatialRoot(I.pop());break}const r=I.pop();if(this.extractingCaster=r.castShadow,!r.visible)continue;if(!1===this.sceneCaptureOptions?.objectFilter?.(r))continue;if(null!==this.sceneCaptureOptions&&!1===r.userData.sceneCapture)continue;if(r.isBone){const e=this.staticSceneSpatialIndex.traversalChildren(r);for(let t=e.length-1;t>=0;t--)I.push(e[t]);continue}const n=0!==(r.layers.mask&t.layers.mask);if(!0===r.isFogVolumeObject&&null!=r.volume)w.push(r);else if(r.isAmbientLight){if(n){const e=r;h.x+=e.color.r*e.intensity,h.y+=e.color.g*e.intensity,h.z+=e.color.b*e.intensity,h.w=1}}else if(r.isHemisphereLight){if(n&&null==p){const e=r,t=this.extractedHemisphereScratch;F.setFromMatrixPosition(e.matrixWorld),t.direction.copy(F),t.direction.lengthSq()<=1e-10?t.direction.set(0,1,0):t.direction.normalize(),t.skyColor.set(e.color.r,e.color.g,e.color.b),t.groundColor.set(e.groundColor.r,e.groundColor.g,e.groundColor.b),t.intensity=e.intensity,p=t}}else if(r.isDirectionalLight){if(n&&m.length<4&&!this.hasExtractedDirectionalLight(m,r)){const e=r,t=e.shadow,i=t.camera,n=this.extractedDirectionalLightsScratch[m.length];n.sourceLight=e,e.target.matrixWorldAutoUpdate&&e.target.updateMatrixWorld(!0),F.setFromMatrixPosition(e.matrixWorld),O.setFromMatrixPosition(e.target.matrixWorld),n.position.copy(F),n.target.copy(O),n.direction.copy(O).sub(F).normalize(),n.color.set(e.color.r,e.color.g,e.color.b),n.intensity=e.intensity,n.volumetricIntensity=e.userData?.volumetricIntensity??0,n.castShadow=e.castShadow&&this.directionalShadowsEnabled,n.shadowBias=t.bias,n.shadowNormalBias=t.normalBias,n.shadowRadius=t.radius,n.shadowIntensity=t.intensity,n.shadowMapSize=Math.max(1,t.mapSize.width,t.mapSize.height),n.shadowCameraLeft=i.left,n.shadowCameraRight=i.right,n.shadowCameraTop=i.top,n.shadowCameraBottom=i.bottom,n.shadowCameraNear=i.near,n.shadowCameraFar=i.far,m.push(n)}}else if(r.isPointLight){if(n&&!1!==this.sceneCaptureOptions?.includeLocalLights){const e=r;!0===e.userData.vfxTransientLight?this.selectTransientPointLight(e,M):v.length<y&&this.extractPointLight(e,v)}}else if(r.isSpotLight){if(n&&!1!==this.sceneCaptureOptions?.includeLocalLights&&x.length<S){const e=r,t=e.shadow,i=t.camera,n=this.extractedSpotLightsScratch[x.length];n.sourceLight=e,e.target.matrixWorldAutoUpdate&&e.target.updateMatrixWorld(!0),F.setFromMatrixPosition(e.matrixWorld),O.setFromMatrixPosition(e.target.matrixWorld);const a=e.distance>0?e.distance:i.far;if(!un(this.cameraFrustumPlanesScratch,F.x,F.y,F.z,a))continue;n.position.copy(F),n.direction.copy(O).sub(F).normalize(),n.color.set(e.color.r,e.color.g,e.color.b),n.intensity=e.intensity,n.volumetricIntensity=e.userData?.volumetricIntensity??0,n.range=a,n.angle=e.angle,n.penumbra=e.penumbra,n.decay=e.decay,n.castShadow=e.castShadow,n.shadowBias=t.bias,n.shadowNormalBias=t.normalBias,n.shadowRadius=t.radius,n.shadowIntensity=t.intensity,n.shadowMapSize=Math.max(1,t.mapSize.width,t.mapSize.height),n.shadowCameraNear=i.near,n.shadowCameraFar=e.distance>0?e.distance:i.far,n.shadowCameraFov=e.angle*(360/Math.PI)*t.focus,n.map=e.map??null,x.push(n)}}else n&&r.isBatchedMesh?this.collectBatchedMesh(r,a,D,B,t,M,P):n&&r.isInstancedMesh?this.collectInstancedMesh(r,a,D,B):n&&r.isSkinnedMesh?this.collectSkinnedMesh(r,a,D,B):n&&r.isLine?this.collectLine(r,a,D,B):n&&r.isSprite?this.collectSprite(r,a,D,B):n&&r.isMesh&&this.collectMesh(r,a,D,B);const s=this.staticSceneSpatialIndex.traversalChildren(r);for(let e=s.length-1;e>=0;e-=1)I.push(s[e])}const T=this.dynamicBatchingEnabled?o.length:0;this.updateTransparentDrawSortDepths(r,M,P),r.sort(Zr),Number.isFinite(b.x)||(b.set(-6,-6,-6),C.set(6,6,6)),this.dynamicBatchingEnabled&&this.sortOpaqueDraws(l);for(let e=0;e<l.length;){const t=l[e];if(!this.dynamicBatchingEnabled){t.sourceRanges=void 0,t.indexed&&!t.hasRenderCallbacks?s.push(t):o.push(t),e++;continue}const i=u.instanceCount;u.appendRange(a,t.instanceStart,t.instanceCount);let r,n=t.instanceCount,c=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<l.length&&en(t,l[g]);){const e=l[g];u.appendRange(a,e.instanceStart,e.instanceCount),r??=[{sourceObject:t.sourceObject,instanceStart:i,instanceCount:t.instanceCount}],r.push({sourceObject:e.sourceObject,instanceStart:i+n,instanceCount:e.instanceCount}),n+=e.instanceCount;const s=e.boundsCenter.x-e.boundsRadius,o=e.boundsCenter.y-e.boundsRadius,v=e.boundsCenter.z-e.boundsRadius,x=e.boundsCenter.x+e.boundsRadius,w=e.boundsCenter.y+e.boundsRadius,b=e.boundsCenter.z+e.boundsRadius;s<c&&(c=s),o<d&&(d=o),v<h&&(h=v),x>p&&(p=x),w>f&&(f=w),b>m&&(m=b),g+=1}const v=.5*(c+p),x=.5*(d+f),w=.5*(h+m),b=p-v,y=f-x,S=m-w;t.instanceStart=i,t.instanceCount=n,t.sourceRanges=r,t.boundsCenter.set(v,x,w),t.boundsRadius=Math.sqrt(b*b+y*y+S*S),t.indexed&&!t.hasRenderCallbacks?s.push(t):o.push(t),e=g}this.sortOpaqueDraws(c,il);for(let e=0;e<c.length;){const t=c[e];let i=t,r=e+1;if(this.dynamicBatchingEnabled&&!t.wireframe&&this.staticSpatialDraws.has(t)){let n=t.instanceCount;for(;r<c.length;){const e=c[r];if(!this.staticSpatialDraws.has(e)||e.wireframe||e.residentInstanceBinding!==t.residentInstanceBinding||e.instanceStart!==t.instanceStart+n||!en(t,e))break;n+=e.instanceCount,r++}if(r>e+1){let a=this.staticSpatialBatches.get(t);if(a||(a={draw:this.createDrawCall(),ranges:[],last:null,revision:-1},this.staticSpatialBatches.set(t,a)),a.revision!==this.staticSpatialDrawRevision||a.last!==c[r-1]||a.ranges.length!==r-e||!en(a.draw,t)){let i=1/0,s=1/0,o=1/0,l=-1/0,u=-1/0,d=-1/0;for(let t=e;t<r;t++){const r=c[t],n=t-e,h=a.ranges[n]??={sourceObject:null,instanceStart:0,instanceCount:0};h.sourceObject=r.sourceObject,h.instanceStart=r.instanceStart,h.instanceCount=r.instanceCount,i=Math.min(i,r.boundsCenter.x-r.boundsRadius),s=Math.min(s,r.boundsCenter.y-r.boundsRadius),o=Math.min(o,r.boundsCenter.z-r.boundsRadius),l=Math.max(l,r.boundsCenter.x+r.boundsRadius),u=Math.max(u,r.boundsCenter.y+r.boundsRadius),d=Math.max(d,r.boundsCenter.z+r.boundsRadius)}const h=.5*(i+l),p=.5*(s+u),f=.5*(o+d);this.populateDrawCall(a.draw,t,t.instanceStart,n,h,p,f,Math.hypot(l-h,u-p,d-f)),a.ranges.length=r-e,a.draw.sourceObject=null,a.draw.sourceRanges=a.ranges,a.last=c[r-1],a.revision=this.staticSpatialDrawRevision}i=a.draw}}i.indexed&&!i.hasRenderCallbacks?s.push(i):o.push(i),e=r}d.appendBuilder(u);for(let e=0;e<T;e+=1){const t=o[e];if(t.residentInstanceBinding)continue;const i=d.instanceCount;d.appendRange(a,t.instanceStart,t.instanceCount),t.instanceStart=i}this.sortOpaqueDraws(s),this.sortOpaqueDraws(o);for(let e=0;this.dynamicBatchingEnabled&&e<r.length;e+=1){const t=r[e];if(t.residentInstanceBinding)continue;const i=d.instanceCount;d.appendRange(a,t.instanceStart,t.instanceCount),t.instanceStart=i}v.sort(sl),x.sort(sl);for(let e=4;e<v.length;e+=1)v[e].castShadow=!1;for(let e=4;e<x.length;e+=1)x[e].castShadow=!1;const R=this.extractedLightsScratch;R.hemisphere=p,R.directional=m[0]??null,R.point=v[0]??null,R.spot=x[0]??null;const V=this.extractedFrameScratch;V.scene=e,V.camera=t,V.fogVolumeObjects=w,V.transparentDraws=r,V.instanceData=d,V.residentInstanceUploads=n,this.extractingCaster=!1;const G=this.shadowDrawsScratch;G.length=0;for(const e of[s,o,r]){for(const t of e)t.castShadow&&!t.transparent&&G.push(t);if(!i){let t=0;for(const i of e){const r=i.detailCulling??f(i.sourceObject);i.cameraDetailRejected||!this.isSphereVisibleScratch(i.boundsCenter.x,i.boundsCenter.y,i.boundsCenter.z,i.boundsRadius,i.sourceObject?.frustumCulled??!0)||null===this.sceneCaptureOptions&&!g(i.boundsCenter,i.boundsRadius,this.cameraViewProjScratch,this.state.width,this.state.height,M,!1===i.cameraDetailRejected?0:r.minScreenSize,r.maxDistance,this.cameraDetailProjectionScratch)||(e[t++]=i)}e.length=t}}return V.shadowDraws=G,this.skinningPaletteArena?.flush(),V}collectLine(e,t,i,r){if(Array.isArray(e.material)||!e.geometry.getAttribute("position"))return;const n=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=`${Cr(n)}:${s}`;let c=this.lineProxyCache.get(e);c&&c.sourceGeometry===n?c.signature!==l&&(c.signature=l):(c={signature:l,sourceGeometry:n,mesh:new ga(n,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,i,r)}const s=Cr(n);let o=this.lineProxyCache.get(e);if(!o||o.sourceGeometry!==n||o.signature!==s){const t=n.getAttribute("position"),i=n.index,r=i?.count??t.count,a=Math.max(0,Math.min(r,n.drawRange.start)),l=Number.isFinite(n.drawRange.count)?n.drawRange.count:r-a,c=Math.max(a,Math.min(r,a+l)),u=e.isLineSegments?2:1,d=[],h=[],p=e=>i?i.getX(e):e;for(let e=a;e+1<c;e+=u){const i=p(e),r=p(e+1);d.push(t.getX(i),t.getY(i),t.getZ(i)),h.push(t.getX(r),t.getY(r),t.getZ(r))}const f=new la;f.setIndex([0,2,1,2,3,1,2,4,3,4,5,3,4,6,5,6,7,5]),f.setAttribute("position",new oa(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 da(new Float32Array(d),3)),f.setAttribute("instanceEnd",new da(new Float32Array(h),3)),f.instanceCount=d.length/3;const m=dn(n);f.boundingSphere=new ba(m.center.clone(),m.radius),o={signature:s,sourceGeometry:n,mesh:new ga(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,i,r)}collectSprite(e,t,i,r){let n=this.spriteProxyCache.get(e);if(!n){const t=e.geometry.clone();n={mesh:new ga(t,e.material),centerX:Number.NaN,centerY:Number.NaN},this.spriteProxyCache.set(e,n)}if(n.centerX!==e.center.x||n.centerY!==e.center.y){const t=n.mesh.geometry.getAttribute("position"),i=e.geometry.getAttribute("position");for(let r=0;r<t.count;r+=1)t.setXYZ(r,i.getX(r)+.5-e.center.x,i.getY(r)+.5-e.center.y,i.getZ(r));t.needsUpdate=!0,n.mesh.geometry.computeBoundingSphere(),n.centerX=e.center.x,n.centerY=e.center.y}const a=n.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,i,r)}hasExtractedDirectionalLight(e,t){for(let i=0;i<e.length;i+=1)if(e[i].sourceLight===t)return!0;return!1}getObjectMotionHistory(e,t){if(null!==this.sceneCaptureOptions)return this.captureMotionHistory.matrix.set(t),this.captureMotionHistory;let i=this.objectMotionHistory.get(e);if(!i)return i={matrix:new Float32Array(16),generation:this.motionVectorHistoryGeneration,lastExtractionVersion:-1,valid:!1},i.matrix.set(t),this.objectMotionHistory.set(e,i),i;const r=!0===e.userData.motionBlurTeleported;r&&(e.userData.motionBlurTeleported=!1);const n=(t[12]??0)-i.matrix[12],a=(t[13]??0)-i.matrix[13],s=(t[14]??0)-i.matrix[14],o=Math.max(0,Number(e.userData.motionBlurTeleportDistance??10));return i.valid=this.motionVectorHistoryValid&&i.generation===this.motionVectorHistoryGeneration&&i.lastExtractionVersion===this.motionHistoryExtractionVersion-1&&!r&&n*n+a*a+s*s<=o*o,i}commitObjectMotionHistory(e,t){null===this.sceneCaptureOptions&&(e.matrix.set(t),e.generation=this.motionVectorHistoryGeneration,e.lastExtractionVersion=this.motionHistoryExtractionVersion)}createRepeatedMeshInstances(e,t){const i=new Cn,r=()=>{t.removeEventListener("dispose",r),i.dispose(),this.repeatedInstanceResources.delete(i)};t.addEventListener("dispose",r),this.repeatedInstanceResources.set(i,r);const n={geometry:t,data:i};return this.repeatedMeshInstances.set(e,n),n}collectMesh(e,t,i,r){const n=e.geometry;if(void 0===n.attributes.position)return;const a=e.material,s=Array.isArray(a);if(s){let e=!0;for(let t=0;t<a.length;t+=1)if(t in a&&!1!==a[t].visible){e=!1;break}if(e)return}else if(!1===a.visible)return;const o=this.hasRenderCallbacks(e),l=o?void 0:this.staticSceneSpatialIndex.getMeshSnapshot(e);let c=l?null:this.getGeometryResource(n,!0);const u=this.meshExtractionCache.get(e),d=u?.geometryResource===c?u:null,h=l||d?null:dn(n),p=l?.boundsCenter??d?.localBoundsCenter??h.center,f=l?.boundsRadius??d?.localBoundsRadius??h.radius,m=e.matrixWorld.elements,v=p.x,x=p.y,w=p.z,b=l?.boundsCenter.x??m[0]*v+m[4]*x+m[8]*w+m[12],y=l?.boundsCenter.y??m[1]*v+m[5]*x+m[9]*w+m[13],S=l?.boundsCenter.z??m[2]*v+m[6]*x+m[10]*w+m[14];let C,M=l?.boundsRadius;if(void 0===M){const e=m[0]*m[0]+m[1]*m[1]+m[2]*m[2],t=m[4]*m[4]+m[5]*m[5]+m[6]*m[6],i=m[8]*m[8]+m[9]*m[9]+m[10]*m[10];M=f*Math.sqrt(Math.max(e,t,i,1e-10))}if(!r(b,y,S,M,e.frustumCulled))return;if(l&&null===this.sceneCaptureOptions&&r!==this.isSphereVisibleForCompilationScratch){const t=l.detailCulling;if(C=!g(l.boundsCenter,M,this.cameraViewProjScratch,this.state.width,this.state.height,this.transparentSortCameraPositionScratch,t.minScreenSize*(this.cameraDetailHistory.get(e)?.85:1.15),t.maxDistance,this.cameraDetailProjectionScratch),this.cameraDetailHistory.set(e,!C),C&&(!e.castShadow||!this.isSpatialShadowSphereVisible(b,y,S,M)))return}c??=this.getGeometryResource(n,!0);const P=this.resolvedMeshMaterialsScratch;P.length=0;let B=null;if(s)for(let e=0;e<a.length;e+=1)P[e]=this.resolveMaterial(a[e]);else{if(!a.visible)return;B=this.resolveMaterial(a)}const D=vn(e),I=u&&u.customDepthMaterial===D&&u.geometryResource.lastValidatedExtractionVersion===this.extractionVersion&&(!s&&u.material===a&&u.resolvedMaterial===B||s&&null!==u.materials&&null!==u.resolvedMaterials&&Tr(u.materials,a)&&Gr(u.resolvedMaterials,P))?u:this.getMeshExtractionCacheEntry(e,a,B,P,D,c),T=I.templates.length;if(0===T)return;if(l&&null===this.sceneCaptureOptions&&!(n instanceof ha))return this.collectStaticMeshDraws(e,l,I.templates,C),void i(m);const R=function(e){const t=e.attributes;let i=!1,r=1/0;for(const e in t){const n=t[e];!0!==n.isInstancedBufferAttribute&&!0!==n.data?.isInstancedInterleavedBuffer||(i=!0,n.count<r&&(r=n.count))}if(!i)return 1;const n=e.instanceCount;return Number.isFinite(n)?Math.max(0,Math.floor(n)):Math.max(0,r)}(n),V=this.getObjectMotionHistory(e,m),G=rl(e),z=nl(e);let L=0,U=null;if(!(n instanceof ha&&R>1)||e instanceof wa||o)for(let e=0;e<R;e+=1){const i=Wr(t,m,1,1,1,1,void 0,V.matrix,G,z,V.valid?1:0);0===e&&(L=i)}else{let t=this.repeatedMeshInstances.get(e);t&&t.geometry===n&&!t.data.disposed||(t&&this.repeatedInstanceResources.get(t.data)?.(),t=this.createRepeatedMeshInstances(e,n)),U=t.data,U.update(R,m,V.matrix,G,z,V.valid?1:0),!U.residentBufferDirty&&U.residentInstanceBinding.buffer||this.residentInstanceUploadsScratch.push(U)}this.commitObjectMotionHistory(V,m),i(m);for(let e=0;e<T;e+=1){const t=I.templates[e],i=this.populateDrawCall(this.acquireDrawCall(),t,L,R,b,y,S,M,l);i.cameraDetailRejected=C,i.residentInstanceBinding=U?.residentInstanceBinding??t.residentInstanceBinding,t.transparent?this.transparentDraws.push(i):this.pushDraw(i);const r=s?a[t.geometryGroup?.materialIndex??0]:a;this.pushToonOutlineDraw(i,r)}}collectStaticMeshDraws(e,t,i,r){let n=this.staticMeshDraws.get(t);if(n)n.templates!==i&&(this.staticSpatialDrawRevision++,n.templates=i,n.draws.length=0,n.outlines.length=0);else{n={templates:i,draws:[],outlines:[],slot:this.staticInstanceSlots.allocate(),motionHistory:this.getObjectMotionHistory(e,e.matrixWorld.elements),motionMode:NaN,motionScale:NaN,historyValid:-1,motionFrames:0},this.staticMeshDraws.set(t,n);const r=n.slot;t.onInvalidate=()=>{t.onInvalidate=void 0,this.staticSpatialDrawRevision++,this.staticMeshDraws.delete(t),this.retiredStaticInstanceSlots.push(r),this.clearIndirectBundleCache()}}const a=n.motionHistory,s=!0===e.userData.motionBlurTeleported;s&&(e.userData.motionBlurTeleported=!1);const o=this.motionVectorHistoryValid&&!s&&a.generation===this.motionVectorHistoryGeneration&&a.lastExtractionVersion===this.motionHistoryExtractionVersion-1?1:0,l=rl(e),c=nl(e);n.motionFrames<2||n.motionMode!==l||n.motionScale!==c||n.historyValid!==o?(this.staticInstanceSlots.write(n.slot,e.matrixWorld.elements,0===n.motionFrames?a.matrix:e.matrixWorld.elements,l,c,o,this.extractionVersion,this.residentInstanceUploadsScratch),0===n.motionFrames&&a.matrix.set(e.matrixWorld.elements),n.motionFrames=Math.min(2,n.motionFrames+1),n.motionMode=l,n.motionScale=c,n.historyValid=o):this.staticInstanceSlots.queueUpload(n.slot,this.extractionVersion,this.residentInstanceUploadsScratch),a.generation=this.motionVectorHistoryGeneration,a.lastExtractionVersion=this.motionHistoryExtractionVersion;const u=Array.isArray(e.material)?e.material:null;for(let a=0;a<i.length;a++){const s=i[a];let o=n.draws[a];const l=s.material.wireframe&&"triangle-list"===s.material.primitiveTopology;if(!o||o.wireframe!==l){const e=s.wireframe===l?s:{...s,wireframe:l};o=this.populateDrawCall(o??this.createDrawCall(),e,n.slot.index,1,t.boundsCenter.x,t.boundsCenter.y,t.boundsCenter.z,t.boundsRadius,t),n.draws[a]=o,this.staticSpatialDraws.add(o)}o.receiveShadow!==e.receiveShadow&&(o.materialResource=null),o.receiveShadow=e.receiveShadow,o.castShadow=e.castShadow,o.renderOrder=e.renderOrder,o.transparent=s.material.transparent||s.material.requiresLatePass(),o.cameraDetailRejected=r,o.residentInstanceBinding=n.slot.page.residentInstanceBinding,this.pushDraw(o),this.pushToonOutlineDraw(o,u?u[s.geometryGroup?.materialIndex??0]:e.material,n.outlines,a)}}prepareSceneForCompilation(e,t,i){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().");const r=i?this.pipelineCompilationDiagnostics:void 0;let n=performance.now();const a=e=>{r&&(r.phases[e]=Math.round(performance.now()-n)),n=performance.now()};e.matrixWorldAutoUpdate&&e.updateMatrixWorld(),null===t.parent&&t.matrixWorldAutoUpdate&&t.updateMatrixWorld(),a("worldMatrices");const s=this.extractScene(e,t,!0);a("extractScene"),this.ensureShadowTextureSizes(s),this.uploadInstanceData(s.instanceData),this.uploadResidentInstanceData(s.residentInstanceUploads),this.uploadDrawMetadata(this.getHiZOcclusionCullingActive()?s.gpuOpaqueDraws:[]),this.ensureTiledLightingSize(),this.updateCameraUniforms(t,e),this.updateLightUniforms(s),a("sceneUploads");const o=this.compileDrawScratch;o.length=0,o.push(...s.gpuOpaqueDraws,...s.directOpaqueDraws,...s.transparentDraws);for(const e of o)this.prepareDrawGeometryVertexBuffers(e);if(r&&(r.drawCount=o.length),a("geometryBuffers"),i){const e=[];this.renderGraph.reset();const t=this.state.device.createCommandEncoder({label:"renderer-graph-compilation-encoder"}),i=this.createGraphBuilderContext(this.renderGraph,t,this.getSharedSceneBindGroup(),this.getSharedShadowBindGroup(),null,this.state.sceneColorView,s,{drawCallCount:0,triangleCount:0},e);this.graphBuilder(this.renderGraph,i),r&&(r.materialRequestCount=e.length),a("renderGraph");const n=[],o=new Set;for(const t of e){n.push(this.compileDrawMaterialsAsync(t.draws,t.colorTargetFormats,t.sampleCount));const e=`${t.sampleCount}:${t.colorTargetFormats.join("|")}:${t.staticDrawStage}`;o.has(e)||(o.add(e),n.push(this.compileStaticDrawMaterialsAsync(t.colorTargetFormats,t.sampleCount,t.staticDrawStage)))}return a("scheduleMaterials"),Promise.all(n).then(()=>{})}this.compileDrawMaterials(o)}collectInstancedMesh(e,t,i,r){if(void 0===e.geometry?.getAttribute("position"))return;const n=e.material;if(!1===n.visible)return;const a=this.instancedMeshExtractionCache.get(e),s=!0===e.userData.webGpuCacheMaterial&&a?.sourceMaterial===n&&a.sourceMaterialVersion===n.version&&a.material!==this.fallbackMaterial?a.material:this.resolveMaterial(n);if(!s)return;const o=vn(e),l=this.getGeometryResource(e.geometry,!0),c=this.getInstancedMeshExtractionCacheEntry(e,s,o,l),u=e.instanceMatrix.array,d=e.instanceMatrix.version,h=e.instanceColor?.array,p=e.instanceColor?.itemSize??0,m=e.instanceColor?.version??-1,g=an(e.matrixWorld.elements),v=f(e),x=g&&!e.frustumCulled&&v.minScreenSize<=0&&v.maxDistance<=0;if(!(c.cacheValid&&(x||c.cachedBoundsValid)&&c.cachedCount===e.count&&c.cachedInstanceMatrixVersion===d&&c.cachedInstanceColorVersion===m&&nn(c.cachedMatrixWorld,e.matrixWorld.elements))){const t=c.cachedInstanceMatrixVersion!==d||c.cachedCount!==e.count,i=c.cachedInstanceColorVersion!==m||c.cachedCount!==e.count;if(x){c.cachedBoundsValid=!1;const r=e.matrixWorld.elements,n=r[12]??0,a=r[13]??0,s=r[14]??0;c.cachedDrawBoundsCenter.set(n,a,s),c.cachedDrawBoundsRadius=0,c.cachedBoundsMin.set(n,a,s),c.cachedBoundsMax.set(n,a,s),c.cachedInstanceMatrixVersion=d,c.cachedInstanceColorVersion=m,c.cachedCount=e.count,c.cachedDefaultColorData=null,rn(e.matrixWorld.elements,c.cachedMatrixWorld),c.residentBufferDirty||=t,c.residentColorBufferDirty||=i,c.cacheValid=!0}else{c.cachedBoundsValid=!0;const t=c.cachedInstanceData.beginWriteInstances(e.count),i=c.cachedBoundsMin,r=c.cachedBoundsMax;i.set(1/0,1/0,1/0),r.set(-1/0,-1/0,-1/0);const n=c.localBoundsCenter,a=c.localBoundsRadius,s=e.matrixWorld.elements,o=an(s),l=n.x,f=n.y,g=n.z,v=s[0],x=s[4],w=s[8],b=s[12],y=s[1],S=s[5],M=s[9],P=s[13],B=s[2],D=s[6],I=s[10],T=s[14],R=s[3],V=s[7],G=s[11],z=s[15];for(let n=0;n<e.count;n+=1){const e=16*n,s=n*C,c=u[e+0]??0,d=u[e+1]??0,m=u[e+2]??0,L=u[e+3]??0,U=u[e+4]??0,k=u[e+5]??0,A=u[e+6]??0,O=u[e+7]??0,E=u[e+8]??0,j=u[e+9]??0,$=u[e+10]??0,W=u[e+11]??0,N=u[e+12]??0,_=u[e+13]??0,H=u[e+14]??0,q=u[e+15]??0;let K,Y,Z,X,J,Q,ee,te,ie,re,ne,ae,se,oe,le,ce;o?(K=c,Y=d,Z=m,X=L,J=U,Q=k,ee=A,te=O,ie=E,re=j,ne=$,ae=W,se=N,oe=_,le=H,ce=q):(K=v*c+x*d+w*m+b*L,J=v*U+x*k+w*A+b*O,ie=v*E+x*j+w*$+b*W,se=v*N+x*_+w*H+b*q,Y=y*c+S*d+M*m+P*L,Q=y*U+S*k+M*A+P*O,re=y*E+S*j+M*$+P*W,oe=y*N+S*_+M*H+P*q,Z=B*c+D*d+I*m+T*L,ee=B*U+D*k+I*A+T*O,ne=B*E+D*j+I*$+T*W,le=B*N+D*_+I*H+T*q,X=R*c+V*d+G*m+z*L,te=R*U+V*k+G*A+z*O,ae=R*E+V*j+G*$+z*W,ce=R*N+V*_+G*H+z*q),t[s+0]=K,t[s+1]=Y,t[s+2]=Z,t[s+3]=X,t[s+4]=J,t[s+5]=Q,t[s+6]=ee,t[s+7]=te,t[s+8]=ie,t[s+9]=re,t[s+10]=ne,t[s+11]=ae,t[s+12]=se,t[s+13]=oe,t[s+14]=le,t[s+15]=ce;const ue=n*p;t[s+16]=h?h[ue+0]??1:1,t[s+17]=h?h[ue+1]??1:1,t[s+18]=h?h[ue+2]??1:1,t[s+19]=h&&p>=4?h[ue+3]??1:1,t[s+20]=n,t[s+21]=1,t[s+22]=1,t[s+23]=0;for(let e=0;e<16;e+=1)t[s+24+e]=t[s+e];const de=K*l+J*f+ie*g+se,he=Y*l+Q*f+re*g+oe,pe=Z*l+ee*f+ne*g+le,fe=Math.sqrt(K*K+Y*Y+Z*Z),me=Math.sqrt(J*J+Q*Q+ee*ee),ge=Math.sqrt(ie*ie+re*re+ne*ne),ve=a*Math.max(fe,me,ge,1e-5);fn(i,r,F.set(de,he,pe),ve)}c.cachedDrawBoundsCenter.copy(i).add(r).multiplyScalar(.5);const L=r.x-c.cachedDrawBoundsCenter.x,U=r.y-c.cachedDrawBoundsCenter.y,k=r.z-c.cachedDrawBoundsCenter.z;c.cachedDrawBoundsRadius=Math.sqrt(L*L+U*U+k*k),c.cachedInstanceMatrixVersion=d,c.cachedInstanceColorVersion=m,c.cachedCount=e.count,c.cachedDefaultColorData=null,rn(e.matrixWorld.elements,c.cachedMatrixWorld),c.residentBufferDirty=!0,c.residentColorBufferDirty=!0,c.cacheValid=!0}}if(!r(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),sn(this.extractedBoundsMinScratch,this.extractedBoundsMaxScratch,c.cachedBoundsMin,c.cachedBoundsMax);const w=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&&!w.transparent?this.directOpaqueDrawsScratch.push(w):this.pushDraw(w)}getSkinnedRenderRecord(e){let t=this.skinnedRenderRecords.get(e);return t?t.geometry!==e.geometry&&(t.geometry.removeEventListener("dispose",t.onGeometryDispose),t.geometry=e.geometry,t.geometry.addEventListener("dispose",t.onGeometryDispose)):(t={slot:this.skinnedInstanceSlots.allocate(),draws:[],outlines:[],geometry:e.geometry,onGeometryDispose:()=>{const t=this.skinnedRenderRecords.get(e);t&&(t.geometry!==e.geometry?this.getSkinnedRenderRecord(e):this.releaseSkinnedMeshResources(e))}},this.skinnedRenderRecords.set(e,t),e.geometry.addEventListener("dispose",t.onGeometryDispose)),t}releaseSkinnedRenderRecord(e){const t=this.skinnedRenderRecords.get(e);if(!t)return;this.clearDynamicDepthBundles(),this.clearSkinnedMaterialBundle(),t.geometry.removeEventListener("dispose",t.onGeometryDispose),this.skinnedInstanceSlots.release(t.slot),this.skinnedRenderRecords.delete(e);const i=this.skinnedGeometryCache.get(e);i?.skinning.releaseInstance(),i?.skinning.bindUniformBuffer.destroy(),this.skinnedGeometryCache.delete(e)}releaseSkinnedMeshResources(e){const t=this.skinnedGeometryCache.get(e);if(this.releaseSkinnedRenderRecord(e),t&&this.skinnedGeometryCache.delete(e)&&(t.skinning.releaseInstance(),t.skinning.bindUniformBuffer.destroy()),t){for(const e of this.skinnedGeometryCache.values())if(e.skinning.palette===t.skinning.palette)return;this.releaseSkinningPalette(t.skinning.palette)}}collectSkinnedMesh(e,t,i,r){if(void 0===e.geometry?.getAttribute("position"))return;const n=e.boundingSphere,a=F;let s=0,o=0,l=0,c=0;if(null!==n){const t=n.center,i=e.matrixWorld.elements;if(s=i[0]*t.x+i[4]*t.y+i[8]*t.z+i[12],o=i[1]*t.x+i[5]*t.y+i[9]*t.z+i[13],l=i[2]*t.x+i[6]*t.y+i[10]*t.z+i[14],c=n.radius*hn(e.matrixWorld),e.frustumCulled&&!r(s,o,l,c,!0))return}const u=Array.isArray(e.material)?e.material:null,d=u?u[0]:e.material,h=vn(e),p=null!==e.geometry.index,m=this.getSkinnedGeometryResource(e,!0);if(this.refreshSkinningPalette(m.skinning.palette),this.refreshSkinningBindMatrices(e,m.skinning),null===n){if(this.updateSkinnedBounds(e,m),a.copy(m.localBoundsCenter).applyMatrix4(e.matrixWorld),c=m.localBoundsRadius*hn(e.matrixWorld),!r(a.x,a.y,a.z,c,e.frustumCulled))return}else a.set(s,o,l);this.uploadSkinningResources(m.skinning);const g=this.getObjectMotionHistory(e,e.matrixWorld.elements),v=this.getSkinnedRenderRecord(e),x=v.slot.index;this.skinnedInstanceSlots.write(v.slot,e.matrixWorld.elements,g.matrix,rl(e),nl(e),g.valid?1:0,this.extractionVersion,this.residentInstanceUploadsScratch),this.commitObjectMotionHistory(g,e.matrixWorld.elements),i(e.matrixWorld.elements);const w=e.geometry.groups,b=w.length>0&&(null===u||u.length>0),y=b?w.length:1;v.draws.length=Math.min(v.draws.length,y),v.outlines.length=Math.min(v.outlines.length,y);const S=this.hasRenderCallbacks(e),C=e.matrixWorld.determinant()<0,M=f(e);for(let t=0;t<y;t++){const i=b?w[t]:null,r=i&&u?u[i.materialIndex??0]??d:d,n=this.resolveSkinnedMaterial(r);if(!n)continue;const s=i?i.start:e.geometry.drawRange.start,o=Ar(e.geometry,p,s,i?i.count:e.geometry.drawRange.count);let l=v.draws[t];l||(v.draws[t]=l=this.createDrawCall());const f=n.wireframe&&"triangle-list"===n.primitiveTopology;if(l.geometry!==e.geometry||l.geometryResource!==m.resource||l.skinning!==m.skinning||l.material!==n||l.customDepthMaterial!==h||l.geometryGroup!==i||l.wireframe!==f||l.indexed!==(f||p)||l.start!==(f?2*s:s)||l.count!==(f?2*o:o)){const r=this.skinnedDrawKeys.get(e,t,n,p,s,o,h);this.populateDynamicDrawCall(l,e.geometry,e,m.resource,n,h,v.slot.page.residentInstanceBinding,e,i,r.batchKey,r.batchHash,p,s,o,n.transparent,e.renderOrder,S,e.castShadow,e.receiveShadow,r.materialId,r.geometryId,r.depthMaterialId,x,1,a.x,a.y,a.z,c,m.skinning)}l.receiveShadow!==e.receiveShadow&&(l.materialResource=null),l.receiveShadow=e.receiveShadow,l.castShadow=e.castShadow,l.renderOrder=e.renderOrder,l.hasRenderCallbacks=S,l.frontFaceCW=C,l.detailCulling=M,l.cameraDetailRejected=void 0,l.transparent=n.transparent,l.boundsCenter.copy(a),l.boundsRadius=c,l.sortDepth=0,l.transparentSortGroup=0,l.transparentSortOrder=0,this.pushDraw(l),r?.userData?.outlineParameters&&this.pushToonOutlineDraw(l,r,v.outlines,t)}}collectBatchedMesh(e,t,i,r,n,a,s){if(void 0===e.geometry?.getAttribute("position"))return;const o=this.resolveMaterial(e.material);if(!o)return;const l=vn(e),c=(e.geometry.index,this.getGeometryResource(e.geometry,!0)),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,v=u._matricesTexture?.version??0,x=u._colorsTexture?.version??-1;if(m.cacheValid&&!o.transparent&&m.cachedMatricesVersion===v&&m.cachedColorsVersion===x&&m.cachedInstanceInfoLength===d.length&&m.cachedGeometryCount===(u._geometryCount??0)&&nn(m.cachedMatrixWorld,g)&&this.batchedGeometryIdsMatchSnapshot(m.geometryIdsSnapshot,d)){let t=!1;for(let i=0;i<m.cachedDraws.length;i+=1){const n=m.cachedDraws[i];r(n.boundsCenter.x,n.boundsCenter.y,n.boundsCenter.z,n.boundsRadius,e.frustumCulled)&&(t=!0,this.pushDraw(this.populateDynamicDrawCall(this.acquireDrawCall(),n.template.geometry,n.template.geometryKey,n.template.geometryResource,n.template.material,n.template.customDepthMaterial,m.residentInstanceBinding,n.template.sourceObject,n.template.geometryGroup,n.template.batchKey,n.template.batchHash,n.template.indexed,n.template.start,n.template.count,n.template.transparent,n.template.sourceObject?.renderOrder??n.template.renderOrder,this.hasRenderCallbacks(n.template.sourceObject),n.template.sourceObject?Boolean(n.template.sourceObject.castShadow):n.template.castShadow,n.template.sourceObject?Boolean(n.template.sourceObject.receiveShadow):n.template.receiveShadow,n.template.sortMaterialId,n.template.sortGeometryId,n.template.sortCustomDepthMaterialId,n.instanceStart,n.instanceCount,n.boundsCenter.x,n.boundsCenter.y,n.boundsCenter.z,n.boundsRadius)))}if(!t)return;return!m.residentBufferDirty&&m.residentInstanceBinding||this.residentInstanceUploadsScratch.push(m),void sn(this.extractedBoundsMinScratch,this.extractedBoundsMaxScratch,m.cachedBoundsMin,m.cachedBoundsMax)}if(o.transparent){const o=[],l=!e.sortObjects||null!==e.customSort;for(let n=0;n<h;n+=1){const c=d[n];if(!c?.active||!c.visible)continue;const u=m.templates[c.geometryIndex];if(!u)continue;p?U.fromArray(p,16*n):e.getMatrixAt(n,U),k.multiplyMatrices(e.matrixWorld,U);const h=u.localBoundsCenter,g=k.elements,v=g[0]*h.x+g[4]*h.y+g[8]*h.z+g[12],x=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(!r(v,x,w,C,e.frustumCulled&&e.perObjectFrustumCulled))continue;const M=f?f[4*n+0]??1:1,P=f?f[4*n+1]??1:1,B=f?f[4*n+2]??1:1,D=f?f[4*n+3]??1:1,I=Nr(t,k,M,P,B,D,n);i(k.elements);const T=this.populateDrawCall(this.acquireDrawCall(),u,I,1,v,x,w,C),R=(v-a.x)*s.x+(x-a.y)*s.y+(w-a.z)*s.z;l?o.push({start:u.start,count:u.count,z:R,index:n,draw:T}):(T.sortDepth=R,this.transparentDraws.push(T))}if(l&&o.length>0){e.sortObjects&&e.customSort?e.customSort.call(e,o,n):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 i=Hr(e);for(let e=0;e<o.length;e+=1){const r=o[e].draw;r.sortDepth=t,r.transparentSortGroup=i,r.transparentSortOrder=e,this.transparentDraws.push(r)}}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 i=m.groups[t.geometryIndex];i?(m.geometryIdsSnapshot[e]=t.geometryIndex,i.activeInFrame||(i.activeInFrame=!0,i.activeCount=0,i.boundsMin.set(1/0,1/0,1/0),i.boundsMax.set(-1/0,-1/0,-1/0),w.push(i)),i.activeCount+=1,S+=1):m.geometryIdsSnapshot[e]=-1}const M=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*C,P+=t.activeCount}const B=an(g),D=g[0],I=g[4],T=g[8],R=g[12],V=g[1],G=g[5],z=g[9],L=g[13],A=g[2],F=g[6],O=g[10],E=g[14],j=g[3],$=g[7],W=g[11],N=g[15];for(let t=0;t<h;t+=1){const i=m.geometryIdsSnapshot[t]??-1;if(i<0)continue;const r=m.groups[i];if(!r)continue;let n,a,s,o,l,c,u,d,h,g,v,x,w,S,P,k,_,H,q,K,Y,Z,X,J,Q,ee,te,ie,re,ne,ae,se;if(p){const e=16*t;n=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,v=p[e+10]??0,x=p[e+11]??0,w=p[e+12]??0,S=p[e+13]??0,P=p[e+14]??0,k=p[e+15]??0}else{e.getMatrixAt(t,U);const i=U.elements;n=i[0]??0,a=i[1]??0,s=i[2]??0,o=i[3]??0,l=i[4]??0,c=i[5]??0,u=i[6]??0,d=i[7]??0,h=i[8]??0,g=i[9]??0,v=i[10]??0,x=i[11]??0,w=i[12]??0,S=i[13]??0,P=i[14]??0,k=i[15]??0}B?(_=n,H=a,q=s,K=o,Y=l,Z=c,X=u,J=d,Q=h,ee=g,te=v,ie=x,re=w,ne=S,ae=P,se=k):(_=D*n+I*a+T*s+R*o,Y=D*l+I*c+T*u+R*d,Q=D*h+I*g+T*v+R*x,re=D*w+I*S+T*P+R*k,H=V*n+G*a+z*s+L*o,Z=V*l+G*c+z*u+L*d,ee=V*h+G*g+z*v+L*x,ne=V*w+G*S+z*P+L*k,q=A*n+F*a+O*s+E*o,X=A*l+F*c+O*u+E*d,te=A*h+F*g+O*v+E*x,ae=A*w+F*S+O*P+E*k,K=j*n+$*a+W*s+N*o,J=j*l+$*c+W*u+N*d,ie=j*h+$*g+W*v+N*x,se=j*w+$*S+W*P+N*k);const oe=f?f[4*t+0]??1:1,le=f?f[4*t+1]??1:1,ce=f?f[4*t+2]??1:1,ue=f?f[4*t+3]??1:1,de=r.writeOffset;M[de+0]=_,M[de+1]=H,M[de+2]=q,M[de+3]=K,M[de+4]=Y,M[de+5]=Z,M[de+6]=X,M[de+7]=J,M[de+8]=Q,M[de+9]=ee,M[de+10]=te,M[de+11]=ie,M[de+12]=re,M[de+13]=ne,M[de+14]=ae,M[de+15]=se,M[de+16]=oe,M[de+17]=le,M[de+18]=ce,M[de+19]=ue,M[de+20]=t,M[de+21]=1,M[de+22]=1,M[de+23]=0;for(let e=0;e<16;e+=1)M[de+24+e]=M[de+e];r.writeOffset+=C;const he=r.template.localBoundsCenter,pe=_*he.x+Y*he.y+Q*he.z+re,fe=H*he.x+Z*he.y+ee*he.z+ne,me=q*he.x+X*he.y+te*he.z+ae,ge=Math.sqrt(_*_+H*H+q*q),ve=Math.sqrt(Y*Y+Z*Z+X*X),xe=Math.sqrt(Q*Q+ee*ee+te*te),we=r.template.localBoundsRadius*Math.max(ge,ve,xe,1e-5),be=pe-we,ye=fe-we,Se=me-we,Ce=pe+we,Me=fe+we,Pe=me+we;be<r.boundsMin.x&&(r.boundsMin.x=be),ye<r.boundsMin.y&&(r.boundsMin.y=ye),Se<r.boundsMin.z&&(r.boundsMin.z=Se),Ce>r.boundsMax.x&&(r.boundsMax.x=Ce),Me>r.boundsMax.y&&(r.boundsMax.y=Me),Pe>r.boundsMax.z&&(r.boundsMax.z=Pe),be<b.x&&(b.x=be),ye<b.y&&(b.y=ye),Se<b.z&&(b.z=Se),Ce>y.x&&(y.x=Ce),Me>y.y&&(y.y=Me),Pe>y.z&&(y.z=Pe)}const _=m.cachedDraws;let H=0;for(let e=0;e<w.length;e+=1){const t=w[e],i=.5*(t.boundsMin.x+t.boundsMax.x),r=.5*(t.boundsMin.y+t.boundsMax.y),n=.5*(t.boundsMin.z+t.boundsMax.z),a=t.boundsMax.x-i,s=t.boundsMax.y-r,o=t.boundsMax.z-n,l=Math.sqrt(a*a+s*s+o*o);let c=_[H];c||(c={template:t.template,instanceStart:0,instanceCount:0,boundsCenter:new Ca,boundsRadius:0},_[H]=c),c.template=t.template,c.instanceStart=t.instanceStart,c.instanceCount=t.activeCount,c.boundsCenter.set(i,r,n),c.boundsRadius=l,H+=1}_.length=H,m.cachedMatricesVersion=v,m.cachedColorsVersion=x,m.cachedInstanceInfoLength=d.length,m.cachedGeometryCount=u._geometryCount??0,rn(g,m.cachedMatrixWorld),m.residentBufferDirty=!0,m.cacheValid=!0;let q=!1;for(let t=0;t<_.length;t+=1){const i=_[t];r(i.boundsCenter.x,i.boundsCenter.y,i.boundsCenter.z,i.boundsRadius,e.frustumCulled)&&(q=!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)))}q&&(this.residentInstanceUploadsScratch.push(m),sn(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,P,0,C)}uploadResidentInstanceData(e){if(this.state.device)for(let t=0;t<e.length;t+=1){const i=e[t],r=i.residentInstanceBinding;if(!r)continue;if("instanced-direct"===r.mode){const e=i,t=e.sourceMesh,n=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((!r.buffer||a>i.residentBufferSize)&&(r.buffer?.destroy(),i.residentBufferSize=256*Math.ceil(a/256),r.buffer=this.state.device.createBuffer({label:"renderer-instanced-mesh-matrix-buffer",size:i.residentBufferSize,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST}),r.sceneBindGroup=null,r.shadowBindGroup=null,r.shadowBindGroups.clear(),r.sceneBindGroupVersion=0,r.shadowBindGroupVersion=0,i.residentBufferDirty=!0),(!r.colorBuffer||o>i.residentColorBufferSize)&&(r.colorBuffer?.destroy(),i.residentColorBufferSize=256*Math.ceil(o/256),r.colorBuffer=this.state.device.createBuffer({label:"renderer-instanced-mesh-color-buffer",size:i.residentColorBufferSize,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST}),r.sceneBindGroup=null,r.shadowBindGroup=null,r.shadowBindGroups.clear(),r.sceneBindGroupVersion=0,r.shadowBindGroupVersion=0,i.residentColorBufferDirty=!0),i.residentBufferDirty&&r.buffer&&(t.count>0?this.state.device.queue.writeBuffer(r.buffer,0,$r(n),0,16*t.count):this.state.device.queue.writeBuffer(r.buffer,0,B,0,4),i.residentBufferDirty=!1),i.residentColorBufferDirty&&r.colorBuffer){if(t.instanceColor&&4===t.instanceColor.itemSize&&t.instanceColor.array instanceof Float32Array)this.state.device.queue.writeBuffer(r.colorBuffer,0,$r(t.instanceColor.array),0,4*s);else{let i=e.cachedDefaultColorData;i&&i.length===4*s||(i=new Float32Array(4*s),e.cachedDefaultColorData=i);for(let e=0;e<s;e+=1){const r=4*e;t.instanceColor?(i[r+0]=t.instanceColor.getComponent(e,0),i[r+1]=t.instanceColor.itemSize>1?t.instanceColor.getComponent(e,1):1,i[r+2]=t.instanceColor.itemSize>2?t.instanceColor.getComponent(e,2):1,i[r+3]=t.instanceColor.itemSize>3?t.instanceColor.getComponent(e,3):1):(i[r+0]=1,i[r+1]=1,i[r+2]=1,i[r+3]=1)}this.state.device.queue.writeBuffer(r.colorBuffer,0,$r(i),0,i.length)}i.residentColorBufferDirty=!1}continue}const n=Math.max(4,i.cachedInstanceData.byteLength);let a=!1;if((!r.buffer||n>i.residentBufferSize)&&(r.buffer?.destroy(),i.residentBufferSize=256*Math.ceil(n/256),r.buffer=this.state.device.createBuffer({label:"renderer-instanced-mesh-buffer",size:i.residentBufferSize,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST}),r.sceneBindGroup=null,r.shadowBindGroup=null,r.shadowBindGroups.clear(),r.sceneBindGroupVersion=0,r.shadowBindGroupVersion=0,i.residentBufferDirty=!0,a=!0),i.residentBufferDirty){if(!r.buffer)continue;if(i.cachedInstanceData.floatLength>0){const e=a?void 0:i.residentBufferDirtyRange,t=e?e.start*C*4:0,n=e?(e.end-e.start)*C*4:i.cachedInstanceData.byteLength;this.state.device.queue.writeBuffer(r.buffer,t,i.cachedInstanceData.rawData.buffer,t,n)}else this.state.device.queue.writeBuffer(r.buffer,0,P,0,C);i.residentBufferDirty=!1,i.residentBufferDirtyRange&&(i.residentBufferDirtyRange.start=1/0,i.residentBufferDirtyRange.end=0)}}}invalidateGraphTextureBundles(){this.graphTextureResourceVersion+=1,this.clearIndirectBundleCache(),this.materialPassStaticBundleCache=new WeakMap;for(const e of this.staticDrawSets)e.indirectForwardBundleCache.clear(),e.directForwardBundle=null,e.directForwardBundleSceneBindGroup=null}clearIndirectBundleCache(){this.state.indirectForwardBundleCache.clear(),this.state.directForwardBundleCache.clear(),this.clearDynamicDepthBundles(),this.clearSkinnedMaterialBundle(),this.indirectBundleInvalidationVersion+=1}clearStaticDrawSetBundleCaches(){this.materialPassStaticBundleCache=new WeakMap;for(const e of this.staticDrawSets){for(const t of e.visibleIndirectSubmissionStreams??[])t.forwardBundleEntry=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;for(const t of e.shadowChunks)t.bundles=new WeakMap;e.depthMaterialResources.clear(),e.temporalDepthSupported=ks(e.draws)}}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&&this.state.spotLightMapView))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},{binding:9,resource:this.state.spotLightMapView},{binding:11,resource:this.tiledPointLights.view}]})),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 i=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,i),i}buildIndirectSubmissionStreams(e,t,i,r){let n=this.dynamicIndirectSubmissionCache.get(e);n||(n=[],this.dynamicIndirectSubmissionCache.set(e,n));const a=void 0!==r;let s=n.find(e=>e.lastUsedExtractionVersion!==this.extractionVersion&&e.sceneBindGroup===t&&e.instanceAccessMode===i&&e.usesExplicitMaterialResources===a);s||(s={sceneBindGroup:t,instanceAccessMode:i,usesExplicitMaterialResources:a,lastUsedExtractionVersion:-1,streams:[]},n.push(s)),s.lastUsedExtractionVersion=this.extractionVersion;const o=s.streams;let l=0,c=null,u=0;for(let n=0;n<e.length;n+=1){const a=e[n],s=r?.[n]??(i?this.getMaterialResource(a.material,i,a.receiveShadow,void 0,null!==a.skinning,this.drawUsesBatching(a)):this.getMaterialResourceForDraw(a)),d=i?t:this.resolveSceneBindGroupForDraw(a,t),h=this.getIndirectStreamKey(s.pipeline,s.bindGroup,d,a.geometryKey),p=mn(a);if(c&&c.key===h&&c.indirectStartIndex+c.indirectCount===n){c.indirectCount+=1,c.drawCallCount+=1,c.triangleCount+=p;continue}c&&c.indirectCount!==u&&(c.forwardBundleEntry=null,c.forwardBundleColorFormatsId=0,c.forwardBundleDrawMetadataResource=null,c.forwardBundleCandidateExtractionVersion=-1),c=o[l],u=c?.indirectCount??0;const f=void 0!==c&&c.key===h&&c.material===a.material&&c.materialResource===s&&c.sceneBindGroup===d&&c.geometry===a.geometry&&c.geometryKey===a.geometryKey&&c.geometryResource===a.geometryResource&&c.indirectStartIndex===n;c?(f||(c.forwardBundleEntry=null,c.forwardBundleColorFormatsId=0,c.forwardBundleDrawMetadataResource=null,c.forwardBundleCandidateExtractionVersion=-1),c.key=h,c.material=a.material,c.materialResource=s,c.sceneBindGroup=d,c.geometry=a.geometry,c.geometryKey=a.geometryKey,c.geometryResource=a.geometryResource,c.indirectStartIndex=n,c.indirectCount=1,c.drawCallCount=1,c.triangleCount=p):(c={key:h,material:a.material,materialResource:s,sceneBindGroup:d,geometry:a.geometry,geometryKey:a.geometryKey,geometryResource:a.geometryResource,indirectStartIndex:n,indirectCount:1,drawCallCount:1,triangleCount:p,forwardBundleEntry:null,forwardBundleMaterialVersion:-1,forwardBundleGraphTextureResourceVersion:-1,forwardBundleInvalidationVersion:-1,forwardBundleDrawMetadataResource:null,forwardBundleSampleCount:0,forwardBundleColorFormatsId:0,forwardBundleCandidateExtractionVersion:-1},o[l]=c),l+=1}return c&&c.indirectCount!==u&&(c.forwardBundleEntry=null,c.forwardBundleColorFormatsId=0,c.forwardBundleDrawMetadataResource=null,c.forwardBundleCandidateExtractionVersion=-1),o.length!==l&&(o.length=l),o}getIndirectStreamKey(e,t,i,r){let n=this.indirectStreamKeyCache.get(e);n||(n=new WeakMap,this.indirectStreamKeyCache.set(e,n));let a=n.get(t);a||(a=new WeakMap,n.set(t,a));let s=a.get(i);s||(s=new WeakMap,a.set(i,s));let o=s.get(r);return void 0===o&&(o=this.nextIndirectStreamKey,this.nextIndirectStreamKey+=1,s.set(r,o)),o}getOrCreateStaticIndirectSubmissionStreams(e,t,i=ol){const r=i.join("|"),n=null!==e.visibleIndirectSubmissionStreams&&e.visibleIndirectStreamsSceneBindGroup===t&&e.visibleIndirectStreamsSampleCount===this.sampleCount&&e.visibleIndirectStreamsColorFormatsKey===r;if(n)return e.visibleIndirectSubmissionStreams;let a=!n;for(const t of e.visibleMaterialBindings){const r=this.getMaterialResource(t.material,"packed-visible",t.receiveShadow,i,!1,t.usesBatching),n=t.resource;t.resource=r,n!==r&&(a=!0);for(const i of t.drawIndices)e.visibleDrawMaterialResources[i]!==r&&(a=!0),e.visibleDrawMaterialResources[i]=r}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=r,e.indirectForwardBundleCache.clear()),e.visibleIndirectSubmissionStreams}getOrCreateIndirectForwardBundle(e,t=this.state.drawMetadataResource,i=this.state.indirectForwardBundleCache,r="renderer-indirect-forward-bundle",n=ol,a=!1,s=this.getColorFormatsId(n)){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.");i.prune(this.extractionVersion);if(null!=e.forwardBundleEntry?.bundle&&e.forwardBundleMaterialVersion===e.material.version&&e.forwardBundleGraphTextureResourceVersion===this.graphTextureResourceVersion&&e.forwardBundleInvalidationVersion===this.indirectBundleInvalidationVersion&&e.forwardBundleDrawMetadataResource===t&&e.forwardBundleSampleCount===this.sampleCount&&e.forwardBundleColorFormatsId===s)return i.touch(e.forwardBundleEntry,this.extractionVersion),e.forwardBundleEntry.bundle;e.forwardBundleEntry=null;const o=this.getIndirectBundleHash(e,t,s),l=i.get(o),c=l?.find(i=>i.streamKey===e.key&&i.positionBuffer===e.geometryResource.position&&i.indexBuffer===e.geometryResource.index&&i.indirectBuffer===t.indirectBuffer&&i.indirectStartIndex===e.indirectStartIndex&&i.indirectCount===e.indirectCount&&i.sampleCount===this.sampleCount&&i.materialVersion===e.material.version&&i.graphTextureResourceVersion===this.graphTextureResourceVersion&&i.colorFormatsId===s);if(c)return i.touch(c,this.extractionVersion),this.setRetainedIndirectBundleState(e,c,t,s),c.bundle;if(a&&e.forwardBundleCandidateExtractionVersion<0)return e.forwardBundleCandidateExtractionVersion=this.extractionVersion,null;if(a&&e.forwardBundleCandidateExtractionVersion===this.extractionVersion)return null;const u=this.state.device.createRenderBundleEncoder({label:`${r}-${o}`,colorFormats:n,depthStencilFormat:"depth32float",sampleCount:this.sampleCount});if(u.setPipeline(e.materialResource.pipeline),this.bindGeometryVertexBuffers(u,e.geometry,e.geometryResource,e.materialResource.vertexAttributes,0,1,e.material.wireframe),Fi(u,0,e.sceneBindGroup),u.setBindGroup(1,e.materialResource.bindGroup),!e.materialResource.graphTextureBindGroupLayout)throw new Error("Graph texture layout is missing.");u.setBindGroup(3,this.createGraphTextureBindGroup(e.material,e.materialResource.graphTextureBindGroupLayout));for(let i=0;i<e.indirectCount;i+=1)u.drawIndexedIndirect(t.indirectBuffer,20*(e.indirectStartIndex+i));const d=u.finish({label:`${r}-${o}`}),h={hash:this.getIndirectBundleHash(e,t,s),lastUsedExtractionVersion:this.extractionVersion,previous:null,next:null,streamKey:e.key,positionBuffer:e.geometryResource.position,indexBuffer:e.geometryResource.index,indirectBuffer:t.indirectBuffer,indirectStartIndex:e.indirectStartIndex,indirectCount:e.indirectCount,sampleCount:this.sampleCount,materialVersion:e.material.version,graphTextureResourceVersion:this.graphTextureResourceVersion,colorFormatsId:s,bundle:d};return i.add(h.hash,h,this.extractionVersion),this.setRetainedIndirectBundleState(e,h,t,s),d}submitIndirectStreamDirect(e,t,i){e.setPipeline(t.materialResource.pipeline),this.bindGeometryVertexBuffers(e,t.geometry,t.geometryResource,t.materialResource.vertexAttributes,0,1,t.material.wireframe),Fi(e,0,t.sceneBindGroup),e.setBindGroup(1,t.materialResource.bindGroup);const r=t.materialResource.graphTextureBindGroupLayout;if(!r)throw new Error("Graph texture layout is missing.");e.setBindGroup(3,this.createGraphTextureBindGroup(t.material,r));for(let r=0;r<t.indirectCount;r+=1)e.drawIndexedIndirect(i.indirectBuffer,20*(t.indirectStartIndex+r))}setRetainedIndirectBundleState(e,t,i,r){e.forwardBundleEntry=t,e.forwardBundleMaterialVersion=e.material.version,e.forwardBundleGraphTextureResourceVersion=this.graphTextureResourceVersion,e.forwardBundleInvalidationVersion=this.indirectBundleInvalidationVersion,e.forwardBundleDrawMetadataResource=i,e.forwardBundleSampleCount=this.sampleCount,e.forwardBundleColorFormatsId=r}getIndirectBundleHash(e,t,i){let r=2166136261;return r=Jr(r,e.key),r=Jr(r,Hr(e.geometryResource.position)),r=Jr(r,e.geometryResource.index?Hr(e.geometryResource.index):0),r=Jr(r,Hr(t.indirectBuffer)),r=Jr(r,e.indirectStartIndex),r=Jr(r,e.indirectCount),r=Jr(r,this.sampleCount),r=Jr(r,e.material.version),r=Jr(r,this.graphTextureResourceVersion),r=Jr(r,i),r>>>0}getColorFormatsId(e){if(e===ol)return 1;const t=this.colorFormatsIdentityCache.get(e);if(void 0!==t)return t;const i=1===e.length?e[0]:e.join("|");let r=this.colorFormatsValueCache.get(i);return void 0===r&&(r=this.nextColorFormatsId,this.nextColorFormatsId+=1,this.colorFormatsValueCache.set(i,r)),this.colorFormatsIdentityCache.set(e,r),r}getDirectForwardBundleKey(e,t,i){let r=2166136261;r=Jr(r,e.length),r=Jr(r,this.sampleCount),r=Jr(r,Hr(t));for(let n=0;n<e.length;n+=1){const a=e[n],s=this.getMaterialResourceForDraw(a,i),o=this.resolveSceneBindGroupForDraw(a,t);r=Jr(r,Hr(a.material)),r=Jr(r,a.receiveShadow?1:0),r=Jr(r,a.material.version??0),r=Jr(r,Hr(s.pipeline)),r=Jr(r,Hr(s.bindGroup)),r=Jr(r,Hr(o)),r=Jr(r,Hr(a.geometryKey)),r=Jr(r,Hr(a.geometryResource.position)),r=Jr(r,Hr(a.geometryResource.normal)),r=Jr(r,Hr(a.geometryResource.uv)),r=Jr(r,Hr(a.geometryResource.color)),r=Jr(r,a.geometryResource.index?Hr(a.geometryResource.index):0);for(const e of a.geometryResource.extraAttributeBuffers.values())r=Jr(r,Hr(e));r=Jr(r,a.indexed?1:0),r=Jr(r,a.start),r=Jr(r,a.count),r=Jr(r,a.instanceStart),r=Jr(r,a.instanceCount);const l=a.material.getTexturesList();r=Jr(r,l.length);for(let e=0;e<l.length;e+=1){const t=l[e];r=Jr(r,Hr(t)),r=Jr(r,t.version)}}return`forward-direct:${r}:${e.length}:samples=${this.sampleCount}:formats=${i.join("|")}`}clearSkinnedMaterialBundle(){this.skinnedMaterialBundle=null,this.skinnedMaterialBundleKey.length=0}skinnedMaterialBundleInputsStable(e,t,i){const r=this.skinnedMaterialBundleKeyScratch;r.push(this.sampleCount,this.getColorFormatsId(i));for(const n of e){const e=this.getMaterialResourceForDraw(n,i),a=this.prepareGeometryVertexBuffers(n.geometry,n.geometryResource,e.vertexAttributes,n.instanceStart,n.instanceCount),s=n.geometryResource;if(!e.graphTextureBindGroupLayout)throw new Error("Graph texture layout is missing.");r.push(e.pipeline,e.bindGroup,this.createGraphTextureBindGroup(n.material,e.graphTextureBindGroupLayout),this.resolveSceneBindGroupForDraw(n,t),e.usesSkinning?n.skinning?.bindGroup??null:null,n.wireframe?s.wireframeIndex:s.index,n.wireframe?s.wireframeIndexFormat:s.indexFormat,n.indexed,n.start,n.count,n.instanceStart,n.instanceCount,n.material.primitiveTopology,a.length);for(const e of a)r.push(e)}const n=this.skinnedMaterialBundleKey;return r.length!==n.length||r.some((e,t)=>e!==n[t])?(this.skinnedMaterialBundle=null,this.skinnedMaterialBundleKey=r,this.skinnedMaterialBundleKeyScratch=n,n.length=0,!1):(r.length=0,!0)}getOrCreateDirectForwardBundle(e,t,i,r=ol,n=!1){if(!this.state.device||!this.state.format||0===e.length)return null;if(n){if(!this.skinnedMaterialBundleInputsStable(e,t,r))return null;if(this.skinnedMaterialBundle)return i.drawCallCount+=this.skinnedMaterialBundleStats.drawCallCount,i.triangleCount+=this.skinnedMaterialBundleStats.triangleCount,this.skinnedMaterialBundle}const a=n?null:this.getDirectForwardBundleKey(e,t,r),s=null===a?"renderer-skinned-material-bundle":`renderer-direct-forward-bundle-${a}`,o=null===a?void 0:this.state.directForwardBundleCache.get(a);if(o){for(let t=0;t<e.length;t+=1){const r=e[t];r.materialResource&&this.updateMaterialUniformBuffer(r.material,r.materialResource),this.recordDraw(r,i)}return o}const l=this.state.device.createRenderBundleEncoder({label:s,colorFormats:r,depthStencilFormat:"depth32float",sampleCount:this.sampleCount});let c=null,u=null,d=null,h=null,p=null;const f=n?this.skinnedMaterialBundleStats:i;n&&(f.drawCallCount=f.triangleCount=0);for(let i=0;i<e.length;i+=1){const a=e[i],s=a.geometryResource,o=this.getMaterialResourceForDraw(a,r),m=this.resolveSceneBindGroupForDraw(a,t);if(c!==o.pipeline&&(c=o.pipeline,h=null,l.setPipeline(c)),(n||h!==a.geometryKey)&&(h=a.geometryKey,this.bindGeometryVertexBuffers(l,a.geometry,s,o.vertexAttributes,a.instanceStart,a.instanceCount,a.wireframe)),p!==m&&(p=m,Fi(l,0,m)),u!==a.material||d!==o){if(u=a.material,d=o,l.setBindGroup(1,o.bindGroup),!o.graphTextureBindGroupLayout)throw new Error("Graph texture layout is missing.");l.setBindGroup(3,this.createGraphTextureBindGroup(a.material,o.graphTextureBindGroupLayout))}o.usesSkinning&&a.skinning&&Fi(l,2,a.skinning.bindGroup),a.indexed&&(a.wireframe?s.wireframeIndex:s.index)?l.drawIndexed(a.count,a.instanceCount,a.start,0,a.instanceStart):l.draw(a.count,a.instanceCount,a.start,a.instanceStart),this.recordDraw(a,f)}const m=l.finish({label:s});return null===a?(this.skinnedMaterialBundle=m,i.drawCallCount+=f.drawCallCount,i.triangleCount+=f.triangleCount):this.state.directForwardBundleCache.set(a,m),m}getOrCreateStaticMaterialBundle(e,t,i,r){const n=`${Hr(t)}:${this.sampleCount}:${r.join("|")}`,a=this.materialPassStaticBundleCache.get(e)?.get(n);if(a)return this.recordStaticDrawStats(e,i),a;const s=this.getOrCreateDirectForwardBundle(e.draws,t,i,r);if(!s)return null;let o=this.materialPassStaticBundleCache.get(e);return o||(o=new Map,this.materialPassStaticBundleCache.set(e,o)),o.set(n,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 i=e.residentInstanceBinding,r=i.buffer,n=i.colorBuffer??i.buffer;return r&&n?(i.sceneBindGroup&&i.sceneBindGroupVersion===this.state.residentSceneBindGroupVersion||(i.sceneBindGroup=this.state.device.createBindGroup("instanced-direct"===i.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:r}},{binding:3,resource:{buffer:n}},{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},{binding:10,resource:this.state.spotLightMapView},{binding:11,resource:this.tiledPointLights.view}]}:{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:r}},{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:9,resource:this.state.spotLightMapView},{binding:11,resource:this.tiledPointLights.view}]}),i.sceneBindGroupVersion=this.state.residentSceneBindGroupVersion),i.sceneBindGroup):t}resolveShadowBindGroupForDraw(e,t,i=this.state.shadowCameraBuffer){if(!(e.residentInstanceBinding&&this.state.device&&this.state.shadowBindGroupLayout&&this.state.directShadowBindGroupLayout&&i&&e.residentInstanceBinding.buffer))return t;const r=e.residentInstanceBinding,n=r.buffer,a=r.colorBuffer??r.buffer;if(!n||!a)return t;if(r.shadowBindGroupVersion!==this.state.residentShadowBindGroupVersion&&(r.shadowBindGroup=null,r.shadowBindGroups.clear(),r.shadowBindGroupVersion=this.state.residentShadowBindGroupVersion),i===this.state.shadowCameraBuffer&&r.shadowBindGroup)return r.shadowBindGroup;const s=r.shadowBindGroups.get(i);if(s)return s;const o=this.state.device.createBindGroup("instanced-direct"===r.mode?{label:"renderer-resident-direct-shadow-bind-group",layout:this.state.directShadowBindGroupLayout,entries:[{binding:0,resource:{buffer:i}},{binding:1,resource:{buffer:n}},{binding:2,resource:{buffer:a}}]}:{label:"renderer-resident-shadow-bind-group",layout:this.state.shadowBindGroupLayout,entries:[{binding:0,resource:{buffer:i}},{binding:1,resource:{buffer:n}}]});return r.shadowBindGroups.set(i,o),i===this.state.shadowCameraBuffer&&(r.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*M;this.drawMetadataUpload.length<t&&(this.drawMetadataUpload=new Float32Array(Math.max(t,2*this.drawMetadataUpload.length,768)));const i=5*e.length;this.indirectDrawUpload.length<i&&(this.indirectDrawUpload=new Uint32Array(Math.max(i,2*this.indirectDrawUpload.length,320)));const r=this.drawMetadataUpload,n=this.indirectDrawUpload;for(let t=0;t<e.length;t+=1){const i=e[t],a=t*M;r[a+0]=i.boundsCenter.x,r[a+1]=i.boundsCenter.y,r[a+2]=i.boundsCenter.z,r[a+3]=i.boundsRadius,r[a+4]=i.count,r[a+5]=i.start,r[a+6]=i.instanceStart,r[a+7]=i.instanceCount,r[a+8]=1,r[a+9]=0,r[a+10]=0,r[a+11]=0;const s=5*t;n[s+0]=i.count,n[s+1]=i.instanceCount,n[s+2]=i.start,n[s+3]=0,n[s+4]=i.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*M*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,r,0,t),this.state.device.queue.writeBuffer(this.state.drawMetadataResource.indirectBuffer,0,n,0,i),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+=mn(e)}executeVisibilityPass(e,t){Js.call(this,e,t)}executeStaticVisibilityPasses(e,t){to.call(this,e,t)}getOrCreateStaticVisibilityBindGroup(e,t){return io.call(this,e,t)}executeDirectionalShadowPass(e,t,i,r){ro.call(this,e,t,i,r)}executePointShadowPass(e,t,i,r){ao.call(this,e,t,i,r)}executeSpotShadowPass(e,t,i,r){so.call(this,e,t,i,r)}executeDepthPrepass(e,t,i,r){lo.call(this,e,t,i,r)}clearDynamicDepthBundles(){this.skinnedDepthBundleCache.bundle=null,this.skinnedDepthBundleCache.key.length=0,this.directionalDepthBundleCaches=new WeakMap}tryExecuteDynamicDepthBundle(e,t,i,r,n){const a=void 0!==n,s=this.state,o=a?s.shadowDepthPipeline:s.depthPrepassPipeline,l=a?s.shadowDepthPipelineDirect:s.depthPrepassPipelineDirect,c=a?s.skinnedShadowDepthPipeline:s.skinnedDepthPrepassPipeline;let u=a?this.directionalDepthBundleCaches.get(n):this.skinnedDepthBundleCache;if(!s.device||!o||(a?0===t.length:!c||!t.some(e=>null!==e.skinning))||Xr(t))return u&&(u.bundle=null,u.key.length=0),!1;u||(u={bundle:null,key:[],scratch:[],stats:{drawCallCount:0,triangleCount:0}},this.directionalDepthBundleCaches.set(n,u));const d=a?"directionalShadow":"prepass",h=u.scratch;h.length=0;for(const e of t){if(!a&&e.customDepthMaterial)continue;const t=e.material,r=(a?e.customDepthMaterial:null)??(null!==t.depthVertexShader?t:null),s=r?this.getDepthPassMaterialResourceForDraw(r,d,e):null;if(!s&&(e.wireframe||!t.primitiveTopology.startsWith("triangle")||!a&&null===t.depthVertexShader&&Us(t)))continue;const u=e.geometryResource,p=e.skinning,f=s?.pipeline??(p&&c?c:"instanced-direct"===this.getDrawInstanceAccessMode(e)?l??o:o),m=s?.vertexAttributes??(p?L:z),g=this.prepareGeometryVertexBuffers(e.geometry,u,m,e.instanceStart,e.instanceCount),v=e.wireframe?u.wireframeIndex:u.index,x=a?this.resolveShadowBindGroupForDraw(e,i,n):this.resolveSceneBindGroupForDraw(e,i);h.push(f,x,s?.bindGroup??null,s?.usesSkinning??p?p?.bindGroup??null:null,e.indexed,v,e.wireframe?u.wireframeIndexFormat:u.indexFormat,e.start,e.count,e.instanceStart,e.instanceCount,t.primitiveTopology,g.length);for(const e of g)h.push(e)}const p=u.key;if(!h.length||h.length!==p.length||h.some((e,t)=>e!==p[t]))return u.bundle=null,u.key=h,u.scratch=p,p.length=0,!1;h.length=0;const f=u.stats;if(!u.bundle){const e=a?"renderer-dynamic-directional-shadow-bundle":"renderer-skinned-depth-prepass-bundle",r=s.device.createRenderBundleEncoder({label:e,colorFormats:[],depthStencilFormat:"depth32float"});f.drawCallCount=f.triangleCount=0,this.drawDepthLike(r,t,f,{fallbackPipeline:o,fallbackPipelineDirect:l,fallbackSkinnedPipeline:c,fallbackBindGroup:i,shadowCameraBuffer:n,passKind:d,customDepthMode:a?"use":"skip",preculled:a}),u.bundle=r.finish({label:e})}const m=this.renderBundleScratch;return m[0]=u.bundle,ji(e,m),m.length=0,r.drawCallCount+=f.drawCallCount,r.triangleCount+=f.triangleCount,!0}executeStaticDepthPrepass(e,t,i){co.call(this,e,t,i)}executeStaticTemporalDepthResolvePass(e){ho.call(this,e)}getOrCreateStaticDepthPrepassBundle(e,t){return fo.call(this,e,t)}executeHiZPasses(e,t=!1,i=!1){vo.call(this,e,t,i)}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&&this.state.spotLightMapView))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}},{binding:9,resource:this.state.spotLightMapView},{binding:11,resource:this.tiledPointLights.view}]}),e.visibleSceneBindGroupVersion=this.state.residentSceneBindGroupVersion),e.visibleSceneBindGroup}getOrCreateStaticVisibleDepthSceneBindGroup(e){if(!(this.state.device&&this.state.visibleDepthSceneBindGroupLayout&&this.state.cameraBuffer&&this.state.lightBuffer))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:1,resource:{buffer:this.state.lightBuffer}},{binding:2,resource:{buffer:e.instanceBuffer}},{binding:3,resource:{buffer:e.instanceVisibilityResource.visibleInstanceIndicesBuffer}}]}),e.visibleDepthSceneBindGroupVersion=this.state.residentSceneBindGroupVersion),e.visibleDepthSceneBindGroup}executeMaterialPass(e,t,i,r,n,a={},s){if(!this.state.mainDepthView||0===t.length)return;const o=t.map(e=>this.getColorTargetFormat(e)),l=this.getColorFormatsId(o),c=t.map(e=>s?.colorView??this.getColorTargetView(e)),u=!s&&this.sampleCount>1,d=u?t.map(e=>this.ensureMsaaColorTarget(e)):[],h=this.getColorTargetDimensions(t[0]),p=u?this.ensureMsaaDepthTarget(h.width,h.height):null,f=e.beginRenderPass({label:"renderer-material-pass",colorAttachments:t.map((e,t)=>({view:d[t]?.view??c[t],resolveTarget:d[t]?c[t]:void 0,clearValue:1===t?{r:.5,g:.5,b:1,a:1}:t>=2?{r:0,g:0,b:0,a:1}:{r:a.clearColor?.[0]??this.clearColor[0],g:a.clearColor?.[1]??this.clearColor[1],b:a.clearColor?.[2]??this.clearColor[2],a:a.clearColor?.[3]??this.clearColor[3]},loadOp:a.loadColor?"load":"clear",storeOp:d[t]?"discard":"store"})),depthStencilAttachment:{view:s?.depthView??p?.view??this.state.mainDepthView,depthClearValue:1,depthLoadOp:p?"clear":a.loadDepth?"load":"clear",depthStoreOp:p?"discard":"store"}});let m=null,g=null,v=null,x=null,w=null;const b=e=>{e.sourceObject&&e.hasRenderCallbacks&&e.sourceObject.onBeforeRender(this,r.scene,r.camera,e.geometry,e.material,e.geometryGroup);const t=e.geometryResource;let a=e.material;const l=this.getMaterialResourceForDraw(e,o,s?1:this.sampleCount),c=this.resolveSceneBindGroupForDraw(e,i);if(m!==l.pipeline&&(m=l.pipeline,v=null,w=null,f.setPipeline(m)),v!==e.geometryKey&&(v=e.geometryKey,this.bindGeometryVertexBuffers(f,e.geometry,t,l.vertexAttributes,e.instanceStart,e.instanceCount,e.wireframe)),x!==c&&(x=c,Fi(f,0,c)),g!==a){if(g=a,f.setBindGroup(1,l.bindGroup),!l.graphTextureBindGroupLayout)throw new Error("Graph texture layout is missing.");f.setBindGroup(3,this.createGraphTextureBindGroup(a,l.graphTextureBindGroupLayout))}l.usesSkinning&&e.skinning&&w!==e.skinning.bindGroup&&(w=e.skinning.bindGroup,Fi(f,2,w)),e.indexed&&(e.wireframe?t.wireframeIndex:t.index)?f.drawIndexed(e.count,e.instanceCount,e.start,0,e.instanceStart):f.draw(e.count,e.instanceCount,e.start,e.instanceStart),this.recordDraw(e,n),e.sourceObject&&e.hasRenderCallbacks&&e.sourceObject.onAfterRender(this,r.scene,r.camera,e.geometry,e.material,e.geometryGroup)},y=a.drawStage??"all";if(a.objectFilter||a.overrideMaterial){const e=e=>{if(s){if(!this.isSphereVisibleScratch(e.boundsCenter.x,e.boundsCenter.y,e.boundsCenter.z,e.boundsRadius,!0))return;if(e.material.requiresLatePass())return;this.prepareDrawGeometryVertexBuffers(e),e={...e,receiveShadow:!1,materialResource:null}}if(a.objectFilter){const t=e.sourceRanges?.filter(e=>a.objectFilter(e.sourceObject));if(0===t?.length)return;if(null!=t&&t.length<e.sourceRanges.length){const i="function"==typeof a.overrideMaterial?a.overrideMaterial(e.material,null!==e.skinning):a.overrideMaterial;if(null===i)return;for(const r of t)b({...e,sourceObject:r.sourceObject,instanceStart:r.instanceStart,instanceCount:r.instanceCount,material:i??e.material,sourceRanges:void 0});return}if(null==t&&!a.objectFilter(e.sourceObject))return}const t="function"==typeof a.overrideMaterial?a.overrideMaterial(e.material,null!==e.skinning):a.overrideMaterial;null!==t&&b(t?{...e,material:t}:e)};if("late"!==y){for(const t of this.getCameraStaticDrawSets())if(t.publicSet.enabled&&"opaque"===t.drawStage)for(const i of t.draws)e(i);for(const t of r.gpuOpaqueDraws)e(t);for(const t of r.directOpaqueDraws)e(t)}if("opaque"!==y){if(s)for(const t of this.staticDrawSets)if(t.publicSet.enabled&&"late"===t.drawStage)for(const i of t.draws)e(i);for(const t of r.transparentDraws)e(t)}return void f.end()}if("late"!==y){const e=this.renderBundleScratch;e.length=0;for(const t of this.getCameraStaticDrawSets()){if(!t.publicSet.enabled||!this.isStaticDrawSetCameraVisible(t)||0===t.draws.length||"opaque"!==t.drawStage)continue;if(this.getHiZOcclusionCullingActive()&&t.lastVisibilityFrameToken===this.staticFrameToken){const i=this.getOrCreateStaticVisibleSceneBindGroup(t),r=this.getOrCreateStaticIndirectSubmissionStreams(t,i,o);for(const i of r){if(this.getMultiDrawIndirectActive()){if(e.length&&(ji(f,e),e.length=0),f.setPipeline(i.materialResource.pipeline),this.bindGeometryVertexBuffers(f,i.geometry,i.geometryResource,i.materialResource.vertexAttributes,0,1,i.material.wireframe),Fi(f,0,i.sceneBindGroup),f.setBindGroup(1,i.materialResource.bindGroup),!i.materialResource.graphTextureBindGroupLayout)throw new Error("Graph texture layout is missing.");f.setBindGroup(3,this.createGraphTextureBindGroup(i.material,i.materialResource.graphTextureBindGroupLayout)),f.multiDrawIndexedIndirect(t.drawMetadataResource.indirectBuffer,5*i.indirectStartIndex*Uint32Array.BYTES_PER_ELEMENT,i.indirectCount)}else e.push(this.getOrCreateIndirectForwardBundle(i,t.drawMetadataResource,t.indirectForwardBundleCache,`${t.label}-static-indirect-material-bundle`,o,!1,l));n.drawCallCount+=i.drawCallCount,n.triangleCount+=i.triangleCount}continue}const r=this.getOrCreateStaticMaterialBundle(t,i,n,o);r&&e.push(r)}if(e.length&&ji(f,e),e.length=0,this.getHiZOcclusionCullingActive()&&this.state.drawMetadataResource){const e=this.indirectMaterialResourcesScratch;e.length=r.gpuOpaqueDraws.length;for(let t=0;t<r.gpuOpaqueDraws.length;t+=1)e[t]=this.getMaterialResourceForDraw(r.gpuOpaqueDraws[t],o);const t=this.buildIndirectSubmissionStreams(r.gpuOpaqueDraws,i,void 0,e);for(const e of t){const t=this.getOrCreateIndirectForwardBundle(e,this.state.drawMetadataResource,this.state.indirectForwardBundleCache,"renderer-indirect-material-bundle",o,!0,l);t?(this.renderBundleScratch[0]=t,ji(f,this.renderBundleScratch)):this.submitIndirectStreamDirect(f,e,this.state.drawMetadataResource),n.drawCallCount+=e.drawCallCount,n.triangleCount+=e.triangleCount}}else{const e=Xr(r.gpuOpaqueDraws)||r.gpuOpaqueDraws.some(e=>null!==e.skinning)?null:this.getOrCreateDirectForwardBundle(r.gpuOpaqueDraws,i,n,o);if(e)this.renderBundleScratch[0]=e,ji(f,this.renderBundleScratch);else for(const e of r.gpuOpaqueDraws)b(e)}const t=r.directOpaqueDraws.some(e=>null!==e.skinning),a=!s&&!Xr(r.directOpaqueDraws);t&&a||this.clearSkinnedMaterialBundle();const c=a?this.getOrCreateDirectForwardBundle(r.directOpaqueDraws,i,n,o,t):null;if(c)this.renderBundleScratch[0]=c,ji(f,this.renderBundleScratch),m=g=v=x=w=null;else for(const e of r.directOpaqueDraws)b(e)}if("opaque"!==y)for(const e of r.transparentDraws)b(e);f.end()}executeForwardPass(e,t,i,r,n,a,s=!1,o="all",l=!1,c=this.sampleCount){xo.call(this,e,t,i,r,n,a,s,o,l,c)}executeStaticForwardPass(e,t,i,r="all",n=this.sampleCount){wo.call(this,e,t,i,r,n)}getOrCreateStaticDirectForwardBundle(e,t,i=this.sampleCount){return bo.call(this,e,t,i)}refreshStaticDrawMaterialResources(e){So.call(this,e)}syncStaticVisibleMaterialBindingCaches(e){yo.call(this,e)}recordStaticDrawStats(e,t){Co.call(this,e,t)}hasEnabledStaticDrawSets(){return Mo.call(this)}executePresentPass(e,t,i){Po.call(this,e,t,i)}clearDirectionalShadow(e){Bo.call(this,e)}clearPointShadow(e){Do.call(this,e)}clearSpotShadow(e){Io.call(this,e)}drawDepthLike(e,t,i,r){Ro.call(this,e,t,i,r)}getGeometryResource(e,t=!1){if(!this.state.device)throw new Error("Renderer is not initialized.");const i=this.geometryCache.get(e);if((t||!this.invokeObjectRenderCallbacks)&&i&&i.lastValidatedExtractionVersion===this.extractionVersion)return i;if(i&&this.refreshGeometryResource(e,i))return i.lastValidatedExtractionVersion=this.extractionVersion,i;if(i&&i.lastValidatedExtractionVersion===this.extractionVersion)return i;i&&(this.clearIndirectBundleCache(),this.retireGeometryResource(i));const r=e.getAttribute("position");if(!r)throw new Error("BufferGeometry is missing the required position attribute.");const n=r.count,a=Ur(r,n,3,[0,0,0]),s=Ur(e.getAttribute("normal"),n,3,[0,0,1]),o=Ur(e.getAttribute("uv"),n,2,[0,0]),l=Ur(e.getAttribute("color"),n,4,[1,1,1,1]),c=e.getAttribute("skinIndex"),u=e.getAttribute("skinWeight"),d=c?kr(c,n,"uint32x4",[]):void 0,h=u?kr(u,n,"float32x4",[]):void 0,p={signature:Cr(e),indexSource:e.index,indexVersion:e.index?.version??0,drawRangeStart:e.drawRange.start,drawRangeCount:e.drawRange.count,vertexCount:n,attributes:["position","normal","uv","color",...c?["skinIndex"]:[],...u?["skinWeight"]:[]].map(t=>{const i=e.getAttribute(t);return{name:t,source:i,version:Sr(i),itemSize:i?.itemSize??0,count:i?.count??0}}),lastValidatedExtractionVersion:this.extractionVersion,groups:e.groups.map(e=>({start:e.start,count:e.count,materialIndex:e.materialIndex??0})),...this.createGeometryBuffers(e.uuid,a,s,o,l,d,h,e.index?.array),extraAttributeBuffers:new Map,extraAttributeBufferVersions:new Map,wireframeIndex:null,wireframeIndexFormat:null};return this.geometryCache.set(e,p),p}refreshGeometryResource(e,t){if(!this.state.device)return!1;let i=!1;for(const r of t.attributes){const t=e.getAttribute(r.name),n=t?.itemSize??0,a=t?.count??0;if(n!==r.itemSize||a!==r.count)return!1;i||=t!==r.source||Sr(t)!==r.version}if(!function(e,t){if(t.indexSource!==e.index||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 i=0;i<t.groups.length;i+=1){const r=t.groups[i],n=e.groups[i];if(r.start!==n?.start||r.count!==n?.count||r.materialIndex!==(n?.materialIndex??0))return!1}return!0}(e,t))return!1;if(!i)return!0;const r={position:{buffer:t.position,format:"float32x3",defaults:[0,0,0]},normal:{buffer:t.normal,format:"float32x3",defaults:[0,0,1]},uv:{buffer:t.uv,format:"float32x2",defaults:[0,0]},color:{buffer:t.color,format:"float32x4",defaults:[1,1,1,1]},skinIndex:{buffer:t.skinIndex,format:"uint32x4",defaults:[0,0,0,0]},skinWeight:{buffer:t.skinWeight,format:"float32x4",defaults:[0,0,0,0]}};for(const i of t.attributes){const t=e.getAttribute(i.name),n=Sr(t),a=t!==i.source;if(!a&&n===i.version)continue;const s=r[i.name];if(!t||!s?.buffer)return!1;const o=Number(s.format.at(-1)),l=!a&&"updateRanges"in t&&t.updateRanges.length>0?t.updateRanges:[{start:0,count:t.count*t.itemSize}];for(const e of l){const i=Math.max(0,Math.floor(e.start/t.itemSize)),r=Math.min(t.count,Math.ceil((e.start+e.count)/t.itemSize));if(r<=i)continue;if(t instanceof oa&&!t.normalized&&t.itemSize===o&&("uint32x4"===s.format&&t.array instanceof Uint32Array||"uint32x4"!==s.format&&t.array instanceof Float32Array)){this.state.device.queue.writeBuffer(s.buffer,i*o*4,t.array.buffer,t.array.byteOffset+i*o*4,(r-i)*o*4);continue}const n="uint32x4"===s.format?new Uint32Array((r-i)*o):new Float32Array((r-i)*o);for(let e=i;e<r;e++){const r=(e-i)*o;for(let i=0;i<o;i++){const a=0===i?t.getX(e):1===i&&t.itemSize>1?t.getY(e):2===i&&t.itemSize>2?t.getZ(e):3===i&&t.itemSize>3?t.getW(e):void 0;n[r+i]=a??s.defaults[i]??0}}this.state.device.queue.writeBuffer(s.buffer,i*o*4,n)}"clearUpdateRanges"in t&&t.clearUpdateRanges(),i.version=n,i.source=t}return t.signature=Cr(e),!0}getSkinnedGeometryResource(e,t=!1){if(!this.state.device)throw new Error("Renderer is not initialized.");const i=e.geometry.getAttribute("skinIndex"),r=e.geometry.getAttribute("skinWeight"),n=e.geometry.getAttribute("position");if(!i||!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 a=this.getGeometryResource(e.geometry,t);let s=this.skinnedGeometryCache.get(e);if(!s||s.resource!==a||s.positionAttribute!==n||s.positionVersion!==Sr(n)||s.skinIndexAttribute!==i||s.skinIndexVersion!==Sr(i)||s.skinWeightAttribute!==r||s.skinWeightVersion!==Sr(r)||s.boneCount!==e.skeleton.bones.length||s.skinning.palette.skeleton!==e.skeleton){s&&(s.skinning.releaseInstance(),s.skinning.bindUniformBuffer.destroy());const t=this.getSkinningPalette(e.skeleton),o=this.state.device.createBuffer({label:`${e.uuid}-skinning-bind-matrices`,size:64*Float32Array.BYTES_PER_ELEMENT,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),l=new Float32Array(64);l.set(e.bindMatrix.elements,0),l.set(e.bindMatrixInverse.elements,16),l.copyWithin(32,0,32);const c={releaseInstance:bn(e,()=>this.releaseSkinnedMeshResources(e)),bindGroup:this.state.device.createBindGroup({label:`${e.uuid}-skinning-bind-group`,layout:this.state.skinningBindGroupLayout,entries:[{binding:0,resource:t.allocation.currentBinding},{binding:1,resource:{buffer:o}},{binding:2,resource:t.allocation.previousBinding}]}),bindUniformBuffer:o,bindMatrices:l,bindMatrixHistory:new Float32Array(32),lastBindRefreshExtractionVersion:-1,palette:t,bindUniformDirty:!0},u={positionAttribute:n,positionVersion:Sr(n),skinIndexAttribute:i,skinIndexVersion:Sr(i),skinWeightAttribute:r,skinWeightVersion:Sr(r),boneCount:e.skeleton.bones.length,resource:a,skinning:c,boneBounds:this.createSkinningBoneBounds(e,n,i,r),localBoundsMin:new Ca,localBoundsMax:new Ca,localBoundsCenter:new Ca,localBoundsRadius:1};s=u,this.skinnedGeometryCache.set(e,u)}if(!s)throw new Error("Skinned geometry cache entry could not be created.");return s}getSkinningPalette(e){const t=this.skinPaletteCache.get(e);if(t&&t.previousMatrices.length===16*e.bones.length)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 i=16*e.bones.length;t&&(t.releaseExternal?.(),this.skinningPaletteArena.release(t.allocation),t.standaloneBuffer?.destroy(),this.skinPaletteResources.delete(t)),e.boneMatrices.length<i&&(e.boneMatrices=new Float32Array(i)),this.skeletonPalettes.update(e);const r=new Float32Array(i);for(let t=0;t<i;t++)r[t]=e.boneMatrices[t];const n=(this.skinningPaletteArena??=new ea(this.state.device)).allocate(e.bones.length),a={skeleton:e,allocation:n,standaloneDirty:!0,matrixBuffer:n.page.current,previousMatrixBuffer:n.page.previous,previousMatrices:r,dirty:!0,previousDirty:!0,previousNeedsAdvance:!1,lastRefreshExtractionVersion:-1};this.skinPaletteCache.set(e,a),this.skinPaletteResources.add(a);const s=qi(e);return s&&(a.releaseExternal=function(e,t){let i=Ni.get(e);return i||(i=new Set,Ni.set(e,i)),i.add(t),()=>i.delete(t)}(s,()=>this.releaseSkinningPalette(a))),a}releaseSkinningPalette(e){if(this.skinPaletteResources.delete(e)){e.releaseExternal?.(),this.skinningPaletteArena.release(e.allocation),e.standaloneBuffer?.destroy(),this.skinPaletteCache.delete(e.skeleton);for(const[t,i]of this.skinnedGeometryCache)i.skinning.palette===e&&(this.releaseSkinnedRenderRecord(t),this.skinnedGeometryCache.delete(t)&&(i.skinning.releaseInstance(),i.skinning.bindUniformBuffer.destroy()))}}refreshSkinningPalette(e){if(null!==this.sceneCaptureOptions)return;if(e.lastRefreshExtractionVersion===this.extractionVersion)return;e.lastRefreshExtractionVersion=this.extractionVersion;const t=this.skeletonPalettes.update(e.skeleton);e.dirty||=t,e.standaloneDirty||=t,e.previousDirty||=t||e.previousNeedsAdvance,e.previousNeedsAdvance=t}refreshSkinningBindMatrices(e,t){const i=t.bindMatrices,r=null===this.sceneCaptureOptions&&t.lastBindRefreshExtractionVersion!==this.extractionVersion,n=t.lastBindRefreshExtractionVersion>=0,a=qi(e.skeleton),s=a?U.copy(e.matrixWorld).invert().multiply(a.root.matrixWorld).elements:e.bindMatrixInverse.elements;let o=!1;for(let a=0;a<16;a+=1){const l=Math.fround(e.bindMatrix.elements[a]),c=Math.fround(s[a]);if(i[a]===l&&i[a+16]===c||(o=!0),i[a]=l,i[a+16]=c,r){const e=n?t.bindMatrixHistory[a]:l,r=n?t.bindMatrixHistory[a+16]:c;o||=i[a+32]!==e||i[a+48]!==r,i[a+32]=e,i[a+48]=r,t.bindMatrixHistory[a]=l,t.bindMatrixHistory[a+16]=c}}r&&(t.lastBindRefreshExtractionVersion=this.extractionVersion),t.bindUniformDirty||=o}uploadSkinningPalette(e,t=!1){if(!this.state.device)return;const i=this.skinningPaletteArena;if(e.previousDirty&&(i.stage(e.allocation,e.previousMatrices,!0),e.previousDirty=!1),e.dirty){const t=e.skeleton.boneMatrices;i.stage(e.allocation,t,!1);const r=e.previousMatrices;if(t.length===r.length)r.set(t);else for(let e=0;e<r.length;e++)r[e]=t[e];e.dirty=!1}t||i.flush()}uploadSkinningResources(e){this.state.device&&(this.uploadSkinningPalette(e.palette,!0),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,i,r){const n=Array.from({length:e.skeleton.bones.length},()=>new Ca(1/0,1/0,1/0)),a=Array.from({length:e.skeleton.bones.length},()=>new Ca(-1/0,-1/0,-1/0));for(let e=0;e<t.count;e+=1){F.set(t.getX(e),t.getY(e),t.getZ(e));for(let t=0;t<4;t+=1){if(r.getComponent(e,t)<=0)continue;const s=Math.round(i.getComponent(e,t)),o=n[s],l=a[s];o&&l&&(o.min(F),l.max(F))}}return n.map((e,t)=>{if(!Number.isFinite(e.x))return null;const i=a[t],r=e.clone().add(i).multiplyScalar(.5);return{center:r,radius:i.distanceTo(r)}})}updateSkinnedBounds(e,t){const i=t.localBoundsMin,r=t.localBoundsMax,n=qi(e.skeleton),a=n?U.copy(e.matrixWorld).invert().multiply(n.root.matrixWorld):e.bindMatrixInverse,s=dn(e.geometry);i.set(s.center.x-s.radius,s.center.y-s.radius,s.center.z-s.radius),r.set(s.center.x+s.radius,s.center.y+s.radius,s.center.z+s.radius);for(let n=0;n<t.boneBounds.length;n+=1){const s=t.boneBounds[n];if(!s)continue;const o=pn(s.center,s.radius,e.bindMatrix,t.skinning.palette.skeleton.boneMatrices,16*n,a,F);i.min(O.copy(F).addScalar(-o)),r.max(O.copy(F).addScalar(o))}t.localBoundsCenter.copy(i).add(r).multiplyScalar(.5),t.localBoundsRadius=r.distanceTo(t.localBoundsCenter)}createGeometryBuffers(e,t,i,r,n,a,s,o,l=GPUBufferUsage.VERTEX,c=GPUBufferUsage.VERTEX){if(!this.state.device)throw new Error("Renderer is not initialized.");let u=null,d=null;if(o){const t=o instanceof Uint32Array?o:new Uint16Array(o);d=o instanceof Uint32Array?"uint32":"uint16",u=Rr(this.state.device,t,GPUBufferUsage.INDEX,`${e}-index`)}return{position:Rr(this.state.device,t,l|GPUBufferUsage.COPY_DST,`${e}-position`),normal:Rr(this.state.device,i,c|GPUBufferUsage.COPY_DST,`${e}-normal`),uv:Rr(this.state.device,r,GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST,`${e}-uv`),color:Rr(this.state.device,n,GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST,`${e}-color`),skinIndex:a?Rr(this.state.device,a,GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST,`${e}-skin-index`):null,skinWeight:s?Rr(this.state.device,s,GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST,`${e}-skin-weight`):null,index:u,indexFormat:d}}createVertexBufferLayouts(e){return this.getVertexAttributeGroups(e).map(e=>{let t=0;const i=e.map(e=>{const i={shaderLocation:e.shaderLocation,offset:t,format:e.format};return t+=4*Mr(e.format),i});return{arrayStride:t,stepMode:e[0].stepMode??"vertex",attributes:i}})}getVertexAttributeGroups(e){const t=this.vertexAttributeGroupCache.get(e);if(t)return t;const i=this.state.device?.limits.maxVertexBuffers??8;if(e.length<=i){const t=e.map(e=>[e]);return this.vertexAttributeGroupCache.set(e,t),t}let r=e.length-i;const n=[],a=new Set;for(const t of["vertex","instance"]){if(0===r)break;const i=e.filter(e=>(e.stepMode??"vertex")===t),s=Math.min(i.length,r+1);if(s<2)continue;const o=i.slice(0,s);n.push(o);for(const e of o)a.add(e);r-=s-1}if(r>0)throw new Error(`Vertex attributes cannot be packed into the device's ${i} vertex-buffer slots.`);const s=[];for(const t of e){if(!a.has(t)){s.push([t]);continue}const e=n.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 i=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,i),i}getGeometryAttributeGroupBufferKey(e){const t=this.vertexAttributeGroupBufferKeyCache.get(e);if(void 0!==t)return t;const i=e.map(e=>this.getGeometryAttributeBufferKey(e)).join("|");return this.vertexAttributeGroupBufferKeyCache.set(e,i),i}getMaterialVertexAttributes(e,t){let i=this.materialVertexAttributeCache.get(e);if(i&&i.version===e.version||(i={version:e.version,unskinned:this.getSharedVertexAttributeLayout(e.vertexAttributes)},this.materialVertexAttributeCache.set(e,i)),!t)return i.unskinned;if(i.skinned)return i.skinned;const r=i.unskinned.slice(),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 i=r.find(t=>t.shaderLocation===e.shaderLocation);if(i)throw new Error(`Skinned material requires location ${e.shaderLocation} for "${e.name}", but it is used by "${i.name}".`);r.push(e)}return i.skinned=this.getSharedVertexAttributeLayout(r),i.skinned}getSharedVertexAttributeLayout(e){const t=JSON.stringify(e.map(e=>[e.name,e.shaderLocation,e.format,e.stepMode??"vertex",e.defaultValue??null]));let i=this.sharedVertexAttributeLayouts.get(t);return i||(i=e.map(e=>({...e,defaultValue:e.defaultValue?.slice()})),this.sharedVertexAttributeLayouts.set(t,i)),i}getGeometryVertexBuffer(e,t,i,r=0,n=1){if(!this.state.device)throw new Error("Renderer is not initialized.");const a=this.getStandardVertexAttribute(i);if(a){const e=t[a];if(e)return e}const s=e.getAttribute(i.name),o="instance"===i.stepMode,l=o?Math.max(0,Math.trunc(r)):0;if(!s&&(o||i.defaultValue)){const e=this.getDefaultVertexAttributeBuffer(i,o?l+Math.max(1,n):t.vertexCount);return this.cacheGeometryVertexBufferFast(t,i,l,void 0,0,e),e}const c=Sr(s),u=this.geometryVertexBufferFastCache.get(t),d=u?.get(i),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(i)}${o?`:instance-start=${l}`:""}`,f=s?`${c}:${s.itemSize}:${s.count}`:"default",m=t.extraAttributeBuffers.get(p);if(m&&h?.source===s&&t.extraAttributeBufferVersions.get(p)===f)return this.cacheGeometryVertexBufferFast(t,i,l,s,c,m),m;if(!s&&!i.defaultValue)throw new Error(`Geometry "${e.uuid}" is missing required vertex attribute "${i.name}".`);const g=kr(s,o?l+Math.max(1,s?.count??1,n):t.vertexCount,i.format,i.defaultValue??[],o?l:0,h?.staging);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,i,l,s,c,m,g),m;const v=Rr(this.state.device,g,GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST,`${e.uuid}-${i.name}-${i.format}`);return m&&(this.clearIndirectBundleCache(),this.retiredGeometryBuffers.push(m)),t.extraAttributeBuffers.set(p,v),t.extraAttributeBufferVersions.set(p,f),this.cacheGeometryVertexBufferFast(t,i,l,s,c,v,g),v}cacheGeometryVertexBufferFast(e,t,i,r,n,a,s){let o=this.geometryVertexBufferFastCache.get(e);o||(o=new WeakMap,this.geometryVertexBufferFastCache.set(e,o));let l=o.get(t);l||(l=new Map,o.set(t,l));const c=r,u=l.get(i);u&&u.buffer!==a&&this.clearIndirectBundleCache(),l.set(i,{source:r,version:n,itemSize:c?.itemSize??0,count:c?.count??0,buffer:a,staging:s&&s.buffer!==(c?.array??c?.data?.array)?.buffer?s:void 0})}packedVertexGroups=new WeakMap;getInterleavedGeometryVertexBuffer(e,t,i,r,n){if(!this.state.device)throw new Error("Renderer is not initialized.");const a=i[0].stepMode??"vertex",s="instance"===a?Math.max(0,Math.trunc(r)):0,o=`interleaved:${this.getGeometryAttributeGroupBufferKey(i)}:instance-start=${s}`;let l=this.packedVertexGroups.get(t);l||(l=new Map,this.packedVertexGroups.set(t,l));let c=l.get(o);c||(c=new Bn(i),l.set(o,c));const u=c.update(e,t.vertexCount,s,n,"instance"===a?this.getInstanceVertexCapacity():0),d=t.extraAttributeBuffers.get(o);if(!u&&d)return d;const h=c.data;if(d&&d.size>=Math.max(4,h.byteLength))return this.state.device.queue.writeBuffer(d,0,h.buffer,h.byteOffset,h.byteLength),d;const p=Rr(this.state.device,h,GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST,`${e.uuid}-interleaved-${a}`);return d&&(this.clearIndirectBundleCache(),this.retiredGeometryBuffers.push(d)),t.extraAttributeBuffers.set(o,p),p}ensureWireframeIndex(e,t){if(t.wireframeIndex)return;if(!this.state.device)throw new Error("Renderer is not initialized.");const i=e.index?.array,r=i?.length??t.vertexCount,n=Math.floor(r/3),a=t.vertexCount>65535,s=a?new Uint32Array(6*n):new Uint16Array(6*n);for(let e=0;e<n;e+=1){const t=3*e,r=6*e,n=i?i[t]:t,a=i?i[t+1]:t+1,o=i?i[t+2]:t+2;s[r]=n,s[r+1]=a,s[r+2]=a,s[r+3]=o,s[r+4]=o,s[r+5]=n}t.wireframeIndexFormat=a?"uint32":"uint16",t.wireframeIndex=Rr(this.state.device,s,GPUBufferUsage.INDEX,`${e.uuid}-wireframe-index`)}bindGeometryVertexBuffers(e,t,i,r,n=0,a=1,s=!1){const o=this.prepareGeometryVertexBuffers(t,i,r,n,a);s&&i.wireframeIndex&&i.wireframeIndexFormat?Ei(e,o,i.wireframeIndex,i.wireframeIndexFormat):Ei(e,o,i.index,i.indexFormat)}prepareGeometryVertexBuffers(e,t,i,r,n,a=!1){let s=this.preparedVertexBufferCache.get(t);s||(s=new WeakMap,this.preparedVertexBufferCache.set(t,s));let o=s.get(i);o||(o={instanced:i.some(e=>"instance"===e.stepMode),ranges:new Map},s.set(i,o));const l=o.instanced?Math.max(0,Math.trunc(r)):0,c=o.instanced?n:1,u=o.instanced?this.getInstanceVertexCapacity():0;let d=o.ranges.get(l);if((a||!this.invokeObjectRenderCallbacks)&&d&&d.extractionVersion===this.extractionVersion&&d.instanceCount===c&&d.instanceCapacity===u&&d.instanceBufferSize===this.state.instanceBufferSize)return d.buffers;d||(d={extractionVersion:-1,instanceCount:c,instanceBufferSize:0,instanceCapacity:0,buffers:[]},o.ranges.set(l,d));let h=this.vertexBufferBindingPlanCache.get(i);h||(h=this.getVertexAttributeGroups(i).map(e=>({group:e,standardAttribute:1===e.length?this.getStandardVertexAttribute(e[0]):null})),this.vertexBufferBindingPlanCache.set(i,h));for(let i=0;i<h.length;i+=1){const{group:a,standardAttribute:s}=h[i],o=s?t[s]:null;d.buffers[i]=o??(1===a.length?this.getGeometryVertexBuffer(e,t,a[0],r,n):this.getInterleavedGeometryVertexBuffer(e,t,a,r,n))}return d.extractionVersion=this.extractionVersion,d.instanceCount=c,d.instanceBufferSize=this.state.instanceBufferSize,d.instanceCapacity=u,d.buffers}getStandardVertexAttribute(e){let t=this.standardVertexAttributeCache.get(e);return void 0!==t||(t="position"===e.name&&"float32x3"===e.format?"position":"normal"!==e.name||"float32x3"!==e.format||void 0!==e.defaultValue&&!zr(e.defaultValue,ml)?"uv"!==e.name||"float32x2"!==e.format||void 0!==e.defaultValue&&!zr(e.defaultValue,fl)?"color"!==e.name||"float32x4"!==e.format||void 0!==e.defaultValue&&!zr(e.defaultValue,gl)?"skinIndex"===e.name&&"uint32x4"===e.format?"skinIndex":"skinWeight"===e.name&&"float32x4"===e.format?"skinWeight":null:"color":"uv":"normal",this.standardVertexAttributeCache.set(e,t)),t}prepareDrawGeometryVertexBuffers(e,t=!1){for(let i=0;i<(e.customDepthMaterial?2:1);i++){const r=0===i?e.material:e.customDepthMaterial,n=this.getMaterialVertexAttributes(r,null!==e.skinning);this.prepareGeometryVertexBuffers(e.geometry,e.geometryResource,n,e.instanceStart,e.instanceCount,t)}}getInstanceVertexCapacity(){return Math.max(Math.ceil(this.state.instanceBufferSize/(Float32Array.BYTES_PER_ELEMENT*C)),this.staticInstanceSlots.instanceCapacity,this.skinnedInstanceSlots.instanceCapacity)}getDefaultVertexAttributeBuffer(e,t){if(!this.state.device)throw new Error("Renderer is not initialized.");const i=Math.max(1,t,"instance"===e.stepMode?this.getInstanceVertexCapacity():0),r=2**Math.ceil(Math.log2(i)),n=`${e.format}:${(e.defaultValue??[]).join(",")}`;let a=this.defaultVertexAttributeBuffers.get(n);a||(a=new Map,this.defaultVertexAttributeBuffers.set(n,a));const s=a.get(r);if(s)return s;const o=Rr(this.state.device,kr(void 0,r,e.format,e.defaultValue??[]),GPUBufferUsage.VERTEX,`renderer-default-attribute-${e.format}`);return a.set(r,o),o}getMeshExtractionCacheEntry(e,t,i,r,n,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===n&&(null!==l&&s.material===l&&s.resolvedMaterial===i||null!==o&&null!==s.materials&&null!==s.resolvedMaterials&&Tr(s.materials,o)&&Gr(s.resolvedMaterials,r)))return s;const c=null!==e.geometry.index,u=dn(e.geometry),d=[];if(e.geometry.groups.length>0)for(const t of e.geometry.groups){const s=o?r[t.materialIndex??0]??r[0]:i;if(!s)continue;const l=Ar(e.geometry,c,t.start,t.count),u=qr(s,e.geometry,c,t.start,l,n),h=Hr(s),p=Hr(e.geometry),f=n?Hr(n):0;d.push({geometry:e.geometry,geometryKey:e.geometry,geometryResource:a,material:s,customDepthMaterial:n,residentInstanceBinding:null,sourceObject:e,frontFaceCW:e.matrixWorld.determinant()<0,usesBatching:!1,geometryGroup:t,batchKey:u,batchHash:Kr(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=i??r?.[0]??null;if(t){const i=Fr(e.geometry,c),r=qr(t,e.geometry,c,i.start,i.count,n),s=Hr(t),o=Hr(e.geometry),l=n?Hr(n):0;d.push({geometry:e.geometry,geometryKey:e.geometry,geometryResource:a,material:t,customDepthMaterial:n,residentInstanceBinding:null,sourceObject:e,frontFaceCW:e.matrixWorld.determinant()<0,usesBatching:!1,geometryGroup:null,batchKey:r,batchHash:Kr(s,o,c,i.start,i.count,l),indexed:c,wireframe:t.wireframe&&"triangle-list"===t.primitiveTopology,start:i.start,count:i.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:i,resolvedMaterials:o?r.slice():null,customDepthMaterial:n,indexed:c,templates:d,localBoundsCenter:u.center.clone(),localBoundsRadius:u.radius};return this.meshExtractionCache.set(e,h),h}getInstancedMeshExtractionCacheEntry(e,t,i,r){const n=null!==e.geometry.index,a=Fr(e.geometry,n),s=dn(e.geometry),o=this.instancedMeshExtractionCache.get(e);if(o&&o.geometryResource===r&&o.material===t&&o.customDepthMaterial===i&&o.indexed===n&&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=Hr(t),c=Hr(e.geometry),u=i?Hr(i):0,d={geometryResource:r,sourceMesh:e,sourceMaterial:e.material,sourceMaterialVersion:e.material.version,material:t,customDepthMaterial:i,indexed:n,drawRangeStart:a.start,drawRangeCount:a.count,batchKey:qr(t,e,n,a.start,a.count,i),batchHash:Kr(l,c,n,a.start,a.count,u),sortMaterialId:l,sortGeometryId:c,sortCustomDepthMaterialId:u,localBoundsCenter:s.center.clone(),localBoundsRadius:s.radius,cachedInstanceData:new Sn(1024),cachedBoundsMin:new Ca,cachedBoundsMax:new Ca,cachedDrawBoundsCenter:new Ca,cachedDrawBoundsRadius:0,cachedMatrixWorld:new Float64Array(16),cachedInstanceMatrixVersion:-1,cachedInstanceColorVersion:-1,cachedCount:0,cachedBoundsValid:!1,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,i,r,n){const a=n._geometryCount??0,s=this.batchedMeshExtractionCache.get(e);if(s&&s.geometryResource===r&&s.material===t&&s.customDepthMaterial===i&&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 n=0;n<a;n+=1){const a=e.getGeometryRangeAt(n);if(!a||a.count<=0)continue;const s=Ar(e.geometry,o,a.start,a.count),u=qr(t,e.geometry,o,a.start,s,i),d=Hr(t),h=Hr(e.geometry),p=i?Hr(i):0,f=e.getBoundingSphereAt(n,A),m={geometry:e.geometry,geometryKey:e.geometry,geometryResource:r,material:t,customDepthMaterial:i,residentInstanceBinding:null,sourceObject:e,frontFaceCW:!1,usesBatching:!0,geometryGroup:null,batchKey:u,batchHash:Kr(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:n,localBoundsCenter:f?f.center.clone():new Ca,localBoundsRadius:f?.radius??1};l[n]=m,c[n]={template:m,boundsMin:new Ca,boundsMax:new Ca,activeInFrame:!1,activeCount:0,instanceStart:0,writeOffset:0}}const u={geometryResource:r,material:t,customDepthMaterial:i,indexed:o,templates:l,groups:c,activeGroups:[],cachedInstanceData:new Sn(1024),cachedDraws:[],cachedBoundsMin:new Ca,cachedBoundsMax:new Ca,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 i=0;i<t.length;i+=1){const r=t[i];if((e[i]??-1)!==(r?.active&&r.visible?r.geometryIndex:-1))return!1}return!0}destroyGeometryResource(e){e.position.destroy(),e.normal.destroy(),e.uv.destroy(),e.color.destroy(),e.skinIndex?.destroy(),e.skinWeight?.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(){if(0===this.retiredGeometryResources.length&&0===this.retiredGeometryBuffers.length&&0===this.retiredStaticInstanceSlots.length)return;const e=this.retiredGeometryResources.splice(0),t=this.retiredGeometryBuffers.splice(0),i=this.retiredStaticInstanceSlots.splice(0);if(this.state.device)this.state.device.queue.onSubmittedWorkDone().then(()=>{for(const e of i)this.staticInstanceSlots.release(e);for(const t of e)this.destroyGeometryResource(t);for(const e of t)e.destroy()},()=>{for(const e of i)this.staticInstanceSlots.release(e);for(const t of e)this.destroyGeometryResource(t);for(const e of t)e.destroy()});else{for(const e of i)this.staticInstanceSlots.release(e);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,i){this.textureManager.uploadDataTextureResource(e,t,i)}uploadCompressedTextureResource(e,t,i){this.textureManager.uploadCompressedTextureResource(e,t,i)}uploadExternalTextureResource(e,t,i){this.textureManager.uploadExternalTextureResource(e,t,i)}uploadTextureResource(e,t,i){this.textureManager.uploadTextureResource(e,t,i)}getTextureResource(e){return this.textureManager.getTextureResource(e)}updateMaterialUniformBuffer(e,t){if(!this.state.device||!t.uniformBuffer)return;const i=e.uniformValuesAutoUpdate;if(!i&&t.uniformValuesAutoVersion===e.uniformValuesAutoVersion)return;const r=e.getUniformLayout();if(0===r.entries.length)return;let n=t.uniformValueHash;if(i&&(n=e.getUniformValueHash(),t.uniformValueHash===n))return;if(r.byteLength>t.uniformBuffer.size)return;let a=this.materialUniformData.get(r);a||(a=new vi(r),this.materialUniformData.set(r,a));const s=a.update(e.uniforms);t.uniformValueHash=n,t.uniformValuesAutoVersion=e.uniformValuesAutoVersion,this.state.device.queue.writeBuffer(t.uniformBuffer,0,s)}materialResourceMatches(e,t,i,r=this.sampleCount){if(e.key!==i)return!1;if(e.materialVersion===t.version&&e.textureVersionHash===t.getTextureVersionHash()&&e.rendererSampleCount===r&&e.uniformBufferSize===t.getUniformLayout().byteLength)return!0;const n=Gr(e.textures,t.getTexturesList())&&zr(e.textureVersions,t.getTextureVersionsList())&&Gr(e.storageBuffers,t.getStorageBufferList())&&e.rendererSampleCount===r&&e.uniformBufferSize===t.getUniformLayout().byteLength;return n&&(e.materialVersion=t.version,e.textureVersionHash=t.getTextureVersionHash()),n}destroyMaterialResource(e){e?.uniformBuffer?.destroy()}createMaterialBindGroupData(e,t,i){if(!this.state.device)throw new Error("Renderer is not initialized.");const r=this.pipelineCompilationDiagnostics,n=r?performance.now():0,a=[],s=[],o=Array.from(e.getTexturesList()),l=Array.from(e.getTextureVersionsList()),c=e.getStorageBufferBindingList();let u=null;const d=r?performance.now():0;if(Object.keys(e.uniforms).length>0){const i=function(e,t){const i=new ArrayBuffer(t.byteLength);return xi(e,t,new DataView(i),new Float32Array(i)),i}(e.uniforms,e.getUniformLayout());u=this.state.device.createBuffer({label:`${t}-uniforms`,size:i.byteLength,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this.state.device.queue.writeBuffer(u,0,i),a.push({binding:0,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}}),s.push({binding:0,resource:{buffer:u}})}r&&(r.cpuTotalsMs.uniformBuffer=(r.cpuTotalsMs.uniformBuffer??0)+performance.now()-d);for(const[t,n]of o.entries()){const o=1+2*t,l=r?performance.now():0,c=this.getTextureResource(n);if(r){const t=performance.now()-l;r.cpuTotalsMs.textureLookup=(r.cpuTotalsMs.textureLookup??0)+t,t>=1&&r.slowTextureLookups.push({material:e.name||e.uuid,texture:n.name||n.uuid,durationMs:t})}a.push({binding:o,visibility:i,sampler:{type:c.samplerBindingType}},{binding:o+1,visibility:i,texture:{sampleType:c.sampleType,viewDimension:c.viewDimension}}),s.push({binding:o,resource:c.sampler},{binding:o+1,resource:c.view})}const h=1+2*o.length,p=Array.from(e.getStorageBufferList());for(const[e,t]of c.entries()){const i=h+e;a.push({binding:i,visibility:Vr(t.visibility),buffer:{type:"read_write"===t.access?"storage":"read-only-storage"}}),s.push({binding:i,resource:{buffer:t.buffer}})}return r&&(r.cpuTotalsMs.bindGroupData=(r.cpuTotalsMs.bindGroupData??0)+performance.now()-n),{bindGroupLayoutEntries:a,bindGroupEntries:s,uniformBuffer:u,textures:o,textureVersions:l,storageBuffers:p}}createGraphTextureBindGroupLayout(e){if(!this.state.device)throw new Error("Renderer is not initialized.");const t=[];return Object.values(e.getGraphTextureInputs()).forEach((e,i)=>{t.push({binding:2*i,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,sampler:{type:e.sampler??("depth-2d"===e.dimension?"non-filtering":"filtering")}},{binding:2*i+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 i=this.graphTextureBindGroupCache.get(e);const r=i?.get(t);if(r&&r.materialVersion===e.version&&r.resourceVersion===this.graphTextureResourceVersion)return r.bindGroup;const n=[];Object.values(e.getGraphTextureInputs()).forEach((e,t)=>{const i="comparison"===e.sampler?this.state.shadowComparisonSampler:"non-filtering"===e.sampler||"depth-2d"===e.dimension?this.state.nearestClampSampler:"physicalTransmissionSnapshot"===e.resource?this.transmissionSampler:this.state.linearClampSampler,r="mainDepth"===e.resource?this.state.sceneDepthSnapshotView:this.getGraphTextureView(e.resource);n.push({binding:2*t,resource:i},{binding:2*t+1,resource:r})});const a=this.state.device.createBindGroup({label:`${e.uuid}-graph-textures`,layout:t,entries:n});return i||(i=new WeakMap,this.graphTextureBindGroupCache.set(e,i)),i.set(t,{materialVersion:e.version,resourceVersion:this.graphTextureResourceVersion,bindGroup:a}),a}getGraphTextureView(e){return"physicalTransmissionSnapshot"===e?this.transmissionSnapshotView:"mainDepth"===e?this.state.mainDepthView:"sceneColorSnapshot"===e?this.state.sceneColorSnapshotView:"sceneDepthSnapshot"===e?this.state.hizMipViews[0]:this.getColorTargetView(e)}compileDrawMaterials(e){const t=new Set;for(const i of e){const e=this.getDrawInstanceAccessMode(i),r=null!==i.skinning,n=this.drawUsesBatching(i),a=`${i.material.uuid}:${e}:receiveShadow=${i.receiveShadow?1:0}:skinning=${r?1:0}:batching=${n?1:0}`;t.has(a)||(i.materialResource=this.getMaterialResource(i.material,e,i.receiveShadow,void 0,r,n),t.add(a))}}async compileDrawMaterialsAsync(e,t=ol,i=this.sampleCount,r=!0){const n=new Set,a=new Set,s=[],o=[],l=ra();for(const c of e){const e=l();e&&await e;const u=this.getDrawInstanceAccessMode(c);r&&c.residentInstanceBinding&&c.sourceObject instanceof pa&&o.push({...c,materialResource:null,residentInstanceBinding:{...c.residentInstanceBinding,mode:"packed"===u?"instanced-direct":"packed"}});const d=null!==c.skinning,h=this.drawUsesBatching(c),p=`${c.material.uuid}:${u}:receiveShadow=${c.receiveShadow?1:0}:skinning=${d?1:0}:batching=${h?1:0}`;if(n.has(p)||(s.push(this.getMaterialResourceAsync(c.material,u,c.receiveShadow,t,d,h,i).then(e=>(c.materialResource=e,e))),n.add(p)),c.customDepthMaterial){const e=`${c.customDepthMaterial.uuid}:${u}:skinning=${d?1:0}`;a.has(e)||(s.push(this.getDepthPassMaterialResourceAsyncForDraw(c.customDepthMaterial,"directionalShadow",c)),a.add(e))}if(null!==c.material.depthVertexShader||h){const e=null!==c.material.depthVertexShader?["prepass","directionalShadow","pointShadow"]:["prepass","directionalShadow"];for(const t of e){const e=`${c.material.uuid}:${t}:${u}:skinning=${d?1:0}:batching=${h?1:0}`;a.has(e)||(s.push(this.getDepthPassMaterialResourceAsyncForDraw(c.material,t,c)),a.add(e))}}}o.length>0&&s.push(this.compileDrawMaterialsAsync(o,t,i,!1)),await Promise.all(s)}async compileStaticDrawMaterialsAsync(e,t=this.sampleCount,i="all"){const r=[],n=new Set;for(const a of this.staticDrawSets)if(a.publicSet.enabled&&("all"===i||a.drawStage===i)){r.push(this.compileDrawMaterialsAsync(a.draws,e,t));for(const i of a.visibleMaterialBindings){const a=`${i.material.uuid}:receiveShadow=${i.receiveShadow?1:0}:batching=${i.usesBatching?1:0}`;n.has(a)||(n.add(a),r.push(this.getMaterialResourceAsync(i.material,"packed-visible",i.receiveShadow,e,!1,i.usesBatching,t)))}for(const e of a.draws){if(e.customDepthMaterial||null===e.material.depthVertexShader||e.material.vertexAttributes.some(e=>"instance"===e.stepMode))continue;const t=`prepass-visible:${e.material.uuid}:${this.drawUsesBatching(e)}:${tn(e)}`;n.has(t)||(n.add(t),r.push(this.getDepthPassMaterialResourceAsync(e.material,"prepass","packed-visible",!1,this.drawUsesBatching(e),tn(e))))}if(this.directionalShadowGpu.available)for(const e of a.draws){const t=e.customDepthMaterial??(null!==e.material.depthVertexShader?e.material:null);if(!t||t.vertexAttributes.some(e=>"instance"===e.stepMode))continue;const i=`shadow-visible:${t.uuid}:${this.drawUsesBatching(e)}:${tn(e)}`;n.has(i)||(n.add(i),r.push(this.getDepthPassMaterialResourceAsync(t,"directionalShadow","packed-visible",!1,this.drawUsesBatching(e),tn(e))))}}await Promise.all(r)}getDepthPassMaterialKey(e,t,i,r,n,a=!1){if(!this.state.device)throw new Error("Renderer is not initialized.");return`${e.getDepthProgramCacheKey("pointShadow"===t)}:${t}:instance=${i}:skinning=${r?1:0}:batching=${n?1:0}:frontFace=${a?"cw":"ccw"}:textures=${e.getTextureLayoutKey(this.state.device)}`}getForwardMaterialKey(e,t,i,r,n,a,s=!1,o=this.sampleCount){return`${e.customProgramCacheKey()}:instance=${t}:receiveShadow=${i?1:0}:skinning=${n?1:0}:batching=${a?1:0}:frontFace=${s?"cw":"ccw"}:textures=${e.getTextureLayoutKey(this.state.device)}:samples=${o}:targets=${r.join("|")}`}getInstanceAccessModeIndex(e){return"packed"===e?0:"packed-visible"===e?1:2}getForwardMaterialFastCacheIndex(e,t,i,r,n=!1){return this.getInstanceAccessModeIndex(e)|(t?4:0)|(i?8:0)|(r?16:0)|(n?32:0)}getDepthMaterialFastCacheIndex(e,t,i,r,n=!1){return("prepass"===e?0:"directionalShadow"===e?1:2)+3*this.getInstanceAccessModeIndex(t)+(i?9:0)+(r?18:0)+(n?36:0)}fastMaterialResourceMatches(e,t,i=this.sampleCount){return e.materialVersion===t.version&&e.textureVersionHash===t.getTextureVersionHash()&&e.rendererSampleCount===i}setForwardMaterialFastCache(e,t,i){let r=this.forwardMaterialFastCache.get(e);r||(r=[],this.forwardMaterialFastCache.set(e,r)),r[t]=i}getForwardMaterialTargetFastCacheKey(e,t){return 32*this.getColorFormatsId(e)+t}setForwardMaterialTargetFastCache(e,t,i){let r=this.forwardMaterialTargetFastCache.get(e);r||(r=new Map,this.forwardMaterialTargetFastCache.set(e,r)),r.set(t,i)}setForwardMaterialFrameCache(e,t,i){let r=this.forwardMaterialFrameCache.get(e);r||(r=[],this.forwardMaterialFrameCache.set(e,r)),r[t]={extractionVersion:this.extractionVersion,resource:i}}setDepthMaterialFastCache(e,t,i){let r=this.depthMaterialFastCache.get(e);r||(r=[],this.depthMaterialFastCache.set(e,r)),r[t]=i}getDrawInstanceAccessMode(e){return"instanced-direct"===e.residentInstanceBinding?.mode?"instanced-direct":"packed"}drawUsesBatching(e){return e.usesBatching}buildMaterialShaderCode(e,t,i,r,n=!1,a=!1){const s=this.pipelineCompilationDiagnostics,o=s?performance.now():0,l=Da(`${t}\n${i}`,this.createMaterialPreprocessorDefines(e,r,n,a),{sourceName:r}),c=r.includes("vertex")?function(e){let t=0,i=0,r=null;for(;;){const n=e.indexOf("@builtin",t);if(n<0)break;t=n+8;let a=t;for(;Ha(e.charCodeAt(a));)a++;if("("!==e[a++])continue;for(;Ha(e.charCodeAt(a));)a++;if(!e.startsWith("position",a))continue;for(a+=8;Ha(e.charCodeAt(a));)a++;if(")"!==e[a++])continue;_a.lastIndex=a;const s=_a.exec(e);s&&(r??=[],r.push(e.slice(i,n),"@builtin(position) @invariant "),i=a+s[0].length,t=i)}return null===r?e:(r.push(e.slice(i)),r.join(""))}(l):l;return s&&(s.cpuTotalsMs.shaderPreprocess=(s.cpuTotalsMs.shaderPreprocess??0)+performance.now()-o),c}createMaterialPreprocessorDefines(e,t,i=!1,r=!1){const n={HIGH_PRECISION:!0,WEBGPU_RENDERER:!0,WGSL_SHADER_MATERIAL:!0,USE_BATCHING:r,USE_COLOR:!0,USE_COLOR_ALPHA:!0,NUM_DIR_LIGHTS:4,NUM_POINT_LIGHTS:y,NUM_SPOT_LIGHTS:S,NUM_DIR_LIGHT_SHADOWS:4,NUM_POINT_LIGHT_SHADOWS:y,NUM_SPOT_LIGHT_SHADOWS:S,NUM_CLIPPING_PLANES:0,UNION_CLIPPING_PLANES:0,USE_SKINNING:i,RENDERER_MOTION_VECTORS:!t.includes("shared-depth"),...this.createTexturePreprocessorDefines(e)};return e.side===ua?n.DOUBLE_SIDED=!0:e.side===sa&&(n.FLIP_SIDED=!0),!t.includes("receiveShadow=1")&&t.includes("receiveShadow=0")||(n.USE_SHADOWMAP=!0,n.SHADOWMAP_TYPE_PCF=!0),{...n,...e.defines,USE_BATCHING:r}}createTexturePreprocessorDefines(e){const t={},i={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[r,n]of Object.entries(i))e.textures[r]&&(t[n]=!0);return t}shouldInvalidateDrawMaterialResource(e,t,i,r,n){return!!e.materialResource&&(e.material!==t||e.receiveShadow!==i||e.usesBatching!==r||e.skinning!==n)}cachedDrawMaterialResourceMatches(e,t,i,r=this.sampleCount){const n=this.getDrawInstanceAccessMode(e),a=null!==e.skinning,s=this.drawUsesBatching(e),o=this.getColorFormatsId(i);return t.instanceAccessMode===n&&t.receiveShadow===e.receiveShadow&&t.useBatching===s&&t.frontFaceCW===tn(e)&&t.usesSkinning===a&&t.rendererSampleCount===r&&t.colorTargetFormatsId===o&&(this.drawMaterialResourceFrameValidation.get(t)===this.extractionVersion||(t.materialVersion===e.material.version&&t.textureVersionHash===e.material.getTextureVersionHash()||this.materialResourceMatches(t,e.material,t.key,r)))}getMaterialResourceForDraw(e,t=ol,i=this.sampleCount){const r=e.materialResource;if(r&&this.cachedDrawMaterialResourceMatches(e,r,t,i))return this.drawMaterialResourceFrameValidation.get(r)!==this.extractionVersion&&(this.updateMaterialUniformBuffer(e.material,r),this.drawMaterialResourceFrameValidation.set(r,this.extractionVersion)),r;const n=this.getDrawInstanceAccessMode(e),a=null!==e.skinning,s=this.drawUsesBatching(e),o=this.getMaterialResource(e.material,n,e.receiveShadow,t,a,s,i,tn(e));return e.materialResource=o,this.drawMaterialResourceFrameValidation.set(o,this.extractionVersion),o}getMaterialResourceAsyncForDraw(e){return this.getMaterialResourceAsync(e.material,this.getDrawInstanceAccessMode(e),e.receiveShadow,void 0,null!==e.skinning,this.drawUsesBatching(e),this.sampleCount,tn(e))}resolveForwardMaterialResources(e){for(let t=0;t<e.length;t+=1){const i=e[t];i.materialResource=this.getMaterialResource(i.material,this.getDrawInstanceAccessMode(i),i.receiveShadow,void 0,null!==i.skinning,this.drawUsesBatching(i),this.sampleCount,tn(i))}}getDepthPassMaterialResourceForDraw(e,t,i,r){return this.getDepthPassMaterialResource(e,t,r??this.getDrawInstanceAccessMode(i),null!==i.skinning,this.drawUsesBatching(i),tn(i))}getDepthPassMaterialResourceAsyncForDraw(e,t,i){return this.getDepthPassMaterialResourceAsync(e,t,this.getDrawInstanceAccessMode(i),null!==i.skinning,this.drawUsesBatching(i),tn(i))}getOrCreateSharedDepthPipeline(e,t,r,n,a,s,o,l){if(!(this.state.device&&this.state.shadowBindGroupLayout&&this.state.directShadowBindGroupLayout&&this.state.skinningBindGroupLayout))throw new Error("Renderer is not initialized.");const c=this.sharedDepthPipelineCache.get(e);if(c)return c;const u=`${t.uuid}-shared-depth-${r}-${n}`;i(this.state.device,u+"-pipeline",{key:String(t.userData.pipelineOrigin?.assetId??t.userData.assetId??t.userData.pipelineOrigin?.sourceUuid??t.uuid)+":depth:"+r,material:{name:t.name,uuid:t.uuid,version:t.version,assetId:t.userData.assetId,assetName:t.userData.assetName,...t.userData.pipelineOrigin},variant:{instanceAccessMode:n,useSkinning:s,useBatching:o,passKind:r,frontFaceCW:l},defines:{...t.defines}});const d=this.state.device.createBindGroupLayout({label:`${u}-material-layout`,entries:a}),h="prepass"===r?"instanced-direct"===n?this.state.directSceneBindGroupLayout:"packed-visible"===n?this.state.visibleDepthSceneBindGroupLayout:this.state.sceneBindGroupLayout:"packed"!==n?this.state.directShadowBindGroupLayout:this.state.shadowBindGroupLayout,p=this.state.device.createPipelineLayout({label:`${u}-pipeline-layout`,bindGroupLayouts:[h,d,...s?[this.state.skinningBindGroupLayout]:[]]}),f=vs(t,"prepass"===r?"camera":"shadow",this.state.device,n,s),m=this.buildMaterialShaderCode(t,f,"pointShadow"===r?t.pointShadowVertexShader??t.vertexShader:t.depthVertexShader??t.vertexShader,`${u}-vertex`,s,o),g="pointShadow"===r?t.pointShadowFragmentShader:t.depthFragmentShader,v=g?this.buildMaterialShaderCode(t,f,g,`${u}-fragment`,s,o):null,x={bindGroupLayout:d,pipeline:this.state.device.createRenderPipeline({label:`${u}-pipeline`,layout:p,vertex:{module:this.state.device.createShaderModule({label:`${u}-vertex`,code:m}),entryPoint:"vsMain",buffers:this.createVertexBufferLayouts(this.getMaterialVertexAttributes(t,s))},...v?{fragment:{module:this.state.device.createShaderModule({label:`${u}-fragment`,code:v}),entryPoint:"fsMain",targets:"pointShadow"===r?[{format:"rgba16float"}]:[]}}:{},primitive:{topology:ul(t),cullMode:dl(t,r,o),frontFace:l?"cw":"ccw"},depthStencil:{format:"depth32float",depthWriteEnabled:!0,depthCompare:"less",...$i(t,"directionalShadow"===r)}})};return this.sharedDepthPipelineCache.set(e,x),x}async getOrCreateSharedDepthPipelineAsync(e,t,r,n,a,s,o,l){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 c=this.sharedDepthPipelineCache.get(e);if(c)return c;const u=this.sharedDepthPipelinePromiseCache.get(e);if(u)return u;const d=`${t.uuid}-shared-depth-${r}-${n}`;i(this.state.device,d+"-pipeline",{key:String(t.userData.pipelineOrigin?.assetId??t.userData.assetId??t.userData.pipelineOrigin?.sourceUuid??t.uuid)+":depth:"+r,material:{name:t.name,uuid:t.uuid,version:t.version,assetId:t.userData.assetId,assetName:t.userData.assetName,...t.userData.pipelineOrigin},variant:{instanceAccessMode:n,useSkinning:s,useBatching:o,passKind:r,frontFaceCW:l},defines:{...t.defines}});const h=(async()=>{const i=this.state.device.createBindGroupLayout({label:`${d}-material-layout`,entries:a}),c="prepass"===r?"instanced-direct"===n?this.state.directSceneBindGroupLayout:"packed-visible"===n?this.state.visibleDepthSceneBindGroupLayout:this.state.sceneBindGroupLayout:"packed"!==n?this.state.directShadowBindGroupLayout:this.state.shadowBindGroupLayout,u=this.state.device.createPipelineLayout({label:`${d}-pipeline-layout`,bindGroupLayouts:[c,i,...s?[this.state.skinningBindGroupLayout]:[]]}),h=vs(t,"prepass"===r?"camera":"shadow",this.state.device,n,s),p=this.buildMaterialShaderCode(t,h,"pointShadow"===r?t.pointShadowVertexShader??t.vertexShader:t.depthVertexShader??t.vertexShader,`${d}-vertex`,s,o),f="pointShadow"===r?t.pointShadowFragmentShader:t.depthFragmentShader,m=f?this.buildMaterialShaderCode(t,h,f,`${d}-fragment`,s,o):null,g={bindGroupLayout:i,pipeline:await vl(this.state.device,{label:`${d}-pipeline`,layout:u,vertex:{module:this.state.device.createShaderModule({label:`${d}-vertex`,code:p}),entryPoint:"vsMain",buffers:this.createVertexBufferLayouts(this.getMaterialVertexAttributes(t,s))},...m?{fragment:{module:this.state.device.createShaderModule({label:`${d}-fragment`,code:m}),entryPoint:"fsMain",targets:"pointShadow"===r?[{format:"rgba16float"}]:[]}}:{},primitive:{topology:ul(t),cullMode:dl(t,r,o),frontFace:l?"cw":"ccw"},depthStencil:{format:"depth32float",depthWriteEnabled:!0,depthCompare:"less",...$i(t,"directionalShadow"===r)}},this.pipelineCompilationDiagnostics,"depth",`${t.name||"unnamed"} [${t.uuid}] (${r}, ${n})`,p.length,m?.length??0)};return this.sharedDepthPipelineCache.set(e,g),this.sharedDepthPipelinePromiseCache.delete(e),g})();return this.sharedDepthPipelinePromiseCache.set(e,h),h}getOrCreateSharedForwardPipeline(e,t,r,n,a,s,o,l,c,u=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 d=this.sharedForwardPipelineCache.get(e);if(d)return d;const h=`${t.uuid}-shared-forward-${r}-${u}-receiveShadow=${a?1:0}`;i(this.state.device,h+"-pipeline",{key:String(t.userData.pipelineOrigin?.assetId??t.userData.assetId??t.userData.pipelineOrigin?.sourceUuid??t.uuid)+":forward",material:{name:t.name,uuid:t.uuid,version:t.version,assetId:t.userData.assetId,assetName:t.userData.assetName,...t.userData.pipelineOrigin},variant:{instanceAccessMode:r,useSkinning:o,useBatching:l,receiveShadow:a,sampleCount:u,colorTargetFormats:s},defines:{...t.defines}});const p=this.state.device.createBindGroupLayout({label:`${h}-material-layout`,entries:n}),f=this.createGraphTextureBindGroupLayout(t),m=this.state.device.createPipelineLayout({label:`${h}-pipeline-layout`,bindGroupLayouts:["instanced-direct"===r?this.state.directSceneBindGroupLayout:"packed-visible"===r?this.state.visibleSceneBindGroupLayout:this.state.sceneBindGroupLayout,p,o?this.state.skinningBindGroupLayout:this.state.emptyBindGroupLayout,f]}),g=ms(t,this.state.device,r,a,o),v=this.buildMaterialShaderCode(t,g,t.vertexShader,`${h}-vertex`,o,l),x=this.buildMaterialShaderCode(t,g,t.fragmentShader,`${h}-fragment`,o,l),w={bindGroupLayout:p,graphTextureBindGroupLayout:f,pipeline:this.state.device.createRenderPipeline({label:`${h}-pipeline`,layout:m,vertex:{module:this.state.device.createShaderModule({label:`${h}-vertex`,code:v}),entryPoint:"vsMain",buffers:this.createVertexBufferLayouts(this.getMaterialVertexAttributes(t,o))},fragment:{module:this.state.device.createShaderModule({label:`${h}-fragment`,code:x}),entryPoint:"fsMain",targets:tl(x,s,Qo(t))},primitive:{topology:ul(t),cullMode:ul(t).startsWith("triangle")&&t.side!==ua?t.side===sa?"front":"back":"none",frontFace:c?"cw":"ccw"},multisample:{count:u},depthStencil:{format:"depth32float",depthWriteEnabled:t.depthWrite,depthCompare:t.depthTest?"less-equal":"always",...$i(t)}})};return this.sharedForwardPipelineCache.set(e,w),w}async getOrCreateSharedForwardPipelineAsync(e,t,r,n,a,s,o,l,c,u=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 d=this.sharedForwardPipelineCache.get(e);if(d)return d;const h=this.sharedForwardPipelinePromiseCache.get(e);if(h)return h;const p=`${t.uuid}-shared-forward-${r}-${u}-receiveShadow=${a?1:0}`;i(this.state.device,p+"-pipeline",{key:String(t.userData.pipelineOrigin?.assetId??t.userData.assetId??t.userData.pipelineOrigin?.sourceUuid??t.uuid)+":forward",material:{name:t.name,uuid:t.uuid,version:t.version,assetId:t.userData.assetId,assetName:t.userData.assetName,...t.userData.pipelineOrigin},variant:{instanceAccessMode:r,useSkinning:o,useBatching:l,receiveShadow:a,sampleCount:u,colorTargetFormats:s},defines:{...t.defines}});const f=(async()=>{const i=this.state.device.createBindGroupLayout({label:`${p}-material-layout`,entries:n}),d=this.createGraphTextureBindGroupLayout(t),h=this.state.device.createPipelineLayout({label:`${p}-pipeline-layout`,bindGroupLayouts:["instanced-direct"===r?this.state.directSceneBindGroupLayout:"packed-visible"===r?this.state.visibleSceneBindGroupLayout:this.state.sceneBindGroupLayout,i,o?this.state.skinningBindGroupLayout:this.state.emptyBindGroupLayout,d]}),f=ms(t,this.state.device,r,a,o),m=this.buildMaterialShaderCode(t,f,t.vertexShader,`${p}-vertex`,o,l),g=this.buildMaterialShaderCode(t,f,t.fragmentShader,`${p}-fragment`,o,l),v={bindGroupLayout:i,graphTextureBindGroupLayout:d,pipeline:await vl(this.state.device,{label:`${p}-pipeline`,layout:h,vertex:{module:this.state.device.createShaderModule({label:`${p}-vertex`,code:m}),entryPoint:"vsMain",buffers:this.createVertexBufferLayouts(this.getMaterialVertexAttributes(t,o))},fragment:{module:this.state.device.createShaderModule({label:`${p}-fragment`,code:g}),entryPoint:"fsMain",targets:tl(g,s,Qo(t))},primitive:{topology:ul(t),cullMode:ul(t).startsWith("triangle")&&t.side!==ua?t.side===sa?"front":"back":"none",frontFace:c?"cw":"ccw"},multisample:{count:u},depthStencil:{format:"depth32float",depthWriteEnabled:t.depthWrite,depthCompare:t.depthTest?"less-equal":"always",...$i(t)}},this.pipelineCompilationDiagnostics,"forward",`${t.name||"unnamed"} [${t.uuid}] (${r}, ${u}x)`,m.length,g.length)};return this.sharedForwardPipelineCache.set(e,v),this.sharedForwardPipelinePromiseCache.delete(e),v})();return this.sharedForwardPipelinePromiseCache.set(e,f),f}getDepthPassMaterialResource(e,t,i,r,n,a=!1){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||"pointShadow"===t&&(null===e.pointShadowVertexShader||null===e.pointShadowFragmentShader))return null;const s=this.getDepthMaterialFastCacheIndex(t,i,r,n,a),o=this.depthMaterialFrameCache.get(e)?.[s];if(o?.extractionVersion===this.extractionVersion)return o.resource;const l=this.depthMaterialFastCache.get(e)?.[s];if(l&&this.fastMaterialResourceMatches(l,e))return this.updateMaterialUniformBuffer(e,l),this.setDepthMaterialFrameCache(e,s,l),l;const c="prepass"===t?this.depthPrepassMaterialCache:r?this.skinnedDirectionalShadowMaterialCache:"instanced-direct"===i?this.directionalShadowMaterialCacheDirect:this.directionalShadowMaterialCache,u=this.getDepthPassMaterialKey(e,t,i,r,n,a),d=c.get(e),h=d?.get(u);if(h&&this.materialResourceMatches(h,e,u))return this.setDepthMaterialFastCache(e,s,h),this.updateMaterialUniformBuffer(e,h),this.setDepthMaterialFrameCache(e,s,h),h;this.destroyMaterialResource(h),d&&d.delete(u);const{bindGroupLayoutEntries:p,bindGroupEntries:f,uniformBuffer:m,textures:g,textureVersions:v,storageBuffers:x}=this.createMaterialBindGroupData(e,`${e.uuid}-${t}-${i}-material`,GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT),w=this.getOrCreateSharedDepthPipeline(u,e,t,i,p,r,n,a),b=this.state.device.createBindGroup({label:`${e.uuid}-${t}-${i}-material-bind-group`,layout:w.bindGroupLayout,entries:f}),y={key:u,materialVersion:e.version,textureVersionHash:e.getTextureVersionHash(),rendererSampleCount:this.sampleCount,instanceAccessMode:i,receiveShadow:!0,useBatching:n,frontFaceCW:a,colorTargetFormatsId:0,pipeline:w.pipeline,graphTextureBindGroupLayout:w.graphTextureBindGroupLayout,bindGroup:b,uniformBuffer:m,uniformBufferSize:m?.size??0,uniformValueHash:e.uniformValuesAutoUpdate?e.getUniformValueHash():0,uniformValuesAutoVersion:e.uniformValuesAutoVersion,textures:g,textureVersions:v,storageBuffers:x,vertexAttributes:this.getMaterialVertexAttributes(e,r),usesSkinning:r};let S=c.get(e);return S||(S=new Map,c.set(e,S)),S.set(u,y),this.setDepthMaterialFastCache(e,s,y),this.setDepthMaterialFrameCache(e,s,y),y}setDepthMaterialFrameCache(e,t,i){let r=this.depthMaterialFrameCache.get(e);r||(r=[],this.depthMaterialFrameCache.set(e,r)),r[t]={extractionVersion:this.extractionVersion,resource:i}}async getDepthPassMaterialResourceAsync(e,t,i,r,n,a=!1){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||"pointShadow"===t&&(null===e.pointShadowVertexShader||null===e.pointShadowFragmentShader))return null;const s=this.getDepthMaterialFastCacheIndex(t,i,r,n,a),o=this.depthMaterialFastCache.get(e)?.[s];if(o&&this.fastMaterialResourceMatches(o,e))return this.updateMaterialUniformBuffer(e,o),o;const l="prepass"===t?this.depthPrepassMaterialCache:r?this.skinnedDirectionalShadowMaterialCache:"instanced-direct"===i?this.directionalShadowMaterialCacheDirect:this.directionalShadowMaterialCache,c=this.getDepthPassMaterialKey(e,t,i,r,n,a),u=l.get(e),d=u?.get(c);if(d&&this.materialResourceMatches(d,e,c))return this.setDepthMaterialFastCache(e,s,d),this.updateMaterialUniformBuffer(e,d),d;this.destroyMaterialResource(d),u&&u.delete(c);const{bindGroupLayoutEntries:h,bindGroupEntries:p,uniformBuffer:f,textures:m,textureVersions:g,storageBuffers:v}=this.createMaterialBindGroupData(e,`${e.uuid}-${t}-${i}-material`,GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT),x=await this.getOrCreateSharedDepthPipelineAsync(c,e,t,i,h,r,n,a),w=this.state.device.createBindGroup({label:`${e.uuid}-${t}-${i}-material-bind-group`,layout:x.bindGroupLayout,entries:p}),b={key:c,materialVersion:e.version,textureVersionHash:e.getTextureVersionHash(),rendererSampleCount:this.sampleCount,instanceAccessMode:i,receiveShadow:!0,useBatching:n,frontFaceCW:a,colorTargetFormatsId:0,pipeline:x.pipeline,graphTextureBindGroupLayout:x.graphTextureBindGroupLayout,bindGroup:w,uniformBuffer:f,uniformBufferSize:f?.size??0,uniformValueHash:e.uniformValuesAutoUpdate?e.getUniformValueHash():0,uniformValuesAutoVersion:e.uniformValuesAutoVersion,textures:m,textureVersions:g,storageBuffers:v,vertexAttributes:this.getMaterialVertexAttributes(e,r),usesSkinning:r};let y=l.get(e);return y||(y=new Map,l.set(e,y)),y.set(c,b),this.setDepthMaterialFastCache(e,s,b),b}getMaterialResource(e,t,i=!0,r,n=!1,a=!1,s=this.sampleCount,o=!1){if(!(this.state.device&&this.state.format&&this.state.sceneBindGroupLayout&&this.state.visibleSceneBindGroupLayout&&this.state.directSceneBindGroupLayout))throw new Error("Renderer is not initialized.");const l=n?i?this.skinnedMaterialCache:this.skinnedMaterialNoReceiveShadowCache:i?"instanced-direct"===t?this.materialCacheDirect:"packed-visible"===t?this.materialCacheVisible:this.materialCache:"instanced-direct"===t?this.materialNoReceiveShadowCacheDirect:"packed-visible"===t?this.materialNoReceiveShadowCacheVisible:this.materialNoReceiveShadowCache,c=r??ol,u=void 0===r||1===r.length&&r[0]===D,d=this.getForwardMaterialFastCacheIndex(t,i,n,a,o),h=u?null:this.getForwardMaterialTargetFastCacheKey(c,d);if(u){const t=this.forwardMaterialFrameCache.get(e)?.[d];if(t?.extractionVersion===this.extractionVersion&&t.resource.rendererSampleCount===s)return t.resource;const i=this.forwardMaterialFastCache.get(e)?.[d];if(i&&this.fastMaterialResourceMatches(i,e,s))return this.updateMaterialUniformBuffer(e,i),this.setForwardMaterialFrameCache(e,d,i),i}else{const t=this.forwardMaterialTargetFastCache.get(e)?.get(h);if(t&&this.fastMaterialResourceMatches(t,e,s))return this.updateMaterialUniformBuffer(e,t),t}const p=this.getForwardMaterialKey(e,t,i,c,n,a,o,s),f=l.get(e),m=f?.get(p);if(m&&this.materialResourceMatches(m,e,p,s))return u?(this.setForwardMaterialFastCache(e,d,m),this.setForwardMaterialFrameCache(e,d,m)):this.setForwardMaterialTargetFastCache(e,h,m),this.updateMaterialUniformBuffer(e,m),m;this.destroyMaterialResource(m),f&&f.delete(p);const{bindGroupLayoutEntries:g,bindGroupEntries:v,uniformBuffer:x,textures:w,textureVersions:b,storageBuffers:y}=this.createMaterialBindGroupData(e,`${e.uuid}-${t}-material`,GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT),S=this.getOrCreateSharedForwardPipeline(p,e,t,g,i,c,n,a,o,s),C=this.state.device.createBindGroup({label:`${e.uuid}-${t}-material-bind-group`,layout:S.bindGroupLayout,entries:v}),M={key:p,materialVersion:e.version,textureVersionHash:e.getTextureVersionHash(),rendererSampleCount:s,instanceAccessMode:t,receiveShadow:i,useBatching:a,frontFaceCW:o,colorTargetFormatsId:this.getColorFormatsId(c),pipeline:S.pipeline,graphTextureBindGroupLayout:S.graphTextureBindGroupLayout,bindGroup:C,uniformBuffer:x,uniformBufferSize:x?.size??0,uniformValueHash:e.uniformValuesAutoUpdate?e.getUniformValueHash():0,uniformValuesAutoVersion:e.uniformValuesAutoVersion,textures:w,textureVersions:b,storageBuffers:y,vertexAttributes:this.getMaterialVertexAttributes(e,n),usesSkinning:n};let P=l.get(e);return P||(P=new Map,l.set(e,P)),P.set(p,M),u?(this.setForwardMaterialFastCache(e,d,M),this.setForwardMaterialFrameCache(e,d,M)):this.setForwardMaterialTargetFastCache(e,h,M),M}async getMaterialResourceAsync(e,t,i=!0,r,n=!1,a=!1,s=this.sampleCount,o=!1){if(!(this.state.device&&this.state.format&&this.state.sceneBindGroupLayout&&this.state.visibleSceneBindGroupLayout&&this.state.directSceneBindGroupLayout))throw new Error("Renderer is not initialized.");const l=n?i?this.skinnedMaterialCache:this.skinnedMaterialNoReceiveShadowCache:i?"instanced-direct"===t?this.materialCacheDirect:"packed-visible"===t?this.materialCacheVisible:this.materialCache:"instanced-direct"===t?this.materialNoReceiveShadowCacheDirect:"packed-visible"===t?this.materialNoReceiveShadowCacheVisible:this.materialNoReceiveShadowCache,c=r??ol,u=void 0===r||1===r.length&&r[0]===D,d=this.getForwardMaterialFastCacheIndex(t,i,n,a,o);if(u){const t=this.forwardMaterialFrameCache.get(e)?.[d];if(t?.extractionVersion===this.extractionVersion&&t.resource.rendererSampleCount===s)return t.resource;const i=this.forwardMaterialFastCache.get(e)?.[d];if(i&&this.fastMaterialResourceMatches(i,e,s))return this.updateMaterialUniformBuffer(e,i),this.setForwardMaterialFrameCache(e,d,i),i}const h=this.getForwardMaterialKey(e,t,i,c,n,a,o,s),p=l.get(e),f=p?.get(h);if(f&&this.materialResourceMatches(f,e,h,s))return u&&(this.setForwardMaterialFastCache(e,d,f),this.setForwardMaterialFrameCache(e,d,f)),this.updateMaterialUniformBuffer(e,f),f;this.destroyMaterialResource(f),p&&p.delete(h);const{bindGroupLayoutEntries:m,bindGroupEntries:g,uniformBuffer:v,textures:x,textureVersions:w,storageBuffers:b}=this.createMaterialBindGroupData(e,`${e.uuid}-${t}-material`,GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT),y=await this.getOrCreateSharedForwardPipelineAsync(h,e,t,m,i,c,n,a,o,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:i,useBatching:a,frontFaceCW:o,colorTargetFormatsId:this.getColorFormatsId(c),pipeline:y.pipeline,graphTextureBindGroupLayout:y.graphTextureBindGroupLayout,bindGroup:S,uniformBuffer:v,uniformBufferSize:v?.size??0,uniformValueHash:e.uniformValuesAutoUpdate?e.getUniformValueHash():0,uniformValuesAutoVersion:e.uniformValuesAutoVersion,textures:x,textureVersions:w,storageBuffers:b,vertexAttributes:this.getMaterialVertexAttributes(e,n),usesSkinning:n};let M=l.get(e);return M||(M=new Map,l.set(e,M)),M.set(h,C),u&&(this.setForwardMaterialFastCache(e,d,C),this.setForwardMaterialFrameCache(e,d,C)),C}ensureTiledLightingSize(){this.tiledPointLights?.resize(this.state.width,this.state.height)&&(this.state.sharedSceneBindGroup=null,this.state.residentSceneBindGroupVersion+=1,this.clearIndirectBundleCache(),this.clearStaticDrawSetBundleCaches())}updateCameraUniforms(e,t,i){if(!this.state.device||!this.state.cameraBuffer)return;const r=this.cameraProjectionScratch.copy(e.projectionMatrix);i||0===this.projectionJitterPixels.x&&0===this.projectionJitterPixels.y||(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(T).multiply(r).multiply(e.matrixWorldInverse);this.cameraDetailProjectionScratch.update(n),e.getWorldPosition(F);const a=this.cameraUniformScratch;a.set(n.elements,0),a[16]=F.x,a[17]=F.y,a[18]=F.z,a[19]=1,a[20]=i?.width??this.state.width,a[21]=i?.height??this.state.height,a[22]=i?1:this.state.pixelRatio,a[23]=this.state.frameTimeSeconds,a.set(e.matrixWorldInverse.elements,24),a.set(k.multiplyMatrices(T,r).elements,40),a[56]=e.near,a[57]=e.far,a[58]=1/Math.max(e.far-e.near,1e-4),a[59]=!i&&this.tiledLightingEnabled?1:0;const s=i?null:t.fog;null!=s?(a[60]=s.color.r,a[61]=s.color.g,a[62]=s.color.b,a[63]=1,"density"in s?(a[64]=0,a[65]=0,a[66]=s.density,a[67]=1):(a[64]=s.near,a[65]=s.far,a[66]=0,a[67]=0)):(a.fill(0,60,68),a[67]=-1);const o=!i&&this.motionVectorProjectionPending?this.motionVectorProjection:e.projectionMatrix,l=(i?U:this.motionVectorCurrentViewProj).copy(T).multiply(o).multiply(e.matrixWorldInverse);a.set(l.elements,68),a.set((!i&&this.motionVectorHistoryValid?this.motionVectorPreviousViewProj:l).elements,84),a[100]=!i&&this.motionVectorHistoryValid?1:0,a[101]=i?.width??this.state.width,a[102]=i?.height??this.state.height,a[103]=0,i||(this.motionVectorProjectionPending=!1),this.state.device.queue.writeBuffer(this.state.cameraBuffer,0,a,0,104)}updateTemporalVisibilityUniforms(e){if(!this.state.device||!this.state.temporalVisibilityBuffer)return;const t=on(e,this.temporalVisibilityCurrentViewProj);e.getWorldPosition(this.temporalVisibilityCurrentCameraPosition);const i=this.temporalVisibilityUniformScratch;i.set(t.elements,0),i.set((this.state.temporalHiZHistoryValid?this.temporalVisibilityPreviousViewProj:t).elements,16),i[32]=this.temporalVisibilityCurrentCameraPosition.x,i[33]=this.temporalVisibilityCurrentCameraPosition.y,i[34]=this.temporalVisibilityCurrentCameraPosition.z,i[35]=1;const r=this.state.temporalHiZHistoryValid?this.temporalVisibilityPreviousCameraPosition:this.temporalVisibilityCurrentCameraPosition;i[36]=r.x,i[37]=r.y,i[38]=r.z,i[39]=1,i[40]=this.state.width,i[41]=this.state.height,i[42]=this.state.pixelRatio,i[43]=this.state.frameTimeSeconds,this.state.device.queue.writeBuffer(this.state.temporalVisibilityBuffer,0,i,0,44)}commitTemporalHiZHistory(){this.temporalVisibilityPreviousViewProj.copy(this.temporalVisibilityCurrentViewProj),this.temporalVisibilityPreviousCameraPosition.copy(this.temporalVisibilityCurrentCameraPosition),this.state.temporalHiZHistoryValid=!0,this.motionVectorPreviousViewProj.copy(this.motionVectorCurrentViewProj),this.motionVectorHistoryValid=!0}updateLightUniforms(e){if(!this.state.device||!this.state.lightBuffer)return;const t=this.lightUniformScratch;null===this.sceneCaptureOptions&&this.updateSpotLightMapAtlas(e.lights.spots),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 i=this.csmCascadeRanges[e],r=3976+4*e;t[r+0]=i.x,t[r+1]=i.y}const i=e.lights.hemisphere;null!=i&&(t[3992]=i.skyColor.x,t[3993]=i.skyColor.y,t[3994]=i.skyColor.z,t[3995]=i.intensity,t[3996]=i.groundColor.x,t[3997]=i.groundColor.y,t[3998]=i.groundColor.z,t[3999]=i.intensity,t[4e3]=i.direction.x,t[4001]=i.direction.y,t[4002]=i.direction.z,t[4003]=1);for(let i=0;i<e.lights.directionals.length;i+=1){const r=e.lights.directionals[i],n=this.directionalShadowCameras[i],a=8+4*i;t[a+0]=r.direction.x,t[a+1]=r.direction.y,t[a+2]=r.direction.z,t[a+3]=1;const s=24+4*i;t[s+0]=r.color.x,t[s+1]=r.color.y,t[s+2]=r.color.z,t[s+3]=r.intensity;const o=40+4*i;t[o+0]=r.shadowBias,t[o+1]=r.castShadow?1:0,t[o+2]=this.state.directionalShadowTextureSize,t[o+3]=r.shadowNormalBias;const l=56+4*i;t[l+0]=r.shadowRadius,t[l+1]=r.shadowIntensity;const c=r.shadowViewProjection??=new ma;t.set(on(n,c).elements,72+16*i)}for(let i=0;i<e.lights.points.length;i+=1){const r=e.lights.points[i],n=136+4*i;t[n+0]=r.position.x,t[n+1]=r.position.y,t[n+2]=r.position.z,t[n+3]=r.range;const a=392+4*i;t[a+0]=r.color.x,t[a+1]=r.color.y,t[a+2]=r.color.z,t[a+3]=r.intensity;const s=648+4*i;t[s+0]=r.distance,t[s+1]=r.decay;const o=904+4*i;t[o+0]=r.shadowBias,t[o+1]=r.castShadow?1:0,t[o+2]=this.state.pointShadowTextureSize,t[o+3]=r.shadowNormalBias;const l=1160+4*i;t[l+0]=r.shadowRadius,t[l+1]=r.shadowIntensity,t[l+2]=r.shadowCameraNear,t[l+3]=r.shadowCameraFar}for(let i=0;i<e.lights.spots.length;i+=1){const r=e.lights.spots[i],n=1416+4*i;t[n+0]=r.position.x,t[n+1]=r.position.y,t[n+2]=r.position.z,t[n+3]=r.range;const a=1672+4*i;t[a+0]=r.direction.x,t[a+1]=r.direction.y,t[a+2]=r.direction.z,t[a+3]=Math.cos(r.angle);const s=1928+4*i;t[s+0]=r.color.x,t[s+1]=r.color.y,t[s+2]=r.color.z,t[s+3]=r.intensity;const o=2184+4*i;t[o+0]=r.shadowBias,t[o+1]=r.castShadow?1:0,t[o+2]=this.state.spotShadowTextureSize,t[o+3]=r.shadowNormalBias;const l=2440+4*i;t[l+0]=r.shadowRadius,t[l+1]=r.shadowIntensity;const c=2696+4*i;if(t[c+0]=r.range,t[c+1]=Math.cos(r.angle*(1-r.penumbra)),t[c+2]=r.decay,t[c+3]=null!=r.map?1:0,r.castShadow||null!=r.map){const e=this.spotShadowCameras[i];e.near=r.shadowCameraNear,e.far=r.shadowCameraFar,e.fov=r.shadowCameraFov,e.aspect=1,e.position.copy(r.position),O.copy(r.position).add(r.direction),e.lookAt(O),e.updateMatrixWorld(!0),e.updateProjectionMatrix(),t.set(on(e,this.shadowViewProjScratch).elements,2952+16*i)}}this.state.device.queue.writeBuffer(this.state.lightBuffer,0,t,0,G)}updateSpotLightMapAtlas(e){const t=this.state.device;if(null==t)return;const i=e.some(e=>null!=e.map),r=i?2048:1,n=i?r/8:1,a=i?e.map(e=>null==e.map?"-":`${e.map.uuid}:${e.map.version}`).join("|"):"fallback";if(null!=this.state.spotLightMapTexture&&r===this.spotLightMapAtlasSize&&a===this.spotLightMapAtlasSignature)return;if(null==this.state.spotLightMapTexture||r!==this.spotLightMapAtlasSize){const e=this.state.spotLightMapTexture,n=t.createTexture({label:i?"spot-light-map-atlas":"spot-light-map-fallback",size:{width:r,height:r},format:"rgba8unorm",usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_DST});this.state.spotLightMapTexture=n,this.state.spotLightMapView=n.createView(),this.spotLightMapAtlasSize=r,e?.destroy(),this.state.sharedSceneBindGroup=null,this.state.residentSceneBindGroupVersion+=1,this.clearIndirectBundleCache(),this.clearStaticDrawSetBundleCaches()}if(!i)return t.queue.writeTexture({texture:this.state.spotLightMapTexture},new Uint8Array([255,255,255,255]),{},{width:1,height:1}),void(this.spotLightMapAtlasSignature=a);if(null==this.spotLightMapAtlasLayout||null==this.spotLightMapAtlasPipeline){this.spotLightMapAtlasLayout=t.createBindGroupLayout({label:"spot-light-map-atlas-layout",entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}},{binding:1,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float"}}]});const e=t.createShaderModule({label:"spot-light-map-atlas-shader",code:"\n struct VertexOutput { @builtin(position) position: vec4<f32>, @location(0) uv: vec2<f32> };\n @vertex fn vertexMain(@builtin(vertex_index) index: u32) -> VertexOutput {\n let positions = array<vec2<f32>, 3>(vec2(-1.0, -1.0), vec2(3.0, -1.0), vec2(-1.0, 3.0));\n var output: VertexOutput;\n output.position = vec4(positions[index], 0.0, 1.0);\n output.uv = positions[index] * vec2(0.5, -0.5) + vec2(0.5);\n return output;\n }\n @group(0) @binding(0) var mapSampler: sampler;\n @group(0) @binding(1) var mapTexture: texture_2d<f32>;\n @fragment fn fragmentMain(input: VertexOutput) -> @location(0) vec4<f32> {\n return textureSample(mapTexture, mapSampler, input.uv);\n }\n "});this.spotLightMapAtlasPipeline=t.createRenderPipeline({label:"spot-light-map-atlas-pipeline",layout:t.createPipelineLayout({bindGroupLayouts:[this.spotLightMapAtlasLayout]}),vertex:{module:e,entryPoint:"vertexMain"},fragment:{module:e,entryPoint:"fragmentMain",targets:[{format:"rgba8unorm"}]}})}const s=t.createCommandEncoder({label:"spot-light-map-atlas-upload"}),o=s.beginRenderPass({colorAttachments:[{view:this.state.spotLightMapView,clearValue:{r:1,g:1,b:1,a:1},loadOp:"clear",storeOp:"store"}]});o.setPipeline(this.spotLightMapAtlasPipeline);for(let i=0;i<e.length;i+=1){const r=e[i].map;if(null==r)continue;const a=this.getTextureResource(r),s=i%8*n,l=Math.floor(i/8)*n;o.setViewport(s,l,n,n,0,1),o.setScissorRect(s,l,n,n),Fi(o,0,t.createBindGroup({layout:this.spotLightMapAtlasLayout,entries:[{binding:0,resource:this.state.linearClampSampler},{binding:1,resource:a.view}]})),o.draw(3)}o.end(),t.queue.submit([s.finish()]),this.spotLightMapAtlasSignature=a}writeShadowCameraBuffer(e,t,i,r,n,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]=i,o[18]=r,o[19]=n,o[60]=this.state.frameTimeSeconds,o[61]=this.state.width,o[62]=this.state.height,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)}};var fl=[0,0],ml=[0,0,1],gl=[1,1,1,1];async function vl(e,t,i,r,n,a=0,s=0){if(null==e)throw new Error("WebGPU device is not initialized");const o=performance.now();try{return await W(e,t)}finally{i&&r&&n&&i.pipelines.push({kind:r,material:n,durationMs:performance.now()-o,vertexCodeLength:a,fragmentCodeLength:s})}}import{DataTexture as xl,Matrix4 as wl,RepeatWrapping as bl}from"three";var yl={off:{enabled:!1,temporal:{}},low:{enabled:!0,resolutionScale:.35,directions:2,steps:3,temporal:{historyWeight:.92,depthRejection:.1},denoise:{samples:4,radius:4}},medium:{enabled:!0,resolutionScale:.5,directions:2,steps:4,temporal:{historyWeight:.9,depthRejection:.08},denoise:{samples:8,radius:6}},high:{enabled:!0,resolutionScale:.5,directions:3,steps:5,temporal:{historyWeight:.88,depthRejection:.06},denoise:{samples:12,radius:8}}},Sl=class{options;noiseTexture=function(){const e=new Array(25).fill(0);let t=Math.floor(2.5),i=4;for(let r=1;r<=25;){-1===t&&5===i?(t=0,i=3):(5===i&&(i=0),t<0&&(t=4));const n=5*t+i;0===e[n]?(e[n]=r++,t-=1,i+=1):(t+=1,i-=2)}const r=new Uint8Array(100);for(let t=0;t<e.length;t+=1){const i=2*Math.PI*e[t]/e.length;r[4*t]=Math.round(255*(.5*Math.cos(i)+.5)),r[4*t+1]=Math.round(255*(.5*Math.sin(i)+.5)),r[4*t+2]=127,r[4*t+3]=255}const n=new xl(r,5,5);return n.wrapS=bl,n.wrapT=bl,n.needsUpdate=!0,n}();gtaoPasses=new Map;temporalPasses=new Map;denoisePasses=new Map;compositePasses=new Map;writeIndex=0;frameIndex=0;historyValid=!1;constructor(e={}){this.options=Tl(e)}get enabled(){return this.options.enabled}get temporalEnabled(){return!1!==this.options.temporal}setOptions(e){Object.assign(this.options,Tl({...this.options,...e,denoise:e.denoise??this.options.denoise,temporal:e.temporal??this.options.temporal,targetPrefix:this.options.targetPrefix})),this.gtaoPasses.clear(),this.temporalPasses.clear(),this.denoisePasses.clear(),this.compositePasses.clear(),this.reset()}applyPreset(e){this.setOptions(yl[e])}reset(){this.writeIndex=0,this.frameIndex=0,this.historyValid=!1}addPasses(e,t){const i=e.createColorTarget(`${this.options.targetPrefix}Raw`,{format:"r16float",scale:this.options.resolutionScale}),r=`${t.depth}:${t.normal}:${i}`;let n=this.gtaoPasses.get(r);n||(n=new Cl(t.depth,t.normal,i,this.noiseTexture,this.options),this.gtaoPasses.set(r,n));const a=!1!==this.options.temporal&&null!=t.velocity;n.frameIndex=a?this.frameIndex:0,e.addFullscreenPass(n);let s=i;if(a&&!1!==this.options.temporal&&null!=t.velocity){const r=e.createColorTarget(`${this.options.targetPrefix}TemporalA`,{format:"r16float",scale:this.options.resolutionScale}),n=e.createColorTarget(`${this.options.targetPrefix}TemporalB`,{format:"r16float",scale:this.options.resolutionScale}),a=e.createColorTarget(`${this.options.targetPrefix}TemporalDepthA`,{format:"r16float",scale:this.options.resolutionScale}),o=e.createColorTarget(`${this.options.targetPrefix}TemporalDepthB`,{format:"r16float",scale:this.options.resolutionScale}),l=0===this.writeIndex?n:r,c=0===this.writeIndex?r:n,u=0===this.writeIndex?o:a,d=0===this.writeIndex?a:o,h=`${i}:${t.depth}:${t.velocity}:${l}:${u}:${c}:${d}`;let p=this.temporalPasses.get(h);p||(p=new Ml(i,t.depth,t.velocity,l,u,c,d,this.options.temporal,this),this.temporalPasses.set(h,p)),e.addFullscreenPass(p),s=c,this.writeIndex=1-this.writeIndex}if(a&&(this.frameIndex+=1),!1===this.options.denoise)return s;const o=e.createColorTarget(`${this.options.targetPrefix}Denoised`,{format:"r16float",scale:this.options.resolutionScale}),l=`${s}:${t.depth}:${t.normal}:${o}`;let c=this.denoisePasses.get(l);return c||(c=new Pl(s,t.depth,t.normal,o,this.options.normalSpace,this.options.denoise),this.denoisePasses.set(l,c)),e.addFullscreenPass(c),o}addCompositePass(e,t,i,r={}){const n=r.output??e.createColorTarget(`${this.options.targetPrefix}Composite`,{format:"rgba16float"}),a=Math.max(0,r.intensity??this.options.intensity),s=Math.max(1e-4,r.power??this.options.power),o=`${t}:${i}:${n}:${a}:${s}`;let l=this.compositePasses.get(o);return l||(l=new Bl(t,i,n,a,s),this.compositePasses.set(o,l)),e.addFullscreenPass(l),n}dispose(){this.noiseTexture.dispose(),this.gtaoPasses.clear(),this.temporalPasses.clear(),this.denoisePasses.clear(),this.compositePasses.clear()}consumeHistoryValid(){const e=this.historyValid;return this.historyValid=!0,e}},Cl=class{constructor(e,t,i,r,n){this.options=n,this.inputs={sceneDepth:e,sceneNormal:t},this.outputs=i,this.textures={gtaoNoise:r},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 baseTangent = normalize(noiseTexel.xy * 2.0 - vec2<f32>(1.0));\n let temporalAngle = f32(i32(fullscreenUniforms[13].x) & 7) * 2.39996323;\n let temporalRotation = mat2x2<f32>(\n vec2<f32>(cos(temporalAngle), sin(temporalAngle)),\n vec2<f32>(-sin(temporalAngle), cos(temporalAngle))\n );\n let rotatedTangent = temporalRotation * baseTangent;\n let tangent = vec3<f32>(rotatedTangent, 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`}(n)}options;name="GTAOPass";sampler="nearest";uniformBufferSize=224;inputs;outputs;textures;fragmentShader;uniforms=new Float32Array(this.uniformBufferSize/4);webGpuProjection=new wl;webGpuProjectionInverse=new wl;frameIndex=0;updateUniforms=e=>(this.webGpuProjection.copy(Dl).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.set([this.frameIndex,0,0,0],52),this.uniforms)},Ml=class{constructor(e,t,i,r,n,a,s,o,l){this.options=o,this.state=l,this.inputs={currentAo:e,sceneDepth:t,velocity:i,historyAo:r,historyDepth:n},this.outputs=[a,s]}options;state;name="GTAOTemporalPass";sampler="linear";uniformBufferSize=80;inputs;outputs;fragmentShader=Il;uniforms=new Float32Array(this.uniformBufferSize/4);inverseProjection=new wl;updateUniforms=e=>(this.inverseProjection.copy(Dl).multiply(e.camera.projectionMatrix).invert(),this.uniforms.set(this.inverseProjection.elements,0),this.uniforms.set([this.options.historyWeight,this.options.depthRejection,this.options.neighborhoodClamp?1:0,this.state.consumeHistoryValid()?1:0],16),this.uniforms)},Pl=class{constructor(e,t,i,r,n,a){this.options=a,this.inputs={aoInput:e,sceneDepth:t,sceneNormal:i},this.outputs=r,this.fragmentShader=function(e,t){const i="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 ${i};\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 < ${t}; i += 1) {\n let sampleIndex = (i * 16) / ${t};\n let sample = POISSON_DISK[sampleIndex];\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`}(n,a.samples)}options;name="GTAODenoisePass";sampler="nearest";uniformBufferSize=144;inputs;outputs;fragmentShader;uniforms=new Float32Array(this.uniformBufferSize/4);webGpuProjectionInverse=new wl;updateUniforms=e=>(this.webGpuProjectionInverse.copy(Dl).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)},Bl=class{name="GTAOCompositePass";sampler="nearest";uniformBufferSize=16;inputs;outputs;uniforms;constructor(e,t,i,r,n){this.inputs={sceneColor:e,ambientOcclusion:t},this.outputs=i,this.uniforms=new Float32Array([r,n,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 materialFlags = u32(round(color.a));\n let isAlphaTested = (materialFlags & 1u) != 0u;\n let visibility = select(mix(1.0, pow(clamp(ao, 0.0, 1.0), fullscreenUniforms[0].y), fullscreenUniforms[0].x), 1.0, isAlphaTested);\n return vec4<f32>(color.rgb * visibility, color.a);\n}\n"},Dl=(new wl).set(1,0,0,0,0,1,0,0,0,0,.5,.5,0,0,0,1);var Il="\nstruct GTAOTemporalOutput {\n @location(0) ao: vec4<f32>,\n @location(1) depth: vec4<f32>,\n};\n\nfn inverseProjectionMatrix() -> mat4x4<f32> {\n return mat4x4<f32>(\n fullscreenUniforms[0], fullscreenUniforms[1],\n fullscreenUniforms[2], fullscreenUniforms[3]\n );\n}\n\nfn loadSceneDepth(uv: vec2<f32>) -> f32 {\n let size = vec2<i32>(textureDimensions(sceneDepthTexture));\n let pixel = clamp(\n vec2<i32>(uv * vec2<f32>(size)),\n vec2<i32>(0),\n size - vec2<i32>(1)\n );\n return textureLoad(sceneDepthTexture, pixel, 0);\n}\n\nfn linearViewDepth(uv: vec2<f32>, depth: f32) -> f32 {\n let clip = vec4<f32>(\n uv.x * 2.0 - 1.0,\n 1.0 - uv.y * 2.0,\n depth,\n 1.0\n );\n let view = inverseProjectionMatrix() * clip;\n return abs(view.z / max(abs(view.w), 1e-6));\n}\n\nfn loadVelocity(uv: vec2<f32>) -> vec2<f32> {\n let size = vec2<i32>(textureDimensions(velocityTexture));\n let pixel = clamp(\n vec2<i32>(uv * vec2<f32>(size)),\n vec2<i32>(0),\n size - vec2<i32>(1)\n );\n return textureLoad(velocityTexture, pixel, 0).xy;\n}\n\nfn loadCurrentAo(pixel: vec2<i32>, size: vec2<i32>) -> f32 {\n return textureLoad(\n currentAoTexture,\n clamp(pixel, vec2<i32>(0), size - vec2<i32>(1)),\n 0\n ).r;\n}\n\n@fragment\nfn fsMain(input: FullscreenVertexOutput) -> GTAOTemporalOutput {\n let aoSize = vec2<i32>(textureDimensions(currentAoTexture));\n let pixel = clamp(\n vec2<i32>(input.position.xy),\n vec2<i32>(0),\n aoSize - vec2<i32>(1)\n );\n let currentAo = loadCurrentAo(pixel, aoSize);\n let currentDepthRaw = loadSceneDepth(input.uv);\n let currentDepth = linearViewDepth(input.uv, currentDepthRaw);\n let previousUv = input.uv - loadVelocity(input.uv);\n let inBounds =\n all(previousUv >= vec2<f32>(0.0)) &&\n all(previousUv <= vec2<f32>(1.0));\n let historySize = vec2<i32>(textureDimensions(historyDepthTexture));\n let historyPixel = clamp(\n vec2<i32>(previousUv * vec2<f32>(historySize)),\n vec2<i32>(0),\n historySize - vec2<i32>(1)\n );\n let previousDepth = textureLoad(historyDepthTexture, historyPixel, 0).r;\n let relativeDepthDifference =\n abs(previousDepth - currentDepth) / max(currentDepth, 1e-3);\n let historyAccepted =\n fullscreenUniforms[4].w > 0.5 &&\n inBounds &&\n currentDepthRaw < 1.0 &&\n relativeDepthDifference <= fullscreenUniforms[4].y;\n\n var historyAo = textureSampleLevel(\n historyAoTexture,\n fullscreenSampler,\n clamp(previousUv, vec2<f32>(0.0), vec2<f32>(1.0)),\n 0.0\n ).r;\n if (fullscreenUniforms[4].z > 0.5) {\n let left = loadCurrentAo(pixel + vec2<i32>(-1, 0), aoSize);\n let right = loadCurrentAo(pixel + vec2<i32>(1, 0), aoSize);\n let up = loadCurrentAo(pixel + vec2<i32>(0, -1), aoSize);\n let down = loadCurrentAo(pixel + vec2<i32>(0, 1), aoSize);\n let neighborhoodMin = min(currentAo, min(min(left, right), min(up, down)));\n let neighborhoodMax = max(currentAo, max(max(left, right), max(up, down)));\n historyAo = clamp(historyAo, neighborhoodMin, neighborhoodMax);\n }\n let historyWeight = select(\n 0.0,\n fullscreenUniforms[4].x,\n historyAccepted\n );\n let accumulated = mix(currentAo, historyAo, historyWeight);\n\n var output: GTAOTemporalOutput;\n output.ao = vec4<f32>(accumulated);\n output.depth = vec4<f32>(currentDepth);\n return output;\n}\n";function Tl(e){return{intensity:Math.max(0,e.intensity??.6),power:Math.max(1e-4,e.power??1),enabled:e.enabled??!0,radius:Math.max(.001,e.radius??.25),resolutionScale:Vl(e.resolutionScale??1,.25,1),thickness:Math.max(.001,e.thickness??1),distanceExponent:Math.max(.01,e.distanceExponent??1),distanceFalloff:Vl(e.distanceFalloff??1,0,1),directions:Gl(e.directions??3,1,8),steps:Gl(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),samples:Rl(e.denoise?.samples??16),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)},temporal:!1!==e.temporal&&{historyWeight:Vl(e.temporal?.historyWeight??.9,0,.98),depthRejection:Vl(e.temporal?.depthRejection??.08,.001,1),neighborhoodClamp:e.temporal?.neighborhoodClamp??!0}}}function Rl(e){return e<=4?4:e<=8?8:e<=12?12:16}function Vl(e,t,i){return Math.min(i,Math.max(t,e))}function Gl(e,t,i){return Math.floor(Vl(e,t,i))}import{Matrix4 as zl}from"three";var Ll=class{options;passes=new Map;constructor(e={}){this.options=jl(e)}get enabled(){return this.options.enabled}get surfaceRaySteps(){return this.options.surfaceSteps}setOptions(e){const t=jl({...this.options,...e});Object.keys(t).every(e=>t[e]===this.options[e])||(Object.assign(this.options,t),this.passes.clear())}addPasses(e,t){if(!this.enabled)return t.sceneColor;const i=e.createColorTarget(`${this.options.targetPrefix}Raw`,{format:"rgba16float",scale:this.options.resolutionScale}),r=`trace:${t.sceneColor}:${t.depth}:${t.normalRoughness}:${i}`;let n=this.passes.get(r);n||(n=new Ul(t,i,this.options),this.passes.set(r,n)),e.addFullscreenPass(n);let a=i;if(this.options.blur)for(let i=0;i<2;i++){const r=e.createColorTarget(`${this.options.targetPrefix}Blur${i}`,{format:"rgba16float",scale:this.options.resolutionScale}),n=`blur:${a}:${t.depth}:${t.normalRoughness}:${r}:${i}:${this.options.blurRadius}`;let s=this.passes.get(n);s||(s=new kl(a,t.depth,t.normalRoughness,r,i,this.options.blurRadius),this.passes.set(n,s)),e.addFullscreenPass(s),a=r}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 Al(t.sceneColor,a,s,this.options.intensity),this.passes.set(o,l)),e.addFullscreenPass(l),s}},Ul=class{constructor(e,t,i){this.options=i,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",i=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 = ${i};\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}`}(i)}options;name="SSRTracePass";sampler="linear";uniformBufferSize=224;inputs;outputs;fragmentShader;uniforms=new Float32Array(56);projection=new zl;inverseProjection=new zl;updateUniforms=e=>(this.projection.copy(Fl).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)},kl=class{name;sampler="linear";uniformBufferSize=16;inputs;outputs;uniforms;constructor(e,t,i,r,n,a){this.name=0===n?"SSRBlurHorizontalPass":"SSRBlurVerticalPass",this.inputs={reflection:e,sceneDepth:t,normalRoughness:i},this.outputs=r,this.uniforms=new Float32Array([0===n?1:0,1===n?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}"},Al=class{name="SSRCompositePass";sampler="linear";uniformBufferSize=16;inputs;outputs;uniforms;constructor(e,t,i,r){this.inputs={sceneColor:e,reflection:t},this.outputs=i,this.uniforms=new Float32Array([r,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 Fl=(new zl).set(1,0,0,0,0,1,0,0,0,0,.5,.5,0,0,0,1);function Ol(e,t,i){return Math.min(i,Math.max(t,e))}function El(e,t,i){return Math.round(Ol(e,t,i))}function jl(e){return{enabled:e.enabled??!0,surfaceSteps:El(e.surfaceSteps??0,0,32),resolutionScale:Ol(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:Ol(e.maxRoughness??.8,.01,1),steps:El(e.steps??2048,8,2048),pixelStride:Ol(e.pixelStride??1,1,4),normalSpace:e.normalSpace??"world",blur:e.blur??!0,blurRadius:Ol(e.blurRadius??6,1,12),targetPrefix:e.targetPrefix??"ssr"}}import{Matrix4 as $l,Vector2 as Wl}from"three";var Nl=(new $l).set(1,0,0,0,0,1,0,0,0,0,.5,.5,0,0,0,1),_l=class{renderScale;sampleCount;minCurrentWeight;motionWeightScale;depthThreshold;relativeDepthThreshold;targetPrefix;writeIndex=0;historyValid=!1;frameIndex=0;renderWidth=1;renderHeight=1;outputWidth=1;outputHeight=1;jitter=new Wl;unjitteredProjection=new $l;previousJitterUv=new Wl;currentJitterUv=new Wl;previousViewProjection=new $l;resolvePasses=new Map;constructor(e={}){this.renderScale=Kl(e.renderScale??1,.25,1),this.sampleCount=Math.max(1,Math.floor(e.sampleCount??32)),this.minCurrentWeight=Kl(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,i){this.setSize(t,i),e.updateProjectionMatrix(),this.unjitteredProjection.copy(e.projectionMatrix),this.jitter.set(ql(this.frameIndex%this.sampleCount+1,2)-.5,ql(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,i=e.mainDepth,r){const n=e.createColorTarget(`${this.targetPrefix}HistoryColorA`,{format:"rgba16float",resolution:"presentation"}),a=e.createColorTarget(`${this.targetPrefix}HistoryColorB`,{format:"rgba16float",resolution:"presentation"}),s=e.createColorTarget(`${this.targetPrefix}HistoryDepthA`,{format:"r32float",resolution:"presentation"}),o=e.createColorTarget(`${this.targetPrefix}HistoryDepthB`,{format:"r32float",resolution:"presentation"}),l=0===this.writeIndex?a:n,c=0===this.writeIndex?n:a,u=0===this.writeIndex?o:s,d=0===this.writeIndex?s:o,h=`${t}:${i}:${r??"camera"}:${l}:${u}:${c}:${d}`;let p=this.resolvePasses.get(h);return p||(p=new Hl(t,i,r,l,u,c,d,this),this.resolvePasses.set(h,p)),e.addFullscreenPass(p),this.writeIndex=1-this.writeIndex,this.frameIndex+=1,c}reset(){this.frameIndex=0,this.writeIndex=0,this.historyValid=!1,this.previousViewProjection.identity(),this.currentJitterUv.set(0,0),this.previousJitterUv.set(0,0)}setRenderScale(e){const t=Kl(e,.25,1);t!==this.renderScale&&(this.renderScale=t,this.renderWidth=Math.max(1,Math.floor(this.outputWidth*this.renderScale)),this.renderHeight=Math.max(1,Math.floor(this.outputHeight*this.renderScale)),this.reset())}setSize(e,t){const i=Math.max(1,Math.floor(e)),r=Math.max(1,Math.floor(t));i===this.outputWidth&&r===this.outputHeight||(this.outputWidth=i,this.outputHeight=r,this.renderWidth=Math.max(1,Math.floor(i*this.renderScale)),this.renderHeight=Math.max(1,Math.floor(r*this.renderScale)),this.reset())}updateResolveUniforms(e,t,i,r){t.copy(Nl).multiply(r.camera.projectionMatrix).multiply(r.camera.matrixWorldInverse),i.copy(t).invert(),e.set(i.elements,0),e.set((this.historyValid?this.previousViewProjection:t).elements,16),e.set([r.presentationWidth,r.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}},Hl=class{constructor(e,t,i,r,n,a,s,o){var l;this.state=o,this.inputs=null==i?{currentColor:e,currentDepth:t,historyColor:r,historyDepth:n}:{currentColor:e,currentDepth:t,historyColor:r,historyDepth:n,velocity:i},this.outputs=[a,s],this.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${(l=null!=i)?"\nfn loadPackedVelocity(pixel: vec2<i32>, renderSize: vec2<i32>) -> vec4<f32> {\n let velocitySize = vec2<i32>(textureDimensions(velocityTexture));\n let velocityPixel = clamp(\n vec2<i32>((vec2<f32>(pixel) + 0.5) * vec2<f32>(velocitySize) / vec2<f32>(renderSize)),\n vec2<i32>(0),\n velocitySize - vec2<i32>(1)\n );\n return textureLoad(velocityTexture, velocityPixel, 0);\n}\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 cameraHistoryUv = centerUv - (closestOutputUv - closestHistoryUv);\n${l?"\n // RG stores unjittered previous-to-current displacement in top-left-origin\n // UV units. History therefore lies opposite the velocity. Sampling at the\n // closest-depth pixel avoids borrowing background motion at silhouettes.\n let packedVelocity = loadPackedVelocity(closestPixel, renderSize);\n let rawVelocity = packedVelocity.xy;\n let finiteVelocity = all(rawVelocity == rawVelocity) && all(abs(rawVelocity) < vec2<f32>(2.0));\n // B=CameraOnly with exactly zero RG is the explicit fallback emitted by a\n // custom-position material that did not provide previous-frame deformation.\n let needsCameraFallback =\n abs(packedVelocity.z - 1.0) < 0.25 &&\n dot(rawVelocity, rawVelocity) < 1e-12;\n let historyUv = select(\n cameraHistoryUv,\n centerUv - rawVelocity,\n finiteVelocity && !needsCameraFallback\n );\n":"\n let historyUv = cameraHistoryUv;\n"}\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>(closestUv.x * 2.0 - 1.0, 1.0 - closestUv.y * 2.0, closestDepth, 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`}state;name="TemporalAAResolvePass";sampler="nearest";uniformBufferSize=176;inputs;outputs;fragmentShader;uniforms=new Float32Array(this.uniformBufferSize/4);currentViewProjection=new $l;currentViewProjectionInverse=new $l;updateUniforms=e=>(this.state.updateResolveUniforms(this.uniforms,this.currentViewProjection,this.currentViewProjectionInverse,e),this.uniforms)};function ql(e,t){let i=1,r=0;for(;e>0;)i/=t,r+=i*(e%t),e=Math.floor(e/t);return r}function Kl(e,t,i){return Math.min(i,Math.max(t,e))}var Yl=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=Xl(e.subpixelBlending??.75,0,1),this.targetPrefix=e.targetPrefix??"fxaa"}addPass(e,t,i={}){const r=i.output??e.createColorTarget(`${this.targetPrefix}Color`,{format:"rgba16float",resolution:"presentation"}),n=`${t}:${r}`;let a=this.passes.get(n);return a||(a=new Zl(t,r,this),this.passes.set(n,a)),e.addFullscreenPass(a),r}},Zl=class{constructor(e,t,i){this.state=i,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),Xl(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 Xl(e,t,i){return Math.min(i,Math.max(t,e))}import{ClampToEdgeWrapping as Jl,DataTexture as Ql,LinearFilter as ec,NoColorSpace as tc,RGFormat as ic,UnsignedByteType as rc}from"three";var nc={low:{searchSteps:4,diagonalSteps:0},medium:{searchSteps:8,diagonalSteps:0},high:{searchSteps:16,diagonalSteps:8},ultra:{searchSteps:32,diagonalSteps:16}},ac=class{threshold;localContrastAdaptation;edgeDetection;cornerRounding;sharpness;quality;targetPrefix;areaTexture;edgePasses=new Map;weightPasses=new Map;blendPasses=new Map;constructor(e={}){this.threshold=Math.max(0,e.threshold??.08),this.localContrastAdaptation=Math.max(0,e.localContrastAdaptation??.5),this.edgeDetection=e.edgeDetection??"color",this.cornerRounding=vc(e.cornerRounding??.25,0,1),this.sharpness=vc(e.sharpness??0,0,1),this.quality=nc[e.quality??"high"],this.targetPrefix=e.targetPrefix??"smaa",this.areaTexture=function(){const e=new Ql(function(){if(cc)return cc;const e=new Uint8Array(25600),t=[[0,0],[3,0],[0,3],[3,3],[1,0],[4,0],[1,3],[4,3],[0,1],[3,1],[0,4],[3,4],[1,1],[4,1],[1,4],[4,4]],i=[[0,0],[1,0],[0,2],[1,2],[2,0],[3,0],[2,2],[3,2],[0,1],[1,1],[0,3],[1,3],[2,1],[3,1],[2,3],[3,3]];for(let r=0;r<16;r+=1){const[n,a]=t[r];for(let t=0;t<16;t+=1)for(let i=0;i<16;i+=1){uc(e,16*n+i,16*a+t,dc(r,i*i,t*t))}const[s,o]=i[r];for(let t=0;t<20;t+=1)for(let i=0;i<20;i+=1){uc(e,80+20*s+i,20*o+t,fc(r,i,t))}}return cc=e,e}(),160,80,ic,rc);return e.name="SMAA-Area-Lookup",e.colorSpace=tc,e.minFilter=ec,e.magFilter=ec,e.wrapS=Jl,e.wrapT=Jl,e.generateMipmaps=!1,e.needsUpdate=!0,e}()}addPass(e,t,i={}){const r=e.createColorTarget(`${this.targetPrefix}Edges`,{format:"rg8unorm",resolution:"render"}),n=e.createColorTarget(`${this.targetPrefix}Weights`,{format:"rgba8unorm",resolution:"render"}),a=i.output??e.createColorTarget(`${this.targetPrefix}Color`,{format:"rgba16float",resolution:"render"}),s=`${t}:${r}`;let o=this.edgePasses.get(s);o||(o=new sc(t,r,this),this.edgePasses.set(s,o));const l=`${r}:${n}`;let c=this.weightPasses.get(l);c||(c=new oc(r,n,this.areaTexture,this),this.weightPasses.set(l,c));const u=`${t}:${n}:${a}`;let d=this.blendPasses.get(u);return d||(d=new lc(t,n,a,this),this.blendPasses.set(u,d)),e.addFullscreenPass(o),e.addFullscreenPass(c),e.addFullscreenPass(d),a}dispose(){this.areaTexture.dispose()}get searchSteps(){return this.quality.searchSteps}get diagonalSteps(){return this.quality.diagonalSteps}},sc=class{constructor(e,t,i){this.state=i,this.inputs={source:e},this.outputs=t}state;name="SMAAEdgeDetectionPass";sampler="nearest";uniformBufferSize=16;inputs;outputs;uniforms=new Float32Array(4);updateUniforms=()=>(this.uniforms.set([Math.max(0,this.state.threshold),Math.max(0,this.state.localContrastAdaptation),"color"===this.state.edgeDetection?1:0,0]),this.uniforms);fragmentShader="\nfn loadColor(pixel: vec2<i32>, size: vec2<i32>) -> vec3<f32> {\n let color = textureLoad(sourceTexture, clamp(pixel, vec2<i32>(0), size - vec2<i32>(1)), 0).rgb;\n // Intermediate buffers are linear. This inexpensive transfer makes the\n // threshold perceptual and keeps black toon strokes from being missed.\n return sqrt(max(color, vec3<f32>(0.0)));\n}\n\nfn colorDelta(a: vec3<f32>, b: vec3<f32>) -> f32 {\n let difference = abs(a - b);\n let colorDelta = max(difference.r, max(difference.g, difference.b));\n let lumaDelta = abs(dot(a - b, vec3<f32>(0.299, 0.587, 0.114)));\n return select(lumaDelta, colorDelta, fullscreenUniforms[0].z > 0.5);\n}\n\n@fragment\nfn fsMain(input: FullscreenVertexOutput) -> @location(0) vec4<f32> {\n let size = vec2<i32>(textureDimensions(sourceTexture));\n let pixel = clamp(vec2<i32>(input.position.xy), vec2<i32>(0), size - vec2<i32>(1));\n let center = loadColor(pixel, size);\n let leftColor = loadColor(pixel + vec2<i32>(-1, 0), size);\n let topColor = loadColor(pixel + vec2<i32>(0, -1), size);\n let left = colorDelta(center, leftColor);\n let top = colorDelta(center, topColor);\n let right = colorDelta(center, loadColor(pixel + vec2<i32>(1, 0), size));\n let bottom = colorDelta(center, loadColor(pixel + vec2<i32>(0, 1), size));\n let left2 = colorDelta(leftColor, loadColor(pixel + vec2<i32>(-2, 0), size));\n let top2 = colorDelta(topColor, loadColor(pixel + vec2<i32>(0, -2), size));\n let maximum = max(max(max(left, top), max(right, bottom)), max(left2, top2));\n let threshold = fullscreenUniforms[0].x;\n let adaptation = fullscreenUniforms[0].y * maximum;\n let westEdge = left >= threshold && left >= adaptation;\n let northEdge = top >= threshold && top >= adaptation;\n return vec4<f32>(\n select(0.0, 1.0, westEdge),\n select(0.0, 1.0, northEdge),\n 0.0,\n 0.0\n );\n}\n"},oc=class{constructor(e,t,i,r){this.state=r,this.inputs={edges:e},this.outputs=t,this.textures={area:i}}state;name="SMAABlendingWeightPass";sampler="nearest";uniformBufferSize=16;inputs;outputs;textures;uniforms=new Float32Array(4);updateUniforms=()=>(this.uniforms.set([this.state.searchSteps,this.state.diagonalSteps,vc(this.state.cornerRounding,0,1),0]),this.uniforms);fragmentShader="\nconst MAX_SEARCH_STEPS: i32 = 32;\nconst MAX_DIAGONAL_STEPS: i32 = 16;\n\nfn edgeAt(pixel: vec2<i32>, size: vec2<i32>) -> vec2<f32> {\n if (any(pixel < vec2<i32>(0)) || any(pixel >= size)) {\n return vec2<f32>(0.0);\n }\n return textureLoad(edgesTexture, pixel, 0).rg;\n}\n\nfn areaOrthogonal(distance: vec2<f32>, e1: f32, e2: f32) -> vec2<f32> {\n let pattern = vec2<f32>(round(4.0 * vec2<f32>(e1, e2)));\n let texel = vec2<f32>(16.0) * pattern + sqrt(max(distance, vec2<f32>(0.0)));\n let uv = (texel + vec2<f32>(0.5)) / vec2<f32>(160.0, 80.0);\n return textureSampleLevel(areaTexture, areaSampler, uv, 0.0).rg;\n}\n\nfn areaDiagonal(distance: vec2<f32>, e: vec2<f32>) -> vec2<f32> {\n let pattern = round(e);\n let texel = vec2<f32>(80.0, 0.0) + vec2<f32>(20.0) * pattern + distance;\n let uv = (texel + vec2<f32>(0.5)) / vec2<f32>(160.0, 80.0);\n return textureSampleLevel(areaTexture, areaSampler, uv, 0.0).rg;\n}\n\nfn searchHorizontal(pixel: vec2<i32>, direction: i32, size: vec2<i32>) -> i32 {\n var distance = 0;\n let limit = i32(fullscreenUniforms[0].x);\n for (var step = 1; step <= MAX_SEARCH_STEPS; step += 1) {\n if (step > limit) { break; }\n let candidate = pixel + vec2<i32>(direction * step, 0);\n let edge = edgeAt(candidate, size);\n if (edge.g < 0.5 || (step > 1 && edge.r > 0.5)) { break; }\n distance = step;\n }\n return distance;\n}\n\nfn searchVertical(pixel: vec2<i32>, direction: i32, size: vec2<i32>) -> i32 {\n var distance = 0;\n let limit = i32(fullscreenUniforms[0].x);\n for (var step = 1; step <= MAX_SEARCH_STEPS; step += 1) {\n if (step > limit) { break; }\n let candidate = pixel + vec2<i32>(0, direction * step);\n let edge = edgeAt(candidate, size);\n if (edge.r < 0.5 || (step > 1 && edge.g > 0.5)) { break; }\n distance = step;\n }\n return distance;\n}\n\nfn horizontalCrossing(pixel: vec2<i32>, size: vec2<i32>) -> f32 {\n let near = edgeAt(pixel, size).r;\n let far = edgeAt(pixel + vec2<i32>(0, -1), size).r;\n return (3.0 * near + far) * 0.25;\n}\n\nfn verticalCrossing(pixel: vec2<i32>, size: vec2<i32>) -> f32 {\n let near = edgeAt(pixel, size).g;\n let far = edgeAt(pixel + vec2<i32>(-1, 0), size).g;\n return (3.0 * near + far) * 0.25;\n}\n\nfn attenuateHorizontalCorners(\n weights: vec2<f32>,\n leftPixel: vec2<i32>,\n rightPixel: vec2<i32>,\n leftDistance: i32,\n rightDistance: i32,\n size: vec2<i32>\n) -> vec2<f32> {\n let rounding = fullscreenUniforms[0].z;\n var result = weights;\n if (leftDistance <= rightDistance) {\n let extended = max(edgeAt(leftPixel + vec2<i32>(0, 1), size).r, edgeAt(leftPixel + vec2<i32>(0, -2), size).r);\n result *= clamp(vec2<f32>(rounding + 1.0 - extended), vec2<f32>(0.0), vec2<f32>(1.0));\n } else {\n let extended = max(edgeAt(rightPixel + vec2<i32>(1, 1), size).r, edgeAt(rightPixel + vec2<i32>(1, -2), size).r);\n result *= clamp(vec2<f32>(rounding + 1.0 - extended), vec2<f32>(0.0), vec2<f32>(1.0));\n }\n return result;\n}\n\nfn attenuateVerticalCorners(\n weights: vec2<f32>,\n topPixel: vec2<i32>,\n bottomPixel: vec2<i32>,\n topDistance: i32,\n bottomDistance: i32,\n size: vec2<i32>\n) -> vec2<f32> {\n let rounding = fullscreenUniforms[0].z;\n var result = weights;\n if (topDistance <= bottomDistance) {\n let extended = max(edgeAt(topPixel + vec2<i32>(1, 0), size).g, edgeAt(topPixel + vec2<i32>(-2, 0), size).g);\n result *= clamp(vec2<f32>(rounding + 1.0 - extended), vec2<f32>(0.0), vec2<f32>(1.0));\n } else {\n let extended = max(edgeAt(bottomPixel + vec2<i32>(1, 1), size).g, edgeAt(bottomPixel + vec2<i32>(-2, 1), size).g);\n result *= clamp(vec2<f32>(rounding + 1.0 - extended), vec2<f32>(0.0), vec2<f32>(1.0));\n }\n return result;\n}\n\nfn searchDiagonal(\n pixel: vec2<i32>,\n direction: vec2<i32>,\n size: vec2<i32>\n) -> vec2<f32> {\n var distance = 0;\n var lastEdge = vec2<f32>(0.0);\n let limit = i32(fullscreenUniforms[0].y);\n for (var step = 1; step <= MAX_DIAGONAL_STEPS; step += 1) {\n if (step > limit) { break; }\n let candidate = pixel + direction * step;\n let edge = edgeAt(candidate, size);\n let adjacent = edgeAt(candidate + vec2<i32>(1, 0), size).r;\n lastEdge = vec2<f32>(edge.g, adjacent);\n if (edge.g + adjacent < 1.5) { break; }\n distance = step;\n }\n return vec2<f32>(f32(distance), lastEdge.g);\n}\n\nfn diagonalWeights(pixel: vec2<i32>, edges: vec2<f32>, size: vec2<i32>) -> vec2<f32> {\n if (fullscreenUniforms[0].y < 1.0 || edges.g < 0.5) {\n return vec2<f32>(0.0);\n }\n var result = vec2<f32>(0.0);\n var negative = vec2<f32>(0.0);\n if (edges.r > 0.5) {\n negative = searchDiagonal(pixel, vec2<i32>(-1, 1), size);\n }\n let positive = searchDiagonal(pixel, vec2<i32>(1, -1), size);\n if (negative.x + positive.x >= 2.0) {\n let leftPixel = pixel + vec2<i32>(-i32(negative.x), i32(negative.x));\n let rightPixel = pixel + vec2<i32>(i32(positive.x), -i32(positive.x));\n let c1 = edgeAt(leftPixel + vec2<i32>(-1, 0), size).g;\n let c2 = edgeAt(leftPixel, size).r;\n let c3 = edgeAt(rightPixel + vec2<i32>(1, 0), size).g;\n let c4 = edgeAt(rightPixel + vec2<i32>(1, -1), size).r;\n result += areaDiagonal(vec2<f32>(negative.x, positive.x), vec2<f32>(2.0 * c1 + c2, 2.0 * c3 + c4));\n }\n\n let negativeOpposite = searchDiagonal(pixel, vec2<i32>(-1, -1), size);\n var positiveOpposite = vec2<f32>(0.0);\n if (edgeAt(pixel + vec2<i32>(1, 0), size).r > 0.5) {\n positiveOpposite = searchDiagonal(pixel, vec2<i32>(1, 1), size);\n }\n if (negativeOpposite.x + positiveOpposite.x >= 2.0) {\n let leftPixel = pixel + vec2<i32>(-i32(negativeOpposite.x), -i32(negativeOpposite.x));\n let rightPixel = pixel + vec2<i32>(i32(positiveOpposite.x), i32(positiveOpposite.x));\n let c1 = edgeAt(leftPixel + vec2<i32>(-1, 0), size).g;\n let c2 = edgeAt(leftPixel + vec2<i32>(0, -1), size).r;\n let rightEdges = edgeAt(rightPixel + vec2<i32>(1, 0), size);\n result += areaDiagonal(\n vec2<f32>(negativeOpposite.x, positiveOpposite.x),\n vec2<f32>(2.0 * c1 + c2, 2.0 * rightEdges.g + rightEdges.r)\n ).gr;\n }\n return result;\n}\n\n@fragment\nfn fsMain(input: FullscreenVertexOutput) -> @location(0) vec4<f32> {\n let size = vec2<i32>(textureDimensions(edgesTexture));\n let pixel = clamp(vec2<i32>(input.position.xy), vec2<i32>(0), size - vec2<i32>(1));\n let edges = edgeAt(pixel, size);\n var weights = vec4<f32>(0.0);\n\n if (edges.g > 0.5) {\n let diagonal = diagonalWeights(pixel, edges, size);\n if (dot(diagonal, vec2<f32>(1.0)) > 1e-5) {\n weights.r = diagonal.x;\n weights.g = diagonal.y;\n } else {\n let leftDistance = searchHorizontal(pixel, -1, size);\n let rightDistance = searchHorizontal(pixel, 1, size);\n let leftPixel = pixel + vec2<i32>(-leftDistance, 0);\n let rightPixel = pixel + vec2<i32>(rightDistance, 0);\n let e1 = horizontalCrossing(leftPixel, size);\n let e2 = horizontalCrossing(rightPixel + vec2<i32>(1, 0), size);\n let area = areaOrthogonal(vec2<f32>(f32(leftDistance), f32(rightDistance)), e1, e2);\n let a = attenuateHorizontalCorners(area, leftPixel, rightPixel, leftDistance, rightDistance, size);\n weights.r = a.x;\n weights.g = a.y;\n }\n }\n\n if (edges.r > 0.5) {\n let topDistance = searchVertical(pixel, -1, size);\n let bottomDistance = searchVertical(pixel, 1, size);\n let topPixel = pixel + vec2<i32>(0, -topDistance);\n let bottomPixel = pixel + vec2<i32>(0, bottomDistance);\n let e1 = verticalCrossing(topPixel, size);\n let e2 = verticalCrossing(bottomPixel + vec2<i32>(0, 1), size);\n let area = areaOrthogonal(vec2<f32>(f32(topDistance), f32(bottomDistance)), e1, e2);\n let a = attenuateVerticalCorners(area, topPixel, bottomPixel, topDistance, bottomDistance, size);\n weights.b = a.x;\n weights.a = a.y;\n }\n\n return weights;\n}\n"},lc=class{constructor(e,t,i,r){this.state=r,this.inputs={source:e,weights:t},this.outputs=i}state;name="SMAANeighborhoodBlendPass";sampler="linear";uniformBufferSize=16;inputs;outputs;uniforms=new Float32Array(4);updateUniforms=()=>(this.uniforms.set([vc(this.state.sharpness,0,1),0,0,0]),this.uniforms);fragmentShader="\nfn loadSource(pixel: vec2<i32>, size: vec2<i32>) -> vec4<f32> {\n return textureLoad(sourceTexture, clamp(pixel, vec2<i32>(0), size - vec2<i32>(1)), 0);\n}\n\nfn loadWeights(pixel: vec2<i32>, size: vec2<i32>) -> vec4<f32> {\n return textureLoad(weightsTexture, clamp(pixel, vec2<i32>(0), size - vec2<i32>(1)), 0);\n}\n\nfn sharpen(center: vec3<f32>, pixel: vec2<i32>, size: vec2<i32>, edgeAmount: f32) -> vec3<f32> {\n let strength = fullscreenUniforms[0].x * (1.0 - clamp(edgeAmount * 2.0, 0.0, 1.0));\n if (strength <= 1e-5) { return center; }\n let left = loadSource(pixel + vec2<i32>(-1, 0), size).rgb;\n let right = loadSource(pixel + vec2<i32>(1, 0), size).rgb;\n let top = loadSource(pixel + vec2<i32>(0, -1), size).rgb;\n let bottom = loadSource(pixel + vec2<i32>(0, 1), size).rgb;\n let minimum = min(center, min(min(left, right), min(top, bottom)));\n let maximum = max(center, max(max(left, right), max(top, bottom)));\n let average = (left + right + top + bottom) * 0.25;\n let contrast = max(maximum.r - minimum.r, max(maximum.g - minimum.g, maximum.b - minimum.b));\n let adaptive = strength * (1.0 - clamp(contrast, 0.0, 1.0)) * 0.5;\n return clamp(center + (center - average) * adaptive, minimum, maximum);\n}\n\n@fragment\nfn fsMain(input: FullscreenVertexOutput) -> @location(0) vec4<f32> {\n let size = vec2<i32>(textureDimensions(sourceTexture));\n let pixel = clamp(vec2<i32>(input.position.xy), vec2<i32>(0), size - vec2<i32>(1));\n let center = loadSource(pixel, size);\n let current = loadWeights(pixel, size);\n\n // SMAA stores right/bottom weights in adjacent texels and left/top weights\n // in the current texel. Preserve that exact channel convention.\n let right = loadWeights(pixel + vec2<i32>(1, 0), size).a;\n let bottom = loadWeights(pixel + vec2<i32>(0, 1), size).g;\n let left = current.b;\n let top = current.r;\n let edgeAmount = max(max(right, bottom), max(left, top));\n\n var color = center;\n if (edgeAmount > 1e-5) {\n let texel = 1.0 / vec2<f32>(size);\n if (max(right, left) > max(bottom, top)) {\n let total = max(right + left, 1e-5);\n let rightColor = textureSampleLevel(\n sourceTexture,\n fullscreenSampler,\n input.uv + vec2<f32>(right * texel.x, 0.0),\n 0.0\n );\n let leftColor = textureSampleLevel(\n sourceTexture,\n fullscreenSampler,\n input.uv - vec2<f32>(left * texel.x, 0.0),\n 0.0\n );\n color = (rightColor * right + leftColor * left) / total;\n } else {\n let total = max(bottom + top, 1e-5);\n let bottomColor = textureSampleLevel(\n sourceTexture,\n fullscreenSampler,\n input.uv + vec2<f32>(0.0, bottom * texel.y),\n 0.0\n );\n let topColor = textureSampleLevel(\n sourceTexture,\n fullscreenSampler,\n input.uv - vec2<f32>(0.0, top * texel.y),\n 0.0\n );\n color = (bottomColor * bottom + topColor * top) / total;\n }\n }\n\n color = vec4<f32>(sharpen(color.rgb, pixel, size, edgeAmount), color.a);\n return color;\n}\n"};var cc=null;function uc(e,t,i,r){const n=2*(160*i+t);e[n]=Math.floor(255*vc(r[0],0,1)),e[n+1]=Math.floor(255*vc(r[1],0,1))}function dc(e,t,i){const r=t+i+1,n=.5,a=-.5,s=()=>hc([0,a],[r/2,0],t),o=()=>hc([r/2,0],[r,a],t);switch(e){case 0:case 5:case 10:case 15:default:return[0,0];case 1:return t<=i?s():[0,0];case 2:return t>=i?o():[0,0];case 3:return pc(r,s(),o());case 4:return t<=i?hc([0,n],[r/2,0],t):[0,0];case 6:case 14:case 7:return hc([0,n],[r,a],t);case 8:return t>=i?hc([r/2,0],[r,n],t):[0,0];case 9:case 11:case 13:return hc([0,a],[r,n],t);case 12:return pc(r,hc([0,n],[r/2,0],t),hc([r/2,0],[r,n],t))}}function hc(e,t,i){const r=t[0]-e[0],n=t[1]-e[1];if(Math.abs(r)<1e-6)return[0,0];const a=i,s=i+1,o=e[1]+n*(a-e[0])/r,l=e[1]+n*(s-e[0])/r;if(!(a>=e[0]&&a<t[0]||s>e[0]&&s<=t[0]))return[0,0];if(Math.sign(o)===Math.sign(l)||Math.abs(o)<1e-4||Math.abs(l)<1e-4){const e=.5*(o+l);return e<0?[-e,0]:[0,e]}const c=-e[1]*r/n+e[0],u=c-Math.floor(c),d=c>e[0]?o*u*.5:0,h=c<t[0]?l*(1-u)*.5:0;return(Math.abs(d)>Math.abs(h)?d:-h)<0?[Math.abs(d),Math.abs(h)]:[Math.abs(h),Math.abs(d)]}function pc(e,t,i){const r=e=>[.5*Math.sqrt(2*e[0]),.5*Math.sqrt(2*e[1])],n=vc(e/32,0,1),a=r(t),s=r(i);return[gc(a[0],t[0],n)+gc(s[0],i[0],n),gc(a[1],t[1],n)+gc(s[1],i[1],n)]}function fc(e,t,i){const r=t+i+1,[n,a]=[[0,0],[1,0],[0,2],[1,2],[2,0],[3,0],[2,2],[3,2],[0,1],[1,1],[0,3],[1,3],[2,1],[3,1],[2,3],[3,3]][e],s=(e,i)=>function(e,t,i){const r=30;let n=0,a=0;if(e[0]===t[0]&&e[1]===t[1])return[0,1];const s=.5*(e[0]+t[0]),o=.5*(e[1]+t[1]),l=t[1]-e[1],c=e[0]-t[0],u=(e,t)=>l*(e-s)+c*(t-o)>0;for(let e=0;e<r;e+=1)for(let t=0;t<r;t+=1){const s=t/(r-1),o=e/(r-1);u(1+i+s,i+o)&&(n+=1),u(1+i+s,1+i+o)&&(a+=1)}const d=r*r;return[1-n/d,a/d]}(n>0?[e[0],e[1]]:e,a>0?[i[0],i[1]]:i,t),o=(e,t)=>s([1,e],[1+r,t+r]);switch(e){case 0:return mc(o(1,1),o(0,0));case 1:return mc(s([1,0],[r,r]),o(0,0));case 2:return mc(s([0,0],[1+r,r]),o(0,0));case 3:return o(0,0);case 4:return mc(s([1,1],[r,r]),s([1,1],[1+r,r]));case 5:return mc(s([1,1],[r,r]),o(0,0));case 6:return s([1,1],[1+r,r]);case 7:return mc(s([1,1],[1+r,r]),o(0,0));case 8:return mc(s([0,0],[1+r,1+r]),s([1,0],[1+r,1+r]));case 9:return s([1,0],[1+r,1+r]);case 10:return mc(s([0,0],[1+r,1+r]),o(0,0));case 11:return mc(s([1,0],[1+r,1+r]),o(0,0));case 12:return s([1,1],[1+r,1+r]);case 13:return mc(s([1,1],[1+r,1+r]),s([1,0],[1+r,1+r]));case 14:return mc(s([1,1],[1+r,1+r]),s([1,1],[1+r,r]));case 15:return mc(s([1,1],[1+r,1+r]),o(0,0));default:return[0,0]}}function mc(e,t){return[.5*(e[0]+t[0]),.5*(e[1]+t[1])]}function gc(e,t,i){return e+(t-e)*i}function vc(e,t,i){return Math.min(i,Math.max(t,e))}var xc=class{strength;threshold;knee;radius;levels;targetPrefix;passes=new Map;constructor(e={}){var t,i,r;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=Sc(e.radius??.2,0,1),this.levels=(t=e.levels??5,i=1,r=5,Math.floor(Sc(t,i,r))),this.targetPrefix=e.targetPrefix??"bloom"}addPass(e,t,i={}){const r=[];let n=t;for(let t=0;t<this.levels;t+=1){const i=1/2**(t+1),a=e.createColorTarget(`${this.targetPrefix}Horizontal${t}`,{format:"rgba16float",scale:i}),s=e.createColorTarget(`${this.targetPrefix}Vertical${t}`,{format:"rgba16float",scale:i}),o=n,l=`h:${t}:${o}:${a}`;let c=this.passes.get(l);c||(c=0===t?new wc(o,a,this):new bc(`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 bc(`BloomVertical${t}`,a,s,!1,t),this.passes.set(u,d)),e.addFullscreenPass(d),r.push(s),n=s}const a=i.output??e.createColorTarget(`${this.targetPrefix}Color`,{format:"rgba16float"}),s=Object.fromEntries(r.map((e,t)=>[`blur${t}`,e])),o=`composite:${t}:${r.join(":")}:${a}`;let l=this.passes.get(o);return l||(l=new yc(t,s,a,this,this.levels),this.passes.set(o,l)),e.addFullscreenPass(l),a}},wc=class{constructor(e,t,i){this.state=i,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}"},bc=class{constructor(e,t,i,r,n){this.name=e,this.inputs={source:t},this.outputs=i;const a=r?"vec2<f32>(texel.x, 0.0)":"vec2<f32>(0.0, texel.y)",s=(1+.35*n).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},yc=class{constructor(e,t,i,r,n){this.state=r,this.inputs={source:e,...t},this.outputs=i;const a=[1,.8,.6,.4,.2],s=Array.from({length:n},(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,Sc(this.state.radius,0,1),0,0]),this.uniforms);fragmentShader};function Sc(e,t,i){return Math.min(i,Math.max(t,e))}var Cc=[1,1,1],Mc=[0,0,0],Pc=class{options;passes=new Map;targetPrefix;constructor(e={}){this.options=e,this.targetPrefix=e.targetPrefix??"colorGrading"}addPass(e,t){if(!1===this.options.enabled)return t;const i=e.createColorTarget(`${this.targetPrefix}Color`,{format:"rgba16float"}),r=`${t}:${i}`;let n=this.passes.get(r);return n||(n=new Bc(t,i,this.options),this.passes.set(r,n)),e.addFullscreenPass(n),i}},Bc=class{constructor(e,t,i){this.state=i,this.inputs={source:e},this.outputs=t}state;name="ColorGrading";sampler="linear";uniformBufferSize=384;inputs;outputs;uniforms=new Float32Array(this.uniformBufferSize/4);writeVector(e,t){this.uniforms[e]=t[0],this.uniforms[e+1]=t[1],this.uniforms[e+2]=t[2],this.uniforms[e+3]=0}writeRange(e,t){this.writeVector(e,t?.saturation??Cc),this.writeVector(e+4,t?.contrast??Cc),this.writeVector(e+8,t?.gamma??Cc),this.writeVector(e+12,t?.gain??Cc),this.writeVector(e+16,t?.offset??Mc)}updateUniforms=()=>(this.writeVector(0,this.state.whiteBalance??Cc),this.writeVector(4,this.state.tint??Cc),this.writeRange(8,this.state),this.writeRange(28,this.state.shadows),this.writeRange(48,this.state.midtones),this.writeRange(68,this.state.highlights),this.uniforms[88]=this.state.exposure??1,this.uniforms[89]={none:0,linear:1,reinhard:2,cineon:3,aces:4,agx:5,neutral:6}[this.state.toneMapping??"none"],this.uniforms[90]=Math.max(0,this.state.vignetteIntensity??0),this.uniforms[91]=Math.min(1,Math.max(0,this.state.tintIntensity??0)),this.uniforms[92]=this.state.shadowsMax??.09,this.uniforms[93]=this.state.highlightsMin??.5,this.uniforms[94]=!1===this.state.enabled?0:1,this.uniforms[95]=0,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 Dc}from"three";var Ic=class{options;passes=new Map;targetPrefix;constructor(e={}){this.options=e,this.targetPrefix=e.targetPrefix??"depthOfField"}addPass(e,t,i){if(!1===this.options.enabled)return t;const r=e.createColorTarget(`${this.targetPrefix}Color`,{format:"rgba16float"}),n=`${t}:${i}:${r}`;let a=this.passes.get(n);return a||(a=new Tc(t,i,r,this.options),this.passes.set(n,a)),e.addFullscreenPass(a),r}},Tc=class{constructor(e,t,i,r){this.state=r,this.inputs={source:e,sceneDepth:t},this.outputs=i}state;name="DepthOfField";sampler="linear";uniformBufferSize=80;inputs;outputs;uniforms=new Float32Array(20);inverseProjection=new Dc;updateUniforms=e=>(this.inverseProjection.copy(Rc).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); }"},Rc=(new Dc).set(1,0,0,0,0,1,0,0,0,0,.5,.5,0,0,0,1);import{Matrix4 as Vc,Vector2 as Gc,Vector3 as zc}from"three";var Lc=(new Vc).set(1,0,0,0,0,1,0,0,0,0,.5,.5,0,0,0,1),Uc=(e=>(e[e.Disabled=0]="Disabled",e[e.CameraOnly=1]="CameraOnly",e[e.ObjectAndCamera=2]="ObjectAndCamera",e[e.ForceObjectBlur=3]="ForceObjectBlur",e))(Uc||{}),kc={off:{enabled:!1,sampleCount:0},low:{enabled:!0,sampleCount:4,shutterScale:.65,maxBlurPixels:10,cameraBlurScale:.08,objectBlurScale:.8,depthRejectionStrength:28,velocityThresholdPixels:.75,dilation:!1},medium:{enabled:!0,sampleCount:8,shutterScale:.75,maxBlurPixels:18,cameraBlurScale:.1,objectBlurScale:1,depthRejectionStrength:24,velocityThresholdPixels:.6,dilation:!0},high:{enabled:!0,sampleCount:12,shutterScale:.85,maxBlurPixels:24,cameraBlurScale:.12,objectBlurScale:1.1,depthRejectionStrength:20,velocityThresholdPixels:.45,dilation:!0}},Ac=class{options;targetPrefix;currentViewProjection=new Vc;currentInverseViewProjection=new Vc;currentInverseProjection=new Vc;previousViewProjection=new Vc;pendingViewProjection=new Vc;previousProjection=new Vc;previousCameraWorld=new Vc;previousCameraPosition=new zc;currentCameraPosition=new zc;currentJitterUv=new Gc;historyValid=!1;pendingCamera=!1;width=1;height=1;timeSeconds=0;frameDuration=1/60;previousTimeSeconds=Number.NaN;nextOverrideId=1;overrides=[];passes=new Map;constructor(e={}){this.options={enabled:e.enabled??!0,sampleCount:Oc(e.sampleCount??8),shutterScale:Ec(e.shutterScale??.75,0,4),maxBlurPixels:Ec(e.maxBlurPixels??18,0,128),cameraBlurScale:Ec(e.cameraBlurScale??.1,0,4),objectBlurScale:Ec(e.objectBlurScale??1,0,8),depthRejectionStrength:Ec(e.depthRejectionStrength??24,0,200),velocityThresholdPixels:Ec(e.velocityThresholdPixels??.6,0,16),dilation:e.dilation??!0,debugVelocity:e.debugVelocity??!1,targetFrameRate:Ec(e.targetFrameRate??60,15,240),maxFrameTime:Ec(e.maxFrameTime??.1,1/240,1),cameraCutDistance:Ec(e.cameraCutDistance??8,0,1e3),cameraCutRotationThreshold:Ec(e.cameraCutRotationThreshold??.75,0,2),projectionCutThreshold:Ec(e.projectionCutThreshold??.25,0,4)},this.targetPrefix=e.targetPrefix??"motionBlur"}applyPreset(e){Object.assign(this.options,kc[e]),this.options.sampleCount=Oc(this.options.sampleCount)}prepareCamera(e,t,i,r){t===this.width&&i===this.height||(this.width=Math.max(1,t),this.height=Math.max(1,i),this.reset());const n=r-this.previousTimeSeconds;Number.isFinite(n)&&n>0&&(this.frameDuration=Math.min(n,this.options.maxFrameTime),n>this.options.maxFrameTime&&this.reset()),this.previousTimeSeconds=r,this.timeSeconds=r,this.pruneOverrides(),e.getWorldPosition(this.currentCameraPosition),this.historyValid&&(this.currentCameraPosition.distanceTo(this.previousCameraPosition)>this.options.cameraCutDistance||function(e,t){let i=0;const r=[0,1,2,4,5,6,8,9,10];for(const n of r)i=Math.max(i,Math.abs(e.elements[n]-t.elements[n]));return i}(e.matrixWorld,this.previousCameraWorld)>this.options.cameraCutRotationThreshold||function(e,t){let i=0;for(let r=0;r<16;r+=1)i=Math.max(i,Math.abs(e.elements[r]-t.elements[r]));return i}(e.projectionMatrix,this.previousProjection)>this.options.projectionCutThreshold)&&this.reset(),this.pendingViewProjection.copy(Lc).multiply(e.projectionMatrix).multiply(e.matrixWorldInverse),this.currentViewProjection.copy(this.pendingViewProjection),this.currentInverseViewProjection.copy(this.currentViewProjection).invert(),this.currentInverseProjection.copy(Lc).multiply(e.projectionMatrix).invert(),this.historyValid||this.previousViewProjection.copy(this.currentViewProjection),this.pendingCamera=!0,this.previousProjection.copy(e.projectionMatrix),this.previousCameraWorld.copy(e.matrixWorld),this.previousCameraPosition.copy(this.currentCameraPosition)}commitCamera(){this.pendingCamera&&(this.previousViewProjection.copy(this.pendingViewProjection),this.historyValid=!0,this.pendingCamera=!1)}setJitterUv(e,t){this.currentJitterUv.set(Number.isFinite(e)?e:0,Number.isFinite(t)?t:0)}reset(){this.historyValid=!1,this.pendingCamera=!1}requiresRendererHistoryReset(){return!this.historyValid}pushOverride(e){const t=this.nextOverrideId++,i=Math.max(0,e.duration);return this.overrides.push({id:t,startTime:this.timeSeconds,endTime:this.timeSeconds+i,options:e}),{id:t,cancel:()=>{const e=this.overrides.findIndex(e=>e.id===t);e>=0&&this.overrides.splice(e,1)}}}addPass(e,t,i,r=e.mainDepth){const n=this.getResolvedSettings();if(!n.enabled||0===n.sampleCount)return t;const a=e.createColorTarget(`${this.targetPrefix}Color`,{format:"rgba16float"}),s=Oc(n.sampleCount),o=`${t}:${i}:${r}:${a}:${s}`;let l=this.passes.get(o);return l||(l=new Fc(t,i,r,a,s,this),this.passes.set(o,l)),l.settings=n,e.addFullscreenPass(l),a}dispose(){this.passes.clear(),this.overrides.length=0}getTemporalMatrices(){return{currentInverseViewProjection:this.currentInverseViewProjection,currentInverseProjection:this.currentInverseProjection,previousViewProjection:this.previousViewProjection}}getFrameDuration(){return this.frameDuration}getJitterUv(){return this.currentJitterUv}pruneOverrides(){for(let e=this.overrides.length-1;e>=0;e-=1)this.overrides[e].endTime<=this.timeSeconds&&this.overrides.splice(e,1)}getResolvedSettings(){const e={...this.options};for(const t of this.overrides){const i=t.options;null!=i.enabled&&(e.enabled||=i.enabled),null!=i.sampleCount&&(e.sampleCount=Math.max(e.sampleCount,Oc(i.sampleCount))),null!=i.shutterScale&&(e.shutterScale=Math.max(e.shutterScale,i.shutterScale)),null!=i.maxBlurPixels&&(e.maxBlurPixels=Math.max(e.maxBlurPixels,i.maxBlurPixels)),null!=i.cameraBlurScale&&(e.cameraBlurScale=Math.max(e.cameraBlurScale,i.cameraBlurScale)),null!=i.objectBlurScale&&(e.objectBlurScale=Math.max(e.objectBlurScale,i.objectBlurScale)),null!=i.dilation&&(e.dilation||=i.dilation),null!=i.debugVelocity&&(e.debugVelocity||=i.debugVelocity)}return e}},Fc=class{constructor(e,t,i,r,n,a){this.state=a,this.name=`MotionBlurResolve${n}`,this.inputs={source:e,velocity:t,depth:i},this.outputs=r,this.settings=a.options,this.fragmentShader=function(e){return`\nfn currentInverseViewProjection() -> mat4x4<f32> {\n return mat4x4<f32>(\n fullscreenUniforms[0], fullscreenUniforms[1],\n fullscreenUniforms[2], fullscreenUniforms[3]\n );\n}\n\nfn previousViewProjection() -> mat4x4<f32> {\n return mat4x4<f32>(\n fullscreenUniforms[4], fullscreenUniforms[5],\n fullscreenUniforms[6], fullscreenUniforms[7]\n );\n}\n\nfn currentInverseProjection() -> mat4x4<f32> {\n return mat4x4<f32>(\n fullscreenUniforms[8], fullscreenUniforms[9],\n fullscreenUniforms[10], fullscreenUniforms[11]\n );\n}\n\nfn uvToNdc(uv: vec2<f32>, depth: f32) -> vec4<f32> {\n let unjitteredUv = uv - fullscreenUniforms[14].xy;\n return vec4<f32>(\n unjitteredUv.x * 2.0 - 1.0,\n (0.5 - unjitteredUv.y) * 2.0,\n depth,\n 1.0\n );\n}\n\nfn viewDepth(uv: vec2<f32>, depth: f32) -> f32 {\n let view = currentInverseProjection() * uvToNdc(uv, depth);\n return abs(view.z / max(abs(view.w), 1e-6));\n}\n\nfn depthAt(uv: vec2<f32>) -> f32 {\n let dimensions = vec2<i32>(textureDimensions(depthTexture));\n let pixel = clamp(\n vec2<i32>(uv * vec2<f32>(dimensions)),\n vec2<i32>(0),\n dimensions - vec2<i32>(1)\n );\n return textureLoad(depthTexture, pixel, 0);\n}\n\nfn cameraVelocity(uv: vec2<f32>, depth: f32) -> vec2<f32> {\n let worldH = currentInverseViewProjection() * uvToNdc(uv, depth);\n let world = worldH / max(abs(worldH.w), 1e-6);\n let previousClip = previousViewProjection() * world;\n let previousNdc = previousClip.xy / max(abs(previousClip.w), 1e-6);\n let previousUv = previousNdc * vec2<f32>(0.5, -0.5) + vec2<f32>(0.5);\n return (uv - fullscreenUniforms[14].xy) - previousUv;\n}\n\nfn scaledVelocity(uv: vec2<f32>, packed: vec4<f32>, depth: f32) -> vec2<f32> {\n let camera = cameraVelocity(uv, depth);\n let objectRelative = packed.xy - camera;\n let mode = i32(round(packed.z));\n if (mode == 0) { return vec2<f32>(0.0); }\n if (mode == 1) {\n return camera * fullscreenUniforms[12].z;\n }\n let forceScale = select(1.0, 1.35, mode == 3);\n return camera * fullscreenUniforms[12].z +\n objectRelative * fullscreenUniforms[12].w * packed.w * forceScale;\n}\n\nfn chooseDilatedVelocity(\n uv: vec2<f32>,\n centerDepthRaw: f32,\n texel: vec2<f32>\n) -> vec2<f32> {\n let centerPacked = textureSampleLevel(velocityTexture, fullscreenSampler, uv, 0.0);\n var best = scaledVelocity(uv, centerPacked, centerDepthRaw);\n if (fullscreenUniforms[13].z < 0.5) { return best; }\n let centerDepth = viewDepth(uv, centerDepthRaw);\n for (var y = -1; y <= 1; y += 1) {\n for (var x = -1; x <= 1; x += 1) {\n let sampleUv = clamp(uv + vec2<f32>(f32(x), f32(y)) * texel, vec2<f32>(0.0), vec2<f32>(1.0));\n let sampleDepthRaw = depthAt(sampleUv);\n let sampleDepth = viewDepth(sampleUv, sampleDepthRaw);\n let depthSimilarity = abs(sampleDepth - centerDepth) / max(centerDepth, 1e-3);\n if (depthSimilarity < 0.025 || sampleDepth <= centerDepth) {\n let candidatePacked = textureSampleLevel(velocityTexture, fullscreenSampler, sampleUv, 0.0);\n let candidate = scaledVelocity(sampleUv, candidatePacked, sampleDepthRaw);\n if (dot(candidate, candidate) > dot(best, best)) { best = candidate; }\n }\n }\n }\n return best;\n}\n\n@fragment\nfn fsMain(input: FullscreenVertexOutput) -> @location(0) vec4<f32> {\n let centerColor = textureSampleLevel(sourceTexture, fullscreenSampler, input.uv, 0.0);\n let dimensions = vec2<f32>(textureDimensions(sourceTexture));\n let texel = 1.0 / dimensions;\n let centerDepthRaw = depthAt(input.uv);\n let centerDepth = viewDepth(input.uv, centerDepthRaw);\n var blurUv = chooseDilatedVelocity(input.uv, centerDepthRaw, texel) * fullscreenUniforms[12].x;\n let velocityPixels = length(blurUv * dimensions);\n\n if (fullscreenUniforms[13].w > 0.5) {\n let debugMagnitude = clamp(\n velocityPixels / max(fullscreenUniforms[12].y, 1.0),\n 0.0,\n 1.0\n );\n // Black means stationary. Moving pixels become brighter; R/G retain the\n // signed horizontal/vertical mapping around 0.5 and B shows magnitude.\n let directionColor = vec3<f32>(\n 0.5 + 0.5 * clamp(blurUv.x * 32.0, -1.0, 1.0),\n 0.5 + 0.5 * clamp(blurUv.y * 32.0, -1.0, 1.0),\n 1.0\n ) * debugMagnitude;\n return vec4<f32>(directionColor, 1.0);\n }\n\n let threshold = fullscreenUniforms[13].y;\n if (velocityPixels <= threshold) { return centerColor; }\n let maxBlurUv = fullscreenUniforms[12].y / max(dimensions.x, dimensions.y);\n let blurLength = length(blurUv);\n if (blurLength > maxBlurUv) { blurUv *= maxBlurUv / blurLength; }\n\n let activeSamples = clamp(\n i32(ceil(velocityPixels / max(threshold, 0.25))),\n 2,\n ${e}\n );\n var accumulated = centerColor;\n var totalWeight = 1.0;\n for (var sampleIndex = 0; sampleIndex < ${e}; sampleIndex += 1) {\n if (sampleIndex >= activeSamples) { continue; }\n let t = (f32(sampleIndex) + 0.5) / f32(activeSamples);\n let sampleUv = clamp(\n input.uv + mix(-0.5, 0.5, t) * blurUv,\n vec2<f32>(0.0),\n vec2<f32>(1.0)\n );\n let sampleDepthRaw = depthAt(sampleUv);\n let sampleDepth = viewDepth(sampleUv, sampleDepthRaw);\n let relativeDifference = abs(sampleDepth - centerDepth) / max(centerDepth, 1e-3);\n let depthWeight = exp(-relativeDifference * fullscreenUniforms[13].x);\n let sampleColor = textureSampleLevel(sourceTexture, fullscreenSampler, sampleUv, 0.0);\n accumulated += sampleColor * depthWeight;\n totalWeight += depthWeight;\n }\n return accumulated / max(totalWeight, 1e-4);\n}\n`}(n)}state;name;sampler="linear";uniformBufferSize=256;inputs;outputs;fragmentShader;settings;uniforms=new Float32Array(64);updateUniforms=()=>{const e=this.state.getTemporalMatrices();this.uniforms.set(e.currentInverseViewProjection.elements,0),this.uniforms.set(e.previousViewProjection.elements,16),this.uniforms.set(e.currentInverseProjection.elements,32);const t=1/this.settings.targetFrameRate/Math.max(this.state.getFrameDuration(),.001);this.uniforms.set([this.settings.shutterScale*t,this.settings.maxBlurPixels,this.settings.cameraBlurScale,this.settings.objectBlurScale,this.settings.depthRejectionStrength,this.settings.velocityThresholdPixels,this.settings.dilation?1:0,this.settings.debugVelocity?1:0],48);const i=this.state.getJitterUv();return this.uniforms[56]=i.x,this.uniforms[57]=i.y,this.uniforms}};function Oc(e){return e<=0?0:e<=4?4:e<=8?8:e<=12?12:16}function Ec(e,t,i){return Math.min(i,Math.max(t,e))}var jc=class{enabled;visibleEdgeColor;edgeStrength;edgeThickness;edgeSoftness;selectedObjects=new Set;selectionMembers=new Set;addSelectionMember=e=>{this.selectionMembers.add(e)};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??.6),this.edgeSoftness=Math.max(0,e.edgeSoftness??.6),this.targetPrefix=e.targetPrefix??"outline",this.maskMaterial=$c(!1),this.skinnedMaskMaterial=$c(!0)}setSelectedObjects(e){this.selectionMembers.clear(),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 i=e.createColorTarget(`${this.targetPrefix}Mask`,{format:"rgba8unorm"}),r=this.selectionMembers;r.clear();for(const e of this.selectedObjects)r.has(e)||e.traverse(this.addSelectionMember);e.addMaterialPass({name:"OutlineMask",outputs:i,clearColor:[0,0,0,0],loadDepth:!0,objectFilter:e=>null!==e&&r.has(e),overrideMaterial:(e,t)=>t?this.skinnedMaskMaterial:this.maskMaterial});for(let t=0;t<this.selectedInstances.length;t+=1){const r=this.selectedInstances[t];let n=this.instanceMaskMaterials.get(r.instanceIndex);n||(n=[$c(!1,r.instanceIndex),$c(!0,r.instanceIndex)],this.instanceMaskMaterials.set(r.instanceIndex,n)),e.addMaterialPass({name:`OutlineInstanceMask${t}-${r.instanceIndex}`,outputs:i,loadColor:!0,loadDepth:!0,objectFilter:e=>e===r.object,overrideMaterial:(e,t)=>t?n[1]:n[0]})}const n=e.createColorTarget(`${this.targetPrefix}Edge`,{format:"rgba16float"}),a=e.createColorTarget(`${this.targetPrefix}BlurHorizontal`,{format:"rgba16float"}),s=e.createColorTarget(`${this.targetPrefix}Blurred`,{format:"rgba16float"}),o=e.createColorTarget(`${this.targetPrefix}Color`,{format:"rgba16float"});return this.addCachedPass(e,`edge:${i}:${n}`,()=>new Wc(i,n,this)),this.addCachedPass(e,`blur-h:${n}:${a}`,()=>new Nc("OutlineBlurHorizontal",n,a,!0,this)),this.addCachedPass(e,`blur-v:${a}:${s}`,()=>new Nc("OutlineBlurVertical",a,s,!1,this)),this.addCachedPass(e,`composite:${t}:${s}:${o}`,()=>new _c(t,s,o,this)),o}addCachedPass(e,t,i){let r=this.passes.get(t);r||(r=i(),this.passes.set(t,r)),e.addFullscreenPass(r)}dispose(){this.selectionMembers.clear(),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 $c(e,t=-1){return new pr({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:!1})}var Wc=class{constructor(e,t,i){this.state=i,this.inputs={mask:e},this.outputs=t}state;name="OutlineEdge";sampler="linear";uniformBufferSize=16;inputs;outputs;uniforms=new Float32Array(4);updateUniforms=()=>(this.uniforms.set([this.state.edgeThickness,0,0,0]),this.uniforms);fragmentShader="\n@fragment fn fsMain(input: FullscreenVertexOutput) -> @location(0) vec4<f32> {\n let texel = 1.0 / vec2<f32>(textureDimensions(maskTexture));\n let radius = max(fullscreenUniforms[0].x, 0.5);\n let center = textureSample(maskTexture, fullscreenSampler, input.uv).r;\n let diagonalRadius = radius * 0.70710678;\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 let diagonalOffset = texel * diagonalRadius;\n around = max(around, textureSample(maskTexture, fullscreenSampler, input.uv + diagonalOffset).r);\n around = max(around, textureSample(maskTexture, fullscreenSampler, input.uv - diagonalOffset).r);\n around = max(around, textureSample(maskTexture, fullscreenSampler, input.uv + vec2(diagonalOffset.x, -diagonalOffset.y)).r);\n around = max(around, textureSample(maskTexture, fullscreenSampler, input.uv + vec2(-diagonalOffset.x, diagonalOffset.y)).r);\n let edge = clamp(around - center, 0.0, 1.0);\n return vec4(edge, edge, edge, 1.0);\n}"},Nc=class{constructor(e,t,i,r,n){this.name=e,this.horizontal=r,this.state=n,this.inputs={source:t},this.outputs=i}name;horizontal;state;sampler="linear";uniformBufferSize=16;inputs;outputs;uniforms=new Float32Array(4);updateUniforms=()=>(this.uniforms.set([this.state.edgeSoftness,this.horizontal?1:0,0,0]),this.uniforms);fragmentShader="\n@fragment fn fsMain(input: FullscreenVertexOutput) -> @location(0) vec4<f32> {\n let texel = 1.0 / vec2<f32>(textureDimensions(sourceTexture));\n let spread = max(fullscreenUniforms[0].x, 0.01);\n let axis = mix(vec2<f32>(0.0, texel.y), vec2<f32>(texel.x, 0.0), fullscreenUniforms[0].y) * spread;\n var value = textureSample(sourceTexture, fullscreenSampler, input.uv).r * 0.227027;\n value += textureSample(sourceTexture, fullscreenSampler, input.uv + axis * 1.384615).r * 0.316216;\n value += textureSample(sourceTexture, fullscreenSampler, input.uv - axis * 1.384615).r * 0.316216;\n value += textureSample(sourceTexture, fullscreenSampler, input.uv + axis * 3.230769).r * 0.070270;\n value += textureSample(sourceTexture, fullscreenSampler, input.uv - axis * 3.230769).r * 0.070270;\n return vec4(value, value, value, 1.0);\n}"},_c=class{constructor(e,t,i,r){this.state=r,this.inputs={source:e,edge:t},this.outputs=i}state;name="OutlineComposite";sampler="linear";uniformBufferSize=16;inputs;outputs;uniforms=new Float32Array(4);updateUniforms=()=>(this.uniforms.set([this.state.visibleEdgeColor[0],this.state.visibleEdgeColor[1],this.state.visibleEdgeColor[2],this.state.edgeStrength]),this.uniforms);fragmentShader="\n@fragment fn fsMain(input: FullscreenVertexOutput) -> @location(0) vec4<f32> {\n let scene = textureSample(sourceTexture, fullscreenSampler, input.uv);\n let edge = textureSample(edgeTexture, fullscreenSampler, input.uv).r;\n let color = fullscreenUniforms[0].rgb * fullscreenUniforms[0].a;\n return vec4(scene.rgb + color * edge, scene.a);\n}"};import{AmbientLight as Hc,BackSide as qc,Bone as Kc,BatchedMesh as Yc,BoxGeometry as Zc,BufferAttribute as Xc,BufferGeometry as Jc,CanvasTexture as Qc,Color as eu,CompressedArrayTexture as tu,CompressedArrayTexture as iu,CompressedCubeTexture as ru,CompressedTexture as nu,CubeTexture as au,Data3DTexture as su,DataArrayTexture as ou,DataTexture as lu,DepthTexture as cu,DirectionalLight as uu,DoubleSide as du,FrontSide as hu,Group as pu,HemisphereLight as fu,InstancedMesh as mu,MathUtils as gu,Matrix4 as vu,Mesh as xu,Object3D as wu,OrthographicCamera as bu,PerspectiveCamera as yu,PlaneGeometry as Su,PointLight as Cu,RepeatWrapping as Mu,Scene as Pu,Skeleton as Bu,SkinnedMesh as Du,SphereGeometry as Iu,SpotLight as Tu,Texture as Ru,Vector2 as Vu,Vector3 as Gu,Vector4 as zu}from"three";export{Hc as AmbientLight,qc as BackSide,Yc as BatchedMesh,xc as BloomEffect,Kc as Bone,Zc as BoxGeometry,Xc as BufferAttribute,Jc as BufferGeometry,Qc as CanvasTexture,eu as Color,Pc as ColorGradingEffect,tu as CompressedArrayTexture,ru as CompressedCubeTexture,nu as CompressedTexture,iu as CompressedTextureArray,_ as ComputeKernel,au as CubeTexture,hr as DEFAULT_WGSL_VERTEX_ATTRIBUTES,su as Data3DTexture,ou as DataArrayTexture,lu as DataTexture,Ic as DepthOfFieldEffect,cu as DepthTexture,uu as DirectionalLight,du as DoubleSide,Yl as FXAAEffect,ki as FrameGraphBuilder,hu as FrontSide,Sl as GTAOEffect,yl as GTAO_PRESETS,pu as Group,fu as HemisphereLight,mu as InstancedMesh,kc as MOTION_BLUR_PRESETS,gu as MathUtils,vu as Matrix4,xu as Mesh,Ac as MotionBlurEffect,Uc as MotionBlurMode,wu as Object3D,bu as OrthographicCamera,jc as OutlineEffect,yu as PerspectiveCamera,Su as PlaneGeometry,Cu as PointLight,qa as RenderGraph,Mu as RepeatWrapping,D as SCENE_COLOR_FORMAT,fe as SDFGI,ve as SDFGISurfaceCapture,ac as SMAAEffect,Ll as SSREffect,Pu as Scene,Bu as Skeleton,Du as SkinnedMesh,Iu as SphereGeometry,Tu as SpotLight,_l as TemporalAAEffect,Ru as Texture,We as VOLUMETRIC_FOG_MATERIAL_WGSL,De as VOLUMETRIC_FOG_PRESETS,Vu as Vector2,Gu as Vector3,zu as Vector4,ke as VolumetricFogEffect,Be as VolumetricFogVolumeObject,pr as WGSLShaderMaterial,rs as WebGpuPMREMGenerator,pl as WebGpuRenderer,gs as buildParticleLightingShaderHeader,Ne as configureVolumetricFogMaterial,N as createComputePipelineAsync,W as createRenderPipelineAsync,_i as disposeExternalSkeletonPalette,yn as disposeSkinnedMeshResources,i as registerPipelineDiagnosticOrigin,f as resolveDetailCulling,Hi as setExternalSkeletonPalette,d as setObjectDetailCulling,t as setPipelineDiagnosticLoading};
|