GPU data

Mipmaps and texture sampling

When a pixel shader reads a texture, the GPU does not just fetch one texel. It works out how big the pixel is on the texture, picks a smaller copy of the texture that matches, and blends a few texels together. This page explains each step: why shrinking a texture flickers, how a mip chain fixes it, how mips are made, how the GPU chooses a level, and the filters and wrap modes that a sampler controls. The last part shows how RASM does it.

In short

  • When one pixel covers many texels, a single sample picks one of them almost at random. The result flickers and shows patterns: aliasing.
  • A mip chain stores the texture again at 1/2, 1/4, 1/8 … of its size, each level filtered from the one above. It costs only 1/3 more memory.
  • The GPU measures how fast the texture coordinates change between neighboring pixels (the derivatives) and picks the level λ = log2(texels per pixel).
  • Bilinear blends 4 texels inside one level; trilinear also blends two levels; anisotropic takes several samples along a stretched footprint.
  • Color mips must be averaged in linear light, not on the stored sRGB values.
  • The wrap mode decides what is read outside 0 to 1: repeat, mirror, or clamp.

1The problem: shrinking a texture

A texture is a grid of texels. The screen is a grid of pixels. The two grids almost never match.

1 texel = 3 × 3 pixels orange: one pixel

Close: magnification

One texel covers several pixels.

1 pixel = 8 × 8 texels orange: one pixel

Far away: minification

One pixel covers many texels. This is the hard case.

texture, far away orange: what one pixel covers blue dot: the one texel it samples amber and gray: two texel values One sample per pixel flickers when the camera moves Average of each footprint steady gray: the right answer
The texture holds more detail than the screen can show. That extra detail must be averaged away, not skipped. Each pixel's dot moves a little when the camera moves, so it jumps between dark and light texels. On a regular pattern this makes moiré: large false stripes.

The right color for a pixel is the average of all texels under it. But a far-away pixel may cover hundreds of texels, and averaging hundreds of texels for every pixel is far too slow. The fix is to do the averaging once, ahead of time.

2The mip chain

A mipmap (from the Latin multum in parvo, "much in a small place") is a list of copies of the texture. Level 0 is the original. Each next level is half as wide and half as high, and each of its texels is the average of 2×2 texels of the level above. The chain stops at 1×1.

level 0 · 1024×1024 1 · 512 2 · 256 3 · 128 … 10 · 1 2×2 texels → 1 texel
Drawn to scale for the first levels. Each level holds a quarter of the texels of the one above.
4/3memory of the whole chain: 1/3 bigger than level 0 alone1 + 1/4 + 1/16 + 1/64 + …
11 levelsfor a 1024 × 1024 texture⌊log2(max(w, h))⌋ + 1
LevelSizeMemory (4 bytes per texel)A pixel at this level covers about
01024 × 10244 MiB1 texel of level 0
1512 × 5121 MiB2 × 2 texels of level 0
2256 × 256256 KiB4 × 4
3128 × 12864 KiB8 × 8
…………
101 × 14 bytesthe whole texture
all 11 levels5.33 MiB (4 MiB × 4/3)

Sizes that are not a power of two work the same way: each level is the size above divided by 2, rounded down, but never below 1. A 1000 × 600 texture has 10 levels: 1000×600, 500×300, 250×150, 125×75, 62×37, 31×18, 15×9, 7×4, 3×2, 1×1. Rounding down means a level does not cover exactly 2×2 texels at the edges, which a good filter takes into account.

3Making the mips

The filter

The simplest filter is the box filter: each new texel is the plain average of the 2×2 texels above it. It is fast and good enough for many textures. Wider filters look at more texels and give sharper, cleaner results. Each picture shows one row of texels and the weight each texel gets:

Box

2 texels per output (in 1D), equal weights.

Slightly blurry; can keep some aliasing

Tent (triangle)

4 texels per output, more weight in the middle.

Smoother

Mitchell–Netravali, Kaiser, Lanczos

4 to 8 texels per output, with small negative weights at the sides.

Sharper, less aliasing; Lanczos can add faint halos

The source of each level is a second choice:

From the level above

Fast.

Small errors add up

From level 0 directly

Better.

More work for the small levels

Edges of a tiling texture

Near the edges a wide filter needs texels from outside the image. For a texture that tiles (a brick wall that repeats), it should take them from the opposite edge; otherwise the small levels show a seam.

Color must be averaged in linear light

