Height Fog - Advanced Rendering - Shader Learning

Advanced Rendering

Height Fog

Task

Enhance a scene rendered using deferred shading by adding a height fog effect. The fog should start at a height of 0.0 units and become completely transparent at a height of 9.0 units. Use fogColor for blending.

Theory

Height Fog is a technique used in computer graphics to simulate fog that varies in density based on the height of the terrain or objects in the scene. This type of fog is particularly useful for creating realistic atmospheric effects where fog is denser in lower areas, such as valleys or near the ground, and becomes less dense at higher altitudes, such as on hills or mountains.


How Height Fog Works


The fog is calculated using an exponential function that depends on the height of the fragment. The formula for the fog factor in exponential height fog is:

$ Fog = e^{ -(FragPosY - FogOriginY) / Density } $

The $Fog$ factor is then clamped to the range $[0.0, 1.0]$ to ensure it stays within valid bounds. $FogOriginY$ - the height at which the fog starts to decrease.


When the fragment's Y position is below the fog origin height, the $Fog$ is $1.0$. As the fragment's Y position increases above the fog origin height, the fog density decreases, leading to clearer visibility.


Fog Height


Sometimes it's easier to control fog by setting the height where it disappears, instead of adjusting the density value. That's because the height is something you can see and measure directly in your scene - for example, fog that stays near the ground and fades as you go higher.


By choosing the height where the fog becomes almost invisible, you can control how it looks around mountains, buildings, or characters. You don’t need to tweak density manually - just pick the height where you want the fog to stop.


To determine the fog density, we need to establish the height at which the fog becomes nearly invisible. Typically, this is the height where the fog intensity reaches $1%$ of its maximum value. By substituting this value into the equation, we get:

$ 0.01 = e^{ - FogHeight / Density } $

taking the natural logarithm of both sides:

$ \ln (0.01) = \frac {- FogHeight } { Density } $

solving for $Denisity$:

$ Density = \frac { - FogHeight } { \ln (0.01) } $

the natural logarithm of $0.01$ is approximately $-4.605$. Therefore, the formula for fog density becomes:

$ Density \approx \frac { FogHeight } { 4.605 } $

the final height fog expression:

$ Fog = e^{ -4.605 \cdot (FragPosY - FogOriginY) / FogHeight } $