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