XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet

XFE.SpaceEngineers.AgentBridge

【SpaceEngineer】AI调试插件

公开
关注 0 Fork 0 Star 0
UTF-8
// XFE's local hybrid path integrator. No proprietary engine shaders or SDK code.
RaytracingAccelerationStructure scene : register(t0);
Texture2D<float4> positions : register(t1);
Texture2D<float4> normals : register(t2);
RWTexture2D<float4> result : register(u0);
RWTexture2D<float4> reflected : register(u1);
RWTexture2D<float4> indirect : register(u2);
RWTexture2D<float4> glassReflected : register(u3);
RWTexture2D<float4> glassData : register(u4);
RWTexture2D<float4> filtered : register(u5);
RWTexture2D<float4> glassRefracted : register(u6);
RWTexture2D<float4> moments : register(u7);
RWTexture2D<float4> filteredReflection : register(u8);
RWTexture2D<float4> glassSharp : register(u10);
RWTexture2D<float4> glassGuide : register(u11);
RWTexture2D<float4> glassRaw : register(u12);
RWTexture2D<float4> glassNormal : register(u13);
RWTexture2D<float4> glassFactor : register(u14);
struct Vertex { float3 position; float2 uv; float3 tint; };
struct InstanceMaterial { uint triangleOffset; float3 tint; row_major float3x4 previousTransform; uint previousValid; uint3 reserved; };
struct GlassMaterial { float4 transmission, optics; };
StructuredBuffer<Vertex> vertices : register(t3);
StructuredBuffer<uint4> triangles : register(t4);
StructuredBuffer<InstanceMaterial> instances : register(t5);
Texture2D<float4> previousPositions : register(t6);
Texture2D<float4> previousNormals : register(t7);
Texture2D<float4> previousReflections : register(t8);
Texture2D<float4> previousIndirect : register(t9);
Texture2D<float4> colorTextures[1024] : register(t10);
StructuredBuffer<GlassMaterial> glassMaterials : register(t1034);
struct Light { float4 positionRange,colorIntensity,directionCone,settings; };
StructuredBuffer<Light> lights : register(t1035);
Texture2D<float4> previousGlassData : register(t1036);
Texture2D<float4> previousGlassReflections : register(t1037);
Texture2D<float4> previousMoments : register(t1038);
struct SurfaceMaterial { float4 colorEmission; uint texture,flags; uint2 reserved; };
StructuredBuffer<SurfaceMaterial> surfaceMaterials : register(t1039);
Texture2D<float4> environmentMap : register(t1040);
Texture2D<float4> surfaceGuide : register(t1041);
Texture2D<float4> previousSurfaceGuide : register(t1042);
Texture2D<float4> previousGlassGuide : register(t1043);
Texture2D<float4> previousGlassNormal : register(t1044);
RWStructuredBuffer<float> environmentCdf : register(u9);
SamplerState linearWrap : register(s0);
cbuffer Parameters : register(b0) {
    row_major float4x4 inverseViewProjection;
    row_major float4x4 inverseView;
    float4 originDelta, sunDirection, settings;
    uint4 sizes;
    float4 sunColor, effects;
    row_major float4x4 previousViewProjection;
    float4 previousCamera, originChange, history, transport;
    row_major float4x4 viewProjection;
    float4 pathSettings, environmentSettings;
};
cbuffer FilterParameters : register(b1) { uint filterStep; };
static const float PI=3.14159265359;
static const uint GLASS=0x40000000, VOXEL=0x80000000;
struct Hit { float3 p,n,albedo,emission,previousP,previousN; float metal,rough,t; uint flags,glass,previousValid; };
float Random(inout uint state) { state=state*747796405u+2891336453u; uint v=((state>>((state>>28u)+4u))^state)*277803737u; v=(v>>22u)^v;return (v>>8)*0.000000059604644775; }
float Luma(float3 v) { return dot(v,float3(.2126,.7152,.0722)); }
float2 EncodeGeometricNormal(float3 n) {
    n/=max(dot(abs(n),1),1e-6);float2 v=n.xy;
    if(n.z<0)v=(1-abs(v.yx))*float2(v.x>=0?1:-1,v.y>=0?1:-1);
    return v;
}
float3 DecodeGeometricNormal(float2 v) {
    float3 n=float3(v,1-abs(v.x)-abs(v.y));float t=saturate(-n.z);
    n.xy+=float2(n.x>=0?-t:t,n.y>=0?-t:t);return normalize(n);
}
float3 CameraRay(uint2 pixel,float4 position) {
    // Perspective rays need the exact pixel center. Dividing the packed
    // FP16 world position by its length moves rays across subpixel geometry.
    // An orthographic/identity projection has no common perspective origin.
    bool perspective=abs(viewProjection[3][3])<1e-6
        && any(abs(float3(viewProjection[0][3],viewProjection[1][3],viewProjection[2][3]))>1e-6);
    if(position.w>0 && !perspective)return normalize(position.xyz-originDelta.xyz);
    uint2 source=min(uint2((float2(pixel)+.5)*float2(sizes.xy)/sizes.zw),sizes.xy-1);
    float2 uv=(float2(source)+.5)/sizes.xy;
    float4 nearPoint=mul(float4(uv.x*2-1,1-uv.y*2,1,1),inverseViewProjection);
    return normalize(nearPoint.xyz/nearPoint.w);
}
void Basis(float3 n,out float3 t,out float3 b) { t=normalize(cross(abs(n.z)<.9?float3(0,0,1):float3(0,1,0),n));b=cross(n,t); }
float3 Cosine(float3 n,inout uint rng) { float3 t,b;Basis(n,t,b);float r=sqrt(Random(rng)),a=2*PI*Random(rng);return t*(r*cos(a))+b*(r*sin(a))+n*sqrt(1-r*r); }
float3 Fresnel(float3 f0,float cosine) { return f0+(1-f0)*pow(1-saturate(cosine),5); }
float Dielectric(float cosine,float ior) {
    // Exact unpolarized dielectric Fresnel (air -> glass), including grazing.
    float c=saturate(cosine),ct=sqrt(saturate(1-(1-c*c)/(ior*ior)));
    float rs=(c-ior*ct)/max(c+ior*ct,1e-5),rp=(ior*c-ct)/max(ior*c+ct,1e-5);
    return saturate((rs*rs+rp*rp)*.5);
}
float4 Tex(uint index,float2 uv) { return index==0?float4(.28,.28,.28,0):colorTextures[NonUniformResourceIndex(index)].SampleLevel(linearWrap,uv,1); }
float4 VoxelTex(Vertex v,float3 p,float3 weights) {
    uint xz=(uint)v.tint.x,y=(uint)v.tint.y;
    p*=max(v.tint.z,.001);
    return Tex(xz,p.yz)*weights.x+Tex(y==0?xz:y,p.xz)*weights.y+Tex(xz,p.xy)*weights.z;
}
bool Closest(float3 origin,float3 direction,float range,out Hit hit,bool shade=true) {
    hit=(Hit)0;
    if(range<=.004) return false;
    RayDesc ray;ray.Origin=origin;ray.Direction=direction;ray.TMin=.003;ray.TMax=range;
    // Closest-hit traversal is intentional. Dielectrics are classified after
    // each ordered hit and rays continue through them; never first-hit-occlude
    // a pane as if it were opaque.
    RayQuery<RAY_FLAG_FORCE_OPAQUE> q;
    InstanceMaterial instance;uint4 tri;SurfaceMaterial surface;bool visible=false;
    [loop] for(uint layer=0;layer<8;layer++) {
        q.TraceRayInline(scene,RAY_FLAG_NONE,0xff,ray);while(q.Proceed()) {}
        if(q.CommittedStatus()==COMMITTED_NOTHING)return false;
        instance=instances[q.CommittedInstanceID()];tri=triangles[instance.triangleOffset+q.CommittedPrimitiveIndex()];
        surface=surfaceMaterials[(tri.w&(GLASS|VOXEL))?0:((tri.w>>20)&1023)];
        if(!(surface.flags&8)) {visible=true;break;}
        ray.TMin=q.CommittedRayT()+.001;if(ray.TMin>=ray.TMax)return false;
    }
    if(!visible)return false;
    Vertex a=vertices[tri.x],b=vertices[tri.y],c=vertices[tri.z];
    float2 bary=q.CommittedTriangleBarycentrics();float3 w=float3(1-bary.x-bary.y,bary);
    float3 localNormal=normalize(cross(b.position-a.position,c.position-a.position));
    hit.n=normalize(mul(localNormal,(float3x3)q.CommittedWorldToObject3x4()));
    if(dot(hit.n,direction)>0) hit.n=-hit.n;
    hit.t=q.CommittedRayT();hit.p=origin+direction*hit.t;
    float3 modelPoint=a.position*w.x+b.position*w.y+c.position*w.z;
    hit.previousP=history.z>0?mul(instance.previousTransform,float4(modelPoint,1)):hit.p+originChange.xyz;hit.flags=tri.w&(GLASS|VOXEL);hit.glass=(tri.w>>20)&1023;
    hit.previousValid=history.z>0?instance.previousValid:1;
    hit.previousN=history.z>0?normalize(mul((float3x3)instance.previousTransform,localNormal)):hit.n;
    if(dot(hit.previousN,hit.n)<0)hit.previousN=-hit.previousN;
    if(!shade || (hit.flags&GLASS)) return true;
    float2 uv=a.uv*w.x+b.uv*w.y+c.uv*w.z;
    float4 cm;
    if(hit.flags&VOXEL) {
        float3 p=a.position*w.x+b.position*w.y+c.position*w.z;
        float3 blend=pow(abs(localNormal),4);blend/=max(dot(blend,1),1e-5);
        cm=VoxelTex(a,p,blend)*w.x+VoxelTex(b,p,blend)*w.y+VoxelTex(c,p,blend)*w.z;
        hit.albedo=cm.rgb;
    } else {
        cm=(surface.flags&2)?colorTextures[NonUniformResourceIndex(surface.texture)].SampleLevel(linearWrap,saturate(uv),0):Tex(tri.w&1023,uv);
        if(surface.flags&4)cm.a=0; // generated LCD alpha is opacity, not metalness
        uint extra=(tri.w>>10)&1023;
        float4 extensions=extra==0?0:colorTextures[NonUniformResourceIndex(extra)].SampleLevel(linearWrap,uv,0);
        float mask=(surface.flags&4)?0:extensions.a;
        float brightness=max(cm.r,max(cm.g,cm.b));
        float value=brightness<=.0031308?brightness*12.92:1.055*pow(brightness,1/2.4)-.055;
        float3 tint=a.tint*w.x+b.tint*w.y+c.tint*w.z+instance.tint;
        float3 hsv=saturate(float3(0,0,value)+tint);
        float3 hue=saturate(abs(frac(hsv.x+float3(0,2.0/3,1.0/3))*6-3)-1);
        float3 painted=hsv.z*lerp(1,hue,hsv.y);
        painted=lerp(painted/12.92,pow((painted+.055)/1.055,2.4),step(.04045,painted));
        hit.albedo=lerp(cm.rgb,painted,mask*(1-cm.a));
        if(surface.flags&1)hit.albedo*=surface.colorEmission.rgb;
        float emissivity=(surface.flags&4)?1:saturate(extensions.g-1.0/255);
        hit.emission=hit.albedo*emissivity*((surface.flags&1)?surface.colorEmission.a:1);
    }
    hit.metal=cm.a;hit.rough=(hit.flags&VOXEL)?.85:.4;
    return true;
}
float3 PaneTransmission(Hit h,float3 d) {
    GlassMaterial g=glassMaterials[h.glass];
    float ct=sqrt(saturate(1-(1-pow(dot(h.n,d),2))/(g.optics.x*g.optics.x)));
    // Beer-Lambert distance correction for grazing rays through a thin slab.
    return pow(max(g.transmission.rgb,.001),1/max(ct,.1))*(1-Dielectric(abs(dot(h.n,d)),g.optics.x));
}
float3 Visibility(float3 origin,float3 direction,float range) {
    float3 t=1;
    [loop] for(uint layer=0;layer<12;layer++) {
        Hit h;if(!Closest(origin,direction,range,h,false)) return t;
        if(!(h.flags&GLASS)) return 0;
        if(transport.z>0) t*=PaneTransmission(h,direction);
        range-=h.t+.012;origin=h.p+direction*.012;
        if(range<=.004) return t;
    }
    return 0; // bounded traversal: never leak light through an unexamined stack
}
float G1(float nv,float a2) { return 2*nv/max(nv+sqrt(a2+(1-a2)*nv*nv),1e-5); }
float3 Bsdf(Hit h,float3 view,float3 light) {
    float nv=saturate(dot(h.n,view)),nl=saturate(dot(h.n,light));
    if(nv<=0 || nl<=0) return 0;
    float3 halfVector=normalize(view+light);float nh=saturate(dot(h.n,halfVector));
    float a=max(h.rough*h.rough,.002),a2=a*a,d=a2/(PI*pow(nh*nh*(a2-1)+1,2));
    float3 f=Fresnel(lerp(.04,h.albedo,h.metal),dot(view,halfVector));
    return (1-f)*(1-h.metal)*h.albedo/PI+f*(d*G1(nv,a2)*G1(nl,a2)/max(4*nv*nl,1e-5));
}
float SpecularProbability(Hit h,float3 view) {
    // Choose lobes by their material energy. A conductor has no diffuse lobe;
    // the former fixed 75% GGX / 25% cosine mix wasted a quarter of samples
    // and produced alternating dark/bright estimates on cockpit metal.
    float3 f=Fresnel(lerp(.04,h.albedo,h.metal),saturate(dot(h.n,view)));
    float specular=max(Luma(f),0),diffuse=max(Luma((1-f)*(1-h.metal)*h.albedo),0);
    if(diffuse<1e-6)return 1;
    return clamp(specular/max(specular+diffuse,1e-6),.05,.95);
}
bool EnvironmentThroughBsdf(Hit h,float3 view) {
    return h.rough<.1 && SpecularProbability(h,view)>.999;
}
float BsdfPdf(Hit h,float3 view,float3 d) {
    float nl=saturate(dot(h.n,d)),nv=saturate(dot(h.n,view));if(nl<=0 || nv<=0)return 0;
    float3 halfVector=normalize(view+d);float nh=saturate(dot(h.n,halfVector));
    float a=max(h.rough*h.rough,.002),a2=a*a;
    float density=a2/(PI*pow(nh*nh*(a2-1)+1,2));
    return lerp(nl/PI,density*G1(nv,a2)/max(4*nv,1e-6),SpecularProbability(h,view));
}
float3 SampleBsdf(Hit h,float3 view,inout uint rng,out float3 weight) {
    float3 d;
    float specularProbability=SpecularProbability(h,view);
    if(h.rough<=.06 && specularProbability>.999) {
        // Resolve a near-delta conductor as a mirror. A handful of random
        // rays across this lobe turns reflected text and silhouettes into
        // different edge pixels each frame, especially during a turn.
        weight=Fresnel(lerp(.04,h.albedo,h.metal),dot(h.n,view));
        return reflect(-view,h.n);
    }
    if(Random(rng)<specularProbability) {
        // Visible GGX normals (Heitz): sample the projected distribution instead
        // of spending glossy samples on normals hidden from the current view.
        float3 t,b;Basis(h.n,t,b);float a=max(h.rough*h.rough,.002);
        float3 v=normalize(float3(dot(view,t)*a,dot(view,b)*a,dot(view,h.n)));
        float3 t1=v.z<.9999?normalize(cross(float3(0,0,1),v)):float3(1,0,0),t2=cross(v,t1);
        float r=sqrt(Random(rng)),phi=2*PI*Random(rng);float x=r*cos(phi),y=r*sin(phi);
        float blend=.5*(1+v.z);y=lerp(sqrt(saturate(1-x*x)),y,blend);
        float3 nh=x*t1+y*t2+sqrt(saturate(1-x*x-y*y))*v;
        float3 hn=normalize(float3(a*nh.xy,max(nh.z,0)));
        d=reflect(-view,t*hn.x+b*hn.y+h.n*hn.z);
    } else d=Cosine(h.n,rng);
    weight=Bsdf(h,view,d)*saturate(dot(h.n,d))/max(BsdfPdf(h,view,d),1e-6);return d;
}
static const uint ENV_W=256,ENV_H=128,ENV_SIZE=ENV_W*ENV_H;
[numthreads(1,1,1)]
void EnvironmentRows(uint3 id:SV_DispatchThreadID) {
    if(id.y>=ENV_H)return;float sum=0;
    float solid=(2*PI/ENV_W)*(cos(PI*id.y/ENV_H)-cos(PI*(id.y+1)/ENV_H));
    for(uint x=0;x<ENV_W;x++) {sum+=max(Luma(environmentMap[uint2(x,id.y)].rgb),1e-5)*solid;environmentCdf[id.y*ENV_W+x]=sum;}
    environmentCdf[ENV_SIZE+id.y]=sum;
}
[numthreads(1,1,1)]
void EnvironmentTotal(uint3 id:SV_DispatchThreadID) {
    float sum=0;for(uint y=0;y<ENV_H;y++){sum+=environmentCdf[ENV_SIZE+y];environmentCdf[ENV_SIZE+y]=sum;}
    environmentCdf[ENV_SIZE+ENV_H]=sum;
}
float2 EnvironmentUv(float3 d) {return float2(frac(atan2(d.z,d.x)/(2*PI)+.5),acos(clamp(d.y,-1,1))/PI);}
float3 EnvironmentRadiance(float3 d) {
    if(environmentSettings.x<=0)return 0;
    float2 uv=EnvironmentUv(d);uv.y=clamp(uv.y,.5/ENV_H,1-.5/ENV_H);
    return environmentMap.SampleLevel(linearWrap,uv,0).rgb*environmentSettings.y;
}
float EnvironmentPdf(float3 d) {
    if(environmentSettings.x<=0)return 0;
    uint2 q=min(uint2(EnvironmentUv(d)*uint2(ENV_W,ENV_H)),uint2(ENV_W-1,ENV_H-1));
    return max(Luma(environmentMap[q].rgb),1e-5)/max(environmentCdf[ENV_SIZE+ENV_H],1e-8);
}
float PowerWeight(float a,float b) {return a*a/max(a*a+b*b,1e-12);}
float3 EnvironmentLighting(Hit h,float3 view,inout uint rng,bool continues=true) {
    if(environmentSettings.x<=0 || pathSettings.x<=0)return 0;
    // Near-delta conductors are sampled much more efficiently by visible GGX.
    // Do not occasionally strike their tiny lobe with an unrelated sky sample
    // and turn an otherwise smooth estimate into bright Monte Carlo outliers.
    // With no continuation, this estimator is still required.
    if(continues && EnvironmentThroughBsdf(h,view))return 0;
    float r=Random(rng)*environmentCdf[ENV_SIZE+ENV_H];uint lo=0,hi=ENV_H-1;
    while(lo<hi){uint m=(lo+hi)/2;if(environmentCdf[ENV_SIZE+m]<r)lo=m+1;else hi=m;}
    uint y=lo;r=Random(rng)*environmentCdf[y*ENV_W+ENV_W-1];lo=0;hi=ENV_W-1;
    while(lo<hi){uint m=(lo+hi)/2;if(environmentCdf[y*ENV_W+m]<r)lo=m+1;else hi=m;}
    float phi=2*PI*((lo+Random(rng))/ENV_W-.5);
    float ct=lerp(cos(PI*y/ENV_H),cos(PI*(y+1)/ENV_H),Random(rng)),st=sqrt(saturate(1-ct*ct));
    float3 d=float3(st*cos(phi),ct,st*sin(phi));float cosine=saturate(dot(h.n,d));if(cosine<=0)return 0;
    float pdf=EnvironmentPdf(d);float mis=continues?PowerWeight(pdf,BsdfPdf(h,view,d)):1;
    return EnvironmentRadiance(d)*Bsdf(h,view,d)*cosine*mis/max(pdf,1e-6)*Visibility(h.p+h.n*.012,d,192);
}
struct LightCandidate { float3 value,direction;float distance,weight; };
float3 VisibleLight(Hit h,LightCandidate light) {
    return light.value*Visibility(h.p+h.n*.04,light.direction,max(.004,light.distance-.06));
}
float3 LocalLighting(Hit h,float3 view,inout uint rng,out float3 exact,bool evaluateExact=true) {
    // Always evaluate the brightest candidate. Rolling it into a single
    // random choice makes two overlapping fixtures alternately light and
    // darken a surface when just one of them is occluded. Use a reservoir
    // only for the remainder, where the variance is lower.
    LightCandidate strongest=(LightCandidate)0,selected=(LightCandidate)0;
    float sum=0;
    uint remainder=0;
    [loop] for(uint i=0;i<(uint)clamp(transport.w,0,64);i++) {
        Light light=lights[i];float3 delta=light.positionRange.xyz-h.p;float distance=length(delta);
        if(distance>=light.positionRange.w || distance<.01) continue;
        float3 direction=delta/distance;float cosine=saturate(dot(h.n,direction));if(cosine<=0) continue;
        float cone=light.directionCone.w<0?1:smoothstep(light.directionCone.w,min(1,light.directionCone.w+.08),dot(-direction,light.directionCone.xyz));
        float normalized=distance/light.positionRange.w;
        float attenuation=pow(saturate(1-normalized*normalized),3)/(1+max(light.settings.x,0)*normalized*normalized);
        float3 value=Bsdf(h,view,direction)*cosine*light.colorIntensity.rgb*light.colorIntensity.w*attenuation*cone;
        LightCandidate candidate={value,direction,distance,Luma(value)};
        if(candidate.weight>strongest.weight) {
            LightCandidate previous=strongest;
            strongest=candidate;
            candidate=previous;
        }
        if(candidate.weight<=0)continue;
        sum+=candidate.weight;
        if(++remainder==1 || Random(rng)*sum<candidate.weight)selected=candidate;
    }
    exact=evaluateExact && strongest.weight>0?VisibleLight(h,strongest):0;
    if(remainder==1 && evaluateExact)exact+=VisibleLight(h,selected);
    return remainder>1?VisibleLight(h,selected)*(sum/selected.weight):0;
}
float4 PathRadiance(float3 origin,float3 direction,float range,inout uint rng,uint depthLimit=0,float previousPdf=0) {
    float3 radiance=0,throughput=1;float found=0;uint bounce=0;
    uint maxBounces=depthLimit>0?depthLimit:(uint)clamp(transport.x,1,8);
    [loop] for(uint step=0;step<32;step++) {
        Hit h;if(!Closest(origin,direction,range,h)) {
            if(pathSettings.x>0)radiance+=throughput*EnvironmentRadiance(direction)*(previousPdf>0?PowerWeight(previousPdf,EnvironmentPdf(direction)):1);
            break;
        }
        if(h.flags&GLASS) {
            GlassMaterial g=glassMaterials[h.glass];
            if(transport.z<=0) {origin=h.p+direction*.012;continue;}
            float f=Dielectric(abs(dot(h.n,direction)),g.optics.x);
            if(Random(rng)<f) {previousPdf=0;direction=reflect(direction,h.n);origin=h.p+h.n*.012;}
            else {
                float3 inside=refract(direction,h.n,1/g.optics.x);
                float distance=g.optics.y/max(abs(dot(inside,h.n)),.1);
                origin=h.p+inside*distance+direction*.012;
                throughput*=pow(max(g.transmission.rgb,.001),distance/g.optics.y);
                // A parallel thin slab exits with its incoming direction, with
                // a refractive lateral shift. This is not a solid-volume model.
            }
            continue;
        }
        found=1;
        float3 l=normalize(sunDirection.xyz);float cosine=saturate(dot(h.n,l));
        float3 lit=cosine>0?Visibility(h.p+h.n*.04,l,192):0;
        float3 exactLocal;
        float3 sampledLocal=LocalLighting(h,-direction,rng,exactLocal);
        radiance+=throughput*(h.emission+Bsdf(h,-direction,l)*sunColor.rgb*cosine*lit+exactLocal+sampledLocal+EnvironmentLighting(h,-direction,rng,bounce+1<maxBounces)+(pathSettings.x>0?0:h.albedo*.018));
        if(++bounce>=maxBounces) break;
        float3 weight,view=-direction;direction=SampleBsdf(h,view,rng,weight);previousPdf=EnvironmentThroughBsdf(h,view)?0:BsdfPdf(h,view,direction);throughput*=weight;
        if(max(throughput.x,max(throughput.y,throughput.z))<.001) break;
        if(bounce>=2) {
            float survive=clamp(max(throughput.x,max(throughput.y,throughput.z)),.1,.95);
            if(Random(rng)>survive) break;throughput/=survive;
        }
        origin=h.p+h.n*.04;range=max(transport.y,12);
    }
    return float4(min(radiance,32),found);
}
// Replace near-field opaque lighting with a complete BSDF path estimate, rather
// than adding a GI/reflection overlay to already lit raster pixels. Raster depth
// validates coverage; missing/deformed/distant geometry keeps native lighting.
void TraceSurfacePaths(uint2 pixel,float4 p,float3 viewRay,Hit primary,bool found,inout uint rng) {
    result[pixel]=0;
    if(p.w<=0)return;
    // The first hit was also used to identify foreground glass and voxels.
    // Only trace again when the first surface is transparent.
    [loop] for(uint layer=1;layer<12 && found && (primary.flags&GLASS);layer++) {
        float3 origin=primary.p+viewRay*.012;
        found=Closest(origin,viewRay,256,primary,environmentSettings.w<=0);
    }
    if(!found || (primary.flags&GLASS) || length(primary.p-p.xyz)>((primary.flags&VOXEL)?max(effects.z,.25):.25))return;
    moments[pixel]=float4(0,0,EncodeGeometricNormal(primary.n));
    primary.n=normalize(normals[pixel].xyz);
    if(dot(primary.n,viewRay)>0)primary.n=-primary.n;
    primary.rough=max(.04,1-normals[pixel].w);
    float4 guide=surfaceGuide[pixel];
    if(environmentSettings.w>0) {
        primary.albedo=guide.rgb;primary.metal=guide.a;
        primary.emission=guide.rgb*(1-guide.a)*max(p.w-1,0)*environmentSettings.z;
    }
    float3 materialFactor=environmentSettings.w>0?max(primary.albedo*(1-primary.metal)+lerp(.04,primary.albedo,primary.metal),.08):1;
    // Deterministic lights preserve normal-map detail and hard shadow edges
    // by going straight into the current frame.
    float3 sun=normalize(sunDirection.xyz);float cosine=saturate(dot(primary.n,sun));
    float3 directLighting=cosine>0?Bsdf(primary,-viewRay,sun)*sunColor.rgb*cosine*Visibility(primary.p+primary.n*.04,sun,192):0;
    float3 radiance=0;uint samples=(uint)clamp(pathSettings.y,1,8);
    [loop] for(uint sample=0;sample<samples;sample++) {
        float3 exactLocal;
        float3 direct=primary.emission+LocalLighting(primary,-viewRay,rng,exactLocal,sample==0)+EnvironmentLighting(primary,-viewRay,rng,transport.x>1);
        directLighting+=exactLocal;
        if(transport.x>1) {
            float3 weight;float3 outgoing=SampleBsdf(primary,-viewRay,rng,weight);
            direct+=weight*PathRadiance(primary.p+primary.n*.04,outgoing,max(transport.y,12),rng,(uint)clamp(transport.x-1,1,7),EnvironmentThroughBsdf(primary,-viewRay)?0:BsdfPdf(primary,-viewRay,outgoing)).rgb;
        }
        radiance+=min(direct,32)/samples;
    }
    if(environmentSettings.w>0)radiance=max(radiance-primary.emission,0)/materialFactor;
    result[pixel]=float4(1,1,(primary.flags&VOXEL)?1:0,1);
    reflected[pixel]=float4(directLighting,1);
    filtered[pixel]=float4(radiance,1);
    // Scratch buffers become the spatial filter outputs only after this pass.
    filteredReflection[pixel]=float4(primary.previousP,primary.previousValid);
}
float ReflectionHistoryLimit(float3 position,float3 previousPoint,float rough) {
    float viewChange=length(normalize(position-originDelta.xyz)-normalize(previousPoint-originChange.xyz-previousCamera.xyz));
    float reactive=(1-smoothstep(.25,.5,rough))*saturate(viewChange/max(.0005,rough*rough*.25));
    return lerp(32,1,reactive);
}
float IlluminationConfidence(float difference,float uncertainty,float signal) {
    // Compare estimates of the local mean, with a confidence interval based
    // on the number of usable current samples. A single bright path should
    // not cause the entire history of a dark receiver to be discarded.
    float tolerance=max(.002,.035*signal)+3*uncertainty;
    return 1-smoothstep(tolerance,2*tolerance,difference);
}
void TemporalPaths(uint2 pixel) {
    if(result[pixel].w<=0)return;
    float4 p=positions[pixel],guide=surfaceGuide[pixel],motion=filteredReflection[pixel];
    float3 shadingNormal=normals[pixel].xyz;
    float3 geometryNormal=DecodeGeometricNormal(moments[pixel].zw);
    float rough=max(.04,1-normals[pixel].w);
    float footprint=max(.012,length(p.xyz-originDelta.xyz)*3/sizes.w);
    float precision=max(abs(p.x),max(abs(p.y),abs(p.z)))*.0006;
    float3 raw=filtered[pixel].rgb;
    if(pathSettings.w<=0) {
        indirect[pixel]=float4(raw,1);
        return;
    }
    float3 spatial=0;
    float secondMoment=0,rgbSecondMoment=0,totalWeight=0,squaredWeight=0;
    [unroll] for(int y=-2;y<=2;y++)[unroll] for(int x=-2;x<=2;x++) {
        int2 q=int2(pixel)+int2(x,y);
        if(any(q<0) || any(q>=int2(sizes.zw)) || result[q].w<=0)continue;
        float3 delta=positions[q].xyz-p.xyz;
        float geometry=pow(saturate(dot(geometryNormal,DecodeGeometricNormal(moments[q].zw))),32)
            * exp(-abs(dot(delta,geometryNormal))/(footprint*.25+precision))
            * pow(saturate(dot(shadingNormal,normals[q].xyz)),lerp(32,3,saturate(rough*4)))
            * exp(-abs(normals[q].w-normals[pixel].w)*16);
        if(length(delta)>footprint*4+precision)continue;
        if(environmentSettings.w>0)geometry*=exp(-abs(surfaceGuide[q].a-guide.a)*20);
        // Keep narrow specular features local. Diffuse/rough bounces can be
        // estimated with other rays from nearby points on the same plane.
        if(x!=0 || y!=0)geometry*=saturate((rough-.06)/.14);
        float weight=geometry*(3-abs(x))*(3-abs(y));
        float3 sample=filtered[q].rgb;float luma=Luma(sample);
        spatial+=sample*weight;secondMoment+=luma*luma*weight;
        rgbSecondMoment+=dot(sample,sample)*weight;
        totalWeight+=weight;squaredWeight+=weight*weight;
    }
    spatial/=max(totalWeight,1e-6);
    float mean=Luma(spatial);
    float variance=max(secondMoment/max(totalWeight,1e-6)-mean*mean,0);
    float inverseSupport=squaredWeight/max(totalWeight*totalWeight,1e-6);
    float3 radiance=lerp(raw,spatial,saturate((rough-.06)/.14));
    float count=1;
    float luma=Luma(radiance);
    float2 stats=float2(luma,min(luma*luma+variance,65504));
    if(history.x>0 && motion.w>0) {
        float3 previousPoint=motion.xyz;
        float4 clip=mul(float4(previousPoint-originChange.xyz-previousCamera.xyz,1),previousViewProjection);
        float2 uv=float2(clip.x/clip.w*.5+.5,.5-clip.y/clip.w*.5);
        if(clip.w>0 && all(uv>=0) && all(uv<1)) {
            float2 sampleAt=uv*sizes.zw-.5;int2 base=int2(floor(sampleAt));float2 fraction=frac(sampleAt);
            float3 oldRadiance=0;float2 oldStats=0;float oldCount=0,total=0;
            float historyFootprint=max(.025,footprint)+precision;
            [unroll] for(int yy=0;yy<2;yy++)[unroll] for(int xx=0;xx<2;xx++) {
                int2 q=base+int2(xx,yy);if(any(q<0) || any(q>=int2(sizes.zw)))continue;
                float4 oldPosition=previousPositions[q],oldNormal=previousNormals[q];
                float3 delta=oldPosition.xyz-previousPoint;
                float4 oldGuide=previousSurfaceGuide[q];
                bool materialMatch=environmentSettings.w<=0 || (abs(oldGuide.a-guide.a)<.08 && length(oldGuide.rgb-guide.rgb)<.25);
                if(previousReflections[q].a>.5 && oldPosition.w>0 && materialMatch && abs(dot(delta,oldNormal.xyz))<max(.012,historyFootprint*.15)+precision && length(delta)<historyFootprint*2 && dot(shadingNormal,oldNormal.xyz)>.9 && abs(normals[pixel].w-oldNormal.w)<.1) {
                    float w=(xx?fraction.x:1-fraction.x)*(yy?fraction.y:1-fraction.y);
                    oldRadiance+=previousIndirect[q].rgb*w;oldCount+=previousIndirect[q].a*w;oldStats+=previousMoments[q].xy*w;total+=w;
                }
            }
            if(total>.1) {
                float3 old=oldRadiance/total;
                float2 oldMoment=oldStats/total;
                float currentVariance=max(rgbSecondMoment/max(totalWeight,1e-6)-dot(spatial,spatial),0);
                float previousVariance=max(oldMoment.y-oldMoment.x*oldMoment.x,0);
                // A small, intermittently visible emitter may be missed by
                // every current ray along a thin feature. Undoing the whole
                // estimate on such a frame creates a repeating dark flash.
                float uncertainty=sqrt(max(currentVariance,previousVariance*.5)*inverseSupport);
                float confidence=IlluminationConfidence(length(old-spatial),uncertainty,length(spatial));
                // Receiver motion is insufficient for view-dependent reflection:
                // a polished lobe moves across a stationary surface as the eye
                // translates. Keep diffuse/rough history, shorten a tight lobe
                // according to its angular footprint instead of dragging it.
                count=1+confidence*min(oldCount/total,ReflectionHistoryLimit(p.xyz,previousPoint,rough)-1);
                radiance=lerp(radiance,old,1-1/count);
                stats=lerp(stats,oldMoment,1-1/count);
            }
        }
    }
    indirect[pixel]=float4(radiance,count);moments[pixel].xy=stats;
}
void TemporalHybrid(uint2 pixel) {
    float4 p=positions[pixel],bounce=filtered[pixel],spec=filteredReflection[pixel];
    if(p.w<=0)return;
    float4 stats=float4(Luma(bounce.rgb),0,Luma(spec.rgb),0);stats.y=stats.x*stats.x;stats.w=stats.z*stats.z;
    if(history.x>0) {
        float3 previousPoint=p.xyz+originChange.xyz;
        float4 clip=mul(float4(p.xyz-previousCamera.xyz,1),previousViewProjection);
        float2 uv=float2(clip.x/clip.w*.5+.5,.5-clip.y/clip.w*.5);
        if(clip.w>0 && all(uv>=0) && all(uv<1)) {
            uint2 q=min(uint2(uv*sizes.zw),sizes.zw-1);
            float4 oldPosition=previousPositions[q],oldNormal=previousNormals[q];
            if(oldPosition.w>0 && length(oldPosition.xyz-previousPoint)<.12 && dot(normals[pixel].xyz,oldNormal.xyz)>.98 && abs(normals[pixel].w-oldNormal.w)<.05) {
                float3 lo=bounce.rgb,hi=bounce.rgb,specLo=spec.rgb,specHi=spec.rgb;
                [unroll] for(int y=-1;y<=1;y++)[unroll] for(int x=-1;x<=1;x++) {
                    int2 at=clamp(int2(pixel)+int2(x,y),0,int2(sizes.zw)-1);
                    if(positions[at].w<=0 || dot(normals[pixel].xyz,normals[at].xyz)<.98 || abs(dot(positions[at].xyz-p.xyz,normals[pixel].xyz))>.025)continue;
                    lo=min(lo,filtered[at].rgb);hi=max(hi,filtered[at].rgb);
                    specLo=min(specLo,filteredReflection[at].rgb);specHi=max(specHi,filteredReflection[at].rgb);
                }
                float4 oldBounce=previousIndirect[q],oldSpec=previousReflections[q];
                float3 clipped=clamp(oldBounce.rgb,lo-.0001,hi+.0001),specClipped=clamp(oldSpec.rgb,specLo-.0001,specHi+.0001);
                float correction=max(length(oldBounce.rgb-clipped)/max(length(oldBounce.rgb),.001),length(oldSpec.rgb-specClipped)/max(length(oldSpec.rgb),.001));
                bounce.a=min(oldBounce.a+1,correction>.2?1:ReflectionHistoryLimit(p.xyz,previousPoint,max(.04,1-normals[pixel].w)));
                float weight=1-1/bounce.a;
                bounce.rgb=lerp(bounce.rgb,clipped,weight);spec=lerp(spec,float4(specClipped,oldSpec.a),weight);
                stats=lerp(stats,previousMoments[q],weight);
            }
        }
    }
    reflected[pixel]=spec;indirect[pixel]=bounce;moments[pixel]=stats;
}
void TemporalGlass(uint2 pixel) {
    float4 raw=glassRaw[pixel],old=glassReflected[pixel];
    float4 guide=glassGuide[pixel],pane=glassData[pixel],normal=glassNormal[pixel];
    if(pathSettings.w<=0 || raw.a<=0 || guide.w<=0){glassReflected[pixel]=raw;return;}
    float3 mean=0,square=0;float total=0,squaredWeight=0;
    float footprint=max(.003,length(guide.xyz-originDelta.xyz)*3/sizes.w);
    float roughWeight=saturate((normal.w-.08)/.14);
    [unroll] for(int y=-2;y<=2;y++)[unroll] for(int x=-2;x<=2;x++) {
        int2 q=int2(pixel)+int2(x,y);
        if(any(q<0) || any(q>=int2(sizes.zw)))continue;
        float4 other=glassGuide[q],value=glassRaw[q];
        float3 delta=other.xyz-guide.xyz;
        if(value.a<=0 || other.w<=0 || length(delta)>footprint*4 || length(glassData[q].rgb-pane.rgb)>.05)continue;
        float4 n=glassNormal[q];
        float weight=pow(saturate(dot(n.xyz,normal.xyz)),64)
            * exp(-abs(dot(delta,normal.xyz))/footprint-abs(n.w-normal.w)*32)
            * (3-abs(x))*(3-abs(y));
        if(x!=0 || y!=0)weight*=roughWeight;
        mean+=value.rgb*weight;square+=value.rgb*value.rgb*weight;
        total+=weight;squaredWeight+=weight*weight;
    }
    mean/=max(total,1e-6);
    float3 variance=max(square/max(total,1e-6)-mean*mean,0);
    float uncertainty=sqrt(dot(variance,1)*squaredWeight/max(total*total,1e-6));
    float confidence=old.a>0?IlluminationConfidence(length(old.rgb-mean),uncertainty,length(mean)):0;
    glassReflected[pixel]=float4(lerp(lerp(raw.rgb,mean,roughWeight),old.rgb,old.a*confidence),raw.a);
}
// Filter illumination in reflected-surface space, not the foreground pane or
// its albedo. The reflected LCD/emission and direct sun never enter this pass.
// Each pass reads one texture and writes another. Only the finest iteration
// feeds history; wider reconstruction passes remain current-frame only.
[numthreads(8,8,1)]
void DenoiseGlass(uint3 id:SV_DispatchThreadID) {
    if(any(id.xy>=sizes.zw))return;
    bool fromRaw=(filterStep&256)!=0;uint stride=filterStep&255;
    float4 center=fromRaw?glassRaw[id.xy]:glassReflected[id.xy],guide=glassGuide[id.xy],normal=glassNormal[id.xy];
    if(guide.w<=0 || center.a<=0) {if(fromRaw)glassReflected[id.xy]=center;else glassRaw[id.xy]=center;return;}
    float3 sum=0;float total=0;
    float footprint=max(.003,length(guide.xyz-originDelta.xyz)*2/sizes.w);
    [unroll] for(int y=-1;y<=1;y++)[unroll] for(int x=-1;x<=1;x++) {
        int2 q=clamp(int2(id.xy)+int2(x,y)*stride,0,int2(sizes.zw)-1);
        float4 other=glassGuide[q],n=glassNormal[q],sample=fromRaw?glassRaw[q]:glassReflected[q];
        if(other.w<=0 || sample.a<=0)continue;
        float3 delta=other.xyz-guide.xyz;
        float geometry=exp(-abs(dot(delta,normal.xyz))/footprint)*pow(saturate(dot(normal.xyz,n.xyz)),64)
            *exp(-abs(n.w-normal.w)*32);
        // Keep a narrow reflected GGX highlight from being averaged with a
        // different view lobe (especially at small test/output resolutions).
        float viewAngle=length(normalize(guide.xyz-originDelta.xyz)-normalize(other.xyz-originDelta.xyz));
        geometry*=exp(-pow(viewAngle/max(.001,normal.w*normal.w*.15),2));
        // Adjacent projections of unrelated surfaces must not exchange light.
        geometry*=saturate(1-length(delta)/(footprint*(stride*8+4)));
        float kernel=(x==0?2:1)*(y==0?2:1);
        float weight=geometry*kernel;
        sum+=sample.rgb*weight;total+=weight;
    }
    float4 value=float4(sum/max(total,1e-6),center.a);
    if(fromRaw)glassReflected[id.xy]=value;else glassRaw[id.xy]=value;
}
[numthreads(8,8,1)]
void Temporal(uint3 id:SV_DispatchThreadID) {
    if(any(id.xy>=sizes.zw))return;
    if(pathSettings.x>0)TemporalPaths(id.xy);
    else TemporalHybrid(id.xy);
    TemporalGlass(id.xy);
}
// Clear glass carries deterministic texture/emission and sunlight separately.
// Only stochastic secondary lighting needs temporal/spatial denoising.
float4 GlassLighting(Hit pane,float3 viewRay,inout uint rng,out Hit anchor,out float3 sharp) {
    sharp=0;anchor=(Hit)0;
    GlassMaterial g=glassMaterials[pane.glass];
    float3 direction=reflect(viewRay,pane.n);
    if(g.transmission.w>.06)direction=normalize(direction+Cosine(pane.n,rng)*g.transmission.w*g.transmission.w);
    float3 origin=pane.p+pane.n*.012,throughput=1,noisy=0;
    float3x3 unfold=float3x3(1,0,0,0,1,0,0,0,1),oldUnfold=unfold;
    float3 offset=0,oldOffset=0;float distance=0;bool resolved=false;
    // Resolve the dominant clear-glass lobe deterministically. Previously a
    // second pane sent emission/text and all lighting through one stochastic
    // Fresnel decision, with no surface guide and no history at all.
    [loop] for(uint layer=0;layer<8;layer++) {
        Hit h;
        if(!Closest(origin,direction,192,h)) {
            if(layer==0)return 0; // retain native environment on a direct miss
            sharp+=throughput*EnvironmentRadiance(direction);
            // The residual branch still contains sampled lighting even when
            // the dominant branch exits to the environment. Use the last pane
            // as a conservative spatial guide, not an uninitialized roughness
            // of zero (which effectively disabled all its denoising).
            anchor.previousValid=0;break;
        }
        distance+=h.t;anchor=h;
        if(!(h.flags&GLASS)){resolved=true;break;}
        GlassMaterial next=glassMaterials[h.glass];
        float f=Dielectric(abs(dot(h.n,direction)),next.optics.x);
        float3 inside=refract(direction,h.n,1/next.optics.x);
        float3 shift=inside*(next.optics.y/max(abs(dot(inside,h.n)),.1));
        float3 transmitted=h.p+shift+direction*.012;origin=transmitted;
        float3 attenuation=pow(max(next.transmission.rgb,.001),1/max(abs(dot(inside,h.n)),.1));
        if(f<.5) {
            noisy+=throughput*f*PathRadiance(h.p+h.n*.012,reflect(direction,h.n),192,rng).rgb;
            throughput*=attenuation*(1-f);
        } else {
            noisy+=throughput*(1-f)*attenuation*PathRadiance(transmitted,direction,192,rng).rgb;
            // Compose mirrors so the final hit has a stable virtual surface.
            float3x3 r=float3x3(1,0,0,0,1,0,0,0,1)-2*float3x3(h.n.x*h.n,h.n.y*h.n,h.n.z*h.n);
            float3 pn=h.previousN;
            float3x3 pr=float3x3(1,0,0,0,1,0,0,0,1)-2*float3x3(pn.x*pn,pn.y*pn,pn.z*pn);
            offset+=mul(unfold,2*dot(h.p,h.n)*h.n);unfold=mul(unfold,r);
            oldOffset+=mul(oldUnfold,2*dot(h.previousP,pn)*pn);oldUnfold=mul(oldUnfold,pr);
            throughput*=f;direction=reflect(direction,h.n);origin=h.p+h.n*.012;
        }
    }
    if(!resolved) {
        anchor.previousValid=0;anchor.rough=.4;
        anchor.p=mul(unfold,anchor.p)+offset;anchor.n=mul(unfold,anchor.n);
        anchor.t=max(distance,.001);return float4(noisy,1);
    }
    float3 sun=normalize(sunDirection.xyz);float cosine=saturate(dot(anchor.n,sun));
    sharp=throughput*(anchor.emission+(cosine>0?Bsdf(anchor,-direction,sun)*sunColor.rgb*cosine*Visibility(anchor.p+anchor.n*.04,sun,192):0));
    if(pathSettings.x<=0)sharp+=throughput*anchor.albedo*.018;
    uint samples=(uint)clamp(pathSettings.y,1,8);
    [loop] for(uint sample=0;sample<samples;sample++) {
        float3 exactLocal;
        float3 light=LocalLighting(anchor,-direction,rng,exactLocal,sample==0)+EnvironmentLighting(anchor,-direction,rng,transport.x>1);
        sharp+=throughput*exactLocal;
        if(transport.x>1){float3 weight;float3 outgoing=SampleBsdf(anchor,-direction,rng,weight);
            light+=weight*PathRadiance(anchor.p+anchor.n*.04,outgoing,max(transport.y,12),rng,(uint)clamp(transport.x-1,1,7),EnvironmentThroughBsdf(anchor,-direction)?0:BsdfPdf(anchor,-direction,outgoing)).rgb;}
        noisy+=throughput*min(light,32)/samples;
    }
    anchor.p=mul(unfold,anchor.p)+offset;anchor.n=mul(unfold,anchor.n);
    anchor.previousP=mul(oldUnfold,anchor.previousP)+oldOffset;anchor.previousN=mul(oldUnfold,anchor.previousN);anchor.t=distance;
    return float4(noisy,1);
}
[numthreads(8,8,1)]
void Trace(uint3 id:SV_DispatchThreadID) {
    if(any(id.xy>=sizes.zw)) return;
    float4 p=positions[id.xy];
    uint rng=id.x*1973+id.y*9277+(uint)history.y*26699+89173;
    result[id.xy]=1;reflected[id.xy]=0;indirect[id.xy]=0;glassReflected[id.xy]=0;glassData[id.xy]=0;glassRefracted[id.xy]=0;moments[id.xy]=0;glassSharp[id.xy]=0;glassGuide[id.xy]=0;glassRaw[id.xy]=0;glassNormal[id.xy]=0;glassFactor[id.xy]=float4(1,1,1,0);
    filtered[id.xy]=0;filteredReflection[id.xy]=0;
    float3 surface=p.xyz, surfaceNormal=normalize(normals[id.xy].xyz);
    float3 viewRay=CameraRay(id.xy,p);
    // Transparent surfaces have no opaque G-buffer entry. Trace camera rays
    // independently, including windows backed by sky or distant terrain.
    bool paths=pathSettings.x>0;
    Hit front=(Hit)0;
    bool found=false;
    if(transport.z>0 || settings.w==6 || effects.z>0 || (paths && p.w>0)) {
        uint2 nativePixel=min(uint2((float2(id.xy)+.5)*float2(sizes.xy)/sizes.zw),sizes.xy-1);
        float2 uv=(float2(nativePixel)+.5)/sizes.xy;
        // Raster voxels and the independently meshed RT surface need not have
        // identical depth. A G-buffer depth cutoff produced holes in coverage.
        float opaqueDistance=p.w>0?length(p.xyz-originDelta.xyz):1e20;
        float range=256;
        found=Closest(originDelta.xyz,viewRay,range,front,paths && p.w>0 && environmentSettings.w<=0);
        if(found) {
            if(front.flags&VOXEL) result[id.xy].z=1;
            else result[id.xy].z=0;
            if((front.flags&VOXEL) && p.w>0 && abs(front.t-opaqueDistance)<effects.z) {
                surface=front.p;surfaceNormal=front.n;
            }
            // Extending a camera ray must not composite glass behind opaque
            // foreground geometry. Only voxel secondary-ray origins are repaired.
            if((front.flags&GLASS) && transport.z>0 && front.t<=opaqueDistance+.02) {
                GlassMaterial g=glassMaterials[front.glass];
                uint glassRng=rng;
                Hit anchor;float3 sharp;float4 local=GlassLighting(front,viewRay,glassRng,anchor,sharp);
                float f=Dielectric(abs(dot(front.n,viewRay)),g.optics.x);
                float4 reflectionSample=float4(local.rgb*local.a,f*local.a);
                glassSharp[id.xy]=float4(sharp,g.transmission.w);
                if(local.a>0) {
                    float3 factor=(anchor.flags&GLASS)?1:max(anchor.albedo*(1-anchor.metal)+lerp(.04,anchor.albedo,anchor.metal),.04);
                    glassFactor[id.xy]=float4(factor,1);
                    reflectionSample.rgb/=factor;
                    float3 virtualPoint=anchor.p-2*dot(anchor.p-front.p,front.n)*front.n;
                    float3 virtualNormal=reflect(anchor.n,front.n);
                    glassGuide[id.xy]=float4(virtualPoint,max(anchor.t,.001));
                    glassNormal[id.xy]=float4(virtualNormal,anchor.rough);
                    if(history.x>0 && front.previousValid!=0 && anchor.previousValid!=0) {
                        // Reflect the hit's previous position across the previous
                        // pane plane. Tracking the pane alone smears LCD text.
                        float3 virtualPrevious=anchor.previousP-2*dot(anchor.previousP-front.previousP,front.previousN)*front.previousN;
                        float3 previousRelative=virtualPrevious-originChange.xyz-previousCamera.xyz;
                        float4 oldClip=mul(float4(previousRelative,1),previousViewProjection);
                        float2 oldUv=float2(oldClip.x/oldClip.w*.5+.5,.5-oldClip.y/oldClip.w*.5);
                        if(oldClip.w>0 && all(oldUv>=0) && all(oldUv<1)) {
                            float2 at=oldUv*sizes.zw-.5;int2 base=int2(floor(at));float2 fraction=frac(at);
                            float4 old=0;float total=0;
                            float tolerance=max(.003,length(previousRelative)*2/sizes.w);
                            float3 oldNormal=reflect(anchor.previousN,front.previousN);
                            [unroll] for(int yy=0;yy<2;yy++)[unroll] for(int xx=0;xx<2;xx++) {
                                int2 q=base+int2(xx,yy);if(any(q<0) || any(q>=int2(sizes.zw)))continue;
                                float4 oldGuide=previousGlassGuide[q];
                                if(oldGuide.w>0 && length(oldGuide.xyz-virtualPrevious)<tolerance*2 && dot(previousGlassNormal[q].xyz,oldNormal)>.95 && abs(previousGlassNormal[q].w-anchor.rough)<.05 && length(previousGlassData[q].rgb-PaneTransmission(front,viewRay))<.05) {
                                    float w=(xx?fraction.x:1-fraction.x)*(yy?fraction.y:1-fraction.y);old+=previousGlassReflections[q]*w;total+=w;
                                }
                            }
                            if(total>.1)glassReflected[id.xy]=float4(old.rgb/total,min(.875,1-1/ReflectionHistoryLimit(virtualPoint,virtualPrevious,anchor.rough)));
                        }
                    }
                }
                glassRaw[id.xy]=reflectionSample;
                glassData[id.xy]=float4(PaneTransmission(front,viewRay),front.t);
                float3 inside=refract(viewRay,front.n,1/g.optics.x);
                float3 exitPoint=front.p+inside*(g.optics.y/max(abs(dot(inside,front.n)),.1))+viewRay*.012;
                // Trace the slab's refracted exit ray, then reuse native HDR only
                // if its projected surface is actually visible. Depth rejection
                // avoids borrowing a foreground object at a disocclusion.
                [loop] for(uint layer=0;layer<8;layer++) {
                    Hit behind;if(!Closest(exitPoint,viewRay,192,behind,false)) break;
                    if(behind.flags&GLASS) {exitPoint=behind.p+viewRay*.012;continue;}
                    float4 clip=mul(float4(behind.p-originDelta.xyz,1),viewProjection);
                    if(clip.w>0) {
                        float2 refractedUv=float2(clip.x/clip.w*.5+.5,.5-clip.y/clip.w*.5);
                        if(all(refractedUv>=0) && all(refractedUv<1)) {
                            uint2 samplePixel=min(uint2(refractedUv*sizes.zw),sizes.zw-1);
                            float4 receiver=positions[samplePixel];
                            if(receiver.w>0 && length(receiver.xyz-behind.p)<.2) glassRefracted[id.xy]=float4(refractedUv-uv,clip.z/clip.w,1);
                        }
                    }
                    break;
                }
            }
        } else result[id.xy].z=0;
    }
    if(paths) {TraceSurfacePaths(id.xy,p,viewRay,front,found,rng);return;}
    if(p.w==0) return;
    float3 n=surfaceNormal,t,b;Basis(n,t,b);
    uint stable=id.x*1973+id.y*9277+89173;float ao=0;
    [unroll] for(uint i=0;i<4;i++) ao+=Luma(Visibility(surface+n*.04,Cosine(n,stable),settings.x));
    float shadow=dot(n,sunDirection.xyz)>0?Luma(Visibility(surface+n*.04,normalize(sunDirection.xyz),192)):1;
    float voxel=result[id.xy].z;result[id.xy]=float4(ao*.25,shadow,voxel,1);
    float3 incoming=normalize(p.xyz-originDelta.xyz);
    float roughness=pow(1-normals[id.xy].w,2);
    float3 rd=normalize(reflect(incoming,n)+Cosine(n,rng)*roughness*.35);
    float4 reflection=effects.x>0 && dot(rd,n)>0?PathRadiance(surface+n*.04,rd,192,rng):0;
    float4 bounce=0;
    if(effects.y>0) {
        [unroll] for(uint j=0;j<2;j++) bounce.rgb+=PathRadiance(surface+n*.04,Cosine(n,rng),max(transport.y,12),rng).rgb*.5;
    }
    bounce.a=1;
    filtered[id.xy]=bounce;filteredReflection[id.xy]=reflection;
}
[numthreads(8,8,1)]
void Denoise(uint3 id:SV_DispatchThreadID) {
    if(any(id.xy>=sizes.zw)) return;
    float4 center=indirect[id.xy],p=positions[id.xy];
    bool pathTraced=pathSettings.x>0;
    if(p.w==0 || (pathTraced && result[id.xy].w==0)) {
        filtered[id.xy]=center;
        if(!pathTraced)filteredReflection[id.xy]=reflected[id.xy];
        return;
    }
    float4 spec=pathTraced?0:reflected[id.xy];
    float4 shading=normals[id.xy];
    float rough=max(.04,1-shading.w);
    float3 view=normalize(p.xyz-originDelta.xyz);
    float3 n=pathTraced?DecodeGeometricNormal(moments[id.xy].zw):shading.xyz;
    float3 sum=0;float total=0;float4 specSum=0;float specTotal=0;
    float4 m=moments[id.xy];
    float2 variance=max(float2(m.y-m.x*m.x,m.w-m.z*m.z),0);
    // A fresh receiver has no temporal variance yet. Bootstrap from the local
    // radiance distribution; subsequent frames use accumulated first/second moments.
    if(center.a<4 && !pathTraced) {
        float4 local=0;float count=0;
        [unroll] for(int yy=-1;yy<=1;yy++) [unroll] for(int xx=-1;xx<=1;xx++) {
            int2 q=clamp(int2(id.xy)+int2(xx,yy),0,int2(sizes.zw)-1);
            if(positions[q].w==0 || dot(n,normals[q].xyz)<.98) continue;
            float a=Luma(indirect[q].rgb),b=Luma(reflected[q].rgb);
            local+=float4(a,a*a,b,b*b);count++;
        }
        local/=max(count,1);variance=max(variance,float2(local.y-local.x*local.x,local.w-local.z*local.z));
    }
    [unroll] for(int y=-1;y<=1;y++) [unroll] for(int x=-1;x<=1;x++) {
        int2 q=clamp(int2(id.xy)+int2(x,y)*(int)filterStep,0,int2(sizes.zw)-1);
        float4 other=positions[q],value=indirect[q];
        if(pathTraced && result[q].w==0)continue;
        float distance=abs(dot(other.xyz-p.xyz,n));
        float3 otherNormal=pathTraced?DecodeGeometricNormal(moments[q].zw):normals[q].xyz;
        float geometry=(other.w>0?1:0)*exp(-distance*20)*pow(saturate(dot(n,otherNormal)),32);
        if(pathTraced) {
            float4 otherShading=normals[q];
            geometry*=pow(saturate(dot(shading.xyz,otherShading.xyz)),shading.w>.75?24:2);
            if(rough<.16) {
                // Neighbors on the same plane can reflect different objects.
                // Keep the filter inside the glossy lobe's angular footprint.
                float angle=length(view-normalize(other.xyz-originDelta.xyz));
                geometry*=exp(-pow(angle/max(.0003,rough*rough*.3),2));
            }
        }
        float kernel=(x==0?2:1)*(y==0?2:1);
        float radiance=exp(-abs(Luma(value.rgb)-Luma(center.rgb))/(.02+4*sqrt(variance.x)));
        if(pathTraced && environmentSettings.w>0)geometry*=exp(-abs(surfaceGuide[q].a-surfaceGuide[id.xy].a)*24);
        float weight=geometry*radiance*kernel;
        sum+=value.rgb*weight;total+=weight;
        if(!pathTraced) {
            float4 otherSpec=reflected[q];
            float specWeight=geometry*kernel*exp(-abs(Luma(otherSpec.rgb)-Luma(spec.rgb))/(.02+4*sqrt(variance.y)))
                *exp(-abs(normals[q].w-normals[id.xy].w)*32);
            // Tight specular lobes keep the finest spatial footprint.
            if(normals[id.xy].w>.9 && filterStep>1 && (x!=0 || y!=0)) specWeight=0;
            specSum+=otherSpec*specWeight;specTotal+=specWeight;
        }
    }
    filtered[id.xy]=float4(sum/max(total,1e-5),center.a);
    if(!pathTraced)filteredReflection[id.xy]=specSum/max(specTotal,1e-5);
}