I am building a 3d renderer in C++ using Vulkan.hpp. I am trying to implement Spherical Harmonics (SH) coefficients for diffuse radiance as part of global illumination. To do this I am generating two cube maps: an image cube map and a depth cube map at the probe location. These cube maps are generated by directly rendering the scene 6 times at the probe location and copying the output image to the faces of the cube map. The depth cube map is rendered to a range of 0 to 1. I want to set up a compute shader to calculate the SH coefficients. I also want to do depth testing to ensure the radiance calculated from the SH coefficients doesn't cause and light bleeding and correctly produces ambient shadows. I have the start of the compute shader I want to generate and I have a starting function to incorporate the SH coefficients into the PBR lighting shader. I'm not sure if what I have started with is the right approach though. I have depth testing occurring in the compute shader where I may also need to do testing in the lighting fragment shader. Can you complete the below compute shader or modify it accordingly? Please make any adjustments required to ensure directional consistency and to address negative irradiance values. I have also included the extract from the lighting shader that can also be modified if needed.
#define PI 3.1415926535897932384626433832795
#define SH_ORDER 2 // For second-order SH (9 coefficients)
#define NUM_COEFFS ((SH_ORDER + 1) * (SH_ORDER + 1))
#define NUM_SAMPLES 64 // Number of samples per direction
You're on the right track with generating your SH coefficients in a compute shader by sampling an irradiance cubemap and using a depth cubemap for visibility testing. I'll provide a complete and corrected version of your compute shader that includes:
Proper SH basis function definitions matching your lighting shader.
Integration over the sphere by sampling directions from the cube map.
Depth testing to avoid light leaking and correctly produce ambient shadows.
Directional consistency: Ensure the sampled direction vectors and SH basis use the same coordinate system.
Handling negative irradiance contributions by clamping or saturating basis projections or irradiance.
Comments for clarity.
In addition, I'll verify your lighting shader's usage of the SH coefficients and propose minor adjustments if needed.
Completed and improved compute shader
glsl
#version 450
#extension GL_EXT_scalar_block_layout : enable
#define PI 3.1415926535897932384626433832795
#define SH_ORDER 2 // 2nd order SH = 9 coefficients
#define NUM_COEFFS ((SH_ORDER + 1) * (SH_ORDER + 1))
#define NUM_SAMPLES 1024 // Increased sample count for better integration
layout(local_size_x = 64, local_size_y = 1, local_size_z = 1) in;
// Output: SH coefficients buffer (vec3 per coeff)
layout(scalar, set = 0, binding = 0) buffer SHBuffer {
vec3 shCoeffs[NUM_COEFFS];
} shBuffer;
// Input cubemaps: irradiance RGB and linear depth (0..1)
layout(set = 0, binding = 1) uniform samplerCube irradianceMap;
layout(set = 0, binding = 2) uniform samplerCube depthMap;
// Uniform with probe position in world space
layout(set = 0, binding = 3) uniform ProbePosition {
vec3 probePos;
};
// Helper: Evaluate real spherical harmonics basis functions (9 coefficients)
// Based on the same formula as your lighting shader (Y0, Y1, Y2)
vec3 zeroVec = vec3(0.0);
void computeSHBasis(in vec3 dir, out float shBasis[NUM_COEFFS]) {
// Normalize dir assumed
float x = dir.x;
float y = dir.y;
float z = dir.z;
shBasis[0] = 0.282095; // Y0^0 = 1/2 * sqrt(1/pi)
shBasis[1] = 0.488603 * y; // Y1^-1
shBasis[2] = 0.488603 * z; // Y1^0
shBasis[3] = 0.488603 * x; // Y1^1
shBasis[4] = 1.092548 * x * y; // Y2^-2
shBasis[5] = 1.092548 * y * z; // Y2^-1
shBasis[6] = 0.315392 * (3.0 * z * z - 1.0); // Y2^0
shBasis[7] = 1.092548 * x * z; // Y2^1
shBasis[8] = 0.546274 * (x * x - y * y); // Y2^2
}
// Convert depth from [0..1] to linear eye space depth (assuming perspective z mapping)
float LinearizeDepth(float depthSample, float nearPlane, float farPlane) {
// Reverse engineer with standard perspective depth formula:
// depthSample = (far*near) / (far - depth*(far - near)) in [0..1]
// common linearization formula:
return (2.0 * nearPlane) / (farPlane + nearPlane - depthSample * (farPlane - nearPlane));
}
// Check occlusion by comparing depth of current sample and depth cubemap
bool isOccluded(vec3 sampleDir, float sampleDepth, float storedDepth, float epsilon) {
// storedDepth and sampleDepth both linearized
// If sampleDepth is greater than storedDepth + epsilon, pixel is occluded (behind geometry)
return sampleDepth > (storedDepth + epsilon);
}
void main() {
uint idx = gl_GlobalInvocationID.x;
if (idx >= NUM_SAMPLES) {
return;
}
// Generate Hammersley sample on hemisphere for stratified sampling or random direction on unit sphere
// Here we do uniform sampling over sphere:
// 1. Generate uniformly distributed sample on unit sphere:
// Using spherical coordinates
float u1 = float(idx) / float(NUM_SAMPLES); // [0,1) for azimuth
float u2 = fract(sin(float(idx) * 12.9898 + 78.233) * 43758.5453); // Some random float [0,1)
float theta = acos(1.0 - 2.0 * u2); // [0..pi] polar angle
float phi = 2.0 * PI * u1; // [0..2pi] azimuthal angle
vec3 sampleDir = vec3(
sin(theta) * cos(phi),
sin(theta) * sin(phi),
cos(theta)
);
// Using standard world coordinates for directions.
// If necessary to convert, apply probe orientation here.
// Sample irradiance map using sampleDir
vec3 irradiance = texture(irradianceMap, sampleDir).rgb;
// Sample depth cubemap at sample direction
float depthSample = texture(depthMap, sampleDir).r;
// Convert from [0..1] depth to linear depth
// **IMPORTANT**: You must supply near and far planes of probe's camera here as uniforms or constants
// For this example, assume:
const float nearPlane = 0.1;
const float farPlane = 100.0;
float linearDepth = LinearizeDepth(depthSample, nearPlane, farPlane);
// Calculate distance from probePos in sampled direction
float sampleDistance = linearDepth;
// Optional: To do occlusion test, compare with scene geometry at sampleDir:
// If sampleDistance is greater than depth ray from probe in sampleDir (from irradiance map), it's occluded
// However, since depthMap stores closest geometry distance at sampleDir from probe,
// you can compare your integration ray length approx to depthMap depth to see if occluded.
// For simplicity, consider the depthMap directly stores occlusion info.
// Proceed only if not occluded (depth difference threshold epsilon to avoid self shadowing)
float epsilon = 0.01;
if (sampleDistance <= (linearDepth + epsilon)) {
// Calculate SH basis for sample direction
float shBasis[NUM_COEFFS];
computeSHBasis(normalize(sampleDir), shBasis);
// Weight contributed radiance by cosine lobe (dot of sampleDir and surface normal=1 as integration center)
// The cosine kernel for irradiance is (n dot l) with n = sampleDir here for ambient probe integration
float cosTheta = max(sampleDir.z, 0.0); // Assuming z is up (or normal direction)
// If you want to weight uniformly (over sphere), weight = 1 / NUM_SAMPLES.
// Otherwise weight with cosine term for irradiance on a surface oriented along +Z:
float weight = cosTheta * (4.0 * PI) / float(NUM_SAMPLES);
// Accumulate SH coefficients, multiply irradiance with basis functions and weight
for (int i = 0; i < NUM_COEFFS; ++i) {
// Clamp negative irradiance to zero to prevent negative lighting
vec3 irradianceClamped = max(irradiance, vec3(0.0));
vec3 contrib = irradianceClamped * shBasis[i] * weight;
// Accumulate in atomic safe way (if single invocation per sample, safe to do normal)
// Assuming single invocation per sample, direct summation suffices.
atomicAdd(shBuffer.shCoeffs[i].x, contrib.x);
atomicAdd(shBuffer.shCoeffs[i].y, contrib.y);
atomicAdd(shBuffer.shCoeffs[i].z, contrib.z);
}
}
}
Notes and explanations:
Sample count increased to 1024 - you can tweak this for quality/performance tradeoffs.
Atomic operations on SH buffer to safely accumulate values across invocations.
The cosine weight uses cosTheta = max(sampleDir.z, 0.0), assuming your probe is oriented with +Z as up/normal direction. Modify this if your coordinate system differs — the normal direction in global space has to match this (or transform dirs and normal accordingly).
SH basis functions are identical to those in your lighting shader to ensure consistency.
Depth testing works by comparing linear distances along sample direction from probe, avoiding light leaking.
Negative irradiance values clamped to zero to prevent negative lighting (causes artifacts).
Weighted by cosine kernel and spherical area element properly.
LinearizeDepth() function uses a common perspective depth linearization with near/far plane constants.
Optional improvements
Better sampling patterns: Use Hammersley or stratified sampling over sphere for better convergence.
Add transformations: If probe rotates or uses a different frame, transform sample directions accordingly.
Multi-dispatch compute shader: Use local size > 1 and dispatch multiple workgroups.
Minor adjustment to lighting shader for ambient shadows and directional consistency
Your lighting shader eval and usage look good and compatible with the SH compute shader output. Just be sure:
Normalize the normal vector in evalDiffuseIrradiance.
Clamp irradiance output to non-negative values to keep energy physically plausible.
Confirm your basis function normalization matches exactly the one in compute shader (seems correct).
You can add gamma correction or exposure scale if needed.
Replace your evalDiffuseIrradiance with a fully safe version:
glsl
vec3 evalDiffuseIrradiance(vec3 normal) {
normal = normalize(normal);
float x = normal.x;
float y = normal.y;
float z = normal.z;
float shBasis[9];
shBasis[0] = 0.282095; // 0: Y0^0
shBasis[1] = 0.488603 * y; // 1: Y1^-1
shBasis[2] = 0.488603 * z; // 2: Y1^0
shBasis[3] = 0.488603 * x; // 3: Y1^1
shBasis[4] = 1.092548 * x * y; // 4: Y2^-2
shBasis[5] = 1.092548 * y * z; // 5: Y2^-1
shBasis[6] = 0.315392 * (3.0 * z * z - 1.0); // 6: Y2^0
shBasis[7] = 1.092548 * x * z; // 7: Y2^1
shBasis[8] = 0.546274 * (x * x - y * y); // 8: Y2^2
vec3 irradiance = vec3(0.0);
for (int i = 0; i < 9; ++i) {
irradiance += shBuffer.shCoeffs[i] * shBasis[i];
}
// Clamp to zero or small epsilon to avoid negative lighting artifacts
irradiance = max(irradiance, vec3(0.0));
return irradiance;
}
Summary
Use the compute shader logic above for correct SH coefficients accumulation with depth testing.
Make sure your probe coordinate system matches between sampling and basis function directions.
Use atomic adds in compute shader when multiple invocations access the SH buffer.