Alpha Test

Alpha-textured objects have the same problem as simpler transparent objects - they must be drawn from front to back in order for the blending to work correctly.

For example, if several cutout trees are drawn in an arbitrary order, we might see this:


Turning off blending makes it clearer what's happening - the invisible "card" that the front tree is drawn on hides part of the trees behind it:

Because our alpha channel in this case is very basic - it's either fully opaque or fully transparent - we can use glAlphaFunc in place of blending.

The alpha test is a simpler transparency mechanism than blending. If a pixel passes the alpha function, it's drawn normally; if it fails the alpha function, it's not drawn at all, and no change is made to the depth buffer. As a result, it's very useful for the cutout-style alpha in our tree example.

To use the alpha test, enable it, and select a function and a reference value. e.g.:

glEnable(GL_ALPHA_TEST);
glAlphaFunc(GL_GREATER, 0.25);

will draw any pixel with an alpha greater than 25%. Anything 25% or less is transparent.

If you have an alpha channel with soft edges, you could combine blending and alpha testing. The alpha test will throw out whatever pixels you define as fully transparent; the blending will apply to the remaining pixels.

glEnable(GL_ALPHA_TEST);
glAlphaFunc(GL_GREATER, 0.25);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

In this case, most things will appear alright, but looking closely you will be able to see haloes around transparent objects that haven't been drawn in back to front order:

Example code: crayoland2.c



next