webgpu_tsl_vfx_linkedparticles.html 17 KB

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