fog.frag 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /* bloom.frag -- Fragment shader for applying fog to the scene
  2. *
  3. * Copyright (c) 2025-2026 Le Juez Victor
  4. *
  5. * This software is provided 'as-is', without any express or implied warranty.
  6. * For conditions of distribution and use, see accompanying LICENSE file.
  7. */
  8. #version 330 core
  9. /* === Includes === */
  10. #include "../include/blocks/view.glsl"
  11. /* === Definitions === */
  12. #define FOG_DISABLED 0
  13. #define FOG_LINEAR 1
  14. #define FOG_EXP2 2
  15. #define FOG_EXP 3
  16. /* === Varyings === */
  17. noperspective in vec2 vTexCoord;
  18. /* === Uniforms === */
  19. uniform sampler2D uSceneTex;
  20. uniform sampler2D uDepthTex;
  21. uniform lowp int uFogMode;
  22. uniform vec3 uFogColor;
  23. uniform float uFogStart;
  24. uniform float uFogEnd;
  25. uniform float uFogDensity;
  26. uniform float uSkyAffect;
  27. /* === Fragments === */
  28. out vec4 FragColor;
  29. // === Helper functions === //
  30. float FogFactorLinear(float dist, float start, float end)
  31. {
  32. return 1.0 - clamp((end - dist) / (end - start), 0.0, 1.0);
  33. }
  34. float FogFactorExp2(float dist, float density)
  35. {
  36. const float LOG2 = -1.442695;
  37. float d = density * dist;
  38. return 1.0 - clamp(exp2(d * d * LOG2), 0.0, 1.0);
  39. }
  40. float FogFactorExp(float dist, float density)
  41. {
  42. return 1.0 - clamp(exp(-density * dist), 0.0, 1.0);
  43. }
  44. float FogFactor(float dist, int mode, float density, float start, float end)
  45. {
  46. if (mode == FOG_LINEAR) return FogFactorLinear(dist, start, end);
  47. if (mode == FOG_EXP2) return FogFactorExp2(dist, density);
  48. if (mode == FOG_EXP) return FogFactorExp(dist, density);
  49. return 1.0; // FOG_DISABLED
  50. }
  51. // === Main program === //
  52. void main()
  53. {
  54. vec3 color = texelFetch(uSceneTex, ivec2(gl_FragCoord.xy), 0).rgb;
  55. float depth = texelFetch(uDepthTex, ivec2(gl_FragCoord.xy), 0).r;
  56. float fogFactor = FogFactor(depth, uFogMode, uFogDensity, uFogStart, uFogEnd);
  57. fogFactor *= mix(1.0, uSkyAffect, step(uView.far, depth));
  58. color = mix(color, uFogColor, fogFactor);
  59. FragColor = vec4(color, 1.0);
  60. }