Algorithmadvanced
Weighted blended order-independent transparency
Also called weighted blended OIT.
Approximate the over operator by a weighted average of the transparent colors with depth-based weights, computed in one pass with additive blending.
- Time
- O(f + p) frameO(k) per_pixel
- Space
- O(p) frameO(1) per_pixel
- Where
- f = the number of fragments in the frame; k = the number of fragments of a pixel; p = the number of pixels
- Model
- Real RAM
- Properties
- deterministicnot in placeonlineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Morgan McGuire, Louis Bavoil, 2013
Weighted blended order-independent transparency is a one-pass approximation for order-independent transparency. It does not sort the fragments. Instead, it replaces the color part of the over operator by a weighted average of the fragment colors, and keeps the part that tells how much of the background shows through, which is a product and needs no order. The weight of each fragment is a function of its depth and opacity, larger for nearer fragments. On a GPU the whole method is two render targets with fixed blend modes and one full-screen pass, with a constant amount of memory per pixel. McGuire and Bavoil published it in 2013. The coverage is exact; the color is exact only in special cases, and the weight function is tuning.
In plain words
Blending glass over glass in the right order needs a sort, and a sort per pixel is slow on a GPU. This method gives up the exact answer. It adds up the colors of all transparent layers, each multiplied by a weight, and divides by the sum of the weights, so the result is an average color. Separately, it multiplies together how much light each layer lets through, which gives the exact amount of background that shows. Nearer layers get larger weights, so they count more, as they would in a correct blend. When all the layers have about the same color, the result is right. When a red pane is in front of a blue pane, the result is a mix that is too even.
The problem
The input is, for each pixel, an opaque background color and the transparent fragments of that pixel in the order in which the rasterizer produces them: is the premultiplied linear color, the opacity and the view depth, smaller is nearer. The exact output is the composite in depth order defined on the problem page:
The method must work in one geometry pass with memory per pixel and blend operations that are commutative, so that the arrival order does not matter. Its output is
for weights .
The algorithm
The loop runs over the fragments of one pixel in arrival order. On a GPU, lines L1 to L5 are the blend units of two render targets, and lines L6 and L7 are a full-screen composite pass.
WEIGHTED-BLENDED-OIT(fragments, C0, WEIGHT, ε)- 1
A ← 0 (one sum per color channel); Aα ← 0; R ← 1 - 2
for each fragment (c, α, z) of the pixel, in arrival order - 3
w ← WEIGHT(c, α, z) - 4
A ← A + c w; Aα ← Aα + α w ▷ additive blending - 5
R ← R (1 - α) ▷ multiplicative blending - 6
avg ← A / max(Aα, ε) - 7
return avg (1 - R) + C0 R
The render targets (lines L4 and L5). The first target holds in a 16-bit or 32-bit float RGBA format. The fragment shader writes and the blend mode is ONE, ONE, an addition. The second target holds in one channel, cleared to 1. The shader writes and the blend mode is ZERO, ONE_MINUS_SRC_ALPHA, so the stored value is multiplied by . Both blends commute, so the order of the fragments does not matter. The depth test is on against the opaque depth buffer, with depth writes off.
The composite (lines L6 and L7). A full-screen pass reads both targets and blends over the opaque image with the factor . The guard stops a division by zero where no transparent fragment lies.
The weight (line L3). The weight should be larger for nearer fragments, because the exact weight of fragment is , which falls as more fragments lie in front of it. The method cannot know without the order, so it uses a fixed function of depth. McGuire's blog post of 2014 gives
where the code of this page uses the positive view depth for and the premultiplied color for . The first factor makes nearly invisible fragments count little. The constants suit a depth range of a few hundred units and must be tuned for other scenes; the clamp keeps the weights inside the range of a 16-bit float.
Example
A red fragment with , lies in front of a blue fragment with , , over black. The exact result is .
| weights (red, blue) | error per channel | ||||
|---|---|---|---|---|---|
| 1, 1 | 1 | 0.125 | |||
| 3, 1 | 2 | 0.0625 | |||
| 2, 1 | 1.5 | 0 |
In all rows , so , the exact coverage. The weights 2 and 1 are in the ratio of the exact transmittances , and they give the exact result. With equal weights, the two panes are mixed half and half, and the red pane in front does not dominate. The order of the two fragments in the loop makes no difference in any row.
Correctness
The method is not exact in general, so correctness here means a list of exact statements, which the proofs folder proves and the tests check in exact rational arithmetic.
- Order independence. Lines L4 and L5 build two sums and a product, which do not depend on the order of their terms. The tests shuffle the fragments and get the same fraction each time.
- Exact coverage. is the same product as in the exact composite, so the background term is exact.
- A weighted mean. with , a convex combination of the unpremultiplied colors. The exact composite has the same form with replaced by , because by a telescoping sum.
- Exact weights. So if is proportional to , the result is exact. The tests build this order-dependent weight and check equality.
- Special cases. With one fragment, or with all fragments of one unpremultiplied color, the result is exact for every positive weight.
How close the result is for a real weight function is a measurement on a scene, not a theorem.
Proof: What weighted blended OIT gets exactly rightfull
Setting. A pixel has an opaque background color and fragments with premultiplied colors , opacities and distinct depths. Rename them so that (front to back). Let be the transmittance in front of fragment , so , and let . The exact composite is
The method takes weights and returns
All claims are in exact arithmetic, as in the tests, which use fractions. The guard of line L6 is assumed to be smaller than , so it does not change the result. Fragments with add nothing to any of the sums and are left out.
Lemma 1 (telescoping). .
Proof. , so . The sum telescopes to .
Theorem 1 (order independence and exact coverage). does not depend on the order in which the fragments arrive, and its background term is the background term of .
Proof. Lines L4 and L5 build two sums and a product. Addition and multiplication are commutative and associative, so the order of the loop does not change , or , provided that each depends only on its own fragment. is the same product as in .
In floating point, the sums and the product round differently for different orders, so the result depends on the order at the level of rounding.
Theorem 2 (the color is a weighted mean). Let be the unpremultiplied color of fragment and . Then , and
So in each channel, .
Proof. , so . The weights are positive and sum to 1. A convex combination lies between the smallest and the largest value in each channel, and .
The exact composite has the same form. By Lemma 1, with . The two results differ only in the mixing weights: is proportional to , and is proportional to .
Theorem 3 (exact weights). If for a constant , then .
Proof. Then by Lemma 1, and the two expressions of Theorem 2 are equal.
The weight needs the fragments in front of fragment , so it depends on the order that the method avoids. A weight that falls with depth is an approximation of by a function of alone, and how well it works depends on the scene.
Theorem 4 (special cases). for every choice of positive weights when (a) , or (b) all fragments have the same unpremultiplied color .
Proof. (a) With one fragment, . (b) Both convex combinations of Theorem 2 equal .
Theorem 5 (a counterexample). The method is not exact in general. Over a black background, let a red fragment , lie in front of a blue fragment , . Then . With equal weights, . With the weights 3 for red and 1 for blue, .
Proof. . Equal weights give the mean of the unpremultiplied colors and , times . The weights 3 and 1 give , so the mean is , times . The exact weights are , which give and .
Theorem 6 (cost). For a pixel with fragments and color channels, the method does arithmetic and keeps numbers.
Proof. Each fragment costs one weight evaluation, multiply-adds and one multiplication. The state is the color sums, the alpha sum and . Line L7 costs .
Complexity
The model is the real RAM. For a pixel with fragments, the method does work and keeps numbers: the color sums, the alpha sum and , which is 5 numbers for RGB. For a frame with transparent fragments over pixels, the geometry pass costs and the composite . At 1920 by 1080 pixels, an RGBA16F target and an R8 target take bytes, about 17.8 MiB, whatever the depth complexity. There is no sort and no list, so the memory is known before the frame.
Properties
- One geometry pass, bounded memory. No per-pixel storage grows with the number of fragments.
- Order independent. The result does not depend on the draw order, apart from floating-point rounding. Particles and other dynamic transparent geometry do not flicker when their order changes.
- Exact coverage, approximate color. The amount of background seen is right. The color is a weighted mean of the layers.
- Weight is tuning. The weight function depends on the depth range and the content of the scene.
- Deterministic. The same input gives the same output, except for rounding when the blend order changes on the GPU.
- No refraction order. Effects that need to know which surface is in front, such as refraction, are not supported by the average itself.
Variants and improvements
- Other weight functions. The paper gives several functions of depth with different falloffs. The choice is a trade between near and far layers in the scene at hand.
- Coverage only. Without the color targets, the second target alone gives the exact transmittance of all transparent surfaces, for example for colored shadow maps.
- Colored transmission. Keep per color channel, so that colored glass tints the background differently in each channel. The product stays order independent.
- Mixed methods. Render the nearest few layers exactly, for example with a small fragment array or depth peeling, and the rest with weighted blending.
- Moment-based and phenomenological methods. Later methods approximate the transmittance as a function of depth with a few moments per pixel and use it as the weight, at the cost of a second pass.
When to use it
Use it for particles, smoke, foliage cards, glass panels and other transparent content where many layers overlap, the layers have similar colors, or speed matters more than an exact order. It fits a deferred shading renderer as a forward pass after the opaque pass. Do not use it where a strongly colored surface in front must cover another strongly colored surface behind it, or where the exact image matters; then use per-pixel linked lists or depth peeling.
Pitfalls
- Overflow in 16-bit floats. Large weights times many layers overflow half floats, whose largest value is 65504. Clamp the weight, or use a 32-bit target.
- Wrong depth space. The constants of a weight function refer to a depth in given units. A nonlinear depth buffer value or a scene in other units changes the falloff.
- Opaque fragments. A fragment with sets , but its color is still averaged with the others. Draw opaque surfaces in the opaque pass.
- Premultiplied or not. The accumulation must use premultiplied colors. Mixing the two forms gives colors that are too dark or too bright.
- Division by zero. A pixel with no transparent fragment has . The guard or a test on avoids the division.
- Expecting exact results. Two strongly colored layers in the wrong ratio of weights give a visibly wrong mix, as the example shows.
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/weighted-blended-oit/. The authors are listed in prov/ZP9G80.jsonl.
"""Weighted blended order-independent transparency (McGuire and Bavoil 2013).
A fragment is (c, alpha, z): a premultiplied linear RGB color c, an opacity
alpha in [0, 1] and a positive view depth z (smaller is nearer). The method
accumulates, in any order,
A.rgb = sum c_i w_i, A.a = sum alpha_i w_i, R = prod (1 - alpha_i)
and returns (A.rgb / A.a) (1 - R) + C0 R. The coverage 1 - R is exact. The
color is a weighted average and is exact only in special cases.
All functions accept floats or fractions.Fraction values, so that the tests
can check the exact claims without rounding.
"""
from typing import Callable, Sequence
Color = tuple
Fragment = tuple # (c, alpha, z)
def over_composite(fragments: Sequence[Fragment], background: Color) -> Color:
"""The exact reference: sort by depth, then c over (... over C0)."""
result = tuple(background)
for c, a, _ in sorted(fragments, key=lambda f: f[2], reverse=True):
result = tuple(ci + (1 - a) * ri for ci, ri in zip(c, result))
return result
def transmittance(fragments: Sequence[Fragment]):
t = 1
for _, a, _ in fragments:
t = t * (1 - a)
return t
def constant_weight(c: Color, a, z):
return 1
def mcguire_blog_weight(c: Color, a: float, z: float) -> float:
"""The weight of McGuire's 2014 blog post, with c premultiplied (so the
unpremultiplied color times alpha is c itself). Tuning, not physics: the
constants 0.03, 200, 1e-2 and 3e3 suit a depth range of a few hundred units."""
m = max(min(1.0, max(c)), a)
return m * min(3e3, max(1e-2, 0.03 / (1e-5 + (z / 200.0) ** 4)))
def wboit(
fragments: Sequence[Fragment],
background: Color,
weight: Callable = mcguire_blog_weight,
eps=1e-5,
) -> Color:
"""Composite the fragments in the order given."""
n = len(background)
acc = [0] * n # @line L1
acc_a = 0
reveal = 1
for c, a, z in fragments: # @line L2
w = weight(c, a, z) # @line L3
for k in range(n): # @line L4
acc[k] = acc[k] + c[k] * w
acc_a = acc_a + a * w
reveal = reveal * (1 - a) # @line L5
denom = acc_a if acc_a > eps else eps
avg = [x / denom for x in acc] # @line L6
return tuple(avg[k] * (1 - reveal) + background[k] * reveal for k in range(n)) # @line L7
def visibility_weight(fragments: Sequence[Fragment]) -> Callable:
"""The order-dependent weight that makes the method exact: the product of
(1 - alpha) of all nearer fragments. It needs the sort that the method
avoids, so it is not a practical weight; the tests use it to check the
theory. The depths must be distinct."""
table = {}
t = 1
for _, a, z in sorted(fragments, key=lambda f: f[2]):
table[z] = t
t = t * (1 - a)
return lambda c, a, z: table[z]
test_weighted_blended_oit.py 134 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/weighted-blended-oit/. The authors are listed in prov/ZP9G80.jsonl.
"""Weighted blended OIT against exact sorted over compositing, in Fractions."""
import random
from fractions import Fraction as F
from weighted_blended_oit import (
constant_weight,
mcguire_blog_weight,
over_composite,
transmittance,
visibility_weight,
wboit,
)
def random_fragments(rng: random.Random, k: int, same_color=None):
frags = []
depths = rng.sample(range(1, 1000), k)
for z in depths:
a = F(rng.randint(1, 99), 100)
base = same_color or (F(rng.randint(0, 100), 100), F(rng.randint(0, 100), 100), F(rng.randint(0, 100), 100))
frags.append((tuple(a * x for x in base), a, F(z, 10)))
return frags
def rational_depth_weight(c, a, z):
"""A positive weight that falls with depth, in exact arithmetic. For the
depths of the tests (z < 100) and alpha >= 0.01 it keeps alpha * w above
the guard eps of wboit, so the guard never changes an exact result."""
return 1 / (1 + z / 10)
def test_coverage_is_exact_in_any_order() -> None:
rng = random.Random(41)
bg = (F(1, 5), F(2, 5), F(3, 5))
for _ in range(60):
frags = random_fragments(rng, rng.randint(1, 8))
rng.shuffle(frags)
# With a black background the alpha of the result is not needed;
# the transmittance is read from the blend of a white background.
white, black = (F(1),), (F(0),)
mono = [((F(0),), a, z) for _, a, z in frags]
assert wboit(mono, white, constant_weight) == over_composite(mono, white)
assert wboit(mono, black, rational_depth_weight)[0] == 0
assert transmittance(frags) == over_composite(mono, white)[0]
out = wboit(frags, bg, rational_depth_weight)
assert len(out) == 3
def test_order_independent_in_exact_arithmetic() -> None:
rng = random.Random(42)
bg = (F(1, 3), F(1, 7), F(0))
for _ in range(40):
frags = random_fragments(rng, rng.randint(2, 6))
ref = wboit(frags, bg, rational_depth_weight)
for _ in range(5):
rng.shuffle(frags)
assert wboit(frags, bg, rational_depth_weight) == ref
def test_exact_for_one_fragment() -> None:
rng = random.Random(43)
bg = (F(1, 2), F(1, 4), F(1, 8))
for _ in range(50):
frags = random_fragments(rng, 1)
assert wboit(frags, bg, rational_depth_weight) == over_composite(frags, bg)
def test_exact_when_all_colors_are_equal() -> None:
rng = random.Random(44)
bg = (F(1, 2), F(1, 4), F(1, 8))
color = (F(9, 10), F(3, 10), F(1, 10))
for _ in range(50):
frags = random_fragments(rng, rng.randint(1, 7), same_color=color)
for weight in (constant_weight, rational_depth_weight):
assert wboit(frags, bg, weight) == over_composite(frags, bg)
def test_exact_with_the_visibility_weight() -> None:
rng = random.Random(45)
bg = (F(1, 2), F(1, 4), F(1, 8))
for _ in range(50):
frags = random_fragments(rng, rng.randint(1, 7))
rng.shuffle(frags)
assert wboit(frags, bg, visibility_weight(frags)) == over_composite(frags, bg)
def test_red_and_blue_example() -> None:
red = ((F(1, 2), F(0), F(0)), F(1, 2), F(1))
blue = ((F(0), F(0), F(1, 2)), F(1, 2), F(2))
black = (F(0), F(0), F(0))
assert over_composite([red, blue], black) == (F(1, 2), F(0), F(1, 4))
assert wboit([red, blue], black, constant_weight) == (F(3, 8), F(0), F(3, 8))
near_first = wboit([red, blue], black, lambda c, a, z: 3 if z == 1 else 1)
assert near_first == (F(9, 16), F(0), F(3, 16))
def test_color_is_in_the_hull_times_coverage() -> None:
rng = random.Random(46)
black = (F(0), F(0), F(0))
for _ in range(50):
frags = random_fragments(rng, rng.randint(1, 6))
cov = 1 - transmittance(frags)
out = wboit(frags, black, rational_depth_weight)
for k in range(3):
lo = min(c[k] / a for c, a, _ in frags)
hi = max(c[k] / a for c, a, _ in frags)
assert lo * cov <= out[k] <= hi * cov
def test_blog_weight_is_positive_and_falls_with_depth() -> None:
c, a = (0.4, 0.2, 0.1), 0.5
prev = None
for z in (0.1, 1.0, 10.0, 50.0, 100.0, 200.0, 400.0, 1000.0, 1e5):
w = mcguire_blog_weight(c, a, z)
assert 0.0 < w <= 3e3
if prev is not None:
assert w <= prev
prev = w
assert mcguire_blog_weight(c, a, 1e5) == 0.5 * 1e-2
def test_float_run_is_close_to_exact() -> None:
rng = random.Random(47)
bg = (0.2, 0.3, 0.4)
for _ in range(30):
frags = random_fragments(rng, rng.randint(1, 6))
fl = [(tuple(float(x) for x in c), float(a), float(z)) for c, a, z in frags]
exact = wboit(frags, tuple(F(x) for x in bg), lambda c, a, z: F(mcguire_blog_weight(tuple(float(x) for x in c), float(a), float(z))))
approx = wboit(fl, bg)
assert all(abs(float(e) - x) < 1e-9 for e, x in zip(exact, approx))
History
The over operator of Porter and Duff (1984) needs a back-to-front order, and exact methods for unsorted fragments, such as the A-buffer and depth peeling, need memory or passes that grow with the depth complexity. Earlier one-pass methods replaced the over operator by sums of colors that did not depend on order, but they did not keep the coverage exact or did not weight the layers by depth. McGuire and Bavoil (2013) combined a weighted average of the colors with the exact product of the transmissions, gave weight functions of depth, and mapped the method to two render targets with standard blend modes. McGuire published shader code and a revised weight in a blog post in 2014.
References
- Morgan McGuire and Louis Bavoil, Weighted blended order-independent transparency, Journal of Computer Graphics Techniques 2(2), 122-141, 2013, the weighted average with the coverage term, the two render targets and their blend modes, and the weight functions of depth
- Morgan McGuire, Weighted blended order-independent transparency, Casual Effects blog, March 2014, the shader code and the weight function with the constants 0.03, 200, 1e-2 and 3e3
- Thomas Porter and Tom Duff, Compositing digital images, SIGGRAPH 1984, Computer Graphics 18(3), 253-259, the premultiplied alpha and the over operator that the method approximates
- 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 5.5, Transparency, Alpha, and Compositing (the part on order-independent methods)
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 ZP9G80 Edit this page History Report an error Markdown