1
0

physics_ammo_cloth.html 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  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. <script type="importmap">
  18. {
  19. "imports": {
  20. "three": "../build/three.module.js",
  21. "three/addons/": "./jsm/"
  22. }
  23. }
  24. </script>
  25. <script type="module">
  26. import * as THREE from 'three';
  27. import Stats from 'three/addons/libs/stats.module.js';
  28. import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
  29. // Graphics variables
  30. let container, stats;
  31. let camera, controls, scene, renderer;
  32. let textureLoader;
  33. const clock = new THREE.Clock();
  34. // Physics variables
  35. const gravityConstant = - 9.8;
  36. let physicsWorld;
  37. const rigidBodies = [];
  38. const margin = 0.05;
  39. let hinge;
  40. let cloth;
  41. let transformAux1;
  42. let armMovement = 0;
  43. Ammo().then( function ( AmmoLib ) {
  44. Ammo = AmmoLib;
  45. init();
  46. } );
  47. function init() {
  48. initGraphics();
  49. initPhysics();
  50. createObjects();
  51. initInput();
  52. }
  53. function initGraphics() {
  54. container = document.getElementById( 'container' );
  55. camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 0.2, 2000 );
  56. scene = new THREE.Scene();
  57. scene.background = new THREE.Color( 0xbfd1e5 );
  58. camera.position.set( - 12, 7, 4 );
  59. renderer = new THREE.WebGLRenderer( { antialias: true } );
  60. renderer.setPixelRatio( window.devicePixelRatio );
  61. renderer.setSize( window.innerWidth, window.innerHeight );
  62. renderer.setAnimationLoop( animate );
  63. renderer.shadowMap.enabled = true;
  64. container.appendChild( renderer.domElement );
  65. controls = new OrbitControls( camera, renderer.domElement );
  66. controls.target.set( 0, 2, 0 );
  67. controls.update();
  68. textureLoader = new THREE.TextureLoader();
  69. const ambientLight = new THREE.AmbientLight( 0xbbbbbb );
  70. scene.add( ambientLight );
  71. const light = new THREE.DirectionalLight( 0xffffff, 3 );
  72. light.position.set( - 7, 10, 15 );
  73. light.castShadow = true;
  74. const d = 10;
  75. light.shadow.camera.left = - d;
  76. light.shadow.camera.right = d;
  77. light.shadow.camera.top = d;
  78. light.shadow.camera.bottom = - d;
  79. light.shadow.camera.near = 2;
  80. light.shadow.camera.far = 50;
  81. light.shadow.mapSize.x = 1024;
  82. light.shadow.mapSize.y = 1024;
  83. light.shadow.bias = - 0.003;
  84. scene.add( light );
  85. stats = new Stats();
  86. stats.domElement.style.position = 'absolute';
  87. stats.domElement.style.top = '0px';
  88. container.appendChild( stats.domElement );
  89. window.addEventListener( 'resize', onWindowResize );
  90. }
  91. function initPhysics() {
  92. // Physics configuration
  93. const collisionConfiguration = new Ammo.btSoftBodyRigidBodyCollisionConfiguration();
  94. const dispatcher = new Ammo.btCollisionDispatcher( collisionConfiguration );
  95. const broadphase = new Ammo.btDbvtBroadphase();
  96. const solver = new Ammo.btSequentialImpulseConstraintSolver();
  97. const softBodySolver = new Ammo.btDefaultSoftBodySolver();
  98. physicsWorld = new Ammo.btSoftRigidDynamicsWorld( dispatcher, broadphase, solver, collisionConfiguration, softBodySolver );
  99. physicsWorld.setGravity( new Ammo.btVector3( 0, gravityConstant, 0 ) );
  100. physicsWorld.getWorldInfo().set_m_gravity( new Ammo.btVector3( 0, gravityConstant, 0 ) );
  101. transformAux1 = new Ammo.btTransform();
  102. }
  103. function createObjects() {
  104. const pos = new THREE.Vector3();
  105. const quat = new THREE.Quaternion();
  106. // Ground
  107. pos.set( 0, - 0.5, 0 );
  108. quat.set( 0, 0, 0, 1 );
  109. const ground = createParalellepiped( 40, 1, 40, 0, pos, quat, new THREE.MeshPhongMaterial( { color: 0xFFFFFF } ) );
  110. ground.castShadow = true;
  111. ground.receiveShadow = true;
  112. textureLoader.load( 'textures/grid.png', function ( texture ) {
  113. texture.colorSpace = THREE.SRGBColorSpace;
  114. texture.wrapS = THREE.RepeatWrapping;
  115. texture.wrapT = THREE.RepeatWrapping;
  116. texture.repeat.set( 40, 40 );
  117. ground.material.map = texture;
  118. ground.material.needsUpdate = true;
  119. } );
  120. // Wall
  121. const brickMass = 0.5;
  122. const brickLength = 1.2;
  123. const brickDepth = 0.6;
  124. const brickHeight = brickLength * 0.5;
  125. const numBricksLength = 6;
  126. const numBricksHeight = 8;
  127. const z0 = - numBricksLength * brickLength * 0.5;
  128. pos.set( 0, brickHeight * 0.5, z0 );
  129. quat.set( 0, 0, 0, 1 );
  130. for ( let j = 0; j < numBricksHeight; j ++ ) {
  131. const oddRow = ( j % 2 ) == 1;
  132. pos.z = z0;
  133. if ( oddRow ) {
  134. pos.z -= 0.25 * brickLength;
  135. }
  136. const nRow = oddRow ? numBricksLength + 1 : numBricksLength;
  137. for ( let i = 0; i < nRow; i ++ ) {
  138. let brickLengthCurrent = brickLength;
  139. let brickMassCurrent = brickMass;
  140. if ( oddRow && ( i == 0 || i == nRow - 1 ) ) {
  141. brickLengthCurrent *= 0.5;
  142. brickMassCurrent *= 0.5;
  143. }
  144. const brick = createParalellepiped( brickDepth, brickHeight, brickLengthCurrent, brickMassCurrent, pos, quat, createMaterial() );
  145. brick.castShadow = true;
  146. brick.receiveShadow = true;
  147. if ( oddRow && ( i == 0 || i == nRow - 2 ) ) {
  148. pos.z += 0.75 * brickLength;
  149. } else {
  150. pos.z += brickLength;
  151. }
  152. }
  153. pos.y += brickHeight;
  154. }
  155. // The cloth
  156. // Cloth graphic object
  157. const clothWidth = 4;
  158. const clothHeight = 3;
  159. const clothNumSegmentsZ = clothWidth * 5;
  160. const clothNumSegmentsY = clothHeight * 5;
  161. const clothPos = new THREE.Vector3( - 3, 3, 2 );
  162. const clothGeometry = new THREE.PlaneGeometry( clothWidth, clothHeight, clothNumSegmentsZ, clothNumSegmentsY );
  163. clothGeometry.rotateY( Math.PI * 0.5 );
  164. clothGeometry.translate( clothPos.x, clothPos.y + clothHeight * 0.5, clothPos.z - clothWidth * 0.5 );
  165. const clothMaterial = new THREE.MeshLambertMaterial( { color: 0xFFFFFF, side: THREE.DoubleSide } );
  166. cloth = new THREE.Mesh( clothGeometry, clothMaterial );
  167. cloth.castShadow = true;
  168. cloth.receiveShadow = true;
  169. scene.add( cloth );
  170. textureLoader.load( 'textures/grid.png', function ( texture ) {
  171. texture.colorSpace = THREE.SRGBColorSpace;
  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. render();
  281. stats.update();
  282. }
  283. function render() {
  284. const deltaTime = clock.getDelta();
  285. updatePhysics( deltaTime );
  286. renderer.render( scene, camera );
  287. }
  288. function updatePhysics( deltaTime ) {
  289. // Hinge control
  290. hinge.enableAngularMotor( true, 0.8 * armMovement, 50 );
  291. // Step world
  292. physicsWorld.stepSimulation( deltaTime, 10 );
  293. // Update cloth
  294. const softBody = cloth.userData.physicsBody;
  295. const clothPositions = cloth.geometry.attributes.position.array;
  296. const numVerts = clothPositions.length / 3;
  297. const nodes = softBody.get_m_nodes();
  298. let indexFloat = 0;
  299. for ( let i = 0; i < numVerts; i ++ ) {
  300. const node = nodes.at( i );
  301. const nodePos = node.get_m_x();
  302. clothPositions[ indexFloat ++ ] = nodePos.x();
  303. clothPositions[ indexFloat ++ ] = nodePos.y();
  304. clothPositions[ indexFloat ++ ] = nodePos.z();
  305. }
  306. cloth.geometry.computeVertexNormals();
  307. cloth.geometry.attributes.position.needsUpdate = true;
  308. cloth.geometry.attributes.normal.needsUpdate = true;
  309. // Update rigid bodies
  310. for ( let i = 0, il = rigidBodies.length; i < il; i ++ ) {
  311. const objThree = rigidBodies[ i ];
  312. const objPhys = objThree.userData.physicsBody;
  313. const ms = objPhys.getMotionState();
  314. if ( ms ) {
  315. ms.getWorldTransform( transformAux1 );
  316. const p = transformAux1.getOrigin();
  317. const q = transformAux1.getRotation();
  318. objThree.position.set( p.x(), p.y(), p.z() );
  319. objThree.quaternion.set( q.x(), q.y(), q.z(), q.w() );
  320. }
  321. }
  322. }
  323. </script>
  324. </body>
  325. </html>