babylon.cannonJSPlugin.ts 13 KB

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