GLSL textureGather Component Selector Explained

In OpenGL Shading Language (GLSL), the textureGather function retrieves the four texels that would normally be used during bilinear interpolation and packs one channel from each texel into a single four-component vector. The component selector parameter determines exactly which color channel—red, green, blue, or alpha—is extracted from these four neighboring texels. By isolating a specific channel across a 2x2 texel footprint in a single operation, this parameter enables efficient custom filtering, shadow mapping, and packed data processing.

Function Signature and Selector Values

The standard overload for two-dimensional sampling takes the following form:

gvec4 textureGather(gsampler2D sampler, vec2 P [, int comp]);

The comp parameter is an optional integer specifying the zero-based index of the component to extract:

  • 0: Red (r / x) component (default if omitted)
  • 1: Green (g / y) component
  • 2: Blue (b / z) component
  • 3: Alpha (a / w) component

The value of comp must be a compile-time constant expression within the range 0 to 3. If a requested component is not present in the texture's internal format (for example, requesting component 2 from a two-channel GL_RG texture), GLSL returns a default fallback value—typically 0.0 for missing color channels or 1.0 for missing alpha.

Output Vector Layout

When textureGather executes, it samples the 2x2 footprint around coordinate P and assigns the chosen component from each texel to the returned vec4 in a counter-clockwise order:

  • .x: Texel at [i, j + 1] (top-left)
  • .y: Texel at [i + 1, j + 1] (top-right)
  • .z: Texel at [i + 1, j] (bottom-right)
  • .w: Texel at [i, j] (bottom-left)

Because all four components of the return vector belong to the same channel specified by comp, developers can implement custom interpolation weights without calling standard texture lookups multiple times.

Practical Applications

The component selector is particularly valuable in the following scenarios:

  • Packed Texture Atlases and G-Buffers: Modern rendering pipelines frequently pack unrelated single-channel data into different channels of one texture (e.g., roughness in R, metallic in G, ambient occlusion in B). The component selector allows a shader to gather neighbors for a specific property without fetching or reconstructing the entire RGBA color.
  • Shadow and Depth Processing: While depth textures naturally rely on component 0, custom depth packing or multi-layer shadow maps can use the selector to isolate depth data stored across arbitrary channels.
  • Custom Reconstruction Filters: Hardware bilinear filtering is limited to linear blending. Gathering a specific channel across four texels allows shaders to perform non-linear filtering, such as bicubic, Catmull-Rom, or threshold-based edge-aware filtering, on individual scalar fields with minimal memory bandwidth overhead.