webgl_physics_volume.html 14 KB

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