|
| 1 | +/* Copyright (c) 2025, Sascha Willems |
| 2 | + * |
| 3 | + * SPDX-License-Identifier: MIT |
| 4 | + * |
| 5 | + */ |
| 6 | + |
| 7 | +import types; |
| 8 | + |
| 9 | +Sampler2D samplerPositionDepth; |
| 10 | +Sampler2D samplerNormal; |
| 11 | +Sampler2D ssaoNoiseSampler; |
| 12 | + |
| 13 | +struct UBOSSAOKernel |
| 14 | +{ |
| 15 | + float4 samples[64]; |
| 16 | +}; |
| 17 | +ConstantBuffer<UBOSSAOKernel> uboSSAOKernel; |
| 18 | + |
| 19 | +struct UBO |
| 20 | +{ |
| 21 | + float4x4 projection; |
| 22 | +}; |
| 23 | +ConstantBuffer<UBO> ubo; |
| 24 | + |
| 25 | +[[SpecializationConstant]] const int SSAO_KERNEL_SIZE = 64; |
| 26 | +[[SpecializationConstant]] const float SSAO_RADIUS = 0.5; |
| 27 | + |
| 28 | +[shader("fragment")] |
| 29 | +float fragmentMain(VSOutput input) |
| 30 | +{ |
| 31 | + // Get G-Buffer values |
| 32 | + float3 fragPos = samplerPositionDepth.Sample(input.UV).rgb; |
| 33 | + float3 normal = normalize(samplerNormal.Sample(input.UV).rgb * 2.0 - 1.0); |
| 34 | + |
| 35 | + // Get a random vector using a noise lookup |
| 36 | + int2 texDim; |
| 37 | + samplerPositionDepth.GetDimensions(texDim.x, texDim.y); |
| 38 | + int2 noiseDim; |
| 39 | + ssaoNoiseSampler.GetDimensions(noiseDim.x, noiseDim.y); |
| 40 | + const float2 noiseUV = float2(float(texDim.x) / float(noiseDim.x), float(texDim.y) / (noiseDim.y)) * input.UV; |
| 41 | + float3 randomVec = ssaoNoiseSampler.Sample(noiseUV).xyz * 2.0 - 1.0; |
| 42 | + |
| 43 | + // Create TBN matrix |
| 44 | + float3 tangent = normalize(randomVec - normal * dot(randomVec, normal)); |
| 45 | + float3 bitangent = cross(tangent, normal); |
| 46 | + float3x3 TBN = transpose(float3x3(tangent, bitangent, normal)); |
| 47 | + |
| 48 | + // Calculate occlusion value |
| 49 | + float occlusion = 0.0f; |
| 50 | + for(int i = 0; i < SSAO_KERNEL_SIZE; i++) |
| 51 | + { |
| 52 | + float3 samplePos = mul(TBN, uboSSAOKernel.samples[i].xyz); |
| 53 | + samplePos = fragPos + samplePos * SSAO_RADIUS; |
| 54 | + |
| 55 | + // project |
| 56 | + float4 offset = float4(samplePos, 1.0f); |
| 57 | + offset = mul(ubo.projection, offset); |
| 58 | + offset.xyz /= offset.w; |
| 59 | + offset.xyz = offset.xyz * 0.5f + 0.5f; |
| 60 | + |
| 61 | + float sampleDepth = -samplerPositionDepth.Sample(offset.xy).w; |
| 62 | + |
| 63 | + float rangeCheck = smoothstep(0.0f, 1.0f, SSAO_RADIUS / abs(fragPos.z - sampleDepth)); |
| 64 | + occlusion += (sampleDepth >= samplePos.z ? 1.0f : 0.0f) * rangeCheck; |
| 65 | + } |
| 66 | + occlusion = 1.0 - (occlusion / float(SSAO_KERNEL_SIZE)); |
| 67 | + |
| 68 | + return occlusion; |
| 69 | +} |
| 70 | + |
0 commit comments