babylon.cannonJSPlugin.ts 12 KB

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