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