webgpu_compute_particles_rain.html 12 KB

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