babylon.cannonJSPlugin.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  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.applyImpulse(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. //Not needed, Cannon has a collideConnected flag
  136. /*if (!jointData.collision) {
  137. //add 1st body to a collision group of its own, if it is not in 1
  138. if (mainBody.collisionFilterGroup === 1) {
  139. mainBody.collisionFilterGroup = this._currentCollisionGroup;
  140. this._currentCollisionGroup <<= 1;
  141. }
  142. if (connectedBody.collisionFilterGroup === 1) {
  143. connectedBody.collisionFilterGroup = this._currentCollisionGroup;
  144. this._currentCollisionGroup <<= 1;
  145. }
  146. //add their mask to the collisionFilterMask of each other:
  147. connectedBody.collisionFilterMask = connectedBody.collisionFilterMask | ~mainBody.collisionFilterGroup;
  148. mainBody.collisionFilterMask = mainBody.collisionFilterMask | ~connectedBody.collisionFilterGroup;
  149. }*/
  150. switch (impostorJoint.joint.type) {
  151. case PhysicsJoint.HingeJoint:
  152. case PhysicsJoint.Hinge2Joint:
  153. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  154. break;
  155. case PhysicsJoint.DistanceJoint:
  156. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, (<DistanceJointData>jointData).maxDistance || 2)
  157. break;
  158. case PhysicsJoint.SpringJoint:
  159. var springData = <SpringJointData>jointData;
  160. constraint = new CANNON.Spring(mainBody, connectedBody, {
  161. restLength: springData.length,
  162. stiffness: springData.stiffness,
  163. damping: springData.damping,
  164. localAnchorA: constraintData.pivotA,
  165. localAnchorB: constraintData.pivotB
  166. });
  167. break;
  168. case PhysicsJoint.LockJoint:
  169. constraint = new CANNON.LockConstraint(mainBody, connectedBody, constraintData);
  170. break;
  171. case PhysicsJoint.PointToPointJoint:
  172. case PhysicsJoint.BallAndSocketJoint:
  173. default:
  174. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  175. break;
  176. }
  177. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  178. constraint.collideConnected = !!jointData.collision
  179. impostorJoint.joint.physicsJoint = constraint;
  180. //don't add spring as constraint, as it is not one.
  181. if (impostorJoint.joint.type !== PhysicsJoint.SpringJoint) {
  182. this.world.addConstraint(constraint);
  183. } else {
  184. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  185. constraint.applyForce();
  186. });
  187. }
  188. }
  189. public removeJoint(impostorJoint: PhysicsImpostorJoint) {
  190. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  191. }
  192. private _addMaterial(name: string, friction: number, restitution: number) {
  193. var index;
  194. var mat;
  195. for (index = 0; index < this._physicsMaterials.length; index++) {
  196. mat = this._physicsMaterials[index];
  197. if (mat.friction === friction && mat.restitution === restitution) {
  198. return mat;
  199. }
  200. }
  201. var currentMat = new CANNON.Material(name);
  202. currentMat.friction = friction;
  203. currentMat.restitution = restitution;
  204. this._physicsMaterials.push(currentMat);
  205. return currentMat;
  206. }
  207. private _checkWithEpsilon(value: number): number {
  208. return value < PhysicsEngine.Epsilon ? PhysicsEngine.Epsilon : value;
  209. }
  210. private _createShape(impostor: PhysicsImpostor) {
  211. var object = impostor.object;
  212. var returnValue;
  213. var extendSize = impostor.getObjectExtendSize();
  214. switch (impostor.type) {
  215. case PhysicsEngine.SphereImpostor:
  216. var radiusX = extendSize.x;
  217. var radiusY = extendSize.y;
  218. var radiusZ = extendSize.z;
  219. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  220. break;
  221. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  222. case PhysicsImpostor.CylinderImpostor:
  223. returnValue = new CANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  224. break;
  225. case PhysicsImpostor.BoxImpostor:
  226. var box = extendSize.scale(0.5);
  227. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  228. break;
  229. case PhysicsImpostor.PlaneImpostor:
  230. Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  231. returnValue = new CANNON.Plane();
  232. break;
  233. case PhysicsImpostor.MeshImpostor:
  234. var rawVerts = object.getVerticesData ? object.getVerticesData(VertexBuffer.PositionKind) : [];
  235. var rawFaces = object.getIndices ? object.getIndices() : [];
  236. Tools.Warn("MeshImpostor only collides against spheres.");
  237. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  238. break;
  239. case PhysicsImpostor.HeightmapImpostor:
  240. returnValue = this._createHeightmap(object);
  241. break;
  242. case PhysicsImpostor.ParticleImpostor:
  243. returnValue = new CANNON.Particle();
  244. break;
  245. }
  246. return returnValue;
  247. }
  248. private _createHeightmap(object: IPhysicsEnabledObject, pointDepth?: number) {
  249. var pos = object.getVerticesData(VertexBuffer.PositionKind);
  250. var matrix = [];
  251. //For now pointDepth will not be used and will be automatically calculated.
  252. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  253. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  254. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSize.x, object.getBoundingInfo().boundingBox.extendSize.z);
  255. var elementSize = dim * 2 / arraySize;
  256. var minY = object.getBoundingInfo().boundingBox.extendSize.y;
  257. for (var i = 0; i < pos.length; i = i + 3) {
  258. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  259. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  260. var y = pos[i + 1] + minY;
  261. if (!matrix[x]) {
  262. matrix[x] = [];
  263. }
  264. if (!matrix[x][z]) {
  265. matrix[x][z] = y;
  266. }
  267. matrix[x][z] = Math.max(y, matrix[x][z]);
  268. }
  269. for (var x = 0; x <= arraySize; ++x) {
  270. if (!matrix[x]) {
  271. var loc = 1;
  272. while (!matrix[(x + loc) % arraySize]) {
  273. loc++;
  274. }
  275. matrix[x] = matrix[(x + loc) % arraySize].slice();
  276. //console.log("missing x", x);
  277. }
  278. for (var z = 0; z <= arraySize; ++z) {
  279. if (!matrix[x][z]) {
  280. var loc = 1;
  281. var newValue;
  282. while (newValue === undefined) {
  283. newValue = matrix[x][(z + loc++) % arraySize];
  284. }
  285. matrix[x][z] = newValue;
  286. }
  287. }
  288. }
  289. var shape = new CANNON.Heightfield(matrix, {
  290. elementSize: elementSize
  291. });
  292. //For future reference, needed for body transformation
  293. shape.minY = minY;
  294. return shape;
  295. }
  296. private _minus90X = new Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  297. private _plus90X = new Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  298. private _tmpPosition: Vector3 = Vector3.Zero();
  299. private _tmpQuaternion: Quaternion = new Quaternion();
  300. private _tmpDeltaPosition: Vector3 = Vector3.Zero();
  301. private _tmpDeltaRotation: Quaternion = new Quaternion();
  302. private _tmpUnityRotation: Quaternion = new Quaternion();
  303. private _updatePhysicsBodyTransformation(impostor: PhysicsImpostor) {
  304. var object = impostor.object;
  305. //make sure it is updated...
  306. object.computeWorldMatrix && object.computeWorldMatrix(true);
  307. // The delta between the mesh position and the mesh bounding box center
  308. var center = impostor.getObjectCenter();
  309. var extendSize = impostor.getObjectExtendSize();
  310. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  311. this._tmpPosition.copyFrom(center);
  312. var quaternion = object.rotationQuaternion;
  313. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  314. if (impostor.type === PhysicsImpostor.PlaneImpostor || impostor.type === PhysicsImpostor.HeightmapImpostor || impostor.type === PhysicsImpostor.CylinderImpostor) {
  315. //-90 DEG in X, precalculated
  316. quaternion = quaternion.multiply(this._minus90X);
  317. //Invert! (Precalculated, 90 deg in X)
  318. //No need to clone. this will never change.
  319. impostor.setDeltaRotation(this._plus90X);
  320. }
  321. //If it is a heightfield, if should be centered.
  322. if (impostor.type === PhysicsEngine.HeightmapImpostor) {
  323. var mesh = <AbstractMesh>(<any>object);
  324. //calculate the correct body position:
  325. var rotationQuaternion = mesh.rotationQuaternion;
  326. mesh.rotationQuaternion = this._tmpUnityRotation;
  327. mesh.computeWorldMatrix(true);
  328. //get original center with no rotation
  329. var c = center.clone();
  330. var oldPivot = mesh.getPivotMatrix() || Matrix.Translation(0, 0, 0);
  331. //rotation is back
  332. mesh.rotationQuaternion = rotationQuaternion;
  333. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  334. var p = Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  335. mesh.setPivotMatrix(p);
  336. mesh.computeWorldMatrix(true);
  337. //calculate the translation
  338. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  339. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  340. //add it inverted to the delta
  341. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center.subtract(c));
  342. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  343. mesh.setPivotMatrix(oldPivot);
  344. mesh.computeWorldMatrix(true);
  345. } else if (impostor.type === PhysicsEngine.MeshImpostor) {
  346. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  347. this._tmpPosition.copyFrom(object.position);
  348. }
  349. impostor.setDeltaPosition(this._tmpDeltaPosition);
  350. //Now update the impostor object
  351. impostor.physicsBody.position.copy(this._tmpPosition);
  352. impostor.physicsBody.quaternion.copy(quaternion);
  353. }
  354. public setTransformationFromPhysicsBody(impostor: PhysicsImpostor) {
  355. impostor.object.position.copyFrom(impostor.physicsBody.position);
  356. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  357. }
  358. public setPhysicsBodyTransformation(impostor: PhysicsImpostor, newPosition: Vector3, newRotation: Quaternion) {
  359. impostor.physicsBody.position.copy(newPosition);
  360. impostor.physicsBody.quaternion.copy(newRotation);
  361. }
  362. public isSupported(): boolean {
  363. return window.CANNON !== undefined;
  364. }
  365. public setLinearVelocity(impostor: PhysicsImpostor, velocity: Vector3) {
  366. impostor.physicsBody.velocity.copy(velocity);
  367. }
  368. public setAngularVelocity(impostor: PhysicsImpostor, velocity: Vector3) {
  369. impostor.physicsBody.angularVelocity.copy(velocity);
  370. }
  371. public getLinearVelocity(impostor: PhysicsImpostor): Vector3 {
  372. var v = impostor.physicsBody.velocity;
  373. if (!v) return null;
  374. return new Vector3(v.x, v.y, v.z)
  375. }
  376. public getAngularVelocity(impostor: PhysicsImpostor): Vector3 {
  377. var v = impostor.physicsBody.angularVelocity;
  378. if (!v) return null;
  379. return new Vector3(v.x, v.y, v.z)
  380. }
  381. public setBodyMass(impostor: PhysicsImpostor, mass: number) {
  382. impostor.physicsBody.mass = mass;
  383. impostor.physicsBody.updateMassProperties();
  384. }
  385. public sleepBody(impostor: PhysicsImpostor) {
  386. impostor.physicsBody.sleep();
  387. }
  388. public wakeUpBody(impostor: PhysicsImpostor) {
  389. impostor.physicsBody.wakeUp();
  390. }
  391. public updateDistanceJoint(joint: PhysicsJoint, maxDistance: number, minDistance?: number) {
  392. joint.physicsJoint.distance = maxDistance;
  393. }
  394. private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  395. if (!motorIndex) {
  396. joint.physicsJoint.enableMotor();
  397. }
  398. }
  399. private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  400. if (!motorIndex) {
  401. joint.physicsJoint.disableMotor();
  402. }
  403. }
  404. public setMotor(joint: IMotorEnabledJoint, speed?: number, maxForce?: number, motorIndex?: number) {
  405. if (!motorIndex) {
  406. joint.physicsJoint.enableMotor();
  407. joint.physicsJoint.setMotorSpeed(speed);
  408. if (maxForce) {
  409. this.setLimit(joint, maxForce);
  410. }
  411. //a hack for force application
  412. /*var torque = new CANNON.Vec3();
  413. var axis = joint.physicsJoint.axisB;
  414. var body = joint.physicsJoint.bodyB;
  415. var bodyTorque = body.torque;
  416. axis.scale(force, torque);
  417. body.vectorToWorldFrame(torque, torque);
  418. bodyTorque.vadd(torque, bodyTorque);*/
  419. }
  420. }
  421. public setLimit(joint: IMotorEnabledJoint, upperLimit: number, lowerLimit?: number) {
  422. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  423. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  424. }
  425. public dispose() {
  426. //nothing to do, actually.
  427. }
  428. }
  429. }