Algorithmcore
Screen-space ambient occlusion
Also called SSAO.
Estimate ambient occlusion per pixel by testing sample points around it against the depth buffer, then blur the noisy result.
- Time
- O(p s + p r^2) worst
- Space
- O(p + s) extra
- Where
- p = the number of pixels; r = the radius of the blur in pixels; s = the number of samples per pixel
- Model
- Real RAM
- Properties
- deterministicnot in placeofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Martin Mittring, Perumalla Shanmugam, Okan Arikan, 2007
Screen-space ambient occlusion estimates, for each pixel, how much of the space around the visible surface is filled by other surfaces, using only the depth buffer of the frame. For a pixel at the point , it places a few sample points in a small sphere or hemisphere around , projects each one to the screen, and compares its depth with the depth stored there. A sample behind the stored surface counts as occluded. The share of occluded samples darkens the ambient light of the pixel, so creases, corners and contact areas get darker. The result is noisy with few samples, so a blur follows. Mittring presented it for the game Crysis in 2007. It approximates ambient occlusion, but what it computes is a volume fraction of one depth layer, not the integral over directions, and how close it comes is a measurement, not a guarantee.
In plain words
Corners and gaps get less light from the sky than open surfaces, and it helps to darken them. A ray tracer would shoot rays from each point to see how much of the sky is blocked. That is too slow for every frame. SSAO does something cheaper with the picture that the GPU has already made. Around each point, it throws a handful of small test points, and for each one it asks the depth buffer: is there a surface in front of this test point, as seen from the camera? If yes, the test point is probably inside something. Many test points inside means the point sits in a corner. The answer is noisy, so neighboring pixels are averaged.
The problem
The input is a depth buffer of pixels with the view depth of the visible surface, and for the hemisphere form the normals, from a G-buffer or from differences of . The output is a visibility per pixel, 1 for open and smaller in creases, to multiply into the ambient light. The reference is the ambient occlusion of the scene, but the depth buffer holds only the nearest surface per pixel, so anything hidden behind it, and anything outside the screen, is unknown.
This page and its code use an orthographic camera that looks along , so that the tests can use height fields with known answers. The pixel has its center at in view units, and its point is . In a perspective camera, with the slopes of the pixel, and a sample is projected with the camera matrix; the method is otherwise the same.
The algorithm
The kernel is a list of offsets of length at most . In the sphere form they fill a ball. In the hemisphere form they fill a half ball and are turned so that its axis is the normal of the pixel. The bias and the range function are tuning.
SSAO(D, kernel, R, β)- 1
for each pixel q with depth d: P ← the point of q - 2
n ← the normal at q ▷ hemisphere form only - 3
occ ← 0 - 4
for each offset k of the kernel: S ← P + k, or P + ROTATE(k, n) in the hemisphere form - 5
b ← the depth of D at the screen position of S; dS ← the depth of S - 6
if b < dS - β then occ ← occ + RANGE(R, |d - b|) - 7
A[q] ← 1 - occ / s - 8
return BLUR(A)
The test (lines L5 and L6). The sample is occluded if the surface stored at its screen position is nearer to the camera than the sample. The bias removes self-occlusion from depth precision and from a coarse reconstruction of the surface.
The range check (line L6). A surface far in front of , such as a near object in front of a far wall, also passes the test. The common fix multiplies the count by a falloff in the depth gap. The code uses , a form found in many engines. The falloff is tuning.
The kernel and the noise. A few samples per pixel give banding. Engines rotate the kernel per pixel with a small tile of random rotations, which turns the banding into high-frequency noise, and the blur of line L8 removes most of it. A bilateral filter that does not blur across depth edges is the usual choice. The code uses a box blur.
Example
A frontal floor at depth 40 meets a block nearer to the camera by 30 units along a line at . The kernel has points in the half ball of radius around the normal , and the lookup is nearest. A point of the floor at the distance from the foot of the block has the expected occluded fraction , the share of a cap of the ball.
| formula | measured | |
|---|---|---|
| 0.5 | 0.438 | 0.471 |
| 1.5 | 0.316 | 0.313 |
| 2.5 | 0.206 | 0.204 |
| 4.5 | 0.043 | 0.044 |
| 5.5 | 0.005 | 0.004 |
The row at is off by more than the noise. Its normal comes from central differences that cross the edge, so it tilts, and the hemisphere leans into the block. The other rows agree within the sampling error of about 0.006.
With a sphere kernel in antithetic pairs and the bilinear lookup, every plane gives exactly: of each pair, one point is in front of the plane and one is behind it. So a flat open floor comes out as gray as a corner. With the hemisphere kernel, every plane gives .
Correctness
SSAO is an estimator, so its correctness is a statement of what it estimates, and the proofs folder proves it. With independent uniform offsets in the half ball and no bias or range check, the expected value of is the fraction of the volume of the half ball that lies behind the surface seen in the depth buffer, and its variance is at most . That volume fraction is a measure of how closed the neighborhood is. It is not the cosine-weighted integral of the ambient occlusion page. The exact cases are planes: the sphere kernel gives on every plane, because the test of an offset is the sign of for the plane normal and antithetic pairs split evenly; the hemisphere kernel gives 1 on every plane, because its offsets have . The wall formula of the example is proved by a cap volume. The tests check all of these, the plane cases exactly.
Proof: What screen-space ambient occlusion estimates, and its exact casesfull
Setting. The camera is orthographic and looks along , as in the code. The pixel has its center at and the depth , and its point is . The reconstructed depth is the bilinear or the nearest lookup of the buffer. For an offset , the sample is occluded when with the bias : the stored surface is nearer to the camera than the sample. Without the range check, each occluded sample adds 1, and the result is for samples. The claims assume that every sample projects inside the buffer, away from the clamped border.
Lemma 1 (bilinear lookup on a plane). If for all pixels, then the bilinear lookup gives inside the buffer.
Proof. Bilinear interpolation is a convex combination of the four corner values with the weights , , and . These weights sum to 1 and reproduce the coordinates: the weighted mean of the corner positions is . An affine function of the corners therefore interpolates to the same affine function at .
Theorem 1 (sphere kernel on a plane). Let the buffer hold a plane as in Lemma 1, read with the bilinear lookup, with . Let the kernel be made of pairs with for . Then at every pixel.
Proof. By Lemma 1, , so the sample is occluded if and only if , that is, . Of and , exactly one has . So half of the samples are occluded.
So the sphere kernel shows every plane, open or not, as half occluded. This is the gray of flat surfaces that the first form of SSAO has, and it is the reason for the normal-oriented form.
Lemma 2 (normal of a plane). For a plane as in Lemma 1, the central differences of the code give the unit normal , which faces the camera.
Proof. The differences of an affine function over two pixels, divided by 2, are exactly and . The surface is the zero set of , whose gradient is .
Theorem 2 (hemisphere kernel on a plane). For a plane as in Lemma 1 with any lookup that is exact on the plane, and for any kernel in the open upper half ball (tangent offsets with ) rotated into the frame of , at every pixel for every .
Proof. The rotation keeps the length and sends the third axis to , so the offset has , hence . As in the proof of Theorem 1, the sample is occluded only if , which does not happen.
Theorem 3 (what the estimate converges to). Let the offsets be independent and uniform in the half ball of radius around , with and no range check. Let be the set of offsets of this half ball with , the part of the half ball that lies behind the surface seen in the buffer. Then is an unbiased estimate of , the volume fraction of , with variance at most .
Proof. Each sample is occluded with probability , the measure of under the uniform distribution. is the mean of independent Bernoulli variables with this mean, and a Bernoulli variable has variance at most .
This volume fraction is not the cosine-weighted ambient occlusion integral over directions. The two agree at the ends (0 for an open plane and 1 for a closed one), and in between they are different functions of the geometry. A claim that SSAO matches ray traced ambient occlusion would be a measurement on scenes, not a consequence of this theorem.
Theorem 4 (the wall). Let lie on a frontal floor () at a distance from the foot of an infinite wall that is nearer to the camera by , with the edge on a pixel boundary and the nearest lookup. Then the volume fraction of Theorem 3 is
which is at the foot of the wall.
Proof. With the nearest lookup the buffer holds the step exactly. An offset with projects onto the wall, whose depth is because , so it is behind the wall; an offset with projects onto the floor at depth and is free. is the part of the half ball with . The ball is symmetric in , so this fraction equals the fraction of the whole ball with , a cap of height with the volume . Dividing by gives the formula.
The tests compare 6000 samples with this formula at pixels 1.5 to 5.5 units from the wall and find errors below 0.025. A pixel next to the edge is not tested: its central difference crosses the edge and tilts the normal.
Theorem 5 (cost). For pixels, samples and a blur of radius , the cost is lookups and for the box blur.
Proof. Each pixel does samples of work, and the blur sums values per pixel.
Complexity
The model is the real RAM. Each pixel takes samples with one depth lookup each, so the pass costs . A box blur of radius costs , or if it is separable. The kernel takes memory and the result . At 1920 by 1080 pixels with 16 samples, this is about 33 million depth reads per frame. Engines often run SSAO at half resolution and upsample, which cuts this by 4.
The reads of the samples are scattered around each pixel, so their cost is mostly in the texture cache. A larger radius in pixels spreads the reads and lowers the hit rate.
Properties
- Screen space only. The input is one depth layer. Surfaces hidden behind it and outside the screen do not occlude.
- Depends on the view. The same corner gets other values from other angles, because the depth buffer changes.
- Volume, not angle. The value is a share of volume, not of directions weighted by the cosine.
- Bias toward gray. The sphere form darkens open planes to . The hemisphere form fixes this but needs normals.
- Noise and blur. Few samples need a rotation pattern and a blur, or temporal accumulation.
- Cheap and local. The cost per pixel is fixed and independent of the scene.
Variants and improvements
- Sphere kernel. The original form needs no normals. Open surfaces come out half gray, and the image is usually rescaled.
- Hemisphere kernel. Turn the kernel to the normal, so that open planes get .
- Range check. A falloff in the depth gap removes halos around near objects.
- Horizon-based methods. March the depth buffer in a few directions and integrate the angle of the horizon, see horizon-based ambient occlusion. The ground-truth ambient occlusion method integrates the cosine-weighted visibility of each slice in closed form.
- Temporal accumulation. Change the kernel each frame and blend with the reprojected result of earlier frames, as in temporal antialiasing.
- Multiple layers. Render a second depth layer to see behind the first, at the cost of another pass.
When to use it
Use SSAO for cheap contact darkening in real-time rendering when the frame has a depth buffer and the budget allows a few samples per pixel. It works best with a deferred shading renderer that has normals in its G-buffer. When the look must be close to ray traced ambient occlusion, use a horizon-based method or ray tracing.
Pitfalls
- Halos. Without a range check, a near object darkens the far wall behind it in a band around its silhouette.
- Self-occlusion. Without a bias, depth precision and a coarse lookup make flat surfaces look occluded in patterns.
- Normals from depth at edges. Differences across a depth edge tilt the normal, as the example shows. Use G-buffer normals, or one-sided differences that pick the smaller gap.
- Radius in the wrong space. The radius is a distance in the scene. In a perspective camera its size on the screen shrinks with depth, so far pixels sample a few pixels only.
- Screen borders. Samples that leave the screen read clamped or missing depths. Fade the effect near the borders, or render a guard band.
- Gray planes. The sphere kernel darkens open surfaces by half. Rescale or use the hemisphere form.
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/screen-space-ambient-occlusion/. The authors are listed in prov/EGC7ET.jsonl.
"""Screen-space ambient occlusion with sample points tested against the depth buffer.
The camera is orthographic and looks along -z, so that the tests can use
height fields with known answers. The pixel (i, j) has its center at
(i + 1/2, j + 1/2) in view units, j counted from the bottom, and D[j][i] is the
positive view depth of the visible surface. The point of a pixel with depth d
is P = (x, y, -d). The result per pixel is the visibility A in [0, 1]: 1 means
not occluded.
Two kernels are given: points in a sphere around P, as in the first SSAO of
2007, and points in the hemisphere around the normal. The depth lookup is
bilinear (exact on planes) or nearest (exact on steps at pixel edges).
"""
import math
import random
from typing import List, Optional, Sequence, Tuple
Vec = Tuple[float, float, float]
Grid = List[List[float]]
def lookup(D: Grid, x: float, y: float, mode: str = "bilinear") -> float:
"""The depth buffer at a screen position, clamped at the borders."""
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) if w > 1 else 0, min(int(v), h - 2) if h > 1 else 0
i1, j1 = min(i0 + 1, w - 1), min(j0 + 1, h - 1)
fu, fv = u - i0, v - j0
top = D[j0][i0] * (1 - fu) + D[j0][i1] * fu
bot = D[j1][i0] * (1 - fu) + D[j1][i1] * fu
return top * (1 - fv) + bot * fv
def normal_from_depth(D: Grid, i: int, j: int) -> Vec:
"""The normal of the surface z = -D from central differences, facing +z."""
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) if ir > il else 0.0
gy = (D[jt][i] - D[jb][i]) / (jt - jb) if jt > jb else 0.0
n = (gx, gy, 1.0)
s = math.sqrt(gx * gx + gy * gy + 1.0)
return (n[0] / s, n[1] / s, n[2] / s)
def _ball_point(rng: random.Random, radius: float) -> Vec:
while True:
p = (rng.uniform(-1, 1), rng.uniform(-1, 1), rng.uniform(-1, 1))
if 0 < p[0] ** 2 + p[1] ** 2 + p[2] ** 2 <= 1:
return (p[0] * radius, p[1] * radius, p[2] * radius)
def sphere_kernel(rng: random.Random, pairs: int, radius: float) -> List[Vec]:
"""Uniform points in a ball, in antithetic pairs k and -k."""
out = []
for _ in range(pairs):
k = _ball_point(rng, radius)
out += [k, (-k[0], -k[1], -k[2])]
return out
def hemisphere_kernel(rng: random.Random, count: int, radius: float) -> List[Vec]:
"""Uniform points in the half ball with z > 0, in the tangent frame."""
out = []
while len(out) < count:
k = _ball_point(rng, radius)
if k[2] != 0:
out.append((k[0], k[1], abs(k[2])))
return out
def to_normal_frame(k: Vec, n: Vec) -> Vec:
"""Rotate a tangent-frame offset so that its z axis becomes n."""
a = (1.0, 0.0, 0.0) if abs(n[0]) < 0.9 else (0.0, 1.0, 0.0)
# t = normalize(a - (a . n) n), b = n x t
d = a[0] * n[0] + a[1] * n[1] + a[2] * n[2]
t = (a[0] - d * n[0], a[1] - d * n[1], a[2] - d * n[2])
tl = math.sqrt(t[0] ** 2 + t[1] ** 2 + t[2] ** 2)
t = (t[0] / tl, t[1] / tl, t[2] / tl)
b = (n[1] * t[2] - n[2] * t[1], n[2] * t[0] - n[0] * t[2], n[0] * t[1] - n[1] * t[0])
return tuple(k[0] * t[c] + k[1] * b[c] + k[2] * n[c] for c in range(3))
def smoothstep01(t: float) -> float:
t = min(max(t, 0.0), 1.0)
return t * t * (3 - 2 * t)
def ssao_pixel(
D: Grid,
i: int,
j: int,
kernel: Sequence[Vec],
oriented: bool,
bias: float = 0.0,
range_radius: Optional[float] = None,
mode: str = "bilinear",
) -> float:
d = D[j][i]
P = (i + 0.5, j + 0.5, -d) # @line L1
n = normal_from_depth(D, i, j) if oriented else None # @line L2
occ = 0.0 # @line L3
for k in kernel: # @line L4
o = to_normal_frame(k, n) if oriented else k
s = (P[0] + o[0], P[1] + o[1], P[2] + o[2])
b = lookup(D, s[0], s[1], mode) # @line L5
ds = -s[2]
if b < ds - bias: # @line L6
if range_radius is None:
occ += 1.0
else:
gap = abs(d - b)
occ += 1.0 if gap == 0 else smoothstep01(range_radius / gap)
return 1.0 - occ / len(kernel) # @line L7
def box_blur(A: Grid, r: int) -> Grid:
"""A (2r+1) by (2r+1) box filter, clamped at the borders."""
h, w = len(A), len(A[0])
out = []
for j in range(h):
row = []
for i in range(w):
acc, cnt = 0.0, 0
for jj in range(max(0, j - r), min(h, j + r + 1)):
for ii in range(max(0, i - r), min(w, i + r + 1)):
acc += A[jj][ii]
cnt += 1
row.append(acc / cnt)
out.append(row)
return out
def ssao(D: Grid, kernel: Sequence[Vec], oriented: bool, blur: int = 0, **kw) -> Grid:
A = [[ssao_pixel(D, i, j, kernel, oriented, **kw) for i in range(len(D[0]))] for j in range(len(D))]
return box_blur(A, blur) if blur > 0 else A # @line L8
def half_ball_beyond(delta: float, radius: float) -> float:
"""The fraction of the half ball of the given radius with x > delta, for
0 <= delta <= radius: the occluded fraction next to an infinite wall at
distance delta that is higher than the radius."""
return (radius - delta) ** 2 * (2 * radius + delta) / (4 * radius ** 3)
test_screen_space_ambient_occlusion.py 106 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/screen-space-ambient-occlusion/. The authors are listed in prov/EGC7ET.jsonl.
"""SSAO on height fields with known answers."""
import math
import random
from screen_space_ambient_occlusion import (
box_blur,
half_ball_beyond,
hemisphere_kernel,
lookup,
normal_from_depth,
sphere_kernel,
ssao,
ssao_pixel,
to_normal_frame,
)
def plane(w, h, d0, gx, gy):
return [[d0 + gx * (i + 0.5) + gy * (j + 0.5) for i in range(w)] for j in range(h)]
def test_bilinear_lookup_is_exact_on_a_plane() -> None:
D = plane(12, 10, 20.0, 0.25, -0.5)
rng = random.Random(61)
for _ in range(200):
x, y = rng.uniform(0.5, 11.5), rng.uniform(0.5, 9.5)
assert abs(lookup(D, x, y) - (20.0 + 0.25 * x - 0.5 * y)) < 1e-9
def test_sphere_kernel_gives_one_half_on_any_plane() -> None:
rng = random.Random(62)
kernel = sphere_kernel(rng, 16, 3.0)
for gx, gy in [(0.0, 0.0), (0.3, 0.0), (-0.4, 0.7), (1.5, -0.2)]:
D = plane(24, 24, 50.0, gx, gy)
for i, j in [(10, 10), (12, 8), (8, 14)]:
assert ssao_pixel(D, i, j, kernel, oriented=False) == 0.5
def test_hemisphere_kernel_gives_one_on_any_plane() -> None:
rng = random.Random(63)
kernel = hemisphere_kernel(rng, 32, 3.0)
for gx, gy in [(0.0, 0.0), (0.3, 0.0), (-0.4, 0.7), (1.5, -0.2)]:
D = plane(24, 24, 50.0, gx, gy)
n = normal_from_depth(D, 11, 11)
s = math.hypot(gx, gy, 1.0)
assert all(abs(a - b) < 1e-12 for a, b in zip(n, (gx / s, gy / s, 1 / s)))
for i, j in [(10, 10), (12, 8), (8, 14)]:
assert ssao_pixel(D, i, j, kernel, oriented=True) == 1.0
def test_rotation_keeps_the_kernel_in_the_hemisphere() -> None:
rng = random.Random(64)
for _ in range(100):
v = (rng.gauss(0, 1), rng.gauss(0, 1), abs(rng.gauss(0, 1)) + 0.1)
L = math.sqrt(sum(c * c for c in v))
n = tuple(c / L for c in v)
for k in hemisphere_kernel(rng, 5, 1.0):
o = to_normal_frame(k, n)
assert abs(sum(c * c for c in o) - sum(c * c for c in k)) < 1e-12
assert abs(sum(a * b for a, b in zip(o, n)) - k[2]) < 1e-12
def test_step_matches_the_volume_fraction() -> None:
# Floor at depth 40 for x < 20, a block nearer by 30 for x >= 20.
w, h, R = 40, 20, 6.0
D = [[40.0 if i < 20 else 10.0 for i in range(w)] for _ in range(h)]
rng = random.Random(65)
kernel = hemisphere_kernel(rng, 6000, R)
# Pixel 19 is left out: its central difference straddles the edge and
# tilts the normal, which is a known artifact of normals from depth.
for i in (18, 17, 15, 14):
delta = 20 - (i + 0.5)
A = ssao_pixel(D, i, 10, kernel, oriented=True, mode="nearest")
assert abs((1 - A) - half_ball_beyond(delta, R)) < 0.025
assert half_ball_beyond(0.0, R) == 0.5
def test_range_check_fades_far_occluders() -> None:
# A plate 30 units in front of a frontal floor covers the right half.
w, h, R = 30, 10, 4.0
D = [[60.0 if i < 15 else 30.0 for i in range(w)] for _ in range(h)]
rng = random.Random(66)
kernel = hemisphere_kernel(rng, 400, R)
plain = ssao_pixel(D, 13, 5, kernel, oriented=True, mode="nearest")
ranged = ssao_pixel(D, 13, 5, kernel, oriented=True, mode="nearest", range_radius=R)
assert abs((1 - plain) - half_ball_beyond(1.5, R)) < 0.05
assert ranged > 0.95
def test_blur_keeps_constants_and_averages() -> None:
A = [[0.25] * 7 for _ in range(5)]
assert box_blur(A, 2) == A
B = [[1.0 if (i + j) % 2 else 0.0 for i in range(9)] for j in range(9)]
out = box_blur(B, 1)
assert abs(out[4][4] - 4 / 9) < 1e-12
def test_whole_image_on_a_plane() -> None:
D = plane(16, 12, 30.0, 0.2, 0.1)
rng = random.Random(67)
A = ssao(D, hemisphere_kernel(rng, 16, 2.0), oriented=True, blur=1)
assert all(abs(a - 1.0) < 1e-12 for row in A for a in row)
History
Ambient occlusion and obscurance were defined for offline rendering in the late 1990s and early 2000s, where rays are traced from each point. In 2007 Mittring described the screen-space form used in CryEngine 2 for Crysis: points in a sphere around the pixel, tested against the depth buffer, with a blur. Shanmugam and Arikan published in the same year a GPU method that also worked from the buffers of the visible surfaces. Later engines turned the kernel to the normal to remove the gray of open surfaces, added range checks, and replaced the random points by horizon searches, which led to horizon-based ambient occlusion in 2008 and ground-truth ambient occlusion in 2016.
References
- Martin Mittring, Finding next gen: CryEngine 2, SIGGRAPH 2007 course Advanced Real-Time Rendering in 3D Graphics and Games, the part on screen-space ambient occlusion, with sample points in a sphere tested against the depth buffer and a blur of the noise
- Perumalla Shanmugam and Okan Arikan, Hardware accelerated ambient occlusion techniques on GPUs, Symposium on Interactive 3D Graphics and Games 2007, ambient occlusion computed from the depth and normal buffers of the visible surfaces
- 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 screen-space methods)
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 | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag EGC7ET Edit this page History Report an error Markdown