webgpu_compute_particles_rain.html 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. <html lang="en">
  2. <head>
  3. <title>three.js webgpu - compute particles rain</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="example.css">
  7. </head>
  8. <body>
  9. <div id="info">
  10. <a href="https://threejs.org/" target="_blank" rel="noopener" class="logo-link"></a>
  11. <div class="title-wrapper">
  12. <a href="https://threejs.org/" target="_blank" rel="noopener">three.js</a><span>Compute Rain</span>
  13. </div>
  14. <small>Compatible with native lights and shadows using post-processing pass.</small>
  15. </div>
  16. <script type="importmap">
  17. {
  18. "imports": {
  19. "three": "../build/three.webgpu.js",
  20. "three/webgpu": "../build/three.webgpu.js",
  21. "three/tsl": "../build/three.tsl.js",
  22. "three/addons/": "./jsm/"
  23. }
  24. }
  25. </script>
  26. <script type="module">
  27. import * as THREE from 'three/webgpu';
  28. import { Fn, texture, uv, uint, instancedArray, positionWorld, billboarding, time, hash, deltaTime, vec2, instanceIndex, positionGeometry, If } from 'three/tsl';
  29. import { Inspector } from 'three/addons/inspector/Inspector.js';
  30. import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
  31. import * as BufferGeometryUtils from 'three/addons/utils/BufferGeometryUtils.js';
  32. const maxParticleCount = 50000;
  33. const instanceCount = maxParticleCount / 2;
  34. let camera, scene, renderer;
  35. let controls;
  36. let computeParticles;
  37. let monkey;
  38. let timer;
  39. let collisionBox, collisionCamera, collisionPosRT, collisionPosMaterial;
  40. let collisionBoxPos, collisionBoxPosUI;
  41. init();
  42. async function init() {
  43. const { innerWidth, innerHeight } = window;
  44. camera = new THREE.PerspectiveCamera( 60, innerWidth / innerHeight, .1, 110 );
  45. camera.position.set( 40, 8, 0 );
  46. camera.lookAt( 0, 0, 0 );
  47. scene = new THREE.Scene();
  48. scene.background = new THREE.Color( 0x000000 );
  49. const dirLight = new THREE.DirectionalLight( 0xffffff, .5 );
  50. dirLight.position.set( 3, 17, 17 );
  51. scene.add( dirLight );
  52. scene.add( new THREE.AmbientLight( 0x111111 ) );
  53. //
  54. collisionCamera = new THREE.OrthographicCamera( - 50, 50, 50, - 50, .1, 50 );
  55. collisionCamera.position.y = 50;
  56. collisionCamera.lookAt( 0, 0, 0 );
  57. collisionCamera.layers.disableAll();
  58. collisionCamera.layers.enable( 1 );
  59. collisionPosRT = new THREE.RenderTarget( 1024, 1024 );
  60. collisionPosRT.texture.type = THREE.HalfFloatType;
  61. collisionPosRT.texture.magFilter = THREE.NearestFilter;
  62. collisionPosRT.texture.minFilter = THREE.NearestFilter;
  63. collisionPosRT.texture.generateMipmaps = false;
  64. collisionPosMaterial = new THREE.MeshBasicNodeMaterial();
  65. collisionPosMaterial.colorNode = positionWorld;
  66. //
  67. const positionBuffer = instancedArray( maxParticleCount, 'vec3' );
  68. const velocityBuffer = instancedArray( maxParticleCount, 'vec3' );
  69. const ripplePositionBuffer = instancedArray( maxParticleCount, 'vec3' );
  70. const rippleTimeBuffer = instancedArray( maxParticleCount, 'vec3' );
  71. // compute
  72. const randUint = () => uint( Math.random() * 0xFFFFFF );
  73. const computeInit = Fn( () => {
  74. const position = positionBuffer.element( instanceIndex );
  75. const velocity = velocityBuffer.element( instanceIndex );
  76. const rippleTime = rippleTimeBuffer.element( instanceIndex );
  77. const randX = hash( instanceIndex );
  78. const randY = hash( instanceIndex.add( randUint() ) );
  79. const randZ = hash( instanceIndex.add( randUint() ) );
  80. position.x = randX.mul( 100 ).add( - 50 );
  81. position.y = randY.mul( 25 );
  82. position.z = randZ.mul( 100 ).add( - 50 );
  83. velocity.y = randX.mul( - .04 ).add( - .2 );
  84. rippleTime.x = 1000;
  85. } )().compute( maxParticleCount );
  86. //
  87. const computeUpdate = Fn( () => {
  88. const getCoord = ( pos ) => pos.add( 50 ).div( 100 );
  89. const position = positionBuffer.element( instanceIndex );
  90. const velocity = velocityBuffer.element( instanceIndex );
  91. const ripplePosition = ripplePositionBuffer.element( instanceIndex );
  92. const rippleTime = rippleTimeBuffer.element( instanceIndex );
  93. position.addAssign( velocity );
  94. rippleTime.x = rippleTime.x.add( deltaTime.mul( 4 ) );
  95. //
  96. const collisionArea = texture( collisionPosRT.texture, getCoord( position.xz ) );
  97. const surfaceOffset = .05;
  98. const floorPosition = collisionArea.y.add( surfaceOffset );
  99. // floor
  100. const ripplePivotOffsetY = - .9;
  101. If( position.y.add( ripplePivotOffsetY ).lessThan( floorPosition ), () => {
  102. position.y = 25;
  103. ripplePosition.xz = position.xz;
  104. ripplePosition.y = floorPosition;
  105. // reset hit time: x = time
  106. rippleTime.x = 1;
  107. // next drops will not fall in the same place
  108. position.x = hash( instanceIndex.add( time ) ).mul( 100 ).add( - 50 );
  109. position.z = hash( instanceIndex.add( time.add( randUint() ) ) ).mul( 100 ).add( - 50 );
  110. } );
  111. const rippleOnSurface = texture( collisionPosRT.texture, getCoord( ripplePosition.xz ) );
  112. const rippleFloorArea = rippleOnSurface.y.add( surfaceOffset );
  113. If( ripplePosition.y.greaterThan( rippleFloorArea ), () => {
  114. rippleTime.x = 1000;
  115. } );
  116. } );
  117. computeParticles = computeUpdate().compute( maxParticleCount ).setName( 'Particles' );
  118. // rain
  119. const rainMaterial = new THREE.MeshBasicNodeMaterial();
  120. rainMaterial.colorNode = uv().distance( vec2( .5, 0 ) ).oneMinus().mul( 3 ).exp().mul( .1 );
  121. rainMaterial.vertexNode = billboarding( { position: positionBuffer.toAttribute() } );
  122. rainMaterial.opacity = .2;
  123. rainMaterial.side = THREE.DoubleSide;
  124. rainMaterial.forceSinglePass = true;
  125. rainMaterial.depthWrite = false;
  126. rainMaterial.depthTest = true;
  127. rainMaterial.transparent = true;
  128. const rainParticles = new THREE.Mesh( new THREE.PlaneGeometry( .1, 2 ), rainMaterial );
  129. rainParticles.count = instanceCount;
  130. scene.add( rainParticles );
  131. // ripple
  132. const rippleTime = rippleTimeBuffer.element( instanceIndex ).x;
  133. const rippleEffect = Fn( () => {
  134. const center = uv().add( vec2( - .5 ) ).length().mul( 7 );
  135. const distance = rippleTime.sub( center );
  136. return distance.min( 1 ).sub( distance.max( 1 ).sub( 1 ) );
  137. } );
  138. const rippleMaterial = new THREE.MeshBasicNodeMaterial();
  139. rippleMaterial.colorNode = rippleEffect();
  140. rippleMaterial.positionNode = positionGeometry.add( ripplePositionBuffer.toAttribute() );
  141. rippleMaterial.opacityNode = rippleTime.mul( .3 ).oneMinus().max( 0 ).mul( .5 );
  142. rippleMaterial.side = THREE.DoubleSide;
  143. rippleMaterial.forceSinglePass = true;
  144. rippleMaterial.depthWrite = false;
  145. rippleMaterial.depthTest = true;
  146. rippleMaterial.transparent = true;
  147. // ripple geometry
  148. const surfaceRippleGeometry = new THREE.PlaneGeometry( 2.5, 2.5 );
  149. surfaceRippleGeometry.rotateX( - Math.PI / 2 );
  150. const xRippleGeometry = new THREE.PlaneGeometry( 1, 2 );
  151. xRippleGeometry.rotateY( - Math.PI / 2 );
  152. const zRippleGeometry = new THREE.PlaneGeometry( 1, 2 );
  153. const rippleGeometry = BufferGeometryUtils.mergeGeometries( [ surfaceRippleGeometry, xRippleGeometry, zRippleGeometry ] );
  154. const rippleParticles = new THREE.Mesh( rippleGeometry, rippleMaterial );
  155. rippleParticles.count = instanceCount;
  156. scene.add( rippleParticles );
  157. // floor geometry
  158. const floorGeometry = new THREE.PlaneGeometry( 1000, 1000 );
  159. floorGeometry.rotateX( - Math.PI / 2 );
  160. const plane = new THREE.Mesh( floorGeometry, new THREE.MeshBasicMaterial( { color: 0x050505 } ) );
  161. scene.add( plane );
  162. //
  163. collisionBox = new THREE.Mesh( new THREE.BoxGeometry( 30, 1, 15 ), new THREE.MeshStandardMaterial() );
  164. collisionBox.material.color.set( 0x333333 );
  165. collisionBox.position.y = 12;
  166. collisionBox.scale.x = 3.5;
  167. collisionBox.layers.enable( 1 );
  168. scene.add( collisionBox );
  169. //
  170. const loader = new THREE.BufferGeometryLoader();
  171. loader.load( 'models/json/suzanne_buffergeometry.json', function ( geometry ) {
  172. geometry.computeVertexNormals();
  173. monkey = new THREE.Mesh( geometry, new THREE.MeshStandardMaterial( { roughness: 1, metalness: 0 } ) );
  174. monkey.scale.setScalar( 5 );
  175. monkey.rotation.y = Math.PI / 2;
  176. monkey.position.y = 4.5;
  177. monkey.layers.enable( 1 ); // add to collision layer
  178. scene.add( monkey );
  179. } );
  180. //
  181. timer = new THREE.Timer();
  182. timer.connect( document );
  183. //
  184. renderer = new THREE.WebGPURenderer( { antialias: true } );
  185. renderer.setPixelRatio( window.devicePixelRatio );
  186. renderer.setSize( window.innerWidth, window.innerHeight );
  187. renderer.setAnimationLoop( animate );
  188. renderer.inspector = new Inspector();
  189. document.body.appendChild( renderer.domElement );
  190. await renderer.init();
  191. //
  192. renderer.compute( computeInit );
  193. //
  194. controls = new OrbitControls( camera, renderer.domElement );
  195. controls.minDistance = 5;
  196. controls.maxDistance = 50;
  197. controls.update();
  198. //
  199. window.addEventListener( 'resize', onWindowResize );
  200. // gui
  201. const gui = renderer.inspector.createParameters( 'Settings' );
  202. // use lerp to smooth the movement
  203. collisionBoxPosUI = new THREE.Vector3().copy( collisionBox.position );
  204. collisionBoxPos = new THREE.Vector3();
  205. gui.add( collisionBoxPosUI, 'z', - 50, 50, .001 ).name( 'position' );
  206. gui.add( collisionBox.scale, 'x', .1, 3.5, 0.01 ).name( 'scale' );
  207. gui.add( rainParticles, 'count', 200, maxParticleCount, 1 ).name( 'drop count' ).onChange( ( v ) => rippleParticles.count = v );
  208. }
  209. function onWindowResize() {
  210. const { innerWidth, innerHeight } = window;
  211. camera.aspect = innerWidth / innerHeight;
  212. camera.updateProjectionMatrix();
  213. renderer.setSize( innerWidth, innerHeight );
  214. }
  215. function animate() {
  216. timer.update();
  217. const delta = timer.getDelta();
  218. if ( monkey ) {
  219. monkey.rotation.y += delta;
  220. }
  221. collisionBoxPos.set( collisionBoxPosUI.x, collisionBoxPosUI.y, - collisionBoxPosUI.z );
  222. collisionBox.position.lerp( collisionBoxPos, 10 * delta );
  223. // position
  224. scene.overrideMaterial = collisionPosMaterial;
  225. scene.name = 'Collision Scene';
  226. renderer.setRenderTarget( collisionPosRT );
  227. renderer.render( scene, collisionCamera );
  228. // compute
  229. renderer.compute( computeParticles );
  230. // result
  231. scene.overrideMaterial = null;
  232. scene.name = 'Scene';
  233. renderer.setRenderTarget( null );
  234. renderer.render( scene, camera );
  235. }
  236. </script>
  237. </body>
  238. </html>
粤ICP备19079148号