Writing Custom PBR Shaders in WebGL: Cook-Torrance BRDF Math
Implementing Physically Based Rendering (PBR) equations directly in GLSL fragment shaders to simulate real-world material responses to metallic and dielectric lighting.
Standard Phong and Blinn-Phong shading models fail to represent real-world physical material behavior. Physically Based Rendering (PBR) uses the Cook-Torrance specular BRDF model to preserve energy conservation across varying surface roughness and metallic parameters.
1. The Microfacet Specular BRDF Equations
The Cook-Torrance specular reflectance depends on three key terms: Normal Distribution Function (D), Geometry Function (G), and Fresnel Equation (F).
2. Trowbridge-Reitz GGX and Fresnel-Schlick in GLSL
In GLSL fragment code, the GGX microfacet distribution models surface roughness variations, while the Fresnel-Schlick approximation calculates the ratio of light reflected versus light refracted across view angles.
3. Image-Based Lighting (IBL) & Environment Maps
Specular reflection for environmental lighting requires pre-filtered cubemaps. Integrating diffuse irradiance convolutions with specular BRDF lookup textures (LUT) enables real-time physical lighting without heavy ray-tracing overhead.