WaterRefractionShader.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. /**
  2. * @module WaterRefractionShader
  3. * @three_import import { WaterRefractionShader } from 'three/addons/shaders/WaterRefractionShader.js';
  4. */
  5. /**
  6. * Basic water refraction shader.
  7. *
  8. * @constant
  9. * @type {ShaderMaterial~Shader}
  10. */
  11. const WaterRefractionShader = {
  12. name: 'WaterRefractionShader',
  13. uniforms: {
  14. 'color': {
  15. value: null
  16. },
  17. 'time': {
  18. value: 0
  19. },
  20. 'tDiffuse': {
  21. value: null
  22. },
  23. 'tDudv': {
  24. value: null
  25. },
  26. 'textureMatrix': {
  27. value: null
  28. }
  29. },
  30. vertexShader: /* glsl */`
  31. uniform mat4 textureMatrix;
  32. varying vec2 vUv;
  33. varying vec4 vUvRefraction;
  34. void main() {
  35. vUv = uv;
  36. vUvRefraction = textureMatrix * vec4( position, 1.0 );
  37. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  38. }`,
  39. fragmentShader: /* glsl */`
  40. uniform vec3 color;
  41. uniform float time;
  42. uniform sampler2D tDiffuse;
  43. uniform sampler2D tDudv;
  44. varying vec2 vUv;
  45. varying vec4 vUvRefraction;
  46. float blendOverlay( float base, float blend ) {
  47. return( base < 0.5 ? ( 2.0 * base * blend ) : ( 1.0 - 2.0 * ( 1.0 - base ) * ( 1.0 - blend ) ) );
  48. }
  49. vec3 blendOverlay( vec3 base, vec3 blend ) {
  50. return vec3( blendOverlay( base.r, blend.r ), blendOverlay( base.g, blend.g ),blendOverlay( base.b, blend.b ) );
  51. }
  52. void main() {
  53. float waveStrength = 0.5;
  54. float waveSpeed = 0.03;
  55. // simple distortion (ripple) via dudv map (see https://www.youtube.com/watch?v=6B7IF6GOu7s)
  56. vec2 distortedUv = texture2D( tDudv, vec2( vUv.x + time * waveSpeed, vUv.y ) ).rg * waveStrength;
  57. distortedUv = vUv.xy + vec2( distortedUv.x, distortedUv.y + time * waveSpeed );
  58. vec2 distortion = ( texture2D( tDudv, distortedUv ).rg * 2.0 - 1.0 ) * waveStrength;
  59. // new uv coords
  60. vec4 uv = vec4( vUvRefraction );
  61. uv.xy += distortion;
  62. vec4 base = texture2DProj( tDiffuse, uv );
  63. gl_FragColor = vec4( blendOverlay( base.rgb, color ), 1.0 );
  64. #include <tonemapping_fragment>
  65. #include <colorspace_fragment>
  66. }`
  67. };
  68. export { WaterRefractionShader };