Water2.js 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. ( function () {
  2. /**
  3. * References:
  4. * http://www.valvesoftware.com/publications/2010/siggraph2010_vlachos_waterflow.pdf
  5. * http://graphicsrunner.blogspot.de/2010/08/water-using-flow-maps.html
  6. *
  7. */
  8. class Water extends THREE.Mesh {
  9. constructor( geometry, options = {} ) {
  10. super( geometry );
  11. this.type = 'Water';
  12. const scope = this;
  13. const color = options.color !== undefined ? new THREE.Color( options.color ) : new THREE.Color( 0xFFFFFF );
  14. const textureWidth = options.textureWidth || 512;
  15. const textureHeight = options.textureHeight || 512;
  16. const clipBias = options.clipBias || 0;
  17. const flowDirection = options.flowDirection || new THREE.Vector2( 1, 0 );
  18. const flowSpeed = options.flowSpeed || 0.03;
  19. const reflectivity = options.reflectivity || 0.02;
  20. const scale = options.scale || 1;
  21. const shader = options.shader || Water.WaterShader;
  22. const encoding = options.encoding !== undefined ? options.encoding : THREE.LinearEncoding;
  23. const textureLoader = new THREE.TextureLoader();
  24. const flowMap = options.flowMap || undefined;
  25. const normalMap0 = options.normalMap0 || textureLoader.load( 'textures/water/Water_1_M_Normal.jpg' );
  26. const normalMap1 = options.normalMap1 || textureLoader.load( 'textures/water/Water_2_M_Normal.jpg' );
  27. const cycle = 0.15; // a cycle of a flow map phase
  28. const halfCycle = cycle * 0.5;
  29. const textureMatrix = new THREE.Matrix4();
  30. const clock = new THREE.Clock(); // internal components
  31. if ( THREE.Reflector === undefined ) {
  32. console.error( 'THREE.Water: Required component THREE.Reflector not found.' );
  33. return;
  34. }
  35. if ( THREE.Refractor === undefined ) {
  36. console.error( 'THREE.Water: Required component THREE.Refractor not found.' );
  37. return;
  38. }
  39. const reflector = new THREE.Reflector( geometry, {
  40. textureWidth: textureWidth,
  41. textureHeight: textureHeight,
  42. clipBias: clipBias,
  43. encoding: encoding
  44. } );
  45. const refractor = new THREE.Refractor( geometry, {
  46. textureWidth: textureWidth,
  47. textureHeight: textureHeight,
  48. clipBias: clipBias,
  49. encoding: encoding
  50. } );
  51. reflector.matrixAutoUpdate = false;
  52. refractor.matrixAutoUpdate = false; // material
  53. this.material = new THREE.ShaderMaterial( {
  54. uniforms: THREE.UniformsUtils.merge( [ THREE.UniformsLib[ 'fog' ], shader.uniforms ] ),
  55. vertexShader: shader.vertexShader,
  56. fragmentShader: shader.fragmentShader,
  57. transparent: true,
  58. fog: true
  59. } );
  60. if ( flowMap !== undefined ) {
  61. this.material.defines.USE_FLOWMAP = '';
  62. this.material.uniforms[ 'tFlowMap' ] = {
  63. type: 't',
  64. value: flowMap
  65. };
  66. } else {
  67. this.material.uniforms[ 'flowDirection' ] = {
  68. type: 'v2',
  69. value: flowDirection
  70. };
  71. } // maps
  72. normalMap0.wrapS = normalMap0.wrapT = THREE.RepeatWrapping;
  73. normalMap1.wrapS = normalMap1.wrapT = THREE.RepeatWrapping;
  74. this.material.uniforms[ 'tReflectionMap' ].value = reflector.getRenderTarget().texture;
  75. this.material.uniforms[ 'tRefractionMap' ].value = refractor.getRenderTarget().texture;
  76. this.material.uniforms[ 'tNormalMap0' ].value = normalMap0;
  77. this.material.uniforms[ 'tNormalMap1' ].value = normalMap1; // water
  78. this.material.uniforms[ 'color' ].value = color;
  79. this.material.uniforms[ 'reflectivity' ].value = reflectivity;
  80. this.material.uniforms[ 'textureMatrix' ].value = textureMatrix; // inital values
  81. this.material.uniforms[ 'config' ].value.x = 0; // flowMapOffset0
  82. this.material.uniforms[ 'config' ].value.y = halfCycle; // flowMapOffset1
  83. this.material.uniforms[ 'config' ].value.z = halfCycle; // halfCycle
  84. this.material.uniforms[ 'config' ].value.w = scale; // scale
  85. // functions
  86. function updateTextureMatrix( camera ) {
  87. textureMatrix.set( 0.5, 0.0, 0.0, 0.5, 0.0, 0.5, 0.0, 0.5, 0.0, 0.0, 0.5, 0.5, 0.0, 0.0, 0.0, 1.0 );
  88. textureMatrix.multiply( camera.projectionMatrix );
  89. textureMatrix.multiply( camera.matrixWorldInverse );
  90. textureMatrix.multiply( scope.matrixWorld );
  91. }
  92. function updateFlow() {
  93. const delta = clock.getDelta();
  94. const config = scope.material.uniforms[ 'config' ];
  95. config.value.x += flowSpeed * delta; // flowMapOffset0
  96. config.value.y = config.value.x + halfCycle; // flowMapOffset1
  97. // Important: The distance between offsets should be always the value of "halfCycle".
  98. // Moreover, both offsets should be in the range of [ 0, cycle ].
  99. // This approach ensures a smooth water flow and avoids "reset" effects.
  100. if ( config.value.x >= cycle ) {
  101. config.value.x = 0;
  102. config.value.y = halfCycle;
  103. } else if ( config.value.y >= cycle ) {
  104. config.value.y = config.value.y - cycle;
  105. }
  106. } //
  107. this.onBeforeRender = function ( renderer, scene, camera ) {
  108. updateTextureMatrix( camera );
  109. updateFlow();
  110. scope.visible = false;
  111. reflector.matrixWorld.copy( scope.matrixWorld );
  112. refractor.matrixWorld.copy( scope.matrixWorld );
  113. reflector.onBeforeRender( renderer, scene, camera );
  114. refractor.onBeforeRender( renderer, scene, camera );
  115. scope.visible = true;
  116. };
  117. }
  118. }
  119. Water.prototype.isWater = true;
  120. Water.WaterShader = {
  121. uniforms: {
  122. 'color': {
  123. type: 'c',
  124. value: null
  125. },
  126. 'reflectivity': {
  127. type: 'f',
  128. value: 0
  129. },
  130. 'tReflectionMap': {
  131. type: 't',
  132. value: null
  133. },
  134. 'tRefractionMap': {
  135. type: 't',
  136. value: null
  137. },
  138. 'tNormalMap0': {
  139. type: 't',
  140. value: null
  141. },
  142. 'tNormalMap1': {
  143. type: 't',
  144. value: null
  145. },
  146. 'textureMatrix': {
  147. type: 'm4',
  148. value: null
  149. },
  150. 'config': {
  151. type: 'v4',
  152. value: new THREE.Vector4()
  153. }
  154. },
  155. vertexShader:
  156. /* glsl */
  157. `
  158. #include <common>
  159. #include <fog_pars_vertex>
  160. #include <logdepthbuf_pars_vertex>
  161. uniform mat4 textureMatrix;
  162. varying vec4 vCoord;
  163. varying vec2 vUv;
  164. varying vec3 vToEye;
  165. void main() {
  166. vUv = uv;
  167. vCoord = textureMatrix * vec4( position, 1.0 );
  168. vec4 worldPosition = modelMatrix * vec4( position, 1.0 );
  169. vToEye = cameraPosition - worldPosition.xyz;
  170. vec4 mvPosition = viewMatrix * worldPosition; // used in fog_vertex
  171. gl_Position = projectionMatrix * mvPosition;
  172. #include <logdepthbuf_vertex>
  173. #include <fog_vertex>
  174. }`,
  175. fragmentShader:
  176. /* glsl */
  177. `
  178. #include <common>
  179. #include <fog_pars_fragment>
  180. #include <logdepthbuf_pars_fragment>
  181. uniform sampler2D tReflectionMap;
  182. uniform sampler2D tRefractionMap;
  183. uniform sampler2D tNormalMap0;
  184. uniform sampler2D tNormalMap1;
  185. #ifdef USE_FLOWMAP
  186. uniform sampler2D tFlowMap;
  187. #else
  188. uniform vec2 flowDirection;
  189. #endif
  190. uniform vec3 color;
  191. uniform float reflectivity;
  192. uniform vec4 config;
  193. varying vec4 vCoord;
  194. varying vec2 vUv;
  195. varying vec3 vToEye;
  196. void main() {
  197. #include <logdepthbuf_fragment>
  198. float flowMapOffset0 = config.x;
  199. float flowMapOffset1 = config.y;
  200. float halfCycle = config.z;
  201. float scale = config.w;
  202. vec3 toEye = normalize( vToEye );
  203. // determine flow direction
  204. vec2 flow;
  205. #ifdef USE_FLOWMAP
  206. flow = texture2D( tFlowMap, vUv ).rg * 2.0 - 1.0;
  207. #else
  208. flow = flowDirection;
  209. #endif
  210. flow.x *= - 1.0;
  211. // sample normal maps (distort uvs with flowdata)
  212. vec4 normalColor0 = texture2D( tNormalMap0, ( vUv * scale ) + flow * flowMapOffset0 );
  213. vec4 normalColor1 = texture2D( tNormalMap1, ( vUv * scale ) + flow * flowMapOffset1 );
  214. // linear interpolate to get the final normal color
  215. float flowLerp = abs( halfCycle - flowMapOffset0 ) / halfCycle;
  216. vec4 normalColor = mix( normalColor0, normalColor1, flowLerp );
  217. // calculate normal vector
  218. vec3 normal = normalize( vec3( normalColor.r * 2.0 - 1.0, normalColor.b, normalColor.g * 2.0 - 1.0 ) );
  219. // calculate the fresnel term to blend reflection and refraction maps
  220. float theta = max( dot( toEye, normal ), 0.0 );
  221. float reflectance = reflectivity + ( 1.0 - reflectivity ) * pow( ( 1.0 - theta ), 5.0 );
  222. // calculate final uv coords
  223. vec3 coord = vCoord.xyz / vCoord.w;
  224. vec2 uv = coord.xy + coord.z * normal.xz * 0.05;
  225. vec4 reflectColor = texture2D( tReflectionMap, vec2( 1.0 - uv.x, uv.y ) );
  226. vec4 refractColor = texture2D( tRefractionMap, uv );
  227. // multiply water color with the mix of both textures
  228. gl_FragColor = vec4( color, 1.0 ) * mix( refractColor, reflectColor, reflectance );
  229. #include <tonemapping_fragment>
  230. #include <encodings_fragment>
  231. #include <fog_fragment>
  232. }`
  233. };
  234. THREE.Water = Water;
  235. } )();