babylon.cannonJSPlugin.ts 28 KB

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