Algorithm Search⌘K

Algorithmadvanced

Tiled shading

Also called tiled light culling, Forward+.

Cut the screen into tiles, keep for each tile the lights whose volume can reach its frustum between the nearest and farthest depth, and shade each pixel with the lights of its tile only.

Time
O(p l) worstO(p + t l) cullingO(p k) shading
Space
O(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 tiles
Properties
deterministicnot in placeofflineiterative
Origin
Ola Olsson, Ulf Assarsson, Takahiro Harada, Jay McKee, Jason C. Yang, 2011

Tiled shading is a light culling method for scenes with many local lights. It cuts the screen into square tiles, often 16 by 16 pixels. For each tile it finds the nearest and the farthest depth of its pixels, builds the frustum that these bounds cut out of the view, and keeps the lights whose sphere of influence is not outside it. Each pixel then shades only the lights in the list of its tile. With deferred shading, the culling and the shading run in one compute pass over the G-buffer, and each pixel reads its G-buffer record once. In tiled forward shading, a depth pre-pass gives the tile depths and the forward pass reads the lists. Olsson and Assarsson described both forms in 2011. Clustered shading is the successor that also cuts the depth range into slices.

In plain words

A scene has hundreds of small lights, but each one lights only a small part of the screen. Testing every light at every pixel wastes almost all the work. So the screen is cut into small squares. For each square, the method looks at how near and how far the visible surfaces are, and asks of each light: can its light reach anything in this box? If the answer is no, the light is left out of the list of that square. Then every pixel goes only through the short list of its square. The test is careful in one direction: it can keep a light that does not reach any pixel, but it never leaves out a light that does.

The problem

The input is a depth buffer DD of p=WHp = W H pixels with the view depth d>0d > 0 of the visible surface (or none for the background), the surface attributes of each pixel, and ll point lights. Light jj has a center cjc_j, a radius rjr_j and an intensity. It reaches a point PP only if ∥P−cj∥<rj\lVert P - c_j \rVert < r_j, and its contribution is exactly 0 elsewhere. The output is the shaded image: for each pixel, the sum of the contributions of all lights. The brute-force method costs Θ(pl)\Theta(p l) light evaluations. The goal is a list of lights per tile that contains every light that reaches a pixel of the tile and as few other lights as possible.

The camera looks along −z-z, and the page stores the linear view depth d=−zd = -z. The pixel (i,j)(i, j) has its center at (i+1/2,j+1/2)(i + 1/2, j + 1/2), with jj counted from the bottom. With the aspect ratio a=W/Ha = W / H and the vertical field of view 2θ2\theta, a screen position sxs_x in pixels has the slope u(sx)=(2sx/W−1) atan⁡θu(s_x) = (2 s_x / W - 1)\, a \tan\theta, and v(sy)=(2sy/H−1)tan⁡θv(s_y) = (2 s_y / H - 1) \tan\theta; the pixel at depth dd is at P=d (u,v,−1)P = d\,(u, v, -1). The radius of a light is part of the light model. Real lights fall off without end, so the radius cuts them, and that cut is tuning.

The algorithm

tt is the number of tiles. Lines L1 to L6 build the lists and lines L7 to L10 shade. SPHERE-IN-TILE is the conservative test of a sphere against the four side planes of the tile, which pass through the eye, and against the depth range.

  1. TILED-SHADING(D, G, lights, T)
  2. 1for each tile τ of T × T pixels ▷ one thread group per tile
  3. 2(dmin, dmax) ← the smallest and largest D over the pixels of τ
  4. 3F ← the inward unit normals of the four side planes of τ
  5. 4list[τ] ← empty
  6. 5for each light j ▷ the threads of the group share this loop
  7. 6if SPHERE-IN-TILE(F, dmin, dmax, cj, rj) then append j to list[τ]
  8. 7for each pixel q with geometry, in tile τ
  9. 8P ← the view position of q; c ← 0
  10. 9for each j in list[τ]: c ← c + SHADE(G[q], P, light j)
  11. 10out[q] ← c
  12. SPHERE-IN-TILE(F, dmin, dmax, c, r)
  13. 11for each m in F: if m · c < -r then return false
  14. 12if -cz + r < dmin or -cz - r > dmax then return false
  15. 13return true

The planes (line L3). The tile covers the pixel rectangle [x0,x1]×[y0,y1][x_0, x_1] \times [y_0, y_1]. Its left plane holds the points with x/d≥u(x0)x / d \ge u(x_0), which is x+u(x0)z≥0x + u(x_0) z \ge 0, so its normal is (1,0,u(x0))(1, 0, u(x_0)) after normalizing. The right plane has (−1,0,−u(x1))(-1, 0, -u(x_1)), and the two planes in yy are the same with vv. The planes depend only on the tile, so they can be computed once per frame.

The depth range (line L2). On a GPU, the threads of a tile read one pixel each and reduce the depth with atomic min and max in shared memory. Background pixels do not take part. A tile with no geometry gets an empty list.

The light loop (lines L5 and L6). The threads of the group take the lights in steps of the group size and append the kept ones to a list in shared memory with an atomic add on its length. The order in the list then depends on the timing of the threads. The code of this page keeps the index order, which makes the floating-point sum equal to the brute-force sum.

The test (lines L11 to L13). A sphere that is fully outside one plane, or fully nearer than dmin⁡d_{\min} or farther than dmax⁡d_{\max}, cannot reach a point in the tile. The test does not catch every miss. A sphere near the corner of two planes can be outside the frustum but not outside either plane.

Example

The test by hand. The screen is 32 by 32 pixels with tan⁡θ=1\tan\theta = 1 and 16-pixel tiles. The tile in the lower left covers u,v∈[−1,0]u, v \in [-1, 0]. Its four normals are (1,0,−1)/2(1, 0, -1)/\sqrt 2, (−1,0,0)(-1, 0, 0), (0,1,−1)/2(0, 1, -1)/\sqrt 2 and (0,−1,0)(0, -1, 0). Say its pixels have the depth range [3,12][3, 12].

light center rr the test result
A (0.5,−0.5,−5)(0.5, -0.5, -5) 1 right plane −0.5≥−1-0.5 \ge -1, the other planes positive, [dc−r,dc+r]=[4,6][d_c - r, d_c + r] = [4, 6] meets [3,12][3, 12] kept
B (2,−1,−5)(2, -1, -5) 1 right plane (−1,0,0)⋅c=−2<−1(-1, 0, 0) \cdot c = -2 < -1 culled
C (−1,−1,−20)(-1, -1, -20) 2 dc−r=18>12d_c - r = 18 > 12 culled
D (−0.5,−0.5,−7)(-0.5, -0.5, -7) 0.5 all planes pass, 7∈[3,12]7 \in [3, 12] kept

If the tile shows a box face at depth 3 and a wall at depth 12 and nothing between, light D reaches no pixel but stays in the list. This is a false positive caused by the depth gap.

A measured scene. The tests render a room of 32 by 32 pixels: a floor, two side walls, a back wall at depth 12 with an open window, and a box face at depth 3. 994 pixels have geometry, and there are 60 random lights with radii between 0.3 and 0.8. Brute force evaluates 994⋅60=59 640994 \cdot 60 = 59\,640 (pixel, light) pairs. Tiled shading with 8-pixel tiles evaluates 5246 pairs, and only 63 pairs have a nonzero contribution. Clustered shading on the same scene evaluates 2374 pairs. The image is the same in all three cases, value for value. These counts are a measurement on one scene.

Correctness

The proofs are in the proofs folder. The pixel center of a tile lies on the inner side of all four planes at every depth, because the slope uu is an increasing function of the screen position. If a light reaches a pixel, then ∥P−c∥<r\lVert P - c \rVert < r, and for each unit normal mm the Cauchy-Schwarz inequality gives m⋅c≥m⋅P−∥P−c∥>−rm \cdot c \ge m \cdot P - \lVert P - c \rVert > -r. The depth of the pixel is in [dmin⁡,dmax⁡][d_{\min}, d_{\max}] and differs from −cz-c_z by less than rr. So no line of the test rejects the light: culling never drops a light that reaches a pixel. Since a dropped light contributes exactly 0, the tiled image equals the brute-force image, and with the lights visited in index order the two floating-point sums are equal too. The tests check both claims at every pixel, with the exact distance test as the reference.

Proof: Tiled light culling never drops a light that reaches a pixelfull

Setting. The camera is at the origin and looks along −z-z. The screen has W×HW \times H pixels, the aspect ratio is a=W/Ha = W / H and tan⁡θ\tan\theta is the tangent of half the vertical field of view. A screen point (sx,sy)(s_x, s_y) in pixels has the slopes u(sx)=(2sx/W−1) atan⁡θu(s_x) = (2 s_x / W - 1)\, a \tan\theta and v(sy)=(2sy/H−1)tan⁡θv(s_y) = (2 s_y / H - 1) \tan\theta, and the pixel (i,j)(i, j) with view depth d>0d > 0 has the position P=d (u(i+1/2),v(j+1/2),−1)P = d\,(u(i + 1/2), v(j + 1/2), -1). A light has a center cc and a radius r>0r > 0, and it reaches PP if ∥P−c∥<r\lVert P - c \rVert < r. SHADE returns exactly 0 when ∥P−c∥≥r\lVert P - c \rVert \ge r. A tile covers the pixel rectangle [x0,x1]×[y0,y1][x_0, x_1] \times [y_0, y_1], and dmin⁡d_{\min} and dmax⁡d_{\max} are the smallest and largest depths of its pixels with geometry. Lines L11 to L13 keep a light unless m⋅c<−rm \cdot c < -r for one of the four unit plane normals mm, or −cz+r<dmin⁡-c_z + r < d_{\min}, or −cz−r>dmax⁡-c_z - r > d_{\max}. The claims are in exact arithmetic. The code adds a slack of 10−9r10^{-9} r to the radius, which only keeps more lights.

Lemma 1 (pixels lie in their tile frustum). Let u0=u(x0)u_0 = u(x_0), u1=u(x1)u_1 = u(x_1), v0=v(y0)v_0 = v(y_0), v1=v(y1)v_1 = v(y_1), and let the four planes have the normals (1,0,u0)(1, 0, u_0), (−1,0,−u1)(-1, 0, -u_1), (0,1,v0)(0, 1, v_0) and (0,−1,−v1)(0, -1, -v_1), each divided by its length. Then m⋅P≥0m \cdot P \ge 0 for each of these normals and for every pixel (i,j)(i, j) of the tile at any depth d>0d > 0.

Proof. uu is an increasing linear function of sxs_x, and x0≤i+1/2≤x1x_0 \le i + 1/2 \le x_1, so u0≤uP≤u1u_0 \le u_P \le u_1 with uP=u(i+1/2)u_P = u(i + 1/2). For the first normal, (1,0,u0)⋅P=duP−du0=d(uP−u0)≥0(1, 0, u_0) \cdot P = d u_P - d u_0 = d (u_P - u_0) \ge 0. For the second, (−1,0,−u1)⋅P=d(u1−uP)≥0(-1, 0, -u_1) \cdot P = d (u_1 - u_P) \ge 0. The two planes in yy are the same with vv. Dividing by a positive length keeps the signs. □\square

Theorem 1 (no miss). If a light reaches the position PP of a pixel of a tile, then the light is in the list of that tile.

Proof. Let δ=∥P−c∥<r\delta = \lVert P - c \rVert < r. For each unit normal mm of the tile, Lemma 1 and the Cauchy-Schwarz inequality give

m⋅c=m⋅P+m⋅(c−P)≥0−∥m∥∥c−P∥=−δ>−r,m \cdot c = m \cdot P + m \cdot (c - P) \ge 0 - \lVert m \rVert \lVert c - P \rVert = -\delta > -r,

so no plane rejects the light. For the depth test, the depth of the pixel is d=−Pzd = -P_z with dmin⁡≤d≤dmax⁡d_{\min} \le d \le d_{\max}, and ∣(−cz)−d∣=∣Pz−cz∣≤δ<r|(-c_z) - d| = |P_z - c_z| \le \delta < r. So −cz+r>d≥dmin⁡-c_z + r > d \ge d_{\min} and −cz−r<d≤dmax⁡-c_z - r < d \le d_{\max}, and the depth test does not reject it either. Line L13 then keeps the light. □\square

Theorem 2 (the image is the brute-force image). Suppose that each tile list holds every light that reaches a pixel of the tile, and that its lights are visited in increasing index order. Then the tiled image equals the image of shading every pixel with every light in index order, value for value, also in floating point.

Proof. For a pixel, let JJ be the list of its tile. By the assumption, every light not in JJ does not reach the pixel, so SHADE returns exactly 0 for it. The brute-force sum visits the lights in index order and adds +0+0 for each light not in JJ; in IEEE 754 arithmetic x+0=xx + 0 = x for every xx that is not −0-0, and the partial sums start at +0+0 and stay ≥0\ge 0. So the brute-force sum performs the same nonzero additions in the same order as the tiled sum, and the two results are equal. □\square

Theorem 1 gives the assumption of Theorem 2 in exact arithmetic. In floating point, a rounded plane test could drop a light whose sphere touches the frustum within the rounding error. The slack on the radius is there for that case, and the tests check the assumption directly against the exact distance test at every pixel.

Theorem 3 (cost). With tt tiles, ll lights and pp pixels, building the lists costs O(p+tl)O(p + t l) and shading costs O(∑q∣J(q)∣)≤O(pl)O(\sum_q |J(q)|) \le O(p l).

Proof. The depth ranges read each pixel once. Each tile tests each light once at O(1)O(1) cost. Each pixel loops over its list once. □\square

What is not claimed. The test is conservative, not exact. It keeps lights that reach no pixel of the tile: lights near the corner of two planes, where the sphere is outside the frustum but not outside one plane, and lights that sit in a depth gap between the near and the far pixels of a tile. The number of such false positives depends on the scene and is measured, not proved. The radius of a light is a property of the light model: a light whose real falloff never reaches 0 is cut at a radius, and the error of that cut is tuning.

Complexity

The model is the real RAM, with pp pixels, ll lights, tt tiles and an average of kk kept lights per pixel. The depth ranges cost O(p)O(p), the culling O(tl)O(t l) sphere tests, and the shading O(pk)O(p k) light evaluations. In the worst case every light reaches every tile, and the cost is the O(pl)O(p l) of brute force. The lists take O(tl)O(t l) space in the worst case; GPUs reserve a fixed maximum per tile. At 1920 by 1080 pixels with 16-pixel tiles, t=120⋅68=8160t = 120 \cdot 68 = 8160, so 1000 lights cost about 8.2 million sphere tests per frame.

On a GPU, the gain is also in memory traffic. Each pixel reads its G-buffer record once instead of once per light volume, and all pixels of a tile read the same list, which is good for the SIMT model: the threads of a warp run the same loop with the same lights, and their branches agree.

Properties

  • Conservative. No light that reaches a pixel is dropped. False positives cost time, not correctness.
  • Sensitive to depth range. A tile that holds a near object and a far background gets every light between them.
  • Brute force per tile. Each tile tests every light. With very many lights, the O(tl)O(t l) term dominates, and a hierarchy over the lights helps.
  • Screen-space only. The lists depend on the view and are built again each frame.
  • Shared lists. The pixels of a tile run the same light loop, so the work is coherent on SIMT hardware.

Variants and improvements

  • Tiled deferred shading. The lists and the shading are built in one compute pass that reads the G-buffer.
  • Tiled forward shading. A depth pre-pass gives dmin⁡d_{\min} and dmax⁡d_{\max}. The forward pass reads the list of the tile of each fragment. It supports MSAA and transparent surfaces; for transparent fragments, the tile range must reach from the near plane to dmax⁡d_{\max}, since they lie in front of the opaque depth. Harada, McKee and Yang (2012) published a renderer of this kind.
  • 2.5D culling. The depth range of the tile is cut into a fixed number of bins, and a bit mask records which bins hold geometry. A light is kept only if its depth range meets an occupied bin. This removes most of the false positives of depth gaps.
  • Tighter tests. Test the sphere against the bounding box of the tile frustum, or the cone of the tile, to remove corner false positives.
  • Clusters. Cut the depth into slices as well, and build lists per cluster, see clustered shading.
  • Other light shapes. Spot lights use a cone test, and area lights a bounding volume of their range.

When to use it

Use tiled shading when a scene has tens to thousands of local lights with a limited range, and the depth inside a tile is mostly continuous, as in most indoor scenes and top-down views. Use the forward form when MSAA, transparency or many material types matter. Use clustered shading when tiles often hold a large depth range, for example in first-person views with foliage or long views, or when transparent surfaces need light lists at their own depth.

Pitfalls

  • No slack in the test. A plane test in floating point can drop a light that touches the frustum by a rounding error. Add a small slack to the radius.
  • Depth in the wrong space. The range must be in the same depth as the test. Convert a nonlinear depth buffer value to view depth before the min and max.
  • Background pixels. Exclude them from the depth range, or the far plane makes the range of every border tile huge.
  • List overflow. A fixed maximum per tile drops lights when it is full, which breaks the guarantee. Size the list for the worst case or fall back to all lights.
  • Transparent surfaces. In tiled forward shading, the opaque depth range does not cover them.
  • Lights with no range. A light with an infinite falloff cannot be culled. Give every local light a radius, and accept the cut as 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.

tiled_shading.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/tiled-shading/. The authors are listed in prov/TE6F11.jsonl.

"""Tiled light culling and shading, after Olsson and Assarsson (2011).

The screen is cut into square tiles. For each tile the method finds the
smallest and the largest view depth of its pixels, forms the four side planes
of the tile frustum through the eye, and keeps every point light whose sphere
of influence is not fully outside one of these planes or outside the depth
range. Each pixel then loops only over the lights of its tile.

Conventions: the camera is at the origin and looks along -z. The depth buffer
holds the linear view depth d = -z > 0, or math.inf for the background. Pixel
(i, j) has its center at (i + 1/2, j + 1/2), with j counted from the bottom.
A light reaches a point only if the distance is below its radius: the falloff
is exactly 0 from the radius on, so a culled light changes nothing.
"""

import math
from dataclasses import dataclass

Vec3 = tuple[float, float, float]


@dataclass(frozen=True)
class Camera:
    width: int
    height: int
    tan_half: float  # tan of half the vertical field of view

    def ndc_to_slope(self, sx: float, sy: float) -> tuple[float, float]:
        """Screen position in pixels to the slopes x / d and y / d of the ray."""
        aspect = self.width / self.height
        u = (2.0 * sx / self.width - 1.0) * aspect * self.tan_half
        v = (2.0 * sy / self.height - 1.0) * self.tan_half
        return u, v

    def position(self, i: int, j: int, d: float) -> Vec3:
        """View-space position of the center of pixel (i, j) at view depth d."""
        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]]:
    """Shade every pixel with every light, in the order of the light list."""
    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 side_planes(cam: Camera, x0: float, x1: float, y0: float, y1: float) -> list[Vec3]:
    """Unit inward normals of the four planes through the eye that bound the
    screen rectangle [x0, x1] x [y0, y1] (in pixels). Each plane is m . x = 0."""
    u0, v0 = cam.ndc_to_slope(x0, y0)
    u1, v1 = cam.ndc_to_slope(x1, y1)
    planes = []
    # x / d >= u0, with d = -z, is x + u0 z >= 0; the other three are alike.
    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_frustum(planes: list[Vec3], dmin: float, dmax: float, light: Light) -> bool:
    """Conservative test: False only if the sphere misses the tile frustum.
    The radius gets a small slack so that rounding cannot drop a light."""
    c, r = light.center, light.radius * (1.0 + 1e-9) + 1e-12
    for m in planes:  # @line L11
        if dot(m, c) < -r:
            return False
    dc = -c[2]  # @line L12
    if dc + r < dmin or dc - r > dmax:
        return False
    return True  # @line L13


