oimoJSPlugin.ts 20 KB

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