Water2.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  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. /** @module Water2 */
  17. /**
  18. * An advanced water effect that supports reflections, refractions and flow maps.
  19. *
  20. * Note that this class can only be used with {@link WebGLRenderer}.
  21. * When using {@link WebGPURenderer}, use {@link module:Water2Mesh}.
  22. *
  23. * References:
  24. *
  25. * - {@link https://alex.vlachos.com/graphics/Vlachos-SIGGRAPH10-WaterFlow.pdf}
  26. * - {@link http://graphicsrunner.blogspot.de/2010/08/water-using-flow-maps.html}
  27. *
  28. * @augments Mesh
  29. */
  30. class Water extends Mesh {
  31. /**
  32. * Constructs a new water instance.
  33. *
  34. * @param {BufferGeometry} geometry - The water's geometry.
  35. * @param {module:Water2~Options} [options] - The configuration options.
  36. */
  37. constructor( geometry, options = {} ) {
  38. super( geometry );
  39. /**
  40. * This flag can be used for type testing.
  41. *
  42. * @type {boolean}
  43. * @readonly
  44. * @default true
  45. */
  46. this.isWater = true;
  47. this.type = 'Water';
  48. const scope = this;
  49. const color = ( options.color !== undefined ) ? new Color( options.color ) : new Color( 0xFFFFFF );
  50. const textureWidth = options.textureWidth !== undefined ? options.textureWidth : 512;
  51. const textureHeight = options.textureHeight !== undefined ? options.textureHeight : 512;
  52. const clipBias = options.clipBias !== undefined ? options.clipBias : 0;
  53. const flowDirection = options.flowDirection !== undefined ? options.flowDirection : new Vector2( 1, 0 );
  54. const flowSpeed = options.flowSpeed !== undefined ? options.flowSpeed : 0.03;
  55. const reflectivity = options.reflectivity !== undefined ? options.reflectivity : 0.02;
  56. const scale = options.scale !== undefined ? options.scale : 1;
  57. const shader = options.shader !== undefined ? options.shader : Water.WaterShader;
  58. const textureLoader = new TextureLoader();
  59. const flowMap = options.flowMap || undefined;
  60. const normalMap0 = options.normalMap0 || textureLoader.load( 'textures/water/Water_1_M_Normal.jpg' );
  61. const normalMap1 = options.normalMap1 || textureLoader.load( 'textures/water/Water_2_M_Normal.jpg' );
  62. const cycle = 0.15; // a cycle of a flow map phase
  63. const halfCycle = cycle * 0.5;
  64. const textureMatrix = new Matrix4();
  65. const clock = new Clock();
  66. // internal components
  67. if ( Reflector === undefined ) {
  68. console.error( 'THREE.Water: Required component Reflector not found.' );
  69. return;
  70. }
  71. if ( Refractor === undefined ) {
  72. console.error( 'THREE.Water: Required component Refractor not found.' );
  73. return;
  74. }
  75. const reflector = new Reflector( geometry, {
  76. textureWidth: textureWidth,
  77. textureHeight: textureHeight,
  78. clipBias: clipBias
  79. } );
  80. const refractor = new Refractor( geometry, {
  81. textureWidth: textureWidth,
  82. textureHeight: textureHeight,
  83. clipBias: clipBias
  84. } );
  85. reflector.matrixAutoUpdate = false;
  86. refractor.matrixAutoUpdate = false;
  87. // material
  88. this.material = new ShaderMaterial( {
  89. name: shader.name,
  90. uniforms: UniformsUtils.merge( [
  91. UniformsLib[ 'fog' ],
  92. shader.uniforms
  93. ] ),
  94. vertexShader: shader.vertexShader,
  95. fragmentShader: shader.fragmentShader,
  96. transparent: true,
  97. fog: true
  98. } );
  99. if ( flowMap !== undefined ) {
  100. this.material.defines.USE_FLOWMAP = '';
  101. this.material.uniforms[ 'tFlowMap' ] = {
  102. type: 't',
  103. value: flowMap
  104. };
  105. } else {
  106. this.material.uniforms[ 'flowDirection' ] = {
  107. type: 'v2',
  108. value: flowDirection
  109. };
  110. }
  111. // maps
  112. normalMap0.wrapS = normalMap0.wrapT = RepeatWrapping;
  113. normalMap1.wrapS = normalMap1.wrapT = RepeatWrapping;
  114. this.material.uniforms[ 'tReflectionMap' ].value = reflector.getRenderTarget().texture;
  115. this.material.uniforms[ 'tRefractionMap' ].value = refractor.getRenderTarget().texture;
  116. this.material.uniforms[ 'tNormalMap0' ].value = normalMap0;
  117. this.material.uniforms[ 'tNormalMap1' ].value = normalMap1;
  118. // water
  119. this.material.uniforms[ 'color' ].value = color;
  120. this.material.uniforms[ 'reflectivity' ].value = reflectivity;
  121. this.material.uniforms[ 'textureMatrix' ].value = textureMatrix;
  122. // initial values
  123. this.material.uniforms[ 'config' ].value.x = 0; // flowMapOffset0
  124. this.material.uniforms[ 'config' ].value.y = halfCycle; // flowMapOffset1
  125. this.material.uniforms[ 'config' ].value.z = halfCycle; // halfCycle
  126. this.material.uniforms[ 'config' ].value.w = scale; // scale
  127. // functions
  128. function updateTextureMatrix( camera ) {
  129. textureMatrix.set(
  130. 0.5, 0.0, 0.0, 0.5,
  131. 0.0, 0.5, 0.0, 0.5,
  132. 0.0, 0.0, 0.5, 0.5,
  133. 0.0, 0.0, 0.0, 1.0
  134. );
  135. textureMatrix.multiply( camera.projectionMatrix );
  136. textureMatrix.multiply( camera.matrixWorldInverse );
  137. textureMatrix.multiply( scope.matrixWorld );
  138. }
  139. function updateFlow() {
  140. const delta = clock.getDelta();
  141. const config = scope.material.uniforms[ 'config' ];
  142. config.value.x += flowSpeed * delta; // flowMapOffset0
  143. config.value.y = config.value.x + halfCycle; // flowMapOffset1
  144. // Important: The distance between offsets should be always the value of "halfCycle".
  145. // Moreover, both offsets should be in the range of [ 0, cycle ].
  146. // This approach ensures a smooth water flow and avoids "reset" effects.
  147. if ( config.value.x >= cycle ) {
  148. config.value.x = 0;
  149. config.value.y = halfCycle;
  150. } else if ( config.value.y >= cycle ) {
  151. config.value.y = config.value.y - cycle;
  152. }
  153. }
  154. //
  155. this.onBeforeRender = function ( renderer, scene, camera ) {
  156. updateTextureMatrix( camera );
  157. updateFlow();
  158. scope.visible = false;
  159. reflector.matrixWorld.copy( scope.matrixWorld );
  160. refractor.matrixWorld.copy( scope.matrixWorld );
  161. reflector.onBeforeRender( renderer, scene, camera );
  162. refractor.onBeforeRender( renderer, scene, camera );
  163. scope.visible = true;
  164. };
  165. }
  166. }
  167. Water.WaterShader = {
  168. name: 'WaterShader',
  169. uniforms: {
  170. 'color': {
  171. type: 'c',
  172. value: null
  173. },
  174. 'reflectivity': {
  175. type: 'f',
  176. value: 0
  177. },
  178. 'tReflectionMap': {
  179. type: 't',
  180. value: null
  181. },
  182. 'tRefractionMap': {
  183. type: 't',
  184. value: null
  185. },
  186. 'tNormalMap0': {
  187. type: 't',
  188. value: null
  189. },
  190. 'tNormalMap1': {
  191. type: 't',
  192. value: null
  193. },
  194. 'textureMatrix': {
  195. type: 'm4',
  196. value: null
  197. },
  198. 'config': {
  199. type: 'v4',
  200. value: new Vector4()
  201. }
  202. },
  203. vertexShader: /* glsl */`
  204. #include <common>
  205. #include <fog_pars_vertex>
  206. #include <logdepthbuf_pars_vertex>
  207. uniform mat4 textureMatrix;
  208. varying vec4 vCoord;
  209. varying vec2 vUv;
  210. varying vec3 vToEye;
  211. void main() {
  212. vUv = uv;
  213. vCoord = textureMatrix * vec4( position, 1.0 );
  214. vec4 worldPosition = modelMatrix * vec4( position, 1.0 );
  215. vToEye = cameraPosition - worldPosition.xyz;
  216. vec4 mvPosition = viewMatrix * worldPosition; // used in fog_vertex
  217. gl_Position = projectionMatrix * mvPosition;
  218. #include <logdepthbuf_vertex>
  219. #include <fog_vertex>
  220. }`,
  221. fragmentShader: /* glsl */`
  222. #include <common>
  223. #include <fog_pars_fragment>
  224. #include <logdepthbuf_pars_fragment>
  225. uniform sampler2D tReflectionMap;
  226. uniform sampler2D tRefractionMap;
  227. uniform sampler2D tNormalMap0;
  228. uniform sampler2D tNormalMap1;
  229. #ifdef USE_FLOWMAP
  230. uniform sampler2D tFlowMap;
  231. #else
  232. uniform vec2 flowDirection;
  233. #endif
  234. uniform vec3 color;
  235. uniform float reflectivity;
  236. uniform vec4 config;
  237. varying vec4 vCoord;
  238. varying vec2 vUv;
  239. varying vec3 vToEye;
  240. void main() {
  241. #include <logdepthbuf_fragment>
  242. float flowMapOffset0 = config.x;
  243. float flowMapOffset1 = config.y;
  244. float halfCycle = config.z;
  245. float scale = config.w;
  246. vec3 toEye = normalize( vToEye );
  247. // determine flow direction
  248. vec2 flow;
  249. #ifdef USE_FLOWMAP
  250. flow = texture2D( tFlowMap, vUv ).rg * 2.0 - 1.0;
  251. #else
  252. flow = flowDirection;
  253. #endif
  254. flow.x *= - 1.0;
  255. // sample normal maps (distort uvs with flowdata)
  256. vec4 normalColor0 = texture2D( tNormalMap0, ( vUv * scale ) + flow * flowMapOffset0 );
  257. vec4 normalColor1 = texture2D( tNormalMap1, ( vUv * scale ) + flow * flowMapOffset1 );
  258. // linear interpolate to get the final normal color
  259. float flowLerp = abs( halfCycle - flowMapOffset0 ) / halfCycle;
  260. vec4 normalColor = mix( normalColor0, normalColor1, flowLerp );
  261. // calculate normal vector
  262. vec3 normal = normalize( vec3( normalColor.r * 2.0 - 1.0, normalColor.b, normalColor.g * 2.0 - 1.0 ) );
  263. // calculate the fresnel term to blend reflection and refraction maps
  264. float theta = max( dot( toEye, normal ), 0.0 );
  265. float reflectance = reflectivity + ( 1.0 - reflectivity ) * pow( ( 1.0 - theta ), 5.0 );
  266. // calculate final uv coords
  267. vec3 coord = vCoord.xyz / vCoord.w;
  268. vec2 uv = coord.xy + coord.z * normal.xz * 0.05;
  269. vec4 reflectColor = texture2D( tReflectionMap, vec2( 1.0 - uv.x, uv.y ) );
  270. vec4 refractColor = texture2D( tRefractionMap, uv );
  271. // multiply water color with the mix of both textures
  272. gl_FragColor = vec4( color, 1.0 ) * mix( refractColor, reflectColor, reflectance );
  273. #include <tonemapping_fragment>
  274. #include <colorspace_fragment>
  275. #include <fog_fragment>
  276. }`
  277. };
  278. /**
  279. * Constructor options of `Water`.
  280. *
  281. * @typedef {Object} module:Water2~Options
  282. * @property {number|Color|string} [color=0xFFFFFF] - The water color.
  283. * @property {number} [textureWidth=512] - The texture width. A higher value results in better quality but is also more expensive.
  284. * @property {number} [textureHeight=512] - The texture height. A higher value results in better quality but is also more expensive.
  285. * @property {number} [clipBias=0] - The clip bias.
  286. * @property {Vector2} [flowDirection=(1,0)] - The water's flow direction.
  287. * @property {number} [flowSpeed=0.03] - The water's flow speed.
  288. * @property {number} [reflectivity=0.02] - The water's reflectivity.
  289. * @property {number} [scale=1] - The water's scale.
  290. * @property {Object} [shader] - A custom water shader.
  291. * @property {?Texture} [flowMap=null] - The flow map. If no flow map is assigned, the water flow is defined by `flowDirection`.
  292. * @property {?Texture} [normalMap0] - The first water normal map.
  293. * @property {?Texture} [normalMap1] - The second water normal map.
  294. **/
  295. export { Water };
粤ICP备19079148号