Color textures are stored in sRGB: the stored number is not proportional to the light (see color spaces). Averaging the stored numbers gives the wrong brightness. Take a 2×2 block of black (0) and white (255) texels:

0 255 255 0 128 21% of the light

Average the stored numbers

(0 + 255 + 255 + 0) / 4 = 128. Too dark: far mips go darker.

0 255 255 0 188 50% of the light

Decode → average → encode

Decode to linear: 0, 1, 1, 0. Average: 0.5. Encode: 0.735 → 188. The true average.

With the wrong average, a fine black-and-white pattern turns visibly darker as it moves away. With the right one, its brightness stays the same.

Textures that are not plain color

decode, average encode

Color (sRGB)

Decode, average, encode (above).

α 1 α 0 α 0 α 0 same color, α 0.25

Color with alpha

Weight each color by its alpha before averaging (premultiply), so that invisible texels do not bleed their color into the edges. Alpha itself is linear.

For cut-out foliage, small levels lose coverage and leaves thin out; some tools rescale alpha per level to keep it.

0.20.4 0.60.8 0.5

Data (roughness, metalness, occlusion)

Average the stored numbers directly: they are already linear.

renormalized: length 1 average: too short

Normal maps

Average the vectors, then renormalize; the average of unit vectors is shorter than 1.

Better tools also store the lost length as extra roughness.

Where to make them

all levels in the file

Offline, in the asset tool

Store all levels in the file (KTX2, DDS), often block-compressed. Good for shipping games and apps.

None at load time; best filters

CPU memory GPU

CPU, at load

Resize level by level in memory, upload all levels. Good for loading plain PNG and JPEG files.

CPU time per texture

GPU: one copy per level 1 2 3

GPU, blit chain

Copy level i into level i+1 with a linear filter, one command per level, a barrier between each. Good for render targets and runtime textures.

Fast; box-like filter only

compute

GPU, compute

One shader makes many levels at once (single-pass downsamplers). Good for many textures per frame and depth pyramids.

Fast; any filter

4How the GPU picks a level

The GPU must know how many texels one pixel covers. It finds out from the neighbors. Pixel shaders always run in blocks of 2×2 pixels (a quad). Every pixel of the quad computes its texture coordinate uv, and the GPU subtracts them: the difference between horizontal neighbors is ∂uv/∂x, between vertical neighbors ∂uv/∂y. These are the derivatives.

A quad of pixels on screen u 0.500v 0.300 u 0.502v 0.300 u 0.500v 0.302 u 0.502v 0.302 ∂uv/∂x = (0.002, 0) ∂uv/∂y = (0, 0.002) × 1024 One pixel, on level 0 2.048 × 2.048 texels The same pixel, on level 1 about 1 texel
The derivatives are free: the 4 pixels of a quad run together, so each one can see its neighbors' values. Level 1 has texels twice as big: one of them is about one pixel. That is the match.
2.048 texelsρ: what one pixel covers on level 00.002 × 1024
1.03λ: the level that matcheslog2(2.048)

The full rule, as the Vulkan and Direct3D specifications give it, for a texture of w × h texels:

ρx = sqrt( (∂u/∂x · w)² + (∂v/∂x · h)² )     texels per pixel, along screen x
ρy = sqrt( (∂u/∂y · w)² + (∂v/∂y · h)² )     texels per pixel, along screen y

λ  = log2( max(ρx, ρy) ) + bias
λ  = clamp(λ, minLod, maxLod)

λ ≤ 0   magnification: use level 0 with the magnification filter
λ > 0   minification: use level λ with the minification filter

Each step of λ by 1 is one level, because each level halves the size. λ is rarely a whole number; what happens with the fraction is the mip filter (section 5). The bias shifts every choice: a negative bias makes textures sharper (and noisier), a positive one blurrier.

uv skipped uv skipped ∂uv/∂x = ?

Derivatives can break

The neighbors must run the same code. Inside an if that differs between the 4 pixels of a quad, some neighbors do not compute uv, and the derivative is undefined. A jump in uv also breaks it: at the seam of a texture atlas, or where uv wraps from 0.99 to 0.01, the GPU sees a huge change and picks the smallest level, which shows as a thin line of wrong color. A pixel that a discard killed has left its quad too; a demote keeps it as a helper that still computes uv.

lod = 1 0 1 2 3 the shader names the level itself

When there are no neighbors

Compute shaders and vertex shaders have no quads, so they have no automatic derivatives. There the shader names the level itself: SampleLevel(uv, lod), or passes its own derivatives: SampleGrad(uv, ddx, ddy). A plain Load(x, y, level) reads one texel with no filter at all.

