RapierPhysics.js 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  1. import { Clock, Vector3, Quaternion, Matrix4 } from 'three';
  2. const RAPIER_PATH = 'https://cdn.skypack.dev/@dimforge/rapier3d-compat@0.12.0';
  3. const frameRate = 60;
  4. const _scale = new Vector3( 1, 1, 1 );
  5. const ZERO = new Vector3();
  6. let RAPIER = null;
  7. function getShape( geometry ) {
  8. const parameters = geometry.parameters;
  9. // TODO change type to is*
  10. if ( geometry.type === 'BoxGeometry' ) {
  11. const sx = parameters.width !== undefined ? parameters.width / 2 : 0.5;
  12. const sy = parameters.height !== undefined ? parameters.height / 2 : 0.5;
  13. const sz = parameters.depth !== undefined ? parameters.depth / 2 : 0.5;
  14. return RAPIER.ColliderDesc.cuboid( sx, sy, sz );
  15. } else if ( geometry.type === 'SphereGeometry' || geometry.type === 'IcosahedronGeometry' ) {
  16. const radius = parameters.radius !== undefined ? parameters.radius : 1;
  17. return RAPIER.ColliderDesc.ball( radius );
  18. } else if ( geometry.type === 'CylinderGeometry' ) {
  19. const radius = parameters.radiusBottom !== undefined ? parameters.radiusBottom : 0.5;
  20. const length = parameters.height !== undefined ? parameters.height : 0.5;
  21. return RAPIER.ColliderDesc.cylinder( length / 2, radius );
  22. } else if ( geometry.type === 'CapsuleGeometry' ) {
  23. const radius = parameters.radius !== undefined ? parameters.radius : 0.5;
  24. const length = parameters.height !== undefined ? parameters.height : 0.5;
  25. return RAPIER.ColliderDesc.capsule( length / 2, radius );
  26. } else if ( geometry.type === 'BufferGeometry' ) {
  27. const vertices = [];
  28. const vertex = new Vector3();
  29. const position = geometry.getAttribute( 'position' );
  30. for ( let i = 0; i < position.count; i ++ ) {
  31. vertex.fromBufferAttribute( position, i );
  32. vertices.push( vertex.x, vertex.y, vertex.z );
  33. }
  34. // if the buffer is non-indexed, generate an index buffer
  35. const indices = geometry.getIndex() === null
  36. ? Uint32Array.from( Array( parseInt( vertices.length / 3 ) ).keys() )
  37. : geometry.getIndex().array;
  38. return RAPIER.ColliderDesc.trimesh( vertices, indices );
  39. }
  40. return null;
  41. }
  42. /**
  43. * @classdesc Can be used to include Rapier as a Physics engine into
  44. * `three.js` apps. The API can be initialized via:
  45. * ```js
  46. * const physics = await RapierPhysics();
  47. * ```
  48. * The component automatically imports Rapier from a CDN so make sure
  49. * to use the component with an active Internet connection.
  50. *
  51. * @name RapierPhysics
  52. * @class
  53. * @hideconstructor
  54. * @three_import import { RapierPhysics } from 'three/addons/physics/RapierPhysics.js';
  55. */
  56. async function RapierPhysics() {
  57. if ( RAPIER === null ) {
  58. RAPIER = await import( `${RAPIER_PATH}` );
  59. await RAPIER.init();
  60. }
  61. // Docs: https://rapier.rs/docs/api/javascript/JavaScript3D/
  62. const gravity = new Vector3( 0.0, - 9.81, 0.0 );
  63. const world = new RAPIER.World( gravity );
  64. const meshes = [];
  65. const meshMap = new WeakMap();
  66. const _vector = new Vector3();
  67. const _quaternion = new Quaternion();
  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. shape.setMass( mass );
  83. shape.setRestitution( restitution );
  84. const body = mesh.isInstancedMesh
  85. ? createInstancedBody( mesh, mass, shape )
  86. : createBody( mesh.position, mesh.quaternion, mass, shape );
  87. if ( ! mesh.userData.physics ) mesh.userData.physics = {};
  88. mesh.userData.physics.body = body;
  89. if ( mass > 0 ) {
  90. meshes.push( mesh );
  91. meshMap.set( mesh, body );
  92. }
  93. }
  94. function createInstancedBody( mesh, mass, shape ) {
  95. const array = mesh.instanceMatrix.array;
  96. const bodies = [];
  97. for ( let i = 0; i < mesh.count; i ++ ) {
  98. const position = _vector.fromArray( array, i * 16 + 12 );
  99. bodies.push( createBody( position, null, mass, shape ) );
  100. }
  101. return bodies;
  102. }
  103. function createBody( position, quaternion, mass, shape ) {
  104. const desc = mass > 0 ? RAPIER.RigidBodyDesc.dynamic() : RAPIER.RigidBodyDesc.fixed();
  105. desc.setTranslation( ...position );
  106. if ( quaternion !== null ) desc.setRotation( quaternion );
  107. const body = world.createRigidBody( desc );
  108. world.createCollider( shape, body );
  109. return body;
  110. }
  111. function setMeshPosition( mesh, position, index = 0 ) {
  112. let body = meshMap.get( mesh );
  113. if ( mesh.isInstancedMesh ) {
  114. body = body[ index ];
  115. }
  116. body.setAngvel( ZERO );
  117. body.setLinvel( ZERO );
  118. body.setTranslation( position );
  119. }
  120. function setMeshVelocity( mesh, velocity, index = 0 ) {
  121. let body = meshMap.get( mesh );
  122. if ( mesh.isInstancedMesh ) {
  123. body = body[ index ];
  124. }
  125. body.setLinvel( velocity );
  126. }
  127. function addHeightfield( mesh, width, depth, heights, scale ) {
  128. const shape = RAPIER.ColliderDesc.heightfield( width, depth, heights, scale );
  129. const bodyDesc = RAPIER.RigidBodyDesc.fixed();
  130. bodyDesc.setTranslation( mesh.position.x, mesh.position.y, mesh.position.z );
  131. bodyDesc.setRotation( mesh.quaternion );
  132. const body = world.createRigidBody( bodyDesc );
  133. world.createCollider( shape, body );
  134. if ( ! mesh.userData.physics ) mesh.userData.physics = {};
  135. mesh.userData.physics.body = body;
  136. return body;
  137. }
  138. //
  139. const clock = new Clock();
  140. function step() {
  141. world.timestep = clock.getDelta();
  142. world.step();
  143. //
  144. for ( let i = 0, l = meshes.length; i < l; i ++ ) {
  145. const mesh = meshes[ i ];
  146. if ( mesh.isInstancedMesh ) {
  147. const array = mesh.instanceMatrix.array;
  148. const bodies = meshMap.get( mesh );
  149. for ( let j = 0; j < bodies.length; j ++ ) {
  150. const body = bodies[ j ];
  151. const position = body.translation();
  152. _quaternion.copy( body.rotation() );
  153. _matrix.compose( position, _quaternion, _scale ).toArray( array, j * 16 );
  154. }
  155. mesh.instanceMatrix.needsUpdate = true;
  156. mesh.computeBoundingSphere();
  157. } else {
  158. const body = meshMap.get( mesh );
  159. mesh.position.copy( body.translation() );
  160. mesh.quaternion.copy( body.rotation() );
  161. }
  162. }
  163. }
  164. // animate
  165. setInterval( step, 1000 / frameRate );
  166. return {
  167. RAPIER,
  168. world,
  169. /**
  170. * Adds the given scene to this physics simulation. Only meshes with a
  171. * `physics` object in their {@link Object3D#userData} field will be honored.
  172. * The object can be used to store the mass and restitution of the mesh. E.g.:
  173. * ```js
  174. * box.userData.physics = { mass: 1, restitution: 0 };
  175. * ```
  176. *
  177. * @method
  178. * @name RapierPhysics#addScene
  179. * @param {Object3D} scene The scene or any type of 3D object to add.
  180. */
  181. addScene: addScene,
  182. /**
  183. * Adds the given mesh to this physics simulation.
  184. *
  185. * @method
  186. * @name RapierPhysics#addMesh
  187. * @param {Mesh} mesh The mesh to add.
  188. * @param {number} [mass=0] The mass in kg of the mesh.
  189. * @param {number} [restitution=0] The restitution/friction of the mesh.
  190. */
  191. addMesh: addMesh,
  192. /**
  193. * Set the position of the given mesh which is part of the physics simulation. Calling this
  194. * method will reset the current simulated velocity of the mesh.
  195. *
  196. * @method
  197. * @name RapierPhysics#setMeshPosition
  198. * @param {Mesh} mesh The mesh to update the position for.
  199. * @param {Vector3} position - The new position.
  200. * @param {number} [index=0] - If the mesh is instanced, the index represents the instanced ID.
  201. */
  202. setMeshPosition: setMeshPosition,
  203. /**
  204. * Set the velocity of the given mesh which is part of the physics simulation.
  205. *
  206. * @method
  207. * @name RapierPhysics#setMeshVelocity
  208. * @param {Mesh} mesh The mesh to update the velocity for.
  209. * @param {Vector3} velocity - The new velocity.
  210. * @param {number} [index=0] - If the mesh is instanced, the index represents the instanced ID.
  211. */
  212. setMeshVelocity: setMeshVelocity,
  213. /**
  214. * Adds a heightfield terrain to the physics simulation.
  215. *
  216. * @method
  217. * @name RapierPhysics#addHeightfield
  218. * @param {Mesh} mesh - The Three.js mesh representing the terrain.
  219. * @param {number} width - The number of vertices along the width (x-axis) of the heightfield.
  220. * @param {number} depth - The number of vertices along the depth (z-axis) of the heightfield.
  221. * @param {Float32Array} heights - Array of height values for each vertex in the heightfield.
  222. * @param {Object} scale - Scale factors for the heightfield dimensions.
  223. * @param {number} scale.x - Scale factor for width.
  224. * @param {number} scale.y - Scale factor for height.
  225. * @param {number} scale.z - Scale factor for depth.
  226. * @returns {RigidBody} The created Rapier rigid body for the heightfield.
  227. */
  228. addHeightfield: addHeightfield
  229. };
  230. }
  231. export { RapierPhysics };