webgpu_compute_particles_fluid.html 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>three.js webgpu - compute fluid 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. <meta property="og:title" content="three.js webgpu - compute fluid particles">
  8. <meta property="og:type" content="website">
  9. <meta property="og:url" content="https://threejs.org/examples/webgpu_compute_particles_fluid.html">
  10. <meta property="og:image" content="https://threejs.org/examples/screenshots/webgpu_compute_particles_fluid.jpg">
  11. <link type="text/css" rel="stylesheet" href="example.css">
  12. </head>
  13. <body>
  14. <div id="info">
  15. <a href="https://threejs.org/" target="_blank" rel="noopener" class="logo-link"></a>
  16. <div class="title-wrapper">
  17. <a href="https://threejs.org/" target="_blank" rel="noopener">three.js</a><span>Fluid Particles</span>
  18. </div>
  19. <small>MLS-MPM particle simulation running in compute shaders.</small>
  20. </div>
  21. <script type="importmap">
  22. {
  23. "imports": {
  24. "three": "../build/three.webgpu.js",
  25. "three/webgpu": "../build/three.webgpu.js",
  26. "three/tsl": "../build/three.tsl.js",
  27. "three/addons/": "./jsm/"
  28. }
  29. }
  30. </script>
  31. <script type="module">
  32. import * as THREE from 'three/webgpu';
  33. import { Fn, If, Return, instancedArray, instanceIndex, uniform, attribute, float, clamp, struct, atomicStore, int, ivec3, array, vec3, atomicAdd, Loop, atomicLoad, max, pow, mat3, vec4, cross, step, storage } from 'three/tsl';
  34. import { Inspector } from 'three/addons/inspector/Inspector.js';
  35. import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
  36. import { UltraHDRLoader } from 'three/addons/loaders/UltraHDRLoader.js';
  37. import * as BufferGeometryUtils from 'three/addons/utils/BufferGeometryUtils.js';
  38. import WebGPU from 'three/addons/capabilities/WebGPU.js';
  39. let renderer, scene, camera, controls;
  40. const timer = new THREE.Timer();
  41. timer.connect( document );
  42. const maxParticles = 8192 * 16;
  43. const gridSize1d = 64;
  44. const workgroupSize = 64;
  45. const gridSize = new THREE.Vector3( gridSize1d, gridSize1d, gridSize1d );
  46. const fixedPointMultiplier = 1e7;
  47. let particleCountUniform, stiffnessUniform, restDensityUniform, dynamicViscosityUniform, dtUniform, gravityUniform, gridSizeUniform;
  48. let particleBuffer, cellBuffer, cellBufferFloat;
  49. let clearGridKernel, p2g1Kernel, p2g2Kernel, updateGridKernel, g2pKernel, workgroupKernel;
  50. let p2g1KernelWorkgroupBuffer, p2g2KernelWorkgroupBuffer, g2pKernelWorkgroupBuffer;
  51. let particleMesh;
  52. const mouseCoord = new THREE.Vector3();
  53. const prevMouseCoord = new THREE.Vector3();
  54. let mouseRayOriginUniform, mouseRayDirectionUniform, mouseForceUniform;
  55. if ( WebGPU.isAvailable() === false ) {
  56. document.body.appendChild( WebGPU.getErrorMessage() );
  57. throw new Error( 'No WebGPU support' );
  58. }
  59. const params = {
  60. particleCount: 8192 * 4,
  61. };
  62. init();
  63. async function init() {
  64. renderer = new THREE.WebGPURenderer( { antialias: true, requiredLimits: { maxStorageBuffersInVertexStage: 1 } } );
  65. renderer.setPixelRatio( window.devicePixelRatio );
  66. renderer.setSize( window.innerWidth, window.innerHeight );
  67. renderer.toneMapping = THREE.ACESFilmicToneMapping;
  68. renderer.toneMappingExposure = 1.35;
  69. renderer.inspector = new Inspector();
  70. document.body.appendChild( renderer.domElement );
  71. scene = new THREE.Scene();
  72. camera = new THREE.PerspectiveCamera( 40, window.innerWidth / window.innerHeight, 0.01, 10 );
  73. camera.position.set( - 1.3, 1.3, - 1.3 );
  74. controls = new OrbitControls( camera, renderer.domElement );
  75. controls.minDistance = 1;
  76. controls.maxDistance = 3;
  77. controls.maxPolarAngle = Math.PI * 0.35;
  78. controls.touches = { TWO: THREE.TOUCH.DOLLY_ROTATE };
  79. const hdrLoader = new UltraHDRLoader().setPath( 'textures/equirectangular/' );
  80. const hdrTexture = await hdrLoader.loadAsync( 'royal_esplanade_2k.hdr.jpg' );
  81. hdrTexture.mapping = THREE.EquirectangularReflectionMapping;
  82. scene.background = hdrTexture;
  83. scene.backgroundBlurriness = 0.5;
  84. scene.environment = hdrTexture;
  85. setupParticles();
  86. const gui = renderer.inspector.createParameters( 'Settings' );
  87. const numWorkgroups = Math.ceil( params.particleCount / workgroupSize );
  88. p2g1KernelWorkgroupBuffer = new THREE.IndirectStorageBufferAttribute( new Uint32Array( [ numWorkgroups, 1, 1 ] ), 1 );
  89. p2g2KernelWorkgroupBuffer = new THREE.IndirectStorageBufferAttribute( new Uint32Array( [ numWorkgroups, 1, 1 ] ), 1 );
  90. g2pKernelWorkgroupBuffer = new THREE.IndirectStorageBufferAttribute( new Uint32Array( [ numWorkgroups, 1, 1 ] ), 1 );
  91. const p2g1WorkgroupStorage = storage( p2g1KernelWorkgroupBuffer, 'uint', 3 );
  92. const p2g2WorkgroupStorage = storage( p2g2KernelWorkgroupBuffer, 'uint', 3 );
  93. const g2pWorkgroupStorage = storage( g2pKernelWorkgroupBuffer, 'uint', 3 );
  94. workgroupKernel = Fn( () => {
  95. const workgroupsToDispatch = ( particleCountUniform.sub( 1 ) ).div( workgroupSize ).add( 1 );
  96. p2g1WorkgroupStorage.element( 0 ).assign( workgroupsToDispatch );
  97. p2g2WorkgroupStorage.element( 0 ).assign( workgroupsToDispatch );
  98. g2pWorkgroupStorage.element( 0 ).assign( workgroupsToDispatch );
  99. } )().compute( 1 );
  100. gui.add( params, 'particleCount', 4096, maxParticles, 4096 ).onChange( value => {
  101. particleMesh.count = value;
  102. p2g1Kernel.count = value;
  103. p2g2Kernel.count = value;
  104. g2pKernel.count = value;
  105. particleCountUniform.value = value;
  106. } );
  107. window.addEventListener( 'resize', onWindowResize );
  108. controls.update();
  109. renderer.setAnimationLoop( render );
  110. }
  111. function setupBuffers() {
  112. const particleStruct = struct( {
  113. position: { type: 'vec3' },
  114. velocity: { type: 'vec3' },
  115. C: { type: 'mat3' },
  116. } );
  117. const particleStructSize = 20; // each vec3 occupies 4 floats and mat3 occupies 12 floats in memory because of webgpu memory alignment
  118. const particleArray = new Float32Array( maxParticles * particleStructSize );
  119. for ( let i = 0; i < maxParticles; i ++ ) {
  120. particleArray[ i * particleStructSize ] = ( Math.random() * 0.8 + 0.1 );
  121. particleArray[ i * particleStructSize + 1 ] = ( Math.random() * 0.8 + 0.1 );
  122. particleArray[ i * particleStructSize + 2 ] = ( Math.random() * 0.8 + 0.1 );
  123. }
  124. particleBuffer = instancedArray( particleArray, particleStruct );
  125. const cellCount = gridSize.x * gridSize.y * gridSize.z;
  126. const cellStruct = struct( {
  127. x: { type: 'int', atomic: true },
  128. y: { type: 'int', atomic: true },
  129. z: { type: 'int', atomic: true },
  130. mass: { type: 'int', atomic: true },
  131. } );
  132. cellBuffer = instancedArray( cellCount, cellStruct );
  133. cellBufferFloat = instancedArray( cellCount, 'vec4' );
  134. }
  135. function setupUniforms() {
  136. gridSizeUniform = uniform( gridSize );
  137. particleCountUniform = uniform( params.particleCount, 'uint' );
  138. stiffnessUniform = uniform( 50 );
  139. restDensityUniform = uniform( 1.5 );
  140. dynamicViscosityUniform = uniform( 0.1 );
  141. dtUniform = uniform( 1 / 60 );
  142. gravityUniform = uniform( new THREE.Vector3( 0, - ( 9.81 * 9.81 ), 0 ) );
  143. mouseRayOriginUniform = uniform( new THREE.Vector3( 0, 0, 0 ) );
  144. mouseRayDirectionUniform = uniform( new THREE.Vector3( 0, 0, 0 ) );
  145. mouseForceUniform = uniform( new THREE.Vector3( 0, 0, 0 ) );
  146. // gui.add(restDensityUniform, "value", 1.0, 3, 0.1).name("restDensity");
  147. // it's interesting to adjust the restDensity but it might cause the simulation to become unstable
  148. }
  149. function setupComputeShaders() {
  150. // the MLS-MPM system uses five compute shaders:
  151. // 1. clearGridKernel: this clears the grid before each pass
  152. // 2. p2g1Kernel & 3. p2g2Kernel: These particle2grid kernels transfer the particles' energy to the grid
  153. // 4. updateGridKernel: updates the grid
  154. // 5. g2pKernel: grid2particle kernel, transfers the grid energy back to the particles
  155. // the implementation closely follows https://github.com/matsuoka-601/WebGPU-Ocean
  156. // because webgpu only supports int atomics, we use fixed point floats by multiplying/dividing the float values with a high integer constant
  157. const encodeFixedPoint = ( f32 ) => {
  158. return int( f32.mul( fixedPointMultiplier ) );
  159. };
  160. const decodeFixedPoint = ( i32 ) => {
  161. return float( i32 ).div( fixedPointMultiplier );
  162. };
  163. const cellCount = gridSize.x * gridSize.y * gridSize.z;
  164. clearGridKernel = Fn( () => {
  165. atomicStore( cellBuffer.element( instanceIndex ).get( 'x' ), 0 );
  166. atomicStore( cellBuffer.element( instanceIndex ).get( 'y' ), 0 );
  167. atomicStore( cellBuffer.element( instanceIndex ).get( 'z' ), 0 );
  168. atomicStore( cellBuffer.element( instanceIndex ).get( 'mass' ), 0 );
  169. } )().compute( cellCount ).setName( 'clearGridKernel' );
  170. p2g1Kernel = Fn( () => {
  171. const particlePosition = particleBuffer.element( instanceIndex ).get( 'position' ).toConst( 'particlePosition' );
  172. const particleVelocity = particleBuffer.element( instanceIndex ).get( 'velocity' ).toConst( 'particleVelocity' );
  173. const C = particleBuffer.element( instanceIndex ).get( 'C' ).toConst( 'C' );
  174. const gridPosition = particlePosition.mul( gridSizeUniform ).toVar();
  175. const cellIndex = ivec3( gridPosition ).sub( 1 ).toConst( 'cellIndex' );
  176. const cellDiff = gridPosition.fract().sub( 0.5 ).toConst( 'cellDiff' );
  177. const w0 = float( 0.5 ).mul( float( 0.5 ).sub( cellDiff ) ).mul( float( 0.5 ).sub( cellDiff ) );
  178. const w1 = float( 0.75 ).sub( cellDiff.mul( cellDiff ) );
  179. const w2 = float( 0.5 ).mul( float( 0.5 ).add( cellDiff ) ).mul( float( 0.5 ).add( cellDiff ) );
  180. const weights = array( [ w0, w1, w2 ] ).toConst( 'weights' );
  181. Loop( { start: 0, end: 3, type: 'int', name: 'gx', condition: '<' }, ( { gx } ) => {
  182. Loop( { start: 0, end: 3, type: 'int', name: 'gy', condition: '<' }, ( { gy } ) => {
  183. Loop( { start: 0, end: 3, type: 'int', name: 'gz', condition: '<' }, ( { gz } ) => {
  184. const weight = weights.element( gx ).x.mul( weights.element( gy ).y ).mul( weights.element( gz ).z );
  185. const cellX = cellIndex.add( ivec3( gx, gy, gz ) ).toConst();
  186. const cellDist = vec3( cellX ).add( 0.5 ).sub( gridPosition ).toConst( 'cellDist' );
  187. const Q = C.mul( cellDist );
  188. const massContrib = weight; // assuming particle mass = 1.0
  189. const velContrib = massContrib.mul( particleVelocity.add( Q ) ).toConst( 'velContrib' );
  190. const cellPtr = cellX.x.mul( int( gridSize.y * gridSize.z ) ).add( cellX.y.mul( int( gridSize.z ) ) ).add( cellX.z ).toConst();
  191. const cell = cellBuffer.element( cellPtr );
  192. atomicAdd( cell.get( 'x' ), encodeFixedPoint( velContrib.x ) );
  193. atomicAdd( cell.get( 'y' ), encodeFixedPoint( velContrib.y ) );
  194. atomicAdd( cell.get( 'z' ), encodeFixedPoint( velContrib.z ) );
  195. atomicAdd( cell.get( 'mass' ), encodeFixedPoint( massContrib ) );
  196. } );
  197. } );
  198. } );
  199. } )().compute( params.particleCount, [ workgroupSize, 1, 1 ] ).setName( 'p2g1Kernel' );
  200. p2g2Kernel = Fn( () => {
  201. const particlePosition = particleBuffer.element( instanceIndex ).get( 'position' ).toConst( 'particlePosition' );
  202. const gridPosition = particlePosition.mul( gridSizeUniform ).toVar();
  203. const cellIndex = ivec3( gridPosition ).sub( 1 ).toConst( 'cellIndex' );
  204. const cellDiff = gridPosition.fract().sub( 0.5 ).toConst( 'cellDiff' );
  205. const w0 = float( 0.5 ).mul( float( 0.5 ).sub( cellDiff ) ).mul( float( 0.5 ).sub( cellDiff ) );
  206. const w1 = float( 0.75 ).sub( cellDiff.mul( cellDiff ) );
  207. const w2 = float( 0.5 ).mul( float( 0.5 ).add( cellDiff ) ).mul( float( 0.5 ).add( cellDiff ) );
  208. const weights = array( [ w0, w1, w2 ] ).toConst( 'weights' );
  209. const density = float( 0 ).toVar( 'density' );
  210. Loop( { start: 0, end: 3, type: 'int', name: 'gx', condition: '<' }, ( { gx } ) => {
  211. Loop( { start: 0, end: 3, type: 'int', name: 'gy', condition: '<' }, ( { gy } ) => {
  212. Loop( { start: 0, end: 3, type: 'int', name: 'gz', condition: '<' }, ( { gz } ) => {
  213. const weight = weights.element( gx ).x.mul( weights.element( gy ).y ).mul( weights.element( gz ).z );
  214. const cellX = cellIndex.add( ivec3( gx, gy, gz ) ).toConst();
  215. const cellPtr = cellX.x.mul( int( gridSize.y * gridSize.z ) ).add( cellX.y.mul( int( gridSize.z ) ) ).add( cellX.z ).toConst();
  216. const cell = cellBuffer.element( cellPtr );
  217. const mass = decodeFixedPoint( atomicLoad( cell.get( 'mass' ) ) );
  218. density.addAssign( mass.mul( weight ) );
  219. } );
  220. } );
  221. } );
  222. const volume = float( 1 ).div( density );
  223. const pressure = max( 0.0, pow( density.div( restDensityUniform ), 5.0 ).sub( 1 ).mul( stiffnessUniform ) ).toConst( 'pressure' );
  224. const stress = mat3( pressure.negate(), 0, 0, 0, pressure.negate(), 0, 0, 0, pressure.negate() ).toVar( 'stress' );
  225. const dudv = particleBuffer.element( instanceIndex ).get( 'C' ).toConst( 'C' );
  226. const strain = dudv.add( dudv.transpose() );
  227. stress.addAssign( strain.mul( dynamicViscosityUniform ) );
  228. const eq16Term0 = volume.mul( - 4 ).mul( stress ).mul( dtUniform );
  229. Loop( { start: 0, end: 3, type: 'int', name: 'gx', condition: '<' }, ( { gx } ) => {
  230. Loop( { start: 0, end: 3, type: 'int', name: 'gy', condition: '<' }, ( { gy } ) => {
  231. Loop( { start: 0, end: 3, type: 'int', name: 'gz', condition: '<' }, ( { gz } ) => {
  232. const weight = weights.element( gx ).x.mul( weights.element( gy ).y ).mul( weights.element( gz ).z );
  233. const cellX = cellIndex.add( ivec3( gx, gy, gz ) ).toConst();
  234. const cellDist = vec3( cellX ).add( 0.5 ).sub( gridPosition ).toConst( 'cellDist' );
  235. const momentum = eq16Term0.mul( weight ).mul( cellDist ).toConst( 'momentum' );
  236. const cellPtr = cellX.x.mul( int( gridSize.y * gridSize.z ) ).add( cellX.y.mul( int( gridSize.z ) ) ).add( cellX.z ).toConst();
  237. const cell = cellBuffer.element( cellPtr );
  238. atomicAdd( cell.get( 'x' ), encodeFixedPoint( momentum.x ) );
  239. atomicAdd( cell.get( 'y' ), encodeFixedPoint( momentum.y ) );
  240. atomicAdd( cell.get( 'z' ), encodeFixedPoint( momentum.z ) );
  241. } );
  242. } );
  243. } );
  244. } )().compute( params.particleCount, [ workgroupSize, 1, 1 ] ).setName( 'p2g2Kernel' );
  245. updateGridKernel = Fn( () => {
  246. const cell = cellBuffer.element( instanceIndex );
  247. const mass = decodeFixedPoint( atomicLoad( cell.get( 'mass' ) ) ).toConst();
  248. If( mass.lessThanEqual( 0 ), () => {
  249. Return();
  250. } );
  251. const vx = decodeFixedPoint( atomicLoad( cell.get( 'x' ) ) ).div( mass ).toVar();
  252. const vy = decodeFixedPoint( atomicLoad( cell.get( 'y' ) ) ).div( mass ).toVar();
  253. const vz = decodeFixedPoint( atomicLoad( cell.get( 'z' ) ) ).div( mass ).toVar();
  254. const x = int( instanceIndex ).div( int( gridSize.z * gridSize.y ) );
  255. const y = int( instanceIndex ).div( int( gridSize.z ) ).mod( int( gridSize.y ) );
  256. const z = int( instanceIndex ).mod( int( gridSize.z ) );
  257. If( x.lessThan( int( 1 ) ).or( x.greaterThan( int( gridSize.x ).sub( int( 2 ) ) ) ), () => {
  258. vx.assign( 0 );
  259. } );
  260. If( y.lessThan( int( 1 ) ).or( y.greaterThan( int( gridSize.y ).sub( int( 2 ) ) ) ), () => {
  261. vy.assign( 0 );
  262. } );
  263. If( z.lessThan( int( 1 ) ).or( z.greaterThan( int( gridSize.z ).sub( int( 2 ) ) ) ), () => {
  264. vz.assign( 0 );
  265. } );
  266. cellBufferFloat.element( instanceIndex ).assign( vec4( vx, vy, vz, mass ) );
  267. } )().compute( cellCount ).setName( 'updateGridKernel' );
  268. const clampToRoundedBox = ( pos, box, radius ) => {
  269. const result = pos.sub( 0.5 ).toVar();
  270. const pp = step( box, result.abs() ).mul( result.add( box.negate().mul( result.sign() ) ) );
  271. const ppLen = pp.length().toVar();
  272. const dist = ppLen.sub( radius );
  273. If( dist.greaterThan( 0.0 ), () => {
  274. result.subAssign( pp.normalize().mul( dist ).mul( 1.3 ) );
  275. } );
  276. result.addAssign( 0.5 );
  277. return result;
  278. };
  279. g2pKernel = Fn( () => {
  280. const particlePosition = particleBuffer.element( instanceIndex ).get( 'position' ).toVar( 'particlePosition' );
  281. const gridPosition = particlePosition.mul( gridSizeUniform ).toVar();
  282. const particleVelocity = vec3( 0 ).toVar();
  283. const cellIndex = ivec3( gridPosition ).sub( 1 ).toConst( 'cellIndex' );
  284. const cellDiff = gridPosition.fract().sub( 0.5 ).toConst( 'cellDiff' );
  285. const w0 = float( 0.5 ).mul( float( 0.5 ).sub( cellDiff ) ).mul( float( 0.5 ).sub( cellDiff ) );
  286. const w1 = float( 0.75 ).sub( cellDiff.mul( cellDiff ) );
  287. const w2 = float( 0.5 ).mul( float( 0.5 ).add( cellDiff ) ).mul( float( 0.5 ).add( cellDiff ) );
  288. const weights = array( [ w0, w1, w2 ] ).toConst( 'weights' );
  289. const B = mat3( 0 ).toVar( 'B' );
  290. Loop( { start: 0, end: 3, type: 'int', name: 'gx', condition: '<' }, ( { gx } ) => {
  291. Loop( { start: 0, end: 3, type: 'int', name: 'gy', condition: '<' }, ( { gy } ) => {
  292. Loop( { start: 0, end: 3, type: 'int', name: 'gz', condition: '<' }, ( { gz } ) => {
  293. const weight = weights.element( gx ).x.mul( weights.element( gy ).y ).mul( weights.element( gz ).z );
  294. const cellX = cellIndex.add( ivec3( gx, gy, gz ) ).toConst();
  295. const cellDist = vec3( cellX ).add( 0.5 ).sub( gridPosition ).toConst( 'cellDist' );
  296. const cellPtr = cellX.x.mul( int( gridSize.y * gridSize.z ) ).add( cellX.y.mul( int( gridSize.z ) ) ).add( cellX.z ).toConst();
  297. const weightedVelocity = cellBufferFloat.element( cellPtr ).xyz.mul( weight ).toConst( 'weightedVelocity' );
  298. const term = mat3(
  299. weightedVelocity.mul( cellDist.x ),
  300. weightedVelocity.mul( cellDist.y ),
  301. weightedVelocity.mul( cellDist.z )
  302. );
  303. B.addAssign( term );
  304. particleVelocity.addAssign( weightedVelocity );
  305. } );
  306. } );
  307. } );
  308. particleBuffer.element( instanceIndex ).get( 'C' ).assign( B.mul( 4 ) );
  309. // gravity
  310. particleVelocity.addAssign( gravityUniform.mul( dtUniform ) );
  311. // scale from (gridSize.x, gridSize.y, gridSize.z) to (1, 1, 1)
  312. particleVelocity.divAssign( gridSizeUniform );
  313. // mouseInteraction
  314. const dist = cross( mouseRayDirectionUniform, particlePosition.sub( mouseRayOriginUniform ) ).length();
  315. const force = dist.mul( 3.00 ).oneMinus().max( 0.0 ).pow( 2 );
  316. particleVelocity.addAssign( mouseForceUniform.mul( force ) );
  317. // add velocity to position
  318. particlePosition.addAssign( particleVelocity.mul( dtUniform ) );
  319. // clamp position so outermost gridCells are not reached
  320. particlePosition.assign( clamp( particlePosition, vec3( 1 ).div( gridSizeUniform ), vec3( gridSize ).sub( 1 ).div( gridSizeUniform ) ) );
  321. // add force for particles to stay within rounded box
  322. const innerBox = gridSizeUniform.mul( 0.5 ).sub( 9.0 ).div( gridSizeUniform ).toVar();
  323. const innerRadius = float( 6.0 ).div( gridSizeUniform.x );
  324. const posNext = particlePosition.add( particleVelocity.mul( dtUniform ).mul( 2.0 ) ).toConst( 'posNext' );
  325. const posNextClamped = clampToRoundedBox( posNext, innerBox, innerRadius );
  326. particleVelocity.addAssign( posNextClamped.sub( posNext ) );
  327. /*
  328. const wallStiffness = 1.0;
  329. const xN = particlePosition.add( particleVelocity.mul( dtUniform ).mul( 2.0 ) ).toConst( 'xN' );
  330. const wallMin = vec3( 3 ).div(gridSizeUniform).toConst( 'wallMin' );
  331. const wallMax = vec3( gridSize ).sub( 3 ).div(gridSizeUniform).toConst( 'wallMax' );
  332. particleVelocity.addAssign( wallMin.sub( xN ).max( 0.0 ).mul( wallStiffness ) );
  333. particleVelocity.addAssign( wallMax.sub( xN ).min( 0.0 ).mul( wallStiffness ) );
  334. */
  335. // scale from (1, 1, 1) back to (gridSize.x, gridSize.y, gridSize.z) to
  336. particleVelocity.mulAssign( gridSizeUniform );
  337. particleBuffer.element( instanceIndex ).get( 'position' ).assign( particlePosition );
  338. particleBuffer.element( instanceIndex ).get( 'velocity' ).assign( particleVelocity );
  339. } )().compute( params.particleCount, [ workgroupSize, 1, 1 ] ).setName( 'g2pKernel' );
  340. }
  341. function setupMesh() {
  342. // mergeVertices to reduce the number of vertexShaderCalls
  343. const geometry = BufferGeometryUtils.mergeVertices( new THREE.IcosahedronGeometry( 0.008, 1 ).deleteAttribute( 'uv' ) );
  344. const material = new THREE.MeshStandardNodeMaterial( {
  345. color: '#0066FF'
  346. } );
  347. material.positionNode = Fn( () => {
  348. const particlePosition = particleBuffer.element( instanceIndex ).get( 'position' );
  349. return attribute( 'position' ).add( particlePosition );
  350. } )();
  351. particleMesh = new THREE.Mesh( geometry, material );
  352. particleMesh.count = params.particleCount;
  353. particleMesh.position.set( - 0.5, 0, - 0.5 );
  354. particleMesh.frustumCulled = false;
  355. scene.add( particleMesh );
  356. }
  357. function setupMouse() {
  358. const raycaster = new THREE.Raycaster();
  359. const raycastPlane = new THREE.Plane( new THREE.Vector3( 0, 1, 0 ) );
  360. const onMove = ( event ) => {
  361. const pointer = new THREE.Vector2( ( event.clientX / window.innerWidth ) * 2 - 1, - ( event.clientY / window.innerHeight ) * 2 + 1 );
  362. raycaster.setFromCamera( pointer, camera );
  363. raycaster.ray.origin.x += 0.5;
  364. raycaster.ray.origin.z += 0.5;
  365. mouseRayOriginUniform.value.copy( raycaster.ray.origin );
  366. mouseRayDirectionUniform.value.copy( raycaster.ray.direction );
  367. raycaster.ray.intersectPlane( raycastPlane, mouseCoord );
  368. };
  369. renderer.domElement.addEventListener( 'pointermove', onMove );
  370. }
  371. function setupParticles() {
  372. setupBuffers();
  373. setupUniforms();
  374. setupComputeShaders();
  375. setupMesh();
  376. setupMouse();
  377. }
  378. function onWindowResize() {
  379. camera.aspect = window.innerWidth / window.innerHeight;
  380. camera.updateProjectionMatrix();
  381. renderer.setSize( window.innerWidth, window.innerHeight );
  382. }
  383. async function render() {
  384. timer.update();
  385. const deltaTime = THREE.MathUtils.clamp( timer.getDelta(), 0.00001, 1 / 60 ); // don't advance the time too far, for example when the window is out of focus
  386. dtUniform.value = deltaTime;
  387. mouseForceUniform.value.copy( mouseCoord ).sub( prevMouseCoord ).multiplyScalar( 2 );
  388. const mouseForceLength = mouseForceUniform.value.length();
  389. if ( mouseForceLength > 0.3 ) {
  390. mouseForceUniform.value.multiplyScalar( 0.3 / mouseForceLength );
  391. }
  392. prevMouseCoord.copy( mouseCoord );
  393. renderer.compute( workgroupKernel );
  394. //renderer.compute( [ clearGridKernel, p2g1Kernel, p2g2Kernel, updateGridKernel, g2pKernel ] );
  395. renderer.compute( clearGridKernel );
  396. renderer.compute( p2g1Kernel, p2g1KernelWorkgroupBuffer );
  397. renderer.compute( p2g2Kernel, p2g2KernelWorkgroupBuffer );
  398. renderer.compute( updateGridKernel );
  399. renderer.compute( g2pKernel, g2pKernelWorkgroupBuffer );
  400. renderer.render( scene, camera );
  401. }
  402. </script>
  403. </body>
  404. </html>
粤ICP备19079148号