webgl_physics_volume.html 13 KB

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