webgl_physics_rope.html 13 KB

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