5Filtering: nearest, bilinear, trilinear

The sample point almost never lands on the center of a texel. The filter decides what to return.

the sample point texel centers the texel that nearest returns
4×4 texture, sample at (0.3, 0.6) 0,01,02,03,0 nearest: texel (1, 2), 1 read Bilinear: the 4 centers and their weights 70% 90% (0,1): 0.03 (1,1): 0.07 (0,2): 0.27 (1,2): 0.63
The closer a center is to the point, the larger its weight (the size of its dot). The −0.5 below moves from "texel edges" to "texel centers": the center of texel i is at (i + 0.5) / w.
x = 0.3 · 4 − 0.5 = 0.7     between texels 0 and 1, 70% of the way
y = 0.6 · 4 − 0.5 = 1.9     between texels 1 and 2, 90% of the way

(0,1): 0.3 · 0.1 = 0.03     (1,1): 0.7 · 0.1 = 0.07
(0,2): 0.3 · 0.9 = 0.27     (1,2): 0.7 · 0.9 = 0.63

Nearest

Return the texel that holds the point: texel (1, 2) above. Blocky up close, which suits pixel art.

1 read

Bilinear

Blend the 4 texel centers around the point. The weights add up to 1. Smooth, but a level is still chosen for the whole sample, so a visible line appears where λ crosses a whole number.

4 reads

The mip filter adds a second choice: what to do with the fraction of λ. Nearest takes the closer level. Linear samples the two levels around λ and blends them by the fraction. Bilinear inside each level plus linear between levels is called trilinear filtering.

123 λ 123 level read

Mip filter: nearest

Takes the closer level. The level jumps, and the jump shows as a line on the surface.

123 λ 123 level read

Mip filter: linear

Samples the two levels around λ and blends them by the fraction. No jump, no line.

Min filterMip filterCommon nameReadsLook
nearestnone (level 0 only)point1sharp, aliases when far
linearnonebilinear, no mips4smooth up close, aliases when far
nearestnearestpoint, mipmapped1blocky, no shimmer
linearnearestbilinear4smooth, visible lines between levels
linearlineartrilinear8smooth, no lines

Try the five rows of the table on a real floor. The picture below computes every pixel the way a GPU does: its uv, the derivatives from its neighbors, λ, then the filter.

Start with point and look at the far end while the floor moves. Then go through the filters from left to right. Turn on Color each level to see which level each pixel reads, and compare "bilinear + mips" with "trilinear".

6Anisotropic filtering

On a floor seen at a low angle, a pixel's footprint is not a square: it is long and thin. It covers few texels across, but many texels along the view direction. λ uses the longer side, so the whole sample comes from a small, blurry level, even though the short side wanted a sharp one.

the area the pixel really covers the area each sample averages
Floor at a grazing angle one pixel covers a long, thin strip Isotropic: one big sample level from the long side: blurry Anisotropic: N small samples level from the short side: sharp
Green: the area each sample averages. Orange: the area the pixel really covers.

The usual rule (from the anisotropic filtering extension that most GPUs follow):

ρmax = max(ρx, ρy)      ρmin = min(ρx, ρy)
N    = min( ceil(ρmax / ρmin), maxAnisotropy )     number of samples
λ    = log2( ρmax / N )                            level of each sample

Each of the N samples is itself trilinear, so 16× anisotropy can mean up to 128 texel reads. GPUs are good at this, and they take fewer samples where the footprint is nearly square. The sampler sets maxAnisotropy; 8 or 16 is common.

7Wrap modes

Texture coordinates outside 0 to 1 are allowed. The wrap mode (or address mode) of the sampler decides which texel they read. It also matters inside the range: bilinear filtering at the edge reads one texel beyond it.

−1012 u repeat A B C D A B C D A B C D tiles: bricks, floors, terrain mirrored repeat D C B A A B C D D C B A tiles with no visible seam clamp to edge A A A A A B C D D D D D UI, sprites, render targets clamp to border border color A B C D border color shadow maps, decals
Orange: the texture itself, u from 0 to 1. The same choice is made for v (and w for 3D textures), often separately. With repeat, bilinear filtering at u = 0 blends texel A with texel D from the other side. That is right for a tiling texture, and a thin wrong-colored edge for a texture that does not tile.

8Worked example

A floor uses a 1024 × 1024 texture, trilinear filtering and up to 8× anisotropy. Three pixels at three distances; click through them.

Pixel A: close to the camera