def tile_depth_range(depth, x0: int, x1: int, y0: int, y1: int) -> tuple[float, float] | None:
    dmin, dmax = math.inf, -math.inf
    for j in range(y0, y1):
        for i in range(x0, x1):
            d = depth[j][i]
            if d != math.inf:
                dmin = min(dmin, d)
                dmax = max(dmax, d)
    if dmin == math.inf:
        return None
    return dmin, dmax


def build_light_lists(depth, cam: Camera, lights: list[Light], tile: int) -> dict[tuple[int, int], list[int]]:
    """The light list of every tile, in increasing light index."""
    lists = {}
    for ty in range((cam.height + tile - 1) // tile):  # @line L1
        for tx in range((cam.width + tile - 1) // tile):
            x0, y0 = tx * tile, ty * tile
            x1, y1 = min(x0 + tile, cam.width), min(y0 + tile, cam.height)
            rng = tile_depth_range(depth, x0, x1, y0, y1)  # @line L2
            chosen = []  # @line L4
            if rng is not None:
                planes = side_planes(cam, x0, x1, y0, y1)  # @line L3
                for idx, light in enumerate(lights):  # @line L5
                    if sphere_in_frustum(planes, rng[0], rng[1], light):  # @line L6
                        chosen.append(idx)
            lists[(tx, ty)] = chosen
    return lists


def tiled_shading(depth, normals, cam: Camera, lights: list[Light], tile: int = 16):
    """Shade with the tile light lists. Returns the image and the lists."""
    lists = build_light_lists(depth, cam, lights, tile)
    out = [[0.0] * cam.width for _ in range(cam.height)]
    for j in range(cam.height):  # @line L7
        for i in range(cam.width):
            d = depth[j][i]
            if d == math.inf:
                continue
            p = cam.position(i, j, d)  # @line L8
            c = 0.0
            for idx in lists[(i // tile, j // tile)]:  # @line L9
                c += shade(p, normals[j][i], lights[idx])
            out[j][i] = c  # @line L10
    return out, lists
test_tiled_shading.py 119 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/tiled-shading/. The authors are listed in prov/TE6F11.jsonl.

"""Tiled shading against brute-force shading of every light at every pixel."""

import math
import random

from tiled_shading import (
    Camera,
    Light,
    affects,
    brute_force,
    build_light_lists,
    shade,
    side_planes,
    tiled_shading,
)


def room(cam: Camera, box: bool = True):
    """Depth and normals of a room seen from the origin: a floor at y = -1,
    side walls at x = -4 and x = 4, a back wall at z = -12 with an open
    window, and a small box face at z = -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 box and -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:
                d, n = min(hits)
                depth[j][i] = d
                normals[j][i] = n
    return depth, normals


def random_lights(rng: random.Random, count: int) -> 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.5, 3.0),
            rng.uniform(0.5, 2.0),
        )
        for _ in range(count)
    ]


def test_no_light_is_missed() -> None:
    rng = random.Random(21)
    cam = Camera(48, 32, 1.0)
    depth, _ = room(cam)
    for tile in (4, 8, 16):
        lights = random_lights(rng, 40)
        lists = build_light_lists(depth, cam, lights, tile)
        for j in range(cam.height):
            for i in range(cam.width):
                if depth[j][i] == math.inf:
                    continue
                p = cam.position(i, j, depth[j][i])
                kept = set(lists[(i // tile, j // tile)])
                for idx, light in enumerate(lights):
                    if affects(p, light):
                        assert idx in kept


def test_equals_brute_force_exactly() -> None:
    rng = random.Random(22)
    cam = Camera(40, 24, 0.7)
    depth, normals = room(cam)
    lights = random_lights(rng, 30)
    ref = brute_force(depth, normals, cam, lights)
    out, _ = tiled_shading(depth, normals, cam, lights, tile=8)
    assert out == ref


def test_pixel_centers_are_inside_their_tile_frustum() -> None:
    cam = Camera(32, 32, 1.0)
    tile = 8
    for j in range(cam.height):
        for i in range(cam.width):
            x0, y0 = (i // tile) * tile, (j // tile) * tile
            planes = side_planes(cam, x0, x0 + tile, y0, y0 + tile)
            p = cam.position(i, j, 5.0)
            assert all(m[0] * p[0] + m[1] * p[1] + m[2] * p[2] >= -1e-12 for m in planes)


def test_light_outside_the_view_is_culled_everywhere() -> None:
    cam = Camera(32, 32, 1.0)
    depth, _ = room(cam)
    behind = Light((0.0, 0.0, 5.0), 2.0, 1.0)
    lists = build_light_lists(depth, cam, [behind], 8)
    assert all(not v for v in lists.values())


def test_depth_gap_gives_false_positives() -> None:
    """A tile that holds the box (d = 3) and the back wall (d = 12) keeps a
    small light at d = 7 in front of the wall, although it reaches no pixel."""
    cam = Camera(32, 32, 1.0)
    depth, normals = room(cam)
    light = Light((-0.3, -0.2, -7.0), 0.5, 1.0)
    lists = build_light_lists(depth, cam, [light], 16)
    holders = [t for t, v in lists.items() if v]
    assert holders
    for j in range(cam.height):
        for i in range(cam.width):
            if depth[j][i] != math.inf:
                p = cam.position(i, j, depth[j][i])
                assert shade(p, normals[j][i], light) == 0.0

History

Light volumes in deferred shading draw one bounding shape per light and blend the results, which reads the G-buffer once per light. Tiles replace this with one pass that reads the G-buffer once per pixel, which became practical with compute shaders and shared memory on GPUs. Olsson and Assarsson (2011) described tiled deferred and tiled forward shading in a journal paper and studied their cost. Harada, McKee and Yang (2012) showed a forward renderer with a depth pre-pass and per-tile light culling, and argued that it keeps the material freedom of forward shading. Olsson, Billeter and Assarsson (2012) then added depth slices and built clustered shading, noting that the tiled methods test every light against every tile.

References

  1. Ola Olsson and Ulf Assarsson, Tiled shading, Journal of Graphics, GPU, and Game Tools 15(4), 235-251, 2011, the tile grid, the per-tile depth range and light lists, and tiled deferred and tiled forward shading
  2. Takahiro Harada, Jay McKee and Jason C. Yang, Forward+: bringing deferred lighting to the next level, Eurographics 2012 Short Papers, 5-8, the depth pre-pass, the light culling per tile in a compute shader, and the forward shading pass that reads the tile lists
  3. Ola Olsson, Markus Billeter and Ulf Assarsson, Clustered deferred and forward shading, High-Performance Graphics 2012, 87-96, Section 3.3 (light assignment), which notes that tiled methods test all lights per tile by brute force
  4. 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 tiled shading)

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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.culling
  • a full proof of time.shading
  • a full proof of time.worst
  • a full proof of space.lists
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example