FragShader.fsh 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. uniform sampler2D NormalTex;
  2. uniform sampler2D ReflectionTex;
  3. #ifdef ENABLE_REFRACTION
  4. uniform sampler2D RefractionTex;
  5. #endif
  6. uniform samplerCube NormalisationCubeMap;
  7. uniform mediump mat4 ModelViewMatrix;
  8. uniform lowp vec4 WaterColour;
  9. #ifdef ENABLE_DISTORTION
  10. uniform mediump float WaveDistortion;
  11. #endif
  12. uniform mediump vec2 RcpWindowSize;
  13. varying mediump vec2 BumpCoord0;
  14. varying mediump vec2 BumpCoord1;
  15. varying mediump vec3 WaterToEye;
  16. varying mediump float WaterToEyeLength;
  17. void main()
  18. {
  19. // Calculate the tex coords of the fragment (using it's position on the screen)
  20. lowp vec3 vAccumulatedNormal = vec3(0.0,1.0,0.0);
  21. mediump vec2 vTexCoord = gl_FragCoord.xy * RcpWindowSize;
  22. #ifdef ENABLE_DISTORTION
  23. // When distortion is enabled, use the normal map to calculate perturbation
  24. vAccumulatedNormal = texture2D(NormalTex, BumpCoord0).rgb;
  25. vAccumulatedNormal += texture2D(NormalTex, BumpCoord1).rgb;
  26. vAccumulatedNormal -= 1.0; // Same as * 2.0 - 2.0
  27. lowp vec2 vTmp = vAccumulatedNormal.xz;
  28. /*
  29. Divide by WaterToEyeLength to scale down the distortion
  30. of fragments based on their distance from the camera
  31. */
  32. vTexCoord.xy -= vTmp * (WaveDistortion / length(WaterToEye));
  33. #endif
  34. #ifdef ENABLE_REFRACTION
  35. lowp vec4 vReflectionColour = texture2D(ReflectionTex, vTexCoord);
  36. lowp vec4 vRefractionColour = texture2D(RefractionTex, vTexCoord);
  37. #ifdef ENABLE_FRESNEL
  38. // Calculate the Fresnel term to determine amount of reflection for each fragment
  39. // Use normalisation cube map instead of normalize() - See section 3.3.1 of white paper for more info
  40. lowp vec3 vWaterToEyeCube = textureCube(NormalisationCubeMap,WaterToEye).rgb * 2.0 - 1.0;
  41. mediump float fEyeToNormalAngle = clamp(dot(vWaterToEyeCube, vAccumulatedNormal),0.0,1.0);
  42. mediump float fAirWaterFresnel = 1.0 - fEyeToNormalAngle;
  43. fAirWaterFresnel = pow(fAirWaterFresnel, 5.0);
  44. fAirWaterFresnel = (0.98 * fAirWaterFresnel) + 0.02; // R(0)-1 = ~0.98 , R(0)= ~0.02
  45. lowp float fTemp = fAirWaterFresnel;
  46. // Blend reflection and refraction
  47. gl_FragColor = mix(vRefractionColour, vReflectionColour, fTemp);
  48. #else
  49. gl_FragColor = mix(vRefractionColour, vReflectionColour, 0.4); // Constant mix
  50. #endif
  51. #else
  52. gl_FragColor = texture2D(ReflectionTex, vTexCoord); // Reflection only
  53. #endif
  54. }