webgl_animation_cloth.html 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>three.js webgl - cloth simulation</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. <style>
  9. body {
  10. background-color: #cce0ff;
  11. color: #000;
  12. }
  13. a {
  14. color: #080;
  15. }
  16. </style>
  17. </head>
  18. <body>
  19. <div id="info">Simple Cloth Simulation<br/>
  20. Verlet integration with relaxed constraints<br/>
  21. </div>
  22. <script type="module">
  23. import * as THREE from '../build/three.module.js';
  24. import Stats from './jsm/libs/stats.module.js';
  25. import { GUI } from './jsm/libs/dat.gui.module.js';
  26. import { OrbitControls } from './jsm/controls/OrbitControls.js';
  27. import { ParametricGeometry } from './jsm/geometries/ParametricGeometry.js';
  28. /*
  29. * Cloth Simulation using a relaxed constraints solver
  30. */
  31. // Suggested Readings
  32. // Advanced Character Physics by Thomas Jakobsen Character
  33. // http://freespace.virgin.net/hugo.elias/models/m_cloth.htm
  34. // http://en.wikipedia.org/wiki/Cloth_modeling
  35. // http://cg.alexandra.dk/tag/spring-mass-system/
  36. // Real-time Cloth Animation http://www.darwin3d.com/gamedev/articles/col0599.pdf
  37. const params = {
  38. enableWind: true,
  39. showBall: false,
  40. togglePins: togglePins
  41. };
  42. const DAMPING = 0.03;
  43. const DRAG = 1 - DAMPING;
  44. const MASS = 0.1;
  45. const restDistance = 25;
  46. const xSegs = 10;
  47. const ySegs = 10;
  48. const clothFunction = plane( restDistance * xSegs, restDistance * ySegs );
  49. const GRAVITY = 981 * 1.4;
  50. const gravity = new THREE.Vector3( 0, - GRAVITY, 0 ).multiplyScalar( MASS );
  51. const TIMESTEP = 18 / 1000;
  52. const TIMESTEP_SQ = TIMESTEP * TIMESTEP;
  53. let pins = [];
  54. const windForce = new THREE.Vector3( 0, 0, 0 );
  55. const ballPosition = new THREE.Vector3( 0, - 45, 0 );
  56. const ballSize = 60; //40
  57. const tmpForce = new THREE.Vector3();
  58. const diff = new THREE.Vector3();
  59. class Particle {
  60. constructor( x, y, z, mass ) {
  61. this.position = new THREE.Vector3();
  62. this.previous = new THREE.Vector3();
  63. this.original = new THREE.Vector3();
  64. this.a = new THREE.Vector3( 0, 0, 0 ); // acceleration
  65. this.mass = mass;
  66. this.invMass = 1 / mass;
  67. this.tmp = new THREE.Vector3();
  68. this.tmp2 = new THREE.Vector3();
  69. // init
  70. clothFunction( x, y, this.position ); // position
  71. clothFunction( x, y, this.previous ); // previous
  72. clothFunction( x, y, this.original );
  73. }
  74. // Force -> Acceleration
  75. addForce( force ) {
  76. this.a.add(
  77. this.tmp2.copy( force ).multiplyScalar( this.invMass )
  78. );
  79. }
  80. // Performs Verlet integration
  81. integrate( timesq ) {
  82. const newPos = this.tmp.subVectors( this.position, this.previous );
  83. newPos.multiplyScalar( DRAG ).add( this.position );
  84. newPos.add( this.a.multiplyScalar( timesq ) );
  85. this.tmp = this.previous;
  86. this.previous = this.position;
  87. this.position = newPos;
  88. this.a.set( 0, 0, 0 );
  89. }
  90. }
  91. class Cloth {
  92. constructor( w = 10, h = 10 ) {
  93. this.w = w;
  94. this.h = h;
  95. const particles = [];
  96. const constraints = [];
  97. // Create particles
  98. for ( let v = 0; v <= h; v ++ ) {
  99. for ( let u = 0; u <= w; u ++ ) {
  100. particles.push(
  101. new Particle( u / w, v / h, 0, MASS )
  102. );
  103. }
  104. }
  105. // Structural
  106. for ( let v = 0; v < h; v ++ ) {
  107. for ( let u = 0; u < w; u ++ ) {
  108. constraints.push( [
  109. particles[ index( u, v ) ],
  110. particles[ index( u, v + 1 ) ],
  111. restDistance
  112. ] );
  113. constraints.push( [
  114. particles[ index( u, v ) ],
  115. particles[ index( u + 1, v ) ],
  116. restDistance
  117. ] );
  118. }
  119. }
  120. for ( let u = w, v = 0; v < h; v ++ ) {
  121. constraints.push( [
  122. particles[ index( u, v ) ],
  123. particles[ index( u, v + 1 ) ],
  124. restDistance
  125. ] );
  126. }
  127. for ( let v = h, u = 0; u < w; u ++ ) {
  128. constraints.push( [
  129. particles[ index( u, v ) ],
  130. particles[ index( u + 1, v ) ],
  131. restDistance
  132. ] );
  133. }
  134. // While many systems use shear and bend springs,
  135. // the relaxed constraints model seems to be just fine
  136. // using structural springs.
  137. // Shear
  138. // const diagonalDist = Math.sqrt(restDistance * restDistance * 2);
  139. // for (v=0;v<h;v++) {
  140. // for (u=0;u<w;u++) {
  141. // constraints.push([
  142. // particles[index(u, v)],
  143. // particles[index(u+1, v+1)],
  144. // diagonalDist
  145. // ]);
  146. // constraints.push([
  147. // particles[index(u+1, v)],
  148. // particles[index(u, v+1)],
  149. // diagonalDist
  150. // ]);
  151. // }
  152. // }
  153. this.particles = particles;
  154. this.constraints = constraints;
  155. function index( u, v ) {
  156. return u + v * ( w + 1 );
  157. }
  158. this.index = index;
  159. }
  160. }
  161. function plane( width, height ) {
  162. return function ( u, v, target ) {
  163. const x = ( u - 0.5 ) * width;
  164. const y = ( v + 0.5 ) * height;
  165. const z = 0;
  166. target.set( x, y, z );
  167. };
  168. }
  169. function satisfyConstraints( p1, p2, distance ) {
  170. diff.subVectors( p2.position, p1.position );
  171. const currentDist = diff.length();
  172. if ( currentDist === 0 ) return; // prevents division by 0
  173. const correction = diff.multiplyScalar( 1 - distance / currentDist );
  174. const correctionHalf = correction.multiplyScalar( 0.5 );
  175. p1.position.add( correctionHalf );
  176. p2.position.sub( correctionHalf );
  177. }
  178. function simulate( now ) {
  179. const windStrength = Math.cos( now / 7000 ) * 20 + 40;
  180. windForce.set( Math.sin( now / 2000 ), Math.cos( now / 3000 ), Math.sin( now / 1000 ) );
  181. windForce.normalize();
  182. windForce.multiplyScalar( windStrength );
  183. // Aerodynamics forces
  184. const particles = cloth.particles;
  185. if ( params.enableWind ) {
  186. let indx;
  187. const normal = new THREE.Vector3();
  188. const indices = clothGeometry.index;
  189. const normals = clothGeometry.attributes.normal;
  190. for ( let i = 0, il = indices.count; i < il; i += 3 ) {
  191. for ( let j = 0; j < 3; j ++ ) {
  192. indx = indices.getX( i + j );
  193. normal.fromBufferAttribute( normals, indx );
  194. tmpForce.copy( normal ).normalize().multiplyScalar( normal.dot( windForce ) );
  195. particles[ indx ].addForce( tmpForce );
  196. }
  197. }
  198. }
  199. for ( let i = 0, il = particles.length; i < il; i ++ ) {
  200. const particle = particles[ i ];
  201. particle.addForce( gravity );
  202. particle.integrate( TIMESTEP_SQ );
  203. }
  204. // Start Constraints
  205. const constraints = cloth.constraints;
  206. const il = constraints.length;
  207. for ( let i = 0; i < il; i ++ ) {
  208. const constraint = constraints[ i ];
  209. satisfyConstraints( constraint[ 0 ], constraint[ 1 ], constraint[ 2 ] );
  210. }
  211. // Ball Constraints
  212. ballPosition.z = - Math.sin( now / 600 ) * 90; //+ 40;
  213. ballPosition.x = Math.cos( now / 400 ) * 70;
  214. if ( params.showBall ) {
  215. sphere.visible = true;
  216. for ( let i = 0, il = particles.length; i < il; i ++ ) {
  217. const particle = particles[ i ];
  218. const pos = particle.position;
  219. diff.subVectors( pos, ballPosition );
  220. if ( diff.length() < ballSize ) {
  221. // collided
  222. diff.normalize().multiplyScalar( ballSize );
  223. pos.copy( ballPosition ).add( diff );
  224. }
  225. }
  226. } else {
  227. sphere.visible = false;
  228. }
  229. // Floor Constraints
  230. for ( let i = 0, il = particles.length; i < il; i ++ ) {
  231. const particle = particles[ i ];
  232. const pos = particle.position;
  233. if ( pos.y < - 250 ) {
  234. pos.y = - 250;
  235. }
  236. }
  237. // Pin Constraints
  238. for ( let i = 0, il = pins.length; i < il; i ++ ) {
  239. const xy = pins[ i ];
  240. const p = particles[ xy ];
  241. p.position.copy( p.original );
  242. p.previous.copy( p.original );
  243. }
  244. }
  245. /* testing cloth simulation */
  246. const cloth = new Cloth( xSegs, ySegs );
  247. const pinsFormation = [];
  248. pins = [ 6 ];
  249. pinsFormation.push( pins );
  250. pins = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ];
  251. pinsFormation.push( pins );
  252. pins = [ 0 ];
  253. pinsFormation.push( pins );
  254. pins = []; // cut the rope ;)
  255. pinsFormation.push( pins );
  256. pins = [ 0, cloth.w ]; // classic 2 pins
  257. pinsFormation.push( pins );
  258. pins = pinsFormation[ 1 ];
  259. function togglePins() {
  260. pins = pinsFormation[ ~ ~ ( Math.random() * pinsFormation.length ) ];
  261. }
  262. let container, stats;
  263. let camera, scene, renderer;
  264. let clothGeometry;
  265. let sphere;
  266. let object;
  267. init();
  268. animate( 0 );
  269. function init() {
  270. container = document.createElement( 'div' );
  271. document.body.appendChild( container );
  272. // scene
  273. scene = new THREE.Scene();
  274. scene.background = new THREE.Color( 0xcce0ff );
  275. scene.fog = new THREE.Fog( 0xcce0ff, 500, 10000 );
  276. // camera
  277. camera = new THREE.PerspectiveCamera( 30, window.innerWidth / window.innerHeight, 1, 10000 );
  278. camera.position.set( 1000, 50, 1500 );
  279. // lights
  280. scene.add( new THREE.AmbientLight( 0x666666 ) );
  281. const light = new THREE.DirectionalLight( 0xdfebff, 1 );
  282. light.position.set( 50, 200, 100 );
  283. light.position.multiplyScalar( 1.3 );
  284. light.castShadow = true;
  285. light.shadow.mapSize.width = 1024;
  286. light.shadow.mapSize.height = 1024;
  287. const d = 300;
  288. light.shadow.camera.left = - d;
  289. light.shadow.camera.right = d;
  290. light.shadow.camera.top = d;
  291. light.shadow.camera.bottom = - d;
  292. light.shadow.camera.far = 1000;
  293. scene.add( light );
  294. // cloth material
  295. const loader = new THREE.TextureLoader();
  296. const clothTexture = loader.load( 'textures/patterns/circuit_pattern.png' );
  297. clothTexture.anisotropy = 16;
  298. const clothMaterial = new THREE.MeshLambertMaterial( {
  299. alphaMap: clothTexture,
  300. side: THREE.DoubleSide,
  301. alphaTest: 0.5
  302. } );
  303. // cloth geometry
  304. clothGeometry = new ParametricGeometry( clothFunction, cloth.w, cloth.h );
  305. // cloth mesh
  306. object = new THREE.Mesh( clothGeometry, clothMaterial );
  307. object.position.set( 0, 0, 0 );
  308. object.castShadow = true;
  309. scene.add( object );
  310. // sphere
  311. const ballGeo = new THREE.SphereGeometry( ballSize, 32, 16 );
  312. const ballMaterial = new THREE.MeshLambertMaterial();
  313. sphere = new THREE.Mesh( ballGeo, ballMaterial );
  314. sphere.castShadow = true;
  315. sphere.receiveShadow = true;
  316. sphere.visible = false;
  317. scene.add( sphere );
  318. // ground
  319. const groundTexture = loader.load( 'textures/terrain/grasslight-big.jpg' );
  320. groundTexture.wrapS = groundTexture.wrapT = THREE.RepeatWrapping;
  321. groundTexture.repeat.set( 25, 25 );
  322. groundTexture.anisotropy = 16;
  323. groundTexture.encoding = THREE.sRGBEncoding;
  324. const groundMaterial = new THREE.MeshLambertMaterial( { map: groundTexture } );
  325. let mesh = new THREE.Mesh( new THREE.PlaneGeometry( 20000, 20000 ), groundMaterial );
  326. mesh.position.y = - 250;
  327. mesh.rotation.x = - Math.PI / 2;
  328. mesh.receiveShadow = true;
  329. scene.add( mesh );
  330. // poles
  331. const poleGeo = new THREE.BoxGeometry( 5, 375, 5 );
  332. const poleMat = new THREE.MeshLambertMaterial();
  333. mesh = new THREE.Mesh( poleGeo, poleMat );
  334. mesh.position.x = - 125;
  335. mesh.position.y = - 62;
  336. mesh.receiveShadow = true;
  337. mesh.castShadow = true;
  338. scene.add( mesh );
  339. mesh = new THREE.Mesh( poleGeo, poleMat );
  340. mesh.position.x = 125;
  341. mesh.position.y = - 62;
  342. mesh.receiveShadow = true;
  343. mesh.castShadow = true;
  344. scene.add( mesh );
  345. mesh = new THREE.Mesh( new THREE.BoxGeometry( 255, 5, 5 ), poleMat );
  346. mesh.position.y = - 250 + ( 750 / 2 );
  347. mesh.position.x = 0;
  348. mesh.receiveShadow = true;
  349. mesh.castShadow = true;
  350. scene.add( mesh );
  351. const gg = new THREE.BoxGeometry( 10, 10, 10 );
  352. mesh = new THREE.Mesh( gg, poleMat );
  353. mesh.position.y = - 250;
  354. mesh.position.x = 125;
  355. mesh.receiveShadow = true;
  356. mesh.castShadow = true;
  357. scene.add( mesh );
  358. mesh = new THREE.Mesh( gg, poleMat );
  359. mesh.position.y = - 250;
  360. mesh.position.x = - 125;
  361. mesh.receiveShadow = true;
  362. mesh.castShadow = true;
  363. scene.add( mesh );
  364. // renderer
  365. renderer = new THREE.WebGLRenderer( { antialias: true } );
  366. renderer.setPixelRatio( window.devicePixelRatio );
  367. renderer.setSize( window.innerWidth, window.innerHeight );
  368. container.appendChild( renderer.domElement );
  369. renderer.outputEncoding = THREE.sRGBEncoding;
  370. renderer.shadowMap.enabled = true;
  371. // controls
  372. const controls = new OrbitControls( camera, renderer.domElement );
  373. controls.maxPolarAngle = Math.PI * 0.5;
  374. controls.minDistance = 1000;
  375. controls.maxDistance = 5000;
  376. // performance monitor
  377. stats = new Stats();
  378. container.appendChild( stats.dom );
  379. //
  380. window.addEventListener( 'resize', onWindowResize );
  381. //
  382. const gui = new GUI();
  383. gui.add( params, 'enableWind' ).name( 'Enable wind' );
  384. gui.add( params, 'showBall' ).name( 'Show ball' );
  385. gui.add( params, 'togglePins' ).name( 'Toggle pins' );
  386. }
  387. //
  388. function onWindowResize() {
  389. camera.aspect = window.innerWidth / window.innerHeight;
  390. camera.updateProjectionMatrix();
  391. renderer.setSize( window.innerWidth, window.innerHeight );
  392. }
  393. //
  394. function animate( now ) {
  395. requestAnimationFrame( animate );
  396. simulate( now );
  397. render();
  398. stats.update();
  399. }
  400. function render() {
  401. const p = cloth.particles;
  402. for ( let i = 0, il = p.length; i < il; i ++ ) {
  403. const v = p[ i ].position;
  404. clothGeometry.attributes.position.setXYZ( i, v.x, v.y, v.z );
  405. }
  406. clothGeometry.attributes.position.needsUpdate = true;
  407. clothGeometry.computeVertexNormals();
  408. sphere.position.copy( ballPosition );
  409. renderer.render( scene, camera );
  410. }
  411. </script>
  412. </body>
  413. </html>