Transparency
Our colors are actually 4 channels: red, green, blue, and alpha. We will use the alpha channel to aid in rendering transparent objects. The alpha value represents opacity: 1 is fully opaque, 0 is fully transparent.
When rendering transparency, background objects show through a transparent object. There are then two colors to consider, the background one and the transparent one. We will call the background color the destination and the transparent object color the source color. Along with the colors, there is also a source alpha and destination alpha.
We want to combine or blend these colors using two scales: a source factor s and a destination factor d. These blend factors are often set using the source or destination alpha.
However, Z-buffering makes transparency difficult. Since the Z-buffer only tracks the closest objects, drawing a nearby transparent object will result in all background objects failing to render, since their depth values will not pass the z test. A common solution is to:
- Render the opaque objects
- Sort transparent objects by view depth
- Render transparent objects farthest to nearest
- Use source factor source alpha, destination factor one minus alpha
Blending in OpenGL
Blending in OpenGL can be enabled withglEnable(GL_BLEND)
. The blend factors are set using glBlendFunc(sourceFactor, destFactor)
. There are many factors that can be used; see the documentation for details. Since the depths in the Z-buffer influence transparency so much, some algorithms disable depth updates, but still perform the depth test. The can be done with the glDepthMask
function.
Blend example
Depth testing is enabled and the purple triangle is closer than the yellow.Blending function (s,d) | ||||
---|---|---|---|---|
1, 0 | srcα,1−srcα | dstα,1−dstα | ||
Draw order | purple, yellow | ![]() |
![]() |
![]() |
yellow, purple | ![]() |
![]() |
![]() |