ammoJSPlugin.ts 34 KB

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