webgpu_tsl_compute_attractors_particles.html 12 KB

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