webgpu_compute_particles_rain.html 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  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 clock;
  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. const dirLight = new THREE.DirectionalLight( 0xffffff, .5 );
  49. dirLight.castShadow = true;
  50. dirLight.position.set( 3, 17, 17 );
  51. dirLight.castShadow = true;
  52. dirLight.shadow.camera.near = 1;
  53. dirLight.shadow.camera.far = 50;
  54. dirLight.shadow.camera.right = 25;
  55. dirLight.shadow.camera.left = - 25;
  56. dirLight.shadow.camera.top = 25;
  57. dirLight.shadow.camera.bottom = - 25;
  58. dirLight.shadow.mapSize.width = 2048;
  59. dirLight.shadow.mapSize.height = 2048;
  60. dirLight.shadow.bias = - 0.01;
  61. scene.add( dirLight );
  62. scene.add( new THREE.AmbientLight( 0x111111 ) );
  63. //
  64. collisionCamera = new THREE.OrthographicCamera( - 50, 50, 50, - 50, .1, 50 );
  65. collisionCamera.position.y = 50;
  66. collisionCamera.lookAt( 0, 0, 0 );
  67. collisionCamera.layers.disableAll();
  68. collisionCamera.layers.enable( 1 );
  69. collisionPosRT = new THREE.RenderTarget( 1024, 1024 );
  70. collisionPosRT.texture.type = THREE.HalfFloatType;
  71. collisionPosRT.texture.magFilter = THREE.NearestFilter;
  72. collisionPosRT.texture.minFilter = THREE.NearestFilter;
  73. collisionPosRT.texture.generateMipmaps = false;
  74. collisionPosMaterial = new THREE.MeshBasicNodeMaterial();
  75. collisionPosMaterial.colorNode = positionWorld;
  76. //
  77. const positionBuffer = instancedArray( maxParticleCount, 'vec3' );
  78. const velocityBuffer = instancedArray( maxParticleCount, 'vec3' );
  79. const ripplePositionBuffer = instancedArray( maxParticleCount, 'vec3' );
  80. const rippleTimeBuffer = instancedArray( maxParticleCount, 'vec3' );
  81. // compute
  82. const randUint = () => uint( Math.random() * 0xFFFFFF );
  83. const computeInit = Fn( () => {
  84. const position = positionBuffer.element( instanceIndex );
  85. const velocity = velocityBuffer.element( instanceIndex );
  86. const rippleTime = rippleTimeBuffer.element( instanceIndex );
  87. const randX = hash( instanceIndex );
  88. const randY = hash( instanceIndex.add( randUint() ) );
  89. const randZ = hash( instanceIndex.add( randUint() ) );
  90. position.x = randX.mul( 100 ).add( - 50 );
  91. position.y = randY.mul( 25 );
  92. position.z = randZ.mul( 100 ).add( - 50 );
  93. velocity.y = randX.mul( - .04 ).add( - .2 );
  94. rippleTime.x = 1000;
  95. } )().compute( maxParticleCount );
  96. //
  97. const computeUpdate = Fn( () => {
  98. const getCoord = ( pos ) => pos.add( 50 ).div( 100 );
  99. const position = positionBuffer.element( instanceIndex );
  100. const velocity = velocityBuffer.element( instanceIndex );
  101. const ripplePosition = ripplePositionBuffer.element( instanceIndex );
  102. const rippleTime = rippleTimeBuffer.element( instanceIndex );
  103. position.addAssign( velocity );
  104. rippleTime.x = rippleTime.x.add( deltaTime.mul( 4 ) );
  105. //
  106. const collisionArea = texture( collisionPosRT.texture, getCoord( position.xz ) );
  107. const surfaceOffset = .05;
  108. const floorPosition = collisionArea.y.add( surfaceOffset );
  109. // floor
  110. const ripplePivotOffsetY = - .9;
  111. If( position.y.add( ripplePivotOffsetY ).lessThan( floorPosition ), () => {
  112. position.y = 25;
  113. ripplePosition.xz = position.xz;
  114. ripplePosition.y = floorPosition;
  115. // reset hit time: x = time
  116. rippleTime.x = 1;
  117. // next drops will not fall in the same place
  118. position.x = hash( instanceIndex.add( time ) ).mul( 100 ).add( - 50 );
  119. position.z = hash( instanceIndex.add( time.add( randUint() ) ) ).mul( 100 ).add( - 50 );
  120. } );
  121. const rippleOnSurface = texture( collisionPosRT.texture, getCoord( ripplePosition.xz ) );
  122. const rippleFloorArea = rippleOnSurface.y.add( surfaceOffset );
  123. If( ripplePosition.y.greaterThan( rippleFloorArea ), () => {
  124. rippleTime.x = 1000;
  125. } );
  126. } );
  127. computeParticles = computeUpdate().compute( maxParticleCount ).setName( 'Particles' );
  128. // rain
  129. const rainMaterial = new THREE.MeshBasicNodeMaterial();
  130. rainMaterial.colorNode = uv().distance( vec2( .5, 0 ) ).oneMinus().mul( 3 ).exp().mul( .1 );
  131. rainMaterial.vertexNode = billboarding( { position: positionBuffer.toAttribute() } );
  132. rainMaterial.opacity = .2;
  133. rainMaterial.side = THREE.DoubleSide;
  134. rainMaterial.forceSinglePass = true;
  135. rainMaterial.depthWrite = false;
  136. rainMaterial.depthTest = true;
  137. rainMaterial.transparent = true;
  138. const rainParticles = new THREE.Mesh( new THREE.PlaneGeometry( .1, 2 ), rainMaterial );
  139. rainParticles.count = instanceCount;
  140. scene.add( rainParticles );
  141. // ripple
  142. const rippleTime = rippleTimeBuffer.element( instanceIndex ).x;
  143. const rippleEffect = Fn( () => {
  144. const center = uv().add( vec2( - .5 ) ).length().mul( 7 );
  145. const distance = rippleTime.sub( center );
  146. return distance.min( 1 ).sub( distance.max( 1 ).sub( 1 ) );
  147. } );
  148. const rippleMaterial = new THREE.MeshBasicNodeMaterial();
  149. rippleMaterial.colorNode = rippleEffect();
  150. rippleMaterial.positionNode = positionGeometry.add( ripplePositionBuffer.toAttribute() );
  151. rippleMaterial.opacityNode = rippleTime.mul( .3 ).oneMinus().max( 0 ).mul( .5 );
  152. rippleMaterial.side = THREE.DoubleSide;
  153. rippleMaterial.forceSinglePass = true;
  154. rippleMaterial.depthWrite = false;
  155. rippleMaterial.depthTest = true;
  156. rippleMaterial.transparent = true;
  157. // ripple geometry
  158. const surfaceRippleGeometry = new THREE.PlaneGeometry( 2.5, 2.5 );
  159. surfaceRippleGeometry.rotateX( - Math.PI / 2 );
  160. const xRippleGeometry = new THREE.PlaneGeometry( 1, 2 );
  161. xRippleGeometry.rotateY( - Math.PI / 2 );
  162. const zRippleGeometry = new THREE.PlaneGeometry( 1, 2 );
  163. const rippleGeometry = BufferGeometryUtils.mergeGeometries( [ surfaceRippleGeometry, xRippleGeometry, zRippleGeometry ] );
  164. const rippleParticles = new THREE.Mesh( rippleGeometry, rippleMaterial );
  165. rippleParticles.count = instanceCount;
  166. scene.add( rippleParticles );
  167. // floor geometry
  168. const floorGeometry = new THREE.PlaneGeometry( 1000, 1000 );
  169. floorGeometry.rotateX( - Math.PI / 2 );
  170. const plane = new THREE.Mesh( floorGeometry, new THREE.MeshBasicMaterial( { color: 0x050505 } ) );
  171. scene.add( plane );
  172. //
  173. collisionBox = new THREE.Mesh( new THREE.BoxGeometry( 30, 1, 15 ), new THREE.MeshStandardMaterial() );
  174. collisionBox.material.color.set( 0x333333 );
  175. collisionBox.position.y = 12;
  176. collisionBox.scale.x = 3.5;
  177. collisionBox.layers.enable( 1 );
  178. collisionBox.castShadow = true;
  179. scene.add( collisionBox );
  180. //
  181. const loader = new THREE.BufferGeometryLoader();
  182. loader.load( 'models/json/suzanne_buffergeometry.json', function ( geometry ) {
  183. geometry.computeVertexNormals();
  184. monkey = new THREE.Mesh( geometry, new THREE.MeshStandardMaterial( { roughness: 1, metalness: 0 } ) );
  185. monkey.receiveShadow = true;
  186. monkey.scale.setScalar( 5 );
  187. monkey.rotation.y = Math.PI / 2;
  188. monkey.position.y = 4.5;
  189. monkey.layers.enable( 1 ); // add to collision layer
  190. scene.add( monkey );
  191. } );
  192. //
  193. clock = new THREE.Clock();
  194. //
  195. renderer = new THREE.WebGPURenderer( { antialias: true } );
  196. renderer.setPixelRatio( window.devicePixelRatio );
  197. renderer.setSize( window.innerWidth, window.innerHeight );
  198. renderer.setAnimationLoop( animate );
  199. renderer.inspector = new Inspector();
  200. document.body.appendChild( renderer.domElement );
  201. await renderer.init();
  202. //
  203. renderer.compute( computeInit );
  204. //
  205. controls = new OrbitControls( camera, renderer.domElement );
  206. controls.minDistance = 5;
  207. controls.maxDistance = 50;
  208. controls.update();
  209. //
  210. window.addEventListener( 'resize', onWindowResize );
  211. // gui
  212. const gui = renderer.inspector.createParameters( 'Settings' );
  213. // use lerp to smooth the movement
  214. collisionBoxPosUI = new THREE.Vector3().copy( collisionBox.position );
  215. collisionBoxPos = new THREE.Vector3();
  216. gui.add( collisionBoxPosUI, 'z', - 50, 50, .001 ).name( 'position' );
  217. gui.add( collisionBox.scale, 'x', .1, 3.5, 0.01 ).name( 'scale' );
  218. gui.add( rainParticles, 'count', 200, maxParticleCount, 1 ).name( 'drop count' ).onChange( ( v ) => rippleParticles.count = v );
  219. }
  220. function onWindowResize() {
  221. const { innerWidth, innerHeight } = window;
  222. camera.aspect = innerWidth / innerHeight;
  223. camera.updateProjectionMatrix();
  224. renderer.setSize( innerWidth, innerHeight );
  225. }
  226. function animate() {
  227. const delta = clock.getDelta();
  228. if ( monkey ) {
  229. monkey.rotation.y += delta;
  230. }
  231. collisionBoxPos.set( collisionBoxPosUI.x, collisionBoxPosUI.y, - collisionBoxPosUI.z );
  232. collisionBox.position.lerp( collisionBoxPos, 10 * delta );
  233. // position
  234. scene.overrideMaterial = collisionPosMaterial;
  235. scene.name = 'Collision Scene';
  236. renderer.setRenderTarget( collisionPosRT );
  237. renderer.render( scene, collisionCamera );
  238. // compute
  239. renderer.compute( computeParticles );
  240. // result
  241. scene.overrideMaterial = null;
  242. scene.name = 'Scene';
  243. renderer.setRenderTarget( null );
  244. renderer.render( scene, camera );
  245. }
  246. </script>
  247. </body>
  248. </html>
粤ICP备19079148号