webgpu_tsl_vfx_linkedparticles.html 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>three.js webgpu - VFX Linked 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 webgpu</a> - VFX Linked particles
  12. <br>
  13. Based on <a href="https://github.com/ULuIQ12/webgpu-tsl-linkedparticles" target="_blank" rel="noopener">this experiment</a> by Christophe Choffel
  14. </div>
  15. <script type="importmap">
  16. {
  17. "imports": {
  18. "three": "../build/three.webgpu.js",
  19. "three/tsl": "../build/three.webgpu.js",
  20. "three/addons/": "./jsm/"
  21. }
  22. }
  23. </script>
  24. <script type="module">
  25. import * as THREE from 'three';
  26. import { atan2, cos, float, max, min, mix, PI, PI2, sin, vec2, vec3, bloom, color, Fn, hash, hue, If, instanceIndex, Loop, mx_fractal_noise_float, mx_fractal_noise_vec3, pass, pcurve, storage, timerDelta, timerGlobal, uv, uniform } from 'three/tsl';
  27. import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
  28. import { GUI } from 'three/addons/libs/lil-gui.module.min.js';
  29. import WebGPU from 'three/addons/capabilities/WebGPU.js';
  30. let camera, scene, renderer, postProcessing, controls, clock, light;
  31. let updateParticles, spawnParticles; // TSL compute nodes
  32. let getInstanceColor; // TSL function
  33. const screenPointer = new THREE.Vector2();
  34. const scenePointer = new THREE.Vector3();
  35. const raycastPlane = new THREE.Plane( new THREE.Vector3( 0, 0, 1 ), 0 );
  36. const raycaster = new THREE.Raycaster();
  37. const nbParticles = Math.pow( 2, 13 );
  38. const timeScale = uniform( 1.0 );
  39. const particleLifetime = uniform( 0.5 );
  40. const particleSize = uniform( 1.0 );
  41. const linksWidth = uniform( 0.005 );
  42. const colorOffset = uniform( 0.0 );
  43. const colorVariance = uniform( 2.0 );
  44. const colorRotationSpeed = uniform( 1.0 );
  45. const spawnIndex = uniform( 0 );
  46. const nbToSpawn = uniform( 5 );
  47. const spawnPosition = uniform( vec3( 0.0 ) );
  48. const previousSpawnPosition = uniform( vec3( 0.0 ) );
  49. const turbFrequency = uniform( 0.5 );
  50. const turbAmplitude = uniform( 0.5 );
  51. const turbOctaves = uniform( 2 );
  52. const turbLacunarity = uniform( 2.0 );
  53. const turbGain = uniform( 0.5 );
  54. const turbFriction = uniform( 0.01 );
  55. init();
  56. function init() {
  57. if ( WebGPU.isAvailable() === false ) {
  58. document.body.appendChild( WebGPU.getErrorMessage() );
  59. throw new Error( 'No WebGPU support' );
  60. }
  61. camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 0.1, 200 );
  62. camera.position.set( 0, 0, 10 );
  63. scene = new THREE.Scene();
  64. clock = new THREE.Clock();
  65. // renderer
  66. renderer = new THREE.WebGPURenderer( { antialias: true } );
  67. renderer.setClearColor( 0x14171a );
  68. renderer.setPixelRatio( window.devicePixelRatio );
  69. renderer.setSize( window.innerWidth, window.innerHeight );
  70. renderer.setAnimationLoop( animate );
  71. document.body.appendChild( renderer.domElement );
  72. // TSL function
  73. // current color from index
  74. getInstanceColor = /*#__PURE__*/ Fn( ( [ i ] ) => {
  75. return hue( color( 0x0000ff ), colorOffset.add( mx_fractal_noise_float( i.toFloat().mul( .1 ), 2, 2.0, 0.5, colorVariance ) ) );
  76. } );
  77. // Particles
  78. // storage buffers
  79. const particlePositions = storage( new THREE.StorageInstancedBufferAttribute( nbParticles, 4 ), 'vec4', nbParticles );
  80. const particleVelocities = storage( new THREE.StorageInstancedBufferAttribute( nbParticles, 4 ), 'vec4', nbParticles );
  81. // init particles buffers
  82. renderer.compute( /*#__PURE__*/ Fn( () => {
  83. particlePositions.element( instanceIndex ).xyz.assign( vec3( 10000.0 ) );
  84. particlePositions.element( instanceIndex ).w.assign( vec3( - 1.0 ) ); // life is stored in w component; x<0 means dead
  85. } )().compute( nbParticles ) );
  86. // particles output
  87. const particleQuadSize = 0.05;
  88. const particleGeom = new THREE.PlaneGeometry( particleQuadSize, particleQuadSize );
  89. const particleMaterial = new THREE.SpriteNodeMaterial();
  90. particleMaterial.transparent = true;
  91. particleMaterial.blending = THREE.AdditiveBlending;
  92. particleMaterial.depthWrite = false;
  93. particleMaterial.positionNode = particlePositions.toAttribute();
  94. particleMaterial.scaleNode = vec2( particleSize );
  95. particleMaterial.rotationNode = atan2( particleVelocities.toAttribute().y, particleVelocities.toAttribute().x );
  96. particleMaterial.colorNode = /*#__PURE__*/ Fn( () => {
  97. const life = particlePositions.toAttribute().w;
  98. const modLife = pcurve( life.oneMinus(), 8.0, 1.0 );
  99. const pulse = pcurve(
  100. sin( hash( instanceIndex ).mul( PI2 ).add( timerGlobal( 0.5 ).mul( PI2 ) ) ).mul( 0.5 ).add( 0.5 ),
  101. 0.25,
  102. 0.25
  103. ).mul( 10.0 ).add( 1.0 );
  104. return getInstanceColor( instanceIndex ).mul( pulse.mul( modLife ) );
  105. } )();
  106. particleMaterial.opacityNode = /*#__PURE__*/ Fn( () => {
  107. const circle = uv().xy.sub( 0.5 ).length().step( 0.5 );
  108. const life = particlePositions.toAttribute().w;
  109. return circle.mul( life );
  110. } )();
  111. const particleMesh = new THREE.InstancedMesh( particleGeom, particleMaterial, nbParticles );
  112. particleMesh.instanceMatrix.setUsage( THREE.DynamicDrawUsage );
  113. particleMesh.frustumCulled = false;
  114. scene.add( particleMesh );
  115. // Links between particles
  116. // first, we define the indices for the links, 2 quads per particle, the indexation is fixed
  117. const linksIndices = [];
  118. for ( let i = 0; i < nbParticles; i ++ ) {
  119. const baseIndex = i * 8;
  120. for ( let j = 0; j < 2; j ++ ) {
  121. const offset = baseIndex + j * 4;
  122. linksIndices.push( offset, offset + 1, offset + 2, offset, offset + 2, offset + 3 );
  123. }
  124. }
  125. // storage buffers attributes for the links
  126. const nbVertices = nbParticles * 8;
  127. const linksVerticesSBA = new THREE.StorageBufferAttribute( nbVertices, 4 );
  128. const linksColorsSBA = new THREE.StorageBufferAttribute( nbVertices, 4 );
  129. // links output
  130. const linksGeom = new THREE.BufferGeometry();
  131. linksGeom.setAttribute( 'position', linksVerticesSBA );
  132. linksGeom.setAttribute( 'color', linksColorsSBA );
  133. linksGeom.setIndex( linksIndices );
  134. const linksMaterial = new THREE.MeshBasicNodeMaterial();
  135. linksMaterial.vertexColors = true;
  136. linksMaterial.side = THREE.DoubleSide;
  137. linksMaterial.transparent = true;
  138. linksMaterial.depthWrite = false;
  139. linksMaterial.depthTest = false;
  140. linksMaterial.blending = THREE.AdditiveBlending;
  141. linksMaterial.opacityNode = storage( linksColorsSBA, 'vec4', linksColorsSBA.count ).toAttribute().w;
  142. const linksMesh = new THREE.Mesh( linksGeom, linksMaterial );
  143. linksMesh.frustumCulled = false;
  144. scene.add( linksMesh );
  145. // compute nodes
  146. updateParticles = /*#__PURE__*/ Fn( () => {
  147. const position = particlePositions.element( instanceIndex ).xyz;
  148. const life = particlePositions.element( instanceIndex ).w;
  149. const velocity = particleVelocities.element( instanceIndex ).xyz;
  150. const dt = timerDelta( 0.1 ).mul( timeScale );
  151. If( life.greaterThan( 0.0 ), () => {
  152. // first we update the particles positions and velocities
  153. // velocity comes from a turbulence field, and is multiplied by the particle lifetime so that it slows down over time
  154. const localVel = mx_fractal_noise_vec3( position.mul( turbFrequency ), turbOctaves, turbLacunarity, turbGain, turbAmplitude ).mul( life.add( .01 ) );
  155. velocity.addAssign( localVel );
  156. velocity.mulAssign( turbFriction.oneMinus() );
  157. position.addAssign( velocity.mul( dt ) );
  158. // then we decrease the lifetime
  159. life.subAssign( dt.mul( particleLifetime.reciprocal() ) );
  160. // then we find the two closest particles and set a quad to each of them
  161. const closestDist1 = float( 10000.0 ).toVar();
  162. const closestPos1 = vec3( 0.0 ).toVar();
  163. const closestLife1 = float( 0.0 ).toVar();
  164. const closestDist2 = float( 10000.0 ).toVar();
  165. const closestPos2 = vec3( 0.0 ).toVar();
  166. const closestLife2 = float( 0.0 ).toVar();
  167. Loop( nbParticles, ( { i } ) => {
  168. const otherPart = particlePositions.element( i );
  169. If( i.notEqual( instanceIndex ).and( otherPart.w.greaterThan( 0.0 ) ), () => { // if not self and other particle is alive
  170. const otherPosition = otherPart.xyz;
  171. const dist = position.sub( otherPosition ).lengthSq();
  172. const moreThanZero = dist.greaterThan( 0.0 );
  173. If( dist.lessThan( closestDist1 ).and( moreThanZero ), () => {
  174. closestDist1.assign( dist );
  175. closestPos1.assign( otherPosition.xyz );
  176. closestLife1.assign( otherPart.w );
  177. } ).ElseIf( dist.lessThan( closestDist2 ).and( moreThanZero ), () => {
  178. closestDist2.assign( dist );
  179. closestPos2.assign( otherPosition.xyz );
  180. closestLife2.assign( otherPart.w );
  181. } );
  182. } );
  183. } );
  184. // then we update the links correspondingly
  185. const linksPositions = storage( linksVerticesSBA, 'vec4', linksVerticesSBA.count );
  186. const linksColors = storage( linksColorsSBA, 'vec4', linksColorsSBA.count );
  187. const firstLinkIndex = instanceIndex.mul( 8 );
  188. const secondLinkIndex = firstLinkIndex.add( 4 );
  189. // positions link 1
  190. linksPositions.element( firstLinkIndex ).xyz.assign( position );
  191. linksPositions.element( firstLinkIndex ).y.addAssign( linksWidth );
  192. linksPositions.element( firstLinkIndex.add( 1 ) ).xyz.assign( position );
  193. linksPositions.element( firstLinkIndex.add( 1 ) ).y.addAssign( linksWidth.negate() );
  194. linksPositions.element( firstLinkIndex.add( 2 ) ).xyz.assign( closestPos1 );
  195. linksPositions.element( firstLinkIndex.add( 2 ) ).y.addAssign( linksWidth.negate() );
  196. linksPositions.element( firstLinkIndex.add( 3 ) ).xyz.assign( closestPos1 );
  197. linksPositions.element( firstLinkIndex.add( 3 ) ).y.addAssign( linksWidth );
  198. // positions link 2
  199. linksPositions.element( secondLinkIndex ).xyz.assign( position );
  200. linksPositions.element( secondLinkIndex ).y.addAssign( linksWidth );
  201. linksPositions.element( secondLinkIndex.add( 1 ) ).xyz.assign( position );
  202. linksPositions.element( secondLinkIndex.add( 1 ) ).y.addAssign( linksWidth.negate() );
  203. linksPositions.element( secondLinkIndex.add( 2 ) ).xyz.assign( closestPos2 );
  204. linksPositions.element( secondLinkIndex.add( 2 ) ).y.addAssign( linksWidth.negate() );
  205. linksPositions.element( secondLinkIndex.add( 3 ) ).xyz.assign( closestPos2 );
  206. linksPositions.element( secondLinkIndex.add( 3 ) ).y.addAssign( linksWidth );
  207. // colors are the same for all vertices of both quads
  208. const linkColor = getInstanceColor( instanceIndex );
  209. // store the minimum lifetime of the closest particles in the w component of colors
  210. const l1 = max( 0.0, min( closestLife1, life ) ).pow( 0.8 ); // pow is here to apply a slight curve to the opacity
  211. const l2 = max( 0.0, min( closestLife2, life ) ).pow( 0.8 );
  212. Loop( 4, ( { i } ) => {
  213. linksColors.element( firstLinkIndex.add( i ) ).xyz.assign( linkColor );
  214. linksColors.element( firstLinkIndex.add( i ) ).w.assign( l1 );
  215. linksColors.element( secondLinkIndex.add( i ) ).xyz.assign( linkColor );
  216. linksColors.element( secondLinkIndex.add( i ) ).w.assign( l2 );
  217. } );
  218. } );
  219. } )().compute( nbParticles );
  220. spawnParticles = /*#__PURE__*/ Fn( () => {
  221. const particleIndex = spawnIndex.add( instanceIndex ).mod( nbParticles ).toInt();
  222. const position = particlePositions.element( particleIndex ).xyz;
  223. const life = particlePositions.element( particleIndex ).w;
  224. const velocity = particleVelocities.element( particleIndex ).xyz;
  225. life.assign( 1.0 ); // sets it alive
  226. // random spherical direction
  227. const rRange = float( 0.01 );
  228. const rTheta = hash( particleIndex ).mul( PI2 );
  229. const rPhi = hash( particleIndex.add( 1 ) ).mul( PI );
  230. const rx = sin( rTheta ).mul( cos( rPhi ) );
  231. const ry = sin( rTheta ).mul( sin( rPhi ) );
  232. const rz = cos( rTheta );
  233. const rDir = vec3( rx, ry, rz );
  234. // position is interpolated between the previous cursor position and the current one over the number of particles spawned
  235. const pos = mix( previousSpawnPosition, spawnPosition, instanceIndex.toFloat().div( nbToSpawn.sub( 1 ).toFloat() ).clamp() );
  236. position.assign( pos.add( rDir.mul( rRange ) ) );
  237. // start in that direction
  238. velocity.assign( rDir.mul( 5.0 ) );
  239. } )().compute( nbToSpawn.value );
  240. // background , an inverted icosahedron
  241. const backgroundGeom = new THREE.IcosahedronGeometry( 100, 5 ).applyMatrix4( new THREE.Matrix4().makeScale( - 1, 1, 1 ) );
  242. const backgroundMaterial = new THREE.MeshStandardNodeMaterial();
  243. backgroundMaterial.roughness = 0.4;
  244. backgroundMaterial.metalness = 0.9;
  245. backgroundMaterial.flatShading = true;
  246. backgroundMaterial.colorNode = color( 0x0 );
  247. const backgroundMesh = new THREE.Mesh( backgroundGeom, backgroundMaterial );
  248. scene.add( backgroundMesh );
  249. // light for the background
  250. light = new THREE.PointLight( 0xffffff, 3000 );
  251. scene.add( light );
  252. // post processing
  253. postProcessing = new THREE.PostProcessing( renderer );
  254. const scenePass = pass( scene, camera );
  255. const scenePassColor = scenePass.getTextureNode( 'output' );
  256. const bloomPass = bloom( scenePassColor, 0.75, 0.1, 0.5 );
  257. postProcessing.outputNode = scenePassColor.add( bloomPass );
  258. // controls
  259. controls = new OrbitControls( camera, renderer.domElement );
  260. controls.enableDamping = true;
  261. controls.autoRotate = true;
  262. controls.maxDistance = 75;
  263. window.addEventListener( 'resize', onWindowResize );
  264. // pointer handling
  265. window.addEventListener( 'pointermove', onPointerMove );
  266. // GUI
  267. const gui = new GUI();
  268. gui.add( controls, 'autoRotate' ).name( 'Auto Rotate' );
  269. gui.add( controls, 'autoRotateSpeed', - 10.0, 10.0, 0.01 ).name( 'Auto Rotate Speed' );
  270. const partFolder = gui.addFolder( 'Particles' );
  271. partFolder.add( timeScale, 'value', 0.0, 4.0, 0.01 ).name( 'timeScale' );
  272. partFolder.add( nbToSpawn, 'value', 1, 100, 1 ).name( 'Spawn rate' );
  273. partFolder.add( particleSize, 'value', 0.01, 3.0, 0.01 ).name( 'Size' );
  274. partFolder.add( particleLifetime, 'value', 0.01, 2.0, 0.01 ).name( 'Lifetime' );
  275. partFolder.add( linksWidth, 'value', 0.001, 0.1, 0.001 ).name( 'Links width' );
  276. partFolder.add( colorVariance, 'value', 0.0, 10.0, 0.01 ).name( 'Color variance' );
  277. partFolder.add( colorRotationSpeed, 'value', 0.0, 5.0, 0.01 ).name( 'Color rotation speed' );
  278. const turbFolder = gui.addFolder( 'Turbulence' );
  279. turbFolder.add( turbFriction, 'value', 0.0, 0.3, 0.01 ).name( 'Friction' );
  280. turbFolder.add( turbFrequency, 'value', 0.0, 1.0, 0.01 ).name( 'Frequency' );
  281. turbFolder.add( turbAmplitude, 'value', 0.0, 10.0, 0.01 ).name( 'Amplitude' );
  282. turbFolder.add( turbOctaves, 'value', 1, 9, 1 ).name( 'Octaves' );
  283. turbFolder.add( turbLacunarity, 'value', 1.0, 5.0, 0.01 ).name( 'Lacunarity' );
  284. turbFolder.add( turbGain, 'value', 0.0, 1.0, 0.01 ).name( 'Gain' );
  285. const bloomFolder = gui.addFolder( 'bloom' );
  286. bloomFolder.add( bloomPass.threshold, 'value', 0, 2.0, 0.01 ).name( 'Threshold' );
  287. bloomFolder.add( bloomPass.strength, 'value', 0, 10, 0.01 ).name( 'Strength' );
  288. bloomFolder.add( bloomPass.radius, 'value', 0, 1, 0.01 ).name( 'Radius' );
  289. }
  290. function onWindowResize( e ) {
  291. camera.aspect = window.innerWidth / window.innerHeight;
  292. camera.updateProjectionMatrix();
  293. renderer.setSize( window.innerWidth, window.innerHeight );
  294. }
  295. function onPointerMove( e ) {
  296. screenPointer.x = ( e.clientX / window.innerWidth ) * 2 - 1;
  297. screenPointer.y = - ( e.clientY / window.innerHeight ) * 2 + 1;
  298. }
  299. function updatePointer() {
  300. raycaster.setFromCamera( screenPointer, camera );
  301. raycaster.ray.intersectPlane( raycastPlane, scenePointer );
  302. }
  303. async function animate() {
  304. // compute particles
  305. await renderer.computeAsync( updateParticles );
  306. await renderer.computeAsync( spawnParticles );
  307. // update particle index for next spawn
  308. spawnIndex.value = ( spawnIndex.value + nbToSpawn.value ) % nbParticles;
  309. // update raycast plane to face camera
  310. raycastPlane.normal.applyEuler( camera.rotation );
  311. updatePointer();
  312. // lerping spawn position
  313. previousSpawnPosition.value.copy( spawnPosition.value );
  314. spawnPosition.value.lerp( scenePointer, 0.1 );
  315. // rotating colors
  316. colorOffset.value += clock.getDelta() * colorRotationSpeed.value * timeScale.value;
  317. const elapsedTime = clock.getElapsedTime();
  318. light.position.set(
  319. Math.sin( elapsedTime * 0.5 ) * 30,
  320. Math.cos( elapsedTime * 0.3 ) * 30,
  321. Math.sin( elapsedTime * 0.2 ) * 30,
  322. );
  323. controls.update();
  324. postProcessing.renderAsync();
  325. }
  326. </script>
  327. </body>
  328. </html>