physics_ammo_rope.html 13 KB

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