babylon.cannonJSPlugin.ts 12 KB

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