Graphics Reference
In-Depth Information
Example 14-17
Noise-Distorted Fog Fragment Shader (continued)
{
float factor;
// Compute linear fog equation
float dist = distance( v_eyePos,
vec4( 0.0, 0.0, 0.0, 1.0 ) );
factor = (u_fogMaxDist − dist) /
(u_fogMaxDist − u_fogMinDist );
// Clamp in the [0, 1] range
factor = clamp( factor, 0.0, 1.0 );
return factor;
}
void main( void )
{
float fogFactor = computeLinearFogFactor();
vec3 noiseCoord =
vec3( v_texCoord.xy + u_time, u_time );
fogFactor −=
texture(s_noiseTex, noiseCoord).r * 0.25;
fogFactor = clamp(fogFactor, 0.0, 1.0);
vec4 baseColor = v_color;
outColor = baseColor * fogFactor +
u_fogColor * (1.0 − fogFactor);
}
This shader is very similar to our linear fog example in Chapter 10,
“Fragment Shaders.” The primary difference is that the linear fog factor
is distorted by the 3D noise texture. The shader computes a 3D texture
coordinate based on time and places it in noiseCoord . The u_time uniform
variable is tied to the current time and is updated each frame. The 3D
texture is set up with s, t , and r wrap modes of GL_MIRRORED_REPEAT so that
the noise volume scrolls smoothly on the surface. The ( s , t ) coordinates are
based on the coordinates for the base texture and scroll in both directions.
The r -coordinate is based purely on time; thus it is continuously scrolled.
The 3D texture is a single-channel (GL_R8) texture, so only the red
component of the texture is used (the green and blue channels have the same
value as the red channel). The value fetched from the volume is subtracted
from the computed fogFactor and then used to linearly interpolate between
the fog color and base color. The result is a wispy fog that appears to roll in
from a distance. Its speed can be increased easily by applying a scale to the
u_time variable when scrolling the 3D texture coordinates.
You can achieve a number of different effects by using a 3D texture to
represent noise. For example, you can use noise to represent dust in a
 
 
Search WWH ::




Custom Search