Optimizing pixel-swapping shader

Viewed 89

I'm using a shader that swaps colors/palettes on a texture. The shader checks a pixel for transparency and then sets the pixel if not transparent. Is there an efficient way to ignore 0 alpha pixels other than a potential branch? In this case, where I set pixel = newPixel:

uniform bool alternate;
uniform sampler2D texture;

void main()
{
    vec4 pixel = texture2D(bitmap, openfl_TextureCoordv);

    if(alternate)
    {
        vec4 newPixel = texture2D(texture, vec2(pixel.r, pixel.b));

        if(newPixel.a != 0.0)
            pixel = newPixel;
    }

    gl_FragColor = pixel;

}
2 Answers

You can use mix and step:

void main()
{
    vec4 pixel = texture2D(bitmap, openfl_TextureCoordv);
    vec4 newPixel = texture2D(texture, vec2(pixel.r, pixel.b));
    gl_FragColor = mix(pixel, newPixel, 
                       float(alternate) * (1.0 - step(newPixel.a, 0.0)));
}

You may want to make a smooth transition depending on the alpha channel. In this case you only need mix:

gl_FragColor = mix(pixel, newPixel, float(alternate) * newPixel.a);

I would look into the step function. You can express the if statement as a product of two conditions.

For example:

if (a >= 0) {
  b = c;
}

Is equivalent to

b = (step(a, 0)*c) + (1.0 - step(a, 0)*b);
Related