webgpu_compute_particles.html 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  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 - 500k 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.webgpu.js",
  29. "three/webgpu": "../build/three.webgpu.js",
  30. "three/tsl": "../build/three.tsl.js",
  31. "three/addons/": "./jsm/"
  32. }
  33. }
  34. </script>
  35. <script type="module">
  36. import * as THREE from 'three';
  37. import { Fn, If, uniform, float, uv, vec2, vec3, hash,
  38. instancedArray, instanceIndex } from 'three/tsl';
  39. import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
  40. import Stats from 'three/addons/libs/stats.module.js';
  41. import { GUI } from 'three/addons/libs/lil-gui.module.min.js';
  42. const particleCount = 200_000;
  43. const gravity = uniform( - .00098 );
  44. const bounce = uniform( .8 );
  45. const friction = uniform( .99 );
  46. const size = uniform( .12 );
  47. const clickPosition = uniform( new THREE.Vector3() );
  48. let camera, scene, renderer;
  49. let controls, stats;
  50. let computeParticles;
  51. let isOrbitControlsActive;
  52. const timestamps = document.getElementById( 'timestamps' );
  53. init();
  54. function init() {
  55. const { innerWidth, innerHeight } = window;
  56. camera = new THREE.PerspectiveCamera( 50, innerWidth / innerHeight, .1, 1000 );
  57. camera.position.set( 0, 5, 20 );
  58. scene = new THREE.Scene();
  59. //
  60. const positions = instancedArray( particleCount, 'vec3' );
  61. const velocities = instancedArray( particleCount, 'vec3' );
  62. const colors = instancedArray( particleCount, 'vec3' );
  63. // compute
  64. const separation = 0.2;
  65. const amount = Math.sqrt( particleCount );
  66. const offset = float( amount / 2 );
  67. const computeInit = Fn( () => {
  68. const position = positions.element( instanceIndex );
  69. const color = colors.element( instanceIndex );
  70. const x = instanceIndex.mod( amount );
  71. const z = instanceIndex.div( amount );
  72. position.x = offset.sub( x ).mul( separation );
  73. position.z = offset.sub( z ).mul( separation );
  74. color.x = hash( instanceIndex );
  75. color.y = hash( instanceIndex.add( 2 ) );
  76. } )().compute( particleCount );
  77. //
  78. const computeUpdate = Fn( () => {
  79. const position = positions.element( instanceIndex );
  80. const velocity = velocities.element( instanceIndex );
  81. velocity.addAssign( vec3( 0.00, gravity, 0.00 ) );
  82. position.addAssign( velocity );
  83. velocity.mulAssign( friction );
  84. // floor
  85. If( position.y.lessThan( 0 ), () => {
  86. position.y = 0;
  87. velocity.y = velocity.y.negate().mul( bounce );
  88. // floor friction
  89. velocity.x = velocity.x.mul( .9 );
  90. velocity.z = velocity.z.mul( .9 );
  91. } );
  92. } );
  93. computeParticles = computeUpdate().compute( particleCount );
  94. // create particles
  95. const material = new THREE.SpriteNodeMaterial();
  96. material.colorNode = uv().mul( colors.element( instanceIndex ) );
  97. material.positionNode = positions.toAttribute();
  98. material.scaleNode = size;
  99. material.alphaTestNode = uv().mul( 2 ).distance( vec2( 1 ) );
  100. material.transparent = false;
  101. const particles = new THREE.Sprite( material );
  102. particles.count = particleCount;
  103. particles.frustumCulled = false;
  104. scene.add( particles );
  105. //
  106. const helper = new THREE.GridHelper( 90, 45, 0x303030, 0x303030 );
  107. scene.add( helper );
  108. const geometry = new THREE.PlaneGeometry( 200, 200 );
  109. geometry.rotateX( - Math.PI / 2 );
  110. const plane = new THREE.Mesh( geometry, new THREE.MeshBasicMaterial( { visible: false } ) );
  111. scene.add( plane );
  112. const raycaster = new THREE.Raycaster();
  113. const pointer = new THREE.Vector2();
  114. //
  115. renderer = new THREE.WebGPURenderer( { antialias: true, trackTimestamp: true } );
  116. renderer.setPixelRatio( window.devicePixelRatio );
  117. renderer.setSize( window.innerWidth, window.innerHeight );
  118. renderer.setAnimationLoop( animate );
  119. document.body.appendChild( renderer.domElement );
  120. stats = new Stats();
  121. document.body.appendChild( stats.dom );
  122. //
  123. renderer.computeAsync( computeInit );
  124. // Hit
  125. const computeHit = Fn( () => {
  126. const position = positions.element( instanceIndex );
  127. const velocity = velocities.element( instanceIndex );
  128. const dist = position.distance( clickPosition );
  129. const direction = position.sub( clickPosition ).normalize();
  130. const distArea = float( 3 ).sub( dist ).max( 0 );
  131. const power = distArea.mul( .01 );
  132. const relativePower = power.mul( hash( instanceIndex ).mul( 1.5 ).add( .5 ) );
  133. velocity.assign( velocity.add( direction.mul( relativePower ) ) );
  134. } )().compute( particleCount );
  135. //
  136. function onMove( event ) {
  137. if ( isOrbitControlsActive ) return;
  138. pointer.set( ( event.clientX / window.innerWidth ) * 2 - 1, - ( event.clientY / window.innerHeight ) * 2 + 1 );
  139. raycaster.setFromCamera( pointer, camera );
  140. const intersects = raycaster.intersectObject( plane, false );
  141. if ( intersects.length > 0 ) {
  142. const { point } = intersects[ 0 ];
  143. // move to uniform
  144. clickPosition.value.copy( point );
  145. clickPosition.value.y = - 1;
  146. // compute
  147. renderer.computeAsync( computeHit );
  148. }
  149. }
  150. renderer.domElement.addEventListener( 'pointermove', onMove );
  151. // controls
  152. controls = new OrbitControls( camera, renderer.domElement );
  153. controls.enableDamping = true;
  154. controls.minDistance = 5;
  155. controls.maxDistance = 200;
  156. controls.target.set( 0, -8, 0 );
  157. controls.update();
  158. controls.addEventListener( 'start', () => { isOrbitControlsActive = true; } );
  159. controls.addEventListener( 'end', () => { isOrbitControlsActive = false; } );
  160. controls.touches = {
  161. ONE: null,
  162. TWO: THREE.TOUCH.DOLLY_PAN
  163. };
  164. //
  165. window.addEventListener( 'resize', onWindowResize );
  166. // gui
  167. const gui = new GUI();
  168. gui.add( gravity, 'value', - .0098, 0, 0.0001 ).name( 'gravity' );
  169. gui.add( bounce, 'value', .1, 1, 0.01 ).name( 'bounce' );
  170. gui.add( friction, 'value', .96, .99, 0.01 ).name( 'friction' );
  171. gui.add( size, 'value', .12, .5, 0.01 ).name( 'size' );
  172. }
  173. function onWindowResize() {
  174. const { innerWidth, innerHeight } = window;
  175. camera.aspect = innerWidth / innerHeight;
  176. camera.updateProjectionMatrix();
  177. renderer.setSize( innerWidth, innerHeight );
  178. }
  179. async function animate() {
  180. stats.update();
  181. controls.update();
  182. await renderer.computeAsync( computeParticles );
  183. renderer.resolveTimestampsAsync( THREE.TimestampQuery.COMPUTE );
  184. await renderer.renderAsync( scene, camera );
  185. renderer.resolveTimestampsAsync( THREE.TimestampQuery.RENDER );
  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>
粤ICP备19079148号