webgl_physics_rope.html 13 KB

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