babylon.cannonJSPlugin.ts 22 KB

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