Algorithm Search⌘K

Algorithmresearch

Moment shadow mapping

Also called moment shadow maps.

Store four power moments of depth and compute the sharp lower bound on the occluded fraction, an upper bound on the lit fraction with less light leaking than variance shadow maps.

Time
Θ(w h + q) worst
Space
Θ(w h) extra
Where
h = the map height in texels; q = the number of shadow lookups; w = the map width in texels
Properties
not adaptivenot comparison baseddeterministicnot in placeofflineiterativenot stable
Origin
Christoph Peters, Reinhard Klein, 2015

Moment shadow mapping stores the first four powers of the depth, z,z2,z3,z4z, z^2, z^3, z^4, at each texel and filters them like variance shadow maps filter their two moments. The lookup solves a small linear system and a quadratic to get the sharp lower bound on the occluded fraction for these four moments, so 1−G1 - G is an upper bound on the lit fraction. With four moments the bound is never weaker than the two-moment Chebyshev bound of variance shadow maps, and in scenes with several occluders it is much tighter, so the light leaking is smaller. It costs twice the storage and more arithmetic per lookup.

In plain words

Variance shadow maps keep two summary numbers for the distances near each dot of the shadow map: the average and the spread. From them they estimate how much of the area is behind a point. When objects at very different distances overlap, the estimate is far too bright.

This method keeps two more numbers, from the cube and the fourth power of the distance. With four numbers it can tell more about the mix of distances. The lookup finds the mix of at most three distances that agrees with the four numbers and makes the point as bright as possible, and uses that brightness. The answer is never darker than the truth, and it is never brighter than the answer from two numbers.

The problem

The input is a map of depths in the Direct3D range [0,1][0, 1], smaller nearer, a filter, and lookups with a receiver depth zz. The filter defines a distribution of the depths under it, as on the variance shadow maps page. The map stores the filtered power moments b=(b1,b2,b3,b4)b = (b_1, b_2, b_3, b_4) with bkb_k the filtered mean of zkz^k. The lit fraction is the probability that a depth is at least zfz_f, the receiver depth after the bias. The output is the smallest value that is an upper bound on the lit fraction for every distribution with the moments bb, together with tunings that make the computation stable.

The algorithm

  1. MSM-LOOKUP(b, z, α, β) ▷ b = (b1, b2, b3, b4), receiver depth z
  2. 1b' ← (1 - α) b + α (1/2, 1/2, 1/2, 1/2) ▷ the moment bias
  3. 2z_f ← z - β ▷ the depth bias
  4. 3solve B c = (1, z_f, z_f^2) for B = [[1, b'1, b'2], [b'1, b'2, b'3], [b'2, b'3, b'4]] by Cholesky
  5. 4z2 < z3 ← the two roots of c3 x^2 + c2 x + c1
  6. 5if z_f ≤ z2 then G ← 0
  7. 6else if z_f ≤ z3 then G ← (z_f z3 - b'1 (z_f + z3) + b'2) / ((z3 - z2)(z_f - z2))
  8. 7else G ← 1 - (z2 z3 - b'1 (z2 + z3) + b'2) / ((z_f - z2)(z_f - z3))
  9. 8return 1 - clamp(G, 0, 1) ▷ the lit estimate

Line L3 uses the Cholesky decomposition B=LDLTB = L D L^T of the Hankel matrix of the moments. Its two pivots are d1=b2−b12d_1 = b_2 - b_1^2, the variance, and d2d_2; both are positive when the filter holds at least three distinct depths. The roots zfz_f, z2z_2 and z3z_3 are the support of the canonical distribution: the distribution on three points with the moments bb that has a point at zfz_f. The value GG is its weight below zfz_f. Lines L6 and L7 are that weight in closed form, so the lookup needs no explicit solve for the weights.

The bias of line L1 mixes in a small amount of the distribution with half its mass at 0 and half at 1, whose moments are all 12\tfrac12. It keeps BB positive definite for maps with one or two distinct depths, such as a plane over a plane, and it hides the rounding of moments stored with few bits. Peters and Klein use α=3⋅10−5\alpha = 3 \cdot 10^{-5}; this value is a tuning.

Example

