To draw semi-transparent geometry, the most common technique is to use
alpha blending. In this technique, the alpha value for each
fragment drawn reflects the transparency of that object. Each
fragment is combined with the values in the frame buffer using the
blending equation
Here, is the output color which will be written to the frame
buffer.
and
are the source color and alpha, which
come from the fragment.
is the destination color, which is
the color value currently in the frame buffer at the location. This
equation is specified using the OpenGL command
glBlendFuncGL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA).
Blending is then enabled with glEnableGL_BLEND(GL_BLEND).
A common mistake when implementing alpha blending is to assume that it requires a frame buffer with an alpha channel. Note that the alpha values in the frame buffer (GL_DST_ALPHA) are not actually used, so no alpha buffer is required.
For the alpha blending technique to work correctly, the transparent
primitives must be drawn in back to front order and must not
intersect. To convince ourselves of this, we can consider two objects
and
with colors
and
and alphas
and
. Assume that
is in front of
and that the frame
buffer has been cleared to black. If
is drawn first,
will not be drawn at all unless depth buffering is disabled. Turning off
depth buffering generally is a bad idea, but even if we could turn it off,
the results would still be incorrect. After
had been drawn,
the frame buffer color would be
. After
had been
drawn, the color would be
. If
had been drawn first, the value would be
. Sorting will be discussed in detail in Section
10.3.
The alpha channel of the fragment can be set in several ways. If lighting is not being used, then the alpha value can be set using a 4 component color command such as glColor4fv(). If lighting is enabled, then the ambient and diffuse reflectance coefficients of the material should correspond to the translucency of the object.
If texturing is enabled, the source of the alpha channel is controlled by the texture internal format, the texture environment function, and the texture environment constant color. The interaction is described in more detail in the glTexEnv() man page. Many intricate effects can be implemented using alpha values from textures.