webgpu_compute_cloth.html 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>three.js webgpu - compute cloth</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 - compute cloth<br />
  12. Simple cloth simulation with a verlet system 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, select, attribute, uint, Loop, float, transformNormalToView, cross, triNoise3D, time } 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 WebGPU from 'three/addons/capabilities/WebGPU.js';
  31. let renderer, scene, camera, controls;
  32. const clothWidth = 1;
  33. const clothHeight = 1;
  34. const clothNumSegmentsX = 30;
  35. const clothNumSegmentsY = 30;
  36. const sphereRadius = 0.15;
  37. let vertexPositionBuffer, vertexForceBuffer, vertexParamsBuffer;
  38. let springVertexIdBuffer, springRestLengthBuffer, springForceBuffer;
  39. let springListBuffer;
  40. let computeSpringForces, computeVertexForces;
  41. let dampeningUniform, spherePositionUniform, stiffnessUniform, sphereUniform, windUniform;
  42. let vertexWireframeObject, springWireframeObject;
  43. let clothMesh, clothMaterial, sphere;
  44. let timeSinceLastStep = 0;
  45. let timestamp = 0;
  46. const verletVertices = [];
  47. const verletSprings = [];
  48. const verletVertexColumns = [];
  49. const clock = new THREE.Clock();
  50. const params = {
  51. wireframe: false,
  52. sphere: true,
  53. wind: 1.0,
  54. };
  55. const API = {
  56. color: 0x204080, // sRGB
  57. sheenColor: 0xffffff // sRGB
  58. };
  59. if ( WebGPU.isAvailable() === false ) {
  60. document.body.appendChild( WebGPU.getErrorMessage() );
  61. throw new Error( 'No WebGPU support' );
  62. }
  63. init();
  64. async function init() {
  65. renderer = new THREE.WebGPURenderer( { antialias: true } );
  66. renderer.setPixelRatio( window.devicePixelRatio );
  67. renderer.setSize( window.innerWidth, window.innerHeight );
  68. renderer.toneMapping = THREE.NeutralToneMapping;
  69. renderer.toneMappingExposure = 1;
  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.6, - 0.1, - 1.6 );
  74. controls = new OrbitControls( camera, renderer.domElement );
  75. controls.minDistance = 1;
  76. controls.maxDistance = 3;
  77. controls.target.set( 0, - 0.1, 0 );
  78. controls.update();
  79. const hdrLoader = new HDRLoader().setPath( 'textures/equirectangular/' );
  80. const hdrTexture = await hdrLoader.loadAsync( 'royal_esplanade_1k.hdr' );
  81. hdrTexture.mapping = THREE.EquirectangularReflectionMapping;
  82. scene.background = hdrTexture;
  83. scene.backgroundBlurriness = 0.5;
  84. scene.environment = hdrTexture;
  85. setupCloth();
  86. const gui = new GUI();
  87. gui.add( stiffnessUniform, 'value', 0.1, 0.5, 0.01 ).name( 'stiffness' );
  88. gui.add( params, 'wireframe' );
  89. gui.add( params, 'sphere' );
  90. gui.add( params, 'wind', 0, 5, 0.1 );
  91. const materialFolder = gui.addFolder( 'material' );
  92. materialFolder.addColor( API, 'color' ).onChange( function ( color ) {
  93. clothMaterial.color.setHex( color );
  94. } );
  95. materialFolder.add( clothMaterial, 'roughness', 0.0, 1, 0.01 );
  96. materialFolder.add( clothMaterial, 'sheen', 0.0, 1, 0.01 );
  97. materialFolder.add( clothMaterial, 'sheenRoughness', 0.0, 1, 0.01 );
  98. materialFolder.addColor( API, 'sheenColor' ).onChange( function ( color ) {
  99. clothMaterial.sheenColor.setHex( color );
  100. } );
  101. window.addEventListener( 'resize', onWindowResize );
  102. renderer.setAnimationLoop( render );
  103. }
  104. function setupVerletGeometry() {
  105. // this function sets up the geometry of the verlet system, a grid of vertices connected by springs
  106. const addVerletVertex = ( x, y, z, isFixed ) => {
  107. const id = verletVertices.length;
  108. const vertex = {
  109. id,
  110. position: new THREE.Vector3( x, y, z ),
  111. isFixed,
  112. springIds: [],
  113. };
  114. verletVertices.push( vertex );
  115. return vertex;
  116. };
  117. const addVerletSpring = ( vertex0, vertex1 ) => {
  118. const id = verletSprings.length;
  119. const spring = {
  120. id,
  121. vertex0,
  122. vertex1
  123. };
  124. vertex0.springIds.push( id );
  125. vertex1.springIds.push( id );
  126. verletSprings.push( spring );
  127. return spring;
  128. };
  129. // create the cloth's verlet vertices
  130. for ( let x = 0; x <= clothNumSegmentsX; x ++ ) {
  131. const column = [];
  132. for ( let y = 0; y <= clothNumSegmentsY; y ++ ) {
  133. const posX = x * ( clothWidth / clothNumSegmentsX ) - clothWidth * 0.5;
  134. const posZ = y * ( clothHeight / clothNumSegmentsY );
  135. const isFixed = ( y === 0 ) && ( ( x % 5 ) === 0 ); // make some of the top vertices' positions fixed
  136. const vertex = addVerletVertex( posX, clothHeight * 0.5, posZ, isFixed );
  137. column.push( vertex );
  138. }
  139. verletVertexColumns.push( column );
  140. }
  141. // create the cloth's verlet springs
  142. for ( let x = 0; x <= clothNumSegmentsX; x ++ ) {
  143. for ( let y = 0; y <= clothNumSegmentsY; y ++ ) {
  144. const vertex0 = verletVertexColumns[ x ][ y ];
  145. if ( x > 0 ) addVerletSpring( vertex0, verletVertexColumns[ x - 1 ][ y ] );
  146. if ( y > 0 ) addVerletSpring( vertex0, verletVertexColumns[ x ][ y - 1 ] );
  147. if ( x > 0 && y > 0 ) addVerletSpring( vertex0, verletVertexColumns[ x - 1 ][ y - 1 ] );
  148. if ( x > 0 && y < clothNumSegmentsY ) addVerletSpring( vertex0, verletVertexColumns[ x - 1 ][ y + 1 ] );
  149. // You can make the cloth more rigid by adding more springs between further apart vertices
  150. //if (x > 1) addVerletSpring(vertex0, verletVertexColumns[x - 2][y]);
  151. //if (y > 1) addVerletSpring(vertex0, verletVertexColumns[x][y - 2]);
  152. }
  153. }
  154. }
  155. function setupVerletVertexBuffers() {
  156. // setup the buffers holding the vertex data for the compute shaders
  157. const vertexCount = verletVertices.length;
  158. const springListArray = [];
  159. // this springListArray will hold a list of spring ids, ordered by the id of the vertex affected by that spring.
  160. // this is so the compute shader that accumulates the spring forces for each vertex can efficiently iterate over all springs affecting that vertex
  161. const vertexPositionArray = new Float32Array( vertexCount * 3 );
  162. const vertexParamsArray = new Uint32Array( vertexCount * 3 );
  163. // the params Array holds three values for each verlet vertex:
  164. // x: isFixed, y: springCount, z: springPointer
  165. // isFixed is 1 if the verlet is marked as immovable, 0 if not
  166. // springCount is the number of springs connected to that vertex
  167. // springPointer is the index of the first spring in the springListArray that is connected to that vertex
  168. for ( let i = 0; i < vertexCount; i ++ ) {
  169. const vertex = verletVertices[ i ];
  170. vertexPositionArray[ i * 3 ] = vertex.position.x;
  171. vertexPositionArray[ i * 3 + 1 ] = vertex.position.y;
  172. vertexPositionArray[ i * 3 + 2 ] = vertex.position.z;
  173. vertexParamsArray[ i * 3 ] = vertex.isFixed ? 1 : 0;
  174. if ( ! vertex.isFixed ) {
  175. vertexParamsArray[ i * 3 + 1 ] = vertex.springIds.length;
  176. vertexParamsArray[ i * 3 + 2 ] = springListArray.length;
  177. springListArray.push( ...vertex.springIds );
  178. }
  179. }
  180. vertexPositionBuffer = instancedArray( vertexPositionArray, 'vec3' ).setPBO( true ); // setPBO(true) is only important for the WebGL Fallback
  181. vertexForceBuffer = instancedArray( vertexCount, 'vec3' );
  182. vertexParamsBuffer = instancedArray( vertexParamsArray, 'uvec3' );
  183. springListBuffer = instancedArray( new Uint32Array( springListArray ), 'uint' ).setPBO( true );
  184. }
  185. function setupVerletSpringBuffers() {
  186. // setup the buffers holding the spring data for the compute shaders
  187. const springCount = verletSprings.length;
  188. const springVertexIdArray = new Uint32Array( springCount * 2 );
  189. const springRestLengthArray = new Float32Array( springCount );
  190. for ( let i = 0; i < springCount; i ++ ) {
  191. const spring = verletSprings[ i ];
  192. springVertexIdArray[ i * 2 ] = spring.vertex0.id;
  193. springVertexIdArray[ i * 2 + 1 ] = spring.vertex1.id;
  194. springRestLengthArray[ i ] = spring.vertex0.position.distanceTo( spring.vertex1.position );
  195. }
  196. springVertexIdBuffer = instancedArray( springVertexIdArray, 'uvec2' ).setPBO( true );
  197. springRestLengthBuffer = instancedArray( springRestLengthArray, 'float' );
  198. springForceBuffer = instancedArray( springCount * 3, 'vec3' ).setPBO( true );
  199. }
  200. function setupUniforms() {
  201. dampeningUniform = uniform( 0.99 );
  202. spherePositionUniform = uniform( new THREE.Vector3( 0, 0, 0 ) );
  203. sphereUniform = uniform( 1.0 );
  204. windUniform = uniform( 1.0 );
  205. stiffnessUniform = uniform( 0.2 );
  206. }
  207. function setupComputeShaders() {
  208. // This function sets up the compute shaders for the verlet simulation
  209. // There are two shaders that are executed for each simulation step
  210. const vertexCount = verletVertices.length;
  211. const springCount = verletSprings.length;
  212. // 1. computeSpringForces:
  213. // This shader computes a force for each spring, depending on the distance between the two vertices connected by that spring and the targeted rest length
  214. computeSpringForces = Fn( () => {
  215. If( instanceIndex.greaterThanEqual( uint( springCount ) ), () => {
  216. // compute Shaders are executed in groups of 64, so instanceIndex might be bigger than the amount of springs.
  217. // in that case, return.
  218. Return();
  219. } );
  220. const vertexIds = springVertexIdBuffer.element( instanceIndex );
  221. const restLength = springRestLengthBuffer.element( instanceIndex );
  222. const vertex0Position = vertexPositionBuffer.element( vertexIds.x );
  223. const vertex1Position = vertexPositionBuffer.element( vertexIds.y );
  224. const delta = vertex1Position.sub( vertex0Position ).toVar();
  225. const dist = delta.length().max( 0.000001 ).toVar();
  226. const force = dist.sub( restLength ).mul( stiffnessUniform ).mul( delta ).mul( 0.5 ).div( dist );
  227. springForceBuffer.element( instanceIndex ).assign( force );
  228. } )().compute( springCount );
  229. // 2. computeVertexForces:
  230. // This shader accumulates the force for each vertex.
  231. // First it iterates over all springs connected to this vertex and accumulates their forces.
  232. // Then it adds a gravital force, wind force, and the collision with the sphere.
  233. // In the end it adds the force to the vertex' position.
  234. computeVertexForces = Fn( () => {
  235. If( instanceIndex.greaterThanEqual( uint( vertexCount ) ), () => {
  236. // compute Shaders are executed in groups of 64, so instanceIndex might be bigger than the amount of vertices.
  237. // in that case, return.
  238. Return();
  239. } );
  240. const params = vertexParamsBuffer.element( instanceIndex ).toVar();
  241. const isFixed = params.x;
  242. const springCount = params.y;
  243. const springPointer = params.z;
  244. If( isFixed, () => {
  245. // don't need to calculate vertex forces if the vertex is set as immovable
  246. Return();
  247. } );
  248. const position = vertexPositionBuffer.element( instanceIndex ).toVar( 'vertexPosition' );
  249. const force = vertexForceBuffer.element( instanceIndex ).toVar( 'vertexForce' );
  250. force.mulAssign( dampeningUniform );
  251. const ptrStart = springPointer.toVar( 'ptrStart' );
  252. const ptrEnd = ptrStart.add( springCount ).toVar( 'ptrEnd' );
  253. Loop( { start: ptrStart, end: ptrEnd, type: 'uint', condition: '<' }, ( { i } ) => {
  254. const springId = springListBuffer.element( i ).toVar( 'springId' );
  255. const springForce = springForceBuffer.element( springId );
  256. const springVertexIds = springVertexIdBuffer.element( springId );
  257. const factor = select( springVertexIds.x.equal( instanceIndex ), 1.0, - 1.0 );
  258. force.addAssign( springForce.mul( factor ) );
  259. } );
  260. // gravity
  261. force.y.subAssign( 0.00005 );
  262. // wind
  263. const noise = triNoise3D( position, 1, time ).sub( 0.2 ).mul( 0.0001 );
  264. const windForce = noise.mul( windUniform );
  265. force.z.subAssign( windForce );
  266. // collision with sphere
  267. const deltaSphere = position.add( force ).sub( spherePositionUniform );
  268. const dist = deltaSphere.length();
  269. const sphereForce = float( sphereRadius ).sub( dist ).max( 0 ).mul( deltaSphere ).div( dist ).mul( sphereUniform );
  270. force.addAssign( sphereForce );
  271. vertexForceBuffer.element( instanceIndex ).assign( force );
  272. vertexPositionBuffer.element( instanceIndex ).addAssign( force );
  273. } )().compute( vertexCount );
  274. }
  275. function setupWireframe() {
  276. // adds helpers to visualize the verlet system
  277. // verlet vertex visualizer
  278. const vertexWireframeMaterial = new THREE.SpriteNodeMaterial();
  279. vertexWireframeMaterial.positionNode = vertexPositionBuffer.element( instanceIndex );
  280. vertexWireframeObject = new THREE.Mesh( new THREE.PlaneGeometry( 0.01, 0.01 ), vertexWireframeMaterial );
  281. vertexWireframeObject.frustumCulled = false;
  282. vertexWireframeObject.count = verletVertices.length;
  283. scene.add( vertexWireframeObject );
  284. // verlet spring visualizer
  285. const springWireframePositionBuffer = new THREE.BufferAttribute( new Float32Array( 6 ), 3, false );
  286. const springWireframeIndexBuffer = new THREE.BufferAttribute( new Uint32Array( [ 0, 1 ] ), 1, false );
  287. const springWireframeMaterial = new THREE.LineBasicNodeMaterial();
  288. springWireframeMaterial.positionNode = Fn( () => {
  289. const vertexIds = springVertexIdBuffer.element( instanceIndex );
  290. const vertexId = select( attribute( 'vertexIndex' ).equal( 0 ), vertexIds.x, vertexIds.y );
  291. return vertexPositionBuffer.element( vertexId );
  292. } )();
  293. const springWireframeGeometry = new THREE.InstancedBufferGeometry();
  294. springWireframeGeometry.setAttribute( 'position', springWireframePositionBuffer );
  295. springWireframeGeometry.setAttribute( 'vertexIndex', springWireframeIndexBuffer );
  296. springWireframeGeometry.instanceCount = verletSprings.length;
  297. springWireframeObject = new THREE.Line( springWireframeGeometry, springWireframeMaterial );
  298. springWireframeObject.frustumCulled = false;
  299. springWireframeObject.count = verletSprings.length;
  300. scene.add( springWireframeObject );
  301. }
  302. function setupSphere() {
  303. const geometry = new THREE.IcosahedronGeometry( sphereRadius * 0.95, 4 );
  304. const material = new THREE.MeshStandardNodeMaterial();
  305. sphere = new THREE.Mesh( geometry, material );
  306. scene.add( sphere );
  307. }
  308. function setupClothMesh() {
  309. // This function generates a three Geometry and Mesh to render the cloth based on the verlet systems position data.
  310. // Therefore it creates a plane mesh, in which each vertex will be centered in the center of 4 verlet vertices.
  311. const vertexCount = clothNumSegmentsX * clothNumSegmentsY;
  312. const geometry = new THREE.BufferGeometry();
  313. // verletVertexIdArray will hold the 4 verlet vertex ids that contribute to each geometry vertex's position
  314. const verletVertexIdArray = new Uint32Array( vertexCount * 4 );
  315. const indices = [];
  316. const getIndex = ( x, y ) => {
  317. return y * clothNumSegmentsX + x;
  318. };
  319. for ( let x = 0; x < clothNumSegmentsX; x ++ ) {
  320. for ( let y = 0; y < clothNumSegmentsX; y ++ ) {
  321. const index = getIndex( x, y );
  322. verletVertexIdArray[ index * 4 ] = verletVertexColumns[ x ][ y ].id;
  323. verletVertexIdArray[ index * 4 + 1 ] = verletVertexColumns[ x + 1 ][ y ].id;
  324. verletVertexIdArray[ index * 4 + 2 ] = verletVertexColumns[ x ][ y + 1 ].id;
  325. verletVertexIdArray[ index * 4 + 3 ] = verletVertexColumns[ x + 1 ][ y + 1 ].id;
  326. if ( x > 0 && y > 0 ) {
  327. indices.push( getIndex( x, y ), getIndex( x - 1, y ), getIndex( x - 1, y - 1 ) );
  328. indices.push( getIndex( x, y ), getIndex( x - 1, y - 1 ), getIndex( x, y - 1 ) );
  329. }
  330. }
  331. }
  332. const verletVertexIdBuffer = new THREE.BufferAttribute( verletVertexIdArray, 4, false );
  333. const positionBuffer = new THREE.BufferAttribute( new Float32Array( vertexCount * 3 ), 3, false );
  334. geometry.setAttribute( 'position', positionBuffer );
  335. geometry.setAttribute( 'vertexIds', verletVertexIdBuffer );
  336. geometry.setIndex( indices );
  337. clothMaterial = new THREE.MeshPhysicalNodeMaterial( {
  338. color: new THREE.Color().setHex( API.color ),
  339. side: THREE.DoubleSide,
  340. transparent: true,
  341. opacity: 0.85,
  342. sheen: 1.0,
  343. sheenRoughness: 0.5,
  344. sheenColor: new THREE.Color().setHex( API.sheenColor ),
  345. } );
  346. clothMaterial.positionNode = Fn( ( { material } ) => {
  347. // gather the position of the 4 verlet vertices and calculate the center position and normal from that
  348. const vertexIds = attribute( 'vertexIds' );
  349. const v0 = vertexPositionBuffer.element( vertexIds.x ).toVar();
  350. const v1 = vertexPositionBuffer.element( vertexIds.y ).toVar();
  351. const v2 = vertexPositionBuffer.element( vertexIds.z ).toVar();
  352. const v3 = vertexPositionBuffer.element( vertexIds.w ).toVar();
  353. const top = v0.add( v1 );
  354. const right = v1.add( v3 );
  355. const bottom = v2.add( v3 );
  356. const left = v0.add( v2 );
  357. const tangent = right.sub( left ).normalize();
  358. const bitangent = bottom.sub( top ).normalize();
  359. const normal = cross( tangent, bitangent );
  360. // send the normalView from the vertex shader to the fragment shader
  361. material.normalNode = transformNormalToView( normal ).toVarying();
  362. return v0.add( v1 ).add( v2 ).add( v3 ).mul( 0.25 );
  363. } )();
  364. clothMesh = new THREE.Mesh( geometry, clothMaterial );
  365. clothMesh.frustumCulled = false;
  366. scene.add( clothMesh );
  367. }
  368. function setupCloth() {
  369. setupVerletGeometry();
  370. setupVerletVertexBuffers();
  371. setupVerletSpringBuffers();
  372. setupUniforms();
  373. setupComputeShaders();
  374. setupWireframe();
  375. setupSphere();
  376. setupClothMesh();
  377. }
  378. function onWindowResize() {
  379. camera.aspect = window.innerWidth / window.innerHeight;
  380. camera.updateProjectionMatrix();
  381. renderer.setSize( window.innerWidth, window.innerHeight );
  382. }
  383. function updateSphere() {
  384. sphere.position.set( Math.sin( timestamp * 2.1 ) * 0.1, 0, Math.sin( timestamp * 0.8 ) );
  385. spherePositionUniform.value.copy( sphere.position );
  386. }
  387. async function render() {
  388. sphere.visible = params.sphere;
  389. sphereUniform.value = params.sphere ? 1 : 0;
  390. windUniform.value = params.wind;
  391. clothMesh.visible = ! params.wireframe;
  392. vertexWireframeObject.visible = params.wireframe;
  393. springWireframeObject.visible = params.wireframe;
  394. const deltaTime = Math.min( clock.getDelta(), 1 / 60 ); // don't advance the time too far, for example when the window is out of focus
  395. const stepsPerSecond = 360; // ensure the same amount of simulation steps per second on all systems, independent of refresh rate
  396. const timePerStep = 1 / stepsPerSecond;
  397. timeSinceLastStep += deltaTime;
  398. while ( timeSinceLastStep >= timePerStep ) {
  399. // run a verlet system simulation step
  400. timestamp += timePerStep;
  401. timeSinceLastStep -= timePerStep;
  402. updateSphere();
  403. await renderer.computeAsync( computeSpringForces );
  404. await renderer.computeAsync( computeVertexForces );
  405. }
  406. await renderer.renderAsync( scene, camera );
  407. }
  408. </script>
  409. </body>
  410. </html>
粤ICP备19079148号