level 0 texels (40 px each); orange: the pixel ∂uv/∂x = (0.0005, 0) ∂uv/∂y = (0, 0.0005) ρx = ρy = 0.0005 × 1024 = 0.512 texels λ = log2(0.512) = −0.97 λ ≤ 0: magnification Level 0, with the magnification filter (bilinear here).

One texel spreads over about 2 × 2 pixels. Mips cannot add detail that the texture does not have. Up close, the only question is how to blend between texels. Bilinear gives smooth gradients; nearest gives visible squares.

Pixel B: in the middle

level 0 texels (20 px each) ∂uv/∂x = (0.002, 0) ∂uv/∂y = (0, 0.002) ρx = ρy = 0.002 × 1024 = 2.048 texels λ = log2(2.048) = 1.03 Trilinear: levels 1 and 2 level 1 (512²): weight 1 − 0.03 = 0.97 level 2 (256²): weight 0.03 4 bilinear reads in each level: 8 reads in all.

The pixel is a little bigger than a level 1 texel, so the result is almost all level 1. As the floor moves away, the weight slides smoothly toward level 2: no line where the level changes.

Pixel C: far away, at a grazing angle

level 0, 4 px per texel: 4.1 × 32.8 texels ∂uv/∂x = (0.004, 0) ∂uv/∂y = (0, 0.032) ρx = 4.10 ρy = 32.77 texels Without anisotropy λ = log2(32.77) = 5.03 → level 5, only 32 × 32: a smear With 8× anisotropy N = min(ceil(32.77 / 4.10), 8) = 8 λ = log2(32.77 / 8) = 2.03 → level 2 (256 × 256) 8 trilinear samples spread along the long side: 64 reads.

Anisotropy keeps the floor sharp across the view, three levels finer than plain trilinear. This is why distant roads and floors look much better with it switched on.

9Pitfalls

Shimmer and moiré on distant surfaces
No mips. Make the full chain.
Black or garbage far away
Mips allocated but not filled. Fill every level, or limit the view to the levels that exist.
Mips are never used
The sampler's maximum level was left at 0 (in Vulkan, the default maxLod is 0). Set it to the number of levels, or "no limit".
Fine patterns get darker with distance
sRGB color averaged as stored numbers. Average in linear light.
Neighbor's colors bleed in at a distance
An atlas without padding. Pad each tile; stop the chain before tiles merge.
Random wrong levels, lines at material edges
A texture sampled inside divergent branches. Sample before the branch, or use an explicit level or derivatives.
A thin line of the opposite edge's color
Repeat mode on a non-tiling texture. Clamp to edge.

10In RASM

RASM makes the full mip chain of an image on the CPU, on the worker thread that decodes it, and the main thread uploads all levels at once (texture uploads). A KTX2 file brings its mips (texture compression). Sampling uses six fixed samplers: trilinear with 8× anisotropy, or nearest, each with three wrap modes.

CPU · level count levels = ⌊log2(max)⌋ + 1 getFullMipCount worker · buildTextureLevels level 0pixels in 1 2 … 1×1 each level resized from the one above sRGB formats: linear light, alpha-weighted (stbir_resize_uint8_srgb) UNORM: the stored numbers (…_linear); glTF normal maps renormalized main: all levels, staging ring or host copy fragMain: gTextures[i].Sample(uv) · the GPU picks λ from derivatives · one of six samplers
loadTexture's worker (decodeTexture) and a glTF image's job (runImageWork) make the levels; finishTextureLoad copies them. A texture the app fills with one level through RenderContext::fillTexture gets the same filter from buildMipChain, in the caller's thread. A Basis KTX2 file without mips is transcoded to RGBA8 and goes through buildMipChain on the worker.

Where RASM follows the textbook, and where it differs

