Algorithm Search⌘K

Algorithmcore

Cascaded shadow maps

Also called CSM, parallel-split shadow maps.

Split the view frustum into depth ranges and render one shadow map per range, so that shadow resolution follows the distance to the eye.

Time
Θ(m N^2 + m t + P + q) worst
Space
Θ(m N^2) extra
Where
N = the map side in texels; P = the number of covered texel centers, summed over all triangles and cascades; m = the number of cascades; q = the number of shadow lookups; t = the number of triangles
Properties
not adaptivecomparison baseddeterministicnot in placeofflineiterativenot stable
Origin
Wolfgang Engel, Fan Zhang, Hanqiu Sun, Leilei Xu, Lee Kit Lun, 2006

Cascaded shadow maps cut the view frustum of the camera into mm slices by depth and give each slice its own shadow map, cropped to the slice as seen from the light. A pixel uses the map of its slice. Near slices are small, so their texels are small, and the shadow resolution falls with the distance from the camera, as the pixel size of the camera grows. The test per pixel is the test of plain shadow mapping; only the choice of map and the crop are new. This is a level of detail scheme for shadows, close to the texture clipmap, which also keeps finer data near the viewer.

In plain words

One shadow map for a whole landscape has the same dots everywhere. Near the camera, one dot of the map covers many screen pixels, and the shadow edges look like steps. Far away, many dots fall on one pixel and are wasted.

So cut the space in front of the camera into a few slabs: a thin one near the camera, then thicker ones. Make one shadow map for each slab, and fit it tightly around that slab as the sun sees it. The near map covers a small area, so its dots are small. The far map covers a large area with large dots, where the camera cannot see the difference.

When you draw a point, find out which slab it is in, and look in that map.

The problem

The camera has the near plane at view depth nn and the far plane at ff, and it looks along −z-z of its frame, with yy up in the world. The light is directional, with an orthonormal frame RR; a point pp has the light coordinates q=Rpq = R p, and −qz-q_z is its light depth, larger farther from the light. The input is the scene, the camera, the light, the number of cascades mm, a blend λ∈[0,1]\lambda \in [0, 1] and a map size of N×NN \times N texels. The output is, for each visible point, the shadow mapping answer from a map whose texels are small where the camera is close. Each map is a z-buffer of the scene from the light, cropped to the light (x,y)(x, y) rectangle of one slice of the view frustum, and it stores linear light depth.

The algorithm

  1. CSM-RENDER(camera, R, scene, n, f, m, λ, N)
  2. 1C_i ← λ n (f/n)^(i/m) + (1 - λ)(n + (f - n) i/m) for i = 0, ..., m ▷ the split depths
  3. 2for i ← 0 to m - 1 do
  4. 3Q ← the 8 corners of the view slice between depths C_i and C_(i+1), mapped by R
  5. 4lo_i, hi_i ← the least and the greatest light (x, y) over Q; texel_i ← (hi_i - lo_i) / N
  6. 5S_i ← the light depth map of the scene over the rectangle [lo_i, hi_i], at N x N texel centers
  7. CSM-SHADOWED(p, bias)
  8. 6i ← the cascade with C_i ≤ depth(p) < C_(i+1) ▷ none: p is lit
  9. 7q ← R p; (a, b) ← (⌊(q_x - lo_x) / texel_x⌋, ⌊(q_y - lo_y) / texel_y⌋) ▷ outside the map: lit
  10. 8return S_i[a, b] < -q_z - bias ▷ the test of shadow mapping

Line L1 is the split scheme of Zhang and coauthors. With λ=1\lambda = 1 the split is logarithmic: every slice has the same ratio Ci+1/CiC_{i+1}/C_i. With λ=0\lambda = 0 it is uniform. The value λ=0.5\lambda = 0.5 of GPU Gems 3 is a tuning. Lines L3 and L4 are the crop: the slice is a convex box with 8 corners, so the rectangle of its corners in the light plane holds the light (x,y)(x, y) of every point of the slice. Line L5 must still draw all shadow casters between the light and the slice, also those outside the view frustum, so its depth range extends toward the light; only xx and yy are cropped.

