RapierPhysics.js 10 KB

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