Algorithmadvanced
Horizon-based ambient occlusion
Also called HBAO.
March the depth buffer in several screen directions to find the horizon angle in each, and integrate the visible part of the hemisphere.
- Time
- O(p m s) worst
- Space
- O(p) extra
- Where
- m = the number of directions per pixel; p = the number of pixels; s = the number of steps per direction
- Model
- Real RAM
- Properties
- deterministicnot in placeofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Louis Bavoil, Miguel Sainz, Rouslan Dimitrov, 2008
Horizon-based ambient occlusion is a screen-space method that treats the depth buffer as a height field seen from the camera. For each pixel, it picks a few directions in the screen and marches along each one, reading the depth buffer at each step. In each direction it keeps the highest elevation angle of the surface seen from the pixel, the horizon, and it assumes that everything below the horizon is blocked. The blocked part of a direction is the sine of the horizon angle minus the sine of the tangent angle of the surface, and the mean over the directions is the occlusion. Bavoil, Sainz and Dimitrov presented it in 2008. It replaces the random points of SSAO by a search along lines, and with no falloff it measures the blocked solid angle exactly, for what the depth buffer shows.
In plain words
Stand in a field next to a wall and look in all directions. The wall hides part of the sky. In each direction, the sky starts above the top of the wall, at some angle above the ground: the horizon. HBAO does this for every pixel of the depth buffer. It walks away from the pixel along a few lines on the screen, looks at how high the surface rises along each line, and remembers the highest angle. A high horizon in many directions means a deep crease. The occluded part of each direction follows from the horizon angle by a simple formula, so a few directions with a few steps each give a smooth answer.
The problem
The input is a depth buffer of pixels with the view depth of the visible surface, and the normals, from a G-buffer or from differences of . The output is the visibility per pixel, 1 for open, to darken the ambient light. The integral that HBAO approximates is, in the paper's form,
where is the screen direction, the elevation above the view plane, the elevation of the tangent plane and the elevation of the horizon. The second form is for a falloff that depends only on .
This page and its code use an orthographic camera that looks along , so that the view vector is everywhere and the tests can use height fields. In a perspective camera, the method reconstructs the view-space point of each step from its depth and the slopes of the pixel, , and measures the angles from the view-space vectors.
The algorithm
directions with a per-pixel offset , steps of length per direction, a radius and a falloff . The code uses , which is tuning.
HBAO(D, q, n, m, s, ℓ, R, W, ξ)- 1
occ ← 0; P ← the point of q - 2
for k ← 0 to m - 1: θ ← 2π (k + ξ) / m; c ← (cos θ, sin θ) - 3
h ← t ← the elevation of the tangent plane of n in the direction c - 4
for i ← 1 to s: S ← the point of D at the screen position of P plus i ℓ c - 5
r ← |S - P|; if r > R then skip this step - 6
α ← the elevation of S - P above the view plane - 7
if α > h then occ ← occ + W(r) (sin α - sin h); h ← α - 8
return A ← 1 - occ / m
The tangent (line L3). With the normal , the tangent plane rises in the direction by . Starting the horizon at ignores everything below the tangent plane, which cannot occlude the pixel.
The march (lines L4 to L7). Each step reads one depth. If its elevation is above the current horizon, the increase of the sine is added, weighted by the falloff at that distance, and the horizon moves up. With the sum of a direction is for the highest horizon . With a falloff, near occluders count fully and far ones less, which hides the cut at the radius .
Noise and blur. The offset and the step offsets are random per pixel, from a small tile of values, and a bilateral filter removes the noise. The paper also adds a small angle bias to the tangent to hide the facets of a coarse mesh; this is tuning.
Example
A frontal floor meets a block that rises by units toward the camera along a straight line. A point of the floor at the distance from the foot of the block, with and no radius, has the exact value (proved in the proofs folder). The march uses steps of 0.25 units.
| exact | , no radius | , no radius | , | , , falloff | |
|---|---|---|---|---|---|
| 2.5 | 0.596 | 0.599 | 0.573 | 0.617 | 0.743 |
| 4.5 | 0.663 | 0.669 | 0.649 | 0.689 | 0.824 |
| 8.5 | 0.760 | 0.763 | 0.752 | 0.824 | 0.937 |
With 64 directions the code is within 0.006 of the exact value; the rest is the step length, which misses the edge of the block by up to one step. With 8 directions the rectangle rule is coarser. A radius of 16 cuts off the far part of the block and opens the point, and the falloff opens it more. The last two columns are not errors of the method but choices of the look, and the cut of a radius is tuning.
Correctness
The proofs are in the proofs folder. Write a direction as an azimuth in the screen plane and an elevation above the view plane, so that the element of solid angle is . A direction is above the tangent plane exactly when , so the hemisphere of the normal is the set above the tangent angles, with the solid angle . If the depth buffer is read as a height field, the blocked directions are those between and , and their solid angle is . So with , is the blocked share of the solid angle, and the code is the rectangle rule for it with the inner sums telescoping to . Three more statements are proved and tested: a plane gives for any falloff, the wall gives , and a falloff between 0 and 1 can only raise , which stays in for an even number of directions. The value is not cosine-weighted, so it is not the ambient occlusion integral, and it is right only for the one layer of the depth buffer.
Proof: Horizon-based ambient occlusion measures the blocked solid anglefull
Setting. The camera is orthographic and looks along , so the view vector is at every pixel. A pixel has the point and the unit normal with . A direction has the azimuth in the screen plane and the elevation above the view plane, so and . The tangent angle is the elevation of the tangent plane of in the azimuth , so . The horizon is the largest elevation of a point of the depth buffer seen from in the azimuth , or if no point is higher. The method of the page computes
where, in the direction , and is the running horizon after the -th rise, found at the distance .
Lemma 1 (telescoping). If , the inner sum of a direction equals , where is the largest elevation of its samples within the radius, or if there is none above .
Proof. The running horizon only rises, and each rise adds . The sum telescopes to the sine of the last value minus the sine of the first.
Theorem 1 (the solid angle). Assume that, seen from , every direction below the horizon is blocked and every direction above it is open (the height-field view of the depth buffer). Then for and in the limit of many directions and exact horizons,
is the blocked part of the solid angle of the hemisphere above the tangent plane, divided by its total .
Proof. Since and , holds if and only if , that is . So the hemisphere above the tangent plane is , a half of the sphere, with solid angle . The blocked part is , with the solid angle . The sum over equally spaced directions is the rectangle rule for this integral, and by Lemma 1 the inner sums are the integrand.
So HBAO with measures solid angle without the cosine weight of the ambient occlusion integral. The page on ground-truth ambient occlusion adds the cosine.
Theorem 2 (planes are open). If the depth buffer holds a plane and the lookup is exact on it, and is the normal of the plane, then for every falloff .
Proof. Every sample lies on the plane, so is a tangent vector and its elevation in its azimuth is . No sample rises above , so every inner sum is empty.
In floating point the elevation of a sample can exceed by a rounding error, so the tests allow .
Theorem 3 (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 and no radius limit,
Proof. Here . Put the wall at . In an azimuth with , the ray in the screen plane reaches the wall at the horizontal distance , and the points of the top have the elevation for , which is largest at . So . In the other azimuths . With , and ,
Finally .
At the foot of the wall, gives , and far from it the value goes to 0. The tests compare the code with 64 directions and steps of 0.25 units with this formula within 0.02, and they check the formula itself by a Monte Carlo estimate with uniform directions.
Theorem 4 (falloff and range). If , then with the falloff is at least with . If is even, the directions come in opposite pairs and .
Proof. Every term is positive, and the falloff multiplies it by at most 1, so the occlusion does not grow. For the range, by Lemma 1 the inner sum of a direction is at most , and because is linear in . A pair of opposite directions thus adds at most , with or without the falloff, so . The terms are positive, so .
Theorem 5 (cost). For pixels, directions and steps per direction, the cost is lookups and arithmetic.
Proof. Each step does one lookup, one arctangent and at most one sine.
Complexity
The model is the real RAM. Each pixel does directions of steps with one depth lookup each: in total, with memory for the result. With 8 directions of 6 steps at 1920 by 1080 pixels, this is about 100 million lookups per frame, which is why HBAO is often run at half resolution and upsampled. The lookups along a line are close to each other in the texture, so they cache better than the scattered points of SSAO.
Properties
- Solid angle. With no falloff it measures the blocked share of the solid angle above the tangent plane.
- Height field. The depth buffer is read as a surface of infinite thickness: everything below the horizon counts as blocked.
- Open planes. A plane is fully open, unlike the sphere form of SSAO.
- Smooth. A few directions give a smooth result, because each direction integrates over all elevations at once.
- Screen space. Surfaces off screen or hidden behind the first layer do not count.
- Tuning. The radius, the falloff, the angle bias and the step count change the look.
Variants and improvements
- Cosine weighting. Weight each direction by the cosine to the normal and integrate it in closed form per slice, see ground-truth ambient occlusion.
- Hierarchical depth. March on a depth pyramid with larger steps far from the pixel.
- Deinterleaved rendering. Split the screen into sub-images with the same random offsets, so that each sub-image reads the texture coherently, then merge.
- Temporal accumulation. Change the offsets each frame and blend with the reprojected history.
- Thickness heuristics. Treat thin objects as having finite thickness, to reduce the over-darkening behind them.
When to use it
Use HBAO when SSAO looks too noisy or too gray and the frame can afford a few directions with a few steps per pixel. It gives the smooth contact shadows of a height field. When the look should match the cosine-weighted ambient occlusion of a ray tracer more closely, use ground-truth ambient occlusion, which costs about the same.
Pitfalls
- Halos around near objects. A near object counts as a tall wall for the pixels around its silhouette. The radius and falloff limit the band.
- Facets. Coarse triangles have slightly wrong normals, so the march finds the neighboring triangles above the tangent plane. An angle bias hides this.
- Thin objects. A pole or a leaf blocks the whole space behind it in the depth buffer, so the floor under it gets too dark.
- Radius in pixels. In a perspective camera, the radius in the scene maps to fewer pixels far away. Clamp the march length in pixels for near pixels, where it becomes very large.
- Screen borders. The march leaves the screen and reads clamped depths. Stop at the border.
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/horizon-based-ambient-occlusion/. The authors are listed in prov/7TY98V.jsonl.
"""Horizon-based ambient occlusion (Bavoil, Sainz and Dimitrov 2008).
The camera is orthographic and looks along -z, so that the view vector is
(0, 0, 1) at every pixel 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). Elevation angles are
measured from the view plane z = const, positive toward the camera.
For each screen direction theta, the method marches the depth buffer, keeps
the highest elevation seen so far (the horizon), and adds W(r) (sin h - sin h')
each time the horizon rises from h' to h, starting at the tangent angle t.
With W = 1 the sum of one direction is sin h - sin t. The result is
A = 1 - (1 / N_d) sum over directions, the visibility (1 = open).
"""
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 tangent_angle(n: Vec, cx: float, cy: float) -> float:
"""The elevation of the tangent plane of n in the screen direction (cx, cy)."""
return math.atan(-(n[0] * cx + n[1] * cy) / n[2])
def hbao_pixel(
D: Grid,
i: int,
j: int,
directions: int,
steps: int,
step: float,
radius: float,
falloff: bool = True,
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)
occ = 0.0 # @line L1
for k in range(directions): # @line L2
theta = 2 * math.pi * (k + jitter) / directions
cx, cy = math.cos(theta), math.sin(theta)
h = tangent_angle(n, cx, cy) # @line L3
sin_h = math.sin(h)
for s in range(1, steps + 1): # @line L4
r = s * step
dz = d - lookup(D, px + r * cx, py + r * cy, mode)
dist2 = r * r + dz * dz # @line L5
if dist2 > radius * radius:
continue
a = math.atan2(dz, r) # @line L6
if a > h: # @line L7
w = 1.0 - dist2 / (radius * radius) if falloff else 1.0
sin_a = math.sin(a)
occ += w * (sin_a - sin_h)
h, sin_h = a, sin_a
return 1.0 - occ / directions # @line L8
def hbao(D: Grid, directions: int, steps: int, step: float, radius: float, **kw) -> Grid:
return [[hbao_pixel(D, i, j, directions, 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 HBAO value with W = 1 and no radius limit for a point on a frontal
floor at the distance delta from an infinite wall of the given height:
1 - atan(height / delta) / pi, the open share of the solid angle."""
return 1.0 - math.atan2(height, delta) / math.pi
test_horizon_based_ambient_occlusion.py 87 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/horizon-based-ambient-occlusion/. The authors are listed in prov/7TY98V.jsonl.
"""HBAO on height fields with known answers."""
import math
import random
from horizon_based_ambient_occlusion import (
hbao,
hbao_pixel,
lookup,
normal_from_depth,
tangent_angle,
wall_reference,
)
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 wall(w, h, edge, floor, height):
return [[floor if i < edge else floor - height for i in range(w)] for _ in range(h)]
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 = plane(40, 40, 100.0, gx, gy)
for falloff in (True, False):
A = hbao_pixel(D, 20, 20, 8, 12, 1.0, 50.0, falloff=falloff, jitter=0.3, mode="bilinear")
assert abs(A - 1.0) < 1e-9
def test_one_direction_telescopes_without_falloff() -> None:
rng = random.Random(71)
D = [[50.0 + rng.uniform(-3, 3) for _ in range(30)] for _ in range(30)]
n = normal_from_depth(D, 15, 15)
for jitter in (0.0, 0.25, 0.6):
A = hbao_pixel(D, 15, 15, 1, 10, 1.0, 1e9, falloff=False, jitter=jitter, normal=n)
theta = 2 * math.pi * jitter
cx, cy = math.cos(theta), math.sin(theta)
t = tangent_angle(n, cx, cy)
h = t
for s in range(1, 11):
dz = D[15][15] - lookup(D, 15.5 + s * cx, 15.5 + s * cy)
h = max(h, math.atan2(dz, s))
assert abs((1 - A) - (math.sin(h) - math.sin(t))) < 1e-12
def test_wall_matches_the_solid_angle_formula() -> None:
D = wall(200, 200, 100, 200.0, 8.0)
for i, delta in ((97, 2.5), (95, 4.5), (91, 8.5)):
A = hbao_pixel(D, i, 100, 64, 360, 0.25, 1e9, falloff=False, jitter=0.5)
assert abs(A - wall_reference(delta, 8.0)) < 0.02
def test_wall_formula_by_monte_carlo() -> None:
# Uniform directions over the upper hemisphere, rays against a wall
# x >= delta of height H: the occluded share is atan(H / delta) / pi.
rng = random.Random(72)
delta, H, count, hit = 3.0, 5.0, 40000, 0
for _ in range(count):
z = rng.random()
phi = rng.uniform(0, 2 * math.pi)
rxy = math.sqrt(1 - z * z)
ox = rxy * math.cos(phi)
if ox > 0 and z * (delta / ox) < H:
hit += 1
assert abs(hit / count - (1 - wall_reference(delta, H))) < 0.01
def test_falloff_only_removes_occlusion() -> None:
rng = random.Random(73)
D = [[60.0 + rng.uniform(-6, 6) for _ in range(32)] for _ in range(32)]
for _ in range(10):
i, j = rng.randrange(4, 28), rng.randrange(4, 28)
hard = hbao_pixel(D, i, j, 8, 8, 1.0, 6.0, falloff=False)
soft = hbao_pixel(D, i, j, 8, 8, 1.0, 6.0, falloff=True)
assert 0.0 <= hard <= soft <= 1.0 + 1e-12
def test_whole_image_of_a_plane() -> None:
# Pixels at least 5 units from the border, so that no sample is clamped.
D = plane(20, 20, 30.0, 0.2, -0.1)
A = hbao(D, 4, 4, 1.0, 5.0, mode="bilinear")
assert all(abs(a - 1.0) < 1e-9 for row in A[5:15] for a in row[5:15])
History
Screen-space ambient occlusion with point samples appeared in 2007. Bavoil, Sainz and Dimitrov presented image-space horizon-based ambient occlusion at SIGGRAPH 2008. They wrote the occlusion as an integral over the screen directions of the sine of the horizon angle minus the sine of the tangent angle, with a falloff, and computed the horizon by marching the depth buffer. The method shipped in many games through the HBAO and HBAO+ libraries of NVIDIA. Jimenez, Wu, Pesce and Jarabo (2016) added the cosine weight in their ground-truth ambient occlusion.
References
- Louis Bavoil, Miguel Sainz and Rouslan Dimitrov, Image-space horizon-based ambient occlusion, SIGGRAPH 2008 talks, Equation 3, the integral of (sin h - sin t) W over the screen directions, and the march in screen space with an attenuation per step
- 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)
- Martin Mittring, Finding next gen: CryEngine 2, SIGGRAPH 2007 course Advanced Real-Time Rendering in 3D Graphics and Games, the screen-space ambient occlusion with point samples that horizon-based methods replace
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 7TY98V Edit this page History Report an error Markdown