webgpu_tsl_compute_attractors_particles.html 12 KB

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