A filter holds three depths 0.2, 0.4 and 0.6 with equal weights. Then b=(2/5,14/75,12/125,98/1875)b = (2/5, 14/75, 12/125, 98/1875), with the mean 0.4 and the variance 2/752/75. There is no bias.

receiver zz VSM bound MSM 1−G1 - G true lit fraction support points
0.8 1/7=0.14291/7 = 0.1429 0.01754 0 0.8, 0.22380, 0.53620
0.5 8/11=0.72738/11 = 0.7273 0.57961 1/31/3 0.5, 0.21729, 0.66271
0.3 1 0.88416 2/32/3 0.3 and two more

At z=0.8z = 0.8 all three depths are in front of the receiver. The variance bound shows 14 percent of the light, and the moment bound 1.75 percent. At z=0.3z = 0.3 the receiver is in front of the mean, so the variance bound gives no information, but the moment bound still says that at least 11.6 percent is occluded.

Two depths. A filter with the depths 0.2 and 0.6 has a singular Hankel matrix, and line L3 cannot be solved. With α=3⋅10−5\alpha = 3 \cdot 10^{-5}, the lookup at z=0.8z = 0.8 returns 0.000122, where the true value is 0 and the variance bound is 0.04/(0.04+0.16)=0.20.04/(0.04 + 0.16) = 0.2.

Correctness

The proof file gives the full argument, and the tests check each claim against the true lit fraction of random distributions and against a direct solve of the canonical weights.

  • The kernel polynomial. The solution cc of line L3 defines K(x)=c1+c2x+c3x2K(x) = c_1 + c_2 x + c_3 x^2 with ∫Kq dμ=q(zf)\int K q \, d\mu = q(z_f) for every quadratic qq. From this, K(zf)>0K(z_f) > 0, and KK has two real roots that differ from zfz_f, by a sum of squares argument.
  • The canonical distribution. The three points zf,z2,z3z_f, z_2, z_3 carry positive weights that sum to 1 and reproduce all four moments.
  • The bound. For each of the three cases of lines L5 to L7 there is a polynomial of degree 4 that lies above the step function of the lit set and meets it at the three points. Integrating it against any distribution with the moments bb gives lit fraction ≤1−G\le 1 - G, and the canonical distribution reaches it. So GG is the sharp lower bound on the occluded fraction, and 1−G1 - G is the sharp upper bound on the lit fraction, over all distributions on the real line.
  • Better than two moments. The set of distributions with four given moments is a subset of the set with two of them, so 1−G1 - G is at most the variance bound.
  • The bias. With the bias of line L1, the result is at least the true lit fraction minus α/2\alpha / 2.

The depths lie in [0,1][0, 1], but the support points can lie outside it. The bound is then still valid, but a distribution on [0,1][0, 1] may not reach it.

Proof: The Hamburger 4MSM lookup returns the sharp lower bound on the occluded fraction given four power moments, so 1 - G is an upper bound on the lit fraction and is never above the VSM boundfull

We use the notation of the page. A filter defines a probability distribution μ\mu of depths on the real line. Its power moments are bk=∫zk dμb_k = \int z^k \, d\mu for k=0,…,4k = 0, \ldots, 4, with b0=1b_0 = 1. The lit fraction for the depth zfz_f is μ([zf,∞))\mu([z_f, \infty)) and the occluded fraction is μ((−∞,zf))\mu((-\infty, z_f)), as in variance shadow maps. Define the linear functional L(p)=∑kpkbkL(p) = \sum_k p_k b_k on polynomials p(x)=∑kpkxkp(x) = \sum_k p_k x^k of degree at most 4. Then L(p)=∫p dμL(p) = \int p \, d\mu for every distribution with these moments. The Hankel matrix is B=(bi+j)i,j=02B = (b_{i + j})_{i, j = 0}^{2}, and cTBc=L(pc2)c^T B c = L(p_c^2) for the polynomial pc(x)=c1+c2x+c3x2p_c(x) = c_1 + c_2 x + c_3 x^2.

The standing hypothesis is that BB is positive definite: L(p2)>0L(p^2) > 0 for every nonzero polynomial pp of degree at most 2. This holds when μ\mu has at least three support points. The factorization in solve_hankel checks it: the pivots d1d_1 and d2d_2 of B=LDLTB = L D L^T are positive exactly when BB is positive definite. We also assume that c3≠0c_3 \ne 0 in line L4; the code stops otherwise. The arithmetic is exact real arithmetic.

