oimoJSPlugin.ts 20 KB

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