What Does GLSL textureQueryLevels Return?

In the OpenGL Shading Language (GLSL), the textureQueryLevels function provides shaders with direct runtime access to mipmap metadata by returning the total number of mipmap levels present in a given texture. This article explains the exact return value of textureQueryLevels, how it behaves under various texture states, which sampler types it supports, and its common practical uses in graphics pipelines.

The Return Value

The textureQueryLevels function returns a single integer (int) representing the total number of accessible mipmap levels for the specified texture sampler.

  • Complete Textures: If a texture is complete and contains mipmaps, the returned value is the count of levels, including the base level (level 0). For instance, a texture with levels 0 through 4 will return 5.
  • Single-Level Textures: If a texture is complete but only contains the base level without additional mipmaps, the function returns 1.
  • Incomplete Textures: If the texture bound to the sampler is not complete (for example, missing dimensions or incomplete mipmap chains), the function returns 0.

Function Signatures and Supported Types

Introduced in GLSL 4.30 (and via the GL_ARB_texture_query_levels extension), textureQueryLevels accepts almost all standard sampler types:

int textureQueryLevels(gsampler sampler);

The gsampler placeholder represents floating-point, signed integer (isampler), and unsigned integer (usampler) variants of:

  • 1D textures (sampler1D, sampler1DArray)
  • 2D textures (sampler2D, sampler2DArray, sampler2DRect)
  • 3D textures (sampler3D)
  • Cube maps (samplerCube, samplerCubeArray)
  • Shadow map samplers (e.g., sampler2DShadow, samplerCubeShadow)

The function cannot be used with multisampled textures (sampler2DMS) or buffer textures (samplerBuffer), as these texture formats do not support mipmapping.

Practical Use Cases

Knowing the number of mipmap levels at shader runtime is valuable in several advanced rendering scenarios:

  1. LOD Clamping and Manual Calculation: It allows shaders to manually clamp Level of Detail (LOD) parameters within valid boundaries using functions like textureLod or textureGrad.
  2. Procedural Blending: Shaders can calculate normalized mip levels (from 0.0 to 1.0) across arbitrary textures regardless of their original resolution.
  3. Debugging and Validation: Developers can visualize whether mipmaps have been properly allocated and uploaded to the GPU directly within a fragment shader output.