Algorithmadvanced
Percentage-closer soft shadows
Also called PCSS.
Estimate the penumbra width from the average blocker depth found in the shadow map and use it as the kernel size of percentage-closer filtering.
- Solves
- Shadow determination
- Time
- Θ(q (m + k)) worst
- Space
- Θ(1) extra
- Where
- k = the number of texels in the filter region; m = the number of texels in the blocker search region; q = the number of shadow lookups
- Model
- Real RAM
- Properties
- adaptivecomparison baseddeterministicnot in placeofflineiterativenot stable
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Randima Fernando, 2005
Percentage-closer soft shadows add two steps before percentage-closer filtering: a search of the shadow map for blockers near the lookup point, and an estimate of the penumbra width from their average depth. The PCF kernel then has that width, so a shadow is sharp where the occluder touches the receiver and soft far from it. Plain PCF has one kernel width everywhere. The map is the ordinary map of shadow mapping, rendered from the center of an area light, so the method costs no extra pass but more lookups.
In plain words
A large lamp makes shadows with soft edges. The edge is narrow where the object is close to the floor, and wide where the object is high above it.
The method first looks in the shadow map around the point and finds the things that are nearer to the lamp than the point. It takes their average distance from the lamp. With that distance, the size of the lamp and the distance of the point, a rule of similar triangles gives the width of the soft edge.
Then it does the usual blur of yes or no answers, with a blur as wide as that edge. If it finds nothing in the way, the point is lit and no blur is needed.
The problem
The light is a square of side in the plane at depth 0 of the light frame. The shadow map is a perspective view from its center with the near plane at depth , and each texel is a square of side on the near plane. Unlike the PCF page, the map stores linear depth , the distance along the light axis, because the steps below do arithmetic on depths. A receiver point has the map position in texels and the depth . The output is an estimate of the fraction of the light that the point sees. The reference answer is the exact visible fraction of the area light, which is known in closed form for a blocker plane parallel to a receiver plane.
The algorithm
PCSS(S, x, y, d_r, w, n, h, bias)- 1
r_s ← w (d_r - n) / (2 d_r h) ▷ half-width of the search region, in texels - 2
B ← the depths S[i, j] < d_r - bias of the texels in the square of half-width r_s around (x, y) - 3
if B is empty then return 1 ▷ no blocker: the point is lit - 4
d_b ← the mean of B ▷ the average blocker depth - 5
w_p ← (d_r - d_b) w / d_b ▷ the penumbra width at the receiver - 6
r_f ← w_p n / (2 d_r h) ▷ the half-width of the filter on the map, in texels - 7
return the box PCF of half-width r_f around (x, y), with the depth d_r and the bias
Line L1 sets the search region. A blocker that hides some part of the light from the receiver lies in the pyramid from the receiver point to the light, and its depth is at least . The pyramid is widest on the map at depth , where it covers on the near plane; the proof file derives this. Fernando's paper uses a search size that is set by the light size; this bound is the size that misses no blocker.
Line L5 is similar triangles for a blocker edge at depth parallel to the receiver: the light of width at distance from the edge throws a penumbra of width at the receiver. Line L6 projects half of it onto the near plane (the factor ) and converts it to texels.
Example
Take , a blocker half-plane at , a receiver plane at , a light of width , and texels of side on the near plane in a map 64 texels wide. The blocker covers the map columns 0 to 31 (the world ).
- Line L1: texels.
- Line L2 at the point that maps to column 32 on a map of 3 rows: the search square covers the columns 24 to 39 of all 3 rows, and the columns 24 to 31 hold the blocker, so .
- Line L4: .
- Line L5: , in world units at the receiver.
- Line L6: texels.
At five receiver points, given by the world of the point:
| PCSS | exact visible fraction | |
|---|---|---|
| 0 | 0 | |
| 0.2 | 0.25 | |
| 0.5 | 0.5 | |
| 0.8 | 0.75 | |
| 1.0 | 1 |
The exact fraction is , a ramp of width . PCSS gets the width right, and its error, at most 0.05 here, comes from the count of whole texels in a filter of half-width 2.5. With a blocker at the same formula gives , a much sharper edge.
Correctness
PCSS is exact for no scene with a penumbra, because it replaces the occluders by one plane at their mean depth. The proof file shows what holds in the model of parallel planes, and the tests check each claim.
- The ramp. For a half-plane blocker at and a receiver plane at , the exact visible fraction of a light of width is with of line L5 (similar triangles).
- The search region. Every map texel that can hold a blocker of the receiver point lies in the square of line L1 (the bound is reached at depth ).
- The limits. With no blocker in the region the result is 1, and with the filter has half-width 0 and PCSS is the hard test of shadow mapping.
- The error bound. In flatland, with the filter inside the map and , the result differs from the exact fraction by at most . The tests check this on random parallel-plane scenes.
For several blockers at different depths, the mean depth of line L4 is a heuristic. It gives a wrong width where a near and a far occluder overlap in the search region.
Proof: The PCSS penumbra estimate is exact for parallel planes, the blocker search region holds every blocker, and PCF then matches the area light within half a tapfull
We use the setup of the page. The light is a square of side in the plane of the light frame, centered on the axis. The shadow map is a perspective view from the center of the light with its image plane at the near plane . It stores the linear depth , and a texel is a square of side on the near plane. A point at lateral position and depth projects to the near plane position . The arithmetic is exact real arithmetic, and the bias is 0.
The proofs work in flatland: one lateral axis and the depth . The projection acts on each lateral axis on its own, so Lemmas 1 to 3 hold per axis in 3D.
The penumbra width
Take a blocker that covers the half-line at depth , a receiver line at depth , and a light segment at depth 0.
Lemma 1. The fraction of the light that the receiver point at sees is with . So goes from 0 to 1 over an interval of width , the value of line L5.
Proof. The segment from the receiver point to the light point meets the depth at . It is blocked when this is negative. Multiply by : the light point is visible when , that is . The visible part of has the length , clamped to . Divide by to get .
This is the similar triangles argument of Fernando. It needs the light, the blocker edge and the receiver to lie in parallel planes. For a tilted receiver or for several blockers at different depths, is an estimate.
The blocker search region
Lemma 2. Let be a receiver point and a point of the light, . Every point of the segment with depth projects to the near plane within texels of the projection of . This is the half-width of line L1.
Proof. The point at depth is . Its projection minus the projection of is
Its absolute value is at most . The function decreases in , so on its largest value is at , where the bound is in near plane units. Divide by .
So a surface nearer to the light than cannot be seen by the map, and every surface that the map holds and that blocks some light from lies inside the search square. Line L2 tests the texel centers in that square, so a blocker that covers no texel center there is not found; this is the sampling error of the map, the same as in shadow mapping.
The two limit cases
Lemma 3. (a) If no texel in the search region is nearer than the receiver, PCSS returns 1 (line L3). (b) If , PCSS returns the binary test of the texel that holds .
Proof. (a) is line L3. (b) With , . The square of half-width 0 holds a texel center only when is a texel center, and then it is the center of the texel that holds ; otherwise the region rule falls back to that texel. So the search tests exactly that texel. If it is not nearer than , the result is 1 by (a), and the binary test also says lit. If it is nearer, the blocker depth is its depth, and (line L6), and the PCF of line L7 tests the same single texel, which is in shadow, so the result is 0.
The flatland match
Use the map of the half-plane blocker: texel holds when its center lies left of the axis, and otherwise. Measure the lookup position in texels from the axis, so the texel centers are the half-integers and the blocker texels are those with . The receiver point at has .
Theorem 4. Suppose and that the squares of half-width and around lie inside the map. Then the PCSS result satisfies .
Proof. The texels with depth less than are exactly the blocker texels, and they all hold . So when line L2 finds any, the average of line L4 is , line L5 gives the of Lemma 1, and line L6 gives , which is the half-width of the penumbra measured in texels at the receiver. With , Lemma 1 becomes : the length of the part of the window to the right of 0, divided by the length of .
Line L7 returns , where is the number of half-integers in and the number of them that are positive. If lies on one side of 0, both and are 0 or both are 1, because is clamped exactly when and the half-integer nearest to 0 is away from it. Otherwise let and be the lengths of the two parts of . The half-integers in for number , which is within of , because 0 lies halfway between two half-integers. So and with . Then
and . So the error is at most . Also , so the error is at most , which is at most when .
There is one more case: the search finds no blocker. Then no half-integer lies in , so , and PCSS returns 1. Since , we have : the inequality reduces to . So , and . The error is at most .
The test checks this bound at random points with and a window inside the map. The example of the page has , and its largest error is , at .
Complexity
Line L2 reads the texels of the search region, and line L7 reads the texels of the filter, so one lookup costs and lookups cost in the worst case. Both regions grow with the light size, and grows as the blocker gets nearer to the light. Renderers bound the cost with a fixed number of taps in each step, for example a Poisson disk of taps scaled to the region, which makes the cost with a fixed constant but adds noise. The extra space is .
Properties
- Contact hardening. The penumbra is narrow at contact and wide far from it, as with an area light (a proved property of the parallel-plane model, and a heuristic elsewhere).
- One map. It needs no extra pass and works with any map that stores linear depth.
- Not a visibility integral. The result is a PCF value with a chosen width, not the visible fraction of the light. Overlapping occluders and receivers that are not planes give a wrong width.
- Adaptive cost. The cost per pixel follows the blocker distance, which makes the frame time depend on the scene.
Variants and improvements
- Fixed tap counts. Sample both regions with a fixed Poisson disk scaled to and , rotated per pixel, and clean the noise with temporal antialiasing.
- Min and max depth maps. Search a mip chain of the minimum and the maximum depths to find the blockers in fewer reads, or to skip points that are fully lit or fully shadowed.
- Filterable blocker search. With variance shadow maps or moment shadow mapping, both the blocker average and the filter come from moments over a box, which a summed-area table or a mip chain gives in per lookup.
- Several maps. With cascaded shadow maps, the light size in texels differs from cascade to cascade, so and are computed per cascade.
When to use it
Use PCSS when soft shadows of a small area light must sharpen at contact and the light is not too large. For large lights, the search and filter regions become large and slow. Then a filterable map with a box filter of variable size, or ray-traced shadows, gives a more even cost. For hard shadows, plain PCF is cheaper.
Pitfalls
- A search region that is too small. If line L1 uses a fixed size smaller than , a blocker far from the point is not found, the point returns 1 at line L3, and the penumbra has lit holes.
- No bias in the search. Without the bias in line L2, the receiver's own depth in the map counts as a blocker, moves toward , and the penumbra becomes too narrow.
- Clip depth in place of linear depth. Lines L4 and L5 need linear depth. With the nonlinear depth of a perspective light, the mean and the ratio are wrong, and the penumbra width changes with the near plane.
- Forgetting the projection. If line L6 omits the factor , the filter is larger than the penumbra by .
- Dividing by zero. Line L5 divides by , which is at least only when the map stores depths from the near plane on.
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/percentage-closer-soft-shadows/. The authors are listed in prov/EXXNC3.jsonl.
"""Percentage-closer soft shadows (Fernando 2005).
The light is a square of side w_light in the plane d = 0 of the light frame,
centered on the light's axis. The shadow map is a perspective view from the
center of the light. It stores linear depth d (the distance along the light's
axis, not the nonlinear clip depth), and its image plane is the near plane at
d = n. A texel is a square of side h in near-plane units. The map s is a list
of rows of depths, s[j][i]; texel (i, j) has its center at (i + 1/2, j + 1/2)
in texel units. A receiver is given by its map position (x, y) in texels and
its depth d_r. Every function returns the lit fraction.
"""
from math import ceil, floor
def region(s, x, y, r):
"""The texels whose centers lie in the square of half-width r texels
around (x, y). If there is none, the texel that holds (x, y)."""
hh, ww = len(s), len(s[0])
i0, i1 = max(ceil(x - r - 0.5), 0), min(floor(x + r - 0.5), ww - 1)
j0, j1 = max(ceil(y - r - 0.5), 0), min(floor(y + r - 0.5), hh - 1)
out = [(i, j) for j in range(j0, j1 + 1) for i in range(i0, i1 + 1)]
if not out:
i, j = min(max(floor(x), 0), ww - 1), min(max(floor(y), 0), hh - 1)
out = [(i, j)]
return out
def search_half_width(d_r, w_light, n, h):
"""Half-width in texels of the region that holds every possible blocker."""
return w_light * (d_r - n) / (2 * d_r * h)
def blocker_search(s, x, y, d_r, w_light, n, h, bias):
"""The average depth and the count of the texels nearer than the receiver."""
rs = search_half_width(d_r, w_light, n, h) # @line L1
found = [s[j][i] for i, j in region(s, x, y, rs) if s[j][i] < d_r - bias] # @line L2
if not found:
return None, 0
return sum(found) / len(found), len(found) # @line L4
def penumbra_width(d_r, d_b, w_light):
"""The penumbra width at the receiver, for parallel planes."""
return (d_r - d_b) * w_light / d_b # @line L5
def pcf(s, x, y, d_r, r, bias):
"""Box PCF over the texels of the square of half-width r texels."""
taps = region(s, x, y, r)
lit = sum(1 for i, j in taps if d_r - bias <= s[j][i])
return lit / len(taps)
def pcss(s, x, y, d_r, w_light, n, h, bias=0.0):
d_b, count = blocker_search(s, x, y, d_r, w_light, n, h, bias)
if count == 0: # @line L3
return 1.0
w_p = penumbra_width(d_r, d_b, w_light)
rf = w_p * n / (2 * d_r * h) # @line L6
return pcf(s, x, y, d_r, rf, bias) # @line L7
def flatland_map(width, h, n, d_b, d_r, rows=3):
"""A map of a half-plane blocker at depth d_b over x < 0 above a receiver
plane at depth d_r. The map is centered on the light's axis, so texel i
covers [(i - width/2) h, (i - width/2 + 1) h] on the near plane."""
row = [d_b if (i - width / 2 + 0.5) * h < 0 else d_r for i in range(width)]
return [row[:] for _ in range(rows)]
def exact_visibility(xw, d_b, d_r, w_light):
"""The visible fraction of the light segment from the receiver point at
world position xw, for the half-plane blocker x < 0 at depth d_b."""
lo = -xw * d_b / (d_r - d_b) # the light points with x >= lo are visible
return min(max((w_light / 2 - lo) / w_light, 0.0), 1.0)
test_percentage_closer_soft_shadows.py 107 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/percentage-closer-soft-shadows/. The authors are listed in prov/EXXNC3.jsonl.
import random
from percentage_closer_soft_shadows import (
blocker_search,
exact_visibility,
flatland_map,
pcss,
penumbra_width,
search_half_width,
)
def test_example_on_the_page():
n, d_b, d_r, wl = 1.0, 2.0, 4.0, 1.0
assert penumbra_width(d_r, d_b, wl) == 1.0
assert search_half_width(d_r, wl, n, 0.05) == 7.5
s = flatland_map(64, 0.05, n, d_b, d_r)
d, count = blocker_search(s, 32.0, 1.5, d_r, wl, n, 0.05, 0.0)
assert (d, count) == (2.0, 24)
got = [pcss(s, xw * n / d_r / 0.05 + 32, 1.5, d_r, wl, n, 0.05) for xw in (-0.5, -0.25, 0.0, 0.25, 0.5)]
assert [round(g, 12) for g in got] == [0.0, 0.2, 0.5, 0.8, 1.0]
want = [exact_visibility(xw, d_b, d_r, wl) for xw in (-0.5, -0.25, 0.0, 0.25, 0.5)]
assert want == [0.0, 0.25, 0.5, 0.75, 1.0]
def test_flatland_parallel_planes_match_the_area_light():
# Precondition: the filter square stays inside the map, so no tap is clamped.
rng = random.Random(1)
tested = 0
while tested < 30:
n = rng.uniform(0.5, 1.5)
d_b = n + rng.uniform(0.5, 2.0)
d_r = d_b + rng.uniform(0.5, 3.0)
wl = rng.uniform(0.3, 1.5)
h = 0.0125
s = flatland_map(64, h, n, d_b, d_r)
rf = penumbra_width(d_r, d_b, wl) * n / (2 * d_r * h)
if not 3 <= rf <= 18:
continue
tested += 1
for _ in range(10):
x = 32 + rng.uniform(-12.0, 12.0)
xw = (x - 32) * h * d_r / n
got = pcss(s, x, 1.5, d_r, wl, n, h)
want = exact_visibility(xw, d_b, d_r, wl)
assert abs(got - want) <= 1.0 / (2 * rf) + 1e-9
def test_blocker_search_equals_brute_force():
rng = random.Random(2)
for _ in range(100):
w, hh = rng.randrange(4, 20), rng.randrange(4, 20)
s = [[rng.uniform(1.0, 5.0) for _ in range(w)] for _ in range(hh)]
x, y = rng.uniform(0, w), rng.uniform(0, hh)
d_r, wl, n, h = rng.uniform(2.0, 6.0), rng.uniform(0.1, 2.0), 1.0, rng.uniform(0.05, 0.3)
rs = wl * (d_r - n) / (2 * d_r * h)
taps = [s[j][i] for j in range(hh) for i in range(w)
if abs(i + 0.5 - x) <= rs and abs(j + 0.5 - y) <= rs]
if not taps:
taps = [s[min(int(y), hh - 1)][min(int(x), w - 1)]]
near = [t for t in taps if t < d_r]
d, count = blocker_search(s, x, y, d_r, wl, n, h, 0.0)
assert count == len(near)
if near:
assert abs(d - sum(near) / len(near)) < 1e-12
def test_search_region_holds_every_blocker_of_the_light():
# A point on the segment from the receiver to a point of the light, at a
# depth in [n, d_r), projects within the search half-width of the receiver.
rng = random.Random(3)
for _ in range(2000):
n, d_r = rng.uniform(0.2, 1.0), rng.uniform(1.5, 8.0)
wl, h = rng.uniform(0.1, 2.0), rng.uniform(0.01, 0.2)
xr = rng.uniform(-3.0, 3.0)
xl = rng.uniform(-wl / 2, wl / 2)
z = rng.uniform(n, d_r)
xp = xr + (xl - xr) * (d_r - z) / d_r
u_p, u_r = xp * n / z, xr * n / d_r
assert abs(u_p - u_r) / h <= search_half_width(d_r, wl, n, h) + 1e-9
def test_no_blocker_is_lit_and_no_light_size_is_the_hard_test():
s = [[5.0] * 8 for _ in range(8)]
assert pcss(s, 4.0, 4.0, 3.0, 1.0, 1.0, 0.1) == 1.0
rng = random.Random(4)
for _ in range(200):
s = [[rng.uniform(1.0, 5.0) for _ in range(6)] for _ in range(6)]
x, y, d_r = rng.uniform(0, 6), rng.uniform(0, 6), rng.uniform(1.0, 5.0)
hard = 1.0 if d_r <= s[int(y)][int(x)] else 0.0
assert pcss(s, x, y, d_r, 0.0, 1.0, 0.1) == hard
def test_result_in_range_and_wider_light_widens_the_penumbra():
n, d_b, d_r, h = 1.0, 2.0, 4.0, 0.0125
s = flatland_map(64, h, n, d_b, d_r)
prev = None
for wl in (0.2, 0.4, 0.8):
lit = [pcss(s, 32 + k / 4, 1.5, d_r, wl, n, h) for k in range(-40, 41)]
assert all(0.0 <= v <= 1.0 for v in lit)
soft = sum(1 for v in lit if 0.0 < v < 1.0)
if prev is not None:
assert soft > prev
prev = soft
History
Fernando presented percentage-closer soft shadows in 2005, as a SIGGRAPH sketch and in NVIDIA material for developers. It used the PCF filter that hardware already supported and needed only one ordinary shadow map, so it fit into existing renderers. Later work replaced its search and filter by filterable moment maps and fixed tap patterns, and the name stayed for the class of contact-hardening shadow filters.
References
- Randima Fernando, Percentage-closer soft shadows, ACM SIGGRAPH 2005 Sketches, article 35, 2005, the three steps (blocker search, penumbra estimation from parallel planes, filtering) and the penumbra formula (general locator)
- Randima Fernando, Percentage-closer soft shadows, NVIDIA presentation at I3D 2005, the slides on the blocker search, the penumbra estimate and the filter 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, Chapter 7, the part on percentage-closer soft shadows (general locator)
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 EXXNC3 Edit this page History Report an error Markdown