babylon.ammoJSPlugin.ts 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760
  1. module BABYLON {
  2. declare var Ammo: any;
  3. /**
  4. * AmmoJS Physics plugin
  5. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  6. * @see https://github.com/kripken/ammo.js/
  7. */
  8. export class AmmoJSPlugin implements IPhysicsEnginePlugin {
  9. /**
  10. * Reference to the Ammo library
  11. */
  12. public bjsAMMO: any;
  13. /**
  14. * Created ammoJS world which physics bodies are added to
  15. */
  16. public world: any;
  17. /**
  18. * Name of the plugin
  19. */
  20. public name: string = "AmmoJSPlugin";
  21. private _timeStep: number = 1 / 60;
  22. private _fixedTimeStep: number = 1 / 60;
  23. private _maxSteps = 5;
  24. private _tmpQuaternion = new BABYLON.Quaternion();
  25. private _tmpAmmoTransform: any;
  26. private _tmpAmmoQuaternion: any;
  27. private _tmpAmmoConcreteContactResultCallback: any;
  28. private _collisionConfiguration: any;
  29. private _dispatcher: any;
  30. private _overlappingPairCache: any;
  31. private _solver: any;
  32. private _tmpAmmoVectorA: any;
  33. private _tmpAmmoVectorB: any;
  34. private _tmpAmmoVectorC: any;
  35. private _tmpContactCallbackResult = false;
  36. private static readonly DISABLE_COLLISION_FLAG = 4;
  37. private static readonly KINEMATIC_FLAG = 2;
  38. private static readonly DISABLE_DEACTIVATION_FLAG = 4;
  39. /**
  40. * Initializes the ammoJS plugin
  41. * @param _useDeltaForWorldStep if the time between frames should be used when calculating physics steps (Default: true)
  42. */
  43. public constructor(private _useDeltaForWorldStep: boolean = true) {
  44. if (typeof Ammo === "function") {
  45. Ammo();
  46. }
  47. this.bjsAMMO = Ammo;
  48. if (!this.isSupported()) {
  49. Tools.Error("AmmoJS is not available. Please make sure you included the js file.");
  50. return;
  51. }
  52. // Initialize the physics world
  53. this._collisionConfiguration = new this.bjsAMMO.btDefaultCollisionConfiguration();
  54. this._dispatcher = new this.bjsAMMO.btCollisionDispatcher(this._collisionConfiguration);
  55. this._overlappingPairCache = new this.bjsAMMO.btDbvtBroadphase();
  56. this._solver = new this.bjsAMMO.btSequentialImpulseConstraintSolver();
  57. this.world = new this.bjsAMMO.btDiscreteDynamicsWorld(this._dispatcher, this._overlappingPairCache, this._solver, this._collisionConfiguration);
  58. this._tmpAmmoConcreteContactResultCallback = new this.bjsAMMO.ConcreteContactResultCallback();
  59. this._tmpAmmoConcreteContactResultCallback.addSingleResult = () => { this._tmpContactCallbackResult = true; };
  60. // Create temp ammo variables
  61. this._tmpAmmoTransform = new this.bjsAMMO.btTransform();
  62. this._tmpAmmoTransform.setIdentity();
  63. this._tmpAmmoQuaternion = new this.bjsAMMO.btQuaternion(0, 0, 0, 1);
  64. this._tmpAmmoVectorA = new this.bjsAMMO.btVector3(0, 0, 0);
  65. this._tmpAmmoVectorB = new this.bjsAMMO.btVector3(0, 0, 0);
  66. this._tmpAmmoVectorC = new this.bjsAMMO.btVector3(0, 0, 0);
  67. }
  68. /**
  69. * Sets the gravity of the physics world (m/(s^2))
  70. * @param gravity Gravity to set
  71. */
  72. public setGravity(gravity: Vector3): void {
  73. this._tmpAmmoVectorA.setValue(gravity.x, gravity.y, gravity.z);
  74. this.world.setGravity(this._tmpAmmoVectorA);
  75. }
  76. /**
  77. * Amount of time to step forward on each frame (only used if useDeltaForWorldStep is false in the constructor)
  78. * @param timeStep timestep to use in seconds
  79. */
  80. public setTimeStep(timeStep: number) {
  81. this._timeStep = timeStep;
  82. }
  83. /**
  84. * Increment to step forward in the physics engine (If timeStep is set to 1/60 and fixedTimeStep is set to 1/120 the physics engine should run 2 steps per frame) (Default: 1/60)
  85. * @param fixedTimeStep fixedTimeStep to use in seconds
  86. */
  87. public setFixedTimeStep(fixedTimeStep: number) {
  88. this._fixedTimeStep = fixedTimeStep;
  89. }
  90. /**
  91. * Sets the maximum number of steps by the physics engine per frame (Default: 5)
  92. * @param maxSteps the maximum number of steps by the physics engine per frame
  93. */
  94. public setMaxSteps(maxSteps: number) {
  95. this._maxSteps = maxSteps;
  96. }
  97. /**
  98. * Gets the current timestep (only used if useDeltaForWorldStep is false in the constructor)
  99. * @returns the current timestep in seconds
  100. */
  101. public getTimeStep(): number {
  102. return this._timeStep;
  103. }
  104. // Ammo's contactTest and contactPairTest take a callback that runs synchronously, wrap them so that they are easier to consume
  105. private _isImpostorInContact(impostor: PhysicsImpostor) {
  106. this._tmpContactCallbackResult = false;
  107. this.world.contactTest(impostor.physicsBody, this._tmpAmmoConcreteContactResultCallback);
  108. return this._tmpContactCallbackResult;
  109. }
  110. // Ammo's collision events have some weird quirks
  111. // contactPairTest fires too many events as it fires events even when objects are close together but contactTest does not
  112. // so only fire event if both contactTest and contactPairTest have a hit
  113. private _isImpostorPairInContact(impostorA: PhysicsImpostor, impostorB: PhysicsImpostor) {
  114. this._tmpContactCallbackResult = false;
  115. this.world.contactPairTest(impostorA.physicsBody, impostorB.physicsBody, this._tmpAmmoConcreteContactResultCallback);
  116. return this._tmpContactCallbackResult;
  117. }
  118. // Ammo's behavior when maxSteps > 0 does not behave as described in docs
  119. // @see http://www.bulletphysics.org/mediawiki-1.5.8/index.php/Stepping_The_World
  120. //
  121. // When maxSteps is 0 do the entire simulation in one step
  122. // When maxSteps is > 0, run up to maxStep times, if on the last step the (remaining step - fixedTimeStep) is < fixedTimeStep, the remainder will be used for the step. (eg. if remainder is 1.001 and fixedTimeStep is 1 the last step will be 1.001, if instead it did 2 steps (1, 0.001) issues occuered when having a tiny step in ammo)
  123. // Note: To get deterministic physics, timeStep would always need to be divisible by fixedTimeStep
  124. private _stepSimulation(timeStep: number = 1 / 60, maxSteps: number = 10, fixedTimeStep: number = 1 / 60) {
  125. if (maxSteps == 0) {
  126. this.world.stepSimulation(timeStep, 0);
  127. }else {
  128. while (maxSteps > 0 && timeStep > 0) {
  129. if (timeStep - fixedTimeStep < fixedTimeStep) {
  130. this.world.stepSimulation(timeStep, 0);
  131. timeStep = 0;
  132. }else {
  133. timeStep -= fixedTimeStep;
  134. this.world.stepSimulation(fixedTimeStep, 0);
  135. }
  136. maxSteps--;
  137. }
  138. }
  139. }
  140. /**
  141. * Moves the physics simulation forward delta seconds and updates the given physics imposters
  142. * Prior to the step the imposters physics location is set to the position of the babylon meshes
  143. * After the step the babylon meshes are set to the position of the physics imposters
  144. * @param delta amount of time to step forward
  145. * @param impostors array of imposters to update before/after the step
  146. */
  147. public executeStep(delta: number, impostors: Array<PhysicsImpostor>): void {
  148. for (var impostor of impostors) {
  149. // Update physics world objects to match babylon world
  150. impostor.beforeStep();
  151. }
  152. this._stepSimulation(this._useDeltaForWorldStep ? delta : this._timeStep, this._maxSteps, this._fixedTimeStep);
  153. for (var mainImpostor of impostors) {
  154. // After physics update make babylon world objects match physics world objects
  155. mainImpostor.afterStep();
  156. // Handle collision event
  157. if (mainImpostor._onPhysicsCollideCallbacks.length > 0) {
  158. if (this._isImpostorInContact(mainImpostor)) {
  159. for (var collideCallback of mainImpostor._onPhysicsCollideCallbacks) {
  160. for (var otherImpostor of collideCallback.otherImpostors) {
  161. if (mainImpostor.physicsBody.isActive() || otherImpostor.physicsBody.isActive()) {
  162. if (this._isImpostorPairInContact(mainImpostor, otherImpostor)) {
  163. mainImpostor.onCollide({ body: otherImpostor.physicsBody });
  164. otherImpostor.onCollide({ body: mainImpostor.physicsBody });
  165. }
  166. }
  167. }
  168. }
  169. }
  170. }
  171. }
  172. }
  173. /**
  174. * Applies an implulse on the imposter
  175. * @param impostor imposter to apply impulse
  176. * @param force amount of force to be applied to the imposter
  177. * @param contactPoint the location to apply the impulse on the imposter
  178. */
  179. public applyImpulse(impostor: PhysicsImpostor, force: Vector3, contactPoint: Vector3) {
  180. var worldPoint = this._tmpAmmoVectorA;
  181. var impulse = this._tmpAmmoVectorB;
  182. worldPoint.setValue(contactPoint.x, contactPoint.y, contactPoint.z);
  183. impulse.setValue(force.x, force.y, force.z);
  184. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  185. }
  186. /**
  187. * Applies a force on the imposter
  188. * @param impostor imposter to apply force
  189. * @param force amount of force to be applied to the imposter
  190. * @param contactPoint the location to apply the force on the imposter
  191. */
  192. public applyForce(impostor: PhysicsImpostor, force: Vector3, contactPoint: Vector3) {
  193. var worldPoint = this._tmpAmmoVectorA;
  194. var impulse = this._tmpAmmoVectorB;
  195. worldPoint.setValue(contactPoint.x, contactPoint.y, contactPoint.z);
  196. impulse.setValue(force.x, force.y, force.z);
  197. impostor.physicsBody.applyForce(impulse, worldPoint);
  198. }
  199. /**
  200. * Creates a physics body using the plugin
  201. * @param impostor the imposter to create the physics body on
  202. */
  203. public generatePhysicsBody(impostor: PhysicsImpostor) {
  204. impostor._pluginData = {toDispose: []};
  205. //parent-child relationship
  206. if (impostor.parent) {
  207. if (impostor.physicsBody) {
  208. this.removePhysicsBody(impostor);
  209. impostor.forceUpdate();
  210. }
  211. return;
  212. }
  213. if (impostor.isBodyInitRequired()) {
  214. var colShape = this._createShape(impostor);
  215. var mass = impostor.getParam("mass");
  216. impostor._pluginData.mass = mass;
  217. var localInertia = new Ammo.btVector3(0, 0, 0);
  218. var startTransform = new Ammo.btTransform();
  219. startTransform.setIdentity();
  220. if (mass !== 0) {
  221. colShape.calculateLocalInertia(mass, localInertia);
  222. }
  223. this._tmpAmmoVectorA.setValue(impostor.object.position.x, impostor.object.position.y, impostor.object.position.z);
  224. this._tmpAmmoQuaternion.setValue(impostor.object.rotationQuaternion!.x, impostor.object.rotationQuaternion!.y, impostor.object.rotationQuaternion!.z, impostor.object.rotationQuaternion!.w);
  225. startTransform.setOrigin(this._tmpAmmoVectorA);
  226. startTransform.setRotation(this._tmpAmmoQuaternion);
  227. var myMotionState = new Ammo.btDefaultMotionState(startTransform);
  228. var rbInfo = new Ammo.btRigidBodyConstructionInfo(mass, myMotionState, colShape, localInertia);
  229. var body = new Ammo.btRigidBody(rbInfo);
  230. // Make objects kinematic if it's mass is 0
  231. if (mass === 0) {
  232. body.setCollisionFlags(body.getCollisionFlags() | AmmoJSPlugin.KINEMATIC_FLAG);
  233. body.setActivationState(AmmoJSPlugin.DISABLE_DEACTIVATION_FLAG);
  234. }
  235. // Disable collision if NoImpostor, but keep collision if shape is btCompoundShape
  236. if (impostor.type == BABYLON.PhysicsImpostor.NoImpostor && !colShape.getChildShape) {
  237. body.setCollisionFlags(body.getCollisionFlags() | AmmoJSPlugin.DISABLE_COLLISION_FLAG);
  238. }
  239. this.world.addRigidBody(body);
  240. impostor.physicsBody = body;
  241. this.setBodyRestitution(impostor, impostor.getParam("restitution"));
  242. this.setBodyFriction(impostor, impostor.getParam("friction"));
  243. impostor._pluginData.toDispose.concat([body, rbInfo, myMotionState, startTransform, localInertia, colShape]);
  244. }
  245. }
  246. /**
  247. * Removes the physics body from the imposter and disposes of the body's memory
  248. * @param impostor imposter to remove the physics body from
  249. */
  250. public removePhysicsBody(impostor: PhysicsImpostor) {
  251. if (this.world) {
  252. this.world.removeRigidBody(impostor.physicsBody);
  253. impostor._pluginData.toDispose.forEach((d: any) => {
  254. this.bjsAMMO.destroy(d);
  255. });
  256. }
  257. }
  258. /**
  259. * Generates a joint
  260. * @param impostorJoint the imposter joint to create the joint with
  261. */
  262. public generateJoint(impostorJoint: PhysicsImpostorJoint) {
  263. var mainBody = impostorJoint.mainImpostor.physicsBody;
  264. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  265. if (!mainBody || !connectedBody) {
  266. return;
  267. }
  268. var jointData = impostorJoint.joint.jointData;
  269. if (!jointData.mainPivot) {
  270. jointData.mainPivot = new Vector3(0, 0, 0);
  271. }
  272. if (!jointData.connectedPivot) {
  273. jointData.connectedPivot = new Vector3(0, 0, 0);
  274. }
  275. var joint: any;
  276. switch (impostorJoint.joint.type) {
  277. case PhysicsJoint.DistanceJoint:
  278. var distance = (<DistanceJointData>jointData).maxDistance;
  279. if (distance) {
  280. jointData.mainPivot = new Vector3(0, -distance / 2, 0);
  281. jointData.connectedPivot = new Vector3(0, distance / 2, 0);
  282. }
  283. joint = new Ammo.btPoint2PointConstraint(mainBody, connectedBody, new Ammo.btVector3(jointData.mainPivot.x, jointData.mainPivot.y, jointData.mainPivot.z), new Ammo.btVector3(jointData.connectedPivot.x, jointData.connectedPivot.y, jointData.connectedPivot.z));
  284. break;
  285. case PhysicsJoint.HingeJoint:
  286. if (!jointData.mainAxis) {
  287. jointData.mainAxis = new Vector3(0, 0, 0);
  288. }
  289. if (!jointData.connectedAxis) {
  290. jointData.connectedAxis = new Vector3(0, 0, 0);
  291. }
  292. var mainAxis = new Ammo.btVector3(jointData.mainAxis.x, jointData.mainAxis.y, jointData.mainAxis.z);
  293. var connectedAxis = new Ammo.btVector3(jointData.connectedAxis.x, jointData.connectedAxis.y, jointData.connectedAxis.z);
  294. joint = new Ammo.btHingeConstraint(mainBody, connectedBody, new Ammo.btVector3(jointData.mainPivot.x, jointData.mainPivot.y, jointData.mainPivot.z), new Ammo.btVector3(jointData.connectedPivot.x, jointData.connectedPivot.y, jointData.connectedPivot.z), mainAxis, connectedAxis);
  295. break;
  296. case PhysicsJoint.BallAndSocketJoint:
  297. joint = new Ammo.btPoint2PointConstraint(mainBody, connectedBody, new Ammo.btVector3(jointData.mainPivot.x, jointData.mainPivot.y, jointData.mainPivot.z), new Ammo.btVector3(jointData.connectedPivot.x, jointData.connectedPivot.y, jointData.connectedPivot.z));
  298. break;
  299. default:
  300. Tools.Warn("JointType not currently supported by the Ammo plugin, falling back to PhysicsJoint.BallAndSocketJoint");
  301. joint = new Ammo.btPoint2PointConstraint(mainBody, connectedBody, new Ammo.btVector3(jointData.mainPivot.x, jointData.mainPivot.y, jointData.mainPivot.z), new Ammo.btVector3(jointData.connectedPivot.x, jointData.connectedPivot.y, jointData.connectedPivot.z));
  302. break;
  303. }
  304. this.world.addConstraint(joint, true);
  305. impostorJoint.joint.physicsJoint = joint;
  306. }
  307. /**
  308. * Removes a joint
  309. * @param impostorJoint the imposter joint to remove the joint from
  310. */
  311. public removeJoint(impostorJoint: PhysicsImpostorJoint) {
  312. if (this.world) {
  313. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  314. }
  315. }
  316. // adds all verticies (including child verticies) to the triangle mesh
  317. private _addMeshVerts(btTriangleMesh: any, topLevelObject: IPhysicsEnabledObject, object: IPhysicsEnabledObject) {
  318. var triangleCount = 0;
  319. if (object && object.getIndices && object.getWorldMatrix && object.getChildMeshes) {
  320. var indices = object.getIndices();
  321. if (!indices) {
  322. indices = [];
  323. }
  324. var vertexPositions = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  325. if (!vertexPositions) {
  326. vertexPositions = [];
  327. }
  328. object.computeWorldMatrix(false);
  329. var faceCount = indices.length / 3;
  330. for (var i = 0; i < faceCount; i++) {
  331. var triPoints = [];
  332. for (var point = 0; point < 3; point++) {
  333. var v = new BABYLON.Vector3(vertexPositions[(indices[(i * 3) + point] * 3) + 0], vertexPositions[(indices[(i * 3) + point] * 3) + 1], vertexPositions[(indices[(i * 3) + point] * 3) + 2]);
  334. v = Vector3.TransformCoordinates(v, object.getWorldMatrix());
  335. v.subtractInPlace(topLevelObject.position);
  336. var vec: any;
  337. if (point == 0) {
  338. vec = this._tmpAmmoVectorA;
  339. }else if (point == 1) {
  340. vec = this._tmpAmmoVectorB;
  341. }else {
  342. vec = this._tmpAmmoVectorC;
  343. }
  344. vec.setValue(v.x, v.y, v.z);
  345. triPoints.push(vec);
  346. }
  347. btTriangleMesh.addTriangle(triPoints[0], triPoints[1], triPoints[2]);
  348. triangleCount++;
  349. }
  350. object.getChildMeshes().forEach((m) => {
  351. triangleCount += this._addMeshVerts(btTriangleMesh, topLevelObject, m);
  352. });
  353. }
  354. return triangleCount;
  355. }
  356. private _createShape(impostor: PhysicsImpostor, ignoreChildren= false) {
  357. var object = impostor.object;
  358. var returnValue: any;
  359. var extendSize = impostor.getObjectExtendSize();
  360. if (!ignoreChildren) {
  361. var meshChildren = impostor.object.getChildMeshes ? impostor.object.getChildMeshes(true) : [];
  362. returnValue = new Ammo.btCompoundShape();
  363. // Add shape of all children to the compound shape
  364. var childrenAdded = 0;
  365. meshChildren.forEach((childMesh) => {
  366. var childImpostor = childMesh.getPhysicsImpostor();
  367. if (childImpostor) {
  368. var shape = this._createShape(childImpostor);
  369. // Position needs to be scaled based on parent's scaling
  370. var parentMat = childMesh.parent!.getWorldMatrix().clone();
  371. var s = new BABYLON.Vector3();
  372. parentMat.decompose(s);
  373. this._tmpAmmoTransform.getOrigin().setValue(childMesh.position.x * s.x, childMesh.position.y * s.y, childMesh.position.z * s.z);
  374. this._tmpAmmoQuaternion.setValue(childMesh.rotationQuaternion!.x, childMesh.rotationQuaternion!.y, childMesh.rotationQuaternion!.z, childMesh.rotationQuaternion!.w);
  375. this._tmpAmmoTransform.setRotation(this._tmpAmmoQuaternion);
  376. returnValue.addChildShape(this._tmpAmmoTransform, shape);
  377. childImpostor.dispose();
  378. childrenAdded++;
  379. }
  380. });
  381. if (childrenAdded > 0) {
  382. // Add parents shape as a child if present
  383. if (impostor.type != PhysicsImpostor.NoImpostor) {
  384. var shape = this._createShape(impostor, true);
  385. if (shape) {
  386. this._tmpAmmoTransform.getOrigin().setValue(0, 0, 0);
  387. this._tmpAmmoQuaternion.setValue(0, 0, 0, 1);
  388. this._tmpAmmoTransform.setRotation(this._tmpAmmoQuaternion);
  389. returnValue.addChildShape(this._tmpAmmoTransform, shape);
  390. }
  391. }
  392. return returnValue;
  393. }else {
  394. // If no children with impostors create the actual shape below instead
  395. Ammo.destroy(returnValue);
  396. returnValue = null;
  397. }
  398. }
  399. switch (impostor.type) {
  400. case PhysicsImpostor.SphereImpostor:
  401. returnValue = new Ammo.btSphereShape(extendSize.x / 2);
  402. break;
  403. case PhysicsImpostor.CylinderImpostor:
  404. this._tmpAmmoVectorA.setValue(extendSize.x / 2, extendSize.y / 2, extendSize.z / 2);
  405. returnValue = new Ammo.btCylinderShape(this._tmpAmmoVectorA);
  406. break;
  407. case PhysicsImpostor.PlaneImpostor:
  408. case PhysicsImpostor.BoxImpostor:
  409. this._tmpAmmoVectorA.setValue(extendSize.x / 2, extendSize.y / 2, extendSize.z / 2);
  410. returnValue = new Ammo.btBoxShape(this._tmpAmmoVectorA);
  411. break;
  412. case PhysicsImpostor.MeshImpostor:
  413. var tetraMesh = new Ammo.btTriangleMesh();
  414. impostor._pluginData.toDispose.concat([tetraMesh]);
  415. var triangeCount = this._addMeshVerts(tetraMesh, object, object);
  416. if (triangeCount == 0) {
  417. returnValue = new Ammo.btCompoundShape();
  418. }else {
  419. returnValue = new Ammo.btBvhTriangleMeshShape(tetraMesh);
  420. }
  421. break;
  422. case PhysicsImpostor.NoImpostor:
  423. // Fill with sphere but collision is disabled on the rigid body in generatePhysicsBody, using an empty shape caused unexpected movement with joints
  424. returnValue = new Ammo.btSphereShape(extendSize.x / 2);
  425. break;
  426. default:
  427. Tools.Warn("The impostor type is not currently supported by the ammo plugin.");
  428. break;
  429. }
  430. return returnValue;
  431. }
  432. /**
  433. * Sets the physics body position/rotation from the babylon mesh's position/rotation
  434. * @param impostor imposter containing the physics body and babylon object
  435. */
  436. public setTransformationFromPhysicsBody(impostor: PhysicsImpostor) {
  437. impostor.physicsBody.getMotionState().getWorldTransform(this._tmpAmmoTransform);
  438. impostor.object.position.set(this._tmpAmmoTransform.getOrigin().x(), this._tmpAmmoTransform.getOrigin().y(), this._tmpAmmoTransform.getOrigin().z());
  439. if (!impostor.object.rotationQuaternion) {
  440. if (impostor.object.rotation) {
  441. this._tmpQuaternion.set(this._tmpAmmoTransform.getRotation().x(), this._tmpAmmoTransform.getRotation().y(), this._tmpAmmoTransform.getRotation().z(), this._tmpAmmoTransform.getRotation().w());
  442. this._tmpQuaternion.toEulerAnglesToRef(impostor.object.rotation);
  443. }
  444. }else {
  445. impostor.object.rotationQuaternion.set(this._tmpAmmoTransform.getRotation().x(), this._tmpAmmoTransform.getRotation().y(), this._tmpAmmoTransform.getRotation().z(), this._tmpAmmoTransform.getRotation().w());
  446. }
  447. }
  448. /**
  449. * Sets the babylon object's position/rotation from the physics body's position/rotation
  450. * @param impostor imposter containing the physics body and babylon object
  451. * @param newPosition new position
  452. * @param newRotation new rotation
  453. */
  454. public setPhysicsBodyTransformation(impostor: PhysicsImpostor, newPosition: Vector3, newRotation: Quaternion) {
  455. var trans = impostor.physicsBody.getWorldTransform();
  456. // If rotation/position has changed update and activate riged body
  457. if (
  458. trans.getOrigin().x() != newPosition.x ||
  459. trans.getOrigin().y() != newPosition.y ||
  460. trans.getOrigin().z() != newPosition.z ||
  461. trans.getRotation().x() != newRotation.x ||
  462. trans.getRotation().y() != newRotation.y ||
  463. trans.getRotation().z() != newRotation.z ||
  464. trans.getRotation().w() != newRotation.w
  465. ) {
  466. this._tmpAmmoVectorA.setValue(newPosition.x, newPosition.y, newPosition.z);
  467. trans.setOrigin(this._tmpAmmoVectorA);
  468. this._tmpAmmoQuaternion.setValue(newRotation.x, newRotation.y, newRotation.z, newRotation.w);
  469. trans.setRotation(this._tmpAmmoQuaternion);
  470. impostor.physicsBody.setWorldTransform(trans);
  471. if (impostor.mass == 0) {
  472. // Kinematic objects must be updated using motion state
  473. var motionState = impostor.physicsBody.getMotionState();
  474. if (motionState) {
  475. motionState.setWorldTransform(trans);
  476. }
  477. }else {
  478. impostor.physicsBody.activate();
  479. }
  480. }
  481. }
  482. /**
  483. * If this plugin is supported
  484. * @returns true if its supported
  485. */
  486. public isSupported(): boolean {
  487. return this.bjsAMMO !== undefined;
  488. }
  489. /**
  490. * Sets the linear velocity of the physics body
  491. * @param impostor imposter to set the velocity on
  492. * @param velocity velocity to set
  493. */
  494. public setLinearVelocity(impostor: PhysicsImpostor, velocity: Vector3) {
  495. this._tmpAmmoVectorA.setValue(velocity.x, velocity.y, velocity.z);
  496. impostor.physicsBody.setLinearVelocity(this._tmpAmmoVectorA);
  497. }
  498. /**
  499. * Sets the angular velocity of the physics body
  500. * @param impostor imposter to set the velocity on
  501. * @param velocity velocity to set
  502. */
  503. public setAngularVelocity(impostor: PhysicsImpostor, velocity: Vector3) {
  504. this._tmpAmmoVectorA.setValue(velocity.x, velocity.y, velocity.z);
  505. impostor.physicsBody.setAngularVelocity(this._tmpAmmoVectorA);
  506. }
  507. /**
  508. * gets the linear velocity
  509. * @param impostor imposter to get linear velocity from
  510. * @returns linear velocity
  511. */
  512. public getLinearVelocity(impostor: PhysicsImpostor): Nullable<Vector3> {
  513. var v = impostor.physicsBody.getLinearVelocity();
  514. if (!v) {
  515. return null;
  516. }
  517. return new Vector3(v.x(), v.y(), v.z());
  518. }
  519. /**
  520. * gets the angular velocity
  521. * @param impostor imposter to get angular velocity from
  522. * @returns angular velocity
  523. */
  524. public getAngularVelocity(impostor: PhysicsImpostor): Nullable<Vector3> {
  525. var v = impostor.physicsBody.getAngularVelocity();
  526. if (!v) {
  527. return null;
  528. }
  529. return new Vector3(v.x(), v.y(), v.z());
  530. }
  531. /**
  532. * Sets the mass of physics body
  533. * @param impostor imposter to set the mass on
  534. * @param mass mass to set
  535. */
  536. public setBodyMass(impostor: PhysicsImpostor, mass: number) {
  537. impostor.physicsBody.setMassProps(mass);
  538. impostor._pluginData.mass = mass;
  539. }
  540. /**
  541. * Gets the mass of the physics body
  542. * @param impostor imposter to get the mass from
  543. * @returns mass
  544. */
  545. public getBodyMass(impostor: PhysicsImpostor): number {
  546. return impostor._pluginData.mass;
  547. }
  548. /**
  549. * Gets friction of the impostor
  550. * @param impostor impostor to get friction from
  551. * @returns friction value
  552. */
  553. public getBodyFriction(impostor: PhysicsImpostor): number {
  554. return impostor._pluginData.friction;
  555. }
  556. /**
  557. * Sets friction of the impostor
  558. * @param impostor impostor to set friction on
  559. * @param friction friction value
  560. */
  561. public setBodyFriction(impostor: PhysicsImpostor, friction: number) {
  562. impostor.physicsBody.setFriction(friction);
  563. impostor._pluginData.friction = friction;
  564. }
  565. /**
  566. * Gets restitution of the impostor
  567. * @param impostor impostor to get restitution from
  568. * @returns restitution value
  569. */
  570. public getBodyRestitution(impostor: PhysicsImpostor): number {
  571. return impostor._pluginData.restitution;
  572. }
  573. /**
  574. * Sets resitution of the impostor
  575. * @param impostor impostor to set resitution on
  576. * @param restitution resitution value
  577. */
  578. public setBodyRestitution(impostor: PhysicsImpostor, restitution: number) {
  579. impostor.physicsBody.setRestitution(restitution);
  580. impostor._pluginData.restitution = restitution;
  581. }
  582. /**
  583. * Sleeps the physics body and stops it from being active
  584. * @param impostor impostor to sleep
  585. */
  586. public sleepBody(impostor: PhysicsImpostor) {
  587. Tools.Warn("sleepBody is not currently supported by the Ammo physics plugin");
  588. }
  589. /**
  590. * Activates the physics body
  591. * @param impostor impostor to activate
  592. */
  593. public wakeUpBody(impostor: PhysicsImpostor) {
  594. impostor.physicsBody.activate();
  595. }
  596. /**
  597. * Updates the distance parameters of the joint
  598. * @param joint joint to update
  599. * @param maxDistance maximum distance of the joint
  600. * @param minDistance minimum distance of the joint
  601. */
  602. public updateDistanceJoint(joint: PhysicsJoint, maxDistance: number, minDistance?: number) {
  603. Tools.Warn("updateDistanceJoint is not currently supported by the Ammo physics plugin");
  604. }
  605. /**
  606. * Sets a motor on the joint
  607. * @param joint joint to set motor on
  608. * @param speed speed of the motor
  609. * @param maxForce maximum force of the motor
  610. * @param motorIndex index of the motor
  611. */
  612. public setMotor(joint: IMotorEnabledJoint, speed?: number, maxForce?: number, motorIndex?: number) {
  613. joint.physicsJoint.enableAngularMotor(true, speed, maxForce);
  614. }
  615. /**
  616. * Sets the motors limit
  617. * @param joint joint to set limit on
  618. * @param upperLimit upper limit
  619. * @param lowerLimit lower limit
  620. */
  621. public setLimit(joint: IMotorEnabledJoint, upperLimit: number, lowerLimit?: number) {
  622. Tools.Warn("setLimit is not currently supported by the Ammo physics plugin");
  623. }
  624. /**
  625. * Syncs the position and rotation of a mesh with the impostor
  626. * @param mesh mesh to sync
  627. * @param impostor impostor to update the mesh with
  628. */
  629. public syncMeshWithImpostor(mesh: AbstractMesh, impostor: PhysicsImpostor) {
  630. var body = impostor.physicsBody;
  631. body.getMotionState().getWorldTransform(this._tmpAmmoTransform);
  632. mesh.position.x = this._tmpAmmoTransform.getOrigin().x();
  633. mesh.position.y = this._tmpAmmoTransform.getOrigin().y();
  634. mesh.position.z = this._tmpAmmoTransform.getOrigin().z();
  635. if (mesh.rotationQuaternion) {
  636. mesh.rotationQuaternion.x = this._tmpAmmoTransform.getRotation().x();
  637. mesh.rotationQuaternion.y = this._tmpAmmoTransform.getRotation().y();
  638. mesh.rotationQuaternion.z = this._tmpAmmoTransform.getRotation().z();
  639. mesh.rotationQuaternion.w = this._tmpAmmoTransform.getRotation().w();
  640. }
  641. }
  642. /**
  643. * Gets the radius of the impostor
  644. * @param impostor impostor to get radius from
  645. * @returns the radius
  646. */
  647. public getRadius(impostor: PhysicsImpostor): number {
  648. var exntend = impostor.getObjectExtendSize();
  649. return exntend.x / 2;
  650. }
  651. /**
  652. * Gets the box size of the impostor
  653. * @param impostor impostor to get box size from
  654. * @param result the resulting box size
  655. */
  656. public getBoxSizeToRef(impostor: PhysicsImpostor, result: Vector3): void {
  657. var exntend = impostor.getObjectExtendSize();
  658. result.x = exntend.x;
  659. result.y = exntend.y;
  660. result.z = exntend.z;
  661. }
  662. /**
  663. * Disposes of the impostor
  664. */
  665. public dispose() {
  666. // Dispose of world
  667. Ammo.destroy(this.world);
  668. Ammo.destroy(this._solver);
  669. Ammo.destroy(this._overlappingPairCache);
  670. Ammo.destroy(this._dispatcher);
  671. Ammo.destroy(this._collisionConfiguration);
  672. // Dispose of tmp variables
  673. Ammo.destroy(this._tmpAmmoVectorA);
  674. Ammo.destroy(this._tmpAmmoVectorB);
  675. Ammo.destroy(this._tmpAmmoVectorC);
  676. Ammo.destroy(this._tmpAmmoTransform);
  677. Ammo.destroy(this._tmpAmmoQuaternion);
  678. Ammo.destroy(this._tmpAmmoConcreteContactResultCallback);
  679. this.world = null;
  680. }
  681. }
  682. }