Is this optimal? (two texture reads)

I was wandering if the following is a good practice or not:


// part of a frag shader
float a = texture2D( tex, tex_coords ).a;
if( a == 0.0 ) discard;
gl_FragColor.rgb = texture2D( tex, tex_coords ).rgb;

In the above code I have 2 texture reads. Is there another more optimal way to discard if the alpha of the texture is zero?


vec4 color = texture2D( tex, tex_coords );
if(color.a==0.0)discard;
gl_FragColor=color;

yes, you’re sampling twice as llian says (even though you’re only using the alpha initially, it’s still sampling the whole texel and giving you the alpha).
an alternative to discard is to use the alpha test glEnable(GL_ALPHA_TEST), and allowing the texel to pass through the rest of the logic in your shader - the end result will not write to the colour or depth buffers.

Thanks for the answers. I believe though that alpha testing is deprecated in 3.2. Isn’t it?

well using the alpha test is only going to be quicker on older cards where discards are expensive but alpha tests are quick. It’s just a legitimate alternative to discard at the moment, but obviously not the right way to do it.

Yes it is. To the best of my knowledge, the performance hit with using discard is that it disables early z but so does using the alpha test so I won’t worry about it. I suppose performance also depends on how well the branch is handled. Refer to the NVIDIA GPU Programming Guide for more information.

Regards,
Patrick

This topic was automatically closed 183 days after the last reply. New replies are no longer allowed.