webgl_physics_volume.html 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  1. <html lang="en">
  2. <head>
  3. <title>Ammo.js softbody volume 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">
  15. Ammo.js physics soft body volume demo<br/>
  16. Click to throw a ball
  17. </div>
  18. <div id="container"></div>
  19. <script src="../build/three.js"></script>
  20. <script src="js/libs/ammo.js"></script>
  21. <script src="js/controls/OrbitControls.js"></script>
  22. <script src="js/utils/BufferGeometryUtils.js"></script>
  23. <script src="js/WebGL.js"></script>
  24. <script src="js/libs/stats.min.js"></script>
  25. <script>
  26. if ( WEBGL.isWebGLAvailable() === false ) {
  27. document.body.appendChild( WEBGL.getWebGLErrorMessage() );
  28. }
  29. // Graphics variables
  30. var container, stats;
  31. var camera, controls, scene, renderer;
  32. var textureLoader;
  33. var clock = new THREE.Clock();
  34. var clickRequest = false;
  35. var mouseCoords = new THREE.Vector2();
  36. var raycaster = new THREE.Raycaster();
  37. var ballMaterial = new THREE.MeshPhongMaterial( { color: 0x202020 } );
  38. var pos = new THREE.Vector3();
  39. var quat = new THREE.Quaternion();
  40. // Physics variables
  41. var gravityConstant = - 9.8;
  42. var physicsWorld;
  43. var rigidBodies = [];
  44. var softBodies = [];
  45. var margin = 0.05;
  46. var transformAux1;
  47. var softBodyHelpers;
  48. Ammo().then( function( AmmoLib ) {
  49. Ammo = AmmoLib;
  50. init();
  51. animate();
  52. } );
  53. function init() {
  54. initGraphics();
  55. initPhysics();
  56. createObjects();
  57. initInput();
  58. }
  59. function initGraphics() {
  60. container = document.getElementById( 'container' );
  61. camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 0.2, 2000 );
  62. scene = new THREE.Scene();
  63. scene.background = new THREE.Color( 0xbfd1e5 );
  64. camera.position.set( - 7, 5, 8 );
  65. renderer = new THREE.WebGLRenderer();
  66. renderer.setPixelRatio( window.devicePixelRatio );
  67. renderer.setSize( window.innerWidth, window.innerHeight );
  68. renderer.shadowMap.enabled = true;
  69. container.appendChild( renderer.domElement );
  70. controls = new THREE.OrbitControls( camera, renderer.domElement );
  71. controls.target.set( 0, 2, 0 );
  72. controls.update();
  73. textureLoader = new THREE.TextureLoader();
  74. var ambientLight = new THREE.AmbientLight( 0x404040 );
  75. scene.add( ambientLight );
  76. var light = new THREE.DirectionalLight( 0xffffff, 1 );
  77. light.position.set( - 10, 10, 5 );
  78. light.castShadow = true;
  79. var d = 20;
  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. window.addEventListener( 'resize', onWindowResize, false );
  94. }
  95. function initPhysics() {
  96. // Physics configuration
  97. var collisionConfiguration = new Ammo.btSoftBodyRigidBodyCollisionConfiguration();
  98. var dispatcher = new Ammo.btCollisionDispatcher( collisionConfiguration );
  99. var broadphase = new Ammo.btDbvtBroadphase();
  100. var solver = new Ammo.btSequentialImpulseConstraintSolver();
  101. var softBodySolver = new Ammo.btDefaultSoftBodySolver();
  102. physicsWorld = new Ammo.btSoftRigidDynamicsWorld( dispatcher, broadphase, solver, collisionConfiguration, softBodySolver );
  103. physicsWorld.setGravity( new Ammo.btVector3( 0, gravityConstant, 0 ) );
  104. physicsWorld.getWorldInfo().set_m_gravity( new Ammo.btVector3( 0, gravityConstant, 0 ) );
  105. transformAux1 = new Ammo.btTransform();
  106. softBodyHelpers = new Ammo.btSoftBodyHelpers();
  107. }
  108. function createObjects() {
  109. // Ground
  110. pos.set( 0, - 0.5, 0 );
  111. quat.set( 0, 0, 0, 1 );
  112. var ground = createParalellepiped( 40, 1, 40, 0, pos, quat, new THREE.MeshPhongMaterial( { color: 0xFFFFFF } ) );
  113. ground.castShadow = true;
  114. ground.receiveShadow = true;
  115. textureLoader.load( "textures/grid.png", function ( texture ) {
  116. texture.wrapS = THREE.RepeatWrapping;
  117. texture.wrapT = THREE.RepeatWrapping;
  118. texture.repeat.set( 40, 40 );
  119. ground.material.map = texture;
  120. ground.material.needsUpdate = true;
  121. } );
  122. // Create soft volumes
  123. var volumeMass = 15;
  124. var sphereGeometry = new THREE.SphereBufferGeometry( 1.5, 40, 25 );
  125. sphereGeometry.translate( 5, 5, 0 );
  126. createSoftVolume( sphereGeometry, volumeMass, 250 );
  127. var boxGeometry = new THREE.BoxBufferGeometry( 1, 1, 5, 4, 4, 20 );
  128. boxGeometry.translate( - 2, 5, 0 );
  129. createSoftVolume( boxGeometry, volumeMass, 120 );
  130. // Ramp
  131. pos.set( 3, 1, 0 );
  132. quat.setFromAxisAngle( new THREE.Vector3( 0, 0, 1 ), 30 * Math.PI / 180 );
  133. var obstacle = createParalellepiped( 10, 1, 4, 0, pos, quat, new THREE.MeshPhongMaterial( { color: 0x606060 } ) );
  134. obstacle.castShadow = true;
  135. obstacle.receiveShadow = true;
  136. }
  137. function processGeometry( bufGeometry ) {
  138. // Ony consider the position values when merging the vertices
  139. var posOnlyBufGeometry = new THREE.BufferGeometry();
  140. posOnlyBufGeometry.addAttribute( 'position', bufGeometry.getAttribute( 'position' ) );
  141. posOnlyBufGeometry.setIndex( bufGeometry.getIndex() );
  142. // Merge the vertices so the triangle soup is converted to indexed triangles
  143. var indexedBufferGeom = THREE.BufferGeometryUtils.mergeVertices( posOnlyBufGeometry );
  144. // Create index arrays mapping the indexed vertices to bufGeometry vertices
  145. mapIndices( bufGeometry, indexedBufferGeom );
  146. }
  147. function isEqual( x1, y1, z1, x2, y2, z2 ) {
  148. var delta = 0.000001;
  149. return Math.abs( x2 - x1 ) < delta &&
  150. Math.abs( y2 - y1 ) < delta &&
  151. Math.abs( z2 - z1 ) < delta;
  152. }
  153. function mapIndices( bufGeometry, indexedBufferGeom ) {
  154. // Creates ammoVertices, ammoIndices and ammoIndexAssociation in bufGeometry
  155. var vertices = bufGeometry.attributes.position.array;
  156. var idxVertices = indexedBufferGeom.attributes.position.array;
  157. var indices = indexedBufferGeom.index.array;
  158. var numIdxVertices = idxVertices.length / 3;
  159. var numVertices = vertices.length / 3;
  160. bufGeometry.ammoVertices = idxVertices;
  161. bufGeometry.ammoIndices = indices;
  162. bufGeometry.ammoIndexAssociation = [];
  163. for ( var i = 0; i < numIdxVertices; i ++ ) {
  164. var association = [];
  165. bufGeometry.ammoIndexAssociation.push( association );
  166. var i3 = i * 3;
  167. for ( var j = 0; j < numVertices; j ++ ) {
  168. var j3 = j * 3;
  169. if ( isEqual( idxVertices[ i3 ], idxVertices[ i3 + 1 ], idxVertices[ i3 + 2 ],
  170. vertices[ j3 ], vertices[ j3 + 1 ], vertices[ j3 + 2 ] ) ) {
  171. association.push( j3 );
  172. }
  173. }
  174. }
  175. }
  176. function createSoftVolume( bufferGeom, mass, pressure ) {
  177. processGeometry( bufferGeom );
  178. var volume = new THREE.Mesh( bufferGeom, new THREE.MeshPhongMaterial( { color: 0xFFFFFF } ) );
  179. volume.castShadow = true;
  180. volume.receiveShadow = true;
  181. volume.frustumCulled = false;
  182. scene.add( volume );
  183. textureLoader.load( "textures/colors.png", function ( texture ) {
  184. volume.material.map = texture;
  185. volume.material.needsUpdate = true;
  186. } );
  187. // Volume physic object
  188. var volumeSoftBody = softBodyHelpers.CreateFromTriMesh(
  189. physicsWorld.getWorldInfo(),
  190. bufferGeom.ammoVertices,
  191. bufferGeom.ammoIndices,
  192. bufferGeom.ammoIndices.length / 3,
  193. true );
  194. var sbConfig = volumeSoftBody.get_m_cfg();
  195. sbConfig.set_viterations( 40 );
  196. sbConfig.set_piterations( 40 );
  197. // Soft-soft and soft-rigid collisions
  198. sbConfig.set_collisions( 0x11 );
  199. // Friction
  200. sbConfig.set_kDF( 0.1 );
  201. // Damping
  202. sbConfig.set_kDP( 0.01 );
  203. // Pressure
  204. sbConfig.set_kPR( pressure );
  205. // Stiffness
  206. volumeSoftBody.get_m_materials().at( 0 ).set_m_kLST( 0.9 );
  207. volumeSoftBody.get_m_materials().at( 0 ).set_m_kAST( 0.9 );
  208. volumeSoftBody.setTotalMass( mass, false );
  209. Ammo.castObject( volumeSoftBody, Ammo.btCollisionObject ).getCollisionShape().setMargin( margin );
  210. physicsWorld.addSoftBody( volumeSoftBody, 1, - 1 );
  211. volume.userData.physicsBody = volumeSoftBody;
  212. // Disable deactivation
  213. volumeSoftBody.setActivationState( 4 );
  214. softBodies.push( volume );
  215. }
  216. function createParalellepiped( sx, sy, sz, mass, pos, quat, material ) {
  217. var threeObject = new THREE.Mesh( new THREE.BoxBufferGeometry( sx, sy, sz, 1, 1, 1 ), material );
  218. var shape = new Ammo.btBoxShape( new Ammo.btVector3( sx * 0.5, sy * 0.5, sz * 0.5 ) );
  219. shape.setMargin( margin );
  220. createRigidBody( threeObject, shape, mass, pos, quat );
  221. return threeObject;
  222. }
  223. function createRigidBody( threeObject, physicsShape, mass, pos, quat ) {
  224. threeObject.position.copy( pos );
  225. threeObject.quaternion.copy( quat );
  226. var transform = new Ammo.btTransform();
  227. transform.setIdentity();
  228. transform.setOrigin( new Ammo.btVector3( pos.x, pos.y, pos.z ) );
  229. transform.setRotation( new Ammo.btQuaternion( quat.x, quat.y, quat.z, quat.w ) );
  230. var motionState = new Ammo.btDefaultMotionState( transform );
  231. var localInertia = new Ammo.btVector3( 0, 0, 0 );
  232. physicsShape.calculateLocalInertia( mass, localInertia );
  233. var rbInfo = new Ammo.btRigidBodyConstructionInfo( mass, motionState, physicsShape, localInertia );
  234. var body = new Ammo.btRigidBody( rbInfo );
  235. threeObject.userData.physicsBody = body;
  236. scene.add( threeObject );
  237. if ( mass > 0 ) {
  238. rigidBodies.push( threeObject );
  239. // Disable deactivation
  240. body.setActivationState( 4 );
  241. }
  242. physicsWorld.addRigidBody( body );
  243. return body;
  244. }
  245. function initInput() {
  246. window.addEventListener( 'mousedown', function ( event ) {
  247. if ( ! clickRequest ) {
  248. mouseCoords.set(
  249. ( event.clientX / window.innerWidth ) * 2 - 1,
  250. - ( event.clientY / window.innerHeight ) * 2 + 1
  251. );
  252. clickRequest = true;
  253. }
  254. }, false );
  255. }
  256. function processClick() {
  257. if ( clickRequest ) {
  258. raycaster.setFromCamera( mouseCoords, camera );
  259. // Creates a ball
  260. var ballMass = 3;
  261. var ballRadius = 0.4;
  262. var ball = new THREE.Mesh( new THREE.SphereBufferGeometry( ballRadius, 18, 16 ), ballMaterial );
  263. ball.castShadow = true;
  264. ball.receiveShadow = true;
  265. var ballShape = new Ammo.btSphereShape( ballRadius );
  266. ballShape.setMargin( margin );
  267. pos.copy( raycaster.ray.direction );
  268. pos.add( raycaster.ray.origin );
  269. quat.set( 0, 0, 0, 1 );
  270. var ballBody = createRigidBody( ball, ballShape, ballMass, pos, quat );
  271. ballBody.setFriction( 0.5 );
  272. pos.copy( raycaster.ray.direction );
  273. pos.multiplyScalar( 14 );
  274. ballBody.setLinearVelocity( new Ammo.btVector3( pos.x, pos.y, pos.z ) );
  275. clickRequest = false;
  276. }
  277. }
  278. function onWindowResize() {
  279. camera.aspect = window.innerWidth / window.innerHeight;
  280. camera.updateProjectionMatrix();
  281. renderer.setSize( window.innerWidth, window.innerHeight );
  282. }
  283. function animate() {
  284. requestAnimationFrame( animate );
  285. render();
  286. stats.update();
  287. }
  288. function render() {
  289. var deltaTime = clock.getDelta();
  290. updatePhysics( deltaTime );
  291. processClick();
  292. renderer.render( scene, camera );
  293. }
  294. function updatePhysics( deltaTime ) {
  295. // Step world
  296. physicsWorld.stepSimulation( deltaTime, 10 );
  297. // Update soft volumes
  298. for ( var i = 0, il = softBodies.length; i < il; i ++ ) {
  299. var volume = softBodies[ i ];
  300. var geometry = volume.geometry;
  301. var softBody = volume.userData.physicsBody;
  302. var volumePositions = geometry.attributes.position.array;
  303. var volumeNormals = geometry.attributes.normal.array;
  304. var association = geometry.ammoIndexAssociation;
  305. var numVerts = association.length;
  306. var nodes = softBody.get_m_nodes();
  307. for ( var j = 0; j < numVerts; j ++ ) {
  308. var node = nodes.at( j );
  309. var nodePos = node.get_m_x();
  310. var x = nodePos.x();
  311. var y = nodePos.y();
  312. var z = nodePos.z();
  313. var nodeNormal = node.get_m_n();
  314. var nx = nodeNormal.x();
  315. var ny = nodeNormal.y();
  316. var nz = nodeNormal.z();
  317. var assocVertex = association[ j ];
  318. for ( var k = 0, kl = assocVertex.length; k < kl; k ++ ) {
  319. var indexVertex = assocVertex[ k ];
  320. volumePositions[ indexVertex ] = x;
  321. volumeNormals[ indexVertex ] = nx;
  322. indexVertex ++;
  323. volumePositions[ indexVertex ] = y;
  324. volumeNormals[ indexVertex ] = ny;
  325. indexVertex ++;
  326. volumePositions[ indexVertex ] = z;
  327. volumeNormals[ indexVertex ] = nz;
  328. }
  329. }
  330. geometry.attributes.position.needsUpdate = true;
  331. geometry.attributes.normal.needsUpdate = true;
  332. }
  333. // Update rigid bodies
  334. for ( var i = 0, il = rigidBodies.length; i < il; i ++ ) {
  335. var objThree = rigidBodies[ i ];
  336. var objPhys = objThree.userData.physicsBody;
  337. var ms = objPhys.getMotionState();
  338. if ( ms ) {
  339. ms.getWorldTransform( transformAux1 );
  340. var p = transformAux1.getOrigin();
  341. var q = transformAux1.getRotation();
  342. objThree.position.set( p.x(), p.y(), p.z() );
  343. objThree.quaternion.set( q.x(), q.y(), q.z(), q.w() );
  344. }
  345. }
  346. }
  347. </script>
  348. </body>
  349. </html>