physics_ammo_cloth.html 13 KB

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