Algorithmresearch
Ground-truth ambient occlusion
Also called GTAO.
A horizon-based screen-space method that integrates cosine-weighted visibility in closed form per slice. Its match with ray traced AO is a measurement, for one depth layer only.
- Time
- O(p m s) worst
- Space
- O(p) extra
- Where
- m = the number of slices per pixel; p = the number of pixels; s = the number of steps per side of a slice
- Model
- Real RAM
- Properties
- deterministicnot in placeofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Jorge Jimenez, Xian Chun Wu, Angelo Pesce, Adrian Jarabo, 2016
Ground-truth ambient occlusion is a screen-space method that computes the cosine-weighted ambient occlusion of the surface seen in the depth buffer. Like horizon-based ambient occlusion, it marches the depth buffer to find horizon angles. It differs in how it splits the hemisphere: into slices, planes through the view vector, each with a horizon on both sides. Inside a slice, the integral of the cosine between the normal and the direction over the open angles has a closed form, so the only numerical integration left is over the slices. Jimenez, Wu, Pesce and Jarabo described it in 2016. The name says ground truth, but the result equals ray traced ambient occlusion only for the scene that the depth buffer describes, a single layer read as a solid height field. How close it comes on real scenes is a measurement.
In plain words
Ambient occlusion asks how much of the sky a point sees, counting directions near the normal more than directions near the ground, as a matte surface does. Horizon methods walk across the depth buffer in a few directions and find, in each, how high the surrounding surface rises. GTAO cuts the half sphere above the point into thin vertical slices, like slices of an orange around the line of sight. In each slice, it finds the horizon on the left and on the right. Between the two horizons the sky is open, and the cosine-weighted share of that open arc can be written down with a formula. So each slice costs one march and one formula, and a few slices give the answer.
The problem
The input is a depth buffer of pixels and the normals, from a G-buffer or from differences of . The output is the visibility
per pixel, where is 1 if the direction is open. The depth buffer does not say what is behind the visible surface, so the method assumes that, seen from the pixel, a direction is blocked exactly when it is below the horizon of its slice.
This page and its code use an orthographic camera that looks along , so the view vector is at every pixel and the tests can use height fields. In a perspective camera the view vector changes from pixel to pixel; the slices are planes through it, and the points of the march are reconstructed as from the depth and the slopes of the pixel.
The algorithm
slices with a per-pixel offset , steps of length per side, and a radius . A slice is spanned by and the screen direction . Angles in a slice are measured from , positive toward .
GTAO(D, q, n, m, s, ℓ, R, ξ)- 1
A ← 0; P ← the point of q - 2
for k ← 0 to m - 1: φ ← π (k + ξ) / m; c ← (cos φ, sin φ, 0) - 3
n_p ← (n · c) c + (n · v) v; γ ← the angle of n_p from v - 4
h2 ← the smallest angle from v of the points of D at P + i ℓ c, i = 1..s, within R, and at most γ + π/2 - 5
h1 ← minus the same on the side P - i ℓ c, and at least γ - π/2 - 6
â ← ¼(-cos(2h1 - γ) + cos γ + 2 h1 sin γ) + ¼(-cos(2h2 - γ) + cos γ + 2 h2 sin γ) - 7
A ← A + |n_p| â - 8
return A / m
The slice (line L3). The projected normal has the length and the angle from in the slice. For a direction of the slice at the angle , .
The horizons (lines L4 and L5). Each side is marched as in HBAO, but the code keeps the largest cosine to of the vectors from to the samples, which is the smallest angle. The search starts at the tangent of the surface, , so that the horizons are clamped to the hemisphere of the normal.
The inner integral (line L6). With in slice coordinates, the open part of a slice contributes , and the expression of line L6 is its antiderivative evaluated at the two horizons. The proofs folder derives it. The report of Jimenez and others gives a closed form for the same integral; this page does not quote its equation.
The rest of the frame. The report runs few slices per pixel, rotates them per pixel and per frame, and removes the noise with spatial and temporal filters. These choices are tuning and are not in the code.
Example
A frontal floor meets a block that rises by toward the camera along a straight line. At the distance from its foot, the cosine-weighted visibility of the height field is , the view factor of a strip (proved in the proofs folder). The code uses 32 slices and steps of 0.25 units with no radius limit.
| exact GTAO value | code | HBAO with no falloff | |
|---|---|---|---|
| 2.5 | 0.649 | 0.654 | 0.596 |
| 4.5 | 0.745 | 0.750 | 0.663 |
| 8.5 | 0.864 | 0.867 | 0.760 |
The code is within 0.005 of the formula; the rest comes from the step length at the edge of the block. HBAO without falloff measures the solid angle without the cosine, so the same wall darkens the point more: directions near the ground count as much as directions near the normal.
One layer. Replace the block by a plate of thickness 1 that floats 4 units above the floor and is 6 units wide. The depth buffer looks the same as for a solid block 5 units high and 6 wide. At a floor point 3.5 units from the plate, the code gives . Cosine-weighted rays against the true plate, which can pass under it, give with 40000 rays. The method is exact for the depth buffer but not for the scene.
Correctness
The proofs are in the proofs folder. In slice coordinates, a direction is with and ; this covers the sphere once, with , and . Under the height-field assumption, the open directions of a slice are those between the two clamped horizons, so the cosine-weighted visibility is , and line L6 is the inner integral in closed form. An open slice gives , and the outer integral of an open hemisphere is exactly 1, so every plane gives . The wall formula of the example is proved with a standard integral. The tests check the closed form against Simpson's rule, planes against 1, and the wall against both the formula and cosine-weighted rays. That the result also matches ray traced ambient occlusion is true only for the height field; for real scenes it is a measurement, as the plate shows.
Proof: The slice integral of ground-truth ambient occlusion and its closed formfull
Setting. The camera is orthographic and looks along , so the view vector is at every pixel, as in the code. A pixel has the point and the unit normal with . For let . The slice is the plane spanned by and , and a direction in it is with , measured from and positive toward . The projection of into the slice is , with the length and the angle from . The height-field assumption: in each slice, the directions between the two horizons are open and the others are blocked, where the horizons are clamped to . The ambient occlusion visibility is .
Lemma 1 (slice coordinates). The map on covers the unit sphere once, apart from the two directions , with . In it, .
Proof. With as the polar axis, a direction with has the polar angle and the azimuth , and one with has the polar angle and the azimuth . As runs over the two cases cover all azimuths once, and the spherical element is . Next, .
Theorem 1 (the slice integral). Under the height-field assumption,
Proof. By Lemma 1, in the slice exactly for , and the open part of it is because of the clamp. Substituting Lemma 1 into the definition of gives the formula.
Theorem 2 (closed form). For ,
Proof. On , and , so
using . On , , and the same antiderivative gives .
The tests compare this form with Simpson's rule at random arguments and find agreement to . This page derives the formula itself; it is not copied from the report of Jimenez and others.
Theorem 3 (open surfaces). If every slice is open, and , then and . In particular, a plane gives , and a frontal plane gives in every slice.
Proof. With , , and Theorem 2 gives . The integral of Theorem 1 is then , the cosine integral over a hemisphere. On a plane, every sample lies in the tangent plane, so no horizon rises above the clamp. For , and .
The code sums equally spaced slices, the rectangle rule for an integrand that is smooth and periodic in with period . For a tilted plane the sum is not exactly 1, but the error falls fast with : the tests measure an error below with 16 slices for slopes up to 1.3.
Theorem 4 (the wall). Let lie on a frontal floor, , at the distance from the foot of an infinite straight wall that rises by toward the camera, with a flat top. With no radius limit,
Proof. Here and . Put the wall at . In the slice with , the side that points to reaches the foot at the horizontal distance , and the top edge has the elevation above the view plane with , which is the largest elevation on that side. So that horizon is in absolute value, and the other side is open with the horizon . By Theorem 2 with , the open side gives , and the wall side gives . So with , and
The standard integral for , gives , so .
This is the view factor of an infinite strip seen from a point, which also follows from the crossed-strings rule. The same wall gives under the solid-angle measure of horizon-based ambient occlusion. The tests check the formula by cosine-weighted Monte Carlo rays and the code against it within 0.01.
Theorem 5 (range). In the integral of Theorem 1, , and the occlusion grows when a horizon rises.
Proof. On the integrand is non-negative, so and shrinks when shrinks. The largest value is the open case of Theorem 3.
What is not a theorem. The match of with ray traced ambient occlusion holds under the height-field assumption, that is, for the scene as the one layer of the depth buffer shows it. A real scene can have open space behind the visible surface. The tests render a plate of thickness 1 whose bottom is 4 units above the floor: the depth buffer sees only its top, as if it were a solid block, and the code gives at a floor point 3.5 units from the plate, while cosine-weighted rays against the true plate give . Any statement about how close GTAO comes to ray traced ambient occlusion in real scenes is a measurement.
Theorem 6 (cost). For pixels, slices and steps per side, the cost is .
Proof. Each slice marches steps of work and evaluates Theorem 2 once.
Complexity
The model is the real RAM. Each pixel marches slices with steps each and evaluates the closed form times: in total, and memory for the result. This is the cost of HBAO with directions. The closed form costs a few trigonometric functions per slice, which is small next to the depth reads.
Properties
- Cosine weighted. The value is the ambient occlusion integral with the cosine to the normal, not the solid angle.
- Exact for the height field. With exact horizons and many slices, the result is the visibility of the depth buffer read as a solid surface.
- One layer. Space behind the visible surface counts as blocked, so thin objects over-occlude.
- Planes are open. Every plane gives , tilted or not.
- Smooth in the slice. The inner integral needs no samples, only the two horizons.
- Screen space. Off-screen geometry does not occlude.
Variants and improvements
- Multiple bounces. The report maps the visibility to an approximate multi-bounce value with a function fitted to ray traced data, as a function of the visibility and the albedo. The fit is a measurement.
- Specular occlusion. The report also derives an occlusion term for glossy reflections from the visibility and a bent normal.
- Thickness heuristic. Let the horizon fall back over distance, as if objects had a finite thickness, which reduces the over-occlusion of thin objects.
- Temporal accumulation. One or two slices per pixel and frame, with a different rotation each frame, filtered over time as in temporal antialiasing.
- Bitmask visibility. Later methods replace the two horizons by a bit mask of open sectors per slice, which can represent gaps behind thin objects.
When to use it
Use GTAO when the ambient occlusion of a real-time renderer should look close to that of a ray tracer and the budget is that of HBAO. It needs depth and normals and a denoiser. Use ray traced ambient occlusion when thin geometry, off-screen occluders or the space behind the first layer matter.
Pitfalls
- Ground truth of what. The match is for the depth buffer as a height field. Thin objects, foliage and gaps under objects come out too dark.
- Wrong normals. The clamp and depend on the normal. Normals from depth differences tilt at edges, and normal maps give normals that do not match the depth surface.
- Radius. A limit on the march radius opens far occluders abruptly. Use a falloff and accept it as tuning.
- Perspective. In a perspective camera the view vector and the slice change per pixel. Using a constant view vector bends the slices near the edges of a wide view.
- Noise. Few slices need filtering, and the filter must respect depth edges, or the occlusion leaks across them.
Implementations
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/ground-truth-ambient-occlusion/. The authors are listed in prov/2H8H92.jsonl.
"""Ground-truth ambient occlusion: horizons per slice and a closed-form
cosine-weighted inner integral.
The camera is orthographic and looks along -z, so the view vector is
v = (0, 0, 1) everywhere and the tests can use height fields. The pixel (i, j)
has its center at (i + 1/2, j + 1/2) in view units, D[j][i] is the positive
view depth, and the point of a pixel is (x, y, -d).
A slice is the plane through v and a screen direction (cos phi, sin phi, 0).
Angles h in a slice are measured from v, positive toward the screen
direction. The two horizons h1 <= 0 <= h2 are found by marching the depth
buffer both ways and clamped to the hemisphere of the normal. The visibility is
A = (1 / pi) integral over phi in [0, pi) of |n_p| a(phi) dphi,
a = integral from h1 to h2 of cos(h - gamma) |sin h| dh,
where n_p is the normal projected into the slice and gamma its angle from v.
The inner integral has the closed form of inner_integral().
"""
import math
from typing import List, Optional, Tuple
Vec = Tuple[float, float, float]
Grid = List[List[float]]
def lookup(D: Grid, x: float, y: float, mode: str = "nearest") -> float:
h, w = len(D), len(D[0])
if mode == "nearest":
i = min(max(int(math.floor(x)), 0), w - 1)
j = min(max(int(math.floor(y)), 0), h - 1)
return D[j][i]
u = min(max(x - 0.5, 0.0), w - 1.0)
v = min(max(y - 0.5, 0.0), h - 1.0)
i0, j0 = min(int(u), w - 2), min(int(v), h - 2)
fu, fv = u - i0, v - j0
top = D[j0][i0] * (1 - fu) + D[j0][i0 + 1] * fu
bot = D[j0 + 1][i0] * (1 - fu) + D[j0 + 1][i0 + 1] * fu
return top * (1 - fv) + bot * fv
def normal_from_depth(D: Grid, i: int, j: int) -> Vec:
h, w = len(D), len(D[0])
il, ir = max(i - 1, 0), min(i + 1, w - 1)
jb, jt = max(j - 1, 0), min(j + 1, h - 1)
gx = (D[j][ir] - D[j][il]) / (ir - il)
gy = (D[jt][i] - D[jb][i]) / (jt - jb)
s = math.sqrt(gx * gx + gy * gy + 1.0)
return (gx / s, gy / s, 1.0 / s)
def inner_integral(h1: float, h2: float, gamma: float) -> float:
"""The integral of cos(h - gamma) |sin h| over [h1, h2], for h1 <= 0 <= h2."""
a = 0.25 * (-math.cos(2 * h1 - gamma) + math.cos(gamma) + 2 * h1 * math.sin(gamma))
b = 0.25 * (-math.cos(2 * h2 - gamma) + math.cos(gamma) + 2 * h2 * math.sin(gamma))
return a + b
def _max_cos(D, px, py, d, cx, cy, steps, step, radius, start, mode):
"""The largest cosine to v of the samples on one side, starting at the
cosine of the clamped tangent horizon."""
best = start
for s in range(1, steps + 1):
r = s * step
dz = d - lookup(D, px + r * cx, py + r * cy, mode)
dist = math.hypot(r, dz)
if dist > radius:
continue
best = max(best, dz / dist)
return best
def gtao_pixel(
D: Grid,
i: int,
j: int,
slices: int,
steps: int,
step: float,
radius: float,
jitter: float = 0.0,
normal: Optional[Vec] = None,
mode: str = "nearest",
) -> float:
d = D[j][i]
px, py = i + 0.5, j + 0.5
n = normal if normal is not None else normal_from_depth(D, i, j)
acc = 0.0 # @line L1
for k in range(slices): # @line L2
phi = math.pi * (k + jitter) / slices
cx, cy = math.cos(phi), math.sin(phi)
n_dir = n[0] * cx + n[1] * cy # @line L3
n_v = n[2]
length = math.hypot(n_dir, n_v)
gamma = math.atan2(n_dir, n_v)
# The tangent horizons gamma -/+ pi/2 have the cosines sin(gamma) and -sin(gamma).
c2 = _max_cos(D, px, py, d, cx, cy, steps, step, radius, -math.sin(gamma), mode) # @line L4
c1 = _max_cos(D, px, py, d, -cx, -cy, steps, step, radius, math.sin(gamma), mode) # @line L5
h1 = -math.acos(min(1.0, c1)) # @line L6
h2 = math.acos(min(1.0, c2))
acc += length * inner_integral(h1, h2, gamma) # @line L7
return acc / slices # @line L8
def gtao(D: Grid, slices: int, steps: int, step: float, radius: float, **kw) -> Grid:
return [[gtao_pixel(D, i, j, slices, steps, step, radius, **kw) for i in range(len(D[0]))] for j in range(len(D))]
def wall_reference(delta: float, height: float) -> float:
"""The cosine-weighted visibility of a point on a frontal floor at the
distance delta from an infinite wall of the given height, with no radius
limit: (1 + delta / sqrt(delta^2 + height^2)) / 2."""
return 0.5 * (1.0 + delta / math.hypot(delta, height))
test_ground_truth_ambient_occlusion.py 102 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ground-truth-ambient-occlusion/. The authors are listed in prov/2H8H92.jsonl.
"""GTAO: the closed form, planes, the wall, and the limit of one depth layer."""
import math
import random
from ground_truth_ambient_occlusion import (
gtao,
gtao_pixel,
inner_integral,
wall_reference,
)
FLOOR = 200.0
def simpson(f, a, b, n=2000):
h = (b - a) / n
s = f(a) + f(b)
for k in range(1, n):
s += (4 if k % 2 else 2) * f(a + k * h)
return s * h / 3
def test_closed_form_matches_quadrature() -> None:
rng = random.Random(81)
for _ in range(40):
gamma = rng.uniform(-1.5, 1.5)
h1 = rng.uniform(gamma - math.pi / 2, 0.0) if gamma < math.pi / 2 else 0.0
h2 = rng.uniform(0.0, gamma + math.pi / 2)
ref = simpson(lambda h: math.cos(h - gamma) * abs(math.sin(h)), h1, 0.0) + simpson(
lambda h: math.cos(h - gamma) * abs(math.sin(h)), 0.0, h2
)
assert abs(inner_integral(h1, h2, gamma) - ref) < 1e-10
assert abs(inner_integral(-math.pi / 2, math.pi / 2, 0.0) - 1.0) < 1e-15
def test_open_slice_integrates_to_one_over_the_hemisphere() -> None:
# For a normal tilted by beta, (1/pi) * integral of |n_p| (cos g + g sin g) is 1.
for beta in (0.2, 0.7, 1.2):
def f(phi):
nd, nv = math.sin(beta) * math.cos(phi), math.cos(beta)
g = math.atan2(nd, nv)
return math.hypot(nd, nv) * inner_integral(g - math.pi / 2, g + math.pi / 2, g)
assert abs(simpson(f, 0.0, math.pi) / math.pi - 1.0) < 1e-10
def test_planes_are_open() -> None:
for gx, gy in [(0.0, 0.0), (0.4, 0.0), (-0.3, 0.6), (1.2, 0.5)]:
D = [[100.0 + gx * (i + 0.5) + gy * (j + 0.5) for i in range(60)] for j in range(60)]
A = gtao_pixel(D, 30, 30, 16, 20, 1.0, 1e9, jitter=0.5, mode="bilinear")
assert abs(A - 1.0) < 1e-9
def test_wall_matches_the_cosine_weighted_formula() -> None:
D = [[FLOOR if i < 100 else FLOOR - 8.0 for i in range(200)] for _ in range(200)]
for i, delta in ((97, 2.5), (95, 4.5), (91, 8.5)):
A = gtao_pixel(D, i, 100, 32, 360, 0.25, 1e9, jitter=0.5)
assert abs(A - wall_reference(delta, 8.0)) < 0.01
assert wall_reference(0.0, 8.0) == 0.5
def test_wall_formula_by_cosine_weighted_rays() -> None:
rng = random.Random(82)
delta, H, count, hit = 3.0, 5.0, 40000, 0
for _ in range(count):
u1, u2 = rng.random(), rng.random()
ox = math.sqrt(u1) * math.cos(2 * math.pi * u2)
oz = math.sqrt(1.0 - u1)
if ox > 0 and oz * (delta / ox) < H:
hit += 1
assert abs((1 - hit / count) - wall_reference(delta, H)) < 0.01
def test_one_layer_over_occludes_a_floating_plate() -> None:
# A plate of thickness 1 over x in [20, 26), its bottom 4 units above the
# floor. The depth buffer shows only its top, as if it were a solid block.
D = [[FLOOR - 5.0 if 20 <= i < 26 else FLOOR for i in range(60)] for _ in range(40)]
A = gtao_pixel(D, 16, 20, 32, 200, 0.25, 1e9, jitter=0.5)
rng = random.Random(83)
delta, L, H, tau, count, hit = 3.5, 6.0, 4.0, 1.0, 40000, 0
for _ in range(count):
u1, u2 = rng.random(), rng.random()
ox = math.sqrt(u1) * math.cos(2 * math.pi * u2)
oz = math.sqrt(1.0 - u1)
if ox <= 0:
continue
t0 = max(delta / ox, H / oz)
t1 = min((delta + L) / ox, (H + tau) / oz)
if t0 <= t1:
hit += 1
traced = 1 - hit / count
assert A < traced - 0.02
def test_whole_image_in_range() -> None:
rng = random.Random(84)
D = [[50.0 + rng.uniform(-4, 4) for _ in range(14)] for _ in range(12)]
A = gtao(D, 4, 4, 1.0, 6.0)
assert all(-1e-12 <= a <= 1.0 + 1e-12 for row in A for a in row)
History
Horizon-based ambient occlusion of 2008 integrated the sine of the horizon angle over screen directions, which measures solid angle. Jimenez, Wu, Pesce and Jarabo (2016) reformulated the integral in slices through the view vector, with two horizons per slice and the cosine weight inside, solved the inner integral in closed form, and compared the result with ray traced references on the depth buffer. Their report also added a fitted multi-bounce term and a specular occlusion term, and it was used in a game engine of Activision. Later screen-space methods kept the slice structure and changed the horizon model, for example with bit masks of open sectors.
References
- Jorge Jimenez, Xian-Chun Wu, Angelo Pesce and Adrian Jarabo, Practical real-time strategies for accurate indirect occlusion, Activision technical report ATVI-TR-16-01, 2016, the slice formulation of the cosine-weighted visibility, the horizon search on both sides of a slice, the inner integral in closed form, and the comparison with ray traced references
- Louis Bavoil, Miguel Sainz and Rouslan Dimitrov, Image-space horizon-based ambient occlusion, SIGGRAPH 2008 talks, the horizon angles found by marching the depth buffer, which GTAO keeps
- Tomas Akenine-Möller, Eric Haines, Naty Hoffman, Angelo Pesce, Michał Iwanicki and Sébastien Hillaire, Real-Time Rendering, fourth edition, CRC Press, 2018, Section 11.3, Ambient Occlusion (the part on horizon-based methods)
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 | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 2H8H92 Edit this page History Report an error Markdown