cannonJSPlugin.ts 34 KB

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