cannonJSPlugin.ts 33 KB

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