| 1 |
//------------------------------------------------------------------------------ |
| 2 |
// Fog |
| 3 |
//------------------------------------------------------------------------------ |
| 4 |
|
| 5 |
vec4 fog(vec4 color, vec3 view) { |
| 6 |
if (frameUniforms.fogDensity > 0.0) { |
| 7 |
float A = frameUniforms.fogDensity; |
| 8 |
float B = frameUniforms.fogHeightFalloff; |
| 9 |
|
| 10 |
float d = length(view); |
| 11 |
|
| 12 |
float h = max(0.001, view.y); |
| 13 |
// The function below is continuous at h=0, so to avoid a divide-by-zero, we just clamp h |
| 14 |
float fogIntegralFunctionOfDistance = A * ((1.0 - exp(-B * h)) / h); |
| 15 |
float fogIntegral = fogIntegralFunctionOfDistance * max(d - frameUniforms.fogStart, 0.0); |
| 16 |
float fogOpacity = max(1.0 - exp2(-fogIntegral), 0.0); |
| 17 |
|
| 18 |
// don't go above requested max opacity |
| 19 |
fogOpacity = min(fogOpacity, frameUniforms.fogMaxOpacity); |
| 20 |
|
| 21 |
// compute fog color |
| 22 |
vec3 fogColor = frameUniforms.fogColor; |
| 23 |
|
| 24 |
if (frameUniforms.fogColorFromIbl > 0.0) { |
| 25 |
// get fog color from envmap |
| 26 |
float lod = frameUniforms.iblRoughnessOneLevel; |
| 27 |
fogColor *= textureLod(light_iblSpecular, view, lod).rgb * frameUniforms.iblLuminance; |
| 28 |
} |
| 29 |
|
| 30 |
fogColor *= fogOpacity; |
| 31 |
if (frameUniforms.fogInscatteringSize > 0.0) { |
| 32 |
// compute a new line-integral for a different start distance |
| 33 |
float inscatteringIntegral = fogIntegralFunctionOfDistance * |
| 34 |
max(d - frameUniforms.fogInscatteringStart, 0.0); |
| 35 |
float inscatteringOpacity = max(1.0 - exp2(-inscatteringIntegral), 0.0); |
| 36 |
|
| 37 |
// Add sun colored fog when looking towards the sun |
| 38 |
vec3 sunColor = frameUniforms.lightColorIntensity.rgb * frameUniforms.lightColorIntensity.w; |
| 39 |
float sunAmount = max(dot(view, frameUniforms.lightDirection) / d, 0.0); // between 0 and 1 |
| 40 |
float sunInscattering = pow(sunAmount, frameUniforms.fogInscatteringSize); |
| 41 |
|
| 42 |
fogColor += sunColor * (sunInscattering * inscatteringOpacity); |
| 43 |
} |
| 44 |
|
| 45 |
#if defined(BLEND_MODE_OPAQUE) |
| 46 |
// nothing to do here |
| 47 |
#elif defined(BLEND_MODE_TRANSPARENT) |
| 48 |
fogColor *= color.a; |
| 49 |
#elif defined(BLEND_MODE_ADD) |
| 50 |
fogColor = vec3(0.0); |
| 51 |
#elif defined(BLEND_MODE_MASKED) |
| 52 |
// nothing to do here |
| 53 |
#elif defined(BLEND_MODE_MULTIPLY) |
| 54 |
// FIXME: unclear what to do here |
| 55 |
#elif defined(BLEND_MODE_SCREEN) |
| 56 |
// FIXME: unclear what to do here |
| 57 |
#endif |
| 58 |
|
| 59 |
color.rgb = color.rgb * (1.0 - fogOpacity) + fogColor; |
| 60 |
} |
| 61 |
return color; |
| 62 |
} |