webgl_physics_cloth.html 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  1. <html lang="en">
  2. <head>
  3. <title>Ammo.js softbody cloth demo</title>
  4. <meta charset="utf-8">
  5. <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
  6. <style>
  7. body {
  8. color: #61443e;
  9. font-family:Monospace;
  10. font-size:13px;
  11. text-align:center;
  12. background-color: #bfd1e5;
  13. margin: 0px;
  14. overflow: hidden;
  15. }
  16. #info {
  17. position: absolute;
  18. top: 0px; width: 100%;
  19. padding: 5px;
  20. }
  21. a {
  22. color: #a06851;
  23. }
  24. </style>
  25. </head>
  26. <body>
  27. <div id="info">Ammo.js physics soft body cloth demo<br>Press Q or A to move the arm.</div>
  28. <div id="container"><br /><br /><br /><br /><br />Loading...</div>
  29. <script src="../build/three.js"></script>
  30. <script src="js/libs/ammo.js"></script>
  31. <script src="js/controls/OrbitControls.js"></script>
  32. <script src="js/WebGL.js"></script>
  33. <script src="js/libs/stats.min.js"></script>
  34. <script>
  35. // Detects webgl
  36. if ( WEBGL.isWebGLAvailable() === false ) {
  37. document.body.appendChild( WEBGL.getWebGLErrorMessage() );
  38. document.getElementById( 'container' ).innerHTML = "";
  39. }
  40. // - Global variables -
  41. // Graphics variables
  42. var container, stats;
  43. var camera, controls, scene, renderer;
  44. var textureLoader;
  45. var clock = new THREE.Clock();
  46. // Physics variables
  47. var gravityConstant = -9.8;
  48. var physicsWorld;
  49. var rigidBodies = [];
  50. var margin = 0.05;
  51. var hinge;
  52. var cloth;
  53. var transformAux1 = new Ammo.btTransform();
  54. var time = 0;
  55. var armMovement = 0;
  56. // - Main code -
  57. init();
  58. animate();
  59. // - Functions -
  60. function init() {
  61. initGraphics();
  62. initPhysics();
  63. createObjects();
  64. initInput();
  65. }
  66. function initGraphics() {
  67. container = document.getElementById( 'container' );
  68. camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 0.2, 2000 );
  69. scene = new THREE.Scene();
  70. scene.background = new THREE.Color( 0xbfd1e5 );
  71. camera.position.set( -12, 7, 4 );
  72. controls = new THREE.OrbitControls( camera );
  73. controls.target.set( 0, 2, 0 );
  74. controls.update();
  75. renderer = new THREE.WebGLRenderer();
  76. renderer.setPixelRatio( window.devicePixelRatio );
  77. renderer.setSize( window.innerWidth, window.innerHeight );
  78. renderer.shadowMap.enabled = true;
  79. textureLoader = new THREE.TextureLoader();
  80. var ambientLight = new THREE.AmbientLight( 0x404040 );
  81. scene.add( ambientLight );
  82. var light = new THREE.DirectionalLight( 0xffffff, 1 );
  83. light.position.set( -7, 10, 15 );
  84. light.castShadow = true;
  85. var d = 10;
  86. light.shadow.camera.left = -d;
  87. light.shadow.camera.right = d;
  88. light.shadow.camera.top = d;
  89. light.shadow.camera.bottom = -d;
  90. light.shadow.camera.near = 2;
  91. light.shadow.camera.far = 50;
  92. light.shadow.mapSize.x = 1024;
  93. light.shadow.mapSize.y = 1024;
  94. light.shadow.bias = -0.003;
  95. scene.add( light );
  96. container.innerHTML = "";
  97. container.appendChild( renderer.domElement );
  98. stats = new Stats();
  99. stats.domElement.style.position = 'absolute';
  100. stats.domElement.style.top = '0px';
  101. container.appendChild( stats.domElement );
  102. window.addEventListener( 'resize', onWindowResize, false );
  103. }
  104. function initPhysics() {
  105. // Physics configuration
  106. var collisionConfiguration = new Ammo.btSoftBodyRigidBodyCollisionConfiguration();
  107. var dispatcher = new Ammo.btCollisionDispatcher( collisionConfiguration );
  108. var broadphase = new Ammo.btDbvtBroadphase();
  109. var solver = new Ammo.btSequentialImpulseConstraintSolver();
  110. var softBodySolver = new Ammo.btDefaultSoftBodySolver();
  111. physicsWorld = new Ammo.btSoftRigidDynamicsWorld( dispatcher, broadphase, solver, collisionConfiguration, softBodySolver);
  112. physicsWorld.setGravity( new Ammo.btVector3( 0, gravityConstant, 0 ) );
  113. physicsWorld.getWorldInfo().set_m_gravity( new Ammo.btVector3( 0, gravityConstant, 0 ) );
  114. }
  115. function createObjects() {
  116. var pos = new THREE.Vector3();
  117. var quat = new THREE.Quaternion();
  118. // Ground
  119. pos.set( 0, - 0.5, 0 );
  120. quat.set( 0, 0, 0, 1 );
  121. var ground = createParalellepiped( 40, 1, 40, 0, pos, quat, new THREE.MeshPhongMaterial( { color: 0xFFFFFF } ) );
  122. ground.castShadow = true;
  123. ground.receiveShadow = true;
  124. textureLoader.load( "textures/grid.png", function( texture ) {
  125. texture.wrapS = THREE.RepeatWrapping;
  126. texture.wrapT = THREE.RepeatWrapping;
  127. texture.repeat.set( 40, 40 );
  128. ground.material.map = texture;
  129. ground.material.needsUpdate = true;
  130. } );
  131. // Wall
  132. var brickMass = 0.5;
  133. var brickLength = 1.2;
  134. var brickDepth = 0.6;
  135. var brickHeight = brickLength * 0.5;
  136. var numBricksLength = 6;
  137. var numBricksHeight = 8;
  138. var z0 = - numBricksLength * brickLength * 0.5;
  139. pos.set( 0, brickHeight * 0.5, z0 );
  140. quat.set( 0, 0, 0, 1 );
  141. for ( var j = 0; j < numBricksHeight; j ++ ) {
  142. var oddRow = ( j % 2 ) == 1;
  143. pos.z = z0;
  144. if ( oddRow ) {
  145. pos.z -= 0.25 * brickLength;
  146. }
  147. var nRow = oddRow? numBricksLength + 1 : numBricksLength;
  148. for ( var i = 0; i < nRow; i ++ ) {
  149. var brickLengthCurrent = brickLength;
  150. var brickMassCurrent = brickMass;
  151. if ( oddRow && ( i == 0 || i == nRow - 1 ) ) {
  152. brickLengthCurrent *= 0.5;
  153. brickMassCurrent *= 0.5;
  154. }
  155. var brick = createParalellepiped( brickDepth, brickHeight, brickLengthCurrent, brickMassCurrent, pos, quat, createMaterial() );
  156. brick.castShadow = true;
  157. brick.receiveShadow = true;
  158. if ( oddRow && ( i == 0 || i == nRow - 2 ) ) {
  159. pos.z += 0.75 * brickLength;
  160. }
  161. else {
  162. pos.z += brickLength;
  163. }
  164. }
  165. pos.y += brickHeight;
  166. }
  167. // The cloth
  168. // Cloth graphic object
  169. var clothWidth = 4;
  170. var clothHeight = 3;
  171. var clothNumSegmentsZ = clothWidth * 5;
  172. var clothNumSegmentsY = clothHeight * 5;
  173. var clothSegmentLengthZ = clothWidth / clothNumSegmentsZ;
  174. var clothSegmentLengthY = clothHeight / clothNumSegmentsY;
  175. var clothPos = new THREE.Vector3( -3, 3, 2 );
  176. //var clothGeometry = new THREE.BufferGeometry();
  177. var clothGeometry = new THREE.PlaneBufferGeometry( clothWidth, clothHeight, clothNumSegmentsZ, clothNumSegmentsY );
  178. clothGeometry.rotateY( Math.PI * 0.5 );
  179. clothGeometry.translate( clothPos.x, clothPos.y + clothHeight * 0.5, clothPos.z - clothWidth * 0.5 );
  180. //var clothMaterial = new THREE.MeshLambertMaterial( { color: 0x0030A0, side: THREE.DoubleSide } );
  181. var clothMaterial = new THREE.MeshLambertMaterial( { color: 0xFFFFFF, side: THREE.DoubleSide } );
  182. cloth = new THREE.Mesh( clothGeometry, clothMaterial );
  183. cloth.castShadow = true;
  184. cloth.receiveShadow = true;
  185. scene.add( cloth );
  186. textureLoader.load( "textures/grid.png", function( texture ) {
  187. texture.wrapS = THREE.RepeatWrapping;
  188. texture.wrapT = THREE.RepeatWrapping;
  189. texture.repeat.set( clothNumSegmentsZ, clothNumSegmentsY );
  190. cloth.material.map = texture;
  191. cloth.material.needsUpdate = true;
  192. } );
  193. // Cloth physic object
  194. var softBodyHelpers = new Ammo.btSoftBodyHelpers();
  195. var clothCorner00 = new Ammo.btVector3( clothPos.x, clothPos.y + clothHeight, clothPos.z );
  196. var clothCorner01 = new Ammo.btVector3( clothPos.x, clothPos.y + clothHeight, clothPos.z - clothWidth );
  197. var clothCorner10 = new Ammo.btVector3( clothPos.x, clothPos.y, clothPos.z );
  198. var clothCorner11 = new Ammo.btVector3( clothPos.x, clothPos.y, clothPos.z - clothWidth );
  199. var clothSoftBody = softBodyHelpers.CreatePatch( physicsWorld.getWorldInfo(), clothCorner00, clothCorner01, clothCorner10, clothCorner11, clothNumSegmentsZ + 1, clothNumSegmentsY + 1, 0, true );
  200. var sbConfig = clothSoftBody.get_m_cfg();
  201. sbConfig.set_viterations( 10 );
  202. sbConfig.set_piterations( 10 );
  203. clothSoftBody.setTotalMass( 0.9, false );
  204. Ammo.castObject( clothSoftBody, Ammo.btCollisionObject ).getCollisionShape().setMargin( margin * 3 );
  205. physicsWorld.addSoftBody( clothSoftBody, 1, -1 );
  206. cloth.userData.physicsBody = clothSoftBody;
  207. // Disable deactivation
  208. clothSoftBody.setActivationState( 4 );
  209. // The base
  210. var armMass = 2;
  211. var armLength = 3 + clothWidth;
  212. var pylonHeight = clothPos.y + clothHeight;
  213. var baseMaterial = new THREE.MeshPhongMaterial( { color: 0x606060 } );
  214. pos.set( clothPos.x, 0.1, clothPos.z - armLength );
  215. quat.set( 0, 0, 0, 1 );
  216. var base = createParalellepiped( 1, 0.2, 1, 0, pos, quat, baseMaterial );
  217. base.castShadow = true;
  218. base.receiveShadow = true;
  219. pos.set( clothPos.x, 0.5 * pylonHeight, clothPos.z - armLength );
  220. var pylon = createParalellepiped( 0.4, pylonHeight, 0.4, 0, pos, quat, baseMaterial );
  221. pylon.castShadow = true;
  222. pylon.receiveShadow = true;
  223. pos.set( clothPos.x, pylonHeight + 0.2, clothPos.z - 0.5 * armLength );
  224. var arm = createParalellepiped( 0.4, 0.4, armLength + 0.4, armMass, pos, quat, baseMaterial );
  225. arm.castShadow = true;
  226. arm.receiveShadow = true;
  227. // Glue the cloth to the arm
  228. var influence = 0.5;
  229. clothSoftBody.appendAnchor( 0, arm.userData.physicsBody, false, influence );
  230. clothSoftBody.appendAnchor( clothNumSegmentsZ, arm.userData.physicsBody, false, influence );
  231. // Hinge constraint to move the arm
  232. var pivotA = new Ammo.btVector3( 0, pylonHeight * 0.5, 0 );
  233. var pivotB = new Ammo.btVector3( 0, -0.2, - armLength * 0.5 );
  234. var axis = new Ammo.btVector3( 0, 1, 0 );
  235. hinge = new Ammo.btHingeConstraint( pylon.userData.physicsBody, arm.userData.physicsBody, pivotA, pivotB, axis, axis, true );
  236. physicsWorld.addConstraint( hinge, true );
  237. }
  238. function createParalellepiped( sx, sy, sz, mass, pos, quat, material ) {
  239. var threeObject = new THREE.Mesh( new THREE.BoxBufferGeometry( sx, sy, sz, 1, 1, 1 ), material );
  240. var shape = new Ammo.btBoxShape( new Ammo.btVector3( sx * 0.5, sy * 0.5, sz * 0.5 ) );
  241. shape.setMargin( margin );
  242. createRigidBody( threeObject, shape, mass, pos, quat );
  243. return threeObject;
  244. }
  245. function createRigidBody( threeObject, physicsShape, mass, pos, quat ) {
  246. threeObject.position.copy( pos );
  247. threeObject.quaternion.copy( quat );
  248. var transform = new Ammo.btTransform();
  249. transform.setIdentity();
  250. transform.setOrigin( new Ammo.btVector3( pos.x, pos.y, pos.z ) );
  251. transform.setRotation( new Ammo.btQuaternion( quat.x, quat.y, quat.z, quat.w ) );
  252. var motionState = new Ammo.btDefaultMotionState( transform );
  253. var localInertia = new Ammo.btVector3( 0, 0, 0 );
  254. physicsShape.calculateLocalInertia( mass, localInertia );
  255. var rbInfo = new Ammo.btRigidBodyConstructionInfo( mass, motionState, physicsShape, localInertia );
  256. var body = new Ammo.btRigidBody( rbInfo );
  257. threeObject.userData.physicsBody = body;
  258. scene.add( threeObject );
  259. if ( mass > 0 ) {
  260. rigidBodies.push( threeObject );
  261. // Disable deactivation
  262. body.setActivationState( 4 );
  263. }
  264. physicsWorld.addRigidBody( body );
  265. }
  266. function createRandomColor() {
  267. return Math.floor( Math.random() * ( 1 << 24 ) );
  268. }
  269. function createMaterial() {
  270. return new THREE.MeshPhongMaterial( { color: createRandomColor() } );
  271. }
  272. function initInput() {
  273. window.addEventListener( 'keydown', function( event ) {
  274. switch ( event.keyCode ) {
  275. // Q
  276. case 81:
  277. armMovement = 1;
  278. break;
  279. // A
  280. case 65:
  281. armMovement = - 1;
  282. break;
  283. }
  284. }, false );
  285. window.addEventListener( 'keyup', function( event ) {
  286. armMovement = 0;
  287. }, false );
  288. }
  289. function onWindowResize() {
  290. camera.aspect = window.innerWidth / window.innerHeight;
  291. camera.updateProjectionMatrix();
  292. renderer.setSize( window.innerWidth, window.innerHeight );
  293. }
  294. function animate() {
  295. requestAnimationFrame( animate );
  296. render();
  297. stats.update();
  298. }
  299. function render() {
  300. var deltaTime = clock.getDelta();
  301. updatePhysics( deltaTime );
  302. renderer.render( scene, camera );
  303. time += deltaTime;
  304. }
  305. function updatePhysics( deltaTime ) {
  306. // Hinge control
  307. hinge.enableAngularMotor( true, 0.8 * armMovement, 50 );
  308. // Step world
  309. physicsWorld.stepSimulation( deltaTime, 10 );
  310. // Update cloth
  311. var softBody = cloth.userData.physicsBody;
  312. var clothPositions = cloth.geometry.attributes.position.array;
  313. var numVerts = clothPositions.length / 3;
  314. var nodes = softBody.get_m_nodes();
  315. var indexFloat = 0;
  316. for ( var i = 0; i < numVerts; i ++ ) {
  317. var node = nodes.at( i );
  318. var nodePos = node.get_m_x();
  319. clothPositions[ indexFloat++ ] = nodePos.x();
  320. clothPositions[ indexFloat++ ] = nodePos.y();
  321. clothPositions[ indexFloat++ ] = nodePos.z();
  322. }
  323. cloth.geometry.computeVertexNormals();
  324. cloth.geometry.attributes.position.needsUpdate = true;
  325. cloth.geometry.attributes.normal.needsUpdate = true;
  326. // Update rigid bodies
  327. for ( var i = 0, il = rigidBodies.length; i < il; i++ ) {
  328. var objThree = rigidBodies[ i ];
  329. var objPhys = objThree.userData.physicsBody;
  330. var ms = objPhys.getMotionState();
  331. if ( ms ) {
  332. ms.getWorldTransform( transformAux1 );
  333. var p = transformAux1.getOrigin();
  334. var q = transformAux1.getRotation();
  335. objThree.position.set( p.x(), p.y(), p.z() );
  336. objThree.quaternion.set( q.x(), q.y(), q.z(), q.w() );
  337. }
  338. }
  339. }
  340. </script>
  341. </body>
  342. </html>