webgpu_tsl_compute_attractors_particles.html 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>three.js webgpu - attractors particles</title>
  5. <meta charset="utf-8">
  6. <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
  7. <link type="text/css" rel="stylesheet" href="main.css">
  8. </head>
  9. <body>
  10. <div id="info">
  11. <a href="https://threejs.org" target="_blank" rel="noopener">three.js</a> WebGPU - Compute Attractors Particles
  12. </div>
  13. <script type="importmap">
  14. {
  15. "imports": {
  16. "three": "../build/three.webgpu.js",
  17. "three/tsl": "../build/three.webgpu.js",
  18. "three/addons/": "./jsm/"
  19. }
  20. }
  21. </script>
  22. <script type="module">
  23. import * as THREE from 'three';
  24. import { float, If, PI, color, cos, instanceIndex, Loop, mix, mod, sin, storage, Fn, uint, uniform, uniformArray, hash, vec3, vec4 } from 'three/tsl';
  25. import { GUI } from 'three/addons/libs/lil-gui.module.min.js';
  26. import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
  27. import { TransformControls } from 'three/addons/controls/TransformControls.js';
  28. let camera, scene, renderer, controls, updateCompute;
  29. init();
  30. function init() {
  31. camera = new THREE.PerspectiveCamera( 25, window.innerWidth / window.innerHeight, 0.1, 100 );
  32. camera.position.set( 3, 5, 8 );
  33. scene = new THREE.Scene();
  34. // ambient light
  35. const ambientLight = new THREE.AmbientLight( '#ffffff', 0.5 );
  36. scene.add( ambientLight );
  37. // directional light
  38. const directionalLight = new THREE.DirectionalLight( '#ffffff', 1.5 );
  39. directionalLight.position.set( 4, 2, 0 );
  40. scene.add( directionalLight );
  41. // renderer
  42. renderer = new THREE.WebGPURenderer( { antialias: true } );
  43. renderer.setPixelRatio( window.devicePixelRatio );
  44. renderer.setSize( window.innerWidth, window.innerHeight );
  45. renderer.setAnimationLoop( animate );
  46. renderer.setClearColor( '#000000' );
  47. document.body.appendChild( renderer.domElement );
  48. controls = new OrbitControls( camera, renderer.domElement );
  49. controls.enableDamping = true;
  50. controls.minDistance = 0.1;
  51. controls.maxDistance = 50;
  52. window.addEventListener( 'resize', onWindowResize );
  53. // attractors
  54. const attractorsPositions = uniformArray( [
  55. new THREE.Vector3( - 1, 0, 0 ),
  56. new THREE.Vector3( 1, 0, - 0.5 ),
  57. new THREE.Vector3( 0, 0.5, 1 )
  58. ] );
  59. const attractorsRotationAxes = uniformArray( [
  60. new THREE.Vector3( 0, 1, 0 ),
  61. new THREE.Vector3( 0, 1, 0 ),
  62. new THREE.Vector3( 1, 0, - 0.5 ).normalize()
  63. ] );
  64. const attractorsLength = uniform( attractorsPositions.array.length );
  65. const attractors = [];
  66. const helpersRingGeometry = new THREE.RingGeometry( 1, 1.02, 32, 1, 0, Math.PI * 1.5 );
  67. const helpersArrowGeometry = new THREE.ConeGeometry( 0.1, 0.4, 12, 1, false );
  68. const helpersMaterial = new THREE.MeshBasicMaterial( { side: THREE.DoubleSide } );
  69. for ( let i = 0; i < attractorsPositions.array.length; i ++ ) {
  70. const attractor = {};
  71. attractor.position = attractorsPositions.array[ i ];
  72. attractor.orientation = attractorsRotationAxes.array[ i ];
  73. attractor.reference = new THREE.Object3D();
  74. attractor.reference.position.copy( attractor.position );
  75. attractor.reference.quaternion.setFromUnitVectors( new THREE.Vector3( 0, 1, 0 ), attractor.orientation );
  76. scene.add( attractor.reference );
  77. attractor.helper = new THREE.Group();
  78. attractor.helper.scale.setScalar( 0.325 );
  79. attractor.reference.add( attractor.helper );
  80. attractor.ring = new THREE.Mesh( helpersRingGeometry, helpersMaterial );
  81. attractor.ring.rotation.x = - Math.PI * 0.5;
  82. attractor.helper.add( attractor.ring );
  83. attractor.arrow = new THREE.Mesh( helpersArrowGeometry, helpersMaterial );
  84. attractor.arrow.position.x = 1;
  85. attractor.arrow.position.z = 0.2;
  86. attractor.arrow.rotation.x = Math.PI * 0.5;
  87. attractor.helper.add( attractor.arrow );
  88. attractor.controls = new TransformControls( camera, renderer.domElement );
  89. attractor.controls.mode = 'rotate';
  90. attractor.controls.size = 0.5;
  91. attractor.controls.attach( attractor.reference );
  92. attractor.controls.visible = true;
  93. attractor.controls.enabled = attractor.controls.visible;
  94. scene.add( attractor.controls );
  95. attractor.controls.addEventListener( 'dragging-changed', ( event ) => {
  96. controls.enabled = ! event.value;
  97. } );
  98. attractor.controls.addEventListener( 'change', () => {
  99. attractor.position.copy( attractor.reference.position );
  100. attractor.orientation.copy( new THREE.Vector3( 0, 1, 0 ).applyQuaternion( attractor.reference.quaternion ) );
  101. } );
  102. attractors.push( attractor );
  103. }
  104. // particles
  105. const count = Math.pow( 2, 18 );
  106. const material = new THREE.SpriteNodeMaterial( { transparent: true, blending: THREE.AdditiveBlending, depthWrite: false } );
  107. const attractorMass = uniform( Number( `1e${7}` ) );
  108. const particleGlobalMass = uniform( Number( `1e${4}` ) );
  109. const timeScale = uniform( 1 );
  110. const spinningStrength = uniform( 2.75 );
  111. const maxSpeed = uniform( 8 );
  112. const gravityConstant = 6.67e-11;
  113. const velocityDamping = uniform( 0.1 );
  114. const scale = uniform( 0.008 );
  115. const boundHalfExtent = uniform( 8 );
  116. const colorA = uniform( color( '#5900ff' ) );
  117. const colorB = uniform( color( '#ffa575' ) );
  118. const positionBuffer = storage( new THREE.StorageInstancedBufferAttribute( count, 3 ), 'vec3', count );
  119. const velocityBuffer = storage( new THREE.StorageInstancedBufferAttribute( count, 3 ), 'vec3', count );
  120. const sphericalToVec3 = Fn( ( [ phi, theta ] ) => {
  121. const sinPhiRadius = sin( phi );
  122. return vec3(
  123. sinPhiRadius.mul( sin( theta ) ),
  124. cos( phi ),
  125. sinPhiRadius.mul( cos( theta ) )
  126. );
  127. } );
  128. // init compute
  129. const init = Fn( () => {
  130. const position = positionBuffer.element( instanceIndex );
  131. const velocity = velocityBuffer.element( instanceIndex );
  132. const basePosition = vec3(
  133. hash( instanceIndex.add( uint( Math.random() * 0xffffff ) ) ),
  134. hash( instanceIndex.add( uint( Math.random() * 0xffffff ) ) ),
  135. hash( instanceIndex.add( uint( Math.random() * 0xffffff ) ) )
  136. ).sub( 0.5 ).mul( vec3( 5, 0.2, 5 ) );
  137. position.assign( basePosition );
  138. const phi = hash( instanceIndex.add( uint( Math.random() * 0xffffff ) ) ).mul( PI ).mul( 2 );
  139. const theta = hash( instanceIndex.add( uint( Math.random() * 0xffffff ) ) ).mul( PI );
  140. const baseVelocity = sphericalToVec3( phi, theta ).mul( 0.05 );
  141. velocity.assign( baseVelocity );
  142. } );
  143. const initCompute = init().compute( count );
  144. const reset = () => {
  145. renderer.compute( initCompute );
  146. };
  147. reset();
  148. // update compute
  149. const particleMassMultiplier = hash( instanceIndex.add( uint( Math.random() * 0xffffff ) ) ).remap( 0.25, 1 ).toVar();
  150. const particleMass = particleMassMultiplier.mul( particleGlobalMass ).toVar();
  151. const update = Fn( () => {
  152. // const delta = timerDelta().mul( timeScale ).min( 1 / 30 ).toVar();
  153. const delta = float( 1 / 60 ).mul( timeScale ).toVar(); // uses fixed delta to consistant result
  154. const position = positionBuffer.element( instanceIndex );
  155. const velocity = velocityBuffer.element( instanceIndex );
  156. // force
  157. const force = vec3( 0 ).toVar();
  158. Loop( attractorsLength, ( { i } ) => {
  159. const attractorPosition = attractorsPositions.element( i );
  160. const attractorRotationAxis = attractorsRotationAxes.element( i );
  161. const toAttractor = attractorPosition.sub( position );
  162. const distance = toAttractor.length();
  163. const direction = toAttractor.normalize();
  164. // gravity
  165. const gravityStrength = attractorMass.mul( particleMass ).mul( gravityConstant ).div( distance.pow( 2 ) ).toVar();
  166. const gravityForce = direction.mul( gravityStrength );
  167. force.addAssign( gravityForce );
  168. // spinning
  169. const spinningForce = attractorRotationAxis.mul( gravityStrength ).mul( spinningStrength );
  170. const spinningVelocity = spinningForce.cross( toAttractor );
  171. force.addAssign( spinningVelocity );
  172. } );
  173. // velocity
  174. velocity.addAssign( force.mul( delta ) );
  175. const speed = velocity.length();
  176. If( speed.greaterThan( maxSpeed ), () => {
  177. velocity.assign( velocity.normalize().mul( maxSpeed ) );
  178. } );
  179. velocity.mulAssign( velocityDamping.oneMinus() );
  180. // position
  181. position.addAssign( velocity.mul( delta ) );
  182. // box loop
  183. const halfHalfExtent = boundHalfExtent.div( 2 ).toVar();
  184. position.assign( mod( position.add( halfHalfExtent ), boundHalfExtent ).sub( halfHalfExtent ) );
  185. } );
  186. updateCompute = update().compute( count );
  187. // nodes
  188. material.positionNode = positionBuffer.toAttribute();
  189. material.colorNode = Fn( () => {
  190. const velocity = velocityBuffer.toAttribute();
  191. const speed = velocity.length();
  192. const colorMix = speed.div( maxSpeed ).smoothstep( 0, 0.5 );
  193. const finalColor = mix( colorA, colorB, colorMix );
  194. return vec4( finalColor, 1 );
  195. } )();
  196. material.scaleNode = particleMassMultiplier.mul( scale );
  197. // mesh
  198. const geometry = new THREE.PlaneGeometry( 1, 1 );
  199. const mesh = new THREE.InstancedMesh( geometry, material, count );
  200. scene.add( mesh );
  201. // debug
  202. const gui = new GUI();
  203. gui.add( { attractorMassExponent: attractorMass.value.toString().length - 1 }, 'attractorMassExponent', 1, 10, 1 ).onChange( value => attractorMass.value = Number( `1e${value}` ) );
  204. gui.add( { particleGlobalMassExponent: particleGlobalMass.value.toString().length - 1 }, 'particleGlobalMassExponent', 1, 10, 1 ).onChange( value => particleGlobalMass.value = Number( `1e${value}` ) );
  205. gui.add( maxSpeed, 'value', 0, 10, 0.01 ).name( 'maxSpeed' );
  206. gui.add( velocityDamping, 'value', 0, 0.1, 0.001 ).name( 'velocityDamping' );
  207. gui.add( spinningStrength, 'value', 0, 10, 0.01 ).name( 'spinningStrength' );
  208. gui.add( scale, 'value', 0, 0.1, 0.001 ).name( 'scale' );
  209. gui.add( boundHalfExtent, 'value', 0, 20, 0.01 ).name( 'boundHalfExtent' );
  210. gui.addColor( { color: colorA.value.getHexString( THREE.SRGBColorSpace ) }, 'color' ).name( 'colorA' ).onChange( value => colorA.value.set( value ) );
  211. gui.addColor( { color: colorB.value.getHexString( THREE.SRGBColorSpace ) }, 'color' ).name( 'colorB' ).onChange( value => colorB.value.set( value ) );
  212. gui
  213. .add( { controlsMode: attractors[ 0 ].controls.mode }, 'controlsMode' )
  214. .options( [ 'translate', 'rotate', 'none' ] )
  215. .onChange( value => {
  216. for ( const attractor of attractors ) {
  217. if ( value === 'none' ) {
  218. attractor.controls.visible = false;
  219. attractor.controls.enabled = false;
  220. } else {
  221. attractor.controls.visible = true;
  222. attractor.controls.enabled = true;
  223. attractor.controls.mode = value;
  224. }
  225. }
  226. } );
  227. gui
  228. .add( { helperVisible: attractors[ 0 ].helper.visible }, 'helperVisible' )
  229. .onChange( value => {
  230. for ( const attractor of attractors )
  231. attractor.helper.visible = value;
  232. } );
  233. gui.add( { reset }, 'reset' );
  234. }
  235. function onWindowResize() {
  236. camera.aspect = window.innerWidth / window.innerHeight;
  237. camera.updateProjectionMatrix();
  238. renderer.setSize( window.innerWidth, window.innerHeight );
  239. }
  240. async function animate() {
  241. controls.update();
  242. renderer.compute( updateCompute );
  243. renderer.render( scene, camera );
  244. }
  245. </script>
  246. </body>
  247. </html>