2
0

webgl_animation_cloth.html 14 KB

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