webgpu_compute_particles_rain.html 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. <html lang="en">
  2. <head>
  3. <title>three.js - WebGPU - Compute Particles Rain</title>
  4. <meta charset="utf-8">
  5. <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
  6. <link type="text/css" rel="stylesheet" href="main.css">
  7. </head>
  8. <body>
  9. <div id="info">
  10. <a href="https://threejs.org" target="_blank" rel="noopener">three.js</a> WebGPU - GPU Compute Rain
  11. </div>
  12. <script type="importmap">
  13. {
  14. "imports": {
  15. "three": "../build/three.webgpu.js",
  16. "three/tsl": "../build/three.webgpu.js",
  17. "three/addons/": "./jsm/"
  18. }
  19. }
  20. </script>
  21. <script type="module">
  22. import * as THREE from 'three';
  23. import { tslFn, texture, uv, uint, positionWorld, modelWorldMatrix, cameraViewMatrix, timerLocal, timerDelta, cameraProjectionMatrix, vec2, instanceIndex, positionGeometry, storage, If } from 'three/tsl';
  24. import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
  25. import Stats from 'three/addons/libs/stats.module.js';
  26. import { GUI } from 'three/addons/libs/lil-gui.module.min.js';
  27. import * as BufferGeometryUtils from 'three/addons/utils/BufferGeometryUtils.js';
  28. const maxParticleCount = 50000;
  29. const instanceCount = maxParticleCount / 2;
  30. let camera, scene, renderer;
  31. let controls, stats;
  32. let computeParticles;
  33. let monkey;
  34. let clock;
  35. let collisionBox, collisionCamera, collisionPosRT, collisionPosMaterial;
  36. let collisionBoxPos, collisionBoxPosUI;
  37. init();
  38. function init() {
  39. const { innerWidth, innerHeight } = window;
  40. camera = new THREE.PerspectiveCamera( 60, innerWidth / innerHeight, .1, 110 );
  41. camera.position.set( 40, 8, 0 );
  42. camera.lookAt( 0, 0, 0 );
  43. scene = new THREE.Scene();
  44. const dirLight = new THREE.DirectionalLight( 0xffffff, .5 );
  45. dirLight.castShadow = true;
  46. dirLight.position.set( 3, 17, 17 );
  47. dirLight.castShadow = true;
  48. dirLight.shadow.camera.near = 1;
  49. dirLight.shadow.camera.far = 50;
  50. dirLight.shadow.camera.right = 25;
  51. dirLight.shadow.camera.left = - 25;
  52. dirLight.shadow.camera.top = 25;
  53. dirLight.shadow.camera.bottom = - 25;
  54. dirLight.shadow.mapSize.width = 2048;
  55. dirLight.shadow.mapSize.height = 2048;
  56. dirLight.shadow.bias = - 0.01;
  57. scene.add( dirLight );
  58. scene.add( new THREE.AmbientLight( 0x111111 ) );
  59. //
  60. collisionCamera = new THREE.OrthographicCamera( - 50, 50, 50, - 50, .1, 50 );
  61. collisionCamera.position.y = 50;
  62. collisionCamera.lookAt( 0, 0, 0 );
  63. collisionCamera.layers.disableAll();
  64. collisionCamera.layers.enable( 1 );
  65. collisionPosRT = new THREE.RenderTarget( 1024, 1024 );
  66. collisionPosRT.texture.type = THREE.HalfFloatType;
  67. collisionPosRT.texture.magFilter = THREE.NearestFilter;
  68. collisionPosRT.texture.minFilter = THREE.NearestFilter;
  69. collisionPosMaterial = new THREE.MeshBasicNodeMaterial();
  70. collisionPosMaterial.colorNode = positionWorld;
  71. //
  72. const createBuffer = ( type = 'vec3' ) => storage( new THREE.StorageInstancedBufferAttribute( maxParticleCount, 3 ), type, maxParticleCount );
  73. const positionBuffer = createBuffer();
  74. const velocityBuffer = createBuffer();
  75. const ripplePositionBuffer = createBuffer();
  76. const rippleTimeBuffer = createBuffer();
  77. // compute
  78. const timer = timerLocal();
  79. const randUint = () => uint( Math.random() * 0xFFFFFF );
  80. const computeInit = tslFn( () => {
  81. const position = positionBuffer.element( instanceIndex );
  82. const velocity = velocityBuffer.element( instanceIndex );
  83. const rippleTime = rippleTimeBuffer.element( instanceIndex );
  84. const randX = instanceIndex.hash();
  85. const randY = instanceIndex.add( randUint() ).hash();
  86. const randZ = instanceIndex.add( randUint() ).hash();
  87. position.x = randX.mul( 100 ).add( - 50 );
  88. position.y = randY.mul( 25 );
  89. position.z = randZ.mul( 100 ).add( - 50 );
  90. velocity.y = randX.mul( - .04 ).add( - .2 );
  91. rippleTime.x = 1000;
  92. } )().compute( maxParticleCount );
  93. //
  94. const computeUpdate = tslFn( () => {
  95. const getCoord = ( pos ) => pos.add( 50 ).div( 100 );
  96. const position = positionBuffer.element( instanceIndex );
  97. const velocity = velocityBuffer.element( instanceIndex );
  98. const ripplePosition = ripplePositionBuffer.element( instanceIndex );
  99. const rippleTime = rippleTimeBuffer.element( instanceIndex );
  100. position.addAssign( velocity );
  101. rippleTime.x = rippleTime.x.add( timerDelta().mul( 4 ) );
  102. //
  103. const collisionArea = texture( collisionPosRT.texture, getCoord( position.xz ) );
  104. const surfaceOffset = .05;
  105. const floorPosition = collisionArea.y.add( surfaceOffset );
  106. // floor
  107. const ripplePivotOffsetY = - .9;
  108. If( position.y.add( ripplePivotOffsetY ).lessThan( floorPosition ), () => {
  109. position.y = 25;
  110. ripplePosition.xz = position.xz;
  111. ripplePosition.y = floorPosition;
  112. // reset hit time: x = time
  113. rippleTime.x = 1;
  114. // next drops will not fall in the same place
  115. position.x = instanceIndex.add( timer ).hash().mul( 100 ).add( - 50 );
  116. position.z = instanceIndex.add( timer.add( randUint() ) ).hash().mul( 100 ).add( - 50 );
  117. } );
  118. const rippleOnSurface = texture( collisionPosRT.texture, getCoord( ripplePosition.xz ) );
  119. const rippleFloorArea = rippleOnSurface.y.add( surfaceOffset );
  120. If( ripplePosition.y.greaterThan( rippleFloorArea ), () => {
  121. rippleTime.x = 1000;
  122. } );
  123. } );
  124. computeParticles = computeUpdate().compute( maxParticleCount );
  125. // rain
  126. const billboarding = tslFn( () => {
  127. const particlePosition = positionBuffer.toAttribute();
  128. const worldMatrix = modelWorldMatrix.toVar();
  129. worldMatrix[ 3 ][ 0 ] = particlePosition.x;
  130. worldMatrix[ 3 ][ 1 ] = particlePosition.y;
  131. worldMatrix[ 3 ][ 2 ] = particlePosition.z;
  132. const modelViewMatrix = cameraViewMatrix.mul( worldMatrix );
  133. modelViewMatrix[ 0 ][ 0 ] = 1;
  134. modelViewMatrix[ 0 ][ 1 ] = 0;
  135. modelViewMatrix[ 0 ][ 2 ] = 0;
  136. //modelViewMatrix[ 0 ][ 0 ] = modelWorldMatrix[ 0 ].length();
  137. //modelViewMatrix[ 1 ][ 1 ] = modelWorldMatrix[ 1 ].length();
  138. modelViewMatrix[ 2 ][ 0 ] = 0;
  139. modelViewMatrix[ 2 ][ 1 ] = 0;
  140. modelViewMatrix[ 2 ][ 2 ] = 1;
  141. return cameraProjectionMatrix.mul( modelViewMatrix ).mul( positionGeometry );
  142. } );
  143. const rainMaterial = new THREE.MeshBasicNodeMaterial();
  144. rainMaterial.colorNode = uv().distance( vec2( .5, 0 ) ).oneMinus().mul( 3 ).exp().mul( .1 );
  145. rainMaterial.vertexNode = billboarding();
  146. rainMaterial.opacity = .2;
  147. rainMaterial.side = THREE.DoubleSide;
  148. rainMaterial.forceSinglePass = true;
  149. rainMaterial.depthWrite = false;
  150. rainMaterial.depthTest = true;
  151. rainMaterial.transparent = true;
  152. const rainParticles = new THREE.Mesh( new THREE.PlaneGeometry( .1, 2 ), rainMaterial );
  153. rainParticles.count = instanceCount;
  154. scene.add( rainParticles );
  155. // ripple
  156. const rippleTime = rippleTimeBuffer.element( instanceIndex ).x;
  157. const rippleEffect = tslFn( () => {
  158. const center = uv().add( vec2( - .5 ) ).length().mul( 7 );
  159. const distance = rippleTime.sub( center );
  160. return distance.min( 1 ).sub( distance.max( 1 ).sub( 1 ) );
  161. } );
  162. const rippleMaterial = new THREE.MeshBasicNodeMaterial();
  163. rippleMaterial.colorNode = rippleEffect();
  164. rippleMaterial.positionNode = positionGeometry.add( ripplePositionBuffer.toAttribute() );
  165. rippleMaterial.opacityNode = rippleTime.mul( .3 ).oneMinus().max( 0 ).mul( .5 );
  166. rippleMaterial.side = THREE.DoubleSide;
  167. rippleMaterial.forceSinglePass = true;
  168. rippleMaterial.depthWrite = false;
  169. rippleMaterial.depthTest = true;
  170. rippleMaterial.transparent = true;
  171. // ripple geometry
  172. const surfaceRippleGeometry = new THREE.PlaneGeometry( 2.5, 2.5 );
  173. surfaceRippleGeometry.rotateX( - Math.PI / 2 );
  174. const xRippleGeometry = new THREE.PlaneGeometry( 1, 2 );
  175. xRippleGeometry.rotateY( - Math.PI / 2 );
  176. const zRippleGeometry = new THREE.PlaneGeometry( 1, 2 );
  177. const rippleGeometry = BufferGeometryUtils.mergeGeometries( [ surfaceRippleGeometry, xRippleGeometry, zRippleGeometry ] );
  178. const rippleParticles = new THREE.Mesh( rippleGeometry, rippleMaterial );
  179. rippleParticles.count = instanceCount;
  180. scene.add( rippleParticles );
  181. // floor geometry
  182. const floorGeometry = new THREE.PlaneGeometry( 1000, 1000 );
  183. floorGeometry.rotateX( - Math.PI / 2 );
  184. const plane = new THREE.Mesh( floorGeometry, new THREE.MeshBasicMaterial( { color: 0x050505 } ) );
  185. scene.add( plane );
  186. //
  187. collisionBox = new THREE.Mesh( new THREE.BoxGeometry( 30, 1, 15 ), new THREE.MeshStandardMaterial() );
  188. collisionBox.material.color.set( 0x333333 );
  189. collisionBox.position.y = 12;
  190. collisionBox.scale.x = 3.5;
  191. collisionBox.layers.enable( 1 );
  192. collisionBox.castShadow = true;
  193. scene.add( collisionBox );
  194. //
  195. const loader = new THREE.BufferGeometryLoader();
  196. loader.load( 'models/json/suzanne_buffergeometry.json', function ( geometry ) {
  197. geometry.computeVertexNormals();
  198. monkey = new THREE.Mesh( geometry, new THREE.MeshStandardMaterial( { roughness: 1, metalness: 0 } ) );
  199. monkey.receiveShadow = true;
  200. monkey.scale.setScalar( 5 );
  201. monkey.rotation.y = Math.PI / 2;
  202. monkey.position.y = 4.5;
  203. monkey.layers.enable( 1 ); // add to collision layer
  204. scene.add( monkey );
  205. } );
  206. //
  207. clock = new THREE.Clock();
  208. //
  209. renderer = new THREE.WebGPURenderer( { antialias: true } );
  210. renderer.setPixelRatio( window.devicePixelRatio );
  211. renderer.setSize( window.innerWidth, window.innerHeight );
  212. renderer.setAnimationLoop( animate );
  213. document.body.appendChild( renderer.domElement );
  214. stats = new Stats();
  215. document.body.appendChild( stats.dom );
  216. //
  217. renderer.compute( computeInit );
  218. //
  219. controls = new OrbitControls( camera, renderer.domElement );
  220. controls.minDistance = 5;
  221. controls.maxDistance = 50;
  222. controls.update();
  223. //
  224. window.addEventListener( 'resize', onWindowResize );
  225. // gui
  226. const gui = new GUI();
  227. // use lerp to smooth the movement
  228. collisionBoxPosUI = new THREE.Vector3().copy( collisionBox.position );
  229. collisionBoxPos = new THREE.Vector3();
  230. gui.add( collisionBoxPosUI, 'z', - 50, 50, .001 ).name( 'position' );
  231. gui.add( collisionBox.scale, 'x', .1, 3.5, 0.01 ).name( 'scale' );
  232. gui.add( rainParticles, 'count', 200, maxParticleCount, 1 ).name( 'drop count' ).onChange( ( v ) => rippleParticles.count = v );
  233. }
  234. function onWindowResize() {
  235. const { innerWidth, innerHeight } = window;
  236. camera.aspect = innerWidth / innerHeight;
  237. camera.updateProjectionMatrix();
  238. renderer.setSize( innerWidth, innerHeight );
  239. }
  240. function animate() {
  241. stats.update();
  242. const delta = clock.getDelta();
  243. if ( monkey ) {
  244. monkey.rotation.y += delta;
  245. }
  246. collisionBoxPos.set( collisionBoxPosUI.x, collisionBoxPosUI.y, - collisionBoxPosUI.z );
  247. collisionBox.position.lerp( collisionBoxPos, 10 * delta );
  248. // position
  249. scene.overrideMaterial = collisionPosMaterial;
  250. renderer.setRenderTarget( collisionPosRT );
  251. renderer.render( scene, collisionCamera );
  252. // compute
  253. renderer.compute( computeParticles );
  254. // result
  255. scene.overrideMaterial = null;
  256. renderer.setRenderTarget( null );
  257. renderer.render( scene, camera );
  258. }
  259. </script>
  260. </body>
  261. </html>