Algorithmadvanced
Parallax occlusion mapping
Also called POM, steep parallax mapping.
March the view ray through a height field in texture space to find the first intersection, giving parallax and self-occlusion per pixel.
- Time
- Θ(P k) worstΘ(P) best
- Space
- Θ(1) extra
- Where
- P = the number of shaded pixels; k = the number of steps of the march
- Model
- Real RAM
- Properties
- deterministicnot in placeonlineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Zoe Brawley, Natalya Tatarchuk, 2004
Parallax occlusion mapping makes a flat polygon look like a surface with real depth. For each pixel it walks along the view ray inside a depth map, in texture space, until the ray goes under the stored surface. Then it shades the pixel with the texture at that point. Bump mapping and normal mapping only change the normal, so the texture does not move with the view. Parallax mapping moves the texture coordinate by one offset from the depth at the start, which works for gentle relief only. This method searches for the first intersection of the ray with the height field, so steep relief shifts and hides itself correctly. Displacement mapping moves the geometry, which also fixes the silhouette, at the cost of many more triangles.
In plain words
Imagine the polygon is a glass window, and behind the glass lies a bumpy landscape stored as a depth image. To color one pixel, follow your line of sight through the glass and into the landscape. Take small steps down along the line. At each step, look at the depth image right below you. As long as you are above the ground, keep going. At the first step that is under the ground, you have passed the surface, so step back a little to where the line crossed the ground, and use the color stored there.
Bumps near the front can then hide what is behind them, just as on a real rough wall.
The problem
The work happens in tangent space, where the polygon is the plane and the texture axes are and . The inputs are the texture coordinate of the pixel, the unit vector from the surface toward the viewer with , a depth map with values in (0 is the top of the relief, at the polygon, and 1 is the bottom), a scale (the depth of the relief in texture units), and the number of steps .
Going one unit of depth down along the ray moves the texture coordinate by , so at depth the ray is at . The ray is under the surface when . The output is the texture coordinate of the first root of in . It exists because .
The algorithm
POM(m, uv0, v, s, k)- 1
Δ ← -s (v_x, v_y) / v_z ▷ the shift per unit of depth - 2
r_prev ← 0; f_prev ← 0 - m(uv0) - 3
if f_prev ≥ 0 then return uv0 ▷ the top of the relief - 4
for i ← 1 to k do - 5
r ← i / k; f ← r - m(uv0 + r Δ) - 6
if f ≥ 0 then ▷ the first sample under the surface - 7
t ← f_prev / (f_prev - f) - 8
r̂ ← r_prev + t (r - r_prev); return uv0 + r̂ Δ - 9
(r_prev, f_prev) ← (r, f)
Lines L4 to L6 are a ray march with a fixed step. Lines L7 and L8 are one step of the secant method between the last sample above the surface and the first sample below it. The pixel is then shaded with all its textures at the returned coordinate, usually with a normal map for the lighting.
Example
Take , , and a view with and , so . Let the depth map along this ray be , which holds for .
| step | under the surface | |||
|---|---|---|---|---|
| L2 | 0 | 0.3 | no | |
| 1 | 0.25 | 0.3375 | no | |
| 2 | 0.5 | 0.45 | yes |
Line L7 gives , and line L8 gives . The texture coordinate is . The true first hit solves , which gives , so the error is , well inside one step of . Plain parallax mapping uses the depth at the start, , which is off by .
Correctness
The proof file shows four facts. First, the loop always returns, with at the previous sample and at the current one, because . Second, the secant step lands in that interval. Third, if the ray, once it enters the relief, stays inside for at least one step, then the first sample under the surface is the one just after , so the result is within of the first hit. Fourth, if the depth map is planar along the ray, is affine and the secant step is exact. Without the condition of the third fact, the result is still within one step of some intersection, but maybe not of the first one.
Proof: The march with a secant step lands within one step of the first hitfull
We use the pseudocode and the notation of the page. Arithmetic is exact (real-ram). The depth map is continuous with values in . Line L1 gives the offset per unit of depth, and the ray at depth is at the texture coordinate . Let
The ray is at or below the surface at depth exactly when . The function is continuous, and . Let . It is closed and contains 1, so it has a least element , the depth of the first hit of the view ray with the height field.
Lemma 1 (the march stops, with a bracket). If line L3 does not return, the loop of lines L4 to L9 returns at the least with , and then . Such an exists.
Proof. , so some passes the test of line L6, and the loop returns at the least one. Line L9 keeps equal to the previous sample, so at the return and . For this is the value of line L2, which is negative because line L3 did not return. For it is negative because sample failed the test.
Lemma 2 (the secant step stays in the bracket). At line L7, , so of line L8 lies in . Also is the root of the line through and .
Proof. , so and , a positive number at most 1. The line through the two points is , and .
Theorem 1 (one step of error). Suppose for all : once the ray enters the height field, it stays inside for at least one step. Then the returned depth satisfies .
Proof. If , then and line L3 returns . Otherwise let , so , and . By the assumption . Every earlier sample with has , so and . So by Lemma 1 the loop returns at this , and by Lemma 2, . Both and lie in this interval of length .
Theorem 2 (exact for a planar map). If along the ray for constants and , the result is exact: .
Proof. Then is affine. If , line L3 returns . Otherwise and give , so is increasing with the single root . The line of Lemma 2 through two points of an affine function is the function itself, so its root is .
Theorem 3 (without the assumption, the result is still a hit). In every case lies within of a root of , that is, of a point where the ray meets the height field.
Proof. By Lemma 1, changes sign on , so by the intermediate value theorem it has a root there, and by Lemma 2 lies in the same interval.
The root of Theorem 3 need not be the first one. If the ray passes through a feature thinner than one step, the samples miss it, and the result is a later hit. The code test test_thin_wall_is_missed_by_a_coarse_march shows this with a wall one texel wide.
Cost. Lines L1 to L3 take time and one sample. The loop runs at most times, with one sample of each. Lines L7 and L8 run once. So one pixel takes time and at most samples, and space.
Complexity
One pixel takes at most samples of the depth map and time. If the ray meets the surface at the first sample, it takes . The memory is per pixel. So pixels take in the worst case. On a GPU the loop runs in the pixel shader, and the pixels of one group wait for the slowest one, so the worst case sets the cost.
Properties
- Within one step of the first hit, when the relief is not too thin. This is proved. It needs the ray to stay under the surface for at least one step after it enters.
- Exact for planar relief. This is proved. The secant step solves an affine .
- Self-occlusion. A high point in front hides a low point behind it, because the march stops at the first hit.
- No silhouette. The geometry does not change, so the edge of the polygon stays straight. Only displacement mapping or a clip of the pixels that leave the texture fixes this.
- Depends on the depth convention. Some engines store height (1 at the top), others depth. Flip to when the map is a height map.
Variants and improvements
- No refinement. McGuire and McGuire (2005) return the first sample under the surface without the secant step. The error is up to one step, and the result shows layers.
- Binary search. Relief mapping (Policarpo, Oliveira and Comba, 2005) refines the bracket with several steps of bisection in place of one secant step.
- A step count from the angle. The ray crosses more texels at a grazing angle. Engines often set between a minimum and a maximum by the angle between and the normal. The values are tuning.
- Self-shadowing. From the hit, march toward the light the same way. If any sample is above the ray, the point is in shadow. Tatarchuk (2006) derives an approximate soft shadow from the same samples.
- Cone step mapping and distance fields. A precomputed cone or distance per texel gives a safe step size, as in sphere tracing, so the march can take large steps without missing thin features.
- Mip level selection. Use the gradients of for all samples, so that the texture lookups in the loop pick the same mip level as the pixel.
When to use it
Use it for walls, floors and rocks that the camera sees from close by, where normal mapping looks flat and real geometry costs too much. It suits relief that is shallow compared with the size of the polygon. Use normal mapping for distant or very fine detail, parallax mapping when only one sample is affordable, and displacement mapping when the silhouette matters.
Pitfalls
- Thin features. A wall thinner than one step can fall between two samples, and the ray passes through it. The code test shows a wall one texel wide that a march of 8 steps misses and a march of 512 steps finds. Raise at grazing angles.
- Stair steps. Without the secant step, or with too few steps, the result shows layers at grazing angles.
- Grazing angles. As , grows without a bound, and the march crosses many texels per step. Clamp or fade the effect out at grazing angles.
- Gradient instructions in a loop. Texture lookups with an implicit mip level inside a loop with a varying count can give wrong derivatives on a GPU. Use explicit gradients or an explicit level.
- Wrong tangent frame. The view vector must be in the same tangent frame as the texture axes. A mirrored or wrongly signed bitangent moves the relief the wrong way.
- Depth and height mixed up. If the map is a height map, the relief appears inverted.
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/parallax-occlusion-mapping/. The authors are listed in prov/2N7VM7.jsonl.
"""Parallax occlusion mapping: a linear march through a depth map, then a secant step.
Conventions (tangent space):
- The depth map m(u, v) is in [0, 1]. Depth 0 is the top of the surface (the
polygon) and depth 1 is the deepest point, at `scale` texture units below it.
- view = (vx, vy, vz) points from the surface point toward the viewer, vz > 0.
- Going one unit of depth down along the view ray moves the texture coordinate
by delta = -scale * (vx, vy) / vz.
The ray at depth r is at uv0 + r * delta. It is below the surface when
r >= m(uv0 + r * delta), so the hit is a root of f(r) = r - m(uv0 + r * delta).
Since f(0) <= 0 and f(1) >= 0, a root always exists in [0, 1] for a continuous m.
"""
from fractions import Fraction
from math import floor
def pom(depth, uv0, view, scale, steps, exact=False):
"""Return (uv, r): the texture coordinate of the hit and its depth r in [0, 1].
With exact=True the sample depths are Fractions, so that rational inputs
and a rational depth map give an exact result.
"""
vx, vy, vz = view
if vz <= 0:
raise ValueError("the view vector must point out of the surface")
du, dv = -scale * vx / vz, -scale * vy / vz # @line L1
r_prev, f_prev = 0, 0 - depth(uv0[0], uv0[1]) # @line L2
if f_prev >= 0: # @line L3
return (uv0[0], uv0[1]), 0
for i in range(1, steps + 1): # @line L4
r = Fraction(i, steps) if exact else i / steps
f = r - depth(uv0[0] + r * du, uv0[1] + r * dv) # @line L5
if f >= 0: # @line L6
t = f_prev / (f_prev - f) # @line L7
rh = r_prev + t * (r - r_prev) # @line L8
return (uv0[0] + rh * du, uv0[1] + rh * dv), rh
r_prev, f_prev = r, f # @line L9
raise AssertionError("unreachable for a depth map with values in [0, 1]")
def depth_texture(texels):
"""A bilinear, wrapping sampler for a depth image given as rows of values in [0, 1].
Texel (x, y) has its center at ((x + 0.5) / w, (y + 0.5) / h).
"""
h, w = len(texels), len(texels[0])
def sample(u, v):
x, y = u * w - 0.5, v * h - 0.5
x0, y0 = floor(x), floor(y)
fx, fy = x - x0, y - y0
def t(i, j):
return texels[j % h][i % w]
top = t(x0, y0) * (1 - fx) + t(x0 + 1, y0) * fx
bot = t(x0, y0 + 1) * (1 - fx) + t(x0 + 1, y0 + 1) * fx
return top * (1 - fy) + bot * fy
return sample
def first_hit_dense(depth, uv0, view, scale, samples=20000):
"""A reference: the first sample of a very fine march, then bisection to full precision."""
vx, vy, vz = view
du, dv = -scale * vx / vz, -scale * vy / vz
def f(r):
return r - depth(uv0[0] + r * du, uv0[1] + r * dv)
if f(0.0) >= 0:
return 0.0
prev = 0.0
for i in range(1, samples + 1):
r = i / samples
if f(r) >= 0:
lo, hi = prev, r
for _ in range(60):
mid = (lo + hi) / 2
if f(mid) >= 0:
hi = mid
else:
lo = mid
return hi
prev = r
return 1.0
test_parallax_occlusion_mapping.py 106 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/parallax-occlusion-mapping/. The authors are listed in prov/2N7VM7.jsonl.
"""Tests of parallax occlusion mapping.
The secant step is exact for a planar depth map (checked with Fractions).
On smooth depth maps the result is within one step of the first hit found by
a dense march with bisection, whenever the ray stays under the surface for at
least one step. The tests also check the bracket of the returned hit, the
view along the normal, and the thin feature that a coarse march misses.
"""
import random
from fractions import Fraction
from math import cos, pi, sin, sqrt
from parallax_occlusion_mapping import depth_texture, first_hit_dense, pom
def f_of(depth, uv0, view, scale):
vx, vy, vz = view
du, dv = -scale * vx / vz, -scale * vy / vz
return lambda r: r - depth(uv0[0] + r * du, uv0[1] + r * dv)
def test_planar_depth_is_exact():
rng = random.Random(1)
for _ in range(300):
a = Fraction(rng.randint(35, 60), 100)
b, c = Fraction(rng.randint(-20, 20), 100), Fraction(rng.randint(-20, 20), 100)
def depth(u, v):
return a + b * u + c * v
uv0 = (Fraction(rng.randint(40, 60), 100), Fraction(rng.randint(40, 60), 100))
view = (Fraction(rng.randint(-100, 100), 100), Fraction(rng.randint(-100, 100), 100),
Fraction(rng.randint(50, 100), 100))
scale = Fraction(1, 10)
du, dv = -scale * view[0] / view[2], -scale * view[1] / view[2]
want = (a + b * uv0[0] + c * uv0[1]) / (1 - b * du - c * dv)
(u, v), r = pom(depth, uv0, view, scale, rng.randint(1, 40), exact=True)
assert r == want
assert (u, v) == (uv0[0] + want * du, uv0[1] + want * dv)
assert r == depth(u, v)
def smooth_depth(u, v):
return 0.5 + 0.25 * sin(2 * pi * 2 * u) * cos(2 * pi * 3 * v)
def test_within_one_step_of_first_hit():
rng = random.Random(2)
checked = 0
for _ in range(150):
uv0 = (rng.random(), rng.random())
theta, phi = rng.uniform(0, 1.3), rng.uniform(0, 2 * pi)
view = (sin(theta) * cos(phi), sin(theta) * sin(phi), cos(theta))
scale, k = 0.08, rng.choice((8, 16, 32))
(_, _), r = pom(smooth_depth, uv0, view, scale, k)
f = f_of(smooth_depth, uv0, view, scale)
rstar = first_hit_dense(smooth_depth, uv0, view, scale, samples=2000)
# The condition of the theorem: f >= 0 on [r*, r* + 1/k].
if all(f(rstar + j / (200 * k)) >= -1e-12 for j in range(201) if rstar + j / (200 * k) <= 1):
assert abs(r - rstar) <= 1 / k + 1e-9
checked += 1
assert checked > 100
def test_result_brackets_a_root():
rng = random.Random(3)
tex = depth_texture([[rng.random() for _ in range(16)] for _ in range(16)])
for _ in range(300):
uv0 = (rng.random(), rng.random())
view = (rng.uniform(-1, 1), rng.uniform(-1, 1), rng.uniform(0.2, 1))
k = rng.randint(1, 30)
(_, _), r = pom(tex, uv0, view, 0.1, k)
assert 0 <= r <= 1
f = f_of(tex, uv0, view, 0.1)
if r > 0:
i = -(-r * k // 1) # the sample that stopped the march
lo, hi = (i - 1) / k, i / k
assert lo - 1e-12 <= r <= hi + 1e-12
assert f(lo) < 0 <= f(hi) + 1e-12
def test_view_along_normal_returns_same_texel():
tex = depth_texture([[0.1, 0.7], [0.4, 0.9]])
for uv0 in ((0.1, 0.2), (0.6, 0.6), (0.9, 0.3)):
(u, v), r = pom(tex, uv0, (0.0, 0.0, 1.0), 0.1, 10)
assert (u, v) == uv0
assert abs(r - tex(*uv0)) < 1e-12
def test_thin_wall_is_missed_by_a_coarse_march():
n = 256
row = [1.0] * n
row[n // 2] = 0.0 # a wall one texel wide, at u = 0.5
tex = depth_texture([row] * 4)
uv0, scale = (0.31, 0.5), 0.1
view = (-4 / sqrt(17), 0.0, 1 / sqrt(17)) # the ray moves +0.4 in u per unit depth
(_, _), coarse = pom(tex, uv0, view, scale, 8)
(_, _), fine = pom(tex, uv0, view, scale, 512)
rstar = first_hit_dense(tex, uv0, view, scale)
assert abs(fine - rstar) <= 1 / 512
assert rstar < 0.5
assert coarse > 0.9 # the coarse march passes the wall and hits the floor
History
Kaneko and others introduced parallax mapping in 2001, with one offset per pixel, and Welsh added offset limiting in 2004. In 2004 Brawley and Tatarchuk described a march of the height map per pixel, which they traced in reverse from the eye, in ShaderX3. McGuire and McGuire showed the march without a refinement step in a 2005 poster, and Policarpo, Oliveira and Comba refined it with a binary search in relief mapping in the same year. Tatarchuk presented the dynamic version with approximate soft shadows at I3D 2006 and in a SIGGRAPH course that year, and the method became standard in game engines.
References
- Natalya Tatarchuk, Dynamic parallax occlusion mapping with approximate soft shadows, Proceedings of the 2006 Symposium on Interactive 3D Graphics and Games (I3D 2006), the linear march of the height field in tangent space, the intersection between the last two samples, and the soft shadow march toward the light (general locator)
- Natalya Tatarchuk, Practical parallax occlusion mapping with approximate soft shadows for detailed surface rendering, SIGGRAPH 2006 course notes, the course version of the same method, with the choice of the sample count (general locator)
- Zoe Brawley and Natalya Tatarchuk, Parallax occlusion mapping, ShaderX3, 2004, the whole chapter (the per-pixel march of the height map)
- Fabio Policarpo, Manuel M. Oliveira and João L. D. Comba, Real-time relief mapping on arbitrary polygonal surfaces, I3D 2005, the linear search followed by a binary search (general locator)
- Morgan McGuire and Max McGuire, Steep parallax mapping, I3D 2005 poster, the linear march without a refinement step (general locator)
- 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 6.8, Parallax Mapping, from page 214
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 2N7VM7 Edit this page History Report an error Markdown