JoltPhysics.js 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. import { Clock, Vector3, Quaternion, Matrix4 } from 'three';
  2. const JOLT_PATH = 'https://cdn.jsdelivr.net/npm/jolt-physics@0.23.0/dist/jolt-physics.wasm-compat.js';
  3. const frameRate = 60;
  4. let Jolt = null;
  5. function getShape( geometry ) {
  6. const parameters = geometry.parameters;
  7. // TODO change type to is*
  8. if ( geometry.type === 'BoxGeometry' ) {
  9. const sx = parameters.width !== undefined ? parameters.width / 2 : 0.5;
  10. const sy = parameters.height !== undefined ? parameters.height / 2 : 0.5;
  11. const sz = parameters.depth !== undefined ? parameters.depth / 2 : 0.5;
  12. return new Jolt.BoxShape( new Jolt.Vec3( sx, sy, sz ), 0.05 * Math.min( sx, sy, sz ), null );
  13. } else if ( geometry.type === 'SphereGeometry' || geometry.type === 'IcosahedronGeometry' ) {
  14. const radius = parameters.radius !== undefined ? parameters.radius : 1;
  15. return new Jolt.SphereShape( radius, null );
  16. }
  17. return null;
  18. }
  19. // Object layers
  20. const LAYER_NON_MOVING = 0;
  21. const LAYER_MOVING = 1;
  22. const NUM_OBJECT_LAYERS = 2;
  23. function setupCollisionFiltering( settings ) {
  24. const objectFilter = new Jolt.ObjectLayerPairFilterTable( NUM_OBJECT_LAYERS );
  25. objectFilter.EnableCollision( LAYER_NON_MOVING, LAYER_MOVING );
  26. objectFilter.EnableCollision( LAYER_MOVING, LAYER_MOVING );
  27. const BP_LAYER_NON_MOVING = new Jolt.BroadPhaseLayer( 0 );
  28. const BP_LAYER_MOVING = new Jolt.BroadPhaseLayer( 1 );
  29. const NUM_BROAD_PHASE_LAYERS = 2;
  30. const bpInterface = new Jolt.BroadPhaseLayerInterfaceTable( NUM_OBJECT_LAYERS, NUM_BROAD_PHASE_LAYERS );
  31. bpInterface.MapObjectToBroadPhaseLayer( LAYER_NON_MOVING, BP_LAYER_NON_MOVING );
  32. bpInterface.MapObjectToBroadPhaseLayer( LAYER_MOVING, BP_LAYER_MOVING );
  33. settings.mObjectLayerPairFilter = objectFilter;
  34. settings.mBroadPhaseLayerInterface = bpInterface;
  35. settings.mObjectVsBroadPhaseLayerFilter = new Jolt.ObjectVsBroadPhaseLayerFilterTable( settings.mBroadPhaseLayerInterface, NUM_BROAD_PHASE_LAYERS, settings.mObjectLayerPairFilter, NUM_OBJECT_LAYERS );
  36. }
  37. /**
  38. * @classdesc Can be used to include Jolt as a Physics engine into
  39. * `three.js` apps. The API can be initialized via:
  40. * ```js
  41. * const physics = await JoltPhysics();
  42. * ```
  43. * The component automatically imports Jolt from a CDN so make sure
  44. * to use the component with an active Internet connection.
  45. *
  46. * @name JoltPhysics
  47. * @class
  48. * @hideconstructor
  49. * @three_import import { JoltPhysics } from 'three/addons/physics/JoltPhysics.js';
  50. */
  51. async function JoltPhysics() {
  52. if ( Jolt === null ) {
  53. const { default: initJolt } = await import( `${JOLT_PATH}` );
  54. Jolt = await initJolt();
  55. }
  56. const settings = new Jolt.JoltSettings();
  57. setupCollisionFiltering( settings );
  58. const jolt = new Jolt.JoltInterface( settings );
  59. Jolt.destroy( settings );
  60. const physicsSystem = jolt.GetPhysicsSystem();
  61. const bodyInterface = physicsSystem.GetBodyInterface();
  62. const meshes = [];
  63. const meshMap = new WeakMap();
  64. const _position = new Vector3();
  65. const _quaternion = new Quaternion();
  66. const _scale = new Vector3( 1, 1, 1 );
  67. const _matrix = new Matrix4();
  68. function addScene( scene ) {
  69. scene.traverse( function ( child ) {
  70. if ( child.isMesh ) {
  71. const physics = child.userData.physics;
  72. if ( physics ) {
  73. addMesh( child, physics.mass, physics.restitution );
  74. }
  75. }
  76. } );
  77. }
  78. function addMesh( mesh, mass = 0, restitution = 0 ) {
  79. const shape = getShape( mesh.geometry );
  80. if ( shape === null ) return;
  81. const body = mesh.isInstancedMesh
  82. ? createInstancedBody( mesh, mass, restitution, shape )
  83. : createBody( mesh.position, mesh.quaternion, mass, restitution, shape );
  84. if ( mass > 0 ) {
  85. meshes.push( mesh );
  86. meshMap.set( mesh, body );
  87. }
  88. }
  89. function createInstancedBody( mesh, mass, restitution, shape ) {
  90. const array = mesh.instanceMatrix.array;
  91. const bodies = [];
  92. for ( let i = 0; i < mesh.count; i ++ ) {
  93. const position = _position.fromArray( array, i * 16 + 12 );
  94. const quaternion = _quaternion.setFromRotationMatrix( _matrix.fromArray( array, i * 16 ) ); // TODO Copilot did this
  95. bodies.push( createBody( position, quaternion, mass, restitution, shape ) );
  96. }
  97. return bodies;
  98. }
  99. function createBody( position, rotation, mass, restitution, shape ) {
  100. const pos = new Jolt.Vec3( position.x, position.y, position.z );
  101. const rot = new Jolt.Quat( rotation.x, rotation.y, rotation.z, rotation.w );
  102. const motion = mass > 0 ? Jolt.EMotionType_Dynamic : Jolt.EMotionType_Static;
  103. const layer = mass > 0 ? LAYER_MOVING : LAYER_NON_MOVING;
  104. const creationSettings = new Jolt.BodyCreationSettings( shape, pos, rot, motion, layer );
  105. creationSettings.mRestitution = restitution;
  106. const body = bodyInterface.CreateBody( creationSettings );
  107. bodyInterface.AddBody( body.GetID(), Jolt.EActivation_Activate );
  108. Jolt.destroy( creationSettings );
  109. return body;
  110. }
  111. function setMeshPosition( mesh, position, index = 0 ) {
  112. if ( mesh.isInstancedMesh ) {
  113. const bodies = meshMap.get( mesh );
  114. const body = bodies[ index ];
  115. bodyInterface.RemoveBody( body.GetID() );
  116. bodyInterface.DestroyBody( body.GetID() );
  117. const physics = mesh.userData.physics;
  118. const shape = body.GetShape();
  119. const body2 = createBody( position, { x: 0, y: 0, z: 0, w: 1 }, physics.mass, physics.restitution, shape );
  120. bodies[ index ] = body2;
  121. } else {
  122. // TODO: Implement this
  123. }
  124. }
  125. function setMeshVelocity( mesh, velocity, index = 0 ) {
  126. /*
  127. let body = meshMap.get( mesh );
  128. if ( mesh.isInstancedMesh ) {
  129. body = body[ index ];
  130. }
  131. body.setLinvel( velocity );
  132. */
  133. }
  134. //
  135. const clock = new Clock();
  136. function step() {
  137. let deltaTime = clock.getDelta();
  138. // Don't go below 30 Hz to prevent spiral of death
  139. deltaTime = Math.min( deltaTime, 1.0 / 30.0 );
  140. // When running below 55 Hz, do 2 steps instead of 1
  141. const numSteps = deltaTime > 1.0 / 55.0 ? 2 : 1;
  142. // Step the physics world
  143. jolt.Step( deltaTime, numSteps );
  144. //
  145. for ( let i = 0, l = meshes.length; i < l; i ++ ) {
  146. const mesh = meshes[ i ];
  147. if ( mesh.isInstancedMesh ) {
  148. const array = mesh.instanceMatrix.array;
  149. const bodies = meshMap.get( mesh );
  150. for ( let j = 0; j < bodies.length; j ++ ) {
  151. const body = bodies[ j ];
  152. const position = body.GetPosition();
  153. const quaternion = body.GetRotation();
  154. _position.set( position.GetX(), position.GetY(), position.GetZ() );
  155. _quaternion.set( quaternion.GetX(), quaternion.GetY(), quaternion.GetZ(), quaternion.GetW() );
  156. _matrix.compose( _position, _quaternion, _scale ).toArray( array, j * 16 );
  157. }
  158. mesh.instanceMatrix.needsUpdate = true;
  159. mesh.computeBoundingSphere();
  160. } else {
  161. const body = meshMap.get( mesh );
  162. const position = body.GetPosition();
  163. const rotation = body.GetRotation();
  164. mesh.position.set( position.GetX(), position.GetY(), position.GetZ() );
  165. mesh.quaternion.set( rotation.GetX(), rotation.GetY(), rotation.GetZ(), rotation.GetW() );
  166. }
  167. }
  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 and restitution of the mesh. E.g.:
  176. * ```js
  177. * box.userData.physics = { mass: 1, restitution: 0 };
  178. * ```
  179. *
  180. * @method
  181. * @name JoltPhysics#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 JoltPhysics#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/friction of the mesh.
  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 JoltPhysics#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. // NOOP
  207. setMeshVelocity: setMeshVelocity
  208. };
  209. }
  210. export { JoltPhysics };