webgl_physics_cloth.html 13 KB

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