Other Blend Functions

If you read the documentation for glBlendFunction(), you'll see that there are many other options for the blending formula, besides the standard one we've been using.

The blending formula takes the general form:

R = SourceFactor * Rs + DestinationFactor * Rd
G = SourceFactor * Gs + DestinationFactor * Gd
B = SourceFactor * Bs + DestinationFactor * Bd

where (Rs, Gs, Bs) is the source color (object being drawn), and (Rd, Gd, Bd) is the destination color (color already in the framebuffer).
SourceFactor and DestinationFactor are two scaling factors between 0 and 1, which are calculated from the alpha or color values, as defined by the last call to glBlendFunc(). In some cases the factor will have a different value for red, green, and blue.

The possible values for SourceFactor & DestinationFactor are:

Factor name Computed factor
GL_ZERO 0
GL_ONE 1

GL_SRC_ALPHA As
GL_ONE_MINUS_SRC_ALPHA 1 - As
 
GL_DST_ALPHA Ad
GL_ONE_MINUS_DST_ALPHA 1 - Ad
 
GL_CONSTANT_ALPHA Ac
GL_ONE_MINUS_CONSTANT_ALPHA 1 - Ac

GL_SRC_COLOR (Rs, Gs, Bs)
GL_ONE_MINUS_SRC_COLOR (1 - Rs, 1 - Gs, 1 - Bs)
 
GL_DST_COLOR (Rd, Gd, Bd)
GL_ONE_MINUS_DST_COLOR (1 - Rd, 1 - Gd, 1 - Bd)
 
GL_CONSTANT_COLOR (Rc, Gc, Bc)
GL_ONE_MINUS_CONSTANT_COLOR (1 - Rc, 1 - Gc, 1 - Bc)

GL_SRC_ALPHA_SATURATE min(As, 1 - Ad)

[Note: the blending factors & formula are also applied to the alpha itself; I've left this out for simplicity.]

Applications

One use for these other blending functions is to apply different color filters to your scene.

This can be done by drawing a square that covers the entire window, as the last step in rendering, with the appropriate blending function and color.

 /* Dim the scene */

glBlendFunc(GL_ZERO, GL_SRC_ALPHA);
glColor4f(1.0, 1.0, 1.0, 0.5);
 /* Apply a purple filter */

glBlendFunc(GL_ZERO, GL_SRC_COLOR);
glColor4f(1.0, 0.0, 0.5, 1.0);
 /* Invert all the colors */

glBlendFunc(GL_ONE_MINUS_DST_COLOR, GL_ZERO);
glColor4f(1.0, 1.0, 1.0, 1.0);

Example code: filter.c



next