webgpu_compute_water.html 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>three.js webgpu - compute - 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. <link type="text/css" rel="stylesheet" href="main.css">
  8. </head>
  9. <body>
  10. <div id="info">
  11. <a href="https://threejs.org" target="_blank" rel="noopener">three.js</a> - <span id="waterSize"></span> webgpu compute water<br/>
  12. Move mouse to disturb water.
  13. </div>
  14. <script type="importmap">
  15. {
  16. "imports": {
  17. "three": "../build/three.webgpu.js",
  18. "three/tsl": "../build/three.webgpu.js",
  19. "three/addons/": "./jsm/"
  20. }
  21. }
  22. </script>
  23. <script type="module">
  24. import * as THREE from 'three';
  25. import { color, instanceIndex, If, varyingProperty, uint, int, negate, floor, float, length, clamp, vec2, cos, vec3, vertexIndex, Fn, uniform, instancedArray, min, max, positionLocal, transformNormalToView } from 'three/tsl';
  26. import { SimplexNoise } from 'three/addons/math/SimplexNoise.js';
  27. import { GUI } from 'three/addons/libs/lil-gui.module.min.js';
  28. import Stats from 'three/addons/libs/stats.module.js';
  29. // Dimensions of simulation grid.
  30. const WIDTH = 128;
  31. // Water size in system units.
  32. const BOUNDS = 512;
  33. const BOUNDS_HALF = BOUNDS * 0.5;
  34. const waterMaxHeight = 10;
  35. let container, stats;
  36. let camera, scene, renderer;
  37. let mouseMoved = false;
  38. const mouseCoords = new THREE.Vector2();
  39. const raycaster = new THREE.Raycaster();
  40. let effectController;
  41. let waterMesh, meshRay;
  42. let computeHeight, computeSmooth, computeSphere;
  43. const NUM_SPHERES = 100;
  44. const simplex = new SimplexNoise();
  45. init();
  46. function noise( x, y ) {
  47. let multR = waterMaxHeight;
  48. let mult = 0.025;
  49. let r = 0;
  50. for ( let i = 0; i < 15; i ++ ) {
  51. r += multR * simplex.noise( x * mult, y * mult );
  52. multR *= 0.53 + 0.025 * i;
  53. mult *= 1.25;
  54. }
  55. return r;
  56. }
  57. function init() {
  58. container = document.createElement( 'div' );
  59. document.body.appendChild( container );
  60. camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 1, 3000 );
  61. camera.position.set( 0, 200, 350 );
  62. camera.lookAt( 0, 0, 0 );
  63. scene = new THREE.Scene();
  64. const sun = new THREE.DirectionalLight( 0xFFFFFF, 3.0 );
  65. sun.position.set( 300, 400, 175 );
  66. scene.add( sun );
  67. const sun2 = new THREE.DirectionalLight( 0x40A040, 2.0 );
  68. sun2.position.set( - 100, 350, - 200 );
  69. scene.add( sun2 );
  70. //
  71. effectController = {
  72. mousePos: uniform( new THREE.Vector2( 10000, 10000 ) ).label( 'mousePos' ),
  73. mouseSize: uniform( 30.0 ).label( 'mouseSize' ),
  74. viscosity: uniform( 0.95 ).label( 'viscosity' ),
  75. spheresEnabled: true,
  76. wireframe: false
  77. };
  78. // Initialize height storage buffers
  79. const heightArray = new Float32Array( WIDTH * WIDTH );
  80. const prevHeightArray = new Float32Array( WIDTH * WIDTH );
  81. let p = 0;
  82. for ( let j = 0; j < WIDTH; j ++ ) {
  83. for ( let i = 0; i < WIDTH; i ++ ) {
  84. const x = i * 128 / WIDTH;
  85. const y = j * 128 / WIDTH;
  86. const height = noise( x, y );
  87. heightArray[ p ] = height;
  88. prevHeightArray[ p ] = height;
  89. p ++;
  90. }
  91. }
  92. const heightStorage = instancedArray( heightArray ).label( 'Height' );
  93. const prevHeightStorage = instancedArray( prevHeightArray ).label( 'PrevHeight' );
  94. // Get Indices of Neighbor Values of an Index in the Simulation Grid
  95. const getNeighborIndicesTSL = ( index ) => {
  96. const width = uint( WIDTH );
  97. // Get 2-D compute coordinate from one-dimensional instanceIndex. The calculation will
  98. // still work even if you dispatch your compute shader 2-dimensionally, since within a compute
  99. // context, instanceIndex is a 1-dimensional value derived from the workgroup dimensions.
  100. // Cast to int to prevent unintended index overflow upon subtraction.
  101. const x = int( index.modInt( WIDTH ) );
  102. const y = int( index.div( WIDTH ) );
  103. // The original shader accesses height via texture uvs. However, unlike with textures, we can't
  104. // access areas that are out of bounds. Accordingly, we emulate the Clamp to Edge Wrapping
  105. // behavior of accessing a DataTexture with out of bounds uvs.
  106. const leftX = max( 0, x.sub( 1 ) );
  107. const rightX = min( x.add( 1 ), width.sub( 1 ) );
  108. const bottomY = max( 0, y.sub( 1 ) );
  109. const topY = min( y.add( 1 ), width.sub( 1 ) );
  110. const westIndex = y.mul( width ).add( leftX );
  111. const eastIndex = y.mul( width ).add( rightX );
  112. const southIndex = bottomY.mul( width ).add( x );
  113. const northIndex = topY.mul( width ).add( x );
  114. return { northIndex, southIndex, eastIndex, westIndex };
  115. };
  116. // Get simulation index neighbor values
  117. const getNeighborValuesTSL = ( index, store ) => {
  118. const { northIndex, southIndex, eastIndex, westIndex } = getNeighborIndicesTSL( index );
  119. const north = store.element( northIndex );
  120. const south = store.element( southIndex );
  121. const east = store.element( eastIndex );
  122. const west = store.element( westIndex );
  123. return { north, south, east, west };
  124. };
  125. // Get new normals of simulation area.
  126. const getNormalsFromHeightTSL = ( index, store ) => {
  127. const { north, south, east, west } = getNeighborValuesTSL( index, store );
  128. const normalX = ( west.sub( east ) ).mul( WIDTH / BOUNDS );
  129. const normalY = ( south.sub( north ) ).mul( WIDTH / BOUNDS );
  130. return { normalX, normalY };
  131. };
  132. computeHeight = Fn( () => {
  133. const { viscosity, mousePos, mouseSize } = effectController;
  134. const height = heightStorage.element( instanceIndex ).toVar();
  135. const prevHeight = prevHeightStorage.element( instanceIndex ).toVar();
  136. const { north, south, east, west } = getNeighborValuesTSL( instanceIndex, heightStorage );
  137. const neighborHeight = north.add( south ).add( east ).add( west );
  138. neighborHeight.mulAssign( 0.5 );
  139. neighborHeight.subAssign( prevHeight );
  140. const newHeight = neighborHeight.mul( viscosity );
  141. // Get 2-D compute coordinate from one-dimensional instanceIndex.
  142. const x = float( instanceIndex.modInt( WIDTH ) ).mul( 1 / WIDTH );
  143. const y = float( instanceIndex.div( WIDTH ) ).mul( 1 / WIDTH );
  144. // Mouse influence
  145. const centerVec = vec2( 0.5 );
  146. // Get length of position in range [ -BOUNDS / 2, BOUNDS / 2 ], offset by mousePos, then scale.
  147. const mousePhase = clamp( length( ( vec2( x, y ).sub( centerVec ) ).mul( BOUNDS ).sub( mousePos ) ).mul( Math.PI ).div( mouseSize ), 0.0, Math.PI );
  148. newHeight.addAssign( cos( mousePhase ).add( 1.0 ).mul( 0.28 ) );
  149. prevHeightStorage.element( instanceIndex ).assign( height );
  150. heightStorage.element( instanceIndex ).assign( newHeight );
  151. } )().compute( WIDTH * WIDTH );
  152. computeSmooth = Fn( () => {
  153. const height = heightStorage.element( instanceIndex ).toVar();
  154. const prevHeight = prevHeightStorage.element( instanceIndex ).toVar();
  155. // Get neighboring height values.
  156. const { north: northH, south: southH, east: eastH, west: westH } = getNeighborValuesTSL( instanceIndex, heightStorage );
  157. // Get neighboring prev height values.
  158. const { north: northP, south: southP, east: eastP, west: westP } = getNeighborValuesTSL( instanceIndex, prevHeightStorage );
  159. height.addAssign( northH.add( southH ).add( eastH ).add( westH ) );
  160. prevHeight.addAssign( northP.add( southP ).add( eastP ).add( westP ) );
  161. heightStorage.element( instanceIndex ).assign( height.div( 5 ) );
  162. prevHeightStorage.element( instanceIndex ).assign( height.div( 5 ) );
  163. } )().compute( WIDTH * WIDTH/*, [ 8, 8 ]*/ );
  164. // Water Geometry corresponds with buffered compute grid.
  165. const waterGeometry = new THREE.PlaneGeometry( BOUNDS, BOUNDS, WIDTH - 1, WIDTH - 1 );
  166. // material: make a THREE.ShaderMaterial clone of THREE.MeshPhongMaterial, with customized position shader.
  167. const waterMaterial = new THREE.MeshPhongNodeMaterial();
  168. waterMaterial.lights = true;
  169. waterMaterial.colorNode = color( 0x0040C0 );
  170. waterMaterial.specularNode = color( 0x111111 );
  171. waterMaterial.shininess = Math.max( 50, 1e-4 );
  172. waterMaterial.positionNode = Fn( () => {
  173. // To correct the lighting as our mesh undulates, we have to reassign the normals in the position shader.
  174. const { normalX, normalY } = getNormalsFromHeightTSL( vertexIndex, heightStorage );
  175. varyingProperty( 'vec3', 'v_normalView' ).assign( transformNormalToView( vec3( normalX, negate( normalY ), 1.0 ) ) );
  176. return vec3( positionLocal.x, positionLocal.y, heightStorage.element( vertexIndex ) );
  177. } )();
  178. waterMesh = new THREE.Mesh( waterGeometry, waterMaterial );
  179. waterMesh.rotation.x = - Math.PI / 2;
  180. waterMesh.matrixAutoUpdate = false;
  181. waterMesh.updateMatrix();
  182. scene.add( waterMesh );
  183. // THREE.Mesh just for mouse raycasting
  184. const geometryRay = new THREE.PlaneGeometry( BOUNDS, BOUNDS, 1, 1 );
  185. meshRay = new THREE.Mesh( geometryRay, new THREE.MeshBasicMaterial( { color: 0xFFFFFF, visible: false } ) );
  186. meshRay.rotation.x = - Math.PI / 2;
  187. meshRay.matrixAutoUpdate = false;
  188. meshRay.updateMatrix();
  189. scene.add( meshRay );
  190. // Create sphere THREE.InstancedMesh
  191. const sphereGeometry = new THREE.SphereGeometry( 4, 24, 12 );
  192. const sphereMaterial = new THREE.MeshPhongMaterial( { color: 0xFFFF00 } );
  193. // Initialize sphere mesh instance position and velocity.
  194. const spherePositionArray = new Float32Array( NUM_SPHERES * 3 );
  195. // Only hold velocity in x and z directions.
  196. // The sphere is wedded to the surface of the water, and will only move vertically with the water.
  197. const sphereVelocityArray = new Float32Array( NUM_SPHERES * 2 );
  198. for ( let i = 0; i < NUM_SPHERES; i ++ ) {
  199. spherePositionArray[ i * 3 + 0 ] = ( Math.random() - 0.5 ) * BOUNDS * 0.7;
  200. spherePositionArray[ i * 3 + 1 ] = 0;
  201. spherePositionArray[ i * 3 + 2 ] = ( Math.random() - 0.5 ) * BOUNDS * 0.7;
  202. }
  203. sphereVelocityArray.fill( 0.0 );
  204. // Sphere Instance Storage
  205. const sphereInstancePositionStorage = instancedArray( spherePositionArray, 'vec3' ).label( 'SpherePosition' );
  206. const sphereVelocityStorage = instancedArray( sphereVelocityArray, 'vec2' ).label( 'SphereVelocity' );
  207. computeSphere = Fn( () => {
  208. const instancePosition = sphereInstancePositionStorage.element( instanceIndex );
  209. const velocity = sphereVelocityStorage.element( instanceIndex );
  210. // Bring position from range of [ -BOUNDS/2, BOUNDS/2 ] to [ 0, BOUNDS ]
  211. const tempX = instancePosition.x.add( BOUNDS_HALF );
  212. const tempZ = instancePosition.z.add( BOUNDS_HALF );
  213. // Bring position from range [ 0, BOUNDS ] to [ 0, WIDTH ]
  214. // ( i.e bring geometry range into 'heightmap' range )
  215. // WIDTH = 128, BOUNDS = 512... same as dividing by 4
  216. tempX.mulAssign( WIDTH / BOUNDS );
  217. tempZ.mulAssign( WIDTH / BOUNDS );
  218. // Can only access storage buffers with uints
  219. const xCoord = uint( floor( tempX ) );
  220. const zCoord = uint( floor( tempZ ) );
  221. // Get one dimensional index
  222. const heightInstanceIndex = zCoord.mul( WIDTH ).add( xCoord );
  223. // Set to read-only to be safe, even if it's not strictly necessary for compute access.
  224. const height = heightStorage.element( heightInstanceIndex );
  225. // Assign height to sphere position
  226. instancePosition.y.assign( height );
  227. // Calculate normal of the water mesh at this location.
  228. const { normalX, normalY } = getNormalsFromHeightTSL( heightInstanceIndex, heightStorage );
  229. normalX.mulAssign( 0.1 );
  230. normalY.mulAssign( 0.1 );
  231. const waterNormal = vec3( normalX, 0.0, negate( normalY ) );
  232. const newVelocity = vec3( velocity.x, 0.0, velocity.y ).add( waterNormal );
  233. newVelocity.mulAssign( 0.998 );
  234. const newPosition = instancePosition.add( newVelocity ).toVar();
  235. // Reverse velocity and reset position when exceeding bounds.
  236. If( newPosition.x.lessThan( - BOUNDS_HALF ), () => {
  237. newPosition.x = float( - BOUNDS_HALF ).add( 0.001 );
  238. newVelocity.x.mulAssign( - 0.3 );
  239. } ).ElseIf( newPosition.x.greaterThan( BOUNDS_HALF ), () => {
  240. newPosition.x = float( BOUNDS_HALF ).sub( 0.001 );
  241. newVelocity.x.mulAssign( - 0.3 );
  242. } );
  243. If( newPosition.z.lessThan( - BOUNDS_HALF ), () => {
  244. newPosition.z = float( - BOUNDS_HALF ).add( 0.001 );
  245. newVelocity.z.mulAssign( - 0.3 );
  246. } ).ElseIf( newPosition.z.greaterThan( BOUNDS_HALF ), () => {
  247. newPosition.z = float( BOUNDS_HALF ).sub( 0.001 );
  248. newVelocity.z.mulAssign( - 0.3 );
  249. } );
  250. instancePosition.assign( newPosition );
  251. velocity.assign( vec2( newVelocity.x, newVelocity.z ) );
  252. } )().compute( NUM_SPHERES );
  253. sphereMaterial.positionNode = Fn( () => {
  254. const instancePosition = sphereInstancePositionStorage.element( instanceIndex );
  255. const newPosition = positionLocal.add( instancePosition );
  256. return newPosition;
  257. } )();
  258. const sphereMesh = new THREE.InstancedMesh( sphereGeometry, sphereMaterial, NUM_SPHERES );
  259. scene.add( sphereMesh );
  260. renderer = new THREE.WebGPURenderer( { antialias: true } );
  261. renderer.setPixelRatio( window.devicePixelRatio );
  262. renderer.setSize( window.innerWidth, window.innerHeight );
  263. renderer.setAnimationLoop( animate );
  264. container.appendChild( renderer.domElement );
  265. stats = new Stats();
  266. container.appendChild( stats.dom );
  267. container.style.touchAction = 'none';
  268. container.addEventListener( 'pointermove', onPointerMove );
  269. window.addEventListener( 'resize', onWindowResize );
  270. const gui = new GUI();
  271. gui.add( effectController.mouseSize, 'value', 1.0, 100.0, 1.0 ).name( 'Mouse Size' );
  272. gui.add( effectController.viscosity, 'value', 0.9, 0.999, 0.001 ).name( 'viscosity' );
  273. const buttonCompute = {
  274. smoothWater: function () {
  275. renderer.computeAsync( computeSmooth );
  276. }
  277. };
  278. gui.add( buttonCompute, 'smoothWater' );
  279. gui.add( effectController, 'spheresEnabled' ).onChange( () => {
  280. sphereMesh.visible = effectController.spheresEnabled;
  281. } );
  282. gui.add( effectController, 'wireframe' ).onChange( () => {
  283. waterMesh.material.wireframe = ! waterMesh.material.wireframe;
  284. waterMesh.material.needsUpdate = true;
  285. } );
  286. }
  287. function onWindowResize() {
  288. camera.aspect = window.innerWidth / window.innerHeight;
  289. camera.updateProjectionMatrix();
  290. renderer.setSize( window.innerWidth, window.innerHeight );
  291. }
  292. function setMouseCoords( x, y ) {
  293. mouseCoords.set( ( x / renderer.domElement.clientWidth ) * 2 - 1, - ( y / renderer.domElement.clientHeight ) * 2 + 1 );
  294. mouseMoved = true;
  295. }
  296. function onPointerMove( event ) {
  297. if ( event.isPrimary === false ) return;
  298. setMouseCoords( event.clientX, event.clientY );
  299. }
  300. function animate() {
  301. render();
  302. stats.update();
  303. }
  304. function render() {
  305. if ( mouseMoved ) {
  306. raycaster.setFromCamera( mouseCoords, camera );
  307. const intersects = raycaster.intersectObject( meshRay );
  308. if ( intersects.length > 0 ) {
  309. const point = intersects[ 0 ].point;
  310. effectController.mousePos.value.set( point.x, point.z );
  311. } else {
  312. effectController.mousePos.value.set( 10000, 10000 );
  313. }
  314. mouseMoved = false;
  315. } else {
  316. effectController.mousePos.value.set( 10000, 10000 );
  317. }
  318. renderer.computeAsync( computeHeight );
  319. if ( effectController.spheresEnabled ) {
  320. renderer.computeAsync( computeSphere );
  321. }
  322. renderer.render( scene, camera );
  323. }
  324. </script>
  325. </body>
  326. </html>
粤ICP备19079148号