webgl_physics_rope.html 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  1. <html lang="en">
  2. <head>
  3. <title>Amjs softbody rope 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 rope demo<br>Press Q or A to move the arm.</div>
  15. <div id="container"></div>
  16. <script src="../build/three.js"></script>
  17. <script src="js/libs/ammo.js"></script>
  18. <script src="js/controls/OrbitControls.js"></script>
  19. <script src="js/WebGL.js"></script>
  20. <script src="js/libs/stats.min.js"></script>
  21. <script>
  22. // Detects webgl
  23. if ( WEBGL.isWebGLAvailable() === false ) {
  24. document.body.appendChild( WEBGL.getWebGLErrorMessage() );
  25. }
  26. // Graphics variables
  27. var container, stats;
  28. var camera, controls, scene, renderer;
  29. var textureLoader;
  30. var clock = new THREE.Clock();
  31. // Physics variables
  32. var gravityConstant = - 9.8;
  33. var collisionConfiguration;
  34. var dispatcher;
  35. var broadphase;
  36. var solver;
  37. var softBodySolver;
  38. var physicsWorld;
  39. var rigidBodies = [];
  40. var margin = 0.05;
  41. var hinge;
  42. var rope;
  43. var transformAux1;
  44. var 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( - 7, 5, 8 );
  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 THREE.OrbitControls( camera, renderer.domElement );
  68. controls.target.set( 0, 2, 0 );
  69. controls.update();
  70. textureLoader = new THREE.TextureLoader();
  71. var ambientLight = new THREE.AmbientLight( 0x404040 );
  72. scene.add( ambientLight );
  73. var light = new THREE.DirectionalLight( 0xffffff, 1 );
  74. light.position.set( - 10, 10, 5 );
  75. light.castShadow = true;
  76. var 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. scene.add( light );
  86. stats = new Stats();
  87. stats.domElement.style.position = 'absolute';
  88. stats.domElement.style.top = '0px';
  89. container.appendChild( stats.domElement );
  90. //
  91. window.addEventListener( 'resize', onWindowResize, false );
  92. }
  93. function initPhysics() {
  94. // Physics configuration
  95. collisionConfiguration = new Ammo.btSoftBodyRigidBodyCollisionConfiguration();
  96. dispatcher = new Ammo.btCollisionDispatcher( collisionConfiguration );
  97. broadphase = new Ammo.btDbvtBroadphase();
  98. solver = new Ammo.btSequentialImpulseConstraintSolver();
  99. 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. var pos = new THREE.Vector3();
  107. var quat = new THREE.Quaternion();
  108. // Ground
  109. pos.set( 0, - 0.5, 0 );
  110. quat.set( 0, 0, 0, 1 );
  111. var 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. // Ball
  122. var ballMass = 1.2;
  123. var ballRadius = 0.6;
  124. var ball = new THREE.Mesh( new THREE.SphereBufferGeometry( ballRadius, 20, 20 ), new THREE.MeshPhongMaterial( { color: 0x202020 } ) );
  125. ball.castShadow = true;
  126. ball.receiveShadow = true;
  127. var ballShape = new Ammo.btSphereShape( ballRadius );
  128. ballShape.setMargin( margin );
  129. pos.set( - 3, 2, 0 );
  130. quat.set( 0, 0, 0, 1 );
  131. createRigidBody( ball, ballShape, ballMass, pos, quat );
  132. ball.userData.physicsBody.setFriction( 0.5 );
  133. // Wall
  134. var brickMass = 0.5;
  135. var brickLength = 1.2;
  136. var brickDepth = 0.6;
  137. var brickHeight = brickLength * 0.5;
  138. var numBricksLength = 6;
  139. var numBricksHeight = 8;
  140. var z0 = - numBricksLength * brickLength * 0.5;
  141. pos.set( 0, brickHeight * 0.5, z0 );
  142. quat.set( 0, 0, 0, 1 );
  143. for ( var j = 0; j < numBricksHeight; j ++ ) {
  144. var oddRow = ( j % 2 ) == 1;
  145. pos.z = z0;
  146. if ( oddRow ) {
  147. pos.z -= 0.25 * brickLength;
  148. }
  149. var nRow = oddRow ? numBricksLength + 1 : numBricksLength;
  150. for ( var i = 0; i < nRow; i ++ ) {
  151. var brickLengthCurrent = brickLength;
  152. var brickMassCurrent = brickMass;
  153. if ( oddRow && ( i == 0 || i == nRow - 1 ) ) {
  154. brickLengthCurrent *= 0.5;
  155. brickMassCurrent *= 0.5;
  156. }
  157. var brick = createParalellepiped( brickDepth, brickHeight, brickLengthCurrent, brickMassCurrent, pos, quat, createMaterial() );
  158. brick.castShadow = true;
  159. brick.receiveShadow = true;
  160. if ( oddRow && ( i == 0 || i == nRow - 2 ) ) {
  161. pos.z += 0.75 * brickLength;
  162. } else {
  163. pos.z += brickLength;
  164. }
  165. }
  166. pos.y += brickHeight;
  167. }
  168. // The rope
  169. // Rope graphic object
  170. var ropeNumSegments = 10;
  171. var ropeLength = 4;
  172. var ropeMass = 3;
  173. var ropePos = ball.position.clone();
  174. ropePos.y += ballRadius;
  175. var segmentLength = ropeLength / ropeNumSegments;
  176. var ropeGeometry = new THREE.BufferGeometry();
  177. var ropeMaterial = new THREE.LineBasicMaterial( { color: 0x000000 } );
  178. var ropePositions = [];
  179. var ropeIndices = [];
  180. for ( var i = 0; i < ropeNumSegments + 1; i ++ ) {
  181. ropePositions.push( ropePos.x, ropePos.y + i * segmentLength, ropePos.z );
  182. }
  183. for ( var i = 0; i < ropeNumSegments; i ++ ) {
  184. ropeIndices.push( i, i + 1 );
  185. }
  186. ropeGeometry.setIndex( new THREE.BufferAttribute( new Uint16Array( ropeIndices ), 1 ) );
  187. ropeGeometry.addAttribute( 'position', new THREE.BufferAttribute( new Float32Array( ropePositions ), 3 ) );
  188. ropeGeometry.computeBoundingSphere();
  189. rope = new THREE.LineSegments( ropeGeometry, ropeMaterial );
  190. rope.castShadow = true;
  191. rope.receiveShadow = true;
  192. scene.add( rope );
  193. // Rope physic object
  194. var softBodyHelpers = new Ammo.btSoftBodyHelpers();
  195. var ropeStart = new Ammo.btVector3( ropePos.x, ropePos.y, ropePos.z );
  196. var ropeEnd = new Ammo.btVector3( ropePos.x, ropePos.y + ropeLength, ropePos.z );
  197. var ropeSoftBody = softBodyHelpers.CreateRope( physicsWorld.getWorldInfo(), ropeStart, ropeEnd, ropeNumSegments - 1, 0 );
  198. var sbConfig = ropeSoftBody.get_m_cfg();
  199. sbConfig.set_viterations( 10 );
  200. sbConfig.set_piterations( 10 );
  201. ropeSoftBody.setTotalMass( ropeMass, false );
  202. Ammo.castObject( ropeSoftBody, Ammo.btCollisionObject ).getCollisionShape().setMargin( margin * 3 );
  203. physicsWorld.addSoftBody( ropeSoftBody, 1, - 1 );
  204. rope.userData.physicsBody = ropeSoftBody;
  205. // Disable deactivation
  206. ropeSoftBody.setActivationState( 4 );
  207. // The base
  208. var armMass = 2;
  209. var armLength = 3;
  210. var pylonHeight = ropePos.y + ropeLength;
  211. var baseMaterial = new THREE.MeshPhongMaterial( { color: 0x606060 } );
  212. pos.set( ropePos.x, 0.1, ropePos.z - armLength );
  213. quat.set( 0, 0, 0, 1 );
  214. var base = createParalellepiped( 1, 0.2, 1, 0, pos, quat, baseMaterial );
  215. base.castShadow = true;
  216. base.receiveShadow = true;
  217. pos.set( ropePos.x, 0.5 * pylonHeight, ropePos.z - armLength );
  218. var pylon = createParalellepiped( 0.4, pylonHeight, 0.4, 0, pos, quat, baseMaterial );
  219. pylon.castShadow = true;
  220. pylon.receiveShadow = true;
  221. pos.set( ropePos.x, pylonHeight + 0.2, ropePos.z - 0.5 * armLength );
  222. var arm = createParalellepiped( 0.4, 0.4, armLength + 0.4, armMass, pos, quat, baseMaterial );
  223. arm.castShadow = true;
  224. arm.receiveShadow = true;
  225. // Glue the rope extremes to the ball and the arm
  226. var influence = 1;
  227. ropeSoftBody.appendAnchor( 0, ball.userData.physicsBody, true, influence );
  228. ropeSoftBody.appendAnchor( ropeNumSegments, arm.userData.physicsBody, true, influence );
  229. // Hinge constraint to move the arm
  230. var pivotA = new Ammo.btVector3( 0, pylonHeight * 0.5, 0 );
  231. var pivotB = new Ammo.btVector3( 0, - 0.2, - armLength * 0.5 );
  232. var axis = new Ammo.btVector3( 0, 1, 0 );
  233. hinge = new Ammo.btHingeConstraint( pylon.userData.physicsBody, arm.userData.physicsBody, pivotA, pivotB, axis, axis, true );
  234. physicsWorld.addConstraint( hinge, true );
  235. }
  236. function createParalellepiped( sx, sy, sz, mass, pos, quat, material ) {
  237. var threeObject = new THREE.Mesh( new THREE.BoxBufferGeometry( sx, sy, sz, 1, 1, 1 ), material );
  238. var shape = new Ammo.btBoxShape( new Ammo.btVector3( sx * 0.5, sy * 0.5, sz * 0.5 ) );
  239. shape.setMargin( margin );
  240. createRigidBody( threeObject, shape, mass, pos, quat );
  241. return threeObject;
  242. }
  243. function createRigidBody( threeObject, physicsShape, mass, pos, quat ) {
  244. threeObject.position.copy( pos );
  245. threeObject.quaternion.copy( quat );
  246. var transform = new Ammo.btTransform();
  247. transform.setIdentity();
  248. transform.setOrigin( new Ammo.btVector3( pos.x, pos.y, pos.z ) );
  249. transform.setRotation( new Ammo.btQuaternion( quat.x, quat.y, quat.z, quat.w ) );
  250. var motionState = new Ammo.btDefaultMotionState( transform );
  251. var localInertia = new Ammo.btVector3( 0, 0, 0 );
  252. physicsShape.calculateLocalInertia( mass, localInertia );
  253. var rbInfo = new Ammo.btRigidBodyConstructionInfo( mass, motionState, physicsShape, localInertia );
  254. var body = new Ammo.btRigidBody( rbInfo );
  255. threeObject.userData.physicsBody = body;
  256. scene.add( threeObject );
  257. if ( mass > 0 ) {
  258. rigidBodies.push( threeObject );
  259. // Disable deactivation
  260. body.setActivationState( 4 );
  261. }
  262. physicsWorld.addRigidBody( body );
  263. }
  264. function createRandomColor() {
  265. return Math.floor( Math.random() * ( 1 << 24 ) );
  266. }
  267. function createMaterial() {
  268. return new THREE.MeshPhongMaterial( { color: createRandomColor() } );
  269. }
  270. function initInput() {
  271. window.addEventListener( 'keydown', function ( event ) {
  272. switch ( event.keyCode ) {
  273. // Q
  274. case 81:
  275. armMovement = 1;
  276. break;
  277. // A
  278. case 65:
  279. armMovement = - 1;
  280. break;
  281. }
  282. }, false );
  283. window.addEventListener( 'keyup', function () {
  284. armMovement = 0;
  285. }, false );
  286. }
  287. function onWindowResize() {
  288. camera.aspect = window.innerWidth / window.innerHeight;
  289. camera.updateProjectionMatrix();
  290. renderer.setSize( window.innerWidth, window.innerHeight );
  291. }
  292. function animate() {
  293. requestAnimationFrame( animate );
  294. render();
  295. stats.update();
  296. }
  297. function render() {
  298. var deltaTime = clock.getDelta();
  299. updatePhysics( deltaTime );
  300. renderer.render( scene, camera );
  301. }
  302. function updatePhysics( deltaTime ) {
  303. // Hinge control
  304. hinge.enableAngularMotor( true, 1.5 * armMovement, 50 );
  305. // Step world
  306. physicsWorld.stepSimulation( deltaTime, 10 );
  307. // Update rope
  308. var softBody = rope.userData.physicsBody;
  309. var ropePositions = rope.geometry.attributes.position.array;
  310. var numVerts = ropePositions.length / 3;
  311. var nodes = softBody.get_m_nodes();
  312. var indexFloat = 0;
  313. for ( var i = 0; i < numVerts; i ++ ) {
  314. var node = nodes.at( i );
  315. var nodePos = node.get_m_x();
  316. ropePositions[ indexFloat ++ ] = nodePos.x();
  317. ropePositions[ indexFloat ++ ] = nodePos.y();
  318. ropePositions[ indexFloat ++ ] = nodePos.z();
  319. }
  320. rope.geometry.attributes.position.needsUpdate = true;
  321. // Update rigid bodies
  322. for ( var i = 0, il = rigidBodies.length; i < il; i ++ ) {
  323. var objThree = rigidBodies[ i ];
  324. var objPhys = objThree.userData.physicsBody;
  325. var ms = objPhys.getMotionState();
  326. if ( ms ) {
  327. ms.getWorldTransform( transformAux1 );
  328. var p = transformAux1.getOrigin();
  329. var q = transformAux1.getRotation();
  330. objThree.position.set( p.x(), p.y(), p.z() );
  331. objThree.quaternion.set( q.x(), q.y(), q.z(), q.w() );
  332. }
  333. }
  334. }
  335. </script>
  336. </body>
  337. </html>