webgl_gpgpu_water.html 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>three.js webgl - gpgpu - water</title>
  5. <meta charset="utf-8">
  6. <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
  7. <style>
  8. body {
  9. background-color: #000000;
  10. margin: 0px;
  11. overflow: hidden;
  12. font-family:Monospace;
  13. font-size:13px;
  14. text-align:center;
  15. text-align:center;
  16. }
  17. a {
  18. color:#0078ff;
  19. }
  20. #info {
  21. color: #ffffff;
  22. position: absolute;
  23. top: 10px;
  24. width: 100%;
  25. }
  26. </style>
  27. </head>
  28. <body>
  29. <div id="info">
  30. <a href="http://threejs.org" target="_blank" rel="noopener">three.js</a> - <span id="waterSize"></span> webgl gpgpu water<br/>
  31. Select <span id="options"></span> water size<br/>
  32. Move mouse to disturb water.<br>
  33. Press mouse button to orbit around. 'W' key toggles wireframe.
  34. </div>
  35. <script src="../build/three.js"></script>
  36. <script src="js/WebGL.js"></script>
  37. <script src="js/libs/stats.min.js"></script>
  38. <script src="js/libs/dat.gui.min.js"></script>
  39. <script src="js/controls/OrbitControls.js"></script>
  40. <script src="js/SimplexNoise.js"></script>
  41. <script src="js/GPUComputationRenderer.js"></script>
  42. <!-- This is the 'compute shader' for the water heightmap: -->
  43. <script id="heightmapFragmentShader" type="x-shader/x-fragment">
  44. #include <common>
  45. uniform vec2 mousePos;
  46. uniform float mouseSize;
  47. uniform float viscosityConstant;
  48. uniform float heightCompensation;
  49. void main() {
  50. vec2 cellSize = 1.0 / resolution.xy;
  51. vec2 uv = gl_FragCoord.xy * cellSize;
  52. // heightmapValue.x == height from previous frame
  53. // heightmapValue.y == height from penultimate frame
  54. // heightmapValue.z, heightmapValue.w not used
  55. vec4 heightmapValue = texture2D( heightmap, uv );
  56. // Get neighbours
  57. vec4 north = texture2D( heightmap, uv + vec2( 0.0, cellSize.y ) );
  58. vec4 south = texture2D( heightmap, uv + vec2( 0.0, - cellSize.y ) );
  59. vec4 east = texture2D( heightmap, uv + vec2( cellSize.x, 0.0 ) );
  60. vec4 west = texture2D( heightmap, uv + vec2( - cellSize.x, 0.0 ) );
  61. // https://web.archive.org/web/20080618181901/http://freespace.virgin.net/hugo.elias/graphics/x_water.htm
  62. float newHeight = ( ( north.x + south.x + east.x + west.x ) * 0.5 - heightmapValue.y ) * viscosityConstant;
  63. // Mouse influence
  64. float mousePhase = clamp( length( ( uv - vec2( 0.5 ) ) * BOUNDS - vec2( mousePos.x, - mousePos.y ) ) * PI / mouseSize, 0.0, PI );
  65. newHeight += ( cos( mousePhase ) + 1.0 ) * 0.28;
  66. heightmapValue.y = heightmapValue.x;
  67. heightmapValue.x = newHeight;
  68. gl_FragColor = heightmapValue;
  69. }
  70. </script>
  71. <!-- This is just a smoothing 'compute shader' for using manually: -->
  72. <script id="smoothFragmentShader" type="x-shader/x-fragment">
  73. uniform sampler2D texture;
  74. void main() {
  75. vec2 cellSize = 1.0 / resolution.xy;
  76. vec2 uv = gl_FragCoord.xy * cellSize;
  77. // Computes the mean of texel and 4 neighbours
  78. vec4 textureValue = texture2D( texture, uv );
  79. textureValue += texture2D( texture, uv + vec2( 0.0, cellSize.y ) );
  80. textureValue += texture2D( texture, uv + vec2( 0.0, - cellSize.y ) );
  81. textureValue += texture2D( texture, uv + vec2( cellSize.x, 0.0 ) );
  82. textureValue += texture2D( texture, uv + vec2( - cellSize.x, 0.0 ) );
  83. textureValue /= 5.0;
  84. gl_FragColor = textureValue;
  85. }
  86. </script>
  87. <!-- This is a 'compute shader' to read the current level and normal of water at a point -->
  88. <!-- It is used with a variable of size 1x1 -->
  89. <script id="readWaterLevelFragmentShader" type="x-shader/x-fragment">
  90. uniform vec2 point1;
  91. uniform sampler2D texture;
  92. // Integer to float conversion from https://stackoverflow.com/questions/17981163/webgl-read-pixels-from-floating-point-render-target
  93. float shift_right( float v, float amt ) {
  94. v = floor( v ) + 0.5;
  95. return floor( v / exp2( amt ) );
  96. }
  97. float shift_left( float v, float amt ) {
  98. return floor( v * exp2( amt ) + 0.5 );
  99. }
  100. float mask_last( float v, float bits ) {
  101. return mod( v, shift_left( 1.0, bits ) );
  102. }
  103. float extract_bits( float num, float from, float to ) {
  104. from = floor( from + 0.5 ); to = floor( to + 0.5 );
  105. return mask_last( shift_right( num, from ), to - from );
  106. }
  107. vec4 encode_float( float val ) {
  108. if ( val == 0.0 ) return vec4( 0, 0, 0, 0 );
  109. float sign = val > 0.0 ? 0.0 : 1.0;
  110. val = abs( val );
  111. float exponent = floor( log2( val ) );
  112. float biased_exponent = exponent + 127.0;
  113. float fraction = ( ( val / exp2( exponent ) ) - 1.0 ) * 8388608.0;
  114. float t = biased_exponent / 2.0;
  115. float last_bit_of_biased_exponent = fract( t ) * 2.0;
  116. float remaining_bits_of_biased_exponent = floor( t );
  117. float byte4 = extract_bits( fraction, 0.0, 8.0 ) / 255.0;
  118. float byte3 = extract_bits( fraction, 8.0, 16.0 ) / 255.0;
  119. float byte2 = ( last_bit_of_biased_exponent * 128.0 + extract_bits( fraction, 16.0, 23.0 ) ) / 255.0;
  120. float byte1 = ( sign * 128.0 + remaining_bits_of_biased_exponent ) / 255.0;
  121. return vec4( byte4, byte3, byte2, byte1 );
  122. }
  123. void main() {
  124. vec2 cellSize = 1.0 / resolution.xy;
  125. float waterLevel = texture2D( texture, point1 ).x;
  126. vec2 normal = vec2(
  127. ( texture2D( texture, point1 + vec2( - cellSize.x, 0 ) ).x - texture2D( texture, point1 + vec2( cellSize.x, 0 ) ).x ) * WIDTH / BOUNDS,
  128. ( texture2D( texture, point1 + vec2( 0, - cellSize.y ) ).x - texture2D( texture, point1 + vec2( 0, cellSize.y ) ).x ) * WIDTH / BOUNDS );
  129. if ( gl_FragCoord.x < 1.5 ) {
  130. gl_FragColor = encode_float( waterLevel );
  131. } else if ( gl_FragCoord.x < 2.5 ) {
  132. gl_FragColor = encode_float( normal.x );
  133. } else if ( gl_FragCoord.x < 3.5 ) {
  134. gl_FragColor = encode_float( normal.y );
  135. } else {
  136. gl_FragColor = encode_float( 0.0 );
  137. }
  138. }
  139. </script>
  140. <!-- This is the water visualization shader, copied from the MeshPhongMaterial and modified: -->
  141. <script id="waterVertexShader" type="x-shader/x-vertex">
  142. uniform sampler2D heightmap;
  143. #define PHONG
  144. varying vec3 vViewPosition;
  145. #ifndef FLAT_SHADED
  146. varying vec3 vNormal;
  147. #endif
  148. #include <common>
  149. #include <uv_pars_vertex>
  150. #include <uv2_pars_vertex>
  151. #include <displacementmap_pars_vertex>
  152. #include <envmap_pars_vertex>
  153. #include <color_pars_vertex>
  154. #include <morphtarget_pars_vertex>
  155. #include <skinning_pars_vertex>
  156. #include <shadowmap_pars_vertex>
  157. #include <logdepthbuf_pars_vertex>
  158. #include <clipping_planes_pars_vertex>
  159. void main() {
  160. vec2 cellSize = vec2( 1.0 / WIDTH, 1.0 / WIDTH );
  161. #include <uv_vertex>
  162. #include <uv2_vertex>
  163. #include <color_vertex>
  164. // # include <beginnormal_vertex>
  165. // Compute normal from heightmap
  166. vec3 objectNormal = vec3(
  167. ( texture2D( heightmap, uv + vec2( - cellSize.x, 0 ) ).x - texture2D( heightmap, uv + vec2( cellSize.x, 0 ) ).x ) * WIDTH / BOUNDS,
  168. ( texture2D( heightmap, uv + vec2( 0, - cellSize.y ) ).x - texture2D( heightmap, uv + vec2( 0, cellSize.y ) ).x ) * WIDTH / BOUNDS,
  169. 1.0 );
  170. //<beginnormal_vertex>
  171. #include <morphnormal_vertex>
  172. #include <skinbase_vertex>
  173. #include <skinnormal_vertex>
  174. #include <defaultnormal_vertex>
  175. #ifndef FLAT_SHADED // Normal computed with derivatives when FLAT_SHADED
  176. vNormal = normalize( transformedNormal );
  177. #endif
  178. //# include <begin_vertex>
  179. float heightValue = texture2D( heightmap, uv ).x;
  180. vec3 transformed = vec3( position.x, position.y, heightValue );
  181. //<begin_vertex>
  182. #include <morphtarget_vertex>
  183. #include <skinning_vertex>
  184. #include <displacementmap_vertex>
  185. #include <project_vertex>
  186. #include <logdepthbuf_vertex>
  187. #include <clipping_planes_vertex>
  188. vViewPosition = - mvPosition.xyz;
  189. #include <worldpos_vertex>
  190. #include <envmap_vertex>
  191. #include <shadowmap_vertex>
  192. }
  193. </script>
  194. <script>
  195. if ( WEBGL.isWebGLAvailable() === false ) {
  196. document.body.appendChild( WEBGL.getWebGLErrorMessage() );
  197. }
  198. var hash = document.location.hash.substr( 1 );
  199. if ( hash ) hash = parseInt( hash, 0 );
  200. // Texture width for simulation
  201. var WIDTH = hash || 128;
  202. var NUM_TEXELS = WIDTH * WIDTH;
  203. // Water size in system units
  204. var BOUNDS = 512;
  205. var BOUNDS_HALF = BOUNDS * 0.5;
  206. var container, stats;
  207. var camera, scene, renderer, controls;
  208. var mouseMoved = false;
  209. var mouseCoords = new THREE.Vector2();
  210. var raycaster = new THREE.Raycaster();
  211. var waterMesh;
  212. var meshRay;
  213. var gpuCompute;
  214. var heightmapVariable;
  215. var waterUniforms;
  216. var smoothShader;
  217. var readWaterLevelShader;
  218. var readWaterLevelRenderTarget;
  219. var readWaterLevelImage;
  220. var waterNormal = new THREE.Vector3();
  221. var NUM_SPHERES = 5;
  222. var spheres = [];
  223. var spheresEnabled = true;
  224. var simplex = new SimplexNoise();
  225. var windowHalfX = window.innerWidth / 2;
  226. var windowHalfY = window.innerHeight / 2;
  227. document.getElementById( 'waterSize' ).innerText = WIDTH + ' x ' + WIDTH;
  228. function change(n) {
  229. location.hash = n;
  230. location.reload();
  231. return false;
  232. }
  233. var options = '';
  234. for ( var i = 4; i < 10; i++ ) {
  235. var j = Math.pow( 2, i );
  236. options += '<a href="#" onclick="return change(' + j + ')">' + j + 'x' + j + '</a> ';
  237. }
  238. document.getElementById('options').innerHTML = options;
  239. init();
  240. animate();
  241. function init() {
  242. container = document.createElement( 'div' );
  243. document.body.appendChild( container );
  244. camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 1, 3000 );
  245. camera.position.set( 0, 200, 350 );
  246. scene = new THREE.Scene();
  247. var sun = new THREE.DirectionalLight( 0xFFFFFF, 1.0 );
  248. sun.position.set( 300, 400, 175 );
  249. scene.add( sun );
  250. var sun2 = new THREE.DirectionalLight( 0x40A040, 0.6 );
  251. sun2.position.set( -100, 350, -200 );
  252. scene.add( sun2 );
  253. renderer = new THREE.WebGLRenderer();
  254. renderer.setPixelRatio( window.devicePixelRatio );
  255. renderer.setSize( window.innerWidth, window.innerHeight );
  256. container.appendChild( renderer.domElement );
  257. controls = new THREE.OrbitControls( camera, renderer.domElement );
  258. stats = new Stats();
  259. container.appendChild( stats.dom );
  260. document.addEventListener( 'mousemove', onDocumentMouseMove, false );
  261. document.addEventListener( 'touchstart', onDocumentTouchStart, false );
  262. document.addEventListener( 'touchmove', onDocumentTouchMove, false );
  263. document.addEventListener( 'keydown', function( event ) {
  264. // W Pressed: Toggle wireframe
  265. if ( event.keyCode === 87 ) {
  266. waterMesh.material.wireframe = ! waterMesh.material.wireframe;
  267. waterMesh.material.needsUpdate = true;
  268. }
  269. } , false );
  270. window.addEventListener( 'resize', onWindowResize, false );
  271. var gui = new dat.GUI();
  272. var effectController = {
  273. mouseSize: 20.0,
  274. viscosity: 0.98,
  275. spheresEnabled: spheresEnabled
  276. };
  277. var valuesChanger = function() {
  278. heightmapVariable.material.uniforms.mouseSize.value = effectController.mouseSize;
  279. heightmapVariable.material.uniforms.viscosityConstant.value = effectController.viscosity;
  280. spheresEnabled = effectController.spheresEnabled;
  281. for ( var i = 0; i < NUM_SPHERES; i++ ) {
  282. if ( spheres[ i ] ) {
  283. spheres[ i ].visible = spheresEnabled;
  284. }
  285. }
  286. };
  287. gui.add( effectController, "mouseSize", 1.0, 100.0, 1.0 ).onChange( valuesChanger );
  288. gui.add( effectController, "viscosity", 0.9, 0.999, 0.001 ).onChange( valuesChanger );
  289. gui.add( effectController, "spheresEnabled", 0, 1, 1 ).onChange( valuesChanger );
  290. var buttonSmooth = {
  291. smoothWater: function() {
  292. smoothWater();
  293. }
  294. };
  295. gui.add( buttonSmooth, 'smoothWater' );
  296. initWater();
  297. createSpheres();
  298. valuesChanger();
  299. }
  300. function initWater() {
  301. var materialColor = 0x0040C0;
  302. var geometry = new THREE.PlaneBufferGeometry( BOUNDS, BOUNDS, WIDTH - 1, WIDTH -1 );
  303. // material: make a ShaderMaterial clone of MeshPhongMaterial, with customized vertex shader
  304. var material = new THREE.ShaderMaterial( {
  305. uniforms: THREE.UniformsUtils.merge( [
  306. THREE.ShaderLib[ 'phong' ].uniforms,
  307. {
  308. heightmap: { value: null }
  309. }
  310. ] ),
  311. vertexShader: document.getElementById( 'waterVertexShader' ).textContent,
  312. fragmentShader: THREE.ShaderChunk[ 'meshphong_frag' ]
  313. } );
  314. material.lights = true;
  315. // Material attributes from MeshPhongMaterial
  316. material.color = new THREE.Color( materialColor );
  317. material.specular = new THREE.Color( 0x111111 );
  318. material.shininess = 50;
  319. // Sets the uniforms with the material values
  320. material.uniforms.diffuse.value = material.color;
  321. material.uniforms.specular.value = material.specular;
  322. material.uniforms.shininess.value = Math.max( material.shininess, 1e-4 );
  323. material.uniforms.opacity.value = material.opacity;
  324. // Defines
  325. material.defines.WIDTH = WIDTH.toFixed( 1 );
  326. material.defines.BOUNDS = BOUNDS.toFixed( 1 );
  327. waterUniforms = material.uniforms;
  328. waterMesh = new THREE.Mesh( geometry, material );
  329. waterMesh.rotation.x = - Math.PI / 2;
  330. waterMesh.matrixAutoUpdate = false;
  331. waterMesh.updateMatrix();
  332. scene.add( waterMesh );
  333. // Mesh just for mouse raycasting
  334. var geometryRay = new THREE.PlaneBufferGeometry( BOUNDS, BOUNDS, 1, 1 );
  335. meshRay = new THREE.Mesh( geometryRay, new THREE.MeshBasicMaterial( { color: 0xFFFFFF, visible: false } ) );
  336. meshRay.rotation.x = - Math.PI / 2;
  337. meshRay.matrixAutoUpdate = false;
  338. meshRay.updateMatrix();
  339. scene.add( meshRay );
  340. // Creates the gpu computation class and sets it up
  341. gpuCompute = new GPUComputationRenderer( WIDTH, WIDTH, renderer );
  342. var heightmap0 = gpuCompute.createTexture();
  343. fillTexture( heightmap0 );
  344. heightmapVariable = gpuCompute.addVariable( "heightmap", document.getElementById( 'heightmapFragmentShader' ).textContent, heightmap0 );
  345. gpuCompute.setVariableDependencies( heightmapVariable, [ heightmapVariable ] );
  346. heightmapVariable.material.uniforms.mousePos = { value: new THREE.Vector2( 10000, 10000 ) };
  347. heightmapVariable.material.uniforms.mouseSize = { value: 20.0 };
  348. heightmapVariable.material.uniforms.viscosityConstant = { value: 0.98 };
  349. heightmapVariable.material.uniforms.heightCompensation = { value: 0 };
  350. heightmapVariable.material.defines.BOUNDS = BOUNDS.toFixed( 1 );
  351. var error = gpuCompute.init();
  352. if ( error !== null ) {
  353. console.error( error );
  354. }
  355. // Create compute shader to smooth the water surface and velocity
  356. smoothShader = gpuCompute.createShaderMaterial( document.getElementById( 'smoothFragmentShader' ).textContent, { texture: { value: null } } );
  357. // Create compute shader to read water level
  358. readWaterLevelShader = gpuCompute.createShaderMaterial( document.getElementById( 'readWaterLevelFragmentShader' ).textContent, {
  359. point1: { value: new THREE.Vector2() },
  360. texture: { value: null }
  361. } );
  362. readWaterLevelShader.defines.WIDTH = WIDTH.toFixed( 1 );
  363. readWaterLevelShader.defines.BOUNDS = BOUNDS.toFixed( 1 );
  364. // Create a 4x1 pixel image and a render target (Uint8, 4 channels, 1 byte per channel) to read water height and orientation
  365. readWaterLevelImage = new Uint8Array( 4 * 1 * 4 );
  366. readWaterLevelRenderTarget = new THREE.WebGLRenderTarget( 4, 1, {
  367. wrapS: THREE.ClampToEdgeWrapping,
  368. wrapT: THREE.ClampToEdgeWrapping,
  369. minFilter: THREE.NearestFilter,
  370. magFilter: THREE.NearestFilter,
  371. format: THREE.RGBAFormat,
  372. type: THREE.UnsignedByteType,
  373. stencilBuffer: false,
  374. depthBuffer: false
  375. } );
  376. }
  377. function fillTexture( texture ) {
  378. var waterMaxHeight = 10;
  379. function noise( x, y, z ) {
  380. var multR = waterMaxHeight;
  381. var mult = 0.025;
  382. var r = 0;
  383. for ( var i = 0; i < 15; i++ ) {
  384. r += multR * simplex.noise( x * mult, y * mult );
  385. multR *= 0.53 + 0.025 * i;
  386. mult *= 1.25;
  387. }
  388. return r;
  389. }
  390. var pixels = texture.image.data;
  391. var p = 0;
  392. for ( var j = 0; j < WIDTH; j++ ) {
  393. for ( var i = 0; i < WIDTH; i++ ) {
  394. var x = i * 128 / WIDTH;
  395. var y = j * 128 / WIDTH;
  396. pixels[ p + 0 ] = noise( x, y, 123.4 );
  397. pixels[ p + 1 ] = pixels[ p + 0 ];
  398. pixels[ p + 2 ] = 0;
  399. pixels[ p + 3 ] = 1;
  400. p += 4;
  401. }
  402. }
  403. }
  404. function smoothWater() {
  405. var currentRenderTarget = gpuCompute.getCurrentRenderTarget( heightmapVariable );
  406. var alternateRenderTarget = gpuCompute.getAlternateRenderTarget( heightmapVariable );
  407. for ( var i = 0; i < 10; i++ ) {
  408. smoothShader.uniforms.texture.value = currentRenderTarget.texture;
  409. gpuCompute.doRenderTarget( smoothShader, alternateRenderTarget );
  410. smoothShader.uniforms.texture.value = alternateRenderTarget.texture;
  411. gpuCompute.doRenderTarget( smoothShader, currentRenderTarget );
  412. }
  413. }
  414. function createSpheres() {
  415. var sphereTemplate = new THREE.Mesh( new THREE.SphereBufferGeometry( 4, 24, 12 ), new THREE.MeshPhongMaterial( { color: 0xFFFF00 } ) );
  416. for ( var i = 0; i < NUM_SPHERES; i++ ) {
  417. var sphere = sphereTemplate;
  418. if ( i < NUM_SPHERES - 1 ) {
  419. sphere = sphereTemplate.clone();
  420. }
  421. sphere.position.x = ( Math.random() - 0.5 ) * BOUNDS * 0.7;
  422. sphere.position.z = ( Math.random() - 0.5 ) * BOUNDS * 0.7;
  423. sphere.userData.velocity = new THREE.Vector3();
  424. scene.add( sphere );
  425. spheres[ i ] = sphere;
  426. }
  427. }
  428. function sphereDynamics() {
  429. var currentRenderTarget = gpuCompute.getCurrentRenderTarget( heightmapVariable );
  430. readWaterLevelShader.uniforms.texture.value = currentRenderTarget.texture;
  431. var gl = renderer.context;
  432. for ( var i = 0; i < NUM_SPHERES; i++ ) {
  433. var sphere = spheres[ i ];
  434. if ( sphere ) {
  435. // Read water level and orientation
  436. var u = 0.5 * sphere.position.x / BOUNDS_HALF + 0.5;
  437. var v = 1 - ( 0.5 * sphere.position.z / BOUNDS_HALF + 0.5 );
  438. readWaterLevelShader.uniforms.point1.value.set( u, v );
  439. gpuCompute.doRenderTarget( readWaterLevelShader, readWaterLevelRenderTarget );
  440. gl.readPixels( 0, 0, 4, 1, gl.RGBA, gl.UNSIGNED_BYTE, readWaterLevelImage );
  441. var pixels = new Float32Array( readWaterLevelImage.buffer );
  442. // Get orientation
  443. waterNormal.set( pixels[ 1 ], 0, - pixels[ 2 ] );
  444. var pos = sphere.position;
  445. // Set height
  446. pos.y = pixels[ 0 ];
  447. // Move sphere
  448. waterNormal.multiplyScalar( 0.1 );
  449. sphere.userData.velocity.add( waterNormal );
  450. sphere.userData.velocity.multiplyScalar( 0.998 );
  451. pos.add( sphere.userData.velocity );
  452. if ( pos.x < - BOUNDS_HALF ) {
  453. pos.x = - BOUNDS_HALF + 0.001;
  454. sphere.userData.velocity.x *= - 0.3;
  455. }
  456. else if ( pos.x > BOUNDS_HALF ) {
  457. pos.x = BOUNDS_HALF - 0.001;
  458. sphere.userData.velocity.x *= - 0.3;
  459. }
  460. if ( pos.z < - BOUNDS_HALF ) {
  461. pos.z = - BOUNDS_HALF + 0.001;
  462. sphere.userData.velocity.z *= - 0.3;
  463. }
  464. else if ( pos.z > BOUNDS_HALF ) {
  465. pos.z = BOUNDS_HALF - 0.001;
  466. sphere.userData.velocity.z *= - 0.3;
  467. }
  468. }
  469. }
  470. }
  471. function onWindowResize() {
  472. windowHalfX = window.innerWidth / 2;
  473. windowHalfY = window.innerHeight / 2;
  474. camera.aspect = window.innerWidth / window.innerHeight;
  475. camera.updateProjectionMatrix();
  476. renderer.setSize( window.innerWidth, window.innerHeight );
  477. }
  478. function setMouseCoords( x, y ) {
  479. mouseCoords.set( ( x / renderer.domElement.clientWidth ) * 2 - 1, - ( y / renderer.domElement.clientHeight ) * 2 + 1 );
  480. mouseMoved = true;
  481. }
  482. function onDocumentMouseMove( event ) {
  483. setMouseCoords( event.clientX, event.clientY );
  484. }
  485. function onDocumentTouchStart( event ) {
  486. if ( event.touches.length === 1 ) {
  487. event.preventDefault();
  488. setMouseCoords( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY );
  489. }
  490. }
  491. function onDocumentTouchMove( event ) {
  492. if ( event.touches.length === 1 ) {
  493. event.preventDefault();
  494. setMouseCoords( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY );
  495. }
  496. }
  497. function animate() {
  498. requestAnimationFrame( animate );
  499. render();
  500. stats.update();
  501. }
  502. function render() {
  503. // Set uniforms: mouse interaction
  504. var uniforms = heightmapVariable.material.uniforms;
  505. if ( mouseMoved ) {
  506. raycaster.setFromCamera( mouseCoords, camera );
  507. var intersects = raycaster.intersectObject( meshRay );
  508. if ( intersects.length > 0 ) {
  509. var point = intersects[ 0 ].point;
  510. uniforms.mousePos.value.set( point.x, point.z );
  511. }
  512. else {
  513. uniforms.mousePos.value.set( 10000, 10000 );
  514. }
  515. mouseMoved = false;
  516. }
  517. else {
  518. uniforms.mousePos.value.set( 10000, 10000 );
  519. }
  520. // Do the gpu computation
  521. gpuCompute.compute();
  522. if ( spheresEnabled ) {
  523. sphereDynamics();
  524. }
  525. // Get compute output in custom uniform
  526. waterUniforms.heightmap.value = gpuCompute.getCurrentRenderTarget( heightmapVariable ).texture;
  527. // Render
  528. renderer.render( scene, camera );
  529. }
  530. </script>
  531. </body>
  532. </html>