A renderer often uses a stable fit in place of lines L3 and L4. It fits a square around a sphere that holds the slice, rounds the radius up to a multiple of a quantum, and snaps the lower corner to whole texels. The texels then keep their size and their grid in the world when the camera turns or moves, and shadow edges do not crawl. The quantum, 1/641/64 in the code, is a tuning.

Example

Take n=1n = 1, f=100f = 100 and m=4m = 4.

scheme C0C_0 C1C_1 C2C_2 C3C_3 C4C_4
logarithmic, λ=1\lambda = 1 1 3.162 10 31.62 100
practical, λ=0.5\lambda = 0.5 1 14.456 30.25 53.436 100
uniform, λ=0\lambda = 0 1 25.75 50.5 75.25 100

The logarithmic split makes the first slice very thin, and the uniform split puts most of the resolution far away; the blend lies between them, slice by slice.

Now a camera at (0,3,0)(0, 3, 0) looks along (0,−0.3,−1)(0, -0.3, -1) with a vertical field of view of 60°60° and the aspect ratio 1, with n=0.5n = 0.5 and f=40f = 40. The light comes from the direction (0.3,−1,0.2)(0.3, -1, 0.2), and each map has 64×6464 \times 64 texels. The splits for λ=0.5\lambda = 0.5 are 0.5, 5.935, 12.361, 21.75 and 40. The texel sizes in world units are:

map texel xx texel yy stable fit
cascade 0 0.132 0.0938 0.1766
cascade 1 0.275 0.1267 0.3363
cascade 2 0.4839 0.196 0.5833
cascade 3 0.8899 0.3742 1.0769
one map for all of [0.5,40][0.5, 40] 0.8899 0.6724

The first cascade has texels 6.7 times smaller in xx and 7.2 times smaller in yy than one map of the same size for the whole frustum. The stable fit costs a factor of 1.21 to 1.34 in texel size here, and it removes the crawl of the edges.

Correctness

The proof file shows four claims, and the tests check them.

  • The splits. C0=nC_0 = n, Cm=fC_m = f, and the CiC_i increase strictly, so each view depth in [n,f)[n, f) has exactly one cascade in line L6. The test checks this and that the practical split lies between the logarithmic and the uniform split.
  • Why logarithmic. In a model in which the texel size of a slice is proportional to its length and the pixel footprint to the depth, the logarithmic split gives the smallest largest ratio of the two. This is a model, not a theorem on scenes.
  • Containment. Every point of slice ii maps into the rectangle of map ii, for the tight fit and for the stable fit. The test samples points of each slice.
  • The lookup. Lines L6 to L8 are the test of shadow mapping against one map, so its correctness result applies: at a texel center with bias 0 the answer is exact, and away from shadow edges by more than half a texel diagonal it is exact as well. The test compares the lookup with ray casting against the spheres of a scene at such points.

The proof file also shows that the stable fit keeps the texel size and the texel grid fixed when the camera moves.

Proof: The practical split scheme is monotone, each cascade map contains its view slice, the lookup is the shadow map test of one map, and the stable fit keeps a fixed texel gridfull

We use the notation of the page. The camera has its near plane at view depth n>0n > 0 and its far plane at f>nf > n; here nn and ff are planes, not counts. There are mm cascades. The light is directional, with the orthonormal frame RR whose rows are lx,ly,lzl_x, l_y, l_z; a point pp has the light coordinates q=Rpq = R p, and −qz-q_z is its light depth. The arithmetic is exact real arithmetic, except where a claim says floating point.

The splits

Line L1 computes Ci=λ n(f/n)i/m+(1−λ)(n+(f−n) i/m)C_i = \lambda\, n (f/n)^{i/m} + (1 - \lambda)(n + (f - n)\, i / m) for i=0,…,mi = 0, \ldots, m and a blend λ∈[0,1]\lambda \in [0, 1].

Lemma 1. C0=nC_0 = n, Cm=fC_m = f, and C0<C1<⋯<CmC_0 < C_1 < \cdots < C_m. So the slices [Ci,Ci+1)[C_i, C_{i+1}) partition [n,f)[n, f), and each view depth in [n,f)[n, f) has exactly one cascade (line L6).

