webgl_physics_volume.html 14 KB

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