The kernel polynomial

Line L3 solves Bc=(1,zf,zf2)TB c = (1, z_f, z_f^2)^T, and we write K(x)=c1+c2x+c3x2K(x) = c_1 + c_2 x + c_3 x^2.

Lemma 1. L(Kq)=q(zf)L(K q) = q(z_f) for every polynomial qq of degree at most 2.

Proof. Row kk of BcB c is c1bk+c2bk+1+c3bk+2=L(Kxk)c_1 b_k + c_2 b_{k + 1} + c_3 b_{k + 2} = L(K x^k), and it equals zfkz_f^k, for k=0,1,2k = 0, 1, 2. Both sides are linear in qq. □\square

Lemma 2. K(zf)>0K(z_f) > 0, and KK has two real roots z2<z3z_2 < z_3, both different from zfz_f. These are the roots of line L4.

Proof. c≠0c \ne 0, because Bc≠0B c \ne 0. By Lemma 1 with q=Kq = K, K(zf)=L(K2)=cTBc>0K(z_f) = L(K^2) = c^T B c > 0. Suppose that KK does not change sign. Since K(zf)>0K(z_f) > 0, then K≥0K \ge 0 on the real line, so K(x)(x−zf)2K(x)(x - z_f)^2 is a nonnegative polynomial of degree at most 4. It is not the zero polynomial. A nonnegative polynomial in one variable is a sum of squares of polynomials of half its degree, so L(K(x−zf)2)>0L(K (x - z_f)^2) > 0 by the hypothesis on BB. But Lemma 1 with q=(x−zf)2q = (x - z_f)^2 gives L(K(x−zf)2)=0L(K (x - z_f)^2) = 0. So KK changes sign. As c3≠0c_3 \ne 0, KK is a quadratic with two distinct real roots, and K(zf)>0K(z_f) > 0 shows that zfz_f is neither of them. □\square

The canonical representation

Let x1=zfx_1 = z_f, x2=z2x_2 = z_2, x3=z3x_3 = z_3, and let ℓi\ell_i be the Lagrange polynomials of degree 2 on these three nodes, with ℓi(xj)=1\ell_i(x_j) = 1 if i=ji = j and 0 otherwise.

Lemma 3. The weights wi=L(ℓi)w_i = L(\ell_i) are positive, sum to 1, and the measure ν=∑iwiδxi\nu = \sum_i w_i \delta_{x_i} has the moments b0,…,b4b_0, \ldots, b_4. So L(p)=∑iwi p(xi)L(p) = \sum_i w_i\, p(x_i) for every pp of degree at most 4.

Proof. Let N(x)=(x−zf)K(x)N(x) = (x - z_f) K(x), a cubic whose roots are the three nodes. Divide a polynomial pp of degree at most 4 by NN: p=Ns+rp = N s + r with deg⁡s≤1\deg s \le 1 and deg⁡r≤2\deg r \le 2. Then L(Ns)=L(K⋅(x−zf)s)=0L(N s) = L(K \cdot (x - z_f) s) = 0 by Lemma 1, because (x−zf)s(x - z_f) s has degree at most 2 and is zero at zfz_f. So L(p)=L(r)L(p) = L(r). Since r=∑ir(xi)ℓir = \sum_i r(x_i) \ell_i, we get L(r)=∑iwir(xi)=∑iwip(xi)L(r) = \sum_i w_i r(x_i) = \sum_i w_i p(x_i), because N(xi)=0N(x_i) = 0. With p=1p = 1, the weights sum to b0=1b_0 = 1. With p=ℓi2p = \ell_i^2, of degree 4, wi=∑jwjℓi(xj)2=L(ℓi2)>0w_i = \sum_j w_j \ell_i(x_j)^2 = L(\ell_i^2) > 0 by the hypothesis on BB. □\square

The two weights that the code uses are, from L((x−a)(x−b))=b2−(a+b)b1+abL((x - a)(x - b)) = b_2 - (a + b) b_1 + a b,

