babylon.oimoJSPlugin.ts 14 KB

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