WaterRefractionShader.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. ( function () {
  2. const WaterRefractionShader = {
  3. uniforms: {
  4. 'color': {
  5. value: null
  6. },
  7. 'time': {
  8. value: 0
  9. },
  10. 'tDiffuse': {
  11. value: null
  12. },
  13. 'tDudv': {
  14. value: null
  15. },
  16. 'textureMatrix': {
  17. value: null
  18. }
  19. },
  20. vertexShader: `uniform mat4 textureMatrix;
  21. varying vec2 vUv;
  22. varying vec4 vUvRefraction;
  23. void main() {
  24. vUv = uv;
  25. vUvRefraction = textureMatrix * vec4( position, 1.0 );
  26. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  27. }`,
  28. fragmentShader: `uniform vec3 color;
  29. uniform float time;
  30. uniform sampler2D tDiffuse;
  31. uniform sampler2D tDudv;
  32. varying vec2 vUv;
  33. varying vec4 vUvRefraction;
  34. float blendOverlay( float base, float blend ) {
  35. return( base < 0.5 ? ( 2.0 * base * blend ) : ( 1.0 - 2.0 * ( 1.0 - base ) * ( 1.0 - blend ) ) );
  36. }
  37. vec3 blendOverlay( vec3 base, vec3 blend ) {
  38. return vec3( blendOverlay( base.r, blend.r ), blendOverlay( base.g, blend.g ),blendOverlay( base.b, blend.b ) );
  39. }
  40. void main() {
  41. float waveStrength = 0.1;
  42. float waveSpeed = 0.03;
  43. // simple distortion (ripple) via dudv map (see https://www.youtube.com/watch?v=6B7IF6GOu7s)
  44. vec2 distortedUv = texture2D( tDudv, vec2( vUv.x + time * waveSpeed, vUv.y ) ).rg * waveStrength;
  45. distortedUv = vUv.xy + vec2( distortedUv.x, distortedUv.y + time * waveSpeed );
  46. vec2 distortion = ( texture2D( tDudv, distortedUv ).rg * 2.0 - 1.0 ) * waveStrength;
  47. // new uv coords
  48. vec4 uv = vec4( vUvRefraction );
  49. uv.xy += distortion;
  50. vec4 base = texture2DProj( tDiffuse, uv );
  51. gl_FragColor = vec4( blendOverlay( base.rgb, color ), 1.0 );
  52. }`
  53. };
  54. THREE.WaterRefractionShader = WaterRefractionShader;
  55. } )();