webgpu_compute_water.html 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605
  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. Click and move mouse to disturb water.
  13. </div>
  14. <script type="importmap">
  15. {
  16. "imports": {
  17. "three": "../build/three.webgpu.js",
  18. "three/webgpu": "../build/three.webgpu.js",
  19. "three/tsl": "../build/three.tsl.js",
  20. "three/addons/": "./jsm/"
  21. }
  22. }
  23. </script>
  24. <script type="module">
  25. import * as THREE from 'three/webgpu';
  26. import { instanceIndex, struct, If, uint, int, floor, float, length, clamp, vec2, cos, vec3, vertexIndex, Fn, uniform, instancedArray, min, max, positionLocal, transformNormalToView } from 'three/tsl';
  27. import { SimplexNoise } from 'three/addons/math/SimplexNoise.js';
  28. import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
  29. import { HDRLoader } from 'three/addons/loaders/HDRLoader.js';
  30. import { DRACOLoader } from 'three/addons/loaders/DRACOLoader.js';
  31. import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
  32. import { GUI } from 'three/addons/libs/lil-gui.module.min.js';
  33. import Stats from 'three/addons/libs/stats.module.js';
  34. import WebGPU from 'three/addons/capabilities/WebGPU.js';
  35. // Dimensions of simulation grid.
  36. const WIDTH = 128;
  37. // Water size in system units.
  38. const BOUNDS = 6;
  39. const BOUNDS_HALF = BOUNDS * 0.5;
  40. const limit = BOUNDS_HALF - 0.2;
  41. const waterMaxHeight = 0.1;
  42. let container, stats;
  43. let camera, scene, renderer, controls;
  44. let mouseDown = false;
  45. let firstClick = true;
  46. let updateOriginMouseDown = false;
  47. const mouseCoords = new THREE.Vector2();
  48. const raycaster = new THREE.Raycaster();
  49. let frame = 0;
  50. const effectController = {
  51. mousePos: uniform( new THREE.Vector2() ).setName( 'mousePos' ),
  52. mouseSpeed: uniform( new THREE.Vector2() ).setName( 'mouseSpeed' ),
  53. mouseDeep: uniform( .5 ).setName( 'mouseDeep' ),
  54. mouseSize: uniform( 0.12 ).setName( 'mouseSize' ),
  55. viscosity: uniform( 0.96 ).setName( 'viscosity' ),
  56. ducksEnabled: true,
  57. wireframe: false,
  58. speed: 5,
  59. };
  60. let sun;
  61. let waterMesh;
  62. let poolBorder;
  63. let meshRay;
  64. let computeHeight, computeDucks;
  65. let duckModel = null;
  66. const NUM_DUCKS = 100;
  67. const simplex = new SimplexNoise();
  68. // TODO: Fix example with WebGL backend
  69. if ( WebGPU.isAvailable() === false ) {
  70. document.body.appendChild( WebGPU.getErrorMessage() );
  71. throw new Error( 'No WebGPU support' );
  72. }
  73. init();
  74. function noise( x, y ) {
  75. let multR = waterMaxHeight;
  76. let mult = 0.025;
  77. let r = 0;
  78. for ( let i = 0; i < 15; i ++ ) {
  79. r += multR * simplex.noise( x * mult, y * mult );
  80. multR *= 0.53 + 0.025 * i;
  81. mult *= 1.25;
  82. }
  83. return r;
  84. }
  85. async function init() {
  86. container = document.createElement( 'div' );
  87. document.body.appendChild( container );
  88. camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 1, 3000 );
  89. camera.position.set( 0, 2.00, 4 );
  90. camera.lookAt( 0, 0, 0 );
  91. scene = new THREE.Scene();
  92. sun = new THREE.DirectionalLight( 0xFFFFFF, 4.0 );
  93. sun.position.set( - 1, 2.6, 1.4 );
  94. scene.add( sun );
  95. //
  96. // Initialize height storage buffers
  97. const heightArray = new Float32Array( WIDTH * WIDTH );
  98. const prevHeightArray = new Float32Array( WIDTH * WIDTH );
  99. let p = 0;
  100. for ( let j = 0; j < WIDTH; j ++ ) {
  101. for ( let i = 0; i < WIDTH; i ++ ) {
  102. const x = i * 128 / WIDTH;
  103. const y = j * 128 / WIDTH;
  104. const height = noise( x, y );
  105. heightArray[ p ] = height;
  106. prevHeightArray[ p ] = height;
  107. p ++;
  108. }
  109. }
  110. const heightStorage = instancedArray( heightArray ).setName( 'Height' );
  111. const prevHeightStorage = instancedArray( prevHeightArray ).setName( 'PrevHeight' );
  112. // Get Indices of Neighbor Values of an Index in the Simulation Grid
  113. const getNeighborIndicesTSL = ( index ) => {
  114. const width = uint( WIDTH );
  115. // Get 2-D compute coordinate from one-dimensional instanceIndex. The calculation will
  116. // still work even if you dispatch your compute shader 2-dimensionally, since within a compute
  117. // context, instanceIndex is a 1-dimensional value derived from the workgroup dimensions.
  118. // Cast to int to prevent unintended index overflow upon subtraction.
  119. const x = int( index.mod( WIDTH ) );
  120. const y = int( index.div( WIDTH ) );
  121. // The original shader accesses height via texture uvs. However, unlike with textures, we can't
  122. // access areas that are out of bounds. Accordingly, we emulate the Clamp to Edge Wrapping
  123. // behavior of accessing a DataTexture with out of bounds uvs.
  124. const leftX = max( 0, x.sub( 1 ) );
  125. const rightX = min( x.add( 1 ), width.sub( 1 ) );
  126. const bottomY = max( 0, y.sub( 1 ) );
  127. const topY = min( y.add( 1 ), width.sub( 1 ) );
  128. const westIndex = y.mul( width ).add( leftX );
  129. const eastIndex = y.mul( width ).add( rightX );
  130. const southIndex = bottomY.mul( width ).add( x );
  131. const northIndex = topY.mul( width ).add( x );
  132. return { northIndex, southIndex, eastIndex, westIndex };
  133. };
  134. // Get simulation index neighbor values
  135. const getNeighborValuesTSL = ( index, store ) => {
  136. const { northIndex, southIndex, eastIndex, westIndex } = getNeighborIndicesTSL( index );
  137. const north = store.element( northIndex );
  138. const south = store.element( southIndex );
  139. const east = store.element( eastIndex );
  140. const west = store.element( westIndex );
  141. return { north, south, east, west };
  142. };
  143. // Get new normals of simulation area.
  144. const getNormalsFromHeightTSL = ( index, store ) => {
  145. const { north, south, east, west } = getNeighborValuesTSL( index, store );
  146. const normalX = ( west.sub( east ) ).mul( WIDTH / BOUNDS );
  147. const normalY = ( south.sub( north ) ).mul( WIDTH / BOUNDS );
  148. return { normalX, normalY };
  149. };
  150. computeHeight = Fn( () => {
  151. const { viscosity, mousePos, mouseSize, mouseDeep, mouseSpeed } = effectController;
  152. const height = heightStorage.element( instanceIndex ).toVar();
  153. const prevHeight = prevHeightStorage.element( instanceIndex ).toVar();
  154. const { north, south, east, west } = getNeighborValuesTSL( instanceIndex, heightStorage );
  155. const neighborHeight = north.add( south ).add( east ).add( west );
  156. neighborHeight.mulAssign( 0.5 );
  157. neighborHeight.subAssign( prevHeight );
  158. const newHeight = neighborHeight.mul( viscosity );
  159. // Get 2-D compute coordinate from one-dimensional instanceIndex.
  160. const x = float( instanceIndex.mod( WIDTH ) ).mul( 1 / WIDTH );
  161. const y = float( instanceIndex.div( WIDTH ) ).mul( 1 / WIDTH );
  162. // Mouse influence
  163. const centerVec = vec2( 0.5 );
  164. // Get length of position in range [ -BOUNDS / 2, BOUNDS / 2 ], offset by mousePos, then scale.
  165. const mousePhase = clamp( length( ( vec2( x, y ).sub( centerVec ) ).mul( BOUNDS ).sub( mousePos ) ).mul( Math.PI ).div( mouseSize ), 0.0, Math.PI );
  166. // "Indent" water down by scaled distance from center of mouse impact
  167. newHeight.addAssign( cos( mousePhase ).add( 1.0 ).mul( mouseDeep ).mul( mouseSpeed.length() ) );
  168. prevHeightStorage.element( instanceIndex ).assign( height );
  169. heightStorage.element( instanceIndex ).assign( newHeight );
  170. } )().compute( WIDTH * WIDTH );
  171. // Water Geometry corresponds with buffered compute grid.
  172. const waterGeometry = new THREE.PlaneGeometry( BOUNDS, BOUNDS, WIDTH - 1, WIDTH - 1 );
  173. const waterMaterial = new THREE.MeshStandardNodeMaterial( {
  174. color: 0x9bd2ec,
  175. metalness: 0.9,
  176. roughness: 0,
  177. transparent: true,
  178. opacity: 0.8,
  179. side: THREE.DoubleSide
  180. } );
  181. waterMaterial.normalNode = Fn( () => {
  182. // To correct the lighting as our mesh undulates, we have to reassign the normals in the normal shader.
  183. const { normalX, normalY } = getNormalsFromHeightTSL( vertexIndex, heightStorage );
  184. return transformNormalToView( vec3( normalX, normalY.negate(), 1.0 ) ).toVertexStage();
  185. } )();
  186. waterMaterial.positionNode = Fn( () => {
  187. return vec3( positionLocal.x, positionLocal.y, heightStorage.element( vertexIndex ) );
  188. } )();
  189. waterMesh = new THREE.Mesh( waterGeometry, waterMaterial );
  190. waterMesh.rotation.x = - Math.PI * 0.5;
  191. waterMesh.matrixAutoUpdate = false;
  192. waterMesh.updateMatrix();
  193. scene.add( waterMesh );
  194. // Pool border
  195. const borderGeom = new THREE.TorusGeometry( 4.2, 0.1, 12, 4 );
  196. borderGeom.rotateX( Math.PI * 0.5 );
  197. borderGeom.rotateY( Math.PI * 0.25 );
  198. poolBorder = new THREE.Mesh( borderGeom, new THREE.MeshStandardMaterial( { color: 0x908877, roughness: 0.2 } ) );
  199. scene.add( poolBorder );
  200. // THREE.Mesh just for mouse raycasting
  201. const geometryRay = new THREE.PlaneGeometry( BOUNDS, BOUNDS, 1, 1 );
  202. meshRay = new THREE.Mesh( geometryRay, new THREE.MeshBasicMaterial( { color: 0xFFFFFF, visible: false } ) );
  203. meshRay.rotation.x = - Math.PI / 2;
  204. meshRay.matrixAutoUpdate = false;
  205. meshRay.updateMatrix();
  206. scene.add( meshRay );
  207. // Initialize sphere mesh instance position and velocity.
  208. // position<vec3> + velocity<vec2> + unused<vec3> = 8 floats per sphere.
  209. // for structs arrays must be enclosed in multiple of 4
  210. const duckStride = 8;
  211. const duckInstanceDataArray = new Float32Array( NUM_DUCKS * duckStride );
  212. // Only hold velocity in x and z directions.
  213. // The sphere is wedded to the surface of the water, and will only move vertically with the water.
  214. for ( let i = 0; i < NUM_DUCKS; i ++ ) {
  215. duckInstanceDataArray[ i * duckStride + 0 ] = ( Math.random() - 0.5 ) * BOUNDS * 0.7;
  216. duckInstanceDataArray[ i * duckStride + 1 ] = 0;
  217. duckInstanceDataArray[ i * duckStride + 2 ] = ( Math.random() - 0.5 ) * BOUNDS * 0.7;
  218. }
  219. const DuckStruct = struct( {
  220. position: 'vec3',
  221. velocity: 'vec2'
  222. } );
  223. // Duck instance data storage
  224. const duckInstanceDataStorage = instancedArray( duckInstanceDataArray, DuckStruct ).setName( 'DuckInstanceData' );
  225. computeDucks = Fn( () => {
  226. const yOffset = float( - 0.04 );
  227. const verticalResponseFactor = float( 0.98 );
  228. const waterPushFactor = float( 0.015 );
  229. const linearDamping = float( 0.92 );
  230. const bounceDamping = float( - 0.4 );
  231. // Get 2-D compute coordinate from one-dimensional instanceIndex. The calculation will
  232. const instancePosition = duckInstanceDataStorage.element( instanceIndex ).get( 'position' ).toVar();
  233. const velocity = duckInstanceDataStorage.element( instanceIndex ).get( 'velocity' ).toVar();
  234. const gridCoordX = instancePosition.x.div( BOUNDS ).add( 0.5 ).mul( WIDTH );
  235. const gridCoordZ = instancePosition.z.div( BOUNDS ).add( 0.5 ).mul( WIDTH );
  236. // Cast to int to prevent unintended index overflow upon subtraction.
  237. const xCoord = uint( clamp( floor( gridCoordX ), 0, WIDTH - 1 ) );
  238. const zCoord = uint( clamp( floor( gridCoordZ ), 0, WIDTH - 1 ) );
  239. const heightInstanceIndex = zCoord.mul( WIDTH ).add( xCoord );
  240. // Get height of water at the duck's position
  241. const waterHeight = heightStorage.element( heightInstanceIndex );
  242. const { normalX, normalY } = getNormalsFromHeightTSL( heightInstanceIndex, heightStorage );
  243. // Calculate the target Y position based on the water height and the duck's vertical offset
  244. const targetY = waterHeight.add( yOffset );
  245. const deltaY = targetY.sub( instancePosition.y );
  246. instancePosition.y.addAssign( deltaY.mul( verticalResponseFactor ) ); // Gradually update position
  247. // Get the normal of the water surface at the duck's position
  248. const pushX = normalX.mul( waterPushFactor );
  249. const pushZ = normalY.mul( waterPushFactor );
  250. // Apply the water push to the duck's velocity
  251. velocity.x.mulAssign( linearDamping );
  252. velocity.y.mulAssign( linearDamping );
  253. velocity.x.addAssign( pushX );
  254. velocity.y.addAssign( pushZ );
  255. // update position based on velocity
  256. instancePosition.x.addAssign( velocity.x );
  257. instancePosition.z.addAssign( velocity.y );
  258. // Clamp position to the pool bounds
  259. If( instancePosition.x.lessThan( - limit ), () => {
  260. instancePosition.x = - limit;
  261. velocity.x.mulAssign( bounceDamping );
  262. } ).ElseIf( instancePosition.x.greaterThan( limit ), () => {
  263. instancePosition.x = limit;
  264. velocity.x.mulAssign( bounceDamping );
  265. } );
  266. If( instancePosition.z.lessThan( - limit ), () => {
  267. instancePosition.z = - limit;
  268. velocity.y.mulAssign( bounceDamping ); // Invert and damp vz (velocity.y)
  269. } ).ElseIf( instancePosition.z.greaterThan( limit ), () => {
  270. instancePosition.z = limit;
  271. velocity.y.mulAssign( bounceDamping );
  272. } );
  273. // assignment of new values to the instance data storage
  274. duckInstanceDataStorage.element( instanceIndex ).get( 'position' ).assign( instancePosition );
  275. duckInstanceDataStorage.element( instanceIndex ).get( 'velocity' ).assign( velocity );
  276. } )().compute( NUM_DUCKS );
  277. // Models / Textures
  278. const hdrLoader = new HDRLoader().setPath( './textures/equirectangular/' );
  279. const glbloader = new GLTFLoader().setPath( 'models/gltf/' );
  280. glbloader.setDRACOLoader( new DRACOLoader().setDecoderPath( 'jsm/libs/draco/gltf/' ) );
  281. const [ env, model ] = await Promise.all( [ hdrLoader.loadAsync( 'blouberg_sunrise_2_1k.hdr' ), glbloader.loadAsync( 'duck.glb' ) ] );
  282. env.mapping = THREE.EquirectangularReflectionMapping;
  283. scene.environment = env;
  284. scene.background = env;
  285. scene.backgroundBlurriness = 0.3;
  286. scene.environmentIntensity = 1.25;
  287. duckModel = model.scene.children[ 0 ];
  288. duckModel.material.positionNode = Fn( () => {
  289. const instancePosition = duckInstanceDataStorage.element( instanceIndex ).get( 'position' );
  290. const newPosition = positionLocal.add( instancePosition );
  291. return newPosition;
  292. } )();
  293. const duckMesh = new THREE.InstancedMesh( duckModel.geometry, duckModel.material, NUM_DUCKS );
  294. scene.add( duckMesh );
  295. renderer = new THREE.WebGPURenderer( { antialias: true } );
  296. renderer.setPixelRatio( window.devicePixelRatio );
  297. renderer.setSize( window.innerWidth, window.innerHeight );
  298. renderer.toneMapping = THREE.ACESFilmicToneMapping;
  299. renderer.toneMappingExposure = 0.5;
  300. renderer.setAnimationLoop( animate );
  301. container.appendChild( renderer.domElement );
  302. controls = new OrbitControls( camera, container );
  303. container.style.touchAction = 'none';
  304. // Stats
  305. stats = new Stats();
  306. container.appendChild( stats.dom );
  307. container.style.touchAction = 'none';
  308. container.addEventListener( 'pointermove', onPointerMove );
  309. container.addEventListener( 'pointerdown', onPointerDown );
  310. container.addEventListener( 'pointerup', onPointerUp );
  311. window.addEventListener( 'resize', onWindowResize );
  312. // GUI
  313. const gui = new GUI();
  314. gui.add( effectController.mouseSize, 'value', 0.1, .3 ).name( 'Mouse Size' );
  315. gui.add( effectController.mouseDeep, 'value', 0.1, 1 ).name( 'Mouse Deep' );
  316. gui.add( effectController.viscosity, 'value', 0.9, 0.96, 0.001 ).name( 'viscosity' );
  317. gui.add( effectController, 'speed', 1, 6, 1 );
  318. gui.add( effectController, 'ducksEnabled' ).onChange( () => {
  319. duckMesh.visible = effectController.ducksEnabled;
  320. } );
  321. gui.add( effectController, 'wireframe' ).onChange( () => {
  322. waterMesh.material.wireframe = ! waterMesh.material.wireframe;
  323. poolBorder.material.wireframe = ! poolBorder.material.wireframe;
  324. duckModel.material.wireframe = ! duckModel.material.wireframe;
  325. waterMesh.material.needsUpdate = true;
  326. poolBorder.material.needsUpdate = true;
  327. } );
  328. }
  329. function onWindowResize() {
  330. camera.aspect = window.innerWidth / window.innerHeight;
  331. camera.updateProjectionMatrix();
  332. renderer.setSize( window.innerWidth, window.innerHeight );
  333. }
  334. function setMouseCoords( x, y ) {
  335. mouseCoords.set( ( x / renderer.domElement.clientWidth ) * 2 - 1, - ( y / renderer.domElement.clientHeight ) * 2 + 1 );
  336. }
  337. function onPointerDown() {
  338. mouseDown = true;
  339. firstClick = true;
  340. updateOriginMouseDown = true;
  341. }
  342. function onPointerUp() {
  343. mouseDown = false;
  344. firstClick = false;
  345. updateOriginMouseDown = false;
  346. controls.enabled = true;
  347. }
  348. function onPointerMove( event ) {
  349. if ( event.isPrimary === false ) return;
  350. setMouseCoords( event.clientX, event.clientY );
  351. }
  352. function animate() {
  353. render();
  354. stats.update();
  355. }
  356. function raycast() {
  357. if ( mouseDown && ( firstClick || ! controls.enabled ) ) {
  358. raycaster.setFromCamera( mouseCoords, camera );
  359. const intersects = raycaster.intersectObject( meshRay );
  360. if ( intersects.length > 0 ) {
  361. const point = intersects[ 0 ].point;
  362. if ( updateOriginMouseDown ) {
  363. effectController.mousePos.value.set( point.x, point.z );
  364. updateOriginMouseDown = false;
  365. }
  366. effectController.mouseSpeed.value.set(
  367. ( point.x - effectController.mousePos.value.x ),
  368. ( point.z - effectController.mousePos.value.y )
  369. );
  370. effectController.mousePos.value.set( point.x, point.z );
  371. if ( firstClick ) {
  372. controls.enabled = false;
  373. }
  374. } else {
  375. updateOriginMouseDown = true;
  376. effectController.mouseSpeed.value.set( 0, 0 );
  377. }
  378. firstClick = false;
  379. } else {
  380. updateOriginMouseDown = true;
  381. effectController.mouseSpeed.value.set( 0, 0 );
  382. }
  383. }
  384. function render() {
  385. raycast();
  386. frame ++;
  387. if ( frame >= 7 - effectController.speed ) {
  388. renderer.computeAsync( computeHeight );
  389. if ( effectController.ducksEnabled ) {
  390. renderer.computeAsync( computeDucks );
  391. }
  392. frame = 0;
  393. }
  394. renderer.render( scene, camera );
  395. }
  396. </script>
  397. </body>
  398. </html>
粤ICP备19079148号