cannonJSPlugin.ts 33 KB

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