babylon.cannonJSPlugin.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  1. module BABYLON {
  2. declare var CANNON;
  3. interface IRegisteredMesh {
  4. mesh: AbstractMesh;
  5. body: any; //Cannon body
  6. material: any;
  7. delta: Vector3;
  8. deltaRotation: Quaternion;
  9. heightmap: boolean;
  10. collisionFunction?: (event: any) => void;
  11. }
  12. export class CannonJSPlugin implements IPhysicsEnginePlugin {
  13. private _world: any;
  14. private _registeredMeshes: Array<IRegisteredMesh> = [];
  15. private _physicsMaterials = [];
  16. private _gravity: Vector3;
  17. public name = "cannon";
  18. public initialize(iterations: number = 10): void {
  19. this._world = new CANNON.World();
  20. this._world.broadphase = new CANNON.NaiveBroadphase();
  21. this._world.solver.iterations = iterations;
  22. }
  23. private _checkWithEpsilon(value: number): number {
  24. return value < PhysicsEngine.Epsilon ? PhysicsEngine.Epsilon : value;
  25. }
  26. public runOneStep(delta: number): void {
  27. this._world.step(delta);
  28. this._registeredMeshes.forEach((registeredMesh) => {
  29. // Body position
  30. var bodyX = registeredMesh.body.position.x,
  31. bodyY = registeredMesh.body.position.y,
  32. bodyZ = registeredMesh.body.position.z;
  33. registeredMesh.mesh.position.x = bodyX + registeredMesh.delta.x;
  34. registeredMesh.mesh.position.y = bodyY + registeredMesh.delta.y;
  35. registeredMesh.mesh.position.z = bodyZ + registeredMesh.delta.z;
  36. registeredMesh.mesh.rotationQuaternion.copyFrom(registeredMesh.body.quaternion);
  37. if (registeredMesh.deltaRotation) {
  38. registeredMesh.mesh.rotationQuaternion.multiplyInPlace(registeredMesh.deltaRotation);
  39. }
  40. //is the physics collision callback is set?
  41. if (registeredMesh.mesh.onPhysicsCollide) {
  42. if (!registeredMesh.collisionFunction) {
  43. registeredMesh.collisionFunction = (e) => {
  44. //find the mesh that collided with the registered mesh
  45. for (var idx = 0; idx < this._registeredMeshes.length; idx++) {
  46. if (this._registeredMeshes[idx].body == e.body) {
  47. registeredMesh.mesh.onPhysicsCollide(this._registeredMeshes[idx].mesh);
  48. }
  49. }
  50. }
  51. registeredMesh.body.addEventListener("collide", registeredMesh.collisionFunction);
  52. }
  53. } else {
  54. //unregister, in case the function was removed for some reason
  55. if (registeredMesh.collisionFunction) {
  56. registeredMesh.body.removeEventListener("collide", registeredMesh.collisionFunction);
  57. }
  58. }
  59. });
  60. }
  61. public setGravity(gravity: Vector3): void {
  62. this._gravity = gravity;
  63. this._world.gravity.set(gravity.x, gravity.y, gravity.z);
  64. }
  65. public getGravity() : Vector3 {
  66. return this._gravity;
  67. }
  68. public registerMesh(mesh: AbstractMesh, impostor: number, options?: PhysicsBodyCreationOptions): any {
  69. this.unregisterMesh(mesh);
  70. if (!mesh.rotationQuaternion) {
  71. mesh.rotationQuaternion = Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  72. }
  73. mesh.computeWorldMatrix(true);
  74. var shape = this._createShape(mesh, impostor);
  75. return this._createRigidBodyFromShape(shape, mesh, options);
  76. }
  77. private _createShape(mesh: AbstractMesh, impostor: number) {
  78. //get the correct bounding box
  79. var oldQuaternion = mesh.rotationQuaternion;
  80. mesh.rotationQuaternion = new Quaternion(0, 0, 0, 1);
  81. mesh.computeWorldMatrix(true);
  82. var returnValue;
  83. switch (impostor) {
  84. case PhysicsEngine.SphereImpostor:
  85. var bbox = mesh.getBoundingInfo().boundingBox;
  86. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  87. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  88. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  89. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  90. break;
  91. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  92. case PhysicsEngine.CylinderImpostor:
  93. Tools.Warn("CylinderImposter not yet implemented, using BoxImposter instead");
  94. case PhysicsEngine.BoxImpostor:
  95. bbox = mesh.getBoundingInfo().boundingBox;
  96. var min = bbox.minimumWorld;
  97. var max = bbox.maximumWorld;
  98. var box = max.subtract(min).scale(0.5);
  99. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  100. break;
  101. case PhysicsEngine.PlaneImpostor:
  102. Tools.Warn("Attention, Cannon.js PlaneImposter might not behave as you wish. Consider using BoxImposter instead");
  103. returnValue = new CANNON.Plane();
  104. break;
  105. case PhysicsEngine.MeshImpostor:
  106. var rawVerts = mesh.getVerticesData(VertexBuffer.PositionKind);
  107. var rawFaces = mesh.getIndices();
  108. returnValue = this._createConvexPolyhedron(rawVerts, rawFaces, mesh);
  109. break;
  110. case PhysicsEngine.HeightmapImpostor:
  111. returnValue = this._createHeightmap(mesh);
  112. break;
  113. }
  114. mesh.rotationQuaternion = oldQuaternion;
  115. return returnValue;
  116. }
  117. private _createConvexPolyhedron(rawVerts: number[] | Float32Array, rawFaces: number[], mesh: AbstractMesh): any {
  118. var verts = [], faces = [];
  119. mesh.computeWorldMatrix(true);
  120. //reuse this variable
  121. var transformed = Vector3.Zero();
  122. // Get vertices
  123. for (var i = 0; i < rawVerts.length; i += 3) {
  124. Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  125. verts.push(new CANNON.Vec3(transformed.x, transformed.y, transformed.z));
  126. }
  127. // Get faces
  128. for (var j = 0; j < rawFaces.length; j += 3) {
  129. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  130. }
  131. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  132. return shape;
  133. }
  134. private _createHeightmap(mesh: AbstractMesh, pointDepth?: number) {
  135. var pos = mesh.getVerticesData(VertexBuffer.PositionKind);
  136. var matrix = [];
  137. //For now pointDepth will not be used and will be automatically calculated.
  138. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  139. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  140. var dim = Math.min(mesh.getBoundingInfo().boundingBox.extendSize.x, mesh.getBoundingInfo().boundingBox.extendSize.z);
  141. var elementSize = dim * 2 / arraySize;
  142. var minY = mesh.getBoundingInfo().boundingBox.extendSize.y;
  143. for (var i = 0; i < pos.length; i = i + 3) {
  144. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  145. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  146. var y = pos[i + 1] + minY;
  147. if (!matrix[x]) {
  148. matrix[x] = [];
  149. }
  150. if (!matrix[x][z]) {
  151. matrix[x][z] = y;
  152. }
  153. matrix[x][z] = Math.max(y, matrix[x][z]);
  154. }
  155. for (var x = 0; x <= arraySize; ++x) {
  156. if (!matrix[x]) {
  157. var loc = 1;
  158. while (!matrix[(x + loc) % arraySize]) {
  159. loc++;
  160. }
  161. matrix[x] = matrix[(x + loc) % arraySize].slice();
  162. //console.log("missing x", x);
  163. }
  164. for (var z = 0; z <= arraySize; ++z) {
  165. if (!matrix[x][z]) {
  166. var loc = 1;
  167. var newValue;
  168. while (newValue === undefined) {
  169. newValue = matrix[x][(z + loc++) % arraySize];
  170. }
  171. matrix[x][z] = newValue;
  172. }
  173. }
  174. }
  175. var shape = new CANNON.Heightfield(matrix, {
  176. elementSize: elementSize
  177. });
  178. //For future reference, needed for body transformation
  179. shape.minY = minY;
  180. return shape;
  181. }
  182. private _addMaterial(friction: number, restitution: number) {
  183. var index;
  184. var mat;
  185. for (index = 0; index < this._physicsMaterials.length; index++) {
  186. mat = this._physicsMaterials[index];
  187. if (mat.friction === friction && mat.restitution === restitution) {
  188. return mat;
  189. }
  190. }
  191. var currentMat = new CANNON.Material("mat");
  192. this._physicsMaterials.push(currentMat);
  193. for (index = 0; index < this._physicsMaterials.length; index++) {
  194. mat = this._physicsMaterials[index];
  195. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, { friction: friction, restitution: restitution });
  196. this._world.addContactMaterial(contactMaterial);
  197. }
  198. return currentMat;
  199. }
  200. private _createRigidBodyFromShape(shape: any, mesh: AbstractMesh, options: PhysicsBodyCreationOptions): any {
  201. if (!mesh.rotationQuaternion) {
  202. mesh.rotationQuaternion = Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  203. }
  204. // The delta between the mesh position and the mesh bounding box center
  205. var bbox = mesh.getBoundingInfo().boundingBox;
  206. var deltaPosition = mesh.position.subtract(bbox.center);
  207. var deltaRotation;
  208. var material = this._addMaterial(options.friction, options.restitution);
  209. var body = new CANNON.Body({
  210. mass: options.mass,
  211. material: material,
  212. position: new CANNON.Vec3(bbox.center.x, bbox.center.y, bbox.center.z)
  213. });
  214. body.quaternion = new CANNON.Quaternion(mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z, mesh.rotationQuaternion.w);
  215. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  216. if (shape.type === CANNON.Shape.types.PLANE || shape.type === CANNON.Shape.types.HEIGHTFIELD) {
  217. //-90 DEG in X, precalculated
  218. var tmpQ = new CANNON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  219. body.quaternion = body.quaternion.mult(tmpQ);
  220. //Invert! (Precalculated, 90 deg in X)
  221. deltaRotation = new Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  222. }
  223. //If it is a heightfield, if should be centered.
  224. if (shape.type === CANNON.Shape.types.HEIGHTFIELD) {
  225. //calculate the correct body position:
  226. var rotationQuaternion = mesh.rotationQuaternion;
  227. mesh.rotationQuaternion = new BABYLON.Quaternion();
  228. mesh.computeWorldMatrix(true);
  229. //get original center with no rotation
  230. var center = mesh.getBoundingInfo().boundingBox.center.clone();
  231. var oldPivot = mesh.getPivotMatrix() || Matrix.Translation(0, 0, 0);
  232. //rotation is back
  233. mesh.rotationQuaternion = rotationQuaternion;
  234. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  235. var p = Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  236. mesh.setPivotMatrix(p);
  237. mesh.computeWorldMatrix(true);
  238. //calculate the translation
  239. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  240. body.position = new CANNON.Vec3(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  241. //add it inverted to the delta
  242. deltaPosition = mesh.getBoundingInfo().boundingBox.center.subtract(center);
  243. deltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  244. mesh.setPivotMatrix(oldPivot);
  245. mesh.computeWorldMatrix(true);
  246. }
  247. //add the shape
  248. body.addShape(shape);
  249. this._world.add(body);
  250. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition, deltaRotation: deltaRotation, heightmap: shape.type === CANNON.Shape.types.HEIGHTFIELD });
  251. return body;
  252. }
  253. public registerMeshesAsCompound(parts: PhysicsCompoundBodyPart[], options: PhysicsBodyCreationOptions): any {
  254. var initialMesh = parts[0].mesh;
  255. this.unregisterMesh(initialMesh);
  256. initialMesh.computeWorldMatrix(true);
  257. var initialShape = this._createShape(initialMesh, parts[0].impostor);
  258. var body = this._createRigidBodyFromShape(initialShape, initialMesh, options);
  259. for (var index = 1; index < parts.length; index++) {
  260. var mesh = parts[index].mesh;
  261. mesh.computeWorldMatrix(true);
  262. var shape = this._createShape(mesh, parts[index].impostor);
  263. var localPosition = mesh.position;
  264. body.addShape(shape, new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  265. }
  266. return body;
  267. }
  268. private _unbindBody(body): void {
  269. for (var index = 0; index < this._registeredMeshes.length; index++) {
  270. var registeredMesh = this._registeredMeshes[index];
  271. if (registeredMesh.body === body) {
  272. this._world.remove(registeredMesh.body);
  273. registeredMesh.body = null;
  274. registeredMesh.delta = null;
  275. registeredMesh.deltaRotation = null;
  276. }
  277. }
  278. }
  279. public unregisterMesh(mesh: AbstractMesh): void {
  280. for (var index = 0; index < this._registeredMeshes.length; index++) {
  281. var registeredMesh = this._registeredMeshes[index];
  282. if (registeredMesh.mesh === mesh) {
  283. // Remove body
  284. if (registeredMesh.body) {
  285. this._unbindBody(registeredMesh.body);
  286. }
  287. this._registeredMeshes.splice(index, 1);
  288. return;
  289. }
  290. }
  291. }
  292. public applyImpulse(mesh: AbstractMesh, force: Vector3, contactPoint: Vector3): void {
  293. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  294. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  295. for (var index = 0; index < this._registeredMeshes.length; index++) {
  296. var registeredMesh = this._registeredMeshes[index];
  297. if (registeredMesh.mesh === mesh) {
  298. registeredMesh.body.applyImpulse(impulse, worldPoint);
  299. return;
  300. }
  301. }
  302. }
  303. public updateBodyPosition = function (mesh: AbstractMesh): void {
  304. for (var index = 0; index < this._registeredMeshes.length; index++) {
  305. var registeredMesh = this._registeredMeshes[index];
  306. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  307. var body = registeredMesh.body;
  308. var center = mesh.getBoundingInfo().boundingBox.center;
  309. body.position.set(center.x, center.y, center.z);
  310. body.quaternion.copy(mesh.rotationQuaternion);
  311. if (registeredMesh.deltaRotation) {
  312. var tmpQ = new CANNON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  313. body.quaternion = body.quaternion.mult(tmpQ);
  314. }
  315. if (registeredMesh.heightmap) {
  316. //calculate the correct body position:
  317. var rotationQuaternion = mesh.rotationQuaternion;
  318. mesh.rotationQuaternion = new BABYLON.Quaternion();
  319. mesh.computeWorldMatrix(true);
  320. //get original center with no rotation
  321. var center = mesh.getBoundingInfo().boundingBox.center.clone();
  322. var oldPivot = mesh.getPivotMatrix() || Matrix.Translation(0, 0, 0);
  323. //rotation is back
  324. mesh.rotationQuaternion = rotationQuaternion;
  325. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  326. var p = Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  327. mesh.setPivotMatrix(p);
  328. mesh.computeWorldMatrix(true);
  329. //calculate the translation
  330. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  331. body.position = new CANNON.Vec3(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  332. //add it inverted to the delta
  333. registeredMesh.delta = mesh.getBoundingInfo().boundingBox.center.subtract(center);
  334. registeredMesh.delta.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  335. mesh.setPivotMatrix(oldPivot);
  336. mesh.computeWorldMatrix(true);
  337. }
  338. return;
  339. }
  340. }
  341. }
  342. public createLink(mesh1: AbstractMesh, mesh2: AbstractMesh, pivot1: Vector3, pivot2: Vector3): boolean {
  343. var body1 = null, body2 = null;
  344. for (var index = 0; index < this._registeredMeshes.length; index++) {
  345. var registeredMesh = this._registeredMeshes[index];
  346. if (registeredMesh.mesh === mesh1) {
  347. body1 = registeredMesh.body;
  348. } else if (registeredMesh.mesh === mesh2) {
  349. body2 = registeredMesh.body;
  350. }
  351. }
  352. if (!body1 || !body2) {
  353. return false;
  354. }
  355. 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));
  356. this._world.addConstraint(constraint);
  357. return true;
  358. }
  359. public dispose(): void {
  360. while (this._registeredMeshes.length) {
  361. this.unregisterMesh(this._registeredMeshes[0].mesh);
  362. }
  363. }
  364. public isSupported(): boolean {
  365. return window.CANNON !== undefined;
  366. }
  367. public getWorldObject(): any {
  368. return this._world;
  369. }
  370. public getPhysicsBodyOfMesh(mesh: AbstractMesh) {
  371. for (var index = 0; index < this._registeredMeshes.length; index++) {
  372. var registeredMesh = this._registeredMeshes[index];
  373. if (registeredMesh.mesh === mesh) {
  374. return registeredMesh.body;
  375. }
  376. }
  377. return null;
  378. }
  379. }
  380. }