webgl_physics_cloth.html 13 KB

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