webgpu_tsl_vfx_linkedparticles.html 17 KB

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