Water2.js 8.4 KB

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