oimoJSPlugin.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  1. import { IPhysicsEnginePlugin, PhysicsImpostorJoint } from "../../Physics/IPhysicsEngine";
  2. import { PhysicsImpostor, IPhysicsEnabledObject } from "../../Physics/physicsImpostor";
  3. import { PhysicsJoint, IMotorEnabledJoint, DistanceJointData, SpringJointData } from "../../Physics/physicsJoint";
  4. import { PhysicsEngine } from "../../Physics/physicsEngine";
  5. import { AbstractMesh } from "../../Meshes/abstractMesh";
  6. import { Vector3, Quaternion } from "../../Maths/math.vector";
  7. import { Nullable } from "../../types";
  8. import { Logger } from "../../Misc/logger";
  9. import { PhysicsRaycastResult } from "../physicsRaycastResult";
  10. declare var OIMO: any;
  11. /** @hidden */
  12. export class OimoJSPlugin implements IPhysicsEnginePlugin {
  13. public world: any;
  14. public name: string = "OimoJSPlugin";
  15. public BJSOIMO: any;
  16. private _raycastResult: PhysicsRaycastResult;
  17. constructor(iterations?: number, oimoInjection = OIMO) {
  18. this.BJSOIMO = oimoInjection;
  19. this.world = new this.BJSOIMO.World({
  20. iterations: iterations
  21. });
  22. this.world.clear();
  23. this._raycastResult = new PhysicsRaycastResult();
  24. }
  25. public setGravity(gravity: Vector3) {
  26. this.world.gravity.copy(gravity);
  27. }
  28. public setTimeStep(timeStep: number) {
  29. this.world.timeStep = timeStep;
  30. }
  31. public getTimeStep(): number {
  32. return this.world.timeStep;
  33. }
  34. private _tmpImpostorsArray: Array<PhysicsImpostor> = [];
  35. public executeStep(delta: number, impostors: Array<PhysicsImpostor>) {
  36. impostors.forEach(function(impostor) {
  37. impostor.beforeStep();
  38. });
  39. this.world.step();
  40. impostors.forEach((impostor) => {
  41. impostor.afterStep();
  42. //update the ordered impostors array
  43. this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  44. });
  45. //check for collisions
  46. var contact = this.world.contacts;
  47. while (contact !== null) {
  48. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  49. contact = contact.next;
  50. continue;
  51. }
  52. //is this body colliding with any other? get the impostor
  53. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  54. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  55. if (!mainImpostor || !collidingImpostor) {
  56. contact = contact.next;
  57. continue;
  58. }
  59. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  60. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  61. contact = contact.next;
  62. }
  63. }
  64. public applyImpulse(impostor: PhysicsImpostor, force: Vector3, contactPoint: Vector3) {
  65. var mass = impostor.physicsBody.mass;
  66. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  67. }
  68. public applyForce(impostor: PhysicsImpostor, force: Vector3, contactPoint: Vector3) {
  69. Logger.Warn("Oimo doesn't support applying force. Using impule instead.");
  70. this.applyImpulse(impostor, force, contactPoint);
  71. }
  72. public generatePhysicsBody(impostor: PhysicsImpostor) {
  73. //parent-child relationship. Does this impostor has a parent impostor?
  74. if (impostor.parent) {
  75. if (impostor.physicsBody) {
  76. this.removePhysicsBody(impostor);
  77. //TODO is that needed?
  78. impostor.forceUpdate();
  79. }
  80. return;
  81. }
  82. if (impostor.isBodyInitRequired()) {
  83. var bodyConfig: any = {
  84. name: impostor.uniqueId,
  85. //Oimo must have mass, also for static objects.
  86. config: [impostor.getParam("mass") || 0.001, impostor.getParam("friction"), impostor.getParam("restitution")],
  87. size: [],
  88. type: [],
  89. pos: [],
  90. posShape: [],
  91. rot: [],
  92. rotShape: [],
  93. move: impostor.getParam("mass") !== 0,
  94. density: impostor.getParam("mass"),
  95. friction: impostor.getParam("friction"),
  96. restitution: impostor.getParam("restitution"),
  97. //Supporting older versions of Oimo
  98. world: this.world
  99. };
  100. var impostors = [impostor];
  101. let addToArray = (parent: IPhysicsEnabledObject) => {
  102. if (!parent.getChildMeshes) { return; }
  103. parent.getChildMeshes().forEach(function(m) {
  104. if (m.physicsImpostor) {
  105. impostors.push(m.physicsImpostor);
  106. //m.physicsImpostor._init();
  107. }
  108. });
  109. };
  110. addToArray(impostor.object);
  111. let checkWithEpsilon = (value: number): number => {
  112. return Math.max(value, PhysicsEngine.Epsilon);
  113. };
  114. let globalQuaternion: Quaternion = new Quaternion();
  115. impostors.forEach((i) => {
  116. if (!i.object.rotationQuaternion) {
  117. return;
  118. }
  119. //get the correct bounding box
  120. var oldQuaternion = i.object.rotationQuaternion;
  121. globalQuaternion = oldQuaternion.clone();
  122. i.object.rotationQuaternion.set(0, 0, 0, 1);
  123. i.object.computeWorldMatrix(true);
  124. var rot = oldQuaternion.toEulerAngles();
  125. var extendSize = i.getObjectExtendSize();
  126. const radToDeg = 57.295779513082320876;
  127. if (i === impostor) {
  128. var center = impostor.getObjectCenter();
  129. impostor.object.getAbsolutePivotPoint().subtractToRef(center, this._tmpPositionVector);
  130. this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  131. //Can also use Array.prototype.push.apply
  132. bodyConfig.pos.push(center.x);
  133. bodyConfig.pos.push(center.y);
  134. bodyConfig.pos.push(center.z);
  135. bodyConfig.posShape.push(0, 0, 0);
  136. bodyConfig.rotShape.push(0, 0, 0);
  137. } else {
  138. let localPosition = i.object.position.clone();
  139. bodyConfig.posShape.push(localPosition.x);
  140. bodyConfig.posShape.push(localPosition.y);
  141. bodyConfig.posShape.push(localPosition.z);
  142. // bodyConfig.pos.push(0, 0, 0);
  143. bodyConfig.rotShape.push(rot.x * radToDeg);
  144. bodyConfig.rotShape.push(rot.y * radToDeg);
  145. bodyConfig.rotShape.push(rot.z * radToDeg);
  146. }
  147. i.object.rotationQuaternion.copyFrom(globalQuaternion);
  148. // register mesh
  149. switch (i.type) {
  150. case PhysicsImpostor.ParticleImpostor:
  151. Logger.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  152. case PhysicsImpostor.SphereImpostor:
  153. var radiusX = extendSize.x;
  154. var radiusY = extendSize.y;
  155. var radiusZ = extendSize.z;
  156. var size = Math.max(
  157. checkWithEpsilon(radiusX),
  158. checkWithEpsilon(radiusY),
  159. checkWithEpsilon(radiusZ)) / 2;
  160. bodyConfig.type.push('sphere');
  161. //due to the way oimo works with compounds, add 3 times
  162. bodyConfig.size.push(size);
  163. bodyConfig.size.push(size);
  164. bodyConfig.size.push(size);
  165. break;
  166. case PhysicsImpostor.CylinderImpostor:
  167. var sizeX = checkWithEpsilon(extendSize.x) / 2;
  168. var sizeY = checkWithEpsilon(extendSize.y);
  169. bodyConfig.type.push('cylinder');
  170. bodyConfig.size.push(sizeX);
  171. bodyConfig.size.push(sizeY);
  172. //due to the way oimo works with compounds, add one more value.
  173. bodyConfig.size.push(sizeY);
  174. break;
  175. case PhysicsImpostor.PlaneImpostor:
  176. case PhysicsImpostor.BoxImpostor:
  177. default:
  178. var sizeX = checkWithEpsilon(extendSize.x);
  179. var sizeY = checkWithEpsilon(extendSize.y);
  180. var sizeZ = checkWithEpsilon(extendSize.z);
  181. bodyConfig.type.push('box');
  182. //if (i === impostor) {
  183. bodyConfig.size.push(sizeX);
  184. bodyConfig.size.push(sizeY);
  185. bodyConfig.size.push(sizeZ);
  186. //} else {
  187. // bodyConfig.size.push(0,0,0);
  188. //}
  189. break;
  190. }
  191. //actually not needed, but hey...
  192. i.object.rotationQuaternion = oldQuaternion;
  193. });
  194. impostor.physicsBody = this.world.add(bodyConfig);
  195. // set the quaternion, ignoring the previously defined (euler) rotation
  196. impostor.physicsBody.resetQuaternion(globalQuaternion);
  197. // update with delta 0, so the body will reveive the new rotation.
  198. impostor.physicsBody.updatePosition(0);
  199. } else {
  200. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  201. }
  202. impostor.setDeltaPosition(this._tmpPositionVector);
  203. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  204. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  205. }
  206. private _tmpPositionVector: Vector3 = Vector3.Zero();
  207. public removePhysicsBody(impostor: PhysicsImpostor) {
  208. //impostor.physicsBody.dispose();
  209. //Same as : (older oimo versions)
  210. this.world.removeRigidBody(impostor.physicsBody);
  211. }
  212. public generateJoint(impostorJoint: PhysicsImpostorJoint) {
  213. var mainBody = impostorJoint.mainImpostor.physicsBody;
  214. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  215. if (!mainBody || !connectedBody) {
  216. return;
  217. }
  218. var jointData = impostorJoint.joint.jointData;
  219. var options = jointData.nativeParams || {};
  220. var type;
  221. var nativeJointData: any = {
  222. body1: mainBody,
  223. body2: connectedBody,
  224. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  225. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  226. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  227. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  228. min: options.min,
  229. max: options.max,
  230. collision: options.collision || jointData.collision,
  231. spring: options.spring,
  232. //supporting older version of Oimo
  233. world: this.world
  234. };
  235. switch (impostorJoint.joint.type) {
  236. case PhysicsJoint.BallAndSocketJoint:
  237. type = "jointBall";
  238. break;
  239. case PhysicsJoint.SpringJoint:
  240. Logger.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  241. var springData = <SpringJointData>jointData;
  242. nativeJointData.min = springData.length || nativeJointData.min;
  243. //Max should also be set, just make sure it is at least min
  244. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  245. case PhysicsJoint.DistanceJoint:
  246. type = "jointDistance";
  247. nativeJointData.max = (<DistanceJointData>jointData).maxDistance;
  248. break;
  249. case PhysicsJoint.PrismaticJoint:
  250. type = "jointPrisme";
  251. break;
  252. case PhysicsJoint.SliderJoint:
  253. type = "jointSlide";
  254. break;
  255. case PhysicsJoint.WheelJoint:
  256. type = "jointWheel";
  257. break;
  258. case PhysicsJoint.HingeJoint:
  259. default:
  260. type = "jointHinge";
  261. break;
  262. }
  263. nativeJointData.type = type;
  264. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  265. }
  266. public removeJoint(impostorJoint: PhysicsImpostorJoint) {
  267. //Bug in Oimo prevents us from disposing a joint in the playground
  268. //joint.joint.physicsJoint.dispose();
  269. //So we will bruteforce it!
  270. try {
  271. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  272. } catch (e) {
  273. Logger.Warn(e);
  274. }
  275. }
  276. public isSupported(): boolean {
  277. return this.BJSOIMO !== undefined;
  278. }
  279. public setTransformationFromPhysicsBody(impostor: PhysicsImpostor) {
  280. if (!impostor.physicsBody.sleeping) {
  281. if (impostor.physicsBody.shapes.next) {
  282. let parent = impostor.physicsBody.shapes;
  283. while (parent.next) {
  284. parent = parent.next;
  285. }
  286. impostor.object.position.copyFrom(parent.position);
  287. } else {
  288. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  289. }
  290. //}
  291. if (impostor.object.rotationQuaternion) {
  292. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  293. }
  294. }
  295. }
  296. public setPhysicsBodyTransformation(impostor: PhysicsImpostor, newPosition: Vector3, newRotation: Quaternion) {
  297. var body = impostor.physicsBody;
  298. // disable bidirectional for compound meshes
  299. if (impostor.physicsBody.shapes.next) {
  300. return;
  301. }
  302. body.position.copy(newPosition);
  303. body.orientation.copy(newRotation);
  304. body.syncShapes();
  305. body.awake();
  306. }
  307. /*private _getLastShape(body: any): any {
  308. var lastShape = body.shapes;
  309. while (lastShape.next) {
  310. lastShape = lastShape.next;
  311. }
  312. return lastShape;
  313. }*/
  314. public setLinearVelocity(impostor: PhysicsImpostor, velocity: Vector3) {
  315. impostor.physicsBody.linearVelocity.copy(velocity);
  316. }
  317. public setAngularVelocity(impostor: PhysicsImpostor, velocity: Vector3) {
  318. impostor.physicsBody.angularVelocity.copy(velocity);
  319. }
  320. public getLinearVelocity(impostor: PhysicsImpostor): Nullable<Vector3> {
  321. var v = impostor.physicsBody.linearVelocity;
  322. if (!v) {
  323. return null;
  324. }
  325. return new Vector3(v.x, v.y, v.z);
  326. }
  327. public getAngularVelocity(impostor: PhysicsImpostor): Nullable<Vector3> {
  328. var v = impostor.physicsBody.angularVelocity;
  329. if (!v) {
  330. return null;
  331. }
  332. return new Vector3(v.x, v.y, v.z);
  333. }
  334. public setBodyMass(impostor: PhysicsImpostor, mass: number) {
  335. var staticBody: boolean = mass === 0;
  336. //this will actually set the body's density and not its mass.
  337. //But this is how oimo treats the mass variable.
  338. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  339. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  340. }
  341. public getBodyMass(impostor: PhysicsImpostor): number {
  342. return impostor.physicsBody.shapes.density;
  343. }
  344. public getBodyFriction(impostor: PhysicsImpostor): number {
  345. return impostor.physicsBody.shapes.friction;
  346. }
  347. public setBodyFriction(impostor: PhysicsImpostor, friction: number) {
  348. impostor.physicsBody.shapes.friction = friction;
  349. }
  350. public getBodyRestitution(impostor: PhysicsImpostor): number {
  351. return impostor.physicsBody.shapes.restitution;
  352. }
  353. public setBodyRestitution(impostor: PhysicsImpostor, restitution: number) {
  354. impostor.physicsBody.shapes.restitution = restitution;
  355. }
  356. public sleepBody(impostor: PhysicsImpostor) {
  357. impostor.physicsBody.sleep();
  358. }
  359. public wakeUpBody(impostor: PhysicsImpostor) {
  360. impostor.physicsBody.awake();
  361. }
  362. public updateDistanceJoint(joint: PhysicsJoint, maxDistance: number, minDistance?: number) {
  363. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  364. if (minDistance !== void 0) {
  365. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  366. }
  367. }
  368. public setMotor(joint: IMotorEnabledJoint, speed: number, force?: number, motorIndex?: number) {
  369. if (force !== undefined) {
  370. Logger.Warn("OimoJS plugin currently has unexpected behavior when using setMotor with force parameter");
  371. } else {
  372. force = 1e6;
  373. }
  374. speed *= -1;
  375. //TODO separate rotational and transational motors.
  376. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  377. if (motor) {
  378. motor.setMotor(speed, force);
  379. }
  380. }
  381. public setLimit(joint: IMotorEnabledJoint, upperLimit: number, lowerLimit?: number, motorIndex?: number) {
  382. //TODO separate rotational and transational motors.
  383. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  384. if (motor) {
  385. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  386. }
  387. }
  388. public syncMeshWithImpostor(mesh: AbstractMesh, impostor: PhysicsImpostor) {
  389. var body = impostor.physicsBody;
  390. mesh.position.x = body.position.x;
  391. mesh.position.y = body.position.y;
  392. mesh.position.z = body.position.z;
  393. if (mesh.rotationQuaternion) {
  394. mesh.rotationQuaternion.x = body.orientation.x;
  395. mesh.rotationQuaternion.y = body.orientation.y;
  396. mesh.rotationQuaternion.z = body.orientation.z;
  397. mesh.rotationQuaternion.w = body.orientation.s;
  398. }
  399. }
  400. public getRadius(impostor: PhysicsImpostor): number {
  401. return impostor.physicsBody.shapes.radius;
  402. }
  403. public getBoxSizeToRef(impostor: PhysicsImpostor, result: Vector3): void {
  404. var shape = impostor.physicsBody.shapes;
  405. result.x = shape.halfWidth * 2;
  406. result.y = shape.halfHeight * 2;
  407. result.z = shape.halfDepth * 2;
  408. }
  409. public dispose() {
  410. this.world.clear();
  411. }
  412. /**
  413. * Does a raycast in the physics world
  414. * @param from when should the ray start?
  415. * @param to when should the ray end?
  416. * @returns PhysicsRaycastResult
  417. */
  418. public raycast(from: Vector3, to: Vector3): PhysicsRaycastResult {
  419. Logger.Warn("raycast is not currently supported by the Oimo physics plugin");
  420. this._raycastResult.reset(from, to);
  421. return this._raycastResult;
  422. }
  423. }