webgpu_compute_cloth.html 20 KB

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