Water.glsl 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. // Thanks for the contribution Jonas
  2. // http://29a.ch/2012/7/19/webgl-terrain-rendering-water-fog
  3. uniform sampler2D specularMap;
  4. uniform sampler2D normalMap;
  5. uniform vec4 baseWaterColor;
  6. uniform vec4 blendColor;
  7. uniform float frequency;
  8. uniform float animationSpeed;
  9. uniform float amplitude;
  10. uniform float specularIntensity;
  11. uniform float fadeFactor;
  12. czm_material czm_getMaterial(czm_materialInput materialInput)
  13. {
  14. czm_material material = czm_getDefaultMaterial(materialInput);
  15. float time = czm_frameNumber * animationSpeed;
  16. // fade is a function of the distance from the fragment and the frequency of the waves
  17. float fade = max(1.0, (length(materialInput.positionToEyeEC) / 10000000000.0) * frequency * fadeFactor);
  18. float specularMapValue = texture2D(specularMap, materialInput.st).r;
  19. // note: not using directional motion at this time, just set the angle to 0.0;
  20. vec4 noise = czm_getWaterNoise(normalMap, materialInput.st * frequency, time, 0.0);
  21. vec3 normalTangentSpace = noise.xyz * vec3(1.0, 1.0, (1.0 / amplitude));
  22. // fade out the normal perturbation as we move further from the water surface
  23. normalTangentSpace.xy /= fade;
  24. // attempt to fade out the normal perturbation as we approach non water areas (low specular map value)
  25. normalTangentSpace = mix(vec3(0.0, 0.0, 50.0), normalTangentSpace, specularMapValue);
  26. normalTangentSpace = normalize(normalTangentSpace);
  27. // get ratios for alignment of the new normal vector with a vector perpendicular to the tangent plane
  28. float tsPerturbationRatio = clamp(dot(normalTangentSpace, vec3(0.0, 0.0, 1.0)), 0.0, 1.0);
  29. // fade out water effect as specular map value decreases
  30. material.alpha = specularMapValue;
  31. // base color is a blend of the water and non-water color based on the value from the specular map
  32. // may need a uniform blend factor to better control this
  33. material.diffuse = mix(blendColor.rgb, baseWaterColor.rgb, specularMapValue);
  34. // diffuse highlights are based on how perturbed the normal is
  35. material.diffuse += (0.1 * tsPerturbationRatio);
  36. material.normal = normalize(materialInput.tangentToEyeMatrix * normalTangentSpace);
  37. material.specular = specularIntensity;
  38. material.shininess = 10.0;
  39. return material;
  40. }