MIP Mapping - Built-in functions - Shader Learning

Built-in functions

MIP Mapping

Task

Animate a texture transition by gradually increasing its mip level from 0 (full resolution) to MIP_MAX (lowest resolution) over time, using a normalized progress variable in the range [0, 1].

Theory

A mipmap is a sequence of precomputed, downscaled versions of a texture. Each mip level is created by downsampling the previous one, typically using a box filter that averages $2 \times 2$ texels. At each step, the resolution is halved until reaching a final $1\times 1$ texel. This process can be performed automatically by the GPU during texture loading if needed.



Mipmaps are used to improve rendering performance and visual quality when textures are viewed at a distance or at steep angles.



Mip Level Sizes


If the base texture is $W \times H$, then:


Mip Dimensions
0 $W \times H$
1 $W/2 \times H/2$
2 $W/4 \times H/4$
… …
$N$ $1 \times 1$

where N = floor(log2(max(W, H))).


Memory Usage


Each level uses $\frac{1}{4}$ the memory of the previous one. The total memory used by all mip levels is approximately:

$ \text{Total} = 1 + \frac{1}{4} + \frac{1}{16} + \frac{1}{64} + \dots \approx \frac{4}{3} $

So if your base texture is $4$ MB, the full mip chain will use $\approx 5.33$ MB.


Mipmap Level Selection


By default, GPUs automatically select the appropriate mipmap level when sampling a texture.


GLSL:

// GPU picks mip level
vec4 color = texture(mySampler, uv);

HLSL:

// GPU picks mip level
float4 color = myTexture.Sample(mySampler, uv);

This is ideal for most use cases, especially when rendering textured geometry at varying scales or angles.


Manual Mip Level Selection


For advanced control, such as debugging, stylized effects, or procedural LOD, you can manually specify the mip level using special sampling functions:


GLSL:

// Explicit mip level
vec4 color = textureLod(mySampler, uv, mipLevel);

HLSL:

// Explicit mip level
float4 color = myTexture.SampleLevel(mySampler, uv, mipLevel);

This bypasses the automatic selection and forces the GPU to sample from the specified mip level.