webgpu_compute_particles_fluid.html 22 KB

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