AmmoPhysics.js 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  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();
  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. console.error( 'AmmoPhysics: Unsupported geometry type:', geometry.type );
  49. return null;
  50. }
  51. const meshes = [];
  52. const meshMap = new WeakMap();
  53. function addScene( scene ) {
  54. scene.traverse( function ( child ) {
  55. if ( child.isMesh ) {
  56. const physics = child.userData.physics;
  57. if ( physics ) {
  58. addMesh( child, physics.mass, physics.restitution );
  59. }
  60. }
  61. } );
  62. }
  63. function addMesh( mesh, mass = 0, restitution = 0 ) {
  64. const shape = getShape( mesh.geometry );
  65. if ( shape !== null ) {
  66. if ( mesh.isInstancedMesh ) {
  67. handleInstancedMesh( mesh, shape, mass, restitution );
  68. } else if ( mesh.isMesh ) {
  69. handleMesh( mesh, shape, mass, restitution );
  70. }
  71. }
  72. }
  73. function handleMesh( mesh, shape, mass, restitution ) {
  74. const position = mesh.position;
  75. const quaternion = mesh.quaternion;
  76. const transform = new AmmoLib.btTransform();
  77. transform.setIdentity();
  78. transform.setOrigin( new AmmoLib.btVector3( position.x, position.y, position.z ) );
  79. transform.setRotation( new AmmoLib.btQuaternion( quaternion.x, quaternion.y, quaternion.z, quaternion.w ) );
  80. const motionState = new AmmoLib.btDefaultMotionState( transform );
  81. const localInertia = new AmmoLib.btVector3( 0, 0, 0 );
  82. shape.calculateLocalInertia( mass, localInertia );
  83. const rbInfo = new AmmoLib.btRigidBodyConstructionInfo( mass, motionState, shape, localInertia );
  84. rbInfo.set_m_restitution( restitution );
  85. const body = new AmmoLib.btRigidBody( rbInfo );
  86. // body.setFriction( 4 );
  87. world.addRigidBody( body );
  88. if ( mass > 0 ) {
  89. meshes.push( mesh );
  90. meshMap.set( mesh, body );
  91. }
  92. }
  93. function handleInstancedMesh( mesh, shape, mass, restitution ) {
  94. const array = mesh.instanceMatrix.array;
  95. const bodies = [];
  96. for ( let i = 0; i < mesh.count; i ++ ) {
  97. const index = i * 16;
  98. const transform = new AmmoLib.btTransform();
  99. transform.setFromOpenGLMatrix( array.slice( index, index + 16 ) );
  100. const motionState = new AmmoLib.btDefaultMotionState( transform );
  101. const localInertia = new AmmoLib.btVector3( 0, 0, 0 );
  102. shape.calculateLocalInertia( mass, localInertia );
  103. const rbInfo = new AmmoLib.btRigidBodyConstructionInfo( mass, motionState, shape, localInertia );
  104. rbInfo.set_m_restitution( restitution );
  105. const body = new AmmoLib.btRigidBody( rbInfo );
  106. world.addRigidBody( body );
  107. bodies.push( body );
  108. }
  109. if ( mass > 0 ) {
  110. meshes.push( mesh );
  111. meshMap.set( mesh, bodies );
  112. }
  113. }
  114. //
  115. function setMeshPosition( mesh, position, index = 0 ) {
  116. if ( mesh.isInstancedMesh ) {
  117. const bodies = meshMap.get( mesh );
  118. const body = bodies[ index ];
  119. body.setAngularVelocity( new AmmoLib.btVector3( 0, 0, 0 ) );
  120. body.setLinearVelocity( new AmmoLib.btVector3( 0, 0, 0 ) );
  121. worldTransform.setIdentity();
  122. worldTransform.setOrigin( new AmmoLib.btVector3( position.x, position.y, position.z ) );
  123. body.setWorldTransform( worldTransform );
  124. } else if ( mesh.isMesh ) {
  125. const body = meshMap.get( mesh );
  126. body.setAngularVelocity( new AmmoLib.btVector3( 0, 0, 0 ) );
  127. body.setLinearVelocity( new AmmoLib.btVector3( 0, 0, 0 ) );
  128. worldTransform.setIdentity();
  129. worldTransform.setOrigin( new AmmoLib.btVector3( position.x, position.y, position.z ) );
  130. body.setWorldTransform( worldTransform );
  131. }
  132. }
  133. //
  134. let lastTime = 0;
  135. function step() {
  136. const time = performance.now();
  137. if ( lastTime > 0 ) {
  138. const delta = ( time - lastTime ) / 1000;
  139. world.stepSimulation( delta, 10 );
  140. //
  141. for ( let i = 0, l = meshes.length; i < l; i ++ ) {
  142. const mesh = meshes[ i ];
  143. if ( mesh.isInstancedMesh ) {
  144. const array = mesh.instanceMatrix.array;
  145. const bodies = meshMap.get( mesh );
  146. for ( let j = 0; j < bodies.length; j ++ ) {
  147. const body = bodies[ j ];
  148. const motionState = body.getMotionState();
  149. motionState.getWorldTransform( worldTransform );
  150. const position = worldTransform.getOrigin();
  151. const quaternion = worldTransform.getRotation();
  152. compose( position, quaternion, array, j * 16 );
  153. }
  154. mesh.instanceMatrix.needsUpdate = true;
  155. mesh.computeBoundingSphere();
  156. } else if ( mesh.isMesh ) {
  157. const body = meshMap.get( mesh );
  158. const motionState = body.getMotionState();
  159. motionState.getWorldTransform( worldTransform );
  160. const position = worldTransform.getOrigin();
  161. const quaternion = worldTransform.getRotation();
  162. mesh.position.set( position.x(), position.y(), position.z() );
  163. mesh.quaternion.set( quaternion.x(), quaternion.y(), quaternion.z(), quaternion.w() );
  164. }
  165. }
  166. }
  167. lastTime = time;
  168. }
  169. // animate
  170. setInterval( step, 1000 / frameRate );
  171. return {
  172. /**
  173. * Adds the given scene to this physics simulation. Only meshes with a
  174. * `physics` object in their {@link Object3D#userData} field will be honored.
  175. * The object can be used to store the mass of the mesh. E.g.:
  176. * ```js
  177. * box.userData.physics = { mass: 1 };
  178. * ```
  179. *
  180. * @method
  181. * @name AmmoPhysics#addScene
  182. * @param {Object3D} scene The scene or any type of 3D object to add.
  183. */
  184. addScene: addScene,
  185. /**
  186. * Adds the given mesh to this physics simulation.
  187. *
  188. * @method
  189. * @name AmmoPhysics#addMesh
  190. * @param {Mesh} mesh The mesh to add.
  191. * @param {number} [mass=0] The mass in kg of the mesh.
  192. * @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.
  193. */
  194. addMesh: addMesh,
  195. /**
  196. * Set the position of the given mesh which is part of the physics simulation. Calling this
  197. * method will reset the current simulated velocity of the mesh.
  198. *
  199. * @method
  200. * @name AmmoPhysics#setMeshPosition
  201. * @param {Mesh} mesh The mesh to update the position for.
  202. * @param {Vector3} position - The new position.
  203. * @param {number} [index=0] - If the mesh is instanced, the index represents the instanced ID.
  204. */
  205. setMeshPosition: setMeshPosition
  206. // addCompoundMesh
  207. };
  208. }
  209. function compose( position, quaternion, array, index ) {
  210. const x = quaternion.x(), y = quaternion.y(), z = quaternion.z(), w = quaternion.w();
  211. const x2 = x + x, y2 = y + y, z2 = z + z;
  212. const xx = x * x2, xy = x * y2, xz = x * z2;
  213. const yy = y * y2, yz = y * z2, zz = z * z2;
  214. const wx = w * x2, wy = w * y2, wz = w * z2;
  215. array[ index + 0 ] = ( 1 - ( yy + zz ) );
  216. array[ index + 1 ] = ( xy + wz );
  217. array[ index + 2 ] = ( xz - wy );
  218. array[ index + 3 ] = 0;
  219. array[ index + 4 ] = ( xy - wz );
  220. array[ index + 5 ] = ( 1 - ( xx + zz ) );
  221. array[ index + 6 ] = ( yz + wx );
  222. array[ index + 7 ] = 0;
  223. array[ index + 8 ] = ( xz + wy );
  224. array[ index + 9 ] = ( yz - wx );
  225. array[ index + 10 ] = ( 1 - ( xx + yy ) );
  226. array[ index + 11 ] = 0;
  227. array[ index + 12 ] = position.x();
  228. array[ index + 13 ] = position.y();
  229. array[ index + 14 ] = position.z();
  230. array[ index + 15 ] = 1;
  231. }
  232. export { AmmoPhysics };
粤ICP备19079148号