JoltPhysics.js 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. import { Clock, Vector3, Quaternion, Matrix4 } from 'three';
  2. const JOLT_PATH = 'https://cdn.jsdelivr.net/npm/[email protected]/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. let 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. let 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. async function JoltPhysics() {
  38. if ( Jolt === null ) {
  39. const { default: initJolt } = await import( JOLT_PATH );
  40. Jolt = await initJolt();
  41. }
  42. const settings = new Jolt.JoltSettings();
  43. setupCollisionFiltering( settings );
  44. const jolt = new Jolt.JoltInterface( settings );
  45. Jolt.destroy( settings );
  46. const physicsSystem = jolt.GetPhysicsSystem();
  47. const bodyInterface = physicsSystem.GetBodyInterface();
  48. const meshes = [];
  49. const meshMap = new WeakMap();
  50. const _position = new Vector3();
  51. const _quaternion = new Quaternion();
  52. const _scale = new Vector3( 1, 1, 1 );
  53. const _matrix = new Matrix4();
  54. function addScene( scene ) {
  55. scene.traverse( function ( child ) {
  56. if ( child.isMesh ) {
  57. const physics = child.userData.physics;
  58. if ( physics ) {
  59. addMesh( child, physics.mass, physics.restitution );
  60. }
  61. }
  62. } );
  63. }
  64. function addMesh( mesh, mass = 0, restitution = 0 ) {
  65. const shape = getShape( mesh.geometry );
  66. if ( shape === null ) return;
  67. const body = mesh.isInstancedMesh
  68. ? createInstancedBody( mesh, mass, restitution, shape )
  69. : createBody( mesh.position, mesh.quaternion, mass, restitution, shape );
  70. if ( mass > 0 ) {
  71. meshes.push( mesh );
  72. meshMap.set( mesh, body );
  73. }
  74. }
  75. function createInstancedBody( mesh, mass, restitution, shape ) {
  76. const array = mesh.instanceMatrix.array;
  77. const bodies = [];
  78. for ( let i = 0; i < mesh.count; i ++ ) {
  79. const position = _position.fromArray( array, i * 16 + 12 );
  80. const quaternion = _quaternion.setFromRotationMatrix( _matrix.fromArray( array, i * 16 ) ); // TODO Copilot did this
  81. bodies.push( createBody( position, quaternion, mass, restitution, shape ) );
  82. }
  83. return bodies;
  84. }
  85. function createBody( position, rotation, mass, restitution, shape ) {
  86. const pos = new Jolt.Vec3( position.x, position.y, position.z );
  87. const rot = new Jolt.Quat( rotation.x, rotation.y, rotation.z, rotation.w );
  88. const motion = mass > 0 ? Jolt.EMotionType_Dynamic : Jolt.EMotionType_Static;
  89. const layer = mass > 0 ? LAYER_MOVING : LAYER_NON_MOVING;
  90. const creationSettings = new Jolt.BodyCreationSettings( shape, pos, rot, motion, layer );
  91. creationSettings.mRestitution = restitution;
  92. const body = bodyInterface.CreateBody( creationSettings );
  93. bodyInterface.AddBody( body.GetID(), Jolt.EActivation_Activate );
  94. Jolt.destroy( creationSettings );
  95. return body;
  96. }
  97. function setMeshPosition( mesh, position, index = 0 ) {
  98. if ( mesh.isInstancedMesh ) {
  99. const bodies = meshMap.get( mesh );
  100. const body = bodies[ index ];
  101. bodyInterface.RemoveBody( body.GetID() );
  102. bodyInterface.DestroyBody( body.GetID() );
  103. const physics = mesh.userData.physics;
  104. let shape = body.GetShape();
  105. let body2 = createBody( position, { x: 0, y: 0, z: 0, w: 1 }, physics.mass, physics.restitution, shape );
  106. bodies[ index ] = body2;
  107. } else {
  108. // TODO: Implement this
  109. }
  110. }
  111. function setMeshVelocity( mesh, velocity, index = 0 ) {
  112. /*
  113. let body = meshMap.get( mesh );
  114. if ( mesh.isInstancedMesh ) {
  115. body = body[ index ];
  116. }
  117. body.setLinvel( velocity );
  118. */
  119. }
  120. //
  121. const clock = new Clock();
  122. function step() {
  123. let deltaTime = clock.getDelta();
  124. // Don't go below 30 Hz to prevent spiral of death
  125. deltaTime = Math.min( deltaTime, 1.0 / 30.0 );
  126. // When running below 55 Hz, do 2 steps instead of 1
  127. const numSteps = deltaTime > 1.0 / 55.0 ? 2 : 1;
  128. // Step the physics world
  129. jolt.Step( deltaTime, numSteps );
  130. //
  131. for ( let i = 0, l = meshes.length; i < l; i ++ ) {
  132. const mesh = meshes[ i ];
  133. if ( mesh.isInstancedMesh ) {
  134. const array = mesh.instanceMatrix.array;
  135. const bodies = meshMap.get( mesh );
  136. for ( let j = 0; j < bodies.length; j ++ ) {
  137. const body = bodies[ j ];
  138. const position = body.GetPosition();
  139. const quaternion = body.GetRotation();
  140. _position.set( position.GetX(), position.GetY(), position.GetZ() );
  141. _quaternion.set( quaternion.GetX(), quaternion.GetY(), quaternion.GetZ(), quaternion.GetW() );
  142. _matrix.compose( _position, _quaternion, _scale ).toArray( array, j * 16 );
  143. }
  144. mesh.instanceMatrix.needsUpdate = true;
  145. mesh.computeBoundingSphere();
  146. } else {
  147. const body = meshMap.get( mesh );
  148. const position = body.GetPosition();
  149. const rotation = body.GetRotation();
  150. mesh.position.set( position.GetX(), position.GetY(), position.GetZ() );
  151. mesh.quaternion.set( rotation.GetX(), rotation.GetY(), rotation.GetZ(), rotation.GetW() );
  152. }
  153. }
  154. }
  155. // animate
  156. setInterval( step, 1000 / frameRate );
  157. return {
  158. addScene: addScene,
  159. addMesh: addMesh,
  160. setMeshPosition: setMeshPosition,
  161. setMeshVelocity: setMeshVelocity
  162. };
  163. }
  164. export { JoltPhysics };