webgl_physics_rope.html 13 KB

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