babylon.cannonJSPlugin.ts 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639
  1. module BABYLON {
  2. declare var require: any;
  3. declare var CANNON: any;
  4. export class CannonJSPlugin implements IPhysicsEnginePlugin {
  5. public world: any; //this.BJSCANNON.World
  6. public name: string = "CannonJSPlugin";
  7. private _physicsMaterials = new Array();
  8. private _fixedTimeStep: number = 1 / 60;
  9. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  10. public BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : (typeof require !== 'undefined' ? require('cannon') : undefined);
  11. public constructor(private _useDeltaForWorldStep: boolean = true, iterations: number = 10) {
  12. if (!this.isSupported()) {
  13. Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  14. return;
  15. }
  16. this._extendNamespace();
  17. this.world = new this.BJSCANNON.World();
  18. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  19. this.world.solver.iterations = iterations;
  20. }
  21. public setGravity(gravity: Vector3): void {
  22. this.world.gravity.copy(gravity);
  23. }
  24. public setTimeStep(timeStep: number) {
  25. this._fixedTimeStep = timeStep;
  26. }
  27. public getTimeStep(): number {
  28. return this._fixedTimeStep;
  29. }
  30. public executeStep(delta: number, impostors: Array<PhysicsImpostor>): void {
  31. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  32. }
  33. public applyImpulse(impostor: PhysicsImpostor, force: Vector3, contactPoint: Vector3) {
  34. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  35. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  36. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  37. }
  38. public applyForce(impostor: PhysicsImpostor, force: Vector3, contactPoint: Vector3) {
  39. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  40. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  41. impostor.physicsBody.applyForce(impulse, worldPoint);
  42. }
  43. public generatePhysicsBody(impostor: PhysicsImpostor) {
  44. //parent-child relationship. Does this impostor has a parent impostor?
  45. if (impostor.parent) {
  46. if (impostor.physicsBody) {
  47. this.removePhysicsBody(impostor);
  48. //TODO is that needed?
  49. impostor.forceUpdate();
  50. }
  51. return;
  52. }
  53. //should a new body be created for this impostor?
  54. if (impostor.isBodyInitRequired()) {
  55. var shape = this._createShape(impostor);
  56. //unregister events, if body is being changed
  57. var oldBody = impostor.physicsBody;
  58. if (oldBody) {
  59. this.removePhysicsBody(impostor);
  60. }
  61. //create the body and material
  62. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  63. var bodyCreationObject = {
  64. mass: impostor.getParam("mass"),
  65. material: material
  66. };
  67. // A simple extend, in case native options were used.
  68. var nativeOptions = impostor.getParam("nativeOptions");
  69. for (var key in nativeOptions) {
  70. if (nativeOptions.hasOwnProperty(key)) {
  71. (<any>bodyCreationObject)[key] = nativeOptions[key];
  72. }
  73. }
  74. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  75. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  76. this.world.addEventListener("preStep", impostor.beforeStep);
  77. this.world.addEventListener("postStep", impostor.afterStep);
  78. impostor.physicsBody.addShape(shape);
  79. this.world.add(impostor.physicsBody);
  80. //try to keep the body moving in the right direction by taking old properties.
  81. //Should be tested!
  82. if (oldBody) {
  83. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  84. impostor.physicsBody[param].copy(oldBody[param]);
  85. });
  86. }
  87. this._processChildMeshes(impostor);
  88. }
  89. //now update the body's transformation
  90. this._updatePhysicsBodyTransformation(impostor);
  91. }
  92. private _processChildMeshes(mainImpostor: PhysicsImpostor) {
  93. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  94. let currentRotation: Nullable<Quaternion> = mainImpostor.object.rotationQuaternion;
  95. if (meshChildren.length) {
  96. var processMesh = (localPosition: Vector3, mesh: AbstractMesh) => {
  97. if (!currentRotation || !mesh.rotationQuaternion) {
  98. return;
  99. }
  100. var childImpostor = mesh.getPhysicsImpostor();
  101. if (childImpostor) {
  102. var parent = childImpostor.parent;
  103. if (parent !== mainImpostor) {
  104. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  105. let localRotation = mesh.rotationQuaternion.multiply(Quaternion.Inverse(currentRotation));
  106. if (childImpostor.physicsBody) {
  107. this.removePhysicsBody(childImpostor);
  108. childImpostor.physicsBody = null;
  109. }
  110. childImpostor.parent = mainImpostor;
  111. childImpostor.resetUpdateFlags();
  112. mainImpostor.physicsBody.addShape(this._createShape(childImpostor), new this.BJSCANNON.Vec3(pPosition.x, pPosition.y, pPosition.z), new this.BJSCANNON.Quaternion(localRotation.x, localRotation.y, localRotation.z, localRotation.w));
  113. //Add the mass of the children.
  114. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  115. }
  116. }
  117. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  118. mesh.getChildMeshes(true).filter(m => !!m.physicsImpostor).forEach(processMesh.bind(this, mesh.getAbsolutePosition()));
  119. }
  120. meshChildren.filter(m => !!m.physicsImpostor).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  121. }
  122. }
  123. public removePhysicsBody(impostor: PhysicsImpostor) {
  124. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  125. this.world.removeEventListener("preStep", impostor.beforeStep);
  126. this.world.removeEventListener("postStep", impostor.afterStep);
  127. this.world.remove(impostor.physicsBody);
  128. }
  129. public generateJoint(impostorJoint: PhysicsImpostorJoint) {
  130. var mainBody = impostorJoint.mainImpostor.physicsBody;
  131. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  132. if (!mainBody || !connectedBody) {
  133. return;
  134. }
  135. var constraint: any;
  136. var jointData = impostorJoint.joint.jointData;
  137. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  138. var constraintData = {
  139. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  140. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  141. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  142. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  143. maxForce: jointData.nativeParams.maxForce,
  144. collideConnected: !!jointData.collision
  145. };
  146. switch (impostorJoint.joint.type) {
  147. case PhysicsJoint.HingeJoint:
  148. case PhysicsJoint.Hinge2Joint:
  149. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  150. break;
  151. case PhysicsJoint.DistanceJoint:
  152. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, (<DistanceJointData>jointData).maxDistance || 2)
  153. break;
  154. case PhysicsJoint.SpringJoint:
  155. var springData = <SpringJointData>jointData;
  156. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  157. restLength: springData.length,
  158. stiffness: springData.stiffness,
  159. damping: springData.damping,
  160. localAnchorA: constraintData.pivotA,
  161. localAnchorB: constraintData.pivotB
  162. });
  163. break;
  164. case PhysicsJoint.LockJoint:
  165. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  166. break;
  167. case PhysicsJoint.PointToPointJoint:
  168. case PhysicsJoint.BallAndSocketJoint:
  169. default:
  170. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  171. break;
  172. }
  173. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  174. constraint.collideConnected = !!jointData.collision
  175. impostorJoint.joint.physicsJoint = constraint;
  176. //don't add spring as constraint, as it is not one.
  177. if (impostorJoint.joint.type !== PhysicsJoint.SpringJoint) {
  178. this.world.addConstraint(constraint);
  179. } else {
  180. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  181. constraint.applyForce();
  182. });
  183. }
  184. }
  185. public removeJoint(impostorJoint: PhysicsImpostorJoint) {
  186. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  187. }
  188. private _addMaterial(name: string, friction: number, restitution: number) {
  189. var index;
  190. var mat;
  191. for (index = 0; index < this._physicsMaterials.length; index++) {
  192. mat = this._physicsMaterials[index];
  193. if (mat.friction === friction && mat.restitution === restitution) {
  194. return mat;
  195. }
  196. }
  197. var currentMat = new this.BJSCANNON.Material(name);
  198. currentMat.friction = friction;
  199. currentMat.restitution = restitution;
  200. this._physicsMaterials.push(currentMat);
  201. return currentMat;
  202. }
  203. private _checkWithEpsilon(value: number): number {
  204. return value < PhysicsEngine.Epsilon ? PhysicsEngine.Epsilon : value;
  205. }
  206. private _createShape(impostor: PhysicsImpostor) {
  207. var object = impostor.object;
  208. var returnValue;
  209. var extendSize = impostor.getObjectExtendSize();
  210. switch (impostor.type) {
  211. case PhysicsImpostor.SphereImpostor:
  212. var radiusX = extendSize.x;
  213. var radiusY = extendSize.y;
  214. var radiusZ = extendSize.z;
  215. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  216. break;
  217. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  218. case PhysicsImpostor.CylinderImpostor:
  219. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  220. break;
  221. case PhysicsImpostor.BoxImpostor:
  222. var box = extendSize.scale(0.5);
  223. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  224. break;
  225. case PhysicsImpostor.PlaneImpostor:
  226. Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  227. returnValue = new this.BJSCANNON.Plane();
  228. break;
  229. case PhysicsImpostor.MeshImpostor:
  230. // should transform the vertex data to world coordinates!!
  231. var rawVerts = object.getVerticesData ? object.getVerticesData(VertexBuffer.PositionKind) : [];
  232. var rawFaces = object.getIndices ? object.getIndices() : [];
  233. if (!rawVerts) return;
  234. // get only scale! so the object could transform correctly.
  235. let oldPosition = object.position.clone();
  236. let oldRotation = object.rotation && object.rotation.clone();
  237. let oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  238. object.position.copyFromFloats(0, 0, 0);
  239. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  240. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  241. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  242. let transform = object.computeWorldMatrix(true);
  243. // convert rawVerts to object space
  244. var temp = new Array<number>();
  245. var index: number;
  246. for (index = 0; index < rawVerts.length; index += 3) {
  247. Vector3.TransformCoordinates(Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  248. }
  249. Tools.Warn("MeshImpostor only collides against spheres.");
  250. returnValue = new this.BJSCANNON.Trimesh(temp, <number[]>rawFaces);
  251. //now set back the transformation!
  252. object.position.copyFrom(oldPosition);
  253. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  254. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  255. break;
  256. case PhysicsImpostor.HeightmapImpostor:
  257. let oldPosition2 = object.position.clone();
  258. let oldRotation2 = object.rotation && object.rotation.clone();
  259. let oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  260. object.position.copyFromFloats(0, 0, 0);
  261. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  262. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  263. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  264. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  265. returnValue = this._createHeightmap(object);
  266. object.position.copyFrom(oldPosition2);
  267. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  268. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  269. object.computeWorldMatrix(true);
  270. break;
  271. case PhysicsImpostor.ParticleImpostor:
  272. returnValue = new this.BJSCANNON.Particle();
  273. break;
  274. }
  275. return returnValue;
  276. }
  277. private _createHeightmap(object: IPhysicsEnabledObject, pointDepth?: number) {
  278. var pos = <FloatArray>(object.getVerticesData(VertexBuffer.PositionKind));
  279. let transform = object.computeWorldMatrix(true);
  280. // convert rawVerts to object space
  281. var temp = new Array<number>();
  282. var index: number;
  283. for (index = 0; index < pos.length; index += 3) {
  284. Vector3.TransformCoordinates(Vector3.FromArray(pos, index), transform).toArray(temp, index);
  285. }
  286. pos = temp;
  287. var matrix = new Array<Array<any>>();
  288. //For now pointDepth will not be used and will be automatically calculated.
  289. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  290. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  291. let boundingInfo = object.getBoundingInfo();
  292. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  293. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  294. var elementSize = dim * 2 / arraySize;
  295. for (var i = 0; i < pos.length; i = i + 3) {
  296. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  297. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  298. var y = -pos[i + 2] + minY;
  299. if (!matrix[x]) {
  300. matrix[x] = [];
  301. }
  302. if (!matrix[x][z]) {
  303. matrix[x][z] = y;
  304. }
  305. matrix[x][z] = Math.max(y, matrix[x][z]);
  306. }
  307. for (var x = 0; x <= arraySize; ++x) {
  308. if (!matrix[x]) {
  309. var loc = 1;
  310. while (!matrix[(x + loc) % arraySize]) {
  311. loc++;
  312. }
  313. matrix[x] = matrix[(x + loc) % arraySize].slice();
  314. //console.log("missing x", x);
  315. }
  316. for (var z = 0; z <= arraySize; ++z) {
  317. if (!matrix[x][z]) {
  318. var loc = 1;
  319. var newValue;
  320. while (newValue === undefined) {
  321. newValue = matrix[x][(z + loc++) % arraySize];
  322. }
  323. matrix[x][z] = newValue;
  324. }
  325. }
  326. }
  327. var shape = new this.BJSCANNON.Heightfield(matrix, {
  328. elementSize: elementSize
  329. });
  330. //For future reference, needed for body transformation
  331. shape.minY = minY;
  332. return shape;
  333. }
  334. private _minus90X = new Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  335. private _plus90X = new Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  336. private _tmpPosition: Vector3 = Vector3.Zero();
  337. private _tmpDeltaPosition: Vector3 = Vector3.Zero();
  338. private _tmpUnityRotation: Quaternion = new Quaternion();
  339. private _updatePhysicsBodyTransformation(impostor: PhysicsImpostor) {
  340. var object = impostor.object;
  341. //make sure it is updated...
  342. object.computeWorldMatrix && object.computeWorldMatrix(true);
  343. // The delta between the mesh position and the mesh bounding box center
  344. let bInfo = object.getBoundingInfo();
  345. if (!bInfo) return;
  346. var center = impostor.getObjectCenter();
  347. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  348. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  349. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  350. this._tmpPosition.copyFrom(center);
  351. var quaternion = object.rotationQuaternion;
  352. if (!quaternion) {
  353. return;
  354. }
  355. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  356. if (impostor.type === PhysicsImpostor.PlaneImpostor || impostor.type === PhysicsImpostor.HeightmapImpostor || impostor.type === PhysicsImpostor.CylinderImpostor) {
  357. //-90 DEG in X, precalculated
  358. quaternion = quaternion.multiply(this._minus90X);
  359. //Invert! (Precalculated, 90 deg in X)
  360. //No need to clone. this will never change.
  361. impostor.setDeltaRotation(this._plus90X);
  362. }
  363. //If it is a heightfield, if should be centered.
  364. if (impostor.type === PhysicsImpostor.HeightmapImpostor) {
  365. var mesh = <AbstractMesh>(<any>object);
  366. let boundingInfo = mesh.getBoundingInfo();
  367. //calculate the correct body position:
  368. var rotationQuaternion = mesh.rotationQuaternion;
  369. mesh.rotationQuaternion = this._tmpUnityRotation;
  370. mesh.computeWorldMatrix(true);
  371. //get original center with no rotation
  372. var c = center.clone();
  373. var oldPivot = mesh.getPivotMatrix() || Matrix.Translation(0, 0, 0);
  374. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  375. var p = Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  376. mesh.setPreTransformMatrix(p);
  377. mesh.computeWorldMatrix(true);
  378. //calculate the translation
  379. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  380. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  381. //add it inverted to the delta
  382. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  383. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  384. //rotation is back
  385. mesh.rotationQuaternion = rotationQuaternion;
  386. mesh.setPreTransformMatrix(oldPivot);
  387. mesh.computeWorldMatrix(true);
  388. } else if (impostor.type === PhysicsImpostor.MeshImpostor) {
  389. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  390. //this._tmpPosition.copyFrom(object.position);
  391. }
  392. impostor.setDeltaPosition(this._tmpDeltaPosition);
  393. //Now update the impostor object
  394. impostor.physicsBody.position.copy(this._tmpPosition);
  395. impostor.physicsBody.quaternion.copy(quaternion);
  396. }
  397. public setTransformationFromPhysicsBody(impostor: PhysicsImpostor) {
  398. impostor.object.position.copyFrom(impostor.physicsBody.position);
  399. if (impostor.object.rotationQuaternion) {
  400. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  401. }
  402. }
  403. public setPhysicsBodyTransformation(impostor: PhysicsImpostor, newPosition: Vector3, newRotation: Quaternion) {
  404. impostor.physicsBody.position.copy(newPosition);
  405. impostor.physicsBody.quaternion.copy(newRotation);
  406. }
  407. public isSupported(): boolean {
  408. return this.BJSCANNON !== undefined;
  409. }
  410. public setLinearVelocity(impostor: PhysicsImpostor, velocity: Vector3) {
  411. impostor.physicsBody.velocity.copy(velocity);
  412. }
  413. public setAngularVelocity(impostor: PhysicsImpostor, velocity: Vector3) {
  414. impostor.physicsBody.angularVelocity.copy(velocity);
  415. }
  416. public getLinearVelocity(impostor: PhysicsImpostor): Nullable<Vector3> {
  417. var v = impostor.physicsBody.velocity;
  418. if (!v) {
  419. return null;
  420. }
  421. return new Vector3(v.x, v.y, v.z)
  422. }
  423. public getAngularVelocity(impostor: PhysicsImpostor): Nullable<Vector3> {
  424. var v = impostor.physicsBody.angularVelocity;
  425. if (!v) {
  426. return null;
  427. }
  428. return new Vector3(v.x, v.y, v.z)
  429. }
  430. public setBodyMass(impostor: PhysicsImpostor, mass: number) {
  431. impostor.physicsBody.mass = mass;
  432. impostor.physicsBody.updateMassProperties();
  433. }
  434. public getBodyMass(impostor: PhysicsImpostor): number {
  435. return impostor.physicsBody.mass;
  436. }
  437. public getBodyFriction(impostor: PhysicsImpostor): number {
  438. return impostor.physicsBody.material.friction;
  439. }
  440. public setBodyFriction(impostor: PhysicsImpostor, friction: number) {
  441. impostor.physicsBody.material.friction = friction;
  442. }
  443. public getBodyRestitution(impostor: PhysicsImpostor): number {
  444. return impostor.physicsBody.material.restitution;
  445. }
  446. public setBodyRestitution(impostor: PhysicsImpostor, restitution: number) {
  447. impostor.physicsBody.material.restitution = restitution;
  448. }
  449. public sleepBody(impostor: PhysicsImpostor) {
  450. impostor.physicsBody.sleep();
  451. }
  452. public wakeUpBody(impostor: PhysicsImpostor) {
  453. impostor.physicsBody.wakeUp();
  454. }
  455. public updateDistanceJoint(joint: PhysicsJoint, maxDistance: number, minDistance?: number) {
  456. joint.physicsJoint.distance = maxDistance;
  457. }
  458. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  459. // if (!motorIndex) {
  460. // joint.physicsJoint.enableMotor();
  461. // }
  462. // }
  463. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  464. // if (!motorIndex) {
  465. // joint.physicsJoint.disableMotor();
  466. // }
  467. // }
  468. public setMotor(joint: IMotorEnabledJoint, speed?: number, maxForce?: number, motorIndex?: number) {
  469. if (!motorIndex) {
  470. joint.physicsJoint.enableMotor();
  471. joint.physicsJoint.setMotorSpeed(speed);
  472. if (maxForce) {
  473. this.setLimit(joint, maxForce);
  474. }
  475. }
  476. }
  477. public setLimit(joint: IMotorEnabledJoint, upperLimit: number, lowerLimit?: number) {
  478. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  479. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  480. }
  481. public syncMeshWithImpostor(mesh: AbstractMesh, impostor: PhysicsImpostor) {
  482. var body = impostor.physicsBody;
  483. mesh.position.x = body.position.x;
  484. mesh.position.y = body.position.y;
  485. mesh.position.z = body.position.z;
  486. if (mesh.rotationQuaternion) {
  487. mesh.rotationQuaternion.x = body.quaternion.x;
  488. mesh.rotationQuaternion.y = body.quaternion.y;
  489. mesh.rotationQuaternion.z = body.quaternion.z;
  490. mesh.rotationQuaternion.w = body.quaternion.w;
  491. }
  492. }
  493. public getRadius(impostor: PhysicsImpostor): number {
  494. var shape = impostor.physicsBody.shapes[0];
  495. return shape.boundingSphereRadius;
  496. }
  497. public getBoxSizeToRef(impostor: PhysicsImpostor, result: Vector3): void {
  498. var shape = impostor.physicsBody.shapes[0];
  499. result.x = shape.halfExtents.x * 2;
  500. result.y = shape.halfExtents.y * 2;
  501. result.z = shape.halfExtents.z * 2;
  502. }
  503. public dispose() {
  504. }
  505. private _extendNamespace() {
  506. //this will force cannon to execute at least one step when using interpolation
  507. let step_tmp1 = new this.BJSCANNON.Vec3();
  508. let Engine = this.BJSCANNON;
  509. this.BJSCANNON.World.prototype.step = function (dt: number, timeSinceLastCalled: number, maxSubSteps: number) {
  510. maxSubSteps = maxSubSteps || 10;
  511. timeSinceLastCalled = timeSinceLastCalled || 0;
  512. if (timeSinceLastCalled === 0) {
  513. this.internalStep(dt);
  514. this.time += dt;
  515. } else {
  516. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  517. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  518. var t0 = performance.now();
  519. for (var i = 0; i !== internalSteps; i++) {
  520. this.internalStep(dt);
  521. if (performance.now() - t0 > dt * 1000) {
  522. break;
  523. }
  524. }
  525. this.time += timeSinceLastCalled;
  526. var h = this.time % dt;
  527. var h_div_dt = h / dt;
  528. var interpvelo = step_tmp1;
  529. var bodies = this.bodies;
  530. for (var j = 0; j !== bodies.length; j++) {
  531. var b = bodies[j];
  532. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  533. b.position.vsub(b.previousPosition, interpvelo);
  534. interpvelo.scale(h_div_dt, interpvelo);
  535. b.position.vadd(interpvelo, b.interpolatedPosition);
  536. } else {
  537. b.interpolatedPosition.copy(b.position);
  538. b.interpolatedQuaternion.copy(b.quaternion);
  539. }
  540. }
  541. }
  542. };
  543. }
  544. }
  545. }