1
0

webgpu_compute_particles_snow.html 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. <html lang="en">
  2. <head>
  3. <title>three.js - WebGPU - Compute Particles Snow</title>
  4. <meta charset="utf-8">
  5. <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
  6. <link type="text/css" rel="stylesheet" href="main.css">
  7. </head>
  8. <body>
  9. <div id="info">
  10. <a href="https://threejs.org" target="_blank" rel="noopener">three.js</a> WebGPU - Compute Snow - 100K Particles
  11. </div>
  12. <script type="importmap">
  13. {
  14. "imports": {
  15. "three": "../build/three.webgpu.js",
  16. "three/tsl": "../build/three.webgpu.js",
  17. "three/addons/": "./jsm/",
  18. "stats-gl": "https://cdn.jsdelivr.net/npm/stats-gl@2.2.8/dist/main.js"
  19. }
  20. }
  21. </script>
  22. <script type="module">
  23. import * as THREE from 'three';
  24. import { Fn, texture, vec3, pass, color, uint, viewportUV, positionWorld, positionLocal, timerLocal, vec2, hash, gaussianBlur, instanceIndex, storage, If } from 'three/tsl';
  25. import { TeapotGeometry } from 'three/addons/geometries/TeapotGeometry.js';
  26. import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
  27. import Stats from 'stats-gl';
  28. const maxParticleCount = 100000;
  29. let camera, scene, renderer;
  30. let controls, stats;
  31. let computeParticles;
  32. let postProcessing;
  33. let collisionCamera, collisionPosRT, collisionPosMaterial;
  34. init();
  35. async function init() {
  36. const { innerWidth, innerHeight } = window;
  37. camera = new THREE.PerspectiveCamera( 60, innerWidth / innerHeight, .1, 100 );
  38. camera.position.set( 20, 2, 20 );
  39. camera.layers.enable( 2 );
  40. camera.lookAt( 0, 40, 0 );
  41. scene = new THREE.Scene();
  42. scene.fog = new THREE.Fog( 0x0f3c37, 5, 40 );
  43. const dirLight = new THREE.DirectionalLight( 0xf9ff9b, 9 );
  44. dirLight.castShadow = true;
  45. dirLight.position.set( 10, 10, 0 );
  46. dirLight.castShadow = true;
  47. dirLight.shadow.camera.near = 1;
  48. dirLight.shadow.camera.far = 30;
  49. dirLight.shadow.camera.right = 30;
  50. dirLight.shadow.camera.left = - 30;
  51. dirLight.shadow.camera.top = 30;
  52. dirLight.shadow.camera.bottom = - 30;
  53. dirLight.shadow.mapSize.width = 2048;
  54. dirLight.shadow.mapSize.height = 2048;
  55. dirLight.shadow.bias = - 0.009;
  56. scene.add( dirLight );
  57. scene.add( new THREE.HemisphereLight( 0x0f3c37, 0x080d10, 100 ) );
  58. //
  59. collisionCamera = new THREE.OrthographicCamera( - 50, 50, 50, - 50, .1, 50 );
  60. collisionCamera.position.y = 50;
  61. collisionCamera.lookAt( 0, 0, 0 );
  62. collisionCamera.layers.enable( 1 );
  63. collisionPosRT = new THREE.RenderTarget( 1024, 1024 );
  64. collisionPosRT.texture.type = THREE.HalfFloatType;
  65. collisionPosRT.texture.magFilter = THREE.NearestFilter;
  66. collisionPosRT.texture.minFilter = THREE.NearestFilter;
  67. collisionPosMaterial = new THREE.MeshBasicNodeMaterial();
  68. collisionPosMaterial.fog = false;
  69. collisionPosMaterial.toneMapped = false;
  70. collisionPosMaterial.colorNode = positionWorld.y;
  71. //
  72. const createBuffer = ( type = 'vec3' ) => storage( new THREE.StorageInstancedBufferAttribute( maxParticleCount, type === 'vec4' ? 4 : 3 ), type, maxParticleCount );
  73. const positionBuffer = createBuffer();
  74. const scaleBuffer = createBuffer();
  75. const staticPositionBuffer = createBuffer();
  76. const dataBuffer = createBuffer( 'vec4' );
  77. // compute
  78. const timer = timerLocal();
  79. const randUint = () => uint( Math.random() * 0xFFFFFF );
  80. const computeInit = Fn( () => {
  81. const position = positionBuffer.element( instanceIndex );
  82. const scale = scaleBuffer.element( instanceIndex );
  83. const particleData = dataBuffer.element( instanceIndex );
  84. const randX = hash( instanceIndex );
  85. const randY = hash( instanceIndex.add( randUint() ) );
  86. const randZ = hash( instanceIndex.add( randUint() ) );
  87. position.x = randX.mul( 100 ).add( - 50 );
  88. position.y = randY.mul( 500 ).add( 3 );
  89. position.z = randZ.mul( 100 ).add( - 50 );
  90. scale.xyz = hash( instanceIndex.add( Math.random() ) ).mul( .8 ).add( .2 );
  91. staticPositionBuffer.element( instanceIndex ).assign( vec3( 1000, 10000, 1000 ) );
  92. particleData.y = randY.mul( - .1 ).add( - .02 );
  93. particleData.x = position.x;
  94. particleData.z = position.z;
  95. particleData.w = randX;
  96. } )().compute( maxParticleCount );
  97. //
  98. const surfaceOffset = .2;
  99. const speed = .4;
  100. const computeUpdate = Fn( () => {
  101. const getCoord = ( pos ) => pos.add( 50 ).div( 100 );
  102. const position = positionBuffer.element( instanceIndex );
  103. const scale = scaleBuffer.element( instanceIndex );
  104. const particleData = dataBuffer.element( instanceIndex );
  105. const velocity = particleData.y;
  106. const random = particleData.w;
  107. const rippleOnSurface = texture( collisionPosRT.texture, getCoord( position.xz ) );
  108. const rippleFloorArea = rippleOnSurface.y.add( scale.x.mul( surfaceOffset ) );
  109. If( position.y.greaterThan( rippleFloorArea ), () => {
  110. position.x = particleData.x.add( timer.mul( random.mul( random ) ).mul( speed ).sin().mul( 3 ) );
  111. position.z = particleData.z.add( timer.mul( random ).mul( speed ).cos().mul( random.mul( 10 ) ) );
  112. position.y = position.y.add( velocity );
  113. } ).Else( () => {
  114. staticPositionBuffer.element( instanceIndex ).assign( position );
  115. } );
  116. } );
  117. computeParticles = computeUpdate().compute( maxParticleCount );
  118. // rain
  119. const geometry = new THREE.SphereGeometry( surfaceOffset, 5, 5 );
  120. function particle( staticParticles ) {
  121. const posBuffer = staticParticles ? staticPositionBuffer : positionBuffer;
  122. const layer = staticParticles ? 1 : 2;
  123. const staticMaterial = new THREE.MeshStandardNodeMaterial( {
  124. color: 0xeeeeee,
  125. roughness: .9,
  126. metalness: 0
  127. } );
  128. staticMaterial.positionNode = positionLocal.mul( scaleBuffer.toAttribute() ).add( posBuffer.toAttribute() );
  129. const rainParticles = new THREE.Mesh( geometry, staticMaterial );
  130. rainParticles.count = maxParticleCount;
  131. rainParticles.castShadow = true;
  132. rainParticles.layers.disableAll();
  133. rainParticles.layers.enable( layer );
  134. return rainParticles;
  135. }
  136. const dynamicParticles = particle();
  137. const staticParticles = particle( true );
  138. scene.add( dynamicParticles );
  139. scene.add( staticParticles );
  140. // floor geometry
  141. const floorGeometry = new THREE.PlaneGeometry( 100, 100 );
  142. floorGeometry.rotateX( - Math.PI / 2 );
  143. const plane = new THREE.Mesh( floorGeometry, new THREE.MeshStandardMaterial( {
  144. color: 0x0c1e1e,
  145. roughness: .5,
  146. metalness: 0,
  147. transparent: true
  148. } ) );
  149. plane.material.opacityNode = positionLocal.xz.mul( .05 ).distance( 0 ).saturate().oneMinus();
  150. scene.add( plane );
  151. // tree
  152. function tree( count = 8 ) {
  153. const coneMaterial = new THREE.MeshStandardNodeMaterial( {
  154. color: 0x0d492c,
  155. roughness: .6,
  156. metalness: 0
  157. } );
  158. const object = new THREE.Group();
  159. for ( let i = 0; i < count; i ++ ) {
  160. const radius = 1 + i;
  161. const coneGeometry = new THREE.ConeGeometry( radius * 0.95, radius * 1.25, 32 );
  162. const cone = new THREE.Mesh( coneGeometry, coneMaterial );
  163. cone.castShadow = true;
  164. cone.position.y = ( ( count - i ) * 1.5 ) + ( count * .6 );
  165. object.add( cone );
  166. }
  167. const geometry = new THREE.CylinderGeometry( 1, 1, count, 32 );
  168. const cone = new THREE.Mesh( geometry, coneMaterial );
  169. cone.position.y = count / 2;
  170. object.add( cone );
  171. return object;
  172. }
  173. const teapotTree = new THREE.Mesh( new TeapotGeometry( .5, 18 ), new THREE.MeshBasicNodeMaterial( {
  174. color: 0xfcfb9e
  175. } ) );
  176. teapotTree.position.y = 18;
  177. scene.add( tree() );
  178. scene.add( teapotTree );
  179. //
  180. scene.backgroundNode = viewportUV.distance( .5 ).mul( 2 ).mix( color( 0x0f4140 ), color( 0x060a0d ) );
  181. //
  182. renderer = new THREE.WebGPURenderer( { antialias: true } );
  183. renderer.toneMapping = THREE.ACESFilmicToneMapping;
  184. renderer.setPixelRatio( window.devicePixelRatio );
  185. renderer.setSize( window.innerWidth, window.innerHeight );
  186. renderer.setAnimationLoop( animate );
  187. document.body.appendChild( renderer.domElement );
  188. stats = new Stats( {
  189. precision: 3,
  190. horizontal: false
  191. } );
  192. stats.init( renderer );
  193. document.body.appendChild( stats.dom );
  194. //
  195. controls = new OrbitControls( camera, renderer.domElement );
  196. controls.target.set( 0, 10, 0 );
  197. controls.minDistance = 25;
  198. controls.maxDistance = 35;
  199. controls.maxPolarAngle = Math.PI / 1.7;
  200. controls.autoRotate = true;
  201. controls.autoRotateSpeed = - 0.7;
  202. controls.update();
  203. // post processing
  204. const scenePass = pass( scene, camera );
  205. const scenePassColor = scenePass.getTextureNode();
  206. const vignet = viewportUV.distance( .5 ).mul( 1.35 ).clamp().oneMinus();
  207. const teapotTreePass = pass( teapotTree, camera ).getTextureNode();
  208. const teapotTreePassBlurred = gaussianBlur( teapotTreePass, vec2( 1 ), 3 );
  209. teapotTreePassBlurred.resolution = new THREE.Vector2( .2, .2 );
  210. const scenePassColorBlurred = gaussianBlur( scenePassColor );
  211. scenePassColorBlurred.resolution = new THREE.Vector2( .5, .5 );
  212. scenePassColorBlurred.directionNode = vec2( 1 );
  213. // compose
  214. let totalPass = scenePass;
  215. totalPass = totalPass.add( scenePassColorBlurred.mul( .1 ) );
  216. totalPass = totalPass.mul( vignet );
  217. totalPass = totalPass.add( teapotTreePass.mul( 10 ).add( teapotTreePassBlurred ) );
  218. postProcessing = new THREE.PostProcessing( renderer );
  219. postProcessing.outputNode = totalPass;
  220. //
  221. await renderer.computeAsync( computeInit );
  222. //
  223. window.addEventListener( 'resize', onWindowResize );
  224. }
  225. function onWindowResize() {
  226. const { innerWidth, innerHeight } = window;
  227. camera.aspect = innerWidth / innerHeight;
  228. camera.updateProjectionMatrix();
  229. renderer.setSize( innerWidth, innerHeight );
  230. }
  231. async function animate() {
  232. controls.update();
  233. // position
  234. scene.overrideMaterial = collisionPosMaterial;
  235. renderer.setRenderTarget( collisionPosRT );
  236. await renderer.renderAsync( scene, collisionCamera );
  237. // compute
  238. await renderer.computeAsync( computeParticles );
  239. // result
  240. scene.overrideMaterial = null;
  241. renderer.setRenderTarget( null );
  242. await postProcessing.renderAsync();
  243. stats.update();
  244. }
  245. </script>
  246. </body>
  247. </html>