Data structureadvanced
Texture clipmap
Also called clipmap.
A mipmap whose finer levels are clipped to a fixed-size window around the viewer, so that very large textures fit in a bounded memory.
- Time
- Θ(C^2 (1 + log(N/C))) buildO(1) lookupO(C (d + log(N/C))) recenter
- Space
- Θ(C^2 (1 + log(N/C))) total
- Where
- C = the clip size in texels; N = the side of the finest level in texels; d = the number of finest-level texels by which the center moves, along one axis
- Model
- Real RAM
- Properties
- not concurrentexternalnot persistent
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Christopher C. Tanner, Christopher J. Migdal, Michael T. Jones, 1998
A texture clipmap is a mipmap in which every level larger than a clip size keeps only a window of texels around a clip center, the point of the texture that the viewer looks at; the levels of size or less are kept whole. A full mipmap of a texture takes about 358 million texels, and a clipmap with takes 1.66 million. Virtual texturing keeps the pages that the view needs, wherever they are, with a page table; the clipmap keeps fixed windows around one point, so it needs no table, and a lookup only has to find the finest level whose window holds the point. Geometry clipmaps use the same nested windows for the heights of a terrain.
In plain words
A huge photo of the ground is too big for the graphics card, and a viewer near the ground sees fine detail only close by. Far away, the coarse versions of the photo are enough.
So keep each coarse version of the photo whole while it is small. For each large version, keep only a square of fixed size around the place under the viewer. The squares of the finer versions cover smaller areas, and the coarsest versions cover everything.
To color a point, use the finest version whose square holds that point. When the viewer moves, each square moves with them. Only the strip of new texels on one side is loaded, and it goes into the place of the strip that drops off the other side.
The abstract type
A texture clipmap of a texture with the mipmap levels (finest, ) to (one texel) has these operations.
- build(c): make the clipmap for the clip center .
- recenter(c): change the clip center to , so that every clipped level holds its new window.
- lookup(u, v, lambda): the filtered sample at the point for the level of detail that the hardware computes, but from a coarser level if the window of level does not hold the point.
Inside the windows, lookup gives the same value as the full mipmap. Outside, it gives a value of a coarser level, which is a blur, not a wrong texel.
Representation
Level has texels along each side. The levels with form the clip stack: each is an array of texels. The clip center at level is per coordinate, and the window of level is the square of texels with in each coordinate. The texel is stored at the slot , a toroidal address as in a circular buffer, so a texel that stays in the window keeps its slot when the center moves. The levels with form the clip pyramid and are stored whole, as in a mipmap.
In level 0 units the window of level is a square of side , so each level of the stack covers four times the area of the level before it, and the pyramid covers the whole texture. The full texture stays on disk or in main memory, and the stack is filled from it.
Operations
RECENTER(c) ▷ the new clip center, in level 0 texels- 1
for each level l of the clip stack do - 2
c_l ← floor(c / 2^l) ▷ per coordinate - 3
for each texel t with c_l - C/2 ≤ t < c_l + C/2 that is not in the old window do - 4
S_l[t_x mod C, t_y mod C] ← texel t of level l, read from the full texture - 5
the window of level l ← the new window LOOKUP(u, v, λ) ▷ λ from the texel footprint, as for a mipmap- 6
l_min ← the smallest l such that the levels l, l + 1, ... all hold the bilinear taps of (u, v) - 7
l ← max(λ, l_min) - 8
return the trilinear sample between the levels floor(l) and floor(l) + 1
BUILD is RECENTER with every texel new, plus the fill of the pyramid. The pyramid levels hold every point. The code finds in line L6 by a walk from the coarsest level down, in steps. A renderer can compute it in : a window of level reaches about level 0 texels from the center, so follows from the largest coordinate distance between and with a logarithm, and a margin of a few texels covers the filter; that margin is a tuning.
Example
Take a texture and . The levels have the sides 16384, 8192, ..., 1. The five levels of side 16384 to 1024 form the stack, with texels. The pyramid holds the levels of side 512 to 1, with texels. So the clipmap has 1,660,245 texels, against 357,913,941 for the full mipmap: 215.6 times fewer. At 4 bytes per texel, that is 6.64 MB in place of 1.43 GB.
A lookup. The clip center is and the point is at the level 0 texel , with .
| level | center | the point at this level | window holds the point |
|---|---|---|---|
| 0 | no, | ||
| 1 | yes | ||
| 2 | yes |
So line L6 gives , and the lookup returns a sample of level 1 where the full mipmap would give level 0. The point is 400 texels from the center, and the full level 0 detail reaches only 256.
A move. Moving the center by 64 texels of level 0 in moves the windows of the levels 0 to 4 by 64, 32, 16, 8 and 4 texels. Line L4 then loads texels, against 1,310,720 for a reload of the whole stack.
Correctness
The proof file gives the arguments. The tests compare the stack after 60 random moves with a fresh fill and with the full mipmap, and compare 800 lookups with trilinear samples of the full mipmap.
- One slot per texel. The texels of a window have, in each coordinate, consecutive values, which have distinct residues mod . So the toroidal slots of line L4 are one to one on a window (a proved property).
- The update. A texel in both the old and the new window keeps its slot and its value, and line L4 writes each new texel. So after line L5 each stack level holds exactly its new window, as a fresh fill would (a proved property).
- The lookup. The lookup reads only texels inside the windows, and it returns the trilinear sample of the full mipmap at . So if , it equals the sample of the full mipmap. Otherwise , and the sample comes from a coarser level of the same mipmap, so it is a blurred value of the right image (a proved property of the structure; how visible the blur is depends on the scene).
- Nesting. In level 0 units the window of level is in each coordinate, and lies in . Comparing the two ends with those of level shows that for each window lies inside the next coarser one. So the levels that hold a point are and all coarser ones, and line L6 is well defined (a proved property).
Proof: The toroidal clip stack equals a fresh fill after every move, the windows nest for clip sizes of at least four, and a lookup equals a full mipmap sample at the level it usesfull
We use the notation of the page and the code. Level has the side , and the levels with form the clip stack; is even. For a clip center (integer level 0 texels), per coordinate, and the window is the set of texels with in each coordinate. The slot of the texel of a stack level is . The texel values of the full mipmap are .
The slots
Lemma 1. For each and , is one to one on .
Proof. In each coordinate the texels of the window take consecutive integer values, and consecutive integers have distinct residues mod . So two texels of the window with the same slot have the same and the same .
The update
Proposition 2. After RECENTER (lines L1 to L5), for each stack level the window is and the slot holds for every texel of inside the texture. The call writes exactly the texels of that are not in the old window. So the stack equals the stack of a fresh build at .
Proof. By induction on the calls. For the first call (from the constructor) there is no old window, so lines L3 and L4 write every texel of , each to its own slot by Lemma 1. For a later call, let be the old window, with holding for by induction. A texel is skipped, and its slot still holds : a write in this call goes to the slot of a texel , and by Lemma 1 on . Each texel of is written by line L4 with its value. Line L5 sets the window. The writes are exactly the texels of , and the contents of the slots depend only on , as for a fresh build.
If the center moves by level 0 texels along one axis, moves by at most , and the new texels form a strip of at most that many columns of texels. So a move writes at most texels at level , and over the stack. When is a multiple of , the rounding does not change the shifts, and the count is exactly ; the test checks for and .
The windows nest
Lemma 3. If , then for every and , the window of level lies inside the window of level when both are written in level 0 units.
Proof. Let , so that in each coordinate. In level 0 units the window of level is the interval in each coordinate. On the low side,
where the middle step is , that is . On the high side,
where the middle step is , that is .
The pyramid levels hold the whole texture. So by Lemma 3 the set of levels whose window holds a given texel position is all levels from some level on. The bilinear taps of a coarser level reach a little farther from the point than those of a finer level, so line L6 defines as the smallest such that every level from on holds the taps; it exists because the coarsest level is in the pyramid or, if , there is no stack.
The lookup
Proposition 4. For every point in the texture and every , LOOKUP reads only texels of the windows, and it returns the trilinear sample of the full mipmap at the level of detail .
Proof. Line L7 sets . The trilinear sample of line L8 reads the bilinear taps of the levels and, if the fraction is not zero, . Both are at least , so by the definition of line L6 their taps are in the windows. The taps are clamped to the texture, so they are texels inside it. By Proposition 2 each slot that is read holds , and the pyramid levels are the mipmap levels. So each read value equals the value that the full mipmap gives, and the weights depend only on and .
So when , the lookup equals the sample of the full mipmap at . When , it equals the sample at the coarser level , a blurred value of the same image. The tests check Proposition 2 after 60 random moves, Lemma 3 for and random centers, and Proposition 4 on 800 random lookups.
Complexity
| operation | time | note |
|---|---|---|
| build | each stack level and the pyramid once | |
| recenter | a move by level 0 texels along one axis writes at most texels at level ; the is the rounding of | |
| lookup | the level from the distance to the center, then a mipmap sample; the walk of the code takes |
The space is : texels for each of the stack levels, and less than for the pyramid. The full mipmap needs . The cost of a recenter is dominated in practice by the reads from disk or main memory, which is why the structure is external.
Variants
- Virtual texturing. Virtual texturing splits all levels into pages and keeps the pages that the frame uses, with a page table per lookup. It serves views where the needed texels are not around one point, such as many objects with their own textures.
- Geometry clipmaps. Geometry clipmaps use the same stack for the heights of a terrain, with the window centered on the viewer.
- Several centers. A scene with two areas of interest, such as two viewers, needs two stacks or larger windows; the clipmap serves one center well.
- Updates over several frames. A large move can load the new strips over several frames, and the lookup uses a coarser level until a strip is complete, which a margin in line L6 makes safe.
When to use it
Use a texture clipmap for one very large texture seen from a viewer that moves over it, such as satellite images on a terrain in a flight simulator or a map viewer, when the full mipmap does not fit in texture memory. If the texels in view are spread over many textures, or the view jumps far from frame to frame, virtual texturing fits better. If the texture fits in memory, a plain mipmap is simpler.
Pitfalls
- An address relative to the window. If line L4 stores the texel at in place of , the slot of every texel changes when the center moves, and each move must copy the whole stack.
- No margin for the filter. If line L6 tests only the point and not its footprint, a bilinear or trilinear sample near the border of a window reads texels outside it, which hold values of the opposite side of the window.
- The wrong level. If line L7 uses in place of , the lookup can read a finer level than the hardware asked for, and the texture aliases; or, with a window that does not hold the point, it reads a wrong texel.
- One center for all levels without rounding. If line L2 uses without the floor, the windows of the levels do not start on texel borders, and the test of line L6 and the slots of line L4 disagree by one texel.
- A visible edge between levels. Where jumps from one level to the next across the image, the sharpness changes along a line. Blending between and in line L8 with a fractional near the border hides 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.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/texture-clipmap/. The authors are listed in prov/NPGSAB.jsonl.
"""A texture clipmap: a mipmap whose levels larger than C keep a C x C window.
Texel coordinates are integers, level 0 is the finest level of side N, and
level l has side N / 2^l. The clip center c is a level 0 texel. A level of
the clip stack stores its window in a C x C array with toroidal addressing;
the levels of side C or less (the clip pyramid) are kept whole. Sample
points (u, v) are in level 0 texel units, with texel centers at i + 1/2.
Values are exact fractions.
"""
from fractions import Fraction
from math import floor
def build_mipmap(tex):
"""All levels of a square power-of-two texture, by 2 x 2 box averages."""
levels = [[[Fraction(x) for x in row] for row in tex]]
while len(levels[-1]) > 1:
a = levels[-1]
m = len(a) // 2
levels.append(
[[Fraction(a[2 * i][2 * j] + a[2 * i + 1][2 * j] + a[2 * i][2 * j + 1] + a[2 * i + 1][2 * j + 1], 4) for j in range(m)] for i in range(m)]
)
return levels
def window(c, l, C):
"""The half-open window (x0, y0, x1, y1) of level l for the clip center c."""
cx, cy = c[0] // 2 ** l, c[1] // 2 ** l
return (cx - C // 2, cy - C // 2, cx + C // 2, cy + C // 2)
def in_window(w, t):
return w[0] <= t[0] < w[2] and w[1] <= t[1] < w[3]
def texel_counts(N, C):
"""The texels of the clipmap and of the full mipmap of an N x N texture."""
sides = []
s = N
while s >= 1:
sides.append(s)
s //= 2
return sum(min(s, C) ** 2 for s in sides), sum(s * s for s in sides)
def taps(size, u, v, l):
"""The bilinear taps of level l at (u, v), with clamp addressing, and the weights."""
x = Fraction(u) / 2 ** l - Fraction(1, 2)
y = Fraction(v) / 2 ** l - Fraction(1, 2)
i0, j0 = floor(x), floor(y)
fx, fy = x - i0, y - j0
def cl(k):
return min(max(k, 0), size - 1)
return (cl(i0), cl(i0 + 1)), (cl(j0), cl(j0 + 1)), fx, fy
def bilinear(get, size, u, v, l):
(i0, i1), (j0, j1), fx, fy = taps(size, u, v, l)
return (
(1 - fx) * (1 - fy) * get(l, i0, j0)
+ fx * (1 - fy) * get(l, i1, j0)
+ (1 - fx) * fy * get(l, i0, j1)
+ fx * fy * get(l, i1, j1)
)
def trilinear(get, sizes, u, v, lam):
"""The trilinear sample at the level of detail lam >= 0."""
a = min(floor(lam), len(sizes) - 1)
f = Fraction(lam) - a if a < len(sizes) - 1 else Fraction(0)
s = bilinear(get, sizes[a], u, v, a)
if f == 0:
return s
return (1 - f) * s + f * bilinear(get, sizes[a + 1], u, v, a + 1)
def mip_sample(mip, u, v, lam):
"""The reference: a trilinear sample of the full mipmap."""
return trilinear(lambda l, i, j: mip[l][i][j], [len(a) for a in mip], u, v, lam)
class Clipmap:
def __init__(self, mip, C, c):
self.mip = mip # the full texture, on disk or in main memory
self.C = C
self.sizes = [len(a) for a in mip]
self.k = sum(1 for s in self.sizes if s > C) # the levels of the clip stack
self.S = [[[None] * C for _ in range(C)] for _ in range(self.k)]
self.win = [None] * self.k
self.recenter(c)
def recenter(self, c):
"""Move the clip center to c. Returns the number of texels written."""
C = self.C
count = 0
for l in range(self.k): # @line L1
new = window(c, l, C) # @line L2
old = self.win[l]
for tx in range(new[0], new[2]):
for ty in range(new[1], new[3]): # @line L3
if old is not None and in_window(old, (tx, ty)):
continue
inside = 0 <= tx < self.sizes[l] and 0 <= ty < self.sizes[l]
self.S[l][tx % C][ty % C] = self.mip[l][tx][ty] if inside else None # @line L4
count += 1
self.win[l] = new # @line L5
return count
def get(self, l, i, j):
if l >= self.k:
return self.mip[l][i][j]
if not in_window(self.win[l], (i, j)):
raise KeyError((l, i, j))
return self.S[l][i % self.C][j % self.C]
def holds(self, u, v, l):
"""Does level l hold the bilinear footprint of (u, v)?"""
if l >= self.k:
return True
(i0, i1), (j0, j1), _, _ = taps(self.sizes[l], u, v, l)
return all(in_window(self.win[l], (i, j)) for i in (i0, i1) for j in (j0, j1))
def finest_level(self, u, v):
"""The smallest l such that the levels l, l + 1, ... all hold the footprint."""
l = len(self.sizes) - 1
while l > 0 and self.holds(u, v, l - 1): # @line L6
l -= 1
return l
def lookup(self, u, v, lam):
l = max(Fraction(lam), self.finest_level(u, v)) # @line L7
return trilinear(self.get, self.sizes, u, v, l) # @line L8
test_texture_clipmap.py 84 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/texture-clipmap/. The authors are listed in prov/NPGSAB.jsonl.
import random
from fractions import Fraction
from texture_clipmap import Clipmap, build_mipmap, in_window, mip_sample, texel_counts, window
N, C = 64, 8
def make_mip(rng):
return build_mipmap([[rng.randrange(256) for _ in range(N)] for _ in range(N)])
def centers(rng, k):
return [(rng.randrange(-8, N + 8), rng.randrange(-8, N + 8)) for _ in range(k)]
def test_stack_after_moves_equals_a_fresh_fill():
rng = random.Random(1)
mip = make_mip(rng)
cm = Clipmap(mip, C, (N // 2, N // 2))
for c in centers(rng, 60):
olds = [set((x, y) for x in range(w[0], w[2]) for y in range(w[1], w[3])) for w in cm.win]
written = cm.recenter(c)
fresh = Clipmap(mip, C, c)
expected = 0
for l in range(cm.k):
w = window(c, l, C)
assert cm.win[l] == w == fresh.win[l]
pts = [(x, y) for x in range(w[0], w[2]) for y in range(w[1], w[3])]
expected += len(set(pts) - olds[l])
for x, y in pts:
slot = cm.S[l][x % C][y % C]
assert slot == fresh.S[l][x % C][y % C]
if 0 <= x < len(mip[l]) and 0 <= y < len(mip[l]):
assert slot == mip[l][x][y]
assert written == expected
def test_a_move_writes_only_the_new_strips():
mip = make_mip(random.Random(2))
cm = Clipmap(mip, C, (32, 32))
assert cm.k == 3
# The windows of the levels 0, 1 and 2 move by 8, 4 and 2 texels.
assert cm.recenter((40, 32)) == C * (8 + 4 + 2)
assert cm.recenter((40, 32)) == 0
def test_lookup_equals_the_full_mipmap_at_the_level_it_uses():
rng = random.Random(3)
mip = make_mip(rng)
full = 0
for c in centers(rng, 20):
cm = Clipmap(mip, C, c)
for _ in range(40):
u = Fraction(rng.randrange(0, 16 * N), 16)
v = Fraction(rng.randrange(0, 16 * N), 16)
lam = Fraction(rng.randrange(0, 4 * len(mip)), 4)
lmin = cm.finest_level(u, v)
assert cm.lookup(u, v, lam) == mip_sample(mip, u, v, max(lam, lmin))
if lmin <= int(lam):
full += 1
assert cm.lookup(u, v, lam) == mip_sample(mip, u, v, lam)
assert full > 0
def test_windows_nest_for_clip_sizes_of_at_least_four():
rng = random.Random(4)
for size in (4, 8, 16, 32):
for c in centers(rng, 200):
for l in range(6):
a, b = window(c, l, size), window(c, l + 1, size)
lo = (a[0] * 2 ** l, a[1] * 2 ** l, a[2] * 2 ** l, a[3] * 2 ** l)
hi = (b[0] * 2 ** (l + 1), b[1] * 2 ** (l + 1), b[2] * 2 ** (l + 1), b[3] * 2 ** (l + 1))
assert hi[0] <= lo[0] and hi[1] <= lo[1] and lo[2] <= hi[2] and lo[3] <= hi[3]
def test_the_numbers_of_the_page():
assert texel_counts(16384, 512) == (1660245, 357913941)
c, p = (8000, 8000), (8400, 8100)
held = [in_window(window(c, l, 512), (p[0] // 2 ** l, p[1] // 2 ** l)) for l in range(3)]
assert held == [False, True, True]
History
Tanner, Migdal and Jones presented the clipmap at SIGGRAPH 98 as a "virtual mipmap": a mipmap of a texture much larger than texture memory, in which only a window around a point of interest is kept for each fine level, and the windows are updated toroidally as the point moves. Losasso and Hoppe took the same nested windows from textures to terrain geometry in 2004, as geometry clipmaps. Later systems for large textures moved to page-based virtual texturing, which does not need a single center of interest.
References
- Christopher C. Tanner, Christopher J. Migdal and Michael T. Jones, The clipmap, a virtual mipmap, SIGGRAPH 98, 151 to 158, the clip stack and the clip pyramid, the clip center, the toroidal update of the clipped levels, and the choice of a coarser level outside the clip region (general locator)
- Frank Losasso and Hugues Hoppe, Geometry clipmaps, terrain rendering using nested regular grids, ACM Transactions on Graphics 23(3), SIGGRAPH 2004, 769 to 776, the comparison with the texture clipmap and the reuse of its nested windows for geometry (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, the part on texture streaming and very large textures in the chapter on texturing (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 | W4 complete |
|
Tag NPGSAB Edit this page History Report an error Markdown