webgpu_compute_cloth.html 18 KB

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