babylon.cannonJSPlugin.js 23 KB

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