webgpu_compute.html 7.4 KB

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