babylon.cannonJSPlugin.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. module BABYLON {
  2. declare var CANNON;
  3. declare var window;
  4. export class CannonJSPlugin {
  5. public checkWithEpsilon: (value: number) => number;
  6. private _world: any;
  7. private _registeredMeshes = [];
  8. private _physicsMaterials = [];
  9. public initialize(iterations: number = 10): void {
  10. this._world = new CANNON.World();
  11. this._world.broadphase = new CANNON.NaiveBroadphase();
  12. this._world.solver.iterations = iterations;
  13. }
  14. private _checkWithEpsilon(value: number): number {
  15. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  16. }
  17. public runOneStep(delta: number): void {
  18. this._world.step(delta);
  19. for (var index = 0; index < this._registeredMeshes.length; index++) {
  20. var registeredMesh = this._registeredMeshes[index];
  21. if (registeredMesh.isChild) {
  22. continue;
  23. }
  24. registeredMesh.mesh.position.x = registeredMesh.body.position.x;
  25. registeredMesh.mesh.position.y = registeredMesh.body.position.z;
  26. registeredMesh.mesh.position.z = registeredMesh.body.position.y;
  27. if (!registeredMesh.mesh.rotationQuaternion) {
  28. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  29. }
  30. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  31. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  32. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  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.z, gravity.y);
  38. }
  39. public registerMesh(mesh: Mesh, impostor: number, options?: PhysicsBodyCreationOptions): any {
  40. this.unregisterMesh(mesh);
  41. mesh.computeWorldMatrix(true);
  42. switch (impostor) {
  43. case BABYLON.PhysicsEngine.SphereImpostor:
  44. var bbox = mesh.getBoundingInfo().boundingBox;
  45. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  46. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  47. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  48. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  49. case BABYLON.PhysicsEngine.BoxImpostor:
  50. bbox = mesh.getBoundingInfo().boundingBox;
  51. var min = bbox.minimumWorld;
  52. var max = bbox.maximumWorld;
  53. var box = max.subtract(min).scale(0.5);
  54. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  55. case BABYLON.PhysicsEngine.PlaneImpostor:
  56. return this._createPlane(mesh, options);
  57. case BABYLON.PhysicsEngine.MeshImpostor:
  58. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  59. var rawFaces = mesh.getIndices();
  60. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  61. }
  62. return null;
  63. }
  64. private _createSphere(radius: number, mesh: Mesh, options?: PhysicsBodyCreationOptions): any {
  65. var shape = new CANNON.Sphere(radius);
  66. if (!options) {
  67. return shape;
  68. }
  69. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  70. }
  71. private _createBox(x: number, y: number, z: number, mesh: Mesh, options?: PhysicsBodyCreationOptions): any {
  72. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  73. if (!options) {
  74. return shape;
  75. }
  76. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  77. }
  78. private _createPlane(mesh: Mesh, options?: PhysicsBodyCreationOptions): any {
  79. var shape = new CANNON.Plane();
  80. if (!options) {
  81. return shape;
  82. }
  83. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  84. }
  85. private _createConvexPolyhedron(rawVerts: number[], rawFaces: number[], mesh: Mesh, options?: PhysicsBodyCreationOptions): any {
  86. var verts = [], faces = [];
  87. mesh.computeWorldMatrix(true);
  88. // Get vertices
  89. for (var i = 0; i < rawVerts.length; i += 3) {
  90. var transformed = BABYLON.Vector3.Zero();
  91. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  92. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  93. }
  94. // Get faces
  95. for (var j = 0; j < rawFaces.length; j += 3) {
  96. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  97. }
  98. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  99. if (!options) {
  100. return shape;
  101. }
  102. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  103. }
  104. private _addMaterial(friction: number, restitution: number) {
  105. var index;
  106. var mat;
  107. for (index = 0; index < this._physicsMaterials.length; index++) {
  108. mat = this._physicsMaterials[index];
  109. if (mat.friction === friction && mat.restitution === restitution) {
  110. return mat;
  111. }
  112. }
  113. var currentMat = new CANNON.Material();
  114. currentMat.friction = friction;
  115. currentMat.restitution = restitution;
  116. this._physicsMaterials.push(currentMat);
  117. for (index = 0; index < this._physicsMaterials.length; index++) {
  118. mat = this._physicsMaterials[index];
  119. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  120. contactMaterial.contactEquationStiffness = 1e10;
  121. contactMaterial.contactEquationRegularizationTime = 10;
  122. this._world.addContactMaterial(contactMaterial);
  123. }
  124. return currentMat;
  125. }
  126. private _createRigidBodyFromShape(shape: any, mesh: Mesh, mass: number, friction: number, restitution: number): any {
  127. var initialRotation: Quaternion = null;
  128. if (mesh.rotationQuaternion) {
  129. initialRotation = mesh.rotationQuaternion.clone();
  130. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  131. }
  132. var material = this._addMaterial(friction, restitution);
  133. var body = new CANNON.RigidBody(mass, shape, material);
  134. if (initialRotation) {
  135. body.quaternion.x = initialRotation.x;
  136. body.quaternion.z = initialRotation.y;
  137. body.quaternion.y = initialRotation.z;
  138. body.quaternion.w = -initialRotation.w;
  139. }
  140. body.position.set(mesh.position.x, mesh.position.z, mesh.position.y);
  141. this._world.add(body);
  142. this._registeredMeshes.push({ mesh: mesh, body: body, material: material });
  143. return body;
  144. }
  145. public registerMeshesAsCompound(parts: PhysicsCompoundBodyPart[], options: PhysicsBodyCreationOptions): any {
  146. var compoundShape = new CANNON.Compound();
  147. for (var index = 0; index < parts.length; index++) {
  148. var mesh = parts[index].mesh;
  149. var shape = this.registerMesh(mesh, parts[index].impostor);
  150. if (index == 0) { // Parent
  151. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  152. } else {
  153. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  154. }
  155. }
  156. var initialMesh = parts[0].mesh;
  157. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  158. body.parts = parts;
  159. return body;
  160. }
  161. private _unbindBody(body): void {
  162. for (var index = 0; index < this._registeredMeshes.length; index++) {
  163. var registeredMesh = this._registeredMeshes[index];
  164. if (registeredMesh.body === body) {
  165. registeredMesh.body = null;
  166. }
  167. }
  168. }
  169. public unregisterMesh(mesh: Mesh): void {
  170. for (var index = 0; index < this._registeredMeshes.length; index++) {
  171. var registeredMesh = this._registeredMeshes[index];
  172. if (registeredMesh.mesh === mesh) {
  173. // Remove body
  174. if (registeredMesh.body) {
  175. this._world.remove(registeredMesh.body);
  176. this._unbindBody(registeredMesh.body);
  177. }
  178. this._registeredMeshes.splice(index, 1);
  179. return;
  180. }
  181. }
  182. }
  183. public applyImpulse(mesh: Mesh, force: Vector3, contactPoint: Vector3): void {
  184. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  185. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  186. for (var index = 0; index < this._registeredMeshes.length; index++) {
  187. var registeredMesh = this._registeredMeshes[index];
  188. if (registeredMesh.mesh === mesh) {
  189. registeredMesh.body.applyImpulse(impulse, worldPoint);
  190. return;
  191. }
  192. }
  193. }
  194. public createLink(mesh1: Mesh, mesh2: Mesh, pivot1: Vector3, pivot2: Vector3): boolean {
  195. var body1 = null, body2 = null;
  196. for (var index = 0; index < this._registeredMeshes.length; index++) {
  197. var registeredMesh = this._registeredMeshes[index];
  198. if (registeredMesh.mesh === mesh1) {
  199. body1 = registeredMesh.body;
  200. } else if (registeredMesh.mesh === mesh2) {
  201. body2 = registeredMesh.body;
  202. }
  203. }
  204. if (!body1 || !body2) {
  205. return false;
  206. }
  207. var constraint = new CANNON.PointToPointConstraint(body1, new CANNON.Vec3(pivot1.x, pivot1.z, pivot1.y), body2, new CANNON.Vec3(pivot2.x, pivot2.z, pivot2.y));
  208. this._world.addConstraint(constraint);
  209. return true;
  210. }
  211. public dispose(): void {
  212. while (this._registeredMeshes.length) {
  213. this.unregisterMesh(this._registeredMeshes[0].mesh);
  214. }
  215. }
  216. public isSupported(): boolean {
  217. return window.CANNON !== undefined;
  218. }
  219. }
  220. }