webgpu_compute_cloth.html 20 KB

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