webgpu_compute_particles.html 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  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, shapeCircle,
  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.opacityNode = shapeCircle();
  100. material.alphaToCoverage = true;
  101. material.transparent = true;
  102. const particles = new THREE.Sprite( material );
  103. particles.count = particleCount;
  104. particles.frustumCulled = false;
  105. scene.add( particles );
  106. //
  107. const helper = new THREE.GridHelper( 90, 45, 0x303030, 0x303030 );
  108. scene.add( helper );
  109. const geometry = new THREE.PlaneGeometry( 200, 200 );
  110. geometry.rotateX( - Math.PI / 2 );
  111. const plane = new THREE.Mesh( geometry, new THREE.MeshBasicMaterial( { visible: false } ) );
  112. scene.add( plane );
  113. const raycaster = new THREE.Raycaster();
  114. const pointer = new THREE.Vector2();
  115. //
  116. renderer = new THREE.WebGPURenderer( { antialias: true, trackTimestamp: true } );
  117. renderer.setPixelRatio( window.devicePixelRatio );
  118. renderer.setSize( window.innerWidth, window.innerHeight );
  119. renderer.setAnimationLoop( animate );
  120. document.body.appendChild( renderer.domElement );
  121. stats = new Stats();
  122. document.body.appendChild( stats.dom );
  123. //
  124. renderer.computeAsync( computeInit );
  125. // Hit
  126. const computeHit = Fn( () => {
  127. const position = positions.element( instanceIndex );
  128. const velocity = velocities.element( instanceIndex );
  129. const dist = position.distance( clickPosition );
  130. const direction = position.sub( clickPosition ).normalize();
  131. const distArea = float( 3 ).sub( dist ).max( 0 );
  132. const power = distArea.mul( .01 );
  133. const relativePower = power.mul( hash( instanceIndex ).mul( 1.5 ).add( .5 ) );
  134. velocity.assign( velocity.add( direction.mul( relativePower ) ) );
  135. } )().compute( particleCount );
  136. //
  137. function onMove( event ) {
  138. if ( isOrbitControlsActive ) return;
  139. pointer.set( ( event.clientX / window.innerWidth ) * 2 - 1, - ( event.clientY / window.innerHeight ) * 2 + 1 );
  140. raycaster.setFromCamera( pointer, camera );
  141. const intersects = raycaster.intersectObject( plane, false );
  142. if ( intersects.length > 0 ) {
  143. const { point } = intersects[ 0 ];
  144. // move to uniform
  145. clickPosition.value.copy( point );
  146. clickPosition.value.y = - 1;
  147. // compute
  148. renderer.computeAsync( computeHit );
  149. }
  150. }
  151. renderer.domElement.addEventListener( 'pointermove', onMove );
  152. // controls
  153. controls = new OrbitControls( camera, renderer.domElement );
  154. controls.enableDamping = true;
  155. controls.minDistance = 5;
  156. controls.maxDistance = 200;
  157. controls.target.set( 0, -8, 0 );
  158. controls.update();
  159. controls.addEventListener( 'start', () => { isOrbitControlsActive = true; } );
  160. controls.addEventListener( 'end', () => { isOrbitControlsActive = false; } );
  161. controls.touches = {
  162. ONE: null,
  163. TWO: THREE.TOUCH.DOLLY_PAN
  164. };
  165. //
  166. window.addEventListener( 'resize', onWindowResize );
  167. // gui
  168. const gui = new GUI();
  169. gui.add( gravity, 'value', - .0098, 0, 0.0001 ).name( 'gravity' );
  170. gui.add( bounce, 'value', .1, 1, 0.01 ).name( 'bounce' );
  171. gui.add( friction, 'value', .96, .99, 0.01 ).name( 'friction' );
  172. gui.add( size, 'value', .12, .5, 0.01 ).name( 'size' );
  173. }
  174. function onWindowResize() {
  175. const { innerWidth, innerHeight } = window;
  176. camera.aspect = innerWidth / innerHeight;
  177. camera.updateProjectionMatrix();
  178. renderer.setSize( innerWidth, innerHeight );
  179. }
  180. async function animate() {
  181. stats.update();
  182. controls.update();
  183. await renderer.computeAsync( computeParticles );
  184. renderer.resolveTimestampsAsync( THREE.TimestampQuery.COMPUTE );
  185. await renderer.renderAsync( scene, camera );
  186. renderer.resolveTimestampsAsync( THREE.TimestampQuery.RENDER );
  187. // throttle the logging
  188. if ( renderer.hasFeature( 'timestamp-query' ) ) {
  189. if ( renderer.info.render.calls % 5 === 0 ) {
  190. timestamps.innerHTML = `
  191. Compute ${renderer.info.compute.frameCalls} pass in ${renderer.info.compute.timestamp.toFixed( 6 )}ms<br>
  192. Draw ${renderer.info.render.drawCalls} pass in ${renderer.info.render.timestamp.toFixed( 6 )}ms`;
  193. }
  194. } else {
  195. timestamps.innerHTML = 'Timestamp queries not supported';
  196. }
  197. }
  198. </script>
  199. </body>
  200. </html>
粤ICP备19079148号