JoltPhysics.js 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  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. console.error( 'JoltPhysics: Unsupported geometry type:', geometry.type );
  18. return null;
  19. }
  20. // Object layers
  21. const LAYER_NON_MOVING = 0;
  22. const LAYER_MOVING = 1;
  23. const NUM_OBJECT_LAYERS = 2;
  24. function setupCollisionFiltering( settings ) {
  25. const objectFilter = new Jolt.ObjectLayerPairFilterTable( NUM_OBJECT_LAYERS );
  26. objectFilter.EnableCollision( LAYER_NON_MOVING, LAYER_MOVING );
  27. objectFilter.EnableCollision( LAYER_MOVING, LAYER_MOVING );
  28. const BP_LAYER_NON_MOVING = new Jolt.BroadPhaseLayer( 0 );
  29. const BP_LAYER_MOVING = new Jolt.BroadPhaseLayer( 1 );
  30. const NUM_BROAD_PHASE_LAYERS = 2;
  31. const bpInterface = new Jolt.BroadPhaseLayerInterfaceTable( NUM_OBJECT_LAYERS, NUM_BROAD_PHASE_LAYERS );
  32. bpInterface.MapObjectToBroadPhaseLayer( LAYER_NON_MOVING, BP_LAYER_NON_MOVING );
  33. bpInterface.MapObjectToBroadPhaseLayer( LAYER_MOVING, BP_LAYER_MOVING );
  34. settings.mObjectLayerPairFilter = objectFilter;
  35. settings.mBroadPhaseLayerInterface = bpInterface;
  36. settings.mObjectVsBroadPhaseLayerFilter = new Jolt.ObjectVsBroadPhaseLayerFilterTable( settings.mBroadPhaseLayerInterface, NUM_BROAD_PHASE_LAYERS, settings.mObjectLayerPairFilter, NUM_OBJECT_LAYERS );
  37. }
  38. /**
  39. * @classdesc Can be used to include Jolt as a Physics engine into
  40. * `three.js` apps. The API can be initialized via:
  41. * ```js
  42. * const physics = await JoltPhysics();
  43. * ```
  44. * The component automatically imports Jolt from a CDN so make sure
  45. * to use the component with an active Internet connection.
  46. *
  47. * @name JoltPhysics
  48. * @class
  49. * @hideconstructor
  50. * @three_import import { JoltPhysics } from 'three/addons/physics/JoltPhysics.js';
  51. */
  52. async function JoltPhysics() {
  53. if ( Jolt === null ) {
  54. const { default: initJolt } = await import( JOLT_PATH /* @vite-ignore */ );
  55. Jolt = await initJolt();
  56. }
  57. const settings = new Jolt.JoltSettings();
  58. setupCollisionFiltering( settings );
  59. const jolt = new Jolt.JoltInterface( settings );
  60. Jolt.destroy( settings );
  61. const physicsSystem = jolt.GetPhysicsSystem();
  62. const bodyInterface = physicsSystem.GetBodyInterface();
  63. const meshes = [];
  64. const meshMap = new WeakMap();
  65. const _position = new Vector3();
  66. const _quaternion = new Quaternion();
  67. const _scale = new Vector3( 1, 1, 1 );
  68. const _matrix = new Matrix4();
  69. function addScene( scene ) {
  70. scene.traverse( function ( child ) {
  71. if ( child.isMesh ) {
  72. const physics = child.userData.physics;
  73. if ( physics ) {
  74. addMesh( child, physics.mass, physics.restitution );
  75. }
  76. }
  77. } );
  78. }
  79. function addMesh( mesh, mass = 0, restitution = 0 ) {
  80. const shape = getShape( mesh.geometry );
  81. if ( shape === null ) return;
  82. const body = mesh.isInstancedMesh
  83. ? createInstancedBody( mesh, mass, restitution, shape )
  84. : createBody( mesh.position, mesh.quaternion, mass, restitution, shape );
  85. if ( mass > 0 ) {
  86. meshes.push( mesh );
  87. meshMap.set( mesh, body );
  88. }
  89. }
  90. function createInstancedBody( mesh, mass, restitution, shape ) {
  91. const array = mesh.instanceMatrix.array;
  92. const bodies = [];
  93. for ( let i = 0; i < mesh.count; i ++ ) {
  94. const position = _position.fromArray( array, i * 16 + 12 );
  95. const quaternion = _quaternion.setFromRotationMatrix( _matrix.fromArray( array, i * 16 ) ); // TODO Copilot did this
  96. bodies.push( createBody( position, quaternion, mass, restitution, shape ) );
  97. }
  98. return bodies;
  99. }
  100. function createBody( position, rotation, mass, restitution, shape ) {
  101. const pos = new Jolt.Vec3( position.x, position.y, position.z );
  102. const rot = new Jolt.Quat( rotation.x, rotation.y, rotation.z, rotation.w );
  103. const motion = mass > 0 ? Jolt.EMotionType_Dynamic : Jolt.EMotionType_Static;
  104. const layer = mass > 0 ? LAYER_MOVING : LAYER_NON_MOVING;
  105. const creationSettings = new Jolt.BodyCreationSettings( shape, pos, rot, motion, layer );
  106. creationSettings.mRestitution = restitution;
  107. const body = bodyInterface.CreateBody( creationSettings );
  108. bodyInterface.AddBody( body.GetID(), Jolt.EActivation_Activate );
  109. Jolt.destroy( creationSettings );
  110. return body;
  111. }
  112. function setMeshPosition( mesh, position, index = 0 ) {
  113. if ( mesh.isInstancedMesh ) {
  114. const bodies = meshMap.get( mesh );
  115. const body = bodies[ index ];
  116. bodyInterface.RemoveBody( body.GetID() );
  117. bodyInterface.DestroyBody( body.GetID() );
  118. const physics = mesh.userData.physics;
  119. const shape = body.GetShape();
  120. const body2 = createBody( position, { x: 0, y: 0, z: 0, w: 1 }, physics.mass, physics.restitution, shape );
  121. bodies[ index ] = body2;
  122. } else {
  123. // TODO: Implement this
  124. }
  125. }
  126. function setMeshVelocity( mesh, velocity, index = 0 ) {
  127. /*
  128. let body = meshMap.get( mesh );
  129. if ( mesh.isInstancedMesh ) {
  130. body = body[ index ];
  131. }
  132. body.setLinvel( velocity );
  133. */
  134. }
  135. //
  136. const clock = new Clock();
  137. function step() {
  138. let deltaTime = clock.getDelta();
  139. // Don't go below 30 Hz to prevent spiral of death
  140. deltaTime = Math.min( deltaTime, 1.0 / 30.0 );
  141. // When running below 55 Hz, do 2 steps instead of 1
  142. const numSteps = deltaTime > 1.0 / 55.0 ? 2 : 1;
  143. // Step the physics world
  144. jolt.Step( deltaTime, numSteps );
  145. //
  146. for ( let i = 0, l = meshes.length; i < l; i ++ ) {
  147. const mesh = meshes[ i ];
  148. if ( mesh.isInstancedMesh ) {
  149. const array = mesh.instanceMatrix.array;
  150. const bodies = meshMap.get( mesh );
  151. for ( let j = 0; j < bodies.length; j ++ ) {
  152. const body = bodies[ j ];
  153. const position = body.GetPosition();
  154. const quaternion = body.GetRotation();
  155. _position.set( position.GetX(), position.GetY(), position.GetZ() );
  156. _quaternion.set( quaternion.GetX(), quaternion.GetY(), quaternion.GetZ(), quaternion.GetW() );
  157. _matrix.compose( _position, _quaternion, _scale ).toArray( array, j * 16 );
  158. }
  159. mesh.instanceMatrix.needsUpdate = true;
  160. mesh.computeBoundingSphere();
  161. } else {
  162. const body = meshMap.get( mesh );
  163. const position = body.GetPosition();
  164. const rotation = body.GetRotation();
  165. mesh.position.set( position.GetX(), position.GetY(), position.GetZ() );
  166. mesh.quaternion.set( rotation.GetX(), rotation.GetY(), rotation.GetZ(), rotation.GetW() );
  167. }
  168. }
  169. }
  170. // animate
  171. setInterval( step, 1000 / frameRate );
  172. return {
  173. /**
  174. * Adds the given scene to this physics simulation. Only meshes with a
  175. * `physics` object in their {@link Object3D#userData} field will be honored.
  176. * The object can be used to store the mass and restitution of the mesh. E.g.:
  177. * ```js
  178. * box.userData.physics = { mass: 1, restitution: 0 };
  179. * ```
  180. *
  181. * @method
  182. * @name JoltPhysics#addScene
  183. * @param {Object3D} scene The scene or any type of 3D object to add.
  184. */
  185. addScene: addScene,
  186. /**
  187. * Adds the given mesh to this physics simulation.
  188. *
  189. * @method
  190. * @name JoltPhysics#addMesh
  191. * @param {Mesh} mesh The mesh to add.
  192. * @param {number} [mass=0] The mass in kg of the mesh.
  193. * @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.
  194. */
  195. addMesh: addMesh,
  196. /**
  197. * Set the position of the given mesh which is part of the physics simulation. Calling this
  198. * method will reset the current simulated velocity of the mesh.
  199. *
  200. * @method
  201. * @name JoltPhysics#setMeshPosition
  202. * @param {Mesh} mesh The mesh to update the position for.
  203. * @param {Vector3} position - The new position.
  204. * @param {number} [index=0] - If the mesh is instanced, the index represents the instanced ID.
  205. */
  206. setMeshPosition: setMeshPosition,
  207. // NOOP
  208. setMeshVelocity: setMeshVelocity
  209. };
  210. }
  211. export { JoltPhysics };
粤ICP备19079148号