Water2.js 8.2 KB

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