webgl_animation_cloth.html 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648
  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. /*
  28. * Cloth Simulation using a relaxed constraints solver
  29. */
  30. // Suggested Readings
  31. // Advanced Character Physics by Thomas Jakobsen Character
  32. // http://freespace.virgin.net/hugo.elias/models/m_cloth.htm
  33. // http://en.wikipedia.org/wiki/Cloth_modeling
  34. // http://cg.alexandra.dk/tag/spring-mass-system/
  35. // Real-time Cloth Animation http://www.darwin3d.com/gamedev/articles/col0599.pdf
  36. var params = {
  37. enableWind: true,
  38. showBall: false,
  39. tooglePins: togglePins
  40. };
  41. var DAMPING = 0.03;
  42. var DRAG = 1 - DAMPING;
  43. var MASS = 0.1;
  44. var restDistance = 25;
  45. var xSegs = 10;
  46. var ySegs = 10;
  47. var clothFunction = plane( restDistance * xSegs, restDistance * ySegs );
  48. var cloth = new Cloth( xSegs, ySegs );
  49. var GRAVITY = 981 * 1.4;
  50. var gravity = new THREE.Vector3( 0, - GRAVITY, 0 ).multiplyScalar( MASS );
  51. var TIMESTEP = 18 / 1000;
  52. var TIMESTEP_SQ = TIMESTEP * TIMESTEP;
  53. var pins = [];
  54. var windForce = new THREE.Vector3( 0, 0, 0 );
  55. var ballPosition = new THREE.Vector3( 0, - 45, 0 );
  56. var ballSize = 60; //40
  57. var tmpForce = new THREE.Vector3();
  58. var lastTime;
  59. function plane( width, height ) {
  60. return function ( u, v, target ) {
  61. var x = ( u - 0.5 ) * width;
  62. var y = ( v + 0.5 ) * height;
  63. var z = 0;
  64. target.set( x, y, z );
  65. };
  66. }
  67. function Particle( x, y, z, mass ) {
  68. this.position = new THREE.Vector3();
  69. this.previous = new THREE.Vector3();
  70. this.original = new THREE.Vector3();
  71. this.a = new THREE.Vector3( 0, 0, 0 ); // acceleration
  72. this.mass = mass;
  73. this.invMass = 1 / mass;
  74. this.tmp = new THREE.Vector3();
  75. this.tmp2 = new THREE.Vector3();
  76. // init
  77. clothFunction( x, y, this.position ); // position
  78. clothFunction( x, y, this.previous ); // previous
  79. clothFunction( x, y, this.original );
  80. }
  81. // Force -> Acceleration
  82. Particle.prototype.addForce = function ( force ) {
  83. this.a.add(
  84. this.tmp2.copy( force ).multiplyScalar( this.invMass )
  85. );
  86. };
  87. // Performs Verlet integration
  88. Particle.prototype.integrate = function ( timesq ) {
  89. var newPos = this.tmp.subVectors( this.position, this.previous );
  90. newPos.multiplyScalar( DRAG ).add( this.position );
  91. newPos.add( this.a.multiplyScalar( timesq ) );
  92. this.tmp = this.previous;
  93. this.previous = this.position;
  94. this.position = newPos;
  95. this.a.set( 0, 0, 0 );
  96. };
  97. var diff = new THREE.Vector3();
  98. function satisfyConstraints( p1, p2, distance ) {
  99. diff.subVectors( p2.position, p1.position );
  100. var currentDist = diff.length();
  101. if ( currentDist === 0 ) return; // prevents division by 0
  102. var correction = diff.multiplyScalar( 1 - distance / currentDist );
  103. var correctionHalf = correction.multiplyScalar( 0.5 );
  104. p1.position.add( correctionHalf );
  105. p2.position.sub( correctionHalf );
  106. }
  107. function Cloth( w, h ) {
  108. w = w || 10;
  109. h = h || 10;
  110. this.w = w;
  111. this.h = h;
  112. var particles = [];
  113. var constraints = [];
  114. var u, v;
  115. // Create particles
  116. for ( v = 0; v <= h; v ++ ) {
  117. for ( u = 0; u <= w; u ++ ) {
  118. particles.push(
  119. new Particle( u / w, v / h, 0, MASS )
  120. );
  121. }
  122. }
  123. // Structural
  124. for ( v = 0; v < h; v ++ ) {
  125. for ( u = 0; u < w; u ++ ) {
  126. constraints.push( [
  127. particles[ index( u, v ) ],
  128. particles[ index( u, v + 1 ) ],
  129. restDistance
  130. ] );
  131. constraints.push( [
  132. particles[ index( u, v ) ],
  133. particles[ index( u + 1, v ) ],
  134. restDistance
  135. ] );
  136. }
  137. }
  138. for ( u = w, v = 0; v < h; v ++ ) {
  139. constraints.push( [
  140. particles[ index( u, v ) ],
  141. particles[ index( u, v + 1 ) ],
  142. restDistance
  143. ] );
  144. }
  145. for ( v = h, u = 0; u < w; u ++ ) {
  146. constraints.push( [
  147. particles[ index( u, v ) ],
  148. particles[ index( u + 1, v ) ],
  149. restDistance
  150. ] );
  151. }
  152. // While many systems use shear and bend springs,
  153. // the relaxed constraints model seems to be just fine
  154. // using structural springs.
  155. // Shear
  156. // var diagonalDist = Math.sqrt(restDistance * restDistance * 2);
  157. // for (v=0;v<h;v++) {
  158. // for (u=0;u<w;u++) {
  159. // constraints.push([
  160. // particles[index(u, v)],
  161. // particles[index(u+1, v+1)],
  162. // diagonalDist
  163. // ]);
  164. // constraints.push([
  165. // particles[index(u+1, v)],
  166. // particles[index(u, v+1)],
  167. // diagonalDist
  168. // ]);
  169. // }
  170. // }
  171. this.particles = particles;
  172. this.constraints = constraints;
  173. function index( u, v ) {
  174. return u + v * ( w + 1 );
  175. }
  176. this.index = index;
  177. }
  178. function simulate( time ) {
  179. if ( ! lastTime ) {
  180. lastTime = time;
  181. return;
  182. }
  183. var i, j, il, particles, particle, constraints, constraint;
  184. // Aerodynamics forces
  185. if ( params.enableWind ) {
  186. var indx;
  187. var normal = new THREE.Vector3();
  188. var indices = clothGeometry.index;
  189. var normals = clothGeometry.attributes.normal;
  190. particles = cloth.particles;
  191. for ( i = 0, il = indices.count; i < il; i += 3 ) {
  192. for ( j = 0; j < 3; j ++ ) {
  193. indx = indices.getX( i + j );
  194. normal.fromBufferAttribute( normals, indx );
  195. tmpForce.copy( normal ).normalize().multiplyScalar( normal.dot( windForce ) );
  196. particles[ indx ].addForce( tmpForce );
  197. }
  198. }
  199. }
  200. for ( particles = cloth.particles, i = 0, il = particles.length; i < il; i ++ ) {
  201. particle = particles[ i ];
  202. particle.addForce( gravity );
  203. particle.integrate( TIMESTEP_SQ );
  204. }
  205. // Start Constraints
  206. constraints = cloth.constraints;
  207. il = constraints.length;
  208. for ( i = 0; i < il; i ++ ) {
  209. constraint = constraints[ i ];
  210. satisfyConstraints( constraint[ 0 ], constraint[ 1 ], constraint[ 2 ] );
  211. }
  212. // Ball Constraints
  213. ballPosition.z = - Math.sin( Date.now() / 600 ) * 90; //+ 40;
  214. ballPosition.x = Math.cos( Date.now() / 400 ) * 70;
  215. if ( params.showBall ) {
  216. sphere.visible = true;
  217. for ( particles = cloth.particles, i = 0, il = particles.length; i < il; i ++ ) {
  218. particle = particles[ i ];
  219. var pos = particle.position;
  220. diff.subVectors( pos, ballPosition );
  221. if ( diff.length() < ballSize ) {
  222. // collided
  223. diff.normalize().multiplyScalar( ballSize );
  224. pos.copy( ballPosition ).add( diff );
  225. }
  226. }
  227. } else {
  228. sphere.visible = false;
  229. }
  230. // Floor Constraints
  231. for ( particles = cloth.particles, i = 0, il = particles.length; i < il; i ++ ) {
  232. particle = particles[ i ];
  233. pos = particle.position;
  234. if ( pos.y < - 250 ) {
  235. pos.y = - 250;
  236. }
  237. }
  238. // Pin Constraints
  239. for ( i = 0, il = pins.length; i < il; i ++ ) {
  240. var xy = pins[ i ];
  241. var p = particles[ xy ];
  242. p.position.copy( p.original );
  243. p.previous.copy( p.original );
  244. }
  245. }
  246. /* testing cloth simulation */
  247. var pinsFormation = [];
  248. var 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. var container, stats;
  263. var camera, scene, renderer;
  264. var clothGeometry;
  265. var sphere;
  266. var object;
  267. init();
  268. animate();
  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. var 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. var 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. var loader = new THREE.TextureLoader();
  296. var clothTexture = loader.load( 'textures/patterns/circuit_pattern.png' );
  297. clothTexture.anisotropy = 16;
  298. var clothMaterial = new THREE.MeshLambertMaterial( {
  299. map: clothTexture,
  300. side: THREE.DoubleSide,
  301. alphaTest: 0.5
  302. } );
  303. // cloth geometry
  304. clothGeometry = new THREE.ParametricBufferGeometry( 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. object.customDepthMaterial = new THREE.MeshDepthMaterial( {
  311. depthPacking: THREE.RGBADepthPacking,
  312. map: clothTexture,
  313. alphaTest: 0.5
  314. } );
  315. // sphere
  316. var ballGeo = new THREE.SphereBufferGeometry( ballSize, 32, 16 );
  317. var ballMaterial = new THREE.MeshLambertMaterial();
  318. sphere = new THREE.Mesh( ballGeo, ballMaterial );
  319. sphere.castShadow = true;
  320. sphere.receiveShadow = true;
  321. sphere.visible = false;
  322. scene.add( sphere );
  323. // ground
  324. var groundTexture = loader.load( 'textures/terrain/grasslight-big.jpg' );
  325. groundTexture.wrapS = groundTexture.wrapT = THREE.RepeatWrapping;
  326. groundTexture.repeat.set( 25, 25 );
  327. groundTexture.anisotropy = 16;
  328. groundTexture.encoding = THREE.sRGBEncoding;
  329. var groundMaterial = new THREE.MeshLambertMaterial( { map: groundTexture } );
  330. var mesh = new THREE.Mesh( new THREE.PlaneBufferGeometry( 20000, 20000 ), groundMaterial );
  331. mesh.position.y = - 250;
  332. mesh.rotation.x = - Math.PI / 2;
  333. mesh.receiveShadow = true;
  334. scene.add( mesh );
  335. // poles
  336. var poleGeo = new THREE.BoxBufferGeometry( 5, 375, 5 );
  337. var poleMat = new THREE.MeshLambertMaterial();
  338. var mesh = new THREE.Mesh( poleGeo, poleMat );
  339. mesh.position.x = - 125;
  340. mesh.position.y = - 62;
  341. mesh.receiveShadow = true;
  342. mesh.castShadow = true;
  343. scene.add( mesh );
  344. var mesh = new THREE.Mesh( poleGeo, poleMat );
  345. mesh.position.x = 125;
  346. mesh.position.y = - 62;
  347. mesh.receiveShadow = true;
  348. mesh.castShadow = true;
  349. scene.add( mesh );
  350. var mesh = new THREE.Mesh( new THREE.BoxBufferGeometry( 255, 5, 5 ), poleMat );
  351. mesh.position.y = - 250 + ( 750 / 2 );
  352. mesh.position.x = 0;
  353. mesh.receiveShadow = true;
  354. mesh.castShadow = true;
  355. scene.add( mesh );
  356. var gg = new THREE.BoxBufferGeometry( 10, 10, 10 );
  357. var mesh = new THREE.Mesh( gg, poleMat );
  358. mesh.position.y = - 250;
  359. mesh.position.x = 125;
  360. mesh.receiveShadow = true;
  361. mesh.castShadow = true;
  362. scene.add( mesh );
  363. var mesh = new THREE.Mesh( gg, poleMat );
  364. mesh.position.y = - 250;
  365. mesh.position.x = - 125;
  366. mesh.receiveShadow = true;
  367. mesh.castShadow = true;
  368. scene.add( mesh );
  369. // renderer
  370. renderer = new THREE.WebGLRenderer( { antialias: true } );
  371. renderer.setPixelRatio( window.devicePixelRatio );
  372. renderer.setSize( window.innerWidth, window.innerHeight );
  373. container.appendChild( renderer.domElement );
  374. renderer.outputEncoding = THREE.sRGBEncoding;
  375. renderer.shadowMap.enabled = true;
  376. // controls
  377. var controls = new OrbitControls( camera, renderer.domElement );
  378. controls.maxPolarAngle = Math.PI * 0.5;
  379. controls.minDistance = 1000;
  380. controls.maxDistance = 5000;
  381. // performance monitor
  382. stats = new Stats();
  383. container.appendChild( stats.dom );
  384. //
  385. window.addEventListener( 'resize', onWindowResize, false );
  386. //
  387. var gui = new GUI();
  388. gui.add( params, 'enableWind' );
  389. gui.add( params, 'showBall' );
  390. gui.add( params, 'tooglePins' );
  391. }
  392. //
  393. function onWindowResize() {
  394. camera.aspect = window.innerWidth / window.innerHeight;
  395. camera.updateProjectionMatrix();
  396. renderer.setSize( window.innerWidth, window.innerHeight );
  397. }
  398. //
  399. function animate() {
  400. requestAnimationFrame( animate );
  401. var time = Date.now();
  402. var windStrength = Math.cos( time / 7000 ) * 20 + 40;
  403. windForce.set( Math.sin( time / 2000 ), Math.cos( time / 3000 ), Math.sin( time / 1000 ) );
  404. windForce.normalize();
  405. windForce.multiplyScalar( windStrength );
  406. simulate( time );
  407. render();
  408. stats.update();
  409. }
  410. function render() {
  411. var p = cloth.particles;
  412. for ( var i = 0, il = p.length; i < il; i ++ ) {
  413. var v = p[ i ].position;
  414. clothGeometry.attributes.position.setXYZ( i, v.x, v.y, v.z );
  415. }
  416. clothGeometry.attributes.position.needsUpdate = true;
  417. clothGeometry.computeVertexNormals();
  418. sphere.position.copy( ballPosition );
  419. renderer.render( scene, camera );
  420. }
  421. </script>
  422. </body>
  423. </html>