babylon.oimoJSPlugin.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. module BABYLON {
  2. declare var OIMO;
  3. export class OimoJSPlugin {
  4. public world: any;
  5. public name: string = "OimoJSPlugin";
  6. constructor(iterations?: number) {
  7. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  8. this.world.clear();
  9. //making sure no stats are calculated
  10. this.world.isNoStat = true;
  11. }
  12. public setGravity(gravity: Vector3) {
  13. this.world.gravity.copy(gravity);
  14. }
  15. private _tmpImpostorsArray: Array<PhysicsImpostor> = [];
  16. public executeStep(delta: number, impostors: Array<PhysicsImpostor>) {
  17. impostors.forEach(function(impostor) {
  18. impostor.beforeStep();
  19. });
  20. this.world.step();
  21. impostors.forEach((impostor) => {
  22. impostor.afterStep();
  23. //update the ordered impostors array
  24. this._tmpImpostorsArray[impostor.mesh.uniqueId] = impostor;
  25. });
  26. //check for collisions
  27. var contact = this.world.contacts;
  28. while (contact !== null) {
  29. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  30. contact = contact.next;
  31. continue;
  32. }
  33. //is this body colliding with any other? get the impostor
  34. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  35. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  36. if (!mainImpostor || !collidingImpostor) {
  37. contact = contact.next;
  38. continue;
  39. }
  40. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  41. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  42. contact = contact.next;
  43. }
  44. }
  45. public applyImpulse(impostor: PhysicsImpostor, force: Vector3, contactPoint: Vector3) {
  46. var mass = impostor.physicsBody.massInfo.mass;
  47. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  48. }
  49. public applyForce(impostor: PhysicsImpostor, force: Vector3, contactPoint: Vector3) {
  50. Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  51. this.applyImpulse(impostor, force, contactPoint);
  52. }
  53. public generatePhysicsBody(impostor: PhysicsImpostor) {
  54. //parent-child relationship. Does this impostor has a parent impostor?
  55. if (impostor.parent) {
  56. if (impostor.physicsBody) {
  57. this.removePhysicsBody(impostor);
  58. //TODO is that needed?
  59. impostor.forceUpdate();
  60. }
  61. return;
  62. }
  63. impostor.mesh.computeWorldMatrix(true);
  64. if (impostor.isBodyInitRequired()) {
  65. if (!impostor.mesh.rotationQuaternion) {
  66. impostor.mesh.rotationQuaternion = Quaternion.RotationYawPitchRoll(impostor.mesh.rotation.y, impostor.mesh.rotation.x, impostor.mesh.rotation.z);
  67. }
  68. var bodyConfig: any = {
  69. name: impostor.mesh.uniqueId,
  70. //Oimo must have mass, also for static objects.
  71. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  72. size: [],
  73. type: [],
  74. pos: [],
  75. rot: [],
  76. move: impostor.getParam("mass") !== 0,
  77. //Supporting older versions of Oimo
  78. world: this.world
  79. };
  80. var impostors = [impostor];
  81. function addToArray(parent: AbstractMesh) {
  82. parent.getChildMeshes().forEach(function(m) {
  83. if (m.physicsImpostor) {
  84. impostors.push(m.physicsImpostor);
  85. m.physicsImpostor._init();
  86. }
  87. addToArray(m);
  88. });
  89. }
  90. addToArray(impostor.mesh)
  91. function checkWithEpsilon(value: number): number {
  92. return Math.max(value, PhysicsEngine.Epsilon);
  93. }
  94. impostors.forEach((i) => {
  95. //get the correct bounding box
  96. var oldQuaternion = i.mesh.rotationQuaternion;
  97. var rot = new OIMO.Euler().setFromQuaternion({ x: impostor.mesh.rotationQuaternion.x, y: impostor.mesh.rotationQuaternion.y, z: impostor.mesh.rotationQuaternion.z, s: impostor.mesh.rotationQuaternion.w });
  98. i.mesh.rotationQuaternion = new Quaternion(0, 0, 0, 1);
  99. i.mesh.computeWorldMatrix(true);
  100. var bbox = i.mesh.getBoundingInfo().boundingBox;
  101. if (i === impostor) {
  102. impostor.mesh.position.subtractToRef(impostor.mesh.getBoundingInfo().boundingBox.center, this._tmpPositionVector);
  103. //Can also use Array.prototype.push.apply
  104. bodyConfig.pos.push(bbox.center.x);
  105. bodyConfig.pos.push(bbox.center.y);
  106. bodyConfig.pos.push(bbox.center.z);
  107. //tmp solution
  108. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  109. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  110. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  111. } else {
  112. bodyConfig.pos.push(i.mesh.position.x);
  113. bodyConfig.pos.push(i.mesh.position.y);
  114. bodyConfig.pos.push(i.mesh.position.z);
  115. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  116. bodyConfig.rot.push(0);
  117. bodyConfig.rot.push(0);
  118. bodyConfig.rot.push(0);
  119. }
  120. // register mesh
  121. switch (i.type) {
  122. case PhysicsEngine.SphereImpostor:
  123. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  124. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  125. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  126. var size = Math.max(
  127. checkWithEpsilon(radiusX),
  128. checkWithEpsilon(radiusY),
  129. checkWithEpsilon(radiusZ)) / 2;
  130. bodyConfig.type.push('sphere');
  131. //due to the way oimo works with compounds, add 3 times
  132. bodyConfig.size.push(size);
  133. bodyConfig.size.push(size);
  134. bodyConfig.size.push(size);
  135. break;
  136. case PhysicsEngine.PlaneImpostor:
  137. //TODO Oimo now supports cylinder!
  138. case PhysicsEngine.CylinderImpostor:
  139. case PhysicsEngine.BoxImpostor:
  140. default:
  141. var min = bbox.minimumWorld;
  142. var max = bbox.maximumWorld;
  143. var box = max.subtract(min);
  144. var sizeX = checkWithEpsilon(box.x);
  145. var sizeY = checkWithEpsilon(box.y);
  146. var sizeZ = checkWithEpsilon(box.z);
  147. bodyConfig.type.push('box');
  148. bodyConfig.size.push(sizeX);
  149. bodyConfig.size.push(sizeY);
  150. bodyConfig.size.push(sizeZ);
  151. break;
  152. }
  153. //actually not needed, but hey...
  154. i.mesh.rotationQuaternion = oldQuaternion;
  155. });
  156. impostor.physicsBody = new OIMO.Body(bodyConfig).body//this.world.add(bodyConfig);
  157. } else {
  158. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  159. }
  160. impostor.setDeltaPosition(this._tmpPositionVector);
  161. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  162. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  163. }
  164. private _tmpPositionVector: Vector3 = Vector3.Zero();
  165. public removePhysicsBody(impostor: PhysicsImpostor) {
  166. //impostor.physicsBody.dispose();
  167. //Same as : (older oimo versions)
  168. this.world.removeRigidBody(impostor.physicsBody);
  169. }
  170. public generateJoint(impostorJoint: PhysicsImpostorJoint) {
  171. var mainBody = impostorJoint.mainImpostor.physicsBody;
  172. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  173. if (!mainBody || !connectedBody) {
  174. return;
  175. }
  176. var jointData = impostorJoint.joint.jointData;
  177. var options = jointData.nativeParams || {};
  178. var type;
  179. var nativeJointData: any = {
  180. body1: mainBody,
  181. body2: connectedBody,
  182. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  183. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  184. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  185. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  186. min: options.min,
  187. max: options.max,
  188. collision: options.collision || jointData.collision,
  189. spring: options.spring,
  190. //supporting older version of Oimo
  191. world: this.world
  192. }
  193. switch (impostorJoint.joint.type) {
  194. case PhysicsJoint.BallAndSocketJoint:
  195. type = "jointBall";
  196. break;
  197. case PhysicsJoint.DistanceJoint:
  198. type = "jointDistance";
  199. nativeJointData.max = (<DistanceJointData>jointData).maxDistance
  200. break;
  201. case PhysicsJoint.PrismaticJoint:
  202. type = "jointPrisme";
  203. break;
  204. case PhysicsJoint.SliderJoint:
  205. type = "jointSlide";
  206. break;
  207. case PhysicsJoint.WheelJoint:
  208. type = "jointWheel";
  209. break;
  210. case PhysicsJoint.HingeJoint:
  211. default:
  212. type = "jointHinge";
  213. break;
  214. }
  215. nativeJointData.type = type;
  216. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint//this.world.add(nativeJointData);
  217. }
  218. public removeJoint(joint: PhysicsImpostorJoint) {
  219. joint.joint.physicsJoint.dispose();
  220. }
  221. public isSupported(): boolean {
  222. return OIMO !== undefined;
  223. }
  224. public setTransformationFromPhysicsBody(impostor: PhysicsImpostor) {
  225. if (!impostor.physicsBody.sleeping) {
  226. //TODO check that
  227. if (impostor.physicsBody.shapes.next) {
  228. var parentShape = this._getLastShape(impostor.physicsBody);
  229. impostor.mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  230. impostor.mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  231. impostor.mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  232. } else {
  233. impostor.mesh.position.copyFrom(impostor.physicsBody.getPosition());
  234. }
  235. impostor.mesh.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  236. }
  237. }
  238. public setPhysicsBodyTransformation(impostor: PhysicsImpostor, newPosition: Vector3, newRotation: Quaternion) {
  239. var body = impostor.physicsBody;
  240. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  241. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  242. body.syncShapes();
  243. body.awake();
  244. }
  245. private _getLastShape(body: any): any {
  246. var lastShape = body.shapes;
  247. while (lastShape.next) {
  248. lastShape = lastShape.next;
  249. }
  250. return lastShape;
  251. }
  252. public setVelocity(impostor: PhysicsImpostor, velocity: Vector3) {
  253. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  254. }
  255. public dispose() {
  256. this.world.clear();
  257. }
  258. }
  259. }