Water.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  1. import {
  2. Color,
  3. FrontSide,
  4. LinearFilter,
  5. MathUtils,
  6. Matrix4,
  7. Mesh,
  8. PerspectiveCamera,
  9. Plane,
  10. RGBFormat,
  11. ShaderMaterial,
  12. UniformsLib,
  13. UniformsUtils,
  14. Vector3,
  15. Vector4,
  16. WebGLRenderTarget
  17. } from '../../../build/three.module.js';
  18. /**
  19. * Work based on :
  20. * http://slayvin.net : Flat mirror for three.js
  21. * http://www.adelphi.edu/~stemkoski : An implementation of water shader based on the flat mirror
  22. * http://29a.ch/ && http://29a.ch/slides/2012/webglwater/ : Water shader explanations in WebGL
  23. */
  24. var Water = function ( geometry, options ) {
  25. Mesh.call( this, geometry );
  26. var scope = this;
  27. options = options || {};
  28. var textureWidth = options.textureWidth !== undefined ? options.textureWidth : 512;
  29. var textureHeight = options.textureHeight !== undefined ? options.textureHeight : 512;
  30. var clipBias = options.clipBias !== undefined ? options.clipBias : 0.0;
  31. var alpha = options.alpha !== undefined ? options.alpha : 1.0;
  32. var time = options.time !== undefined ? options.time : 0.0;
  33. var normalSampler = options.waterNormals !== undefined ? options.waterNormals : null;
  34. var sunDirection = options.sunDirection !== undefined ? options.sunDirection : new Vector3( 0.70707, 0.70707, 0.0 );
  35. var sunColor = new Color( options.sunColor !== undefined ? options.sunColor : 0xffffff );
  36. var waterColor = new Color( options.waterColor !== undefined ? options.waterColor : 0x7F7F7F );
  37. var eye = options.eye !== undefined ? options.eye : new Vector3( 0, 0, 0 );
  38. var distortionScale = options.distortionScale !== undefined ? options.distortionScale : 20.0;
  39. var side = options.side !== undefined ? options.side : FrontSide;
  40. var fog = options.fog !== undefined ? options.fog : false;
  41. //
  42. var mirrorPlane = new Plane();
  43. var normal = new Vector3();
  44. var mirrorWorldPosition = new Vector3();
  45. var cameraWorldPosition = new Vector3();
  46. var rotationMatrix = new Matrix4();
  47. var lookAtPosition = new Vector3( 0, 0, - 1 );
  48. var clipPlane = new Vector4();
  49. var view = new Vector3();
  50. var target = new Vector3();
  51. var q = new Vector4();
  52. var textureMatrix = new Matrix4();
  53. var mirrorCamera = new PerspectiveCamera();
  54. var parameters = {
  55. minFilter: LinearFilter,
  56. magFilter: LinearFilter,
  57. format: RGBFormat
  58. };
  59. var renderTarget = new WebGLRenderTarget( textureWidth, textureHeight, parameters );
  60. if ( ! MathUtils.isPowerOfTwo( textureWidth ) || ! MathUtils.isPowerOfTwo( textureHeight ) ) {
  61. renderTarget.texture.generateMipmaps = false;
  62. }
  63. var mirrorShader = {
  64. uniforms: UniformsUtils.merge( [
  65. UniformsLib[ 'fog' ],
  66. UniformsLib[ 'lights' ],
  67. {
  68. 'normalSampler': { value: null },
  69. 'mirrorSampler': { value: null },
  70. 'alpha': { value: 1.0 },
  71. 'time': { value: 0.0 },
  72. 'size': { value: 1.0 },
  73. 'distortionScale': { value: 20.0 },
  74. 'textureMatrix': { value: new Matrix4() },
  75. 'sunColor': { value: new Color( 0x7F7F7F ) },
  76. 'sunDirection': { value: new Vector3( 0.70707, 0.70707, 0 ) },
  77. 'eye': { value: new Vector3() },
  78. 'waterColor': { value: new Color( 0x555555 ) }
  79. }
  80. ] ),
  81. vertexShader: [
  82. 'uniform mat4 textureMatrix;',
  83. 'uniform float time;',
  84. 'varying vec4 mirrorCoord;',
  85. 'varying vec4 worldPosition;',
  86. '#include <common>',
  87. '#include <fog_pars_vertex>',
  88. '#include <shadowmap_pars_vertex>',
  89. '#include <logdepthbuf_pars_vertex>',
  90. 'void main() {',
  91. ' mirrorCoord = modelMatrix * vec4( position, 1.0 );',
  92. ' worldPosition = mirrorCoord.xyzw;',
  93. ' mirrorCoord = textureMatrix * mirrorCoord;',
  94. ' vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );',
  95. ' gl_Position = projectionMatrix * mvPosition;',
  96. '#include <beginnormal_vertex>',
  97. '#include <defaultnormal_vertex>',
  98. '#include <logdepthbuf_vertex>',
  99. '#include <fog_vertex>',
  100. '#include <shadowmap_vertex>',
  101. '}'
  102. ].join( '\n' ),
  103. fragmentShader: [
  104. 'uniform sampler2D mirrorSampler;',
  105. 'uniform float alpha;',
  106. 'uniform float time;',
  107. 'uniform float size;',
  108. 'uniform float distortionScale;',
  109. 'uniform sampler2D normalSampler;',
  110. 'uniform vec3 sunColor;',
  111. 'uniform vec3 sunDirection;',
  112. 'uniform vec3 eye;',
  113. 'uniform vec3 waterColor;',
  114. 'varying vec4 mirrorCoord;',
  115. 'varying vec4 worldPosition;',
  116. 'vec4 getNoise( vec2 uv ) {',
  117. ' vec2 uv0 = ( uv / 103.0 ) + vec2(time / 17.0, time / 29.0);',
  118. ' vec2 uv1 = uv / 107.0-vec2( time / -19.0, time / 31.0 );',
  119. ' vec2 uv2 = uv / vec2( 8907.0, 9803.0 ) + vec2( time / 101.0, time / 97.0 );',
  120. ' vec2 uv3 = uv / vec2( 1091.0, 1027.0 ) - vec2( time / 109.0, time / -113.0 );',
  121. ' vec4 noise = texture2D( normalSampler, uv0 ) +',
  122. ' texture2D( normalSampler, uv1 ) +',
  123. ' texture2D( normalSampler, uv2 ) +',
  124. ' texture2D( normalSampler, uv3 );',
  125. ' return noise * 0.5 - 1.0;',
  126. '}',
  127. 'void sunLight( const vec3 surfaceNormal, const vec3 eyeDirection, float shiny, float spec, float diffuse, inout vec3 diffuseColor, inout vec3 specularColor ) {',
  128. ' vec3 reflection = normalize( reflect( -sunDirection, surfaceNormal ) );',
  129. ' float direction = max( 0.0, dot( eyeDirection, reflection ) );',
  130. ' specularColor += pow( direction, shiny ) * sunColor * spec;',
  131. ' diffuseColor += max( dot( sunDirection, surfaceNormal ), 0.0 ) * sunColor * diffuse;',
  132. '}',
  133. '#include <common>',
  134. '#include <packing>',
  135. '#include <bsdfs>',
  136. '#include <fog_pars_fragment>',
  137. '#include <logdepthbuf_pars_fragment>',
  138. '#include <lights_pars_begin>',
  139. '#include <shadowmap_pars_fragment>',
  140. '#include <shadowmask_pars_fragment>',
  141. 'void main() {',
  142. '#include <logdepthbuf_fragment>',
  143. ' vec4 noise = getNoise( worldPosition.xz * size );',
  144. ' vec3 surfaceNormal = normalize( noise.xzy * vec3( 1.5, 1.0, 1.5 ) );',
  145. ' vec3 diffuseLight = vec3(0.0);',
  146. ' vec3 specularLight = vec3(0.0);',
  147. ' vec3 worldToEye = eye-worldPosition.xyz;',
  148. ' vec3 eyeDirection = normalize( worldToEye );',
  149. ' sunLight( surfaceNormal, eyeDirection, 100.0, 2.0, 0.5, diffuseLight, specularLight );',
  150. ' float distance = length(worldToEye);',
  151. ' vec2 distortion = surfaceNormal.xz * ( 0.001 + 1.0 / distance ) * distortionScale;',
  152. ' vec3 reflectionSample = vec3( texture2D( mirrorSampler, mirrorCoord.xy / mirrorCoord.w + distortion ) );',
  153. ' float theta = max( dot( eyeDirection, surfaceNormal ), 0.0 );',
  154. ' float rf0 = 0.3;',
  155. ' float reflectance = rf0 + ( 1.0 - rf0 ) * pow( ( 1.0 - theta ), 5.0 );',
  156. ' vec3 scatter = max( 0.0, dot( surfaceNormal, eyeDirection ) ) * waterColor;',
  157. ' vec3 albedo = mix( ( sunColor * diffuseLight * 0.3 + scatter ) * getShadowMask(), ( vec3( 0.1 ) + reflectionSample * 0.9 + reflectionSample * specularLight ), reflectance);',
  158. ' vec3 outgoingLight = albedo;',
  159. ' gl_FragColor = vec4( outgoingLight, alpha );',
  160. '#include <tonemapping_fragment>',
  161. '#include <fog_fragment>',
  162. '}'
  163. ].join( '\n' )
  164. };
  165. var material = new ShaderMaterial( {
  166. fragmentShader: mirrorShader.fragmentShader,
  167. vertexShader: mirrorShader.vertexShader,
  168. uniforms: UniformsUtils.clone( mirrorShader.uniforms ),
  169. lights: true,
  170. side: side,
  171. fog: fog
  172. } );
  173. material.uniforms[ 'mirrorSampler' ].value = renderTarget.texture;
  174. material.uniforms[ 'textureMatrix' ].value = textureMatrix;
  175. material.uniforms[ 'alpha' ].value = alpha;
  176. material.uniforms[ 'time' ].value = time;
  177. material.uniforms[ 'normalSampler' ].value = normalSampler;
  178. material.uniforms[ 'sunColor' ].value = sunColor;
  179. material.uniforms[ 'waterColor' ].value = waterColor;
  180. material.uniforms[ 'sunDirection' ].value = sunDirection;
  181. material.uniforms[ 'distortionScale' ].value = distortionScale;
  182. material.uniforms[ 'eye' ].value = eye;
  183. scope.material = material;
  184. scope.onBeforeRender = function ( renderer, scene, camera ) {
  185. mirrorWorldPosition.setFromMatrixPosition( scope.matrixWorld );
  186. cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld );
  187. rotationMatrix.extractRotation( scope.matrixWorld );
  188. normal.set( 0, 0, 1 );
  189. normal.applyMatrix4( rotationMatrix );
  190. view.subVectors( mirrorWorldPosition, cameraWorldPosition );
  191. // Avoid rendering when mirror is facing away
  192. if ( view.dot( normal ) > 0 ) return;
  193. view.reflect( normal ).negate();
  194. view.add( mirrorWorldPosition );
  195. rotationMatrix.extractRotation( camera.matrixWorld );
  196. lookAtPosition.set( 0, 0, - 1 );
  197. lookAtPosition.applyMatrix4( rotationMatrix );
  198. lookAtPosition.add( cameraWorldPosition );
  199. target.subVectors( mirrorWorldPosition, lookAtPosition );
  200. target.reflect( normal ).negate();
  201. target.add( mirrorWorldPosition );
  202. mirrorCamera.position.copy( view );
  203. mirrorCamera.up.set( 0, 1, 0 );
  204. mirrorCamera.up.applyMatrix4( rotationMatrix );
  205. mirrorCamera.up.reflect( normal );
  206. mirrorCamera.lookAt( target );
  207. mirrorCamera.far = camera.far; // Used in WebGLBackground
  208. mirrorCamera.updateMatrixWorld();
  209. mirrorCamera.projectionMatrix.copy( camera.projectionMatrix );
  210. // Update the texture matrix
  211. textureMatrix.set(
  212. 0.5, 0.0, 0.0, 0.5,
  213. 0.0, 0.5, 0.0, 0.5,
  214. 0.0, 0.0, 0.5, 0.5,
  215. 0.0, 0.0, 0.0, 1.0
  216. );
  217. textureMatrix.multiply( mirrorCamera.projectionMatrix );
  218. textureMatrix.multiply( mirrorCamera.matrixWorldInverse );
  219. // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
  220. // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
  221. mirrorPlane.setFromNormalAndCoplanarPoint( normal, mirrorWorldPosition );
  222. mirrorPlane.applyMatrix4( mirrorCamera.matrixWorldInverse );
  223. clipPlane.set( mirrorPlane.normal.x, mirrorPlane.normal.y, mirrorPlane.normal.z, mirrorPlane.constant );
  224. var projectionMatrix = mirrorCamera.projectionMatrix;
  225. q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
  226. q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
  227. q.z = - 1.0;
  228. q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];
  229. // Calculate the scaled plane vector
  230. clipPlane.multiplyScalar( 2.0 / clipPlane.dot( q ) );
  231. // Replacing the third row of the projection matrix
  232. projectionMatrix.elements[ 2 ] = clipPlane.x;
  233. projectionMatrix.elements[ 6 ] = clipPlane.y;
  234. projectionMatrix.elements[ 10 ] = clipPlane.z + 1.0 - clipBias;
  235. projectionMatrix.elements[ 14 ] = clipPlane.w;
  236. eye.setFromMatrixPosition( camera.matrixWorld );
  237. // Render
  238. var currentRenderTarget = renderer.getRenderTarget();
  239. var currentXrEnabled = renderer.xr.enabled;
  240. var currentShadowAutoUpdate = renderer.shadowMap.autoUpdate;
  241. scope.visible = false;
  242. renderer.xr.enabled = false; // Avoid camera modification and recursion
  243. renderer.shadowMap.autoUpdate = false; // Avoid re-computing shadows
  244. renderer.setRenderTarget( renderTarget );
  245. renderer.state.buffers.depth.setMask( true ); // make sure the depth buffer is writable so it can be properly cleared, see #18897
  246. if ( renderer.autoClear === false ) renderer.clear();
  247. renderer.render( scene, mirrorCamera );
  248. scope.visible = true;
  249. renderer.xr.enabled = currentXrEnabled;
  250. renderer.shadowMap.autoUpdate = currentShadowAutoUpdate;
  251. renderer.setRenderTarget( currentRenderTarget );
  252. // Restore viewport
  253. var viewport = camera.viewport;
  254. if ( viewport !== undefined ) {
  255. renderer.state.viewport( viewport );
  256. }
  257. };
  258. };
  259. Water.prototype = Object.create( Mesh.prototype );
  260. Water.prototype.constructor = Water;
  261. export { Water };