webgpu_compute_cloth.html 19 KB

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