wz2=zfz3−b1(zf+z3)+b2(z3−z2)(zf−z2),wzf=z2z3−b1(z2+z3)+b2(zf−z2)(zf−z3).w_{z_2} = \frac{z_f z_3 - b_1 (z_f + z_3) + b_2}{(z_3 - z_2)(z_f - z_2)}, \qquad w_{z_f} = \frac{z_2 z_3 - b_1 (z_2 + z_3) + b_2}{(z_f - z_2)(z_f - z_3)}.

The first is line L6. Line L7 returns 1−wzf1 - w_{z_f}.

The bound

Let GG be the value of lines L5 to L7: G=0G = 0 if zf<z2z_f < z_2, G=wz2G = w_{z_2} if z2<zf<z3z_2 < z_f < z_3, and G=1−wzf=wz2+wz3G = 1 - w_{z_f} = w_{z_2} + w_{z_3} if zf>z3z_f > z_3. In each case G=ν((−∞,zf))G = \nu((-\infty, z_f)), the weight of the nodes less than zfz_f. (By Lemma 2, zfz_f is not a node of KK, so the tests zf≤z2z_f \le z_2 and zf≤z3z_f \le z_3 of the code are strict.)

Theorem 4. Every distribution μ\mu on the real line with the moments b1,…,b4b_1, \ldots, b_4 has μ((−∞,zf))≥G\mu((-\infty, z_f)) \ge G, and ν\nu attains it. So GG is the sharp lower bound on the occluded fraction, and 1−G1 - G is the sharp upper bound on the lit fraction.

Proof. We give in each case a polynomial uu of degree at most 4 with u≥1[zf,∞)u \ge \mathbf{1}_{[z_f, \infty)} on the real line and u(xi)=1[xi≥zf]u(x_i) = \mathbf{1}[x_i \ge z_f] at the three nodes. Then μ([zf,∞))≤∫u dμ=L(u)=∑iwiu(xi)=ν([zf,∞))=1−G\mu([z_f, \infty)) \le \int u \, d\mu = L(u) = \sum_i w_i u(x_i) = \nu([z_f, \infty)) = 1 - G by Lemma 3.

Case zf<z2z_f < z_2. Take u=1u = 1. Here 1−G=11 - G = 1.

Case zf>z3z_f > z_3. Take u(x)=κ(x−z2)2(x−z3)2u(x) = \kappa (x - z_2)^2 (x - z_3)^2 with κ=1/((zf−z2)(zf−z3))2\kappa = 1 / ((z_f - z_2)(z_f - z_3))^2. Then u≥0u \ge 0, u(z2)=u(z3)=0u(z_2) = u(z_3) = 0 and u(zf)=1u(z_f) = 1. For x>z3x > z_3 the factor (x−z2)(x−z3)(x - z_2)(x - z_3) is positive and increasing, so uu is increasing there and u≥1u \ge 1 on [zf,∞)[z_f, \infty).

Case z2<zf<z3z_2 < z_f < z_3. We want u(z2)=0u(z_2) = 0 and u(zf)=u(z3)=1u(z_f) = u(z_3) = 1. Take u(x)=1+κ(x−zf)(x−z3)2(x−e)u(x) = 1 + \kappa (x - z_f)(x - z_3)^2 (x - e) and choose ee and κ\kappa so that u(z2)=0u(z_2) = 0 and u′(z2)=0u'(z_2) = 0. At z2z_2 we have u−1=−1≠0u - 1 = -1 \ne 0, so u′(z2)=0u'(z_2) = 0 is the condition that the logarithmic derivative of u−1u - 1 is zero there:

1z2−e=1zf−z2+2z3−z2>0.\frac{1}{z_2 - e} = \frac{1}{z_f - z_2} + \frac{2}{z_3 - z_2} > 0.

This fixes e<z2e < z_2. Then u(z2)=0u(z_2) = 0 gives κ=1/((zf−z2)(z3−z2)2(z2−e))>0\kappa = 1 / ((z_f - z_2)(z_3 - z_2)^2 (z_2 - e)) > 0. For x≥zfx \ge z_f, the factors x−zfx - z_f, (x−z3)2(x - z_3)^2 and x−ex - e are all nonnegative, so u≥1u \ge 1. For x<zfx < z_f we need u≥0u \ge 0. The roots of u−1u - 1 are e<zf<z3e < z_f < z_3, with z3z_3 double, so by Rolle's theorem u′=(u−1)′u' = (u - 1)' has a root in (e,zf)(e, z_f), a root in (zf,z3)(z_f, z_3) and the root z3z_3. These are its three roots. Since u′(z2)=0u'(z_2) = 0 and z2∈(e,zf)z_2 \in (e, z_f), z2z_2 is the only root of u′u' below zfz_f. The leading coefficient κ\kappa is positive, so uu decreases on (−∞,z2)(-\infty, z_2) and increases on (z2,zf)(z_2, z_f). So u≥u(z2)=0u \ge u(z_2) = 0 on (−∞,zf)(-\infty, z_f).

