'Sampling texture with MTLPixelFormat.r32Float

I have a texture with MTLPixelFormat.r32Float, and I would like to sample it with linear interpolation using texture.sample(mySampler, float2(u, v)). I am configuring the sampler as:

constexpr sampler mySampler (mag_filter::linear,
                             address::clamp_to_edge,
                             min_filter::linear);

However, within a metal Shader, texture.sample() always returns a 4-component vector (float4). So my questions are:

  1. Can the sampler interpolate the texture with MTLPixelFormat.r32Float correctly?
  2. If so, which component of the sampler output (float4) represents the sampled value?

So far, I have been unsuccessful at finding this out experimentally. None of the components of the sample output seem to work. Is it possible I have to configure sampling differently? Or is it impossible?



Solution 1:[1]

A texture with MTLPixelFormatR32Float pixel format can not be filtered during sampling on most GPUs.

According Metal Shader Language Specification:

For unspecified color components in a pixel format, the default values are:

  • zero, for components other than alpha.
  • one, for the alpha component.

If so, which component of the sampler output (float4) represents the sampled value?

You can use an array index to access vector components:

float c = texture.sample(mySampler, float2(u, v))[0];

or swizzling:

float c = texture.sample(mySampler, float2(u, v)).r;



float c = texture.sample(mySampler, float2(u, v)).x;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1