webgpu_tsl_vfx_linkedparticles.html 17 KB

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