Component-wise GLSL vector branching

Posted by Gustavo Maciel on Game Development See other posts from Game Development or by Gustavo Maciel
Published on 2014-06-12T14:44:22Z Indexed on 2014/06/12 21:41 UTC
Read the original article Hit count: 340

Filed under:
|
|

I'm aware that it usually is a BAD idea to operate separately on GLSL vec's components separately. For example:

//use instrinsic functions, they do the calculation on 4 components at a time.
float dot = v1.x*v2.x + v1.y * v2.y + v1.z * v2.z; //NEVER
float dot = dot(v1, v2); //YES
//Multiply one by one is not good too, since the ALU can do the 4 components at a time too.
vec3 mul = vec3(v1.x * v2.x, v1.y * v2.y, v1.z * v2.z); //NEVER
vec3 mul = v1 * v2;

I've been struggling thinking, are there equivalent operations for branching?

For example:

vec4 Overlay(vec4 v1, vec4 v2, vec4 opacity)
{
    bvec4 less = lessThan(v1, vec4(0.5));
    vec4 blend;
    for(int i = 0; i < 4; ++i)
    {
    if(less[i])
            blend[i] = 2.0 * v1[i]*v2[i];
        else
            blend[i] = 1.0 - 2.0 * (1.0 - v1[i])*(1.0 - v2[i]);
    }
    return v1 + (blend-v1)*opacity;
}

This is a Overlay operator that works component wise. I'm not sure if this is the best way to do it, since I'm afraid these for and if can be a bottleneck later.

Tl;dr, Can I branch component wise? If yes, how can I optimize that Overlay function with it?

© Game Development or respective owner

Related posts about shaders

Related posts about glsl