babylon.cannonJSPlugin.ts 31 KB

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