2
0

webgpu_compute_particles.html 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. <html lang="en">
  2. <head>
  3. <title>three.js - WebGPU - Compute Particles</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 - Compute - 1M Particles
  11. <div id="timestamps" style="
  12. position: absolute;
  13. top: 60px;
  14. left: 0;
  15. padding: 10px;
  16. background: rgba( 0, 0, 0, 0.5 );
  17. color: #fff;
  18. font-family: monospace;
  19. font-size: 12px;
  20. line-height: 1.5;
  21. pointer-events: none;
  22. text-align: left;
  23. "></div>
  24. </div>
  25. <script type="importmap">
  26. {
  27. "imports": {
  28. "three": "../build/three.module.js",
  29. "three/addons/": "./jsm/",
  30. "three/nodes": "./jsm/nodes/Nodes.js"
  31. }
  32. }
  33. </script>
  34. <script type="module">
  35. import * as THREE from 'three';
  36. import { tslFn, uniform, texture, instanceIndex, float, vec3, storage, SpriteNodeMaterial, If } from 'three/nodes';
  37. import WebGPU from 'three/addons/capabilities/WebGPU.js';
  38. import WebGL from 'three/addons/capabilities/WebGL.js';
  39. import WebGPURenderer from 'three/addons/renderers/webgpu/WebGPURenderer.js';
  40. import StorageInstancedBufferAttribute from 'three/addons/renderers/common/StorageInstancedBufferAttribute.js';
  41. import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
  42. import Stats from 'three/addons/libs/stats.module.js';
  43. import { GUI } from 'three/addons/libs/lil-gui.module.min.js';
  44. const particleCount = 1000000;
  45. const gravity = uniform( - .0098 );
  46. const bounce = uniform( .8 );
  47. const friction = uniform( .99 );
  48. const size = uniform( .12 );
  49. const clickPosition = uniform( new THREE.Vector3() );
  50. let camera, scene, renderer;
  51. let controls, stats;
  52. let computeParticles;
  53. const timestamps = document.getElementById( 'timestamps' );
  54. init();
  55. function init() {
  56. if ( WebGPU.isAvailable() === false && WebGL.isWebGL2Available() === false ) {
  57. document.body.appendChild( WebGPU.getErrorMessage() );
  58. throw new Error( 'No WebGPU or WebGL2 support' );
  59. }
  60. const { innerWidth, innerHeight } = window;
  61. camera = new THREE.PerspectiveCamera( 50, innerWidth / innerHeight, .1, 1000 );
  62. camera.position.set( 15, 30, 15 );
  63. scene = new THREE.Scene();
  64. // textures
  65. const textureLoader = new THREE.TextureLoader();
  66. const map = textureLoader.load( 'textures/sprite1.png' );
  67. //
  68. const createBuffer = () => storage( new StorageInstancedBufferAttribute( particleCount, 3 ), 'vec3', particleCount );
  69. const positionBuffer = createBuffer();
  70. const velocityBuffer = createBuffer();
  71. const colorBuffer = createBuffer();
  72. // compute
  73. const computeInit = tslFn( () => {
  74. const position = positionBuffer.element( instanceIndex );
  75. const color = colorBuffer.element( instanceIndex );
  76. const randX = instanceIndex.hash();
  77. const randY = instanceIndex.add( 2 ).hash();
  78. const randZ = instanceIndex.add( 3 ).hash();
  79. position.x = randX.mul( 100 ).add( - 50 );
  80. position.y = 0; // randY.mul( 10 );
  81. position.z = randZ.mul( 100 ).add( - 50 );
  82. color.assign( vec3( randX, randY, randZ ) );
  83. } )().compute( particleCount );
  84. //
  85. const computeUpdate = tslFn( () => {
  86. const position = positionBuffer.element( instanceIndex );
  87. const velocity = velocityBuffer.element( instanceIndex );
  88. velocity.addAssign( vec3( 0.00, gravity, 0.00 ) );
  89. position.addAssign( velocity );
  90. velocity.mulAssign( friction );
  91. // floor
  92. If( position.y.lessThan( 0 ), () => {
  93. position.y = 0;
  94. velocity.y = velocity.y.negate().mul( bounce );
  95. // floor friction
  96. velocity.x = velocity.x.mul( .9 );
  97. velocity.z = velocity.z.mul( .9 );
  98. } );
  99. } );
  100. computeParticles = computeUpdate().compute( particleCount );
  101. // create nodes
  102. const textureNode = texture( map );
  103. // create particles
  104. const particleMaterial = new SpriteNodeMaterial();
  105. particleMaterial.colorNode = textureNode.mul( colorBuffer.element( instanceIndex ) );
  106. particleMaterial.positionNode = positionBuffer.toAttribute();
  107. particleMaterial.scaleNode = size;
  108. particleMaterial.depthWrite = false;
  109. particleMaterial.depthTest = true;
  110. particleMaterial.transparent = true;
  111. const particles = new THREE.Mesh( new THREE.PlaneGeometry( 1, 1 ), particleMaterial );
  112. particles.count = particleCount;
  113. particles.frustumCulled = false;
  114. scene.add( particles );
  115. //
  116. const helper = new THREE.GridHelper( 60, 40, 0x303030, 0x303030 );
  117. scene.add( helper );
  118. const geometry = new THREE.PlaneGeometry( 1000, 1000 );
  119. geometry.rotateX( - Math.PI / 2 );
  120. const plane = new THREE.Mesh( geometry, new THREE.MeshBasicMaterial( { visible: false } ) );
  121. scene.add( plane );
  122. const raycaster = new THREE.Raycaster();
  123. const pointer = new THREE.Vector2();
  124. //
  125. renderer = new WebGPURenderer( { antialias: true, trackTimestamp: true } );
  126. renderer.setPixelRatio( window.devicePixelRatio );
  127. renderer.setSize( window.innerWidth, window.innerHeight );
  128. renderer.setAnimationLoop( animate );
  129. document.body.appendChild( renderer.domElement );
  130. stats = new Stats();
  131. document.body.appendChild( stats.dom );
  132. //
  133. renderer.compute( computeInit );
  134. // click event
  135. const computeHit = tslFn( () => {
  136. const position = positionBuffer.element( instanceIndex );
  137. const velocity = velocityBuffer.element( instanceIndex );
  138. const dist = position.distance( clickPosition );
  139. const direction = position.sub( clickPosition ).normalize();
  140. const distArea = float( 6 ).sub( dist ).max( 0 );
  141. const power = distArea.mul( .01 );
  142. const relativePower = power.mul( instanceIndex.hash().mul( .5 ).add( .5 ) );
  143. velocity.assign( velocity.add( direction.mul( relativePower ) ) );
  144. } )().compute( particleCount );
  145. //
  146. function onMove( event ) {
  147. pointer.set( ( event.clientX / window.innerWidth ) * 2 - 1, - ( event.clientY / window.innerHeight ) * 2 + 1 );
  148. raycaster.setFromCamera( pointer, camera );
  149. const intersects = raycaster.intersectObjects( [ plane ], false );
  150. if ( intersects.length > 0 ) {
  151. const { point } = intersects[ 0 ];
  152. // move to uniform
  153. clickPosition.value.copy( point );
  154. clickPosition.value.y = - 1;
  155. // compute
  156. renderer.compute( computeHit );
  157. }
  158. }
  159. // events
  160. renderer.domElement.addEventListener( 'pointermove', onMove );
  161. //
  162. controls = new OrbitControls( camera, renderer.domElement );
  163. controls.minDistance = 5;
  164. controls.maxDistance = 200;
  165. controls.target.set( 0, 0, 0 );
  166. controls.update();
  167. //
  168. window.addEventListener( 'resize', onWindowResize );
  169. // gui
  170. const gui = new GUI();
  171. gui.add( gravity, 'value', - .0098, 0, 0.0001 ).name( 'gravity' );
  172. gui.add( bounce, 'value', .1, 1, 0.01 ).name( 'bounce' );
  173. gui.add( friction, 'value', .96, .99, 0.01 ).name( 'friction' );
  174. gui.add( size, 'value', .12, .5, 0.01 ).name( 'size' );
  175. }
  176. function onWindowResize() {
  177. const { innerWidth, innerHeight } = window;
  178. camera.aspect = innerWidth / innerHeight;
  179. camera.updateProjectionMatrix();
  180. renderer.setSize( innerWidth, innerHeight );
  181. }
  182. async function animate() {
  183. stats.update();
  184. await renderer.computeAsync( computeParticles );
  185. await renderer.renderAsync( scene, camera );
  186. // throttle the logging
  187. if ( renderer.hasFeature( 'timestamp-query' ) ) {
  188. if ( renderer.info.render.calls % 5 === 0 ) {
  189. timestamps.innerHTML = `
  190. Compute ${renderer.info.compute.frameCalls} pass in ${renderer.info.compute.timestamp.toFixed( 6 )}ms<br>
  191. Draw ${renderer.info.render.drawCalls} pass in ${renderer.info.render.timestamp.toFixed( 6 )}ms`;
  192. }
  193. } else {
  194. timestamps.innerHTML = 'Timestamp queries not supported';
  195. }
  196. }
  197. </script>
  198. </body>
  199. </html>