WaterShader.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. /**
  2. * @author jbouny / https://github.com/jbouny
  3. *
  4. * Work based on :
  5. * @author Slayvin / http://slayvin.net : Flat mirror for three.js
  6. * @author Stemkoski / http://www.adelphi.edu/~stemkoski : An implementation of water shader based on the flat mirror
  7. * @author Jonas Wagner / http://29a.ch/ && http://29a.ch/slides/2012/webglwater/ : Water shader explanations in WebGL
  8. */
  9. THREE.ShaderLib[ 'water' ] = {
  10. uniforms: THREE.UniformsUtils.merge( [
  11. THREE.UniformsLib[ "fog" ], {
  12. "normalSampler": { value: null },
  13. "mirrorSampler": { value: null },
  14. "alpha": { value: 1.0 },
  15. "time": { value: 0.0 },
  16. "distortionScale": { value: 20.0 },
  17. "noiseScale": { value: 1.0 },
  18. "textureMatrix" : { value: new THREE.Matrix4() },
  19. "sunColor": { value: new THREE.Color( 0x7F7F7F ) },
  20. "sunDirection": { value: new THREE.Vector3( 0.70707, 0.70707, 0 ) },
  21. "eye": { value: new THREE.Vector3() },
  22. "waterColor": { value: new THREE.Color( 0x555555 ) }
  23. }
  24. ] ),
  25. vertexShader: [
  26. 'uniform mat4 textureMatrix;',
  27. 'uniform float time;',
  28. 'varying vec4 mirrorCoord;',
  29. 'varying vec3 worldPosition;',
  30. THREE.ShaderChunk[ "fog_pars_vertex"],
  31. 'void main()',
  32. '{',
  33. ' mirrorCoord = modelMatrix * vec4( position, 1.0 );',
  34. ' worldPosition = mirrorCoord.xyz;',
  35. ' mirrorCoord = textureMatrix * mirrorCoord;',
  36. ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );',
  37. THREE.ShaderChunk[ "fog_vertex"],
  38. '}'
  39. ].join( '\n' ),
  40. fragmentShader: [
  41. 'precision highp float;',
  42. 'uniform sampler2D mirrorSampler;',
  43. 'uniform float alpha;',
  44. 'uniform float time;',
  45. 'uniform float distortionScale;',
  46. 'uniform sampler2D normalSampler;',
  47. 'uniform vec3 sunColor;',
  48. 'uniform vec3 sunDirection;',
  49. 'uniform vec3 eye;',
  50. 'uniform vec3 waterColor;',
  51. 'varying vec4 mirrorCoord;',
  52. 'varying vec3 worldPosition;',
  53. 'vec4 getNoise( vec2 uv )',
  54. '{',
  55. ' vec2 uv0 = ( uv / 103.0 ) + vec2(time / 17.0, time / 29.0);',
  56. ' vec2 uv1 = uv / 107.0-vec2( time / -19.0, time / 31.0 );',
  57. ' vec2 uv2 = uv / vec2( 8907.0, 9803.0 ) + vec2( time / 101.0, time / 97.0 );',
  58. ' vec2 uv3 = uv / vec2( 1091.0, 1027.0 ) - vec2( time / 109.0, time / -113.0 );',
  59. ' vec4 noise = texture2D( normalSampler, uv0 ) +',
  60. ' texture2D( normalSampler, uv1 ) +',
  61. ' texture2D( normalSampler, uv2 ) +',
  62. ' texture2D( normalSampler, uv3 );',
  63. ' return noise * 0.5 - 1.0;',
  64. '}',
  65. 'void sunLight( const vec3 surfaceNormal, const vec3 eyeDirection, float shiny, float spec, float diffuse, inout vec3 diffuseColor, inout vec3 specularColor )',
  66. '{',
  67. ' vec3 reflection = normalize( reflect( -sunDirection, surfaceNormal ) );',
  68. ' float direction = max( 0.0, dot( eyeDirection, reflection ) );',
  69. ' specularColor += pow( direction, shiny ) * sunColor * spec;',
  70. ' diffuseColor += max( dot( sunDirection, surfaceNormal ), 0.0 ) * sunColor * diffuse;',
  71. '}',
  72. THREE.ShaderChunk[ "common" ],
  73. THREE.ShaderChunk[ "fog_pars_fragment" ],
  74. 'void main()',
  75. '{',
  76. ' vec4 noise = getNoise( worldPosition.xz );',
  77. ' vec3 surfaceNormal = normalize( noise.xzy * vec3( 1.5, 1.0, 1.5 ) );',
  78. ' vec3 diffuseLight = vec3(0.0);',
  79. ' vec3 specularLight = vec3(0.0);',
  80. ' vec3 worldToEye = eye-worldPosition;',
  81. ' vec3 eyeDirection = normalize( worldToEye );',
  82. ' sunLight( surfaceNormal, eyeDirection, 100.0, 2.0, 0.5, diffuseLight, specularLight );',
  83. ' float distance = length(worldToEye);',
  84. ' vec2 distortion = surfaceNormal.xz * ( 0.001 + 1.0 / distance ) * distortionScale;',
  85. ' vec3 reflectionSample = vec3( texture2D( mirrorSampler, mirrorCoord.xy / mirrorCoord.z + distortion ) );',
  86. ' float theta = max( dot( eyeDirection, surfaceNormal ), 0.0 );',
  87. ' float rf0 = 0.3;',
  88. ' float reflectance = rf0 + ( 1.0 - rf0 ) * pow( ( 1.0 - theta ), 5.0 );',
  89. ' vec3 scatter = max( 0.0, dot( surfaceNormal, eyeDirection ) ) * waterColor;',
  90. ' vec3 albedo = mix( sunColor * diffuseLight * 0.3 + scatter, ( vec3( 0.1 ) + reflectionSample * 0.9 + reflectionSample * specularLight ), reflectance );',
  91. ' vec3 outgoingLight = albedo;',
  92. THREE.ShaderChunk[ "fog_fragment" ],
  93. ' gl_FragColor = vec4( outgoingLight, alpha );',
  94. '}'
  95. ].join( '\n' )
  96. };
  97. THREE.Water = function ( renderer, camera, scene, options ) {
  98. THREE.Object3D.call( this );
  99. this.name = 'water_' + this.id;
  100. function optionalParameter ( value, defaultValue ) {
  101. return value !== undefined ? value : defaultValue;
  102. }
  103. options = options || {};
  104. this.matrixNeedsUpdate = true;
  105. var width = optionalParameter( options.textureWidth, 512 );
  106. var height = optionalParameter( options.textureHeight, 512 );
  107. this.clipBias = optionalParameter( options.clipBias, 0.0 );
  108. this.alpha = optionalParameter( options.alpha, 1.0 );
  109. this.time = optionalParameter( options.time, 0.0 );
  110. this.normalSampler = optionalParameter( options.waterNormals, null );
  111. this.sunDirection = optionalParameter( options.sunDirection, new THREE.Vector3( 0.70707, 0.70707, 0.0 ) );
  112. this.sunColor = new THREE.Color( optionalParameter( options.sunColor, 0xffffff ) );
  113. this.waterColor = new THREE.Color( optionalParameter( options.waterColor, 0x7F7F7F ) );
  114. this.eye = optionalParameter( options.eye, new THREE.Vector3( 0, 0, 0 ) );
  115. this.distortionScale = optionalParameter( options.distortionScale, 20.0 );
  116. this.side = optionalParameter( options.side, THREE.FrontSide );
  117. this.fog = optionalParameter( options.fog, false );
  118. this.renderer = renderer;
  119. this.scene = scene;
  120. this.mirrorPlane = new THREE.Plane();
  121. this.normal = new THREE.Vector3( 0, 0, 1 );
  122. this.mirrorWorldPosition = new THREE.Vector3();
  123. this.cameraWorldPosition = new THREE.Vector3();
  124. this.rotationMatrix = new THREE.Matrix4();
  125. this.lookAtPosition = new THREE.Vector3( 0, 0, - 1 );
  126. this.clipPlane = new THREE.Vector4();
  127. if ( camera instanceof THREE.PerspectiveCamera ) {
  128. this.camera = camera;
  129. } else {
  130. this.camera = new THREE.PerspectiveCamera();
  131. console.log( this.name + ': camera is not a Perspective Camera!' );
  132. }
  133. this.textureMatrix = new THREE.Matrix4();
  134. this.mirrorCamera = this.camera.clone();
  135. this.renderTarget = new THREE.WebGLRenderTarget( width, height );
  136. this.renderTarget2 = new THREE.WebGLRenderTarget( width, height );
  137. var mirrorShader = THREE.ShaderLib[ "water" ];
  138. var mirrorUniforms = THREE.UniformsUtils.clone( mirrorShader.uniforms );
  139. this.material = new THREE.ShaderMaterial( {
  140. fragmentShader: mirrorShader.fragmentShader,
  141. vertexShader: mirrorShader.vertexShader,
  142. uniforms: mirrorUniforms,
  143. transparent: true,
  144. side: this.side,
  145. fog: this.fog
  146. } );
  147. this.material.uniforms.mirrorSampler.value = this.renderTarget.texture;
  148. this.material.uniforms.textureMatrix.value = this.textureMatrix;
  149. this.material.uniforms.alpha.value = this.alpha;
  150. this.material.uniforms.time.value = this.time;
  151. this.material.uniforms.normalSampler.value = this.normalSampler;
  152. this.material.uniforms.sunColor.value = this.sunColor;
  153. this.material.uniforms.waterColor.value = this.waterColor;
  154. this.material.uniforms.sunDirection.value = this.sunDirection;
  155. this.material.uniforms.distortionScale.value = this.distortionScale;
  156. this.material.uniforms.eye.value = this.eye;
  157. if ( ! THREE.Math.isPowerOfTwo( width ) || ! THREE.Math.isPowerOfTwo( height ) ) {
  158. this.renderTarget.texture.generateMipmaps = false;
  159. this.renderTarget.texture.minFilter = THREE.LinearFilter;
  160. this.renderTarget2.texture.generateMipmaps = false;
  161. this.renderTarget2.texture.minFilter = THREE.LinearFilter;
  162. }
  163. this.updateTextureMatrix();
  164. this.render();
  165. };
  166. THREE.Water.prototype = Object.create( THREE.Mirror.prototype );
  167. THREE.Water.prototype.constructor = THREE.Water;
  168. THREE.Water.prototype.updateTextureMatrix = function () {
  169. function sign( x ) {
  170. return x ? x < 0 ? - 1 : 1 : 0;
  171. }
  172. this.updateMatrixWorld();
  173. this.camera.updateMatrixWorld();
  174. this.mirrorWorldPosition.setFromMatrixPosition( this.matrixWorld );
  175. this.cameraWorldPosition.setFromMatrixPosition( this.camera.matrixWorld );
  176. this.rotationMatrix.extractRotation( this.matrixWorld );
  177. this.normal.set( 0, 0, 1 );
  178. this.normal.applyMatrix4( this.rotationMatrix );
  179. var view = this.mirrorWorldPosition.clone().sub( this.cameraWorldPosition );
  180. view.reflect( this.normal ).negate();
  181. view.add( this.mirrorWorldPosition );
  182. this.rotationMatrix.extractRotation( this.camera.matrixWorld );
  183. this.lookAtPosition.set( 0, 0, - 1 );
  184. this.lookAtPosition.applyMatrix4( this.rotationMatrix );
  185. this.lookAtPosition.add( this.cameraWorldPosition );
  186. var target = this.mirrorWorldPosition.clone().sub( this.lookAtPosition );
  187. target.reflect( this.normal ).negate();
  188. target.add( this.mirrorWorldPosition );
  189. this.up.set( 0, - 1, 0 );
  190. this.up.applyMatrix4( this.rotationMatrix );
  191. this.up.reflect( this.normal ).negate();
  192. this.mirrorCamera.position.copy( view );
  193. this.mirrorCamera.up = this.up;
  194. this.mirrorCamera.lookAt( target );
  195. this.mirrorCamera.aspect = this.camera.aspect;
  196. this.mirrorCamera.updateProjectionMatrix();
  197. this.mirrorCamera.updateMatrixWorld();
  198. this.mirrorCamera.matrixWorldInverse.getInverse( this.mirrorCamera.matrixWorld );
  199. // Update the texture matrix
  200. this.textureMatrix.set( 0.5, 0.0, 0.0, 0.5,
  201. 0.0, 0.5, 0.0, 0.5,
  202. 0.0, 0.0, 0.5, 0.5,
  203. 0.0, 0.0, 0.0, 1.0 );
  204. this.textureMatrix.multiply( this.mirrorCamera.projectionMatrix );
  205. this.textureMatrix.multiply( this.mirrorCamera.matrixWorldInverse );
  206. // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
  207. // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
  208. this.mirrorPlane.setFromNormalAndCoplanarPoint( this.normal, this.mirrorWorldPosition );
  209. this.mirrorPlane.applyMatrix4( this.mirrorCamera.matrixWorldInverse );
  210. this.clipPlane.set( this.mirrorPlane.normal.x, this.mirrorPlane.normal.y, this.mirrorPlane.normal.z, this.mirrorPlane.constant );
  211. var q = new THREE.Vector4();
  212. var projectionMatrix = this.mirrorCamera.projectionMatrix;
  213. q.x = ( sign( this.clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
  214. q.y = ( sign( this.clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
  215. q.z = - 1.0;
  216. q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];
  217. // Calculate the scaled plane vector
  218. var c = new THREE.Vector4();
  219. c = this.clipPlane.multiplyScalar( 2.0 / this.clipPlane.dot( q ) );
  220. // Replacing the third row of the projection matrix
  221. projectionMatrix.elements[ 2 ] = c.x;
  222. projectionMatrix.elements[ 6 ] = c.y;
  223. projectionMatrix.elements[ 10 ] = c.z + 1.0 - this.clipBias;
  224. projectionMatrix.elements[ 14 ] = c.w;
  225. var worldCoordinates = new THREE.Vector3();
  226. worldCoordinates.setFromMatrixPosition( this.camera.matrixWorld );
  227. this.eye = worldCoordinates;
  228. this.material.uniforms.eye.value = this.eye;
  229. };