physics_ammo_volume.html 14 KB

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