Article

Determining Which Mipmaps the GPU Will Try to Access

Get information at runtime about mipmaps the GPU will sample.

Overview

When you sample a texture, the GPU automatically chooses which mipmaps to access and fetches pixels from them. For the most part, this process is transparent to your app.

Sometimes, you want to know which mipmaps the GPU is going to read from. For example, if only some of your mipmaps have data, you might already be using a clamp operation to limit the range of mipmaps the GPU can sample from, but want to know when the GPU will try to sample higher mipmaps. Metal Shading Language provides texture functions that you can use to find out which mipmaps your shader would access if it sampled the texture.

Check for Level-of-Detail Support

Not all device objects support level-of-detail (LOD) queries. Before loading any shaders that use LOD queries, check to make sure that they are supported:

Boolean supportsLODCalculation = [_device supportsFamily:MTLGPUFamilyMac2];

Determine Level of Detail

In your shader, the functions that return level-of-detail information have signatures that are similar to those of functions used to sample textures. There are two kinds of these functions: clamped and unclamped. The clamped kind restricts level-of-detail selection by applying the sampler's range of permitted values, the range of mipmaps provided in the texture, and the sampler's anisotropy settings. The unclamped kind returns the raw calculation.

float clampedLOD = texture.calculate_clamped_lod(mySampler, coords)
float unclampedLOD = texture.calculate_unclamped_lod(mySampler, coords);

A fractional part in a returned value indicates that the value is between two mipmaps. The fractional part of the number is the blending weight that is applied between the two mipmaps if you have specified linear mipmap blending.

Determine Level of Detail when Shader Support is Unavailable

An alternative approach to getting the level of detail is to perform the calculation yourself, based on the size of the model object and its distance from the camera. For an example of this technique, see Using Function Specialization to Build Pipeline Variants.

See Also

Mipmap Access

Restricting Access to Specific Mipmaps

Set the range of mipmap levels that a sampler can access.

Dynamically Adjusting Texture Level of Detail

Defer generating or loading larger mipmaps until that level of detail is needed.