AmmoPhysics.js 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. /**
  2. * @classdesc Can be used to include Ammo.js as a Physics engine into
  3. * `three.js` apps. Make sure to include `ammo.wasm.js` first:
  4. * ```
  5. * <script src="jsm/libs/ammo.wasm.js"></script>
  6. * ```
  7. * It is then possible to initialize the API via:
  8. * ```js
  9. * const physics = await AmmoPhysics();
  10. * ```
  11. *
  12. * @name AmmoPhysics
  13. * @class
  14. * @hideconstructor
  15. * @three_import import { AmmoPhysics } from 'three/addons/physics/AmmoPhysics.js';
  16. */
  17. async function AmmoPhysics() {
  18. if ( 'Ammo' in window === false ) {
  19. console.error( 'AmmoPhysics: Couldn\'t find Ammo.js' );
  20. return;
  21. }
  22. const AmmoLib = await Ammo(); // eslint-disable-line no-undef
  23. const frameRate = 60;
  24. const collisionConfiguration = new AmmoLib.btDefaultCollisionConfiguration();
  25. const dispatcher = new AmmoLib.btCollisionDispatcher( collisionConfiguration );
  26. const broadphase = new AmmoLib.btDbvtBroadphase();
  27. const solver = new AmmoLib.btSequentialImpulseConstraintSolver();
  28. const world = new AmmoLib.btDiscreteDynamicsWorld( dispatcher, broadphase, solver, collisionConfiguration );
  29. world.setGravity( new AmmoLib.btVector3( 0, - 9.8, 0 ) );
  30. const worldTransform = new AmmoLib.btTransform();
  31. //
  32. function getShape( geometry ) {
  33. const parameters = geometry.parameters;
  34. // TODO change type to is*
  35. if ( geometry.type === 'BoxGeometry' ) {
  36. const sx = parameters.width !== undefined ? parameters.width / 2 : 0.5;
  37. const sy = parameters.height !== undefined ? parameters.height / 2 : 0.5;
  38. const sz = parameters.depth !== undefined ? parameters.depth / 2 : 0.5;
  39. const shape = new AmmoLib.btBoxShape( new AmmoLib.btVector3( sx, sy, sz ) );
  40. shape.setMargin( 0.05 );
  41. return shape;
  42. } else if ( geometry.type === 'SphereGeometry' || geometry.type === 'IcosahedronGeometry' ) {
  43. const radius = parameters.radius !== undefined ? parameters.radius : 1;
  44. const shape = new AmmoLib.btSphereShape( radius );
  45. shape.setMargin( 0.05 );
  46. return shape;
  47. }
  48. return null;
  49. }
  50. const meshes = [];
  51. const meshMap = new WeakMap();
  52. function addScene( scene ) {
  53. scene.traverse( function ( child ) {
  54. if ( child.isMesh ) {
  55. const physics = child.userData.physics;
  56. if ( physics ) {
  57. addMesh( child, physics.mass, physics.restitution );
  58. }
  59. }
  60. } );
  61. }
  62. function addMesh( mesh, mass = 0, restitution = 0 ) {
  63. const shape = getShape( mesh.geometry );
  64. if ( shape !== null ) {
  65. if ( mesh.isInstancedMesh ) {
  66. handleInstancedMesh( mesh, shape, mass, restitution );
  67. } else if ( mesh.isMesh ) {
  68. handleMesh( mesh, shape, mass, restitution );
  69. }
  70. }
  71. }
  72. function handleMesh( mesh, shape, mass, restitution ) {
  73. const position = mesh.position;
  74. const quaternion = mesh.quaternion;
  75. const transform = new AmmoLib.btTransform();
  76. transform.setIdentity();
  77. transform.setOrigin( new AmmoLib.btVector3( position.x, position.y, position.z ) );
  78. transform.setRotation( new AmmoLib.btQuaternion( quaternion.x, quaternion.y, quaternion.z, quaternion.w ) );
  79. const motionState = new AmmoLib.btDefaultMotionState( transform );
  80. const localInertia = new AmmoLib.btVector3( 0, 0, 0 );
  81. shape.calculateLocalInertia( mass, localInertia );
  82. const rbInfo = new AmmoLib.btRigidBodyConstructionInfo( mass, motionState, shape, localInertia );
  83. rbInfo.set_m_restitution( restitution );
  84. const body = new AmmoLib.btRigidBody( rbInfo );
  85. // body.setFriction( 4 );
  86. world.addRigidBody( body );
  87. if ( mass > 0 ) {
  88. meshes.push( mesh );
  89. meshMap.set( mesh, body );
  90. }
  91. }
  92. function handleInstancedMesh( mesh, shape, mass, restitution ) {
  93. const array = mesh.instanceMatrix.array;
  94. const bodies = [];
  95. for ( let i = 0; i < mesh.count; i ++ ) {
  96. const index = i * 16;
  97. const transform = new AmmoLib.btTransform();
  98. transform.setFromOpenGLMatrix( array.slice( index, index + 16 ) );
  99. const motionState = new AmmoLib.btDefaultMotionState( transform );
  100. const localInertia = new AmmoLib.btVector3( 0, 0, 0 );
  101. shape.calculateLocalInertia( mass, localInertia );
  102. const rbInfo = new AmmoLib.btRigidBodyConstructionInfo( mass, motionState, shape, localInertia );
  103. rbInfo.set_m_restitution( restitution );
  104. const body = new AmmoLib.btRigidBody( rbInfo );
  105. world.addRigidBody( body );
  106. bodies.push( body );
  107. }
  108. if ( mass > 0 ) {
  109. meshes.push( mesh );
  110. meshMap.set( mesh, bodies );
  111. }
  112. }
  113. //
  114. function setMeshPosition( mesh, position, index = 0 ) {
  115. if ( mesh.isInstancedMesh ) {
  116. const bodies = meshMap.get( mesh );
  117. const body = bodies[ index ];
  118. body.setAngularVelocity( new AmmoLib.btVector3( 0, 0, 0 ) );
  119. body.setLinearVelocity( new AmmoLib.btVector3( 0, 0, 0 ) );
  120. worldTransform.setIdentity();
  121. worldTransform.setOrigin( new AmmoLib.btVector3( position.x, position.y, position.z ) );
  122. body.setWorldTransform( worldTransform );
  123. } else if ( mesh.isMesh ) {
  124. const body = meshMap.get( mesh );
  125. body.setAngularVelocity( new AmmoLib.btVector3( 0, 0, 0 ) );
  126. body.setLinearVelocity( new AmmoLib.btVector3( 0, 0, 0 ) );
  127. worldTransform.setIdentity();
  128. worldTransform.setOrigin( new AmmoLib.btVector3( position.x, position.y, position.z ) );
  129. body.setWorldTransform( worldTransform );
  130. }
  131. }
  132. //
  133. let lastTime = 0;
  134. function step() {
  135. const time = performance.now();
  136. if ( lastTime > 0 ) {
  137. const delta = ( time - lastTime ) / 1000;
  138. world.stepSimulation( delta, 10 );
  139. //
  140. for ( let i = 0, l = meshes.length; i < l; i ++ ) {
  141. const mesh = meshes[ i ];
  142. if ( mesh.isInstancedMesh ) {
  143. const array = mesh.instanceMatrix.array;
  144. const bodies = meshMap.get( mesh );
  145. for ( let j = 0; j < bodies.length; j ++ ) {
  146. const body = bodies[ j ];
  147. const motionState = body.getMotionState();
  148. motionState.getWorldTransform( worldTransform );
  149. const position = worldTransform.getOrigin();
  150. const quaternion = worldTransform.getRotation();
  151. compose( position, quaternion, array, j * 16 );
  152. }
  153. mesh.instanceMatrix.needsUpdate = true;
  154. mesh.computeBoundingSphere();
  155. } else if ( mesh.isMesh ) {
  156. const body = meshMap.get( mesh );
  157. const motionState = body.getMotionState();
  158. motionState.getWorldTransform( worldTransform );
  159. const position = worldTransform.getOrigin();
  160. const quaternion = worldTransform.getRotation();
  161. mesh.position.set( position.x(), position.y(), position.z() );
  162. mesh.quaternion.set( quaternion.x(), quaternion.y(), quaternion.z(), quaternion.w() );
  163. }
  164. }
  165. }
  166. lastTime = time;
  167. }
  168. // animate
  169. setInterval( step, 1000 / frameRate );
  170. return {
  171. /**
  172. * Adds the given scene to this physics simulation. Only meshes with a
  173. * `physics` object in their {@link Object3D#userData} field will be honored.
  174. * The object can be used to store the mass of the mesh. E.g.:
  175. * ```js
  176. * box.userData.physics = { mass: 1 };
  177. * ```
  178. *
  179. * @method
  180. * @name AmmoPhysics#addScene
  181. * @param {Object3D} scene The scene or any type of 3D object to add.
  182. */
  183. addScene: addScene,
  184. /**
  185. * Adds the given mesh to this physics simulation.
  186. *
  187. * @method
  188. * @name AmmoPhysics#addMesh
  189. * @param {Mesh} mesh The mesh to add.
  190. * @param {number} [mass=0] The mass in kg of the mesh.
  191. * @param {number} [restitution=0] The restitution of the mesh, usually from 0 to 1. Represents how "bouncy" objects are when they collide with each other.
  192. */
  193. addMesh: addMesh,
  194. /**
  195. * Set the position of the given mesh which is part of the physics simulation. Calling this
  196. * method will reset the current simulated velocity of the mesh.
  197. *
  198. * @method
  199. * @name AmmoPhysics#setMeshPosition
  200. * @param {Mesh} mesh The mesh to update the position for.
  201. * @param {Vector3} position - The new position.
  202. * @param {number} [index=0] - If the mesh is instanced, the index represents the instanced ID.
  203. */
  204. setMeshPosition: setMeshPosition
  205. // addCompoundMesh
  206. };
  207. }
  208. function compose( position, quaternion, array, index ) {
  209. const x = quaternion.x(), y = quaternion.y(), z = quaternion.z(), w = quaternion.w();
  210. const x2 = x + x, y2 = y + y, z2 = z + z;
  211. const xx = x * x2, xy = x * y2, xz = x * z2;
  212. const yy = y * y2, yz = y * z2, zz = z * z2;
  213. const wx = w * x2, wy = w * y2, wz = w * z2;
  214. array[ index + 0 ] = ( 1 - ( yy + zz ) );
  215. array[ index + 1 ] = ( xy + wz );
  216. array[ index + 2 ] = ( xz - wy );
  217. array[ index + 3 ] = 0;
  218. array[ index + 4 ] = ( xy - wz );
  219. array[ index + 5 ] = ( 1 - ( xx + zz ) );
  220. array[ index + 6 ] = ( yz + wx );
  221. array[ index + 7 ] = 0;
  222. array[ index + 8 ] = ( xz + wy );
  223. array[ index + 9 ] = ( yz - wx );
  224. array[ index + 10 ] = ( 1 - ( xx + yy ) );
  225. array[ index + 11 ] = 0;
  226. array[ index + 12 ] = position.x();
  227. array[ index + 13 ] = position.y();
  228. array[ index + 14 ] = position.z();
  229. array[ index + 15 ] = 1;
  230. }
  231. export { AmmoPhysics };
粤ICP备19079148号