Data structurecore
G-buffer
Also called geometry buffer.
A set of screen-sized images that stores, per pixel, the depth and the surface attributes of the nearest surface, such as the normal, the base color and the roughness, for a later shading pass.
- Time
- Θ(p m b) clearO(1) read · write
- Space
- Θ(p m b) total
- Where
- b = the number of bytes per pixel; m = the number of samples per pixel; p = the number of pixels
- Model
- Real RAM
- Properties
- not concurrentnot externalnot persistent
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Takafumi Saito, Tokiichiro Takahashi, 1990
A G-buffer is a group of screen-sized images, written in one geometry pass, that keeps for each pixel the depth and the surface attributes of the nearest surface: for example the normal, the base color, the roughness and the metallic value. Later passes read it instead of the triangles. It is the data structure under deferred shading, which shades each pixel once from these values, and under screen-space effects such as screen-space ambient occlusion. A visibility buffer is a smaller relative: it stores only a triangle id per pixel and computes the attributes again. Saito and Takahashi named the G-buffer in 1990. This page gives one layout as an example and the octahedral encoding of the normal, which is the most common way to store a normal in 32 bits.
In plain words
When the renderer draws the scene, it does not compute the light yet. For each pixel it only writes down facts about the surface that is closest to the camera: how far away it is, which way it faces, what color it is and how rough it is. These notes fill a few images of the same size as the screen. A later pass reads the notes for each pixel and computes the light from them, without going back to the triangles. The notes must be small, because there is one set for every pixel, so each value is packed into few bits. A direction, for example, is stored as two short numbers instead of three long ones.
The abstract type
A G-buffer of width and height holds records, one per pixel, or records with samples per pixel. Each record has the same fixed fields. The operations are:
- clear: set every record to the value of the background (the far depth and no surface).
- write(pixel, record): store the record of a fragment that passes the depth test. The geometry pass calls it, and the z-buffer test decides which fragment is kept.
- read(pixel): return the record. Lighting and screen-space passes call it.
After the geometry pass, the record of each pixel is the record of the fragment with the smallest depth at that pixel, which is the depth test invariant. The buffer holds one surface per pixel and sample. It cannot hold a second, partly hidden surface, so it has no place for transparent fragments.
Representation
Each field is a channel of one of a few render targets, and the GPU writes all targets of a pixel in one fragment shader call. The layout below is an example, not a standard. Engines differ in the fields, the formats and the number of targets.
| target | format | content | bytes |
|---|---|---|---|
| depth | 32-bit float | the depth of the nearest surface | 4 |
| RT0 | RGBA, 8 bits unorm each | base color (sRGB) and metallic | 4 |
| RT1 | RG, 16 bits snorm each | normal, octahedral code | 4 |
| RT2 | RGBA, 8 bits unorm each | roughness and 3 spare channels | 4 |
This layout uses bytes per pixel. The view-space position is not stored: the shading pass computes it from the depth and the pixel position.
The octahedral normal. A unit normal has two degrees of freedom, so three floats waste space. The octahedral map of Cigolle, Donow, Evangelakos, Mara, McGuire and Meyer (2014) divides by , which puts it on the octahedron . The upper half () projects straight down onto the diamond . The lower half is folded out over the four corners of the square . The square is then stored as two signed normalized integers of bits. The survey compares this map with many other unit-vector codes and finds it among the best in error for its size, at a low cost of encode and decode. That ranking is a measurement.
Operations
Lines L1 to L4 encode and lines L5 to L7 decode a normal. is for and for . The assignment in L3 and L6 is simultaneous: both new values use the old and . Lines L8 and L9 store a value of in bits with . Lines L10 to L15 write and read one texel of the example layout.
OCT-ENCODE(n)- 1
s ← |n.x| + |n.y| + |n.z| - 2
(u, v) ← (n.x / s, n.y / s) - 3
if n.z < 0 then (u, v) ← ((1 - |v|) sgn(u), (1 - |u|) sgn(v)) ▷ fold the lower half - 4
return (u, v) OCT-DECODE(u, v)- 5
z ← 1 - |u| - |v| - 6
if z < 0 then (u, v) ← ((1 - |v|) sgn(u), (1 - |u|) sgn(v)) ▷ unfold - 7
return (u, v, z) / ‖(u, v, z)‖ QUANTIZE(x, b) and DEQUANTIZE(q, b)- 8
q ← round(x · m) - 9
x ← max(-1, q / m) PACK-TEXEL(c, n, r, k) ▷ base color c, normal n, roughness r, metallic k- 10
word0 ← unorm8(c.r) | unorm8(c.g) << 8 | unorm8(c.b) << 16 | unorm8(k) << 24 - 11
word1 ← the two 16-bit codes QUANTIZE(OCT-ENCODE(n), 16), low half first - 12
word2 ← unorm8(r) UNPACK-TEXEL(word0, word1, word2)- 13
c ← the low three bytes of word0 / 255; k ← the high byte / 255 - 14
n ← OCT-DECODE(DEQUANTIZE of the two signed halves of word1) - 15
return (c, n, word2 / 255, k)
The sign rule matters. With the usual sign function, which is 0 at 0, a normal in the plane or with folds to a wrong point. The clamp in L9 is there because the integer has no partner; it maps to like .
Precise encoding. Rounding and separately does not always give the code that decodes closest to . The survey also gives an encoder that tries the four integer points around and keeps the one with the smallest angle error. It costs four decodes and helps when the normal is written once and read many times.
Example
Encode and decode. Take . Line L1 gives and line L2 gives . Since , line L3 folds: and . The code is , a point on the right edge of the square.
To decode, line L5 gives , which is negative, so line L6 unfolds to . Line L7 normalizes , whose length is , and returns .
With 8 bits. , so the code becomes the integers , because . Decoding gives , then after the unfold, and after normalizing. The angle error is degrees. With 16 bits () the code is , and since exactly, this normal decodes without error.
One texel. The base color , metallic 0, the normal above and roughness give the three words 0x00FF4080 (the bytes 128, 64, 255 and 0, low byte first), 0x49247FFF (the codes 32767 and 18724) and 0x00000066 (102, which is ).
Memory. At 1920 by 1080 pixels, , and the 16 bytes of the layout take bytes, about 31.6 MiB. With 4 samples per pixel for multisample antialiasing, every sample needs its own record, and the size is 126.6 MiB. These numbers are the reason for tight packing.
Correctness
The proofs are in the proofs folder. With and exact arithmetic:
- OCT-ENCODE maps every nonzero vector into , and OCT-DECODE(OCT-ENCODE) . The proof splits on the sign of and shows that the unfold undoes the fold, because the fold keeps the signs of and .
- On the open square the map is also one to one in the other direction: OCT-ENCODE(OCT-DECODE) . On the border, and decode to the same vector, and the four corners all decode to .
- Quantization moves each coordinate by at most . The angle error after decoding is not proved here. The values in the tests are measurements on 4000 random directions: below 1 degree with 8 bits and below 0.005 degrees with 16 bits, and the precise encoding is never worse.
- The texel pack and unpack return each 8-bit value to within and give the normal of the 16-bit code.
The depth test invariant of the abstract type is a property of the z-buffer, see its page.
Proof: The octahedral normal encoding is a round tripfull
Setting. for and for , so that . The fold is . OCT-ENCODE (lines L1 to L4) maps a nonzero vector to with if , and to if . OCT-DECODE (lines L5 to L7) maps to the normalized vector of if , and of otherwise. The claims are in exact arithmetic.
Lemma 1 (the image is in the square). For every nonzero , OCT-ENCODE.
Proof. , so both coordinates are in . The fold keeps them there, because and are in when .
Theorem 1 (round trip). For every nonzero , OCT-DECODE(OCT-ENCODE) .
Proof. Let , , . Then , so is scaled by the positive number .
Case . The encoder returns . The decoder computes , which is not negative, so it does not fold. It returns the normalized vector of , which is .
Case . Then , so and . The encoder returns , with and . So and ; this needs when or is 0. The decoder computes , so it folds:
It returns the normalized vector of , which is again .
Theorem 2 (the other direction). For every in the open square , OCT-ENCODE(OCT-DECODE) .
Proof. The decoder computes a vector proportional to with : for , with ; otherwise and , and . So with , the encoder computes , and it gets , with the sign of equal to the sign of . In the first case it returns . In the second case it returns . Here , so and , the signs are kept, and as in Theorem 1.
On the border of the square the map is not one to one: and decode to the same vector, and all four corners decode to . The encoder returns one of these points. This does not affect Theorem 1.
Theorem 3 (quantization). With bits per coordinate and , QUANTIZE (line L8) followed by DEQUANTIZE (line L9) changes each coordinate in by at most .
Proof. differs from by at most , and , so the result is in and the clamp in line L9 does not act on it. Dividing by gives the bound.
The angle error that this coordinate error causes after decoding depends on where the point is in the square. The largest values on the page and in the tests (below 1 degree for 8 bits and below 0.005 degrees for 16 bits per coordinate) are measurements on random directions, not proved bounds.
Theorem 4 (the texel layout). UNPACK-TEXEL(PACK-TEXEL) returns each color channel, the roughness and the metallic value to within of the input, after clamping to , and returns the normal of the 16-bit octahedral code of .
Proof. Each unorm8 value is , so it fits in 8 bits, the shifts put the four values in disjoint bytes of word 0, and the masks in the unpack read them back unchanged. Division by 255 gives a value within of . The two 16-bit codes are stored as two's complement in the two halves of word 1 and read back with sign extension, so DECODE receives the same pair of integers.
Complexity
The model is the real RAM with pixels, samples per pixel and bytes per record. A write and a read are . A clear is in bytes, though GPUs often clear with a fast metadata flag. The space is . The encode and decode of a normal take operations and one square root.
On a GPU the cost that matters is memory bandwidth. The geometry pass writes bytes for every fragment that passes the depth test, including fragments that a nearer fragment later overwrites, and each lighting or screen-space pass reads bytes per pixel. A layout with fewer bytes per pixel is often faster even when it needs more arithmetic to decode. This is the trade that the octahedral code makes, see memory coalescing.
Variants
- Thin G-buffer. Only depth and normal, for a light pre-pass: the lights are accumulated into a light buffer, and a second geometry pass reads it to apply the materials.
- Visibility buffer. Only the triangle id and the instance id. The visibility buffer page explains the trade.
- Other normal codes. Spherical coordinates, a stored with computed from them (wrong for normals that face away from the camera, which occur with normal maps and perspective), and the sphere map code. The survey of Cigolle and coauthors compares them.
- Material ids. Some layouts store a small material or shading model id per pixel, so that the shading pass can branch per pixel. This costs bits and can cause warp divergence.
- Multisample G-buffer. One record per sample, with a resolve that shades edge pixels per sample and inner pixels once.
When to use it
Use a G-buffer when many lights or screen-space passes need the surface attributes of each pixel, and the cost of reading them back is lower than the cost of drawing the geometry again. Keep it as small as the materials allow. Use a visibility buffer when the G-buffer bandwidth is the limit, for example at high resolution or with many samples per pixel. Do not use it for transparent surfaces: draw them in a forward pass after the deferred pass.
Pitfalls
- The sign of zero. Use a sign function with in the fold, or normals with or in the lower half decode wrong.
- The code with assumed. View-space normals can point away from the camera, so the sign of must be stored.
- Base color in the wrong space. Store the base color in an sRGB format, which the hardware converts, or in linear values with more bits. 8-bit linear values band in dark areas.
- Interpolating codes. Do not filter the encoded normal across pixels: the code is not linear, and the fold edges give wrong values. Decode first.
- Precision of depth. If the position is computed from the depth, the depth format sets its precision. A 24-bit depth with a standard projection loses precision far from the camera.
- Bandwidth of MSAA. With samples per pixel the buffer is times larger.
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/g-buffer/. The authors are listed in prov/P04D18.jsonl.
"""A G-buffer texel with an octahedral normal, after Cigolle et al. (2014).
The octahedral map projects a unit vector onto the octahedron
|x| + |y| + |z| = 1, keeps the upper half as it is, and folds the lower half
out over the four corners of the square [-1, 1]^2. The square is then stored
as two signed normalized integers of b bits each.
The texel layout is an example, not a standard: three 32-bit words, with the
base color and the metallic value in unorm8, the normal in two snorm16 values
and the roughness in unorm8. The depth is kept in the depth buffer.
"""
import math
Vec3 = tuple[float, float, float]
def sign_not_zero(x: float) -> float:
"""+1 for x >= 0 and -1 for x < 0. The fold needs sign(0) = +1."""
return 1.0 if x >= 0.0 else -1.0
def normalize(v: Vec3) -> Vec3:
length = math.sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2])
return (v[0] / length, v[1] / length, v[2] / length)
def oct_encode(n: Vec3) -> tuple[float, float]:
"""Map a nonzero vector to a point of the square [-1, 1]^2."""
s = abs(n[0]) + abs(n[1]) + abs(n[2]) # @line L1
u, v = n[0] / s, n[1] / s # @line L2
if n[2] < 0.0: # @line L3
u, v = (1.0 - abs(v)) * sign_not_zero(u), (1.0 - abs(u)) * sign_not_zero(v)
return u, v # @line L4
def oct_decode(u: float, v: float) -> Vec3:
"""Map a point of the square back to a unit vector."""
z = 1.0 - abs(u) - abs(v) # @line L5
if z < 0.0: # @line L6
u, v = (1.0 - abs(v)) * sign_not_zero(u), (1.0 - abs(u)) * sign_not_zero(v)
return normalize((u, v, z)) # @line L7
def quantize_snorm(x: float, bits: int) -> int:
"""Store x in [-1, 1] as a signed integer of the given width."""
m = (1 << (bits - 1)) - 1
return round(max(-1.0, min(1.0, x)) * m) # @line L8
def dequantize_snorm(q: int, bits: int) -> float:
m = (1 << (bits - 1)) - 1
return max(-1.0, q / m) # @line L9
def encode_normal(n: Vec3, bits: int) -> tuple[int, int]:
u, v = oct_encode(n)
return quantize_snorm(u, bits), quantize_snorm(v, bits)
def decode_normal(q: tuple[int, int], bits: int) -> Vec3:
return oct_decode(dequantize_snorm(q[0], bits), dequantize_snorm(q[1], bits))
def encode_normal_best(n: Vec3, bits: int) -> tuple[int, int]:
"""Try the four integer neighbors of the encoded point and keep the one
that decodes closest to n. Cigolle et al. call this the precise encoding."""
u, v = oct_encode(n)
m = (1 << (bits - 1)) - 1
best = None
best_dot = -2.0
for qu in (math.floor(u * m), math.floor(u * m) + 1):
for qv in (math.floor(v * m), math.floor(v * m) + 1):
q = (max(-m, min(m, qu)), max(-m, min(m, qv)))
d = decode_normal(q, bits)
dot = d[0] * n[0] + d[1] * n[1] + d[2] * n[2]
if dot > best_dot:
best, best_dot = q, dot
return best
def unorm8(x: float) -> int:
return round(max(0.0, min(1.0, x)) * 255.0)
def pack_texel(albedo: Vec3, normal: Vec3, roughness: float, metallic: float) -> tuple[int, int, int]:
"""The geometry pass writes one texel: three 32-bit words."""
r, g, b = (unorm8(c) for c in albedo)
word0 = r | (g << 8) | (b << 16) | (unorm8(metallic) << 24) # @line L10
qu, qv = encode_normal(normal, 16)
word1 = (qu & 0xFFFF) | ((qv & 0xFFFF) << 16) # @line L11
word2 = unorm8(roughness) # @line L12
return word0, word1, word2
def to_signed16(x: int) -> int:
return x - 0x10000 if x & 0x8000 else x
def unpack_texel(words: tuple[int, int, int]) -> tuple[Vec3, Vec3, float, float]:
"""The lighting pass reads the texel back."""
word0, word1, word2 = words
albedo = tuple((word0 >> s & 0xFF) / 255.0 for s in (0, 8, 16)) # @line L13
metallic = (word0 >> 24 & 0xFF) / 255.0
q = (to_signed16(word1 & 0xFFFF), to_signed16(word1 >> 16 & 0xFFFF))
normal = decode_normal(q, 16) # @line L14
roughness = (word2 & 0xFF) / 255.0
return albedo, normal, roughness, metallic # @line L15
test_g_buffer.py 106 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/g-buffer/. The authors are listed in prov/P04D18.jsonl.
"""Tests of the octahedral normal encoding and of the example texel layout."""
import math
import random
from g_buffer import (
decode_normal,
encode_normal,
encode_normal_best,
normalize,
oct_decode,
oct_encode,
pack_texel,
unpack_texel,
)
def random_unit(rng: random.Random) -> tuple[float, float, float]:
while True:
v = (rng.gauss(0.0, 1.0), rng.gauss(0.0, 1.0), rng.gauss(0.0, 1.0))
if v[0] * v[0] + v[1] * v[1] + v[2] * v[2] > 1e-6:
return normalize(v)
def angle_deg(a, b) -> float:
d = a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
return math.degrees(math.acos(max(-1.0, min(1.0, d))))
def close(a, b, tol: float = 1e-12) -> bool:
return all(abs(x - y) <= tol for x, y in zip(a, b))
def test_axes_and_corners() -> None:
assert oct_encode((0.0, 0.0, 1.0)) == (0.0, 0.0)
assert oct_encode((1.0, 0.0, 0.0)) == (1.0, 0.0)
assert oct_encode((0.0, -1.0, 0.0)) == (0.0, -1.0)
# The south pole goes to a corner; all four corners decode to it.
assert oct_encode((0.0, 0.0, -1.0)) == (1.0, 1.0)
for u, v in ((1.0, 1.0), (-1.0, 1.0), (1.0, -1.0), (-1.0, -1.0)):
assert close(oct_decode(u, v), (0.0, 0.0, -1.0))
def test_round_trip_float() -> None:
rng = random.Random(7)
for _ in range(3000):
n = random_unit(rng)
u, v = oct_encode(n)
assert -1.0 <= u <= 1.0 and -1.0 <= v <= 1.0
assert close(oct_decode(u, v), n)
def test_round_trip_on_signed_zeros_and_equator() -> None:
for n in ((0.0, 0.6, -0.8), (0.6, 0.0, -0.8), (-0.6, -0.0, -0.8), (0.6, 0.8, 0.0), (-0.8, 0.6, -0.0)):
assert close(oct_decode(*oct_encode(n)), normalize(n))
def test_square_to_sphere_to_square() -> None:
"""On the open square the map is one to one, so encode(decode(p)) = p."""
rng = random.Random(8)
for _ in range(3000):
u, v = rng.uniform(-0.999, 0.999), rng.uniform(-0.999, 0.999)
p = oct_encode(oct_decode(u, v))
assert abs(p[0] - u) < 1e-12 and abs(p[1] - v) < 1e-12
def test_decode_is_unit() -> None:
rng = random.Random(9)
for _ in range(2000):
d = oct_decode(rng.uniform(-1.0, 1.0), rng.uniform(-1.0, 1.0))
assert abs(d[0] ** 2 + d[1] ** 2 + d[2] ** 2 - 1.0) < 1e-12
def test_quantized_error_measured() -> None:
"""Measured largest angle errors on 4000 random directions. These are
measurements on this sample, not proved bounds."""
rng = random.Random(10)
worst = {8: 0.0, 16: 0.0}
worst_best = {8: 0.0, 16: 0.0}
for _ in range(4000):
n = random_unit(rng)
for bits in (8, 16):
worst[bits] = max(worst[bits], angle_deg(n, decode_normal(encode_normal(n, bits), bits)))
worst_best[bits] = max(worst_best[bits], angle_deg(n, decode_normal(encode_normal_best(n, bits), bits)))
assert worst[8] < 1.0 and worst[16] < 0.005
assert worst_best[8] <= worst[8] and worst_best[16] <= worst[16]
def test_texel_round_trip() -> None:
rng = random.Random(11)
for _ in range(500):
albedo = (rng.random(), rng.random(), rng.random())
n = random_unit(rng)
rough, metal = rng.random(), rng.random()
words = pack_texel(albedo, n, rough, metal)
assert all(0 <= w < 1 << 32 for w in words)
a2, n2, r2, m2 = unpack_texel(words)
assert all(abs(x - y) <= 0.5 / 255.0 + 1e-12 for x, y in zip(albedo, a2))
assert abs(rough - r2) <= 0.5 / 255.0 + 1e-12
assert abs(metal - m2) <= 0.5 / 255.0 + 1e-12
assert angle_deg(n, n2) < 0.005
again = pack_texel(a2, n2, r2, m2)
assert again[0] == words[0] and again[2] == words[2]
History
Deering, Winner, Schediwy, Duffy and Hunt built a hardware pipeline in 1988 that found the visible surface first and then shaded each pixel from its stored normal. Saito and Takahashi (1990) gave the stored per-pixel geometry the name G-buffer, and used it for image-space operations: edges, contours and hatching for illustration. In games, deferred shading with a G-buffer became common in the late 2000s, when GPUs could write several render targets at once. The octahedral normal map was used in graphics before 2014; the survey by Cigolle, Donow, Evangelakos, Mara, McGuire and Meyer compared it with the other codes and made it a standard choice.
References
- Takafumi Saito and Tokiichiro Takahashi, Comprehensible rendering of 3-D shapes, SIGGRAPH 1990, Computer Graphics 24(4), 197-206, the geometric buffers (G-buffers) and the image-space operations on them
- Zina H. Cigolle, Sam Donow, Daniel Evangelakos, Michael Mara, Morgan McGuire and Quirin Meyer, A survey of efficient representations for independent unit vectors, Journal of Computer Graphics Techniques 3(2), 1-30, 2014, the octahedral representation, its encode and decode, and the precise encoding that tests the nearby integer codes
- Michael Deering, Stephanie Winner, Bic Schediwy, Chris Duffy and Neil Hunt, The triangle processor and normal vector shader: a VLSI system for high performance graphics, SIGGRAPH 1988, 21-30, the shading of each pixel from a stored normal after the visibility stage
- Tomas Akenine-Möller, Eric Haines, Naty Hoffman, Angelo Pesce, Michał Iwanicki and Sébastien Hillaire, Real-Time Rendering, fourth edition, CRC Press, 2018, Chapter 20, Efficient Shading (the part on deferred shading and G-buffer layouts)
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| 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 | W4 complete |
|
Tag P04D18 Edit this page History Report an error Markdown