X-Git-Url: http://git.lukelau.me/?p=opengl.git;a=blobdiff_plain;f=prefilterfrag.glsl;fp=prefilterfrag.glsl;h=87cd70e4dae93209cbd03d598fa57baefbd9b748;hp=0000000000000000000000000000000000000000;hb=d80972d96e5fcd444657f937ab2700039efa83d2;hpb=9e43c799021b7bcca324b988aae44e98b05d10b4 diff --git a/prefilterfrag.glsl b/prefilterfrag.glsl new file mode 100644 index 0000000..87cd70e --- /dev/null +++ b/prefilterfrag.glsl @@ -0,0 +1,67 @@ +#version 330 + +in vec3 localPos, normal; +out vec4 fragColor; + +uniform samplerCube environmentMap; +uniform float roughness; + +const float PI = 3.14159265359; + +//TODO: Put this in a separate shader program +float radicalInverse(uint bits) { + bits = (bits << 16u) | (bits >> 16u); + bits = ((bits & 0x55555555u) << 1u) | ((bits & 0xAAAAAAAAu) >> 1u); + bits = ((bits & 0x33333333u) << 2u) | ((bits & 0xCCCCCCCCu) >> 2u); + bits = ((bits & 0x0F0F0F0Fu) << 4u) | ((bits & 0xF0F0F0F0u) >> 4u); + bits = ((bits & 0x00FF00FFu) << 8u) | ((bits & 0xFF00FF00u) >> 8u); + return float(bits) * 2.3283064365386963e-10; +} + +vec2 hammersley(uint i, uint N) { + return vec2(float(i) / float(N), radicalInverse(i)); +} + +vec3 importanceSampleGGX(vec2 Xi, vec3 N, float roughness) { + float a = roughness * roughness; + + float phi = 2.f * PI * Xi.x; + float cosTheta = sqrt((1.f - Xi.y) / (1.f + (a * a - 1.f) * Xi.y)); + float sinTheta = sqrt(1.f - cosTheta * cosTheta); + + // spherical -> cartesian + vec3 H = vec3(cos(phi) * sinTheta, sin(phi) * sinTheta, cosTheta); + + vec3 up = abs(N.z) < 0.999 ? vec3(0, 0, 1) : vec3(1, 0, 0); + vec3 tangent = normalize(cross(up, N)); + vec3 bitangent = cross(N, tangent); + + vec3 sampleVec = tangent * H.x + bitangent * H.y + N * H.z; + return normalize(sampleVec); +} + +void main() { + vec3 N = normalize(localPos); + + // approximate view direction - no grazing specular reflections + vec3 R = N; + vec3 V = R; + + const uint sampleCount = 1024u; + float totalWeight = 0; + vec3 prefilteredColor = vec3(0); + for (uint i = 0u; i < sampleCount; i++) { + vec2 Xi = hammersley(i, sampleCount); + vec3 H = importanceSampleGGX(Xi, N, roughness); + vec3 L = normalize(2.f * dot(V, H) * H - V); + + float NdotL = max(dot(N, L), 0.f); + if (NdotL > 0) { + prefilteredColor += texture(environmentMap, L).rgb * NdotL; + totalWeight += NdotL; + } + } + + prefilteredColor = prefilteredColor / totalWeight; + fragColor = vec4(prefilteredColor, 1.f); +}