babylon.cannonJSPlugin.ts 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645
  1. module BABYLON {
  2. //declare var require: any;
  3. declare var CANNON: any;
  4. export class CannonJSPlugin implements IPhysicsEnginePlugin {
  5. public world: any;
  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 = CANNON;
  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. (<SpringJointData>impostorJoint.joint.jointData).forceApplicationCallback = (<SpringJointData>impostorJoint.joint.jointData).forceApplicationCallback || function () {
  181. constraint.applyForce();
  182. };
  183. impostorJoint.mainImpostor.registerAfterPhysicsStep((<SpringJointData>impostorJoint.joint.jointData).forceApplicationCallback);
  184. }
  185. }
  186. public removeJoint(impostorJoint: PhysicsImpostorJoint) {
  187. if (impostorJoint.joint.type !== PhysicsJoint.SpringJoint) {
  188. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  189. } else {
  190. impostorJoint.mainImpostor.unregisterAfterPhysicsStep((<SpringJointData>impostorJoint.joint.jointData).forceApplicationCallback);
  191. }
  192. }
  193. private _addMaterial(name: string, friction: number, restitution: number) {
  194. var index;
  195. var mat;
  196. for (index = 0; index < this._physicsMaterials.length; index++) {
  197. mat = this._physicsMaterials[index];
  198. if (mat.friction === friction && mat.restitution === restitution) {
  199. return mat;
  200. }
  201. }
  202. var currentMat = new this.BJSCANNON.Material(name);
  203. currentMat.friction = friction;
  204. currentMat.restitution = restitution;
  205. this._physicsMaterials.push(currentMat);
  206. return currentMat;
  207. }
  208. private _checkWithEpsilon(value: number): number {
  209. return value < PhysicsEngine.Epsilon ? PhysicsEngine.Epsilon : value;
  210. }
  211. private _createShape(impostor: PhysicsImpostor) {
  212. var object = impostor.object;
  213. var returnValue;
  214. var extendSize = impostor.getObjectExtendSize();
  215. switch (impostor.type) {
  216. case PhysicsImpostor.SphereImpostor:
  217. var radiusX = extendSize.x;
  218. var radiusY = extendSize.y;
  219. var radiusZ = extendSize.z;
  220. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  221. break;
  222. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  223. case PhysicsImpostor.CylinderImpostor:
  224. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  225. break;
  226. case PhysicsImpostor.BoxImpostor:
  227. var box = extendSize.scale(0.5);
  228. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  229. break;
  230. case PhysicsImpostor.PlaneImpostor:
  231. Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  232. returnValue = new this.BJSCANNON.Plane();
  233. break;
  234. case PhysicsImpostor.MeshImpostor:
  235. // should transform the vertex data to world coordinates!!
  236. var rawVerts = object.getVerticesData ? object.getVerticesData(VertexBuffer.PositionKind) : [];
  237. var rawFaces = object.getIndices ? object.getIndices() : [];
  238. if (!rawVerts) return;
  239. // get only scale! so the object could transform correctly.
  240. let oldPosition = object.position.clone();
  241. let oldRotation = object.rotation && object.rotation.clone();
  242. let oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  243. object.position.copyFromFloats(0, 0, 0);
  244. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  245. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  246. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  247. let transform = object.computeWorldMatrix(true);
  248. // convert rawVerts to object space
  249. var temp = new Array<number>();
  250. var index: number;
  251. for (index = 0; index < rawVerts.length; index += 3) {
  252. Vector3.TransformCoordinates(Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  253. }
  254. Tools.Warn("MeshImpostor only collides against spheres.");
  255. returnValue = new this.BJSCANNON.Trimesh(temp, <number[]>rawFaces);
  256. //now set back the transformation!
  257. object.position.copyFrom(oldPosition);
  258. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  259. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  260. break;
  261. case PhysicsImpostor.HeightmapImpostor:
  262. let oldPosition2 = object.position.clone();
  263. let oldRotation2 = object.rotation && object.rotation.clone();
  264. let oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  265. object.position.copyFromFloats(0, 0, 0);
  266. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  267. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  268. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  269. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  270. returnValue = this._createHeightmap(object);
  271. object.position.copyFrom(oldPosition2);
  272. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  273. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  274. object.computeWorldMatrix(true);
  275. break;
  276. case PhysicsImpostor.ParticleImpostor:
  277. returnValue = new this.BJSCANNON.Particle();
  278. break;
  279. }
  280. return returnValue;
  281. }
  282. private _createHeightmap(object: IPhysicsEnabledObject, pointDepth?: number) {
  283. var pos = <FloatArray>(object.getVerticesData(VertexBuffer.PositionKind));
  284. let transform = object.computeWorldMatrix(true);
  285. // convert rawVerts to object space
  286. var temp = new Array<number>();
  287. var index: number;
  288. for (index = 0; index < pos.length; index += 3) {
  289. Vector3.TransformCoordinates(Vector3.FromArray(pos, index), transform).toArray(temp, index);
  290. }
  291. pos = temp;
  292. var matrix = new Array<Array<any>>();
  293. //For now pointDepth will not be used and will be automatically calculated.
  294. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  295. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  296. let boundingInfo = object.getBoundingInfo();
  297. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  298. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  299. var elementSize = dim * 2 / arraySize;
  300. for (var i = 0; i < pos.length; i = i + 3) {
  301. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  302. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  303. var y = -pos[i + 2] + minY;
  304. if (!matrix[x]) {
  305. matrix[x] = [];
  306. }
  307. if (!matrix[x][z]) {
  308. matrix[x][z] = y;
  309. }
  310. matrix[x][z] = Math.max(y, matrix[x][z]);
  311. }
  312. for (var x = 0; x <= arraySize; ++x) {
  313. if (!matrix[x]) {
  314. var loc = 1;
  315. while (!matrix[(x + loc) % arraySize]) {
  316. loc++;
  317. }
  318. matrix[x] = matrix[(x + loc) % arraySize].slice();
  319. //console.log("missing x", x);
  320. }
  321. for (var z = 0; z <= arraySize; ++z) {
  322. if (!matrix[x][z]) {
  323. var loc = 1;
  324. var newValue;
  325. while (newValue === undefined) {
  326. newValue = matrix[x][(z + loc++) % arraySize];
  327. }
  328. matrix[x][z] = newValue;
  329. }
  330. }
  331. }
  332. var shape = new this.BJSCANNON.Heightfield(matrix, {
  333. elementSize: elementSize
  334. });
  335. //For future reference, needed for body transformation
  336. shape.minY = minY;
  337. return shape;
  338. }
  339. private _minus90X = new Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  340. private _plus90X = new Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  341. private _tmpPosition: Vector3 = Vector3.Zero();
  342. private _tmpDeltaPosition: Vector3 = Vector3.Zero();
  343. private _tmpUnityRotation: Quaternion = new Quaternion();
  344. private _updatePhysicsBodyTransformation(impostor: PhysicsImpostor) {
  345. var object = impostor.object;
  346. //make sure it is updated...
  347. object.computeWorldMatrix && object.computeWorldMatrix(true);
  348. // The delta between the mesh position and the mesh bounding box center
  349. let bInfo = object.getBoundingInfo();
  350. if (!bInfo) return;
  351. var center = impostor.getObjectCenter();
  352. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  353. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  354. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  355. this._tmpPosition.copyFrom(center);
  356. var quaternion = object.rotationQuaternion;
  357. if (!quaternion) {
  358. return;
  359. }
  360. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  361. if (impostor.type === PhysicsImpostor.PlaneImpostor || impostor.type === PhysicsImpostor.HeightmapImpostor || impostor.type === PhysicsImpostor.CylinderImpostor) {
  362. //-90 DEG in X, precalculated
  363. quaternion = quaternion.multiply(this._minus90X);
  364. //Invert! (Precalculated, 90 deg in X)
  365. //No need to clone. this will never change.
  366. impostor.setDeltaRotation(this._plus90X);
  367. }
  368. //If it is a heightfield, if should be centered.
  369. if (impostor.type === PhysicsImpostor.HeightmapImpostor) {
  370. var mesh = <AbstractMesh>(<any>object);
  371. let boundingInfo = mesh.getBoundingInfo();
  372. //calculate the correct body position:
  373. var rotationQuaternion = mesh.rotationQuaternion;
  374. mesh.rotationQuaternion = this._tmpUnityRotation;
  375. mesh.computeWorldMatrix(true);
  376. //get original center with no rotation
  377. var c = center.clone();
  378. var oldPivot = mesh.getPivotMatrix() || Matrix.Translation(0, 0, 0);
  379. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  380. var p = Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  381. mesh.setPreTransformMatrix(p);
  382. mesh.computeWorldMatrix(true);
  383. //calculate the translation
  384. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  385. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  386. //add it inverted to the delta
  387. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  388. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  389. //rotation is back
  390. mesh.rotationQuaternion = rotationQuaternion;
  391. mesh.setPreTransformMatrix(oldPivot);
  392. mesh.computeWorldMatrix(true);
  393. } else if (impostor.type === PhysicsImpostor.MeshImpostor) {
  394. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  395. //this._tmpPosition.copyFrom(object.position);
  396. }
  397. impostor.setDeltaPosition(this._tmpDeltaPosition);
  398. //Now update the impostor object
  399. impostor.physicsBody.position.copy(this._tmpPosition);
  400. impostor.physicsBody.quaternion.copy(quaternion);
  401. }
  402. public setTransformationFromPhysicsBody(impostor: PhysicsImpostor) {
  403. impostor.object.position.copyFrom(impostor.physicsBody.position);
  404. if (impostor.object.rotationQuaternion) {
  405. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  406. }
  407. }
  408. public setPhysicsBodyTransformation(impostor: PhysicsImpostor, newPosition: Vector3, newRotation: Quaternion) {
  409. impostor.physicsBody.position.copy(newPosition);
  410. impostor.physicsBody.quaternion.copy(newRotation);
  411. }
  412. public isSupported(): boolean {
  413. return this.BJSCANNON !== undefined;
  414. }
  415. public setLinearVelocity(impostor: PhysicsImpostor, velocity: Vector3) {
  416. impostor.physicsBody.velocity.copy(velocity);
  417. }
  418. public setAngularVelocity(impostor: PhysicsImpostor, velocity: Vector3) {
  419. impostor.physicsBody.angularVelocity.copy(velocity);
  420. }
  421. public getLinearVelocity(impostor: PhysicsImpostor): Nullable<Vector3> {
  422. var v = impostor.physicsBody.velocity;
  423. if (!v) {
  424. return null;
  425. }
  426. return new Vector3(v.x, v.y, v.z)
  427. }
  428. public getAngularVelocity(impostor: PhysicsImpostor): Nullable<Vector3> {
  429. var v = impostor.physicsBody.angularVelocity;
  430. if (!v) {
  431. return null;
  432. }
  433. return new Vector3(v.x, v.y, v.z)
  434. }
  435. public setBodyMass(impostor: PhysicsImpostor, mass: number) {
  436. impostor.physicsBody.mass = mass;
  437. impostor.physicsBody.updateMassProperties();
  438. }
  439. public getBodyMass(impostor: PhysicsImpostor): number {
  440. return impostor.physicsBody.mass;
  441. }
  442. public getBodyFriction(impostor: PhysicsImpostor): number {
  443. return impostor.physicsBody.material.friction;
  444. }
  445. public setBodyFriction(impostor: PhysicsImpostor, friction: number) {
  446. impostor.physicsBody.material.friction = friction;
  447. }
  448. public getBodyRestitution(impostor: PhysicsImpostor): number {
  449. return impostor.physicsBody.material.restitution;
  450. }
  451. public setBodyRestitution(impostor: PhysicsImpostor, restitution: number) {
  452. impostor.physicsBody.material.restitution = restitution;
  453. }
  454. public sleepBody(impostor: PhysicsImpostor) {
  455. impostor.physicsBody.sleep();
  456. }
  457. public wakeUpBody(impostor: PhysicsImpostor) {
  458. impostor.physicsBody.wakeUp();
  459. }
  460. public updateDistanceJoint(joint: PhysicsJoint, maxDistance: number, minDistance?: number) {
  461. joint.physicsJoint.distance = maxDistance;
  462. }
  463. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  464. // if (!motorIndex) {
  465. // joint.physicsJoint.enableMotor();
  466. // }
  467. // }
  468. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  469. // if (!motorIndex) {
  470. // joint.physicsJoint.disableMotor();
  471. // }
  472. // }
  473. public setMotor(joint: IMotorEnabledJoint, speed?: number, maxForce?: number, motorIndex?: number) {
  474. if (!motorIndex) {
  475. joint.physicsJoint.enableMotor();
  476. joint.physicsJoint.setMotorSpeed(speed);
  477. if (maxForce) {
  478. this.setLimit(joint, maxForce);
  479. }
  480. }
  481. }
  482. public setLimit(joint: IMotorEnabledJoint, upperLimit: number, lowerLimit?: number) {
  483. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  484. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  485. }
  486. public syncMeshWithImpostor(mesh: AbstractMesh, impostor: PhysicsImpostor) {
  487. var body = impostor.physicsBody;
  488. mesh.position.x = body.position.x;
  489. mesh.position.y = body.position.y;
  490. mesh.position.z = body.position.z;
  491. if (mesh.rotationQuaternion) {
  492. mesh.rotationQuaternion.x = body.quaternion.x;
  493. mesh.rotationQuaternion.y = body.quaternion.y;
  494. mesh.rotationQuaternion.z = body.quaternion.z;
  495. mesh.rotationQuaternion.w = body.quaternion.w;
  496. }
  497. }
  498. public getRadius(impostor: PhysicsImpostor): number {
  499. var shape = impostor.physicsBody.shapes[0];
  500. return shape.boundingSphereRadius;
  501. }
  502. public getBoxSizeToRef(impostor: PhysicsImpostor, result: Vector3): void {
  503. var shape = impostor.physicsBody.shapes[0];
  504. result.x = shape.halfExtents.x * 2;
  505. result.y = shape.halfExtents.y * 2;
  506. result.z = shape.halfExtents.z * 2;
  507. }
  508. public dispose() {
  509. }
  510. private _extendNamespace() {
  511. //this will force cannon to execute at least one step when using interpolation
  512. let step_tmp1 = new this.BJSCANNON.Vec3();
  513. let Engine = this.BJSCANNON;
  514. this.BJSCANNON.World.prototype.step = function (dt: number, timeSinceLastCalled: number, maxSubSteps: number) {
  515. maxSubSteps = maxSubSteps || 10;
  516. timeSinceLastCalled = timeSinceLastCalled || 0;
  517. if (timeSinceLastCalled === 0) {
  518. this.internalStep(dt);
  519. this.time += dt;
  520. } else {
  521. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  522. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  523. var t0 = performance.now();
  524. for (var i = 0; i !== internalSteps; i++) {
  525. this.internalStep(dt);
  526. if (performance.now() - t0 > dt * 1000) {
  527. break;
  528. }
  529. }
  530. this.time += timeSinceLastCalled;
  531. var h = this.time % dt;
  532. var h_div_dt = h / dt;
  533. var interpvelo = step_tmp1;
  534. var bodies = this.bodies;
  535. for (var j = 0; j !== bodies.length; j++) {
  536. var b = bodies[j];
  537. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  538. b.position.vsub(b.previousPosition, interpvelo);
  539. interpvelo.scale(h_div_dt, interpvelo);
  540. b.position.vadd(interpvelo, b.interpolatedPosition);
  541. } else {
  542. b.interpolatedPosition.copy(b.position);
  543. b.interpolatedQuaternion.copy(b.quaternion);
  544. }
  545. }
  546. }
  547. };
  548. }
  549. }
  550. }