Search code examples
graphicsglslshaderlinear-algebra

Efficient component selector in glsl


A long time ago I ran into a snippet for glsl that efficiently computed the absolute wise maximum component of a vector and zeroed out the other components.

For example the following inputs would yield the following outputs:

vec3(1, 0, 0) -> vec3(1, 0, 0)
vec3(-1, 0.5, 0) -> vec3(-1, 0, 0)
vec3(2, 0.5, 0) -> vec3(2, 0, 0)

it relied mostly on mathematical operations to achieve this by leveraging the lin alg hardware built into most gpus as much as possible, but I don't remember how the snippet looked like.


Solution

  • You need the calculate the absolute value of the vector and the component-wise maximum of vector in GLSL. Finally you can use greaterThanEqual:

    vec3 vabs = abs(v);
    float m = max(vabs.x, max(vabs.y, vabs.z));
    vec3 vmax = v * vec3(greaterThanEqual(vabs, vec3(m)));