babylon.cannonJSPlugin.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. var BABYLON;
  2. (function (BABYLON) {
  3. var CannonJSPlugin = (function () {
  4. function CannonJSPlugin() {
  5. this._registeredMeshes = [];
  6. this._physicsMaterials = [];
  7. this.updateBodyPosition = function (mesh) {
  8. for (var index = 0; index < this._registeredMeshes.length; index++) {
  9. var registeredMesh = this._registeredMeshes[index];
  10. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  11. var body = registeredMesh.body;
  12. var center = mesh.getBoundingInfo().boundingBox.center;
  13. body.position.set(center.x, center.y, center.z);
  14. body.quaternion.copy(mesh.rotationQuaternion);
  15. if (registeredMesh.deltaRotation) {
  16. var tmpQ = new CANNON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  17. body.quaternion = body.quaternion.mult(tmpQ);
  18. }
  19. //TODO - If the body is heightmap-based, this won't work correctly. find a good fix.
  20. return;
  21. }
  22. }
  23. };
  24. }
  25. CannonJSPlugin.prototype.initialize = function (iterations) {
  26. if (iterations === void 0) { iterations = 10; }
  27. this._world = new CANNON.World();
  28. this._world.broadphase = new CANNON.NaiveBroadphase();
  29. this._world.solver.iterations = iterations;
  30. };
  31. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  32. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  33. };
  34. CannonJSPlugin.prototype.runOneStep = function (delta) {
  35. this._world.step(delta);
  36. for (var index = 0; index < this._registeredMeshes.length; index++) {
  37. var registeredMesh = this._registeredMeshes[index];
  38. if (registeredMesh.isChild) {
  39. continue;
  40. }
  41. // Body position
  42. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  43. registeredMesh.mesh.position.x = bodyX + registeredMesh.delta.x;
  44. registeredMesh.mesh.position.y = bodyY + registeredMesh.delta.y;
  45. registeredMesh.mesh.position.z = bodyZ + registeredMesh.delta.z;
  46. registeredMesh.mesh.rotationQuaternion.copyFrom(registeredMesh.body.quaternion);
  47. if (registeredMesh.deltaRotation) {
  48. registeredMesh.mesh.rotationQuaternion.multiplyInPlace(registeredMesh.deltaRotation);
  49. }
  50. }
  51. };
  52. CannonJSPlugin.prototype.setGravity = function (gravity) {
  53. this._world.gravity.set(gravity.x, gravity.y, gravity.z);
  54. };
  55. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  56. this.unregisterMesh(mesh);
  57. if (!mesh.rotationQuaternion) {
  58. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  59. }
  60. mesh.computeWorldMatrix(true);
  61. var shape = this._createShape(mesh, impostor);
  62. return this._createRigidBodyFromShape(shape, mesh, options);
  63. };
  64. CannonJSPlugin.prototype._createShape = function (mesh, impostor) {
  65. //get the correct bounding box
  66. var oldQuaternion = mesh.rotationQuaternion;
  67. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  68. mesh.computeWorldMatrix(true);
  69. var returnValue;
  70. switch (impostor) {
  71. case BABYLON.PhysicsEngine.SphereImpostor:
  72. var bbox = mesh.getBoundingInfo().boundingBox;
  73. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  74. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  75. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  76. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  77. break;
  78. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  79. case BABYLON.PhysicsEngine.CylinderImpostor:
  80. BABYLON.Tools.Warn("CylinderImposter not yet implemented, using BoxImposter instead");
  81. case BABYLON.PhysicsEngine.BoxImpostor:
  82. bbox = mesh.getBoundingInfo().boundingBox;
  83. var min = bbox.minimumWorld;
  84. var max = bbox.maximumWorld;
  85. var box = max.subtract(min).scale(0.5);
  86. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  87. break;
  88. case BABYLON.PhysicsEngine.PlaneImpostor:
  89. BABYLON.Tools.Warn("Attention, Cannon.js PlaneImposter might not behave as you wish. Consider using BoxImposter instead");
  90. returnValue = new CANNON.Plane();
  91. break;
  92. case BABYLON.PhysicsEngine.MeshImpostor:
  93. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  94. var rawFaces = mesh.getIndices();
  95. returnValue = this._createConvexPolyhedron(rawVerts, rawFaces, mesh);
  96. break;
  97. case BABYLON.PhysicsEngine.HeightmapImpostor:
  98. returnValue = this._createHeightmap(mesh);
  99. break;
  100. }
  101. mesh.rotationQuaternion = oldQuaternion;
  102. return returnValue;
  103. };
  104. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh) {
  105. var verts = [], faces = [];
  106. mesh.computeWorldMatrix(true);
  107. // Get vertices
  108. for (var i = 0; i < rawVerts.length; i += 3) {
  109. var transformed = BABYLON.Vector3.Zero();
  110. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  111. verts.push(new CANNON.Vec3(transformed.x, transformed.y, transformed.z));
  112. }
  113. // Get faces
  114. for (var j = 0; j < rawFaces.length; j += 3) {
  115. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  116. }
  117. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  118. return shape;
  119. };
  120. CannonJSPlugin.prototype._createHeightmap = function (mesh) {
  121. var pos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  122. if (pos[0] !== pos[pos.length - 1]) {
  123. console.log("ERROR");
  124. return;
  125. }
  126. var matrix = [];
  127. //dimension
  128. var dim = -pos[0];
  129. //array size
  130. var arraySize = -1;
  131. for (var i = 0; i < pos.length; i = i + 3) {
  132. if (pos[i + 2] === pos[2]) {
  133. arraySize++;
  134. }
  135. else {
  136. break;
  137. }
  138. }
  139. //calculate element size
  140. var elementSize = dim * 2 / arraySize;
  141. //calculate the matrix for cannon's heightfield
  142. for (var i = 0; i < pos.length; i = i + 3) {
  143. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  144. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  145. if (!matrix[x]) {
  146. matrix[x] = [];
  147. }
  148. matrix[x][z] = pos[i + 1];
  149. }
  150. return CANNON.Heightfield(matrix, {
  151. elementSize: elementSize,
  152. //Babylon options, NOT cannon
  153. dim: dim
  154. });
  155. };
  156. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  157. var index;
  158. var mat;
  159. for (index = 0; index < this._physicsMaterials.length; index++) {
  160. mat = this._physicsMaterials[index];
  161. if (mat.friction === friction && mat.restitution === restitution) {
  162. return mat;
  163. }
  164. }
  165. var currentMat = new CANNON.Material("mat");
  166. this._physicsMaterials.push(currentMat);
  167. for (index = 0; index < this._physicsMaterials.length; index++) {
  168. mat = this._physicsMaterials[index];
  169. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, { friction: friction, restitution: restitution });
  170. this._world.addContactMaterial(contactMaterial);
  171. }
  172. return currentMat;
  173. };
  174. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, options) {
  175. if (!mesh.rotationQuaternion) {
  176. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  177. }
  178. // The delta between the mesh position and the mesh bounding box center
  179. var bbox = mesh.getBoundingInfo().boundingBox;
  180. var deltaPosition = mesh.position.subtract(bbox.center);
  181. var deltaRotation;
  182. var material = this._addMaterial(options.friction, options.restitution);
  183. var body = new CANNON.Body({
  184. mass: options.mass,
  185. material: material,
  186. position: new CANNON.Vec3(bbox.center.x, bbox.center.y, bbox.center.z)
  187. });
  188. body.quaternion = new CANNON.Quaternion(mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z, mesh.rotationQuaternion.w);
  189. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  190. if (shape.type === CANNON.Shape.types.PLANE || shape.type === CANNON.Shape.types.HEIGHTFIELD) {
  191. //-90 DEG in X, precalculated
  192. var tmpQ = new CANNON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  193. body.quaternion = body.quaternion.mult(tmpQ);
  194. //Invert!
  195. deltaRotation = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  196. }
  197. //If it is a heightfield, if should be centered.
  198. if (shape.type === CANNON.Shape.types.HEIGHTFIELD) {
  199. body.position = body.position.vadd(new CANNON.Vec3(-shape.options.dim, 0, shape.options.dim));
  200. //add it inverted to the delta
  201. deltaPosition.x += shape.options.dim;
  202. deltaPosition.z -= shape.options.dim;
  203. }
  204. //add the shape
  205. body.addShape(shape);
  206. this._world.add(body);
  207. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition, deltaRotation: deltaRotation });
  208. return body;
  209. };
  210. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  211. var initialMesh = parts[0].mesh;
  212. this.unregisterMesh(initialMesh);
  213. initialMesh.computeWorldMatrix(true);
  214. var initialShape = this._createShape(initialMesh, parts[0].impostor);
  215. var body = this._createRigidBodyFromShape(initialShape, initialMesh, options);
  216. for (var index = 1; index < parts.length; index++) {
  217. var mesh = parts[index].mesh;
  218. mesh.computeWorldMatrix(true);
  219. var shape = this._createShape(mesh, parts[index].impostor);
  220. var localPosition = mesh.position;
  221. body.addShape(shape, new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  222. }
  223. return body;
  224. };
  225. CannonJSPlugin.prototype._unbindBody = function (body) {
  226. for (var index = 0; index < this._registeredMeshes.length; index++) {
  227. var registeredMesh = this._registeredMeshes[index];
  228. if (registeredMesh.body === body) {
  229. this._world.remove(registeredMesh.body);
  230. registeredMesh.body = null;
  231. registeredMesh.delta = null;
  232. registeredMesh.deltaRotation = null;
  233. }
  234. }
  235. };
  236. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  237. for (var index = 0; index < this._registeredMeshes.length; index++) {
  238. var registeredMesh = this._registeredMeshes[index];
  239. if (registeredMesh.mesh === mesh) {
  240. // Remove body
  241. if (registeredMesh.body) {
  242. this._unbindBody(registeredMesh.body);
  243. }
  244. this._registeredMeshes.splice(index, 1);
  245. return;
  246. }
  247. }
  248. };
  249. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  250. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  251. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  252. for (var index = 0; index < this._registeredMeshes.length; index++) {
  253. var registeredMesh = this._registeredMeshes[index];
  254. if (registeredMesh.mesh === mesh) {
  255. registeredMesh.body.applyImpulse(impulse, worldPoint);
  256. return;
  257. }
  258. }
  259. };
  260. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  261. var body1 = null, body2 = null;
  262. for (var index = 0; index < this._registeredMeshes.length; index++) {
  263. var registeredMesh = this._registeredMeshes[index];
  264. if (registeredMesh.mesh === mesh1) {
  265. body1 = registeredMesh.body;
  266. }
  267. else if (registeredMesh.mesh === mesh2) {
  268. body2 = registeredMesh.body;
  269. }
  270. }
  271. if (!body1 || !body2) {
  272. return false;
  273. }
  274. var constraint = new CANNON.PointToPointConstraint(body1, new CANNON.Vec3(pivot1.x, pivot1.y, pivot1.z), body2, new CANNON.Vec3(pivot2.x, pivot2.y, pivot2.z));
  275. this._world.addConstraint(constraint);
  276. return true;
  277. };
  278. CannonJSPlugin.prototype.dispose = function () {
  279. while (this._registeredMeshes.length) {
  280. this.unregisterMesh(this._registeredMeshes[0].mesh);
  281. }
  282. };
  283. CannonJSPlugin.prototype.isSupported = function () {
  284. return window.CANNON !== undefined;
  285. };
  286. CannonJSPlugin.prototype.getWorldObject = function () {
  287. return this._world;
  288. };
  289. CannonJSPlugin.prototype.getPhysicsBodyOfMesh = function (mesh) {
  290. for (var index = 0; index < this._registeredMeshes.length; index++) {
  291. var registeredMesh = this._registeredMeshes[index];
  292. if (registeredMesh.mesh === mesh) {
  293. return registeredMesh.body;
  294. }
  295. }
  296. return null;
  297. };
  298. return CannonJSPlugin;
  299. })();
  300. BABYLON.CannonJSPlugin = CannonJSPlugin;
  301. })(BABYLON || (BABYLON = {}));