Modelcore
GGX microfacet distribution
Also called Trowbridge-Reitz distribution, GGX, GGX normal distribution function.
The density of microfacet normals D(h) = alpha^2 / (pi ((n.h)^2 (alpha^2 - 1) + 1)^2), normalized over projected area. It has a sharp peak and a long tail, and is the usual D of microfacet BRDFs.
The GGX distribution gives the density of microfacet normals in a microfacet BRDF: how much facet area per unit surface area has its normal in a small cone around the direction . With the parameter and ,
Trowbridge and Reitz derived this function in optics in 1975. Walter, Marschner, Li and Torrance used it again in 2007, named it GGX, and showed that it fits measured rough glass better than the Beckmann distribution. Compared with Beckmann at the same , it has a similar peak and a much longer tail, which gives a highlight with a bright core and a wide soft halo. It is now the default of real-time and offline physically based shading. This page gives the factor only; Smith masking-shadowing gives and Schlick's approximation gives .
The machine
The surface. A rough surface with the macro normal , the axis of a local frame. At a scale far below a pixel it is a height field of flat facets. is a density on the hemisphere of facet normals , in units of 1/sr.
The normalization. The facets, projected onto the macro surface, cover it exactly once:
For GGX this holds for every . With and after the integral over the azimuth, and then :
for ; for , and the integral is . This is a proved property of the formula.
The slope form. With the slope of the facet,
This is the form of Walter et al. In slope space it is the density of the 2D slope , which falls like . The Beckmann distribution has Gaussian slopes instead. Heitz (2014) calls both shape invariant: changing only stretches the slopes. Stretching the two slope axes by different factors gives the anisotropic form
which is the isotropic one when .
The parameter. is the width of the distribution of slopes. At the peak . As , tends to a delta at and the surface is a mirror. At , is constant on the hemisphere. Many renderers expose a roughness and set . Burley (2012) chose this remap because it made the change of roughness look more even to artists. It is a convention, not physics. This page uses itself everywhere.
Sampling. The density has the CDF in , so inversion gives for uniform, with a uniform azimuth. The change from to the reflected direction is on the microfacet BRDF page.
What it counts
counts facet area: is the area of the facets with normals in over the patch . The normalization counts projected area, not facet area: the facet area is larger, by the factor . In a BRDF, weights the facets that act as mirrors between and . Its integral against over the visible facets enters the masking function.
Example. For , the peak is . Beckmann with the same has the same peak.
| 0° | 10° | 20° | 30° | 45° | 60° | 75° | |
|---|---|---|---|---|---|---|---|
| GGX | 3.5368 | 2.0771 | 0.7423 | 0.2842 | 0.0965 | 0.0480 | 0.0325 |
| Beckmann | 3.5368 | 2.6618 | 1.0409 | 0.1549 | 0.00021 | 0.0000 | 0.0000 |
Near the peak GGX falls faster than Beckmann, and past about 25° it is far above it: at 45° by a factor of 456. Far from the peak, , a power law, while Beckmann decays like . These numbers come from the code of this page, which also checks the normalization by Gauss-Legendre quadrature to for from 0.02 to 2, the anisotropic normalization, and the sampling CDF with a Kolmogorov test.
Relation to other models
- Microfacet BRDF. GGX is the in . The derivation of the factor 4 and the albedo loss of the single scattering model are on that page.
- Beckmann. The other common , with Gaussian slopes. It was the of Cook and Torrance. At small the two are close near the peak.
- Blinn-Phong. The normalized lobe is also a valid , with a short tail like Beckmann's. The match to Beckmann is a common fit near the peak.
- GTR. Burley's generalized Trowbridge-Reitz family has GGX at . The Disney principled BRDF uses for the main lobe and for the clear coat, with a longer tail.
- Smith masking. Each has its own . For GGX, has a closed form, which is one reason for its use.
Known results in the model
- Normalization (proved). for all , shown above, and for the anisotropic form for all .
- Long tail (proved). In slopes, the density falls like , so its second moment is infinite. The variance of the slopes is not a useful roughness measure for GGX; is a scale, not a standard deviation.
- Fit to measurements (measurement). Walter et al. fitted GGX and Beckmann to measured transmission through rough glass and found that GGX matched the long tails better. Which fits a given material best is a measurement for that material.
- Energy loss (proved for the model). With single scattering and Smith , the albedo of a white GGX conductor drops as grows, because light that would scatter more than once is lost. The microfacet BRDF page gives the numbers. Multiple scattering models correct this.
Proof: Properties of the GGX distributionfull
Setting. For and a unit vector with , the code evaluates for and otherwise. It also evaluates the slope form, the anisotropic form and a sampler. The claims are about these formulas in exact arithmetic. Whether GGX fits a given material is a measurement and is not claimed here.
Claim 1 (normalization). for every .
Proof. does not depend on the azimuth, and , so with the integral is . With , , this is . For an antiderivative is , so the integral is . For the integrand is 1 and the integral is .
Claim 2 (the slope form). For , .
Proof. , since . Squaring gives .
Claim 3 (the anisotropic form). equals when , and it is normalized for all .
Proof. With , , so the bracket is , and . For normalization, map a normal to its slope . Then with , because . For this gives . The substitution , turns into .
Claim 4 (sampling). If is uniform in and , with an independent uniform azimuth, then has the density on the hemisphere.
Proof. By Claim 1 and the substitution there, the probability that the angle of a normal drawn with the density is at most is . Computing it with the antiderivative of Claim 1 gives . This is continuous and increasing from 0 to 1, and solving gives . So has the distribution , by the inverse transform method. The density does not depend on the azimuth, so a uniform azimuth completes the sample.
Claim 5 (peak and tail). , and as .
Proof. At the bracket is . As the bracket tends to 1 and , so .
What the tests check. Claims 1 and 3 by Gauss-Legendre quadrature, Claims 2 and 3 at random points, Claim 4 by a Kolmogorov test of 20000 samples per , and Claim 5 at sample points. The page table of GGX and Beckmann values is checked to five digits.
Code
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ggx-distribution/. The authors are listed in prov/CCM8S7.jsonl.
"""The GGX (Trowbridge-Reitz) distribution of microfacet normals.
Directions are in the local frame of the surface: the normal n is the z
axis, and a unit vector h has cos(theta_h) = h[2]. alpha is the parameter of
the distribution itself, not a perceptual roughness. A renderer that exposes
a roughness r often sets alpha = r^2; that remap is a convention.
"""
import math
import random
Vec = tuple[float, float, float]
def ggx_d(cos_h: float, alpha: float) -> float:
"""D(h) = alpha^2 / (pi ((n.h)^2 (alpha^2 - 1) + 1)^2) for n.h > 0, else 0."""
if cos_h <= 0.0:
return 0.0
a2 = alpha * alpha
t = cos_h * cos_h * (a2 - 1.0) + 1.0
return a2 / (math.pi * t * t)
def ggx_d_aniso(h: Vec, ax: float, ay: float) -> float:
"""The anisotropic form with alpha_x along the x axis and alpha_y along y."""
if h[2] <= 0.0:
return 0.0
t = (h[0] / ax) ** 2 + (h[1] / ay) ** 2 + h[2] ** 2
return 1.0 / (math.pi * ax * ay * t * t)
def ggx_d_slope(cos_h: float, alpha: float) -> float:
"""The same D written with the slope tan(theta_h), as in Walter et al. 2007."""
if cos_h <= 0.0:
return 0.0
t2 = (1.0 - cos_h * cos_h) / (cos_h * cos_h)
a2 = alpha * alpha
return a2 / (math.pi * cos_h ** 4 * (a2 + t2) ** 2)
def beckmann_d(cos_h: float, alpha: float) -> float:
"""The Beckmann distribution, for comparison of the tails."""
if cos_h <= 0.0:
return 0.0
t2 = (1.0 - cos_h * cos_h) / (cos_h * cos_h)
return math.exp(-t2 / (alpha * alpha)) / (math.pi * alpha * alpha * cos_h ** 4)
def sample_ggx(rng: random.Random, alpha: float) -> Vec:
"""Sample h with the density D(h) (n.h) by inversion of its CDF.
The CDF of theta_h is F = tan^2 / (alpha^2 + tan^2), so
tan^2(theta_h) = alpha^2 u / (1 - u) for u uniform in [0, 1).
"""
u = rng.random()
phi = 2.0 * math.pi * rng.random()
tan2 = alpha * alpha * u / (1.0 - u)
cos_t = 1.0 / math.sqrt(1.0 + tan2)
sin_t = math.sqrt(max(0.0, 1.0 - cos_t * cos_t))
return (sin_t * math.cos(phi), sin_t * math.sin(phi), cos_t)
def cdf_theta(theta: float, alpha: float) -> float:
"""P(theta_h <= theta) for h drawn with the density D(h) (n.h)."""
t2 = math.tan(theta) ** 2
return t2 / (alpha * alpha + t2)
test_ggx_distribution.py 119 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ggx-distribution/. The authors are listed in prov/CCM8S7.jsonl.
"""Tests of the GGX distribution by quadrature and by sampling."""
import math
import random
from ggx_distribution import beckmann_d, cdf_theta, ggx_d, ggx_d_aniso, ggx_d_slope, sample_ggx
def legendre_nodes(n: int) -> list[tuple[float, float]]:
"""Gauss-Legendre nodes and weights on [-1, 1], by Newton's method."""
out = []
for i in range(1, n + 1):
x = math.cos(math.pi * (i - 0.25) / (n + 0.5))
for _ in range(100):
p0, p1 = 1.0, x
for k in range(2, n + 1):
p0, p1 = p1, ((2 * k - 1) * x * p1 - (k - 1) * p0) / k
dp = n * (x * p1 - p0) / (x * x - 1.0)
dx = p1 / dp
x -= dx
if abs(dx) < 1e-15:
break
out.append((x, 2.0 / ((1.0 - x * x) * dp * dp)))
return out
GL = legendre_nodes(16)
def integrate(f, a: float, b: float, panels: int) -> float:
"""Composite Gauss-Legendre rule with 16 nodes per panel."""
total = 0.0
hw = (b - a) / panels / 2.0
for k in range(panels):
mid = a + (2 * k + 1) * hw
total += hw * sum(w * f(mid + hw * x) for x, w in GL)
return total
def test_normalization() -> None:
# The integral of D(h) (n.h) over the hemisphere, in theta_h.
for alpha in (0.02, 0.1, 0.3, 0.5, 1.0, 2.0):
val = integrate(
lambda t: ggx_d(math.cos(t), alpha) * math.cos(t) * math.sin(t) * 2.0 * math.pi,
0.0,
math.pi / 2.0,
200,
)
assert abs(val - 1.0) < 1e-6
def test_anisotropic_normalization() -> None:
for ax, ay in ((0.2, 0.6), (0.5, 0.1), (0.4, 0.4)):
def ring(t: float) -> float:
st, ct = math.sin(t), math.cos(t)
inner = integrate(
lambda p: ggx_d_aniso((st * math.cos(p), st * math.sin(p), ct), ax, ay),
0.0,
2.0 * math.pi,
8,
)
return inner * ct * st
val = integrate(ring, 0.0, math.pi / 2.0, 40)
assert abs(val - 1.0) < 1e-3
def test_forms_agree() -> None:
rng = random.Random(1)
for _ in range(200):
alpha = rng.uniform(0.05, 1.5)
t = rng.uniform(0.0, 1.5)
st, ct = math.sin(t), math.cos(t)
p = rng.uniform(0.0, 2.0 * math.pi)
d = ggx_d(ct, alpha)
assert abs(ggx_d_slope(ct, alpha) - d) < 1e-9 * d
assert abs(ggx_d_aniso((st * math.cos(p), st * math.sin(p), ct), alpha, alpha) - d) < 1e-9 * d
def test_peak_and_tail() -> None:
for alpha in (0.1, 0.3, 0.7):
assert abs(ggx_d(1.0, alpha) - 1.0 / (math.pi * alpha * alpha)) < 1e-9
assert abs(beckmann_d(1.0, alpha) - ggx_d(1.0, alpha)) < 1e-9
# Values on the page, alpha = 0.3.
assert abs(ggx_d(math.cos(math.radians(30.0)), 0.3) - 0.28419) < 1e-5
assert abs(beckmann_d(math.cos(math.radians(30.0)), 0.3) - 0.15488) < 1e-5
# The tail of GGX is longer: past some angle it is above Beckmann.
for deg in (45.0, 60.0, 75.0):
c = math.cos(math.radians(deg))
assert ggx_d(c, 0.3) > 100.0 * beckmann_d(c, 0.3)
# D falls like cos^-4 / tan^4 far from the peak: D sin^4 tends to alpha^2 / pi.
c = math.cos(math.radians(89.99))
assert abs(ggx_d(c, 0.3) * (1.0 - c * c) ** 2 - 0.09 / math.pi) < 1e-6
def test_sampling_matches_cdf() -> None:
rng = random.Random(2)
n = 20000
for alpha in (0.1, 0.5):
thetas = sorted(math.acos(min(1.0, sample_ggx(rng, alpha)[2])) for _ in range(n))
ks = max(abs((i + 1) / n - cdf_theta(t, alpha)) for i, t in enumerate(thetas))
assert ks < 1.63 / math.sqrt(n) # the 1 percent level of the Kolmogorov test
def test_monte_carlo_normalization() -> None:
# Uniform directions on the hemisphere: E[2 pi D(h) (n.h)] = 1.
rng = random.Random(3)
n = 40000
alpha = 0.5
vals = []
for _ in range(n):
cos_h = rng.random() # uniform on the hemisphere has a uniform cos
vals.append(2.0 * math.pi * ggx_d(cos_h, alpha) * cos_h)
mean = sum(vals) / n
var = sum((v - mean) ** 2 for v in vals) / (n - 1)
assert abs(mean - 1.0) < 4.0 * math.sqrt(var / n)
References
- Bruce Walter, Stephen R. Marschner, Hongsong Li and Kenneth E. Torrance, Microfacet models for refraction through rough surfaces, Eurographics Symposium on Rendering, 2007, 195 to 206, the GGX distribution, its Smith masking function and its sampling, fitted to measured rough glass
- T. S. Trowbridge and K. P. Reitz, Average irregularity representation of a rough surface for ray reflection, Journal of the Optical Society of America 65(5), 1975, 531 to 536, the distribution of facet normals from ellipsoidal irregularities, the same function as GGX (general locator)
- Eric Heitz, Understanding the masking-shadowing function in microfacet-based BRDFs, Journal of Computer Graphics Techniques 3(2), 2014, 48 to 107, Section 5.3, Isotropic Shape-Invariant Distributions of Slopes (GGX in Equation 71 and its Lambda in Equation 72), and Section 5 on stretching for the anisotropic form
- Brent Burley, Physically-based shading at Disney, course notes, SIGGRAPH 2012 course Practical Physically Based Shading in Film and Game Production, revised 2014, Section 5.4, Specular D details (the GTR family with GGX as gamma = 2, and the remap alpha = roughness^2), and Appendix B
- Tomas Akenine-Möller, Eric Haines, Naty Hoffman, Angelo Pesce, Michał Iwanicki and Sébastien Hillaire, Real-Time Rendering, fourth edition, CRC Press, 2018, Chapter 9, Physically Based Shading (the section on normal distribution functions)
- Matt Pharr, Wenzel Jakob and Greg Humphreys, Physically Based Rendering, From Theory to Implementation, third edition, Morgan Kaufmann, 2016, Section 8.4, Microfacet Models (the Trowbridge-Reitz distribution)
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H2 full proof |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag CCM8S7 Edit this page History Report an error Markdown