webgpu_compute.html 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  1. <html lang="en">
  2. <head>
  3. <title>three.js - WebGPU - Compute</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. <!-- WebGPU (For Chrome 94-97), expires 10/11/2021 -->
  8. <meta http-equiv="origin-trial" content="Agfr4hEaaoH1kaTtGTZY4OU2lQQOv+gWq+8rYeHZBPWNnLww/smePFCIJOUdRFnQZkO3KAio+SNJapjzaoyFfQQAAABLeyJvcmlnaW4iOiJodHRwczovL3RocmVlanMub3JnOjQ0MyIsImZlYXR1cmUiOiJXZWJHUFUiLCJleHBpcnkiOjE2NDMxNTUxOTl9">
  9. </head>
  10. <body>
  11. <div id="info">
  12. <a href="https://threejs.org" target="_blank" rel="noopener">three.js</a> WebGPU - Compute<br/>(Chrome Canary with flag: --enable-unsafe-webgpu)
  13. </div>
  14. <script type="importmap">
  15. {
  16. "imports": {
  17. "three": "../build/three.module.js"
  18. }
  19. }
  20. </script>
  21. <script type="module">
  22. import * as THREE from 'three';
  23. import { GUI } from './jsm/libs/dat.gui.module.js';
  24. import WebGPURenderer from './jsm/renderers/webgpu/WebGPURenderer.js';
  25. import WebGPU from './jsm/renderers/webgpu/WebGPU.js';
  26. import WebGPUStorageBuffer from './jsm/renderers/webgpu/WebGPUStorageBuffer.js';
  27. import WebGPUUniformBuffer from './jsm/renderers/webgpu/WebGPUUniformBuffer.js';
  28. import * as WebGPUBufferUtils from './jsm/renderers/webgpu/WebGPUBufferUtils.js';
  29. import WebGPUUniformsGroup from './jsm/renderers/webgpu/WebGPUUniformsGroup.js';
  30. import { Vector2Uniform } from './jsm/renderers/webgpu/WebGPUUniform.js';
  31. import PositionNode from './jsm/renderers/nodes/accessors/PositionNode.js';
  32. import ColorNode from './jsm/renderers/nodes/inputs/ColorNode.js';
  33. import OperatorNode from './jsm/renderers/nodes/math/OperatorNode.js';
  34. import PointsNodeMaterial from './jsm/renderers/nodes/materials/PointsNodeMaterial.js';
  35. let camera, scene, renderer;
  36. let pointer;
  37. let scaleUniformBuffer;
  38. let scaleVector = new THREE.Vector3( 1, 1, 1 );
  39. const computeParams = [];
  40. init().then( animate ).catch( error );
  41. async function init() {
  42. if ( WebGPU.isAvailable() === false ) {
  43. document.body.appendChild( WebGPU.getErrorMessage() );
  44. throw 'No WebGPU support';
  45. }
  46. camera = new THREE.OrthographicCamera( - 1.0, 1.0, 1.0, - 1.0, 0, 1 );
  47. camera.position.z = 1;
  48. scene = new THREE.Scene();
  49. scene.background = new THREE.Color( 0x000000 );
  50. const particleNum = 65000; // 16-bit limit
  51. const particleSize = 3;
  52. const particleArray = new Float32Array( particleNum * particleSize );
  53. const velocityArray = new Float32Array( particleNum * particleSize );
  54. for ( let i = 0; i < particleArray.length; i += 3 ) {
  55. const r = Math.random() * 0.01 + 0.0005;
  56. const degree = Math.random() * 360;
  57. velocityArray[ i + 0 ] = r * Math.sin( degree * Math.PI / 180 );
  58. velocityArray[ i + 1 ] = r * Math.cos( degree * Math.PI / 180 );
  59. }
  60. const particleBuffer = new WebGPUStorageBuffer( 'particle', new THREE.BufferAttribute( particleArray, 3 ) );
  61. const velocityBuffer = new WebGPUStorageBuffer( 'velocity', new THREE.BufferAttribute( velocityArray, 3 ) );
  62. const scaleUniformLength = WebGPUBufferUtils.getVectorLength( 2, 3 ); // two vector3 for array
  63. scaleUniformBuffer = new WebGPUUniformBuffer( 'scaleUniform', new Float32Array( scaleUniformLength ) );
  64. pointer = new THREE.Vector2( - 10.0, - 10.0 ); // Out of bounds first
  65. const pointerGroup = new WebGPUUniformsGroup( 'mouseUniforms' ).addUniform(
  66. new Vector2Uniform( 'pointer', pointer )
  67. );
  68. // Object keys need follow the binding shader sequence
  69. const computeBindings = [
  70. particleBuffer,
  71. velocityBuffer,
  72. scaleUniformBuffer,
  73. pointerGroup
  74. ];
  75. const computeShader = /* glsl */`#version 450
  76. #define PARTICLE_NUM ${particleNum}
  77. #define PARTICLE_SIZE ${particleSize}
  78. #define ROOM_SIZE 1.0
  79. #define POINTER_SIZE 0.1
  80. // Limitation for now: the order should be the same as bindings order
  81. layout(set = 0, binding = 0) buffer Particle {
  82. float particle[ PARTICLE_NUM * PARTICLE_SIZE ];
  83. } particle;
  84. layout(set = 0, binding = 1) buffer Velocity {
  85. float velocity[ PARTICLE_NUM * PARTICLE_SIZE ];
  86. } velocity;
  87. layout(set = 0, binding = 2) uniform Scale {
  88. vec3 value[2];
  89. } scaleUniform;
  90. layout(set = 0, binding = 3) uniform MouseUniforms {
  91. vec2 pointer;
  92. } mouseUniforms;
  93. void main() {
  94. uint index = gl_GlobalInvocationID.x;
  95. if ( index >= PARTICLE_NUM ) { return; }
  96. vec3 position = vec3(
  97. particle.particle[ index * 3 + 0 ] + velocity.velocity[ index * 3 + 0 ],
  98. particle.particle[ index * 3 + 1 ] + velocity.velocity[ index * 3 + 1 ],
  99. particle.particle[ index * 3 + 2 ] + velocity.velocity[ index * 3 + 2 ]
  100. );
  101. if ( abs( position.x ) >= ROOM_SIZE ) {
  102. velocity.velocity[ index * 3 + 0 ] = - velocity.velocity[ index * 3 + 0 ];
  103. }
  104. if ( abs( position.y ) >= ROOM_SIZE ) {
  105. velocity.velocity[ index * 3 + 1 ] = - velocity.velocity[ index * 3 + 1 ];
  106. }
  107. if ( abs( position.z ) >= ROOM_SIZE ) {
  108. velocity.velocity[ index * 3 + 2 ] = - velocity.velocity[ index * 3 + 2 ];
  109. }
  110. float dx = mouseUniforms.pointer.x - position.x;
  111. float dy = mouseUniforms.pointer.y - position.y;
  112. float distanceFromPointer = sqrt( dx * dx + dy * dy );
  113. if ( distanceFromPointer <= POINTER_SIZE ) {
  114. position.x = 0.0;
  115. position.y = 0.0;
  116. position.z = 0.0;
  117. }
  118. particle.particle[ index * 3 + 0 ] = position.x * scaleUniform.value[0].x;
  119. particle.particle[ index * 3 + 1 ] = position.y * scaleUniform.value[0].y;
  120. particle.particle[ index * 3 + 2 ] = position.z * scaleUniform.value[0].z;
  121. }
  122. `;
  123. computeParams.push( {
  124. num: particleNum,
  125. shader: computeShader,
  126. bindings: computeBindings
  127. } );
  128. // Use a compute shader to animate the point cloud's vertex data.
  129. const pointsGeometry = new THREE.BufferGeometry().setAttribute(
  130. 'position', particleBuffer.attribute
  131. );
  132. const pointsMaterial = new PointsNodeMaterial();
  133. pointsMaterial.colorNode = new OperatorNode( '+', new PositionNode(), new ColorNode( new THREE.Color( 0x0000FF ) ) );
  134. const mesh = new THREE.Points( pointsGeometry, pointsMaterial );
  135. scene.add( mesh );
  136. renderer = new WebGPURenderer();
  137. renderer.setPixelRatio( window.devicePixelRatio );
  138. renderer.setSize( window.innerWidth, window.innerHeight );
  139. document.body.appendChild( renderer.domElement );
  140. window.addEventListener( 'resize', onWindowResize );
  141. window.addEventListener( 'mousemove', onMouseMove );
  142. // gui
  143. const gui = new GUI();
  144. gui.add( scaleVector, 'x', 0.9, 1.1, 0.01 );
  145. gui.add( scaleVector, 'y', 0.9, 1.1, 0.01 );
  146. gui.add( scaleVector, 'z', 0.9, 1.1, 0.01 );
  147. return renderer.init();
  148. }
  149. function onWindowResize() {
  150. camera.updateProjectionMatrix();
  151. renderer.setSize( window.innerWidth, window.innerHeight );
  152. }
  153. function onMouseMove( event ) {
  154. const x = event.clientX;
  155. const y = event.clientY;
  156. const width = window.innerWidth;
  157. const height = window.innerHeight;
  158. pointer.set(
  159. ( x / width - 0.5 ) * 2.0,
  160. ( - y / height + 0.5 ) * 2.0
  161. );
  162. }
  163. function animate() {
  164. requestAnimationFrame( animate );
  165. renderer.compute( computeParams );
  166. renderer.render( scene, camera );
  167. scaleVector.toArray( scaleUniformBuffer.buffer, 0 );
  168. }
  169. function error( error ) {
  170. console.error( error );
  171. }
  172. </script>
  173. </body>
  174. </html>