babylon.cannonJSPlugin.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. module BABYLON {
  2. declare var CANNON;
  3. export class CannonJSPlugin implements IPhysicsEnginePlugin {
  4. private _world: any;
  5. private _registeredMeshes = [];
  6. private _physicsMaterials = [];
  7. public initialize(iterations: number = 10): void {
  8. this._world = new CANNON.World();
  9. this._world.broadphase = new CANNON.NaiveBroadphase();
  10. this._world.solver.iterations = iterations;
  11. }
  12. private _checkWithEpsilon(value: number): number {
  13. return value < PhysicsEngine.Epsilon ? PhysicsEngine.Epsilon : value;
  14. }
  15. public runOneStep(delta: number): void {
  16. this._world.step(delta);
  17. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18. var registeredMesh = this._registeredMeshes[index];
  19. if (registeredMesh.isChild) {
  20. continue;
  21. }
  22. // Body position
  23. var bodyX = registeredMesh.body.position.x,
  24. bodyY = registeredMesh.body.position.y,
  25. bodyZ = registeredMesh.body.position.z;
  26. if(!registeredMesh.delta) {
  27. registeredMesh.delta = Vector3.Zero();
  28. }
  29. registeredMesh.mesh.position.x = bodyX + registeredMesh.delta.x;
  30. registeredMesh.mesh.position.y = bodyY + registeredMesh.delta.y;
  31. registeredMesh.mesh.position.z = bodyZ + registeredMesh.delta.z;
  32. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  33. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.y;
  34. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.z;
  35. registeredMesh.mesh.rotationQuaternion.w = registeredMesh.body.quaternion.w;
  36. }
  37. }
  38. public setGravity(gravity: Vector3): void {
  39. this._world.gravity.set(gravity.x, gravity.y, gravity.z);
  40. }
  41. public registerMesh(mesh: AbstractMesh, impostor: number, options?: PhysicsBodyCreationOptions): any {
  42. this.unregisterMesh(mesh);
  43. if (!mesh.rotationQuaternion) {
  44. mesh.rotationQuaternion = Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  45. }
  46. mesh.computeWorldMatrix(true);
  47. var shape = this._createShape(mesh, impostor, options);
  48. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  49. }
  50. private _createShape(mesh: AbstractMesh, impostor: number, options?: PhysicsBodyCreationOptions) {
  51. //get the correct bounding box
  52. var oldQuaternion = mesh.rotationQuaternion;
  53. mesh.rotationQuaternion = new Quaternion(0, 0, 0, 1);
  54. mesh.computeWorldMatrix(true);
  55. var returnValue;
  56. switch (impostor) {
  57. case PhysicsEngine.SphereImpostor:
  58. var bbox = mesh.getBoundingInfo().boundingBox;
  59. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  60. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  61. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  62. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  63. break;
  64. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  65. case PhysicsEngine.CylinderImpostor:
  66. Tools.Warn("CylinderImposter not yet implemented, using BoxImposter instead");
  67. case PhysicsEngine.BoxImpostor:
  68. bbox = mesh.getBoundingInfo().boundingBox;
  69. var min = bbox.minimumWorld;
  70. var max = bbox.maximumWorld;
  71. var box = max.subtract(min).scale(0.5);
  72. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  73. break;
  74. case PhysicsEngine.PlaneImpostor:
  75. Tools.Warn("Attention, Cannon.js PlaneImposter might not behave as you wish. Consider using BoxImposter instead");
  76. returnValue = new CANNON.Plane();
  77. break;
  78. case PhysicsEngine.MeshImpostor:
  79. var rawVerts = mesh.getVerticesData(VertexBuffer.PositionKind);
  80. var rawFaces = mesh.getIndices();
  81. returnValue = this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  82. break;
  83. }
  84. mesh.rotationQuaternion = oldQuaternion;
  85. return returnValue;
  86. }
  87. private _createConvexPolyhedron(rawVerts: number[] | Float32Array, rawFaces: number[], mesh: AbstractMesh, options?: PhysicsBodyCreationOptions): any {
  88. var verts = [], faces = [];
  89. mesh.computeWorldMatrix(true);
  90. // Get vertices
  91. for (var i = 0; i < rawVerts.length; i += 3) {
  92. var transformed = Vector3.Zero();
  93. Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  94. verts.push(new CANNON.Vec3(transformed.x, transformed.y, transformed.z));
  95. }
  96. // Get faces
  97. for (var j = 0; j < rawFaces.length; j += 3) {
  98. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  99. }
  100. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  101. return shape;
  102. }
  103. private _addMaterial(friction: number, restitution: number) {
  104. var index;
  105. var mat;
  106. for (index = 0; index < this._physicsMaterials.length; index++) {
  107. mat = this._physicsMaterials[index];
  108. if (mat.friction === friction && mat.restitution === restitution) {
  109. return mat;
  110. }
  111. }
  112. var currentMat = new CANNON.Material("mat");
  113. this._physicsMaterials.push(currentMat);
  114. for (index = 0; index < this._physicsMaterials.length; index++) {
  115. mat = this._physicsMaterials[index];
  116. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, { friction: friction, restitution: restitution });
  117. this._world.addContactMaterial(contactMaterial);
  118. }
  119. return currentMat;
  120. }
  121. private _createRigidBodyFromShape(shape: any, mesh: AbstractMesh, mass: number, friction: number, restitution: number): any {
  122. if (!mesh.rotationQuaternion) {
  123. mesh.rotationQuaternion = Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  124. }
  125. // The delta between the mesh position and the mesh bounding box center
  126. var bbox = mesh.getBoundingInfo().boundingBox;
  127. var deltaPosition = mesh.position.subtract(bbox.center);
  128. var material = this._addMaterial(friction, restitution);
  129. var body = new CANNON.Body({
  130. mass: mass,
  131. material: material,
  132. position: new CANNON.Vec3(bbox.center.x, bbox.center.y, bbox.center.z)
  133. });
  134. body.quaternion = new CANNON.Quaternion(mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z, mesh.rotationQuaternion.w);
  135. //is shape is a plane, it must be rotated 90 degs in the X axis.
  136. if (shape.type === CANNON.Shape.types.PLANE) {
  137. var tmpQ = new CANNON.Quaternion();
  138. tmpQ.setFromAxisAngle(new CANNON.Vec3(1, 0, 0), -Math.PI / 2);
  139. body.quaternion = body.quaternion.mult(tmpQ);
  140. }
  141. //add the shape
  142. body.addShape(shape);
  143. this._world.add(body);
  144. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  145. return body;
  146. }
  147. public registerMeshesAsCompound(parts: PhysicsCompoundBodyPart[], options: PhysicsBodyCreationOptions): any {
  148. var initialMesh = parts[0].mesh;
  149. this.unregisterMesh(initialMesh);
  150. initialMesh.computeWorldMatrix(true);
  151. var initialShape = this._createShape(initialMesh, parts[0].impostor);
  152. var body = this._createRigidBodyFromShape(initialShape, initialMesh, options.mass, options.friction, options.restitution);
  153. for (var index = 1; index < parts.length; index++) {
  154. var mesh = parts[index].mesh;
  155. mesh.computeWorldMatrix(true);
  156. var shape = this._createShape(mesh, parts[index].impostor);
  157. var localPosition = mesh.position;
  158. body.addShape(shape, new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  159. }
  160. return body;
  161. }
  162. private _unbindBody(body): void {
  163. for (var index = 0; index < this._registeredMeshes.length; index++) {
  164. var registeredMesh = this._registeredMeshes[index];
  165. if (registeredMesh.body === body) {
  166. this._world.remove(registeredMesh.body);
  167. registeredMesh.body = null;
  168. registeredMesh.delta = null;
  169. }
  170. }
  171. }
  172. public unregisterMesh(mesh: AbstractMesh): void {
  173. for (var index = 0; index < this._registeredMeshes.length; index++) {
  174. var registeredMesh = this._registeredMeshes[index];
  175. if (registeredMesh.mesh === mesh) {
  176. // Remove body
  177. if (registeredMesh.body) {
  178. this._unbindBody(registeredMesh.body);
  179. }
  180. this._registeredMeshes.splice(index, 1);
  181. return;
  182. }
  183. }
  184. }
  185. public applyImpulse(mesh: AbstractMesh, force: Vector3, contactPoint: Vector3): void {
  186. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  187. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  188. for (var index = 0; index < this._registeredMeshes.length; index++) {
  189. var registeredMesh = this._registeredMeshes[index];
  190. if (registeredMesh.mesh === mesh) {
  191. registeredMesh.body.applyImpulse(impulse, worldPoint);
  192. return;
  193. }
  194. }
  195. }
  196. public updateBodyPosition = function (mesh: AbstractMesh): void {
  197. for (var index = 0; index < this._registeredMeshes.length; index++) {
  198. var registeredMesh = this._registeredMeshes[index];
  199. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  200. var body = registeredMesh.body;
  201. var center = mesh.getBoundingInfo().boundingBox.center;
  202. body.position.set(center.x, center.y, center.z);
  203. body.quaternion.x = mesh.rotationQuaternion.x;
  204. body.quaternion.z = mesh.rotationQuaternion.z;
  205. body.quaternion.y = mesh.rotationQuaternion.y;
  206. body.quaternion.w = mesh.rotationQuaternion.w;
  207. return;
  208. }
  209. }
  210. }
  211. public createLink(mesh1: AbstractMesh, mesh2: AbstractMesh, pivot1: Vector3, pivot2: Vector3): boolean {
  212. var body1 = null, body2 = null;
  213. for (var index = 0; index < this._registeredMeshes.length; index++) {
  214. var registeredMesh = this._registeredMeshes[index];
  215. if (registeredMesh.mesh === mesh1) {
  216. body1 = registeredMesh.body;
  217. } else if (registeredMesh.mesh === mesh2) {
  218. body2 = registeredMesh.body;
  219. }
  220. }
  221. if (!body1 || !body2) {
  222. return false;
  223. }
  224. 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));
  225. this._world.addConstraint(constraint);
  226. return true;
  227. }
  228. public dispose(): void {
  229. while (this._registeredMeshes.length) {
  230. this.unregisterMesh(this._registeredMeshes[0].mesh);
  231. }
  232. }
  233. public isSupported(): boolean {
  234. return window.CANNON !== undefined;
  235. }
  236. public getWorldObject() : any {
  237. return this._world;
  238. }
  239. public getPhysicsBodyOfMesh(mesh: AbstractMesh) {
  240. for (var index = 0; index < this._registeredMeshes.length; index++) {
  241. var registeredMesh = this._registeredMeshes[index];
  242. if (registeredMesh.mesh === mesh) {
  243. return registeredMesh.body;
  244. }
  245. }
  246. return null;
  247. }
  248. }
  249. }