Chapter 9
You can use fog to achieve a number of effects in Microsoft Direct3D Immediate Mode applications. By adding fog to a scene, you can simulate the real world in a powerful way. Combined with the right sounds and music, fog can help you create worlds that convey a range of atmospheres, from mysterious or creepy to fantastic or other-worldly to pastoral or humorous. Even more important for real-time applications, in which you need to eke out the last possible bit of performance, you can use fog to hide the bizarre and distracting effects of objects popping into existence as they cross into the viewing frustum. To prevent popping, you just set up fog so that users can't see beyond the far clipping plane.
Direct3D implements fog by blending the color of each object in a scene with the fog color you select. The amount of blending that occurs is based on the object's distance from the viewpoint. Direct3D blends the colors of distant objects so that the object's final color approximates the color of the fog. The colors of objects that are near the viewpoint change slightly or not at all. For example, if you use a color such as blue or white as your fog color, your objects will become increasingly obscured the farther away from the viewpoint they are, producing the illusion of fog. If you use black as your fog color, objects will appear to fade into the darkness in a night scene. If the scene has a solid background color (that is, if rendered objects don't cover every screen pixel), you should set the fog color to that background color. If objects are rendered over every screen pixel, however, you can pick any fog color you like. Then, as polygons recede from the camera, they will smoothly fade into the background. In this case, white will give you a realistically fogged scene.
Direct3D supplies two different forms of fog you can use in a scene: vertex fog and pixel fog. (We'll examine these types of fog in detail later in the chapter.) To determine what capabilities the host system has, you can check for the following flags in the dwShadeCaps member of the D3DPRIMCAPS structure:
And you can check for the following flags in the dwRasterCaps member of the D3DPRIMCAPS structure:
Before examining how to use the two available types of fog, let's look at how Direct3D computes the fog for a scene.