How to do a branchless discard?

601 Views Asked by At

I have a fairly basic fragment shader which can sample from texture and change the assigned fixed color based on the sample. If I sample from the texture, I do an alpha check and discard low-alpha values. Is there a way to make this process branchless?

#version 460 core
layout (location = 0) out vec4 FragColor;

uniform vec4 color;
uniform sampler2D tex;
uniform bool useTex;
in vec2 texCoords;

void main() {
   vec4 tex = texture(tex, texCoords);
   if(useTex && tex.a < 0.1) { discard; }
   vec4 outColor = mix(color, color * tex, int(useTex));
   FragColor = outColor;
}
1

There are 1 best solutions below

0
Rabbid76 On

I recommend always binding a texture, at least a 1x1 texture with the color (1, 1, 1, 1). With this approach, you can omit out useTex entirely and the shader is much simpler:

#version 460 core

layout (location = 0) out vec4 FragColor;

uniform vec4 color;
uniform sampler2D tex;
in vec2 texCoords;

void main() 
{
    vec4 outColor = color * texture(tex, texCoords);
    if (outColor.a < 0.1)
        discard;
    FragColor = outColor;
}

If you could use Blending instead of discard, the shader could be further simplified:

#version 460 core

layout (location = 0) out vec4 FragColor;

uniform vec4 color;
uniform sampler2D tex;
in vec2 texCoords;

void main() 
{
    FragColor = color * texture(tex, texCoords);
}