physics_ammo_volume.html 14 KB

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