webgpu_compute_particles_fluid.html 21 KB

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