Proof. At i=0i = 0 both terms equal nn, and at i=mi = m both equal ff, so the convex combination does too. For f>nf > n, both n(f/n)i/mn (f/n)^{i/m} and n+(f−n)i/mn + (f - n) i / m increase strictly in ii, and a convex combination of two strictly increasing sequences increases strictly. □\square

With λ=1\lambda = 1 the ratio Ci+1/Ci=(f/n)1/mC_{i+1} / C_i = (f/n)^{1/m} is the same for all slices (the logarithmic split). With λ=0\lambda = 0 the differences Ci+1−Ci=(f−n)/mC_{i+1} - C_i = (f - n)/m are equal (the uniform split). The blend λ\lambda is a tuning; GPU Gems 3, chapter 10, suggests 0.5.

Lemma 2 (why the logarithmic split). Take the model in which the shadow texel size in cascade ii is proportional to the slice length Ci+1−CiC_{i+1} - C_i and the pixel footprint at depth dd is proportional to dd. Then the largest ratio of texel size to pixel footprint at the near end of a slice, max⁡i(Ci+1−Ci)/Ci\max_i (C_{i+1} - C_i)/C_i, over all splits with C0=nC_0 = n and Cm=fC_m = f, is smallest for the logarithmic split.

Proof. Let ri=Ci+1/Cir_i = C_{i+1} / C_i. The product of the rir_i is f/nf / n, so the largest rir_i is at least the geometric mean (f/n)1/m(f/n)^{1/m}, with equality only when all rir_i are equal. The quantity is max⁡iri−1\max_i r_i - 1. □\square

This is a model, not a property of real scenes: a tight crop also depends on the width of the slice and on the light direction. Zhang, Sun and Nyman (GPU Gems 3, chapter 10) give the logarithmic split as the split that distributes the perspective aliasing evenly; the lemma is a simple form of that argument. The uniform part of the blend is there because the pure logarithmic split makes the first slices very thin when nn is small.

Containment

The slice SiS_i is the set of points with view depth in [Ci,Ci+1][C_i, C_{i+1}] whose image lies on the screen. In the camera frame it is {(ad ts,bd t,d):d∈[Ci,Ci+1],(a,b)∈[−1,1]2}\{(a d\, t s, b d\, t, d) : d \in [C_i, C_{i+1}], (a, b) \in [-1, 1]^2\}, written as right, up and forward components, where t=tan⁡(θ/2)t = \tan(\theta/2) for the vertical field of view θ\theta and ss is the aspect ratio.

Lemma 3. SiS_i is a convex polytope with the 8 corners that slice_corners returns. The rectangle that lines L3 and L4 compute from the corners holds the light (x,y)(x, y) of every point of SiS_i. The stable fit holds them too.

Proof. SiS_i is the intersection of six half-spaces: the two depth planes and the four planes ∣r∣≤ts d|r| \le t s\, d, ∣u∣≤t d|u| \le t\, d through the camera center. So it is convex, and it is bounded, so it is the convex hull of its vertices. Its vertices are the points with d∈{Ci,Ci+1}d \in \{C_i, C_{i+1}\} and a,b∈{−1,1}a, b \in \{-1, 1\}. The map p↦(qx,qy)p \mapsto (q_x, q_y) is linear, so the image of SiS_i is the convex hull of the images of the corners, and it lies in the box of their least and greatest coordinates.

For the stable fit, every corner lies within the radius rr of the corner mean cc, so SiS_i, the hull of the corners, lies in the ball of radius rr around cc, and its light (x,y)(x, y) lies in the square of side 2r2r around the light (x,y)(x, y) of cc, since RR is orthonormal. The fit takes lo≤q(c)−r\mathrm{lo} \le q(c) - r per axis, with the texel τ=2r/(N−1)\tau = 2r/(N - 1) for a map of NN texels. The map covers up to lo+Nτ>(q(c)−r−τ)+2r+τ=q(c)+r\mathrm{lo} + N \tau > (q(c) - r - \tau) + 2r + \tau = q(c) + r. □\square