The measure ν\nu has the moments bb by Lemma 3 and ν((−∞,zf))=G\nu((-\infty, z_f)) = G, so no larger lower bound holds for all μ\mu. □\square

This is the Markov-Krein type result that Peters and Klein use (Krein and Nudel'man, Theorem IV.3.1). The bound is sharp over distributions on the whole real line (the Hamburger problem). The depths of a map lie in [0,1][0, 1], and the nodes z2,z3z_2, z_3 can lie outside it; then the bound is still valid, but a distribution on [0,1][0, 1] may not attain it.

Corollary 5. 1−G1 - G is never larger than the VSM value pmax⁡(zf)p_{\max}(z_f) of the same distribution.

Proof. If zf≤b1z_f \le b_1, the VSM value is 1. Otherwise, the set of distributions with the moments b1,…,b4b_1, \ldots, b_4 is a subset of the set with the moments b1,b2b_1, b_2. The largest lit fraction over the smaller set is 1−G1 - G (Theorem 4), and over the larger set it is pmax⁡p_{\max} (Cantelli's inequality, which is sharp). □\square

The moment bias

Proposition 6. Line L1 with α∈[0,1]\alpha \in [0, 1] and b∗=(12,12,12,12)b^\ast = (\tfrac12, \tfrac12, \tfrac12, \tfrac12) replaces μ\mu by the mixture μ′=(1−α)μ+α2(δ0+δ1)\mu' = (1 - \alpha) \mu + \tfrac{\alpha}{2} (\delta_0 + \delta_1). For 0<zf≤10 < z_f \le 1 the result 1−G′1 - G' satisfies 1−G′≥μ([zf,∞))−α/21 - G' \ge \mu([z_f, \infty)) - \alpha / 2. If α>0\alpha > 0 and μ\mu has a depth outside {0,1}\{0, 1\}, the biased Hankel matrix is positive definite.

Proof. The point masses at 0 and 1 have zkz^k equal to 0 and 1 for k≥1k \ge 1, so their moments are all 12\tfrac12, and the moments of μ′\mu' are (1−α)b+αb∗(1 - \alpha) b + \alpha b^\ast. With 0<zf≤10 < z_f \le 1, μ′([zf,∞))=(1−α)μ([zf,∞))+α/2\mu'([z_f, \infty)) = (1 - \alpha) \mu([z_f, \infty)) + \alpha / 2. By Theorem 4 applied to μ′\mu', 1−G′≥(1−α)μ([zf,∞))+α/2≥μ([zf,∞))−α/21 - G' \ge (1 - \alpha) \mu([z_f, \infty)) + \alpha / 2 \ge \mu([z_f, \infty)) - \alpha / 2, because μ([zf,∞))≤1\mu([z_f, \infty)) \le 1. For the last claim, B′=(1−α)B+αB∗B' = (1 - \alpha) B + \alpha B^\ast, and cTB′c=(1−α)∫pc2 dμ+α2(pc(0)2+pc(1)2)c^T B' c = (1 - \alpha) \int p_c^2 \, d\mu + \tfrac{\alpha}{2} (p_c(0)^2 + p_c(1)^2). If this is 0, then pcp_c is zero at 0, at 1 and at a depth of μ\mu outside {0,1}\{0, 1\}, so pc=0p_c = 0 and c=0c = 0. □\square

So the bias trades an upper bound for an estimate that is at most α/2\alpha/2 below the true lit fraction, and it makes maps with one or two distinct depths usable, as a plane under a plane is. Peters and Klein use α=3⋅10−5\alpha = 3 \cdot 10^{-5} for their quantized formats; this value is a tuning, not a derived constant. The clamp of line L8 does nothing in exact arithmetic, because 0≤G≤10 \le G \le 1; it guards against rounding.

Complexity

The map pass computes four moments per texel, and any linear filter acts on them as on the two moments of variance shadow maps, in Θ(wh)\Theta(w h) for a summed-area table or a fixed-size blur. A lookup is O(1)O(1): a 3×33 \times 3 Cholesky solve, a quadratic and a few divisions, so qq lookups cost Θ(wh+q)\Theta(w h + q) in the worst case. The map takes four values per texel. Peters and Klein store them in 64 bits per texel with a quantization transform, or in 128 bits as floats.

Properties

  • Sharp for four moments. No lookup that sees only b1b_1 to b4b_4 can give a lower upper bound on the lit fraction (a proved property).
  • At most the variance bound. The leak is never larger than that of variance shadow maps for the same filter (a proved property).
  • Filterable. The moments are linear in the weights, so blurs, mipmaps and summed-area tables apply before the lookup.
  • Still leaks. The bound is an upper bound, not the lit fraction. In the example it shows 58 percent of the light where the truth is 33 percent.
  • Sensitive to precision. Without the bias of line L1, moments of one or two distinct depths, or moments rounded to 16 bits, make line L3 singular or unstable.

Variants and improvements

  • Optimized quantization. Peters and Klein store an affine transform of the moments in place of the raw powers, so that 16 bits per moment are enough with a small α\alpha.
  • Hausdorff moments. A variant uses the moment problem on a bounded interval, which knows that the depths lie in [0,1][0, 1]; it needs more work per lookup.
  • Soft shadows. The filtered moments also give an estimate of the average blocker depth, so the blocker search of percentage-closer soft shadows can run on a summed-area table of moments.
  • Fewer moments. Variance shadow maps keep two moments and the Chebyshev bound; exponential maps keep one moment of a warped depth.

When to use it

Use moment shadow maps where filtered shadows are needed, as for variance shadow maps, and the light leaking of two moments is visible: scenes with several layers of occluders, such as foliage or buildings, or a large filter on a distant cascade. If the filter is small, PCF is cheaper and exact for its taps. If memory bandwidth is tight, the four moments cost twice as much as two.

Pitfalls

  • No moment bias. With α=0\alpha = 0 in line L1, a texel that holds one plane, or a plane over a plane, gives a singular BB, and line L3 divides by zero.
  • Unsorted roots. If line L4 does not order the roots so that z2<z3z_2 < z_3, lines L5 and L6 test the wrong case and return a weight of the wrong node.
  • No depth bias. With β=0\beta = 0 in line L2, a lit receiver can lie a rounding error behind its own depth in the map, and the bound then darkens it a little; peaks of this kind show as acne.
  • Raw powers in 16 bits. Storing z3z^3 and z4z^4 in 16 bits destroys the information that the lookup needs; use 32-bit floats or the quantization transform.
  • No clamp. In floating point, GG from lines L6 and L7 can fall slightly outside [0,1][0, 1]; line L8 must clamp it.

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.

moment_shadow_mapping.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/moment-shadow-mapping/. The authors are listed in prov/ZPXE0M.jsonl.

"""Moment shadow mapping with four power moments (Peters and Klein 2015).

This is the Hamburger 4MSM lookup of the paper. Depth is in [0, 1] (the
Direct3D clip range), smaller is nearer to the light. A filtered texel holds
b = (b1, b2, b3, b4), the means of z, z^2, z^3 and z^4 over the depths z under
the filter. The lookup computes G, the sharp lower bound on the occluded
fraction (the weight of the depths z < zf), and returns 1 - G, which is an
upper bound on the lit fraction (the weight of the depths z >= zf).
"""

from math import sqrt


def power_moments(depths, weights=None):
    """The filtered moments (b1, b2, b3, b4) of a list of depths."""
    if weights is None:
        weights = [1] * len(depths)
    total = sum(weights)
    return tuple(sum(w * z ** k for z, w in zip(depths, weights)) / total for k in range(1, 5))


def solve_hankel(b, zf):
    """Solve B c = (1, zf, zf^2) for B = [[1, b1, b2], [b1, b2, b3], [b2, b3, b4]]
    by the Cholesky factorization B = L D L^T, as in the paper's shader."""
    b1, b2, b3, b4 = b
    d1 = b2 - b1 * b1
    if d1 <= 0:
        raise ValueError("the moments are not in the interior of the moment space")
    l32 = (b3 - b1 * b2) / d1
    d2 = (b4 - b2 * b2) - l32 * l32 * d1
    if d2 <= 0:
        raise ValueError("the moments are not in the interior of the moment space")
    # Forward substitution with the unit lower triangle L = [[1,0,0],[b1,1,0],[b2,l32,1]].
    y1 = 1
    y2 = zf - b1 * y1
    y3 = zf * zf - b2 * y1 - l32 * y2
    # Divide by D and back substitution with L^T.
    c3 = y3 / d2
    c2 = y2 / d1 - l32 * c3
    c1 = y1 - b1 * c2 - b2 * c3
    return c1, c2, c3


def shadow_intensity(b, zf):
    """G of the paper: the sharp lower bound on the occluded fraction."""
    c1, c2, c3 = solve_hankel(b, zf)  # @line L3
    if c3 == 0:
        raise ZeroDivisionError("c3 = 0: no canonical representation for this depth")
    p, q = c2 / c3, c1 / c3  # @line L4
    disc = sqrt(max(p * p / 4 - q, 0.0))
    z2, z3 = -p / 2 - disc, -p / 2 + disc
    b1, b2 = b[0], b[1]
    if zf <= z2:  # @line L5
        return 0.0
    if zf <= z3:  # @line L6
        return (zf * z3 - b1 * (zf + z3) + b2) / ((z3 - z2) * (zf - z2))
    return 1 - (z2 * z3 - b1 * (z2 + z3) + b2) / ((zf - z2) * (zf - z3))  # @line L7


def msm_lookup(b, z, alpha=0.0, beta=0.0):
    """The lit estimate 1 - G for the receiver depth z.

    alpha is the moment bias (the paper uses 3e-5 for its quantized formats),
    beta the depth bias. Both are tuning.
    """
    bb = tuple((1 - alpha) * x + alpha * 0.5 for x in b)  # @line L1
    zf = z - beta  # @line L2
    g = shadow_intensity(bb, zf)
    return 1 - min(max(g, 0.0), 1.0)  # @line L8


def canonical_nodes(b, zf):
    """The support {zf, z2, z3} of the canonical representation."""
    c1, c2, c3 = solve_hankel(b, zf)
    p, q = c2 / c3, c1 / c3
    disc = sqrt(max(p * p / 4 - q, 0.0))
    return zf, -p / 2 - disc, -p / 2 + disc
test_moment_shadow_mapping.py 120 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/moment-shadow-mapping/. The authors are listed in prov/ZPXE0M.jsonl.

import random

from moment_shadow_mapping import canonical_nodes, msm_lookup, power_moments, shadow_intensity

TOL = 1e-7


def solve3(a, r):
    """Gaussian elimination with partial pivoting on a 3 x 3 system."""
    m = [row[:] + [v] for row, v in zip(a, r)]
    for c in range(3):
        p = max(range(c, 3), key=lambda k: abs(m[k][c]))
        m[c], m[p] = m[p], m[c]
        for k in range(c + 1, 3):
            f = m[k][c] / m[c][c]
            for j in range(c, 4):
                m[k][j] -= f * m[c][j]
    x = [0.0] * 3
    for c in (2, 1, 0):
        x[c] = (m[c][3] - sum(m[c][j] * x[j] for j in range(c + 1, 3))) / m[c][c]
    return x


def random_distribution(rng):
    """3 to 7 distinct depths in [0, 1], at least 0.05 apart, with weights."""
    while True:
        k = rng.randrange(3, 8)
        zs = sorted(rng.uniform(0.0, 1.0) for _ in range(k))
        if all(b - a >= 0.05 for a, b in zip(zs, zs[1:])):
            ws = [rng.randrange(1, 10) for _ in range(k)]
            return zs, ws


def occluded(zs, ws, zf):
    return sum(w for z, w in zip(zs, ws) if z < zf) / sum(ws)


def vsm_bound(b, t):
    m1, m2 = b[0], b[1]
    if t <= m1:
        return 1.0
    v = m2 - m1 * m1
    return v / (v + (t - m1) ** 2)


def test_lower_bound_on_the_occluded_fraction():
    rng = random.Random(1)
    for _ in range(400):
        zs, ws = random_distribution(rng)
        b = power_moments(zs, ws)
        for _ in range(5):
            zf = rng.uniform(0.0, 1.0)
            g = shadow_intensity(b, zf)
            assert g <= occluded(zs, ws, zf) + TOL
            assert 1 - min(max(g, 0.0), 1.0) >= 1 - occluded(zs, ws, zf) - TOL


def test_sharp_the_canonical_measure_attains_the_bound():
    rng = random.Random(2)
    for _ in range(300):
        zs, ws = random_distribution(rng)
        b = power_moments(zs, ws)
        zf = rng.uniform(0.0, 1.0)
        nodes = canonical_nodes(b, zf)
        assert abs(nodes[1] - nodes[2]) > 1e-9
        assert min(abs(nodes[0] - nodes[1]), abs(nodes[0] - nodes[2])) > 1e-9
        # Weights from the 3 x 3 Vandermonde system on moments 0, 1, 2.
        vand = [[x ** k for x in nodes] for k in range(3)]
        w = solve3(vand, [1.0, b[0], b[1]])
        assert min(w) > -TOL
        # The same weights reproduce moments 3 and 4 as well.
        assert abs(sum(wi * x ** 3 for wi, x in zip(w, nodes)) - b[2]) < 1e-6
        assert abs(sum(wi * x ** 4 for wi, x in zip(w, nodes)) - b[3]) < 1e-6
        g = sum(wi for wi, x in zip(w, nodes) if x < zf)
        assert abs(g - shadow_intensity(b, zf)) < 1e-6


def test_four_moments_are_at_least_as_tight_as_two():
    rng = random.Random(3)
    for _ in range(400):
        zs, ws = random_distribution(rng)
        b = power_moments(zs, ws)
        t = rng.uniform(0.0, 1.0)
        assert msm_lookup(b, t) <= vsm_bound(b, t) + TOL


def test_moment_bias_costs_at_most_half_alpha():
    rng = random.Random(4)
    for _ in range(300):
        zs, ws = random_distribution(rng)
        b = power_moments(zs, ws)
        alpha = rng.choice([3e-5, 1e-3, 0.05])
        zf = rng.uniform(0.01, 1.0)
        lit = 1 - occluded(zs, ws, zf)
        assert msm_lookup(b, zf, alpha=alpha) >= lit - alpha / 2 - TOL


def test_bias_makes_two_point_maps_usable():
    # Two depths give a singular Hankel matrix; the moment bias fixes it.
    b = power_moments([0.1, 0.9], [1, 1])
    got = msm_lookup(b, 1.0, alpha=3e-5)
    assert 0.0 <= got <= 1.0
    try:
        shadow_intensity(b, 1.0)
    except ValueError:
        pass
    else:
        raise AssertionError("an unbiased two-point map must be rejected")


def test_receiver_in_front_is_lit():
    rng = random.Random(5)
    for _ in range(200):
        zs, ws = random_distribution(rng)
        b = power_moments(zs, ws)
        zf = rng.uniform(-0.5, zs[0])
        assert abs(msm_lookup(b, zf) - 1.0) < TOL

History

The bound that moment shadow mapping uses is a classical result on the moment problem, treated in the book of Krein and Nudel'man (1977) on the Markov moment problem. Peters and Klein brought it to shadows at I3D 2015, as the next step after the two moments of variance shadow maps. They gave a closed form for four moments that fits in a pixel shader, the moment bias, and a quantization of the moments for 64 bits per texel. Later work by Peters and others used the same bounds for transparency and for other filterable signals.

References

  1. Christoph Peters and Reinhard Klein, Moment shadow mapping, Proceedings of the 19th Symposium on Interactive 3D Graphics and Games (I3D 2015), 7 to 14, the Hamburger 4MSM lookup (the Cholesky solve, the quadratic and the three cases), the moment bias with alpha = 3e-5 in the supplementary Algorithm 3, and the comparison with variance shadow maps
  2. M. G. Krein and A. A. Nudel'man, The Markov Moment Problem and Extremal Problems, Translations of Mathematical Monographs 50, American Mathematical Society, 1977, Theorem IV.3.1 (the sharp bound from the canonical representation, as cited by Peters and Klein)
  3. 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 filtered shadow maps (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.

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