Algorithmadvanced
Clustered shading
Also called clustered light culling.
Group pixels into clusters by screen tile and exponential depth slice, keep a light list for each occupied cluster, and shade each pixel with the lights of its cluster.
- Time
- O(t l) assignmentO(p) keysO(p k) shading
- Space
- O(p) keysO(t l) lists
- Where
- k = the average number of lights kept per pixel; l = the number of lights; p = the number of pixels; t = the number of occupied clusters
- Model
- Real RAM
- Properties
- deterministicnot in placeofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Ola Olsson, Markus Billeter, Ulf Assarsson, 2012
Clustered shading is a light culling method that groups the pixels of the screen into clusters in view space. A cluster is a screen tile cut along the depth into one slice of an exponential sequence, so that each cluster is about as deep as it is wide. The method finds the clusters that hold at least one pixel, builds a list of lights for each of them, and shades each pixel with the lights of its cluster. It is the successor of tiled shading, whose lists cover the whole depth range of a tile: a tile with a near object and a far wall gets every light between them. Clusters cut that range into pieces. Olsson, Billeter and Assarsson published it in 2012 for both deferred shading and forward shading.
In plain words
Tiled shading cuts the screen into squares and gives each square one list of lights. If a square shows a close object and a far wall, the list must hold all lights between them, even the ones that light nothing visible. Clustered shading also cuts the space behind each square into layers, like the floors of a building that gets wider with distance. The layers get thicker farther away, so that each piece is about as deep as it is wide. Only pieces that contain a visible surface get a list. Each pixel then looks up the piece it falls into and uses that list, which is usually shorter.
The problem
The input is the same as for tiled shading: a depth buffer of pixels with the view depth of the visible surface, the surface attributes of each pixel, and point lights with centers and radii . A light reaches a point only if the distance is below its radius. The output is the image with the full sum of light contributions at each pixel, and the goal is short light lists that never miss a light that reaches a pixel.
The camera looks along , and the page stores the view depth . Pixel centers are at . The screen has tiles of pixels, the vertical field of view is and the near plane is at the depth . The paper defines the slices by
its Equations 1 and 2. Slice covers the depths .
The algorithm
The paper gives five steps: render the G-buffer, assign clusters, find the unique clusters, assign lights to clusters, and shade. Lines L1 to L3 are steps 2 and 3, lines L4 to L6 are step 4 and lines L7 to L9 are step 5. . SPHERE-IN-CLUSTER is the test of the tiled shading page with the slab in place of the depth range of the tile.
CLUSTERED-SHADING(D, G, lights, T)- 1
for each pixel q with geometry - 2
key[q] ← (⌊qx / T⌋, ⌊qy / T⌋, ⌊log(D[q] / n0) / log q⌋) - 3
C ← the set of distinct keys ▷ sort, hash, or a flag per cluster - 4
for each cluster κ = (i, j, k) in C - 5
F ← the side planes of tile (i, j); the slab is [nk, nk+1] - 6
list[κ] ← the lights j with SPHERE-IN-CLUSTER(F, nk, nk+1, cj, rj) - 7
for each pixel q with geometry - 8
c ← the sum of SHADE(G[q], Pq, light j) over j in list[key[q]] - 9
out[q] ← c
The slices (line L2). The ratio makes the slices self-similar. A tile is high at the depth , and slice has the depth extent , which is exactly the tile height at . So the clusters are as close to cubes as a frustum cell allows. The number of slices from to the far depth is . With a small , many thin slices are spent near the camera, and implementations often start the exponential slices at a larger depth.
The unique clusters (line L3). Most of the times (number of slices) clusters hold no pixel. The occupied ones can be found by sorting the keys, or by marking a flag per cluster in a grid and compacting the flags with a prefix sum. Only these get a list, so the light assignment is not spent on empty space.
The light assignment (lines L4 to L6). The simple form tests every light against every occupied cluster, at cost. The paper builds a bounding volume hierarchy over the lights each frame, sorted by their Morton codes, and walks it for each cluster, which replaces the brute-force loop over all lights.
Normals (an option). The paper can add a quantized normal direction to the key, so that the pixels of a cluster also face about the same way. A light behind all these surfaces can then be culled with a normal cone test. The code of this page does not do this.
Example
The slices. Take , tiles in and . Then , and the slices start at , , , , , , , and . A pixel at depth 3 gets , the slice . A pixel at depth 12 gets , the slice .
A depth gap. A tile shows a box face at depth 3 and a wall at depth 12. Tiled shading gives the tile the range . A light at depth 7 with radius covers and stays in the tile list, though it lights nothing that the tile shows. Here the tile has two occupied clusters, slices 4 and 7. The light meets neither nor , so both cluster lists drop it.
A measured scene. The room of the tests has 32 by 32 pixels, 994 of them with geometry, 60 random lights with radii between and , and 8-pixel tiles. Brute force evaluates 59 640 (pixel, light) pairs, tiled shading 5246 and clustered shading 2374, of which 63 give a nonzero contribution. 48 clusters are occupied. All three images are equal value for value. These numbers are a measurement on one scene.
Correctness
The proofs are in the proofs folder. Equation 2 gives the unique with , because and the slice bounds increase with . So the position of a pixel lies in the slab of its cluster, and inside the four side planes of its tile. If a light reaches the pixel, its sphere is not fully outside any of these six boundaries, by the same Cauchy-Schwarz step as in tiled shading. So the list of the cluster holds the light: clustered culling never drops a light that reaches a pixel. A dropped light contributes exactly 0, so the image equals the brute-force image, and with the lights in index order the floating-point sums are equal. The code corrects the slice index of a depth that rounding puts one slice off, so that the claim holds for the computed slices too. The tests check both claims at every pixel.
Proof: Clustered light assignment never drops a light that reaches a pixelfull
Setting. The conventions are those of the tiled shading page: the camera is at the origin and looks along , the view depth is , the pixel at depth has the position , and a light with center and radius reaches only if , with a contribution of exactly 0 otherwise. The screen has tiles in , the vertical field of view is , the near plane is at depth , and . Slice covers the depths with (Equation 1 of Olsson, Billeter and Assarsson). A pixel at depth gets the key (tile , tile , slice ) with (Equation 2). The light list of an occupied cluster keeps a light unless the sphere is fully outside one of the four side planes of the tile, or , or . The claims are in exact arithmetic.
Lemma 1 (the slice of a depth). For , the index of Equation 2 satisfies , and it is the only integer that does.
Proof. Since , is the same as , which is . The intervals are disjoint, because is increasing in .
In floating point, the logarithms can put a depth that lies very close to one slice off. The code corrects with one comparison against and in each direction, so Lemma 1 holds for the computed index with the computed slice bounds.
Lemma 2 (self-similar slices). The depth extent of slice equals the height of one tile at the depth .
Proof. At depth , the view frustum is high, so one of the tiles is high. The extent of slice is , which is this height at .
So the near face of each cluster is a square in view space if the tiles are square in view space, and the cluster is as deep as it is high. The far face is larger by the factor .
Theorem 1 (no miss). If a light reaches the position of a pixel, then the light is in the list of the cluster of that pixel.
Proof. Let the pixel be in tile and slice . By Lemma 1 of the tiled shading proof, for each of the four inward unit normals of , so with we get , and no plane rejects the light. By Lemma 1 above, , where . Also . Hence and , and the depth test keeps the light.
Theorem 2 (the image is the brute-force image). If the lists hold every light that reaches a pixel of the cluster and are visited in increasing index order, the clustered image equals the brute-force image value for value, also in floating point.
Proof. As for tiled shading: each light that is not in the list contributes exactly to the brute-force sum, and adding to a sum that is does not change it, so both sums perform the same nonzero additions in the same order.
Theorem 3 (cost). Let be the number of pixels, the number of lights and the number of occupied clusters. The keys cost , finding the occupied clusters costs expected time with hashing or with sorting, the light assignment by testing every light against every occupied cluster costs , and . With tiles and the depth range , also .
Proof. Each pixel computes one key in . The set of distinct keys is built with one insertion per pixel. Each pair of an occupied cluster and a light costs one test of . A cluster is occupied only if at least one pixel has its key, so . The slice index of a depth in is at most , which bounds the number of slices.
What is not claimed. Clusters remove the false positives of a large depth range in a tile, but the list of a cluster is not always a subset of the list of its tile, because the slab of the slice can reach past the nearest or farthest pixel of the tile. The gain over tiled shading in the tests is a measurement on one scene. The radius of a light, the tile size and the slice ratio are tuning.
Complexity
The model is the real RAM, with pixels, lights, occupied clusters and an average of kept lights per pixel. The keys cost . The unique clusters cost expected time with a hash or a flag grid and a prefix sum, or with a comparison sort (radix sort on GPUs). The assignment by brute force costs , and with a hierarchy over the lights it costs to build plus a walk per cluster whose cost depends on the overlap of lights. The shading costs . Always , and .
The number is usually a small multiple of the number of tiles, because the visible surfaces in a tile cover few slices. The lists take space in the worst case.
Properties
- Conservative. No light that reaches a pixel is dropped.
- Robust to depth gaps. A tile with far apart depths gets separate clusters for its surfaces, so lights in the gap are culled.
- View dependent. The clusters follow the view frustum and are built each frame. A cluster grid fixed in view space can also be filled without a depth buffer, which forward renderers and transparent surfaces use.
- Self-similar cells. With the ratio of Equation 1, each cluster is as deep as it is high at its near face.
- Indirection. Each pixel finds its list through its key, which costs a lookup that tiled shading does not need.
Variants and improvements
- Clustered forward shading. The cluster key of a fragment is computed from its own depth, so transparent fragments and MSAA work, and the lists are built for all clusters of a fixed grid or for the clusters a depth pre-pass marks.
- Tighter bounds. The real minimum and maximum depth of the pixels inside a cluster can replace the slab bounds, and the side planes can be replaced by the bounding box of the pixel positions.
- Normal clusters. A quantized normal in the key, with a cone test against the light, as in the paper.
- Linear or mixed slices. Fewer slices near the camera and exponential slices farther away, a common change for wide depth ranges.
- Light hierarchies. A hierarchy over the lights, as in the paper, or a uniform grid over the lights in view space.
When to use it
Use clustered shading when tiles often hold surfaces at very different depths, as in first-person views, foliage and long views, or when transparent surfaces and forward materials need light lists at their own depth. Use plain tiled shading when the depth is mostly continuous inside tiles and the extra lookup and the cluster search do not pay. With few lights, neither is needed.
Pitfalls
- Slices near the camera. With a small , Equation 1 spends many slices on the first meter. Start the exponential slices at a larger depth and put the near region into one slice.
- Rounding at slice borders. The logarithm can put a depth that lies on a slice border into the wrong slice, which can drop a light. Check against and .
- Depth space. Equation 2 needs the linear view depth, not the value of a nonlinear depth buffer.
- List storage. The total length of all lists varies by frame. Build it with a count, a prefix sum and a fill, or a fixed budget per cluster that can overflow.
- Cluster grid size. A finer grid gives shorter lists but more clusters to cull and more memory. The tile size and the number of slices are tuning.
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/clustered-shading/. The authors are listed in prov/82B7J9.jsonl.
"""Clustered deferred shading, after Olsson, Billeter and Assarsson (2012).
Each pixel gets a cluster key (i, j, k): the screen tile (i, j) and the depth
slice k. The slices grow exponentially with the depth, so that each cluster is
about as deep as it is wide (Equations 1 and 2 of the paper):
near_k = near * (1 + 2 tan(theta) / S_y) ** k
k = floor(log(d / near) / log(1 + 2 tan(theta) / S_y))
where 2 theta is the vertical field of view and S_y the number of tiles in y.
Only the clusters that hold at least one pixel get a light list. A light is
kept for a cluster unless its sphere is outside one of the four side planes
of the tile or outside the depth slab of the slice.
Conventions as on the tiled shading page: the camera looks along -z, the depth
buffer holds the view depth d = -z > 0 or math.inf for the background, and
pixel (i, j) has its center at (i + 1/2, j + 1/2).
"""
import math
from dataclasses import dataclass
Vec3 = tuple[float, float, float]
@dataclass(frozen=True)
class Camera:
width: int
height: int
tan_half: float
near: float
def ndc_to_slope(self, sx: float, sy: float) -> tuple[float, float]:
aspect = self.width / self.height
return (2.0 * sx / self.width - 1.0) * aspect * self.tan_half, (2.0 * sy / self.height - 1.0) * self.tan_half
def position(self, i: int, j: int, d: float) -> Vec3:
u, v = self.ndc_to_slope(i + 0.5, j + 0.5)
return (u * d, v * d, -d)
@dataclass(frozen=True)
class Light:
center: Vec3
radius: float
intensity: float
def dot(a: Vec3, b: Vec3) -> float:
return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
def shade(p: Vec3, n: Vec3, light: Light) -> float:
"""Lambert term times a falloff that is 0 for distances >= radius."""
lx, ly, lz = light.center[0] - p[0], light.center[1] - p[1], light.center[2] - p[2]
dist2 = lx * lx + ly * ly + lz * lz
r2 = light.radius * light.radius
if dist2 >= r2:
return 0.0
dist = math.sqrt(dist2)
cos_t = 0.0 if dist == 0.0 else max(0.0, (n[0] * lx + n[1] * ly + n[2] * lz) / dist)
w = 1.0 - dist2 / r2
return light.intensity * cos_t * w * w
def affects(p: Vec3, light: Light) -> bool:
c = light.center
return (c[0] - p[0]) ** 2 + (c[1] - p[1]) ** 2 + (c[2] - p[2]) ** 2 < light.radius * light.radius
def brute_force(depth, normals, cam: Camera, lights: list[Light]) -> list[list[float]]:
out = [[0.0] * cam.width for _ in range(cam.height)]
for j in range(cam.height):
for i in range(cam.width):
d = depth[j][i]
if d == math.inf:
continue
p = cam.position(i, j, d)
c = 0.0
for light in lights:
c += shade(p, normals[j][i], light)
out[j][i] = c
return out
def slice_ratio(cam: Camera, tile: int) -> float:
"""1 + 2 tan(theta) / S_y, with S_y = height / tile tiles in y."""
s_y = cam.height / tile
return 1.0 + 2.0 * cam.tan_half / s_y
def slice_near(cam: Camera, tile: int, k: int) -> float:
"""Equation 1: the near depth of slice k."""
return cam.near * slice_ratio(cam, tile) ** k
def slice_index(cam: Camera, tile: int, d: float) -> int:
"""Equation 2, with a correction step against rounding at the borders."""
q = slice_ratio(cam, tile)
k = int(math.floor(math.log(d / cam.near) / math.log(q)))
while k > 0 and slice_near(cam, tile, k) > d:
k -= 1
while slice_near(cam, tile, k + 1) <= d:
k += 1
return k
def side_planes(cam: Camera, x0: float, x1: float, y0: float, y1: float) -> list[Vec3]:
u0, v0 = cam.ndc_to_slope(x0, y0)
u1, v1 = cam.ndc_to_slope(x1, y1)
planes = []
for m in ((1.0, 0.0, u0), (-1.0, 0.0, -u1), (0.0, 1.0, v0), (0.0, -1.0, -v1)):
length = math.sqrt(dot(m, m))
planes.append((m[0] / length, m[1] / length, m[2] / length))
return planes
def sphere_in_cluster(planes: list[Vec3], d0: float, d1: float, light: Light) -> bool:
"""Conservative: False only if the sphere misses the cluster frustum."""
c, r = light.center, light.radius * (1.0 + 1e-9) + 1e-12
for m in planes:
if dot(m, c) < -r:
return False
dc = -c[2]
return not (dc + r < d0 or dc - r > d1)
def cluster_keys(depth, cam: Camera, tile: int) -> dict[tuple[int, int], tuple[int, int, int]]:
"""Step 2 of the paper: the cluster key of every pixel with geometry."""
keys = {}
for j in range(cam.height):
for i in range(cam.width):
d = depth[j][i]
if d != math.inf:
keys[(i, j)] = (i // tile, j // tile, slice_index(cam, tile, d)) # @line L2
return keys
def assign_lights(cam: Camera, tile: int, clusters, lights: list[Light]) -> dict[tuple[int, int, int], list[int]]:
"""Step 4: the light list of every occupied cluster, in light order."""
lists = {}
for key in sorted(clusters): # @line L4
ti, tj, k = key
x0, y0 = ti * tile, tj * tile
planes = side_planes(cam, x0, min(x0 + tile, cam.width), y0, min(y0 + tile, cam.height)) # @line L5
d0, d1 = slice_near(cam, tile, k), slice_near(cam, tile, k + 1)
lists[key] = [idx for idx, light in enumerate(lights) if sphere_in_cluster(planes, d0, d1, light)] # @line L6
return lists
def clustered_shading(depth, normals, cam: Camera, lights: list[Light], tile: int = 16):
"""The five steps. Returns the image, the cluster lists and the number of
(pixel, light) pairs that the shading loop evaluated."""
keys = cluster_keys(depth, cam, tile) # @line L1
clusters = set(keys.values()) # @line L3
lists = assign_lights(cam, tile, clusters, lights)
out = [[0.0] * cam.width for _ in range(cam.height)]
pairs = 0
for (i, j), key in keys.items(): # @line L7
p = cam.position(i, j, depth[j][i])
c = 0.0
for idx in lists[key]: # @line L8
c += shade(p, normals[j][i], lights[idx])
pairs += len(lists[key])
out[j][i] = c # @line L9
return out, lists, pairs
test_clustered_shading.py 129 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/clustered-shading/. The authors are listed in prov/82B7J9.jsonl.
"""Clustered shading against brute-force shading, and the slice formulas."""
import math
import random
from clustered_shading import (
Camera,
Light,
affects,
brute_force,
cluster_keys,
clustered_shading,
side_planes,
slice_index,
slice_near,
sphere_in_cluster,
)
def room(cam: Camera):
"""The scene of the tiled shading tests: floor, side walls, a back wall
at d = 12 with an open window, and a box face at d = 3."""
depth = [[math.inf] * cam.width for _ in range(cam.height)]
normals = [[(0.0, 0.0, 1.0)] * cam.width for _ in range(cam.height)]
for j in range(cam.height):
for i in range(cam.width):
u, v = cam.ndc_to_slope(i + 0.5, j + 0.5)
hits = []
if not (u * 12.0 > 2.0 and v * 12.0 > 1.0):
hits.append((12.0, (0.0, 0.0, 1.0)))
if v < 0.0:
hits.append((-1.0 / v, (0.0, 1.0, 0.0)))
if u < 0.0 and -4.0 / u <= 12.0:
hits.append((-4.0 / u, (1.0, 0.0, 0.0)))
if u > 0.0 and 4.0 / u <= 12.0:
hits.append((4.0 / u, (-1.0, 0.0, 0.0)))
if -1.0 <= 3.0 * u <= 0.5 and -1.0 <= 3.0 * v <= 0.5:
hits.append((3.0, (0.0, 0.0, 1.0)))
if hits:
depth[j][i], normals[j][i] = min(hits)
return depth, normals
def random_lights(rng: random.Random, count: int, r_max: float = 3.0) -> list[Light]:
return [
Light(
(rng.uniform(-4.0, 4.0), rng.uniform(-1.0, 3.0), rng.uniform(-12.0, -1.0)),
rng.uniform(0.3, r_max),
rng.uniform(0.5, 2.0),
)
for _ in range(count)
]
def tiled_pairs(depth, cam: Camera, lights: list[Light], tile: int) -> int:
"""(pixel, light) pairs of plain tiled culling with the tile depth range."""
total = 0
for ty in range(cam.height // tile):
for tx in range(cam.width // tile):
ds = [depth[j][i] for j in range(ty * tile, ty * tile + tile) for i in range(tx * tile, tx * tile + tile)]
ds = [d for d in ds if d != math.inf]
if not ds:
continue
planes = side_planes(cam, tx * tile, tx * tile + tile, ty * tile, ty * tile + tile)
kept = sum(1 for light in lights if sphere_in_cluster(planes, min(ds), max(ds), light))
total += kept * len(ds)
return total
def test_slice_formulas() -> None:
cam = Camera(64, 48, 0.8, 0.5)
tile = 8
rng = random.Random(31)
for _ in range(2000):
d = math.exp(rng.uniform(math.log(0.5), math.log(200.0)))
k = slice_index(cam, tile, d)
assert slice_near(cam, tile, k) <= d < slice_near(cam, tile, k + 1)
# Self-similar slices: the depth of slice k equals the height of a tile at near_k.
s_y = cam.height / tile
for k in range(40):
n0, n1 = slice_near(cam, tile, k), slice_near(cam, tile, k + 1)
assert abs((n1 - n0) - 2.0 * n0 * cam.tan_half / s_y) <= 1e-9 * n1
def test_no_light_is_missed() -> None:
rng = random.Random(32)
cam = Camera(48, 32, 1.0, 0.5)
depth, normals = room(cam)
for tile in (4, 8):
lights = random_lights(rng, 40)
_, lists, _ = clustered_shading(depth, normals, cam, lights, tile)
keys = cluster_keys(depth, cam, tile)
for (i, j), key in keys.items():
p = cam.position(i, j, depth[j][i])
kept = set(lists[key])
for idx, light in enumerate(lights):
if affects(p, light):
assert idx in kept
def test_equals_brute_force_exactly() -> None:
rng = random.Random(33)
cam = Camera(40, 24, 0.7, 0.5)
depth, normals = room(cam)
lights = random_lights(rng, 30)
out, _, _ = clustered_shading(depth, normals, cam, lights, tile=8)
assert out == brute_force(depth, normals, cam, lights)
def test_only_occupied_clusters_get_lists() -> None:
cam = Camera(32, 32, 1.0, 0.5)
depth, normals = room(cam)
_, lists, _ = clustered_shading(depth, normals, cam, [], tile=8)
assert set(lists) == set(cluster_keys(depth, cam, 8).values())
assert len(lists) <= sum(1 for row in depth for d in row if d != math.inf)
def test_fewer_pairs_than_tiles_with_depth_gaps() -> None:
"""A measurement on this scene: many small lights between the box and the
back wall. Clusters cut the tile depth range, so fewer pairs remain."""
rng = random.Random(34)
cam = Camera(32, 32, 1.0, 0.5)
depth, normals = room(cam)
lights = random_lights(rng, 60, r_max=0.8)
_, _, pairs = clustered_shading(depth, normals, cam, lights, tile=8)
assert pairs < tiled_pairs(depth, cam, lights, 8)
History
Tiled shading (Olsson and Assarsson 2011) keeps one list per screen tile over the depth range of the tile. Olsson, Billeter and Assarsson (2012) added the depth slices of Equation 1 and the optional normal direction, found only the occupied clusters, and assigned the lights with a hierarchy over the lights in place of the brute-force test of every light against every tile. They showed both a deferred and a forward form. The forward form gives light lists at any depth, which is what transparent surfaces need.
References
- Ola Olsson, Markus Billeter and Ulf Assarsson, Clustered deferred and forward shading, High-Performance Graphics 2012, 87-96, Section 3 (the five steps), Equations 1 and 2 (the exponential depth slices), and Section 3.3 (light assignment with a hierarchy over the lights)
- Ola Olsson and Ulf Assarsson, Tiled shading, Journal of Graphics, GPU, and Game Tools 15(4), 235-251, 2011, the tiled method that clustered shading extends, and the effect of the depth range of a tile
- 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 20, Efficient Shading (the part on clustered shading)
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 82B7J9 Edit this page History Report an error Markdown