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