The lookup

Theorem 4. Let pp be a visible point with view depth d∈[n,f)d \in [n, f). Lines L6 to L8 return the binary shadow map test of pp against the map of the unique cascade ii with Ci≤d<Ci+1C_i \le d < C_{i+1}, at the texel that holds the light (x,y)(x, y) of pp. If pp is at a texel center of that map and the bias is 0, the result is shadowed exactly when a sphere of the scene meets the ray from pp toward the light strictly nearer to the light.

Proof. By Lemma 1 there is exactly one such ii. By Lemma 3 the light (x,y)(x, y) of pp lies in the rectangle of map ii, so the lookup does not fall outside the map (a point on the upper edge of the rectangle is the one exception, and the code calls it lit). Line L5 rendered map ii as the nearest light depth of the spheres at each texel center, and line L8 compares the light depth of pp with it. This is the test of shadow mapping, and its exactness at texel centers is the correctness result of that page: the stored value is the least light depth of the spheres along the light ray through the center, and the ray from pp toward the light is that ray when pp projects to the center. □\square

Away from texel centers the test is exact when pp is farther than half a texel diagonal from every shadow edge, measured in the light (x,y)(x, y) plane; the test of the code checks the lookup against ray casting at such points.

The stable fit

Proposition 5. In the stable fit, (a) the texel size of each cascade does not change when the camera moves or turns, and (b) the texel centers lie on the fixed grid {((k+12)τ,(k′+12)τ)}\{((k + \tfrac12) \tau, (k' + \tfrac12) \tau)\} of the light plane in every frame. So a static occluder gives the same map values at the same light positions in every frame, and its shadow edge does not move from frame to frame.

Proof. (a) The corners of SiS_i in the camera frame depend only on CiC_i, Ci+1C_{i+1}, tt and ss. A motion of the camera is a rotation and a translation, which keep the distances from the corners to their mean. So rr is the same in every frame, and so is the rounded radius and τ=2r/(N−1)\tau = 2r/(N - 1). (b) The fit sets each coordinate of lo to ⌊(q−r)/τ⌋ τ\lfloor (q - r)/\tau \rfloor\, \tau, a whole multiple of τ\tau, so the centers lo+(k+12)τ\mathrm{lo} + (k + \tfrac12)\tau lie on the stated grid. □\square

In floating point the radius can change in its last bits when the camera turns. The rounding up of rr to a multiple of a quantum makes these changes disappear unless the radius is within one rounding error of a multiple of the quantum. The quantum 1/641/64 is a tuning. The cost of the stable fit is that the square of side 2r2r is larger than the tight rectangle, so the texels are larger (by a factor of 1.21 to 1.34 in the example of the page).

Complexity

Each cascade is a depth pass over the scene: Θ(N2)\Theta(N^2) to clear, Θ(t)\Theta(t) for the triangles and the covered texel centers, so the mm passes cost Θ(mN2+mt+P)\Theta(m N^2 + m t + P), with frustum culling per cascade to reduce tt. A lookup costs O(m)O(m) to find the cascade by a scan, or O(1)O(1) with a compare against the split depths in a vector, plus the cost of the filter. The total is Θ(mN2+mt+P+q)\Theta(m N^2 + m t + P + q) in the worst case, and the maps take Θ(mN2)\Theta(m N^2) space, often as the layers of one texture array.

Properties

  • Resolution follows the depth. The texel size grows with the slice, as the pixel size of the camera grows with the depth (a measured effect in the example, and a model argument in the proof file).
  • Perspective aliasing reduced, projective aliasing not. The slices fix the mismatch caused by the camera's perspective. Surfaces almost parallel to the light still get stretched texels.
  • Seams. At a split depth, the texel size jumps, and a filtered shadow edge can change its look.
  • Cost grows with mm. Each cascade draws the scene again from the light, and the casters near the light are drawn into several maps.

Variants and improvements

  • Stable fit. Fit to a bounding sphere, round the radius and snap to texels, as described above, at the cost of larger texels.
  • Tighter crops. Fit each map to the visible receivers in the slice, found from the depth buffer of the camera, in place of the whole slice (sample distribution shadow maps).
  • Blending at the splits. Look in two maps near a split and blend the answers, to hide the seam.
  • Filtering per cascade. Use PCF, variance shadow maps or moment shadow mapping per map, with a filter width scaled by the texel size of the cascade.
  • Warped maps. Perspective and light space perspective shadow maps warp one map in place of several; they can be combined with slices.

When to use it

Use cascaded shadow maps for a directional light, such as the sun, over a large scene with a view that reaches far: outdoor games, flight and driving views, terrain. For a small scene or a spot light, one map is usually enough. For very large views, combine them with a coarse map for the distance, or with baked shadows.

Pitfalls

  • Radial distance in place of depth. If line L6 picks the cascade by the distance ∣p−eye∣|p - \text{eye}|, a point near the edge of the screen in slice ii can get cascade i+1i + 1, whose map does not hold it, and the point is called lit.
  • Cropping the light depth. If line L5 also clips the light depth to the slice, casters outside the view frustum (a tall building behind the camera) cast no shadow into it.
  • One bias for all cascades. The bias of line L8 must grow with the texel size of the cascade; a bias set for cascade 0 gives acne in cascade 3, and a bias set for cascade 3 gives peter panning near the camera.
  • Tight fit with a moving camera. Lines L3 and L4 change the size and the position of the texels in every frame, so the shadow edges shimmer when the camera turns. Use the stable fit.
  • Too thin a first slice. With λ\lambda near 1 in line L1 and a small nn, the first slice is very thin, and most pixels near the camera fall in the second one.

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.

cascaded_shadow_maps.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/cascaded-shadow-maps/. The authors are listed in prov/SFEHPC.jsonl.

"""Cascaded shadow maps for a directional light.

The world is right handed with y up. The camera looks along the negative z
axis of its frame; a point's view depth d is its distance along the view
direction. The near plane is at d = n and the far plane at d = f. The light
frame has rows (lx, ly, lz); the light travels along -lz, so a point p has
light coordinates q = R p and light depth -q_z, larger is farther from the
light. Each cascade map stores the linear light depth of the nearest
occluder at each texel center. The scene for the shadow maps is a list of
spheres (center, radius), which keeps the depth render exact and small.
"""

from math import ceil, floor, sqrt, tan


def add(a, b):
    return tuple(x + y for x, y in zip(a, b))


def sub(a, b):
    return tuple(x - y for x, y in zip(a, b))


def scale(a, s):
    return tuple(x * s for x in a)


def dot(a, b):
    return sum(x * y for x, y in zip(a, b))


def cross(a, b):
    return (a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0])


def normalize(a):
    return scale(a, 1.0 / sqrt(dot(a, a)))


def splits(n, f, m, lam):
    """The practical split scheme: a blend of the logarithmic and the uniform split."""
    return [lam * n * (f / n) ** (i / m) + (1 - lam) * (n + (f - n) * i / m)  # @line L1
            for i in range(m + 1)]


class Camera:
    def __init__(self, pos, forward, fov_y, aspect):
        self.pos = pos
        self.fwd = normalize(forward)
        self.right = normalize(cross(self.fwd, (0.0, 1.0, 0.0)))
        self.up = cross(self.right, self.fwd)
        self.t = tan(fov_y / 2)
        self.aspect = aspect

    def depth(self, p):
        return dot(sub(p, self.pos), self.fwd)

    def slice_corners(self, d0, d1):
        out = []
        for d in (d0, d1):
            c = add(self.pos, scale(self.fwd, d))
            for sx in (-1, 1):
                for sy in (-1, 1):
                    out.append(add(c, add(scale(self.right, sx * d * self.t * self.aspect),
                                          scale(self.up, sy * d * self.t))))
        return out

    def point(self, d, a, b):
        """The point at view depth d and normalized screen position (a, b) in [-1, 1]^2."""
        c = add(self.pos, scale(self.fwd, d))
        return add(c, add(scale(self.right, a * d * self.t * self.aspect), scale(self.up, b * d * self.t)))


def light_frame(direction):
    """Rows (lx, ly, lz) of the light frame for a light that travels along direction."""
    lz = normalize(scale(direction, -1.0))
    hint = (0.0, 0.0, 1.0) if abs(lz[2]) < 0.9 else (1.0, 0.0, 0.0)
    lx = normalize(cross(hint, lz))
    ly = cross(lz, lx)
    return (lx, ly, lz)


def to_light(rows, p):
    return tuple(dot(r, p) for r in rows)


def fit_tight(cam, rows, d0, d1, size):
    """The crop of one cascade: the light-space bounds of the slice corners."""
    q = [to_light(rows, p) for p in cam.slice_corners(d0, d1)]  # @line L3
    lo = (min(v[0] for v in q), min(v[1] for v in q))  # @line L4
    hi = (max(v[0] for v in q), max(v[1] for v in q))
    return lo, ((hi[0] - lo[0]) / size, (hi[1] - lo[1]) / size)


def fit_stable(cam, rows, d0, d1, size, quantum=1.0 / 64):
    """A crop that does not change size when the camera turns and whose texel
    grid stays fixed in the world when the camera moves: a bounding sphere of
    the slice, with the radius rounded up and the origin snapped to texels."""
    pts = cam.slice_corners(d0, d1)
    c = scale(pts[0], 0.0)
    for p in pts:
        c = add(c, scale(p, 1.0 / len(pts)))
    r = max(sqrt(dot(sub(p, c), sub(p, c))) for p in pts)
    r = ceil(r / quantum) * quantum
    texel = 2 * r / (size - 1)
    q = to_light(rows, c)
    lo = (floor((q[0] - r) / texel) * texel, floor((q[1] - r) / texel) * texel)
    return lo, (texel, texel)


def render(spheres, rows, lo, texel, size):
    """The depth map of the spheres: the light depth of the nearest surface at
    each texel center, or infinity where no sphere covers the center."""
    lsph = [(to_light(rows, c), r) for c, r in spheres]
    out = []
    for j in range(size):
        y = lo[1] + (j + 0.5) * texel[1]
        row = []
        for i in range(size):
            x = lo[0] + (i + 0.5) * texel[0]
            best = float("inf")
            for c, r in lsph:
                e = r * r - (x - c[0]) ** 2 - (y - c[1]) ** 2
                if e >= 0:
                    best = min(best, -c[2] - sqrt(e))
            row.append(best)
        out.append(row)
    return out


class Cascades:
    def __init__(self, cam, light_dir, spheres, n, f, m, lam, size, stable=False):
        self.cam = cam
        self.rows = light_frame(light_dir)
        self.c = splits(n, f, m, lam)
        self.size = size
        self.maps = []
        for i in range(m):  # @line L2
            fit = fit_stable if stable else fit_tight
            lo, texel = fit(cam, self.rows, self.c[i], self.c[i + 1], size)
            s = render(spheres, self.rows, lo, texel, size)  # @line L5
            self.maps.append((lo, texel, s))

    def cascade_of(self, d):
        for i in range(len(self.c) - 1):  # @line L6
            if self.c[i] <= d < self.c[i + 1]:
                return i
        return None

    def shadowed(self, p, bias=1e-6):
        i = self.cascade_of(self.cam.depth(p))
        if i is None:
            return False
        lo, texel, s = self.maps[i]
        q = to_light(self.rows, p)  # @line L7
        a, b = floor((q[0] - lo[0]) / texel[0]), floor((q[1] - lo[1]) / texel[1])
        if not (0 <= a < self.size and 0 <= b < self.size):
            return False
        return s[b][a] < -q[2] - bias  # @line L8


def exact_shadowed(p, spheres, rows):
    """Does the ray from p toward the light meet a sphere?"""
    q = to_light(rows, p)
    for c, r in spheres:
        lc = to_light(rows, c)
        e = r * r - (q[0] - lc[0]) ** 2 - (q[1] - lc[1]) ** 2
        if e >= 0 and -lc[2] - sqrt(e) < -q[2]:
            return True
    return False
test_cascaded_shadow_maps.py 132 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/cascaded-shadow-maps/. The authors are listed in prov/SFEHPC.jsonl.

import random
from math import pi, sqrt

from cascaded_shadow_maps import (
    Camera,
    Cascades,
    dot,
    exact_shadowed,
    fit_stable,
    fit_tight,
    light_frame,
    splits,
    to_light,
)

LIGHT = (0.3, -1.0, 0.2)


def scene(rng, k=10):
    out = []
    for _ in range(k):
        r = rng.uniform(0.3, 1.2)
        z = rng.uniform(-30, -3)
        out.append(((rng.uniform(-0.4, 0.4) * -z, r + rng.uniform(0.2, 1.0), z), r))
    return out


def test_split_scheme():
    c = splits(1.0, 100.0, 4, 0.5)
    want = [1.0, 14.456, 30.25, 53.436, 100.0]
    assert all(abs(a - b) < 1e-3 for a, b in zip(c, want))
    log = splits(1.0, 100.0, 4, 1.0)
    assert all(abs(log[i + 1] / log[i] - 100 ** 0.25) < 1e-12 for i in range(4))
    uni = splits(1.0, 100.0, 4, 0.0)
    assert all(abs(uni[i + 1] - uni[i] - 24.75) < 1e-12 for i in range(4))
    rng = random.Random(1)
    for _ in range(200):
        n = rng.uniform(0.05, 2.0)
        f = n * rng.uniform(2.0, 2000.0)
        m = rng.randrange(1, 9)
        lam = rng.uniform(0.0, 1.0)
        c = splits(n, f, m, lam)
        assert abs(c[0] - n) < 1e-12 * f and abs(c[-1] - f) < 1e-9 * f
        assert all(a < b for a, b in zip(c, c[1:]))
        # The practical split lies between the uniform and the logarithmic one.
        lo, hi = splits(n, f, m, 1.0), splits(n, f, m, 0.0)
        assert all(a - 1e-9 <= x <= b + 1e-9 for a, x, b in zip(lo, c, hi))


def test_every_point_of_a_slice_is_inside_its_cascade():
    rng = random.Random(2)
    rows = light_frame(LIGHT)
    for _ in range(20):
        cam = Camera((rng.uniform(-3, 3), rng.uniform(1, 4), 0.0),
                     (rng.uniform(-1, 1), rng.uniform(-0.5, 0.1), -1.0), pi / 3, rng.uniform(1.0, 2.0))
        c = splits(0.5, 40.0, 4, rng.uniform(0, 1))
        for i in range(4):
            for fit in (fit_tight, fit_stable):
                lo, texel = fit(cam, rows, c[i], c[i + 1], 32)
                for _ in range(30):
                    p = cam.point(rng.uniform(c[i], c[i + 1]), rng.uniform(-1, 1), rng.uniform(-1, 1))
                    q = to_light(rows, p)
                    for k in (0, 1):
                        assert lo[k] - 1e-9 <= q[k] <= lo[k] + 32 * texel[k] + 1e-9


def test_lookup_agrees_with_ray_casting_away_from_edges():
    rng = random.Random(3)
    spheres = scene(rng)
    cam = Camera((0.0, 3.0, 0.0), (0.0, -0.3, -1.0), pi / 3, 1.0)
    rows = light_frame(LIGHT)
    for stable in (False, True):
        csm = Cascades(cam, LIGHT, spheres, 0.5, 40.0, 4, 0.5, 64, stable)
        tested = shadowed = 0
        for k in range(3000):
            if k % 2:
                p = (rng.uniform(-12, 12), 0.0, rng.uniform(-40, -1))
            else:
                (cx, cy, cz), r = spheres[k // 2 % len(spheres)]
                p = (cx + 0.3 * cy + rng.uniform(-2 * r, 2 * r), 0.0, cz + 0.2 * cy + rng.uniform(-2 * r, 2 * r))
            d = cam.depth(p)
            i = csm.cascade_of(d)
            v = tuple(a - b for a, b in zip(p, cam.pos))
            if i is None or abs(dot(v, cam.right)) > d * cam.t * cam.aspect or abs(dot(v, cam.up)) > d * cam.t:
                continue
            lo, texel, _ = csm.maps[i]
            q = to_light(rows, p)
            half_diag = 0.5 * sqrt(texel[0] ** 2 + texel[1] ** 2)
            margin = min(abs(sqrt((q[0] - lc[0]) ** 2 + (q[1] - lc[1]) ** 2) - r)
                         for lc, r in ((to_light(rows, c), r) for c, r in spheres))
            if margin <= half_diag:
                continue
            want = exact_shadowed(p, spheres, rows)
            assert csm.shadowed(p) == want
            tested += 1
            shadowed += want
        assert tested > 500 and shadowed > 20


def test_cascade_choice_follows_the_splits():
    cam = Camera((0.0, 3.0, 0.0), (0.0, -0.3, -1.0), pi / 3, 1.0)
    csm = Cascades(cam, LIGHT, [], 0.5, 40.0, 4, 0.5, 4)
    for d in (0.5, 1.0, 2.0, 5.0, 10.0, 20.0, 39.9):
        i = csm.cascade_of(d)
        assert csm.c[i] <= d < csm.c[i + 1]
    assert csm.cascade_of(0.4) is None and csm.cascade_of(40.0) is None


def test_near_cascades_have_smaller_texels():
    cam = Camera((0.0, 3.0, 0.0), (0.0, -0.3, -1.0), pi / 3, 1.0)
    csm = Cascades(cam, LIGHT, [], 0.5, 40.0, 4, 0.5, 4)
    sizes = [max(t) for _, t, _ in csm.maps]
    assert all(a < b for a, b in zip(sizes, sizes[1:]))


def test_stable_fit_keeps_size_and_texel_grid():
    rows = light_frame(LIGHT)
    rng = random.Random(4)
    base = None
    for _ in range(40):
        cam = Camera((rng.uniform(-5, 5), rng.uniform(1, 4), rng.uniform(-5, 5)),
                     (rng.uniform(-1, 1), rng.uniform(-0.5, 0.1), rng.uniform(-1, 1)), pi / 3, 1.5)
        lo, texel = fit_stable(cam, rows, 2.0, 8.0, 32)
        if base is None:
            base = texel
        assert texel == base
        for k in (0, 1):
            t = lo[k] / texel[k]
            assert abs(t - round(t)) < 1e-9

History

Engel described cascaded shadow maps in ShaderX5 in 2006, as a set of maps for slices of the view frustum. In the same year Zhang, Sun, Xu and Lun published their method with the split scheme that blends a logarithmic and a uniform split, and Zhang, Sun and Nyman described its GPU form in GPU Gems 3 in 2007. Later work added the stable fit, cascades fit to the visible samples, and the blend between cascades. The method became the standard way to draw sun shadows in games.

References

  1. Wolfgang Engel (editor), ShaderX5, Advanced Rendering Techniques, Charles River Media, 2006, Wolfgang Engel, Cascaded Shadow Maps, 197 to 206, the whole chapter (the slices of the view frustum, one map per slice, and the choice of the map per pixel)
  2. Fan Zhang, Hanqiu Sun, Leilei Xu and Lee Kit Lun, Parallel-split shadow maps for large-scale virtual environments, Proceedings of the 2006 ACM International Conference on Virtual Reality Continuum and Its Applications (VRCIA 2006), 311 to 318, the practical split scheme (the blend of the logarithmic and the uniform split) and the fit of each map to its slice
  3. Hubert Nguyen (editor), GPU Gems 3, Addison-Wesley, 2007, Chapter 10, Fan Zhang, Hanqiu Sun and Oskari Nyman, Parallel-Split Shadow Maps on Programmable GPUs, the split scheme with lambda = 0.5, the logarithmic split as the split that distributes the perspective aliasing evenly, and the crop matrix of each slice
  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, Section 7.4 (the part on cascaded shadow maps)

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.worst
  • a full proof of space.extra
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