PartThis pageRASM
Which textures get mipsany minified textureTextureUsage::SAMPLED textures in R8G8B8A8_UNORM, R8G8B8A8_SRGB or B8G8R8A8_SRGB get the full chain (VulkanDevice::createTexture), and KTX2 textures the file's levels. Render targets and depth textures have 1 level.
Where mips are madeoffline, CPU or GPUImages: CPU, on the worker that decodes them, in buildTextureLevels (src/rhi/mipChain.cpp); an app's one-level RenderContext::fillTexture in its own thread (buildMipChain). KTX2: offline, in the file; a Basis file without them gets RGBA8 mips from buildMipChain on the worker. No GPU blits or compute (why: texture uploads).
Filterbox or widerstb_image_resize2's default for shrinking (Mitchell), each level made from the level above.
Linear-light colorsection 3Yes: _SRGB formats go through stbir_resize_uint8_srgb with STBIR_RGBA, which decodes to linear, weights by alpha, and keeps alpha linear.
Data and normal mapsaverage directly; renormalize normalsUNORM textures use stbir_resize_uint8_linear with STBIR_4CHANNEL: plain averages, no alpha weighting. The levels of a glTF normal texture are renormalized after each resize, so each texel is a unit direction; loadTexture does not know the slot and does not renormalize.
Edges of tiling textureswrap when filteringThe resizer clamps at the edges, also for textures sampled with repeat. Small levels of a tiling texture can show a faint seam.
Uploadstaging buffer and copyThe staging ring and a GPU copy (GPU memory), or host image copy where it costs the GPU nothing for the format: vkTransitionImageLayout moves the image to the shader-read layout and vkCopyMemoryToImage writes every level from CPU memory (texture uploads).
Level choiceλ from derivatives, clampedThe hardware rule. Every sampler has maxLod = VK_LOD_CLAMP_NONE, minimum 0 and no bias, so one sampler serves textures with any number of levels.
Filtersnearest to anisotropicLINEAR_* samplers: linear mag, min and mip filter (trilinear) with 8× anisotropy, capped by the device's limit. NEAREST_*: nearest everything, nearest mip, no anisotropy.
Wrap modes4 modes, per axisRepeat, mirrored repeat and clamp to edge; no border. The same mode on every axis.
glTF samplersseparate wrap per axis, separate min and mag filterstoSamplerType reads only wrapS (used for both axes) and magFilter (nearest or linear for everything). wrapT and minFilter are ignored.
Explicit levelsSampleLevel, LoadThe material shaders use Sample with automatic derivatives. The Hi-Z build reads depth with Load, and builds its own depth pyramid with a minimum instead of an average (see occlusion culling).

The six samplers

SamplerTypeMag / min / mip filterWrapAnisotropyUsed for
LINEAR_REPEATlinear / linear / linearrepeat8×the default for material textures
LINEAR_MIRRORED_REPEATlinear / linear / linearmirrored repeat8×glTF textures that ask for it
LINEAR_CLAMPlinear / linear / linearclamp to edge8×render target color attachments
NEAREST_REPEATnearest / nearest / nearestrepeatoffglTF textures with a nearest magFilter
NEAREST_MIRRORED_REPEATnearest / nearest / nearestmirrored repeatoffthe same, mirrored
NEAREST_CLAMPnearest / nearest / nearestclamp to edgeoffdepth textures for occlusion culling

The sampler is chosen per bindless slot, when the slot is written (see bindless resources).

Where it lives in code

WhatWhere
Level count, image and viewVulkanDevice::createTexture in src/rhi/vulkan/vulkanDevice.cpp
Mip generationbuildTextureLevels in src/rhi/mipChain.cpp, called by decodeTexture and runImageWork on the workers; buildMipChain, called by RenderContext::fillTexture and, for KTX2 without mips, by decodeKtx
UploadRenderContext::fillTexture; VulkanDevice::fillTexture (host copy) or UploadManager::uploadTexture (staging)
Sampler objectsVulkanDevice::createSampler in src/rhi/vulkan/vulkanDevice.cpp; rhi::SamplerDesc in src/rhi/device.h
The six sampler settingssamplerDesc in src/rhi/renderContext.cpp; SamplerType in include/rasm/render/resource.h
glTF sampler mappingtoSamplerType in src/assets/material.cpp
When pixels arriveAssetLoader::Impl::finishTextureLoad in src/assets/texture.cpp; AssetLoader::Impl::loadMaterial in src/assets/material.cpp
Keep these true
  • fillTexture must fill every level that createTexture allocated: the view covers all of them, and an unfilled level is read as garbage at a distance.
  • A load's worker makes every level, and its count is getFullMipCount, the texture's: fillTexture refuses another count.
  • Color textures (_SRGB) take the sRGB resize path; data textures (_UNORM) take the linear one. The format decides, so a texture must be created with the right one (see color spaces).
  • Keep maxLod at VK_LOD_CLAMP_NONE. A sampler with the Vulkan default of 0 would use level 0 only.
  • Sample with automatic derivatives only outside branches that differ within a quad.
Not done yet

The resizer clamps at the edges also for tiling textures. Each glTF image gets its mips in a job of its own, so a model's images run on several workers at once.

Further reading