2
0

webgl_physics_cloth.html 13 KB

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