babylon.physicsImpostor.ts 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711
  1. module BABYLON {
  2. export interface PhysicsImpostorParameters {
  3. mass: number;
  4. friction?: number;
  5. restitution?: number;
  6. nativeOptions?: any;
  7. ignoreParent?: boolean;
  8. disableBidirectionalTransformation?: boolean;
  9. }
  10. export interface IPhysicsEnabledObject {
  11. position: Vector3;
  12. rotationQuaternion: Nullable<Quaternion>;
  13. scaling: Vector3;
  14. rotation?: Vector3;
  15. parent?: any;
  16. getBoundingInfo(): BoundingInfo;
  17. computeWorldMatrix(force: boolean): Matrix;
  18. getWorldMatrix?(): Matrix;
  19. getChildMeshes?(directDescendantsOnly?: boolean): Array<AbstractMesh>;
  20. getVerticesData(kind: string): Nullable<Array<number> | Float32Array>;
  21. getIndices?(): Nullable<IndicesArray>;
  22. getScene?(): Scene;
  23. getAbsolutePosition(): Vector3;
  24. getAbsolutePivotPoint(): Vector3;
  25. rotate(axis: Vector3, amount: number, space?: Space): TransformNode;
  26. translate(axis: Vector3, distance: number, space?: Space): TransformNode;
  27. setAbsolutePosition(absolutePosition: Vector3): TransformNode;
  28. }
  29. export class PhysicsImpostor {
  30. public static DEFAULT_OBJECT_SIZE: Vector3 = new BABYLON.Vector3(1, 1, 1);
  31. public static IDENTITY_QUATERNION = Quaternion.Identity();
  32. private _physicsEngine: Nullable<PhysicsEngine>;
  33. //The native cannon/oimo/energy physics body object.
  34. private _physicsBody: any;
  35. private _bodyUpdateRequired: boolean = false;
  36. private _onBeforePhysicsStepCallbacks = new Array<(impostor: PhysicsImpostor) => void>();
  37. private _onAfterPhysicsStepCallbacks = new Array<(impostor: PhysicsImpostor) => void>();
  38. private _onPhysicsCollideCallbacks: Array<{ callback: (collider: PhysicsImpostor, collidedAgainst: PhysicsImpostor) => void, otherImpostors: Array<PhysicsImpostor> }> = []
  39. private _deltaPosition: Vector3 = Vector3.Zero();
  40. private _deltaRotation: Quaternion;
  41. private _deltaRotationConjugated: Quaternion;
  42. //If set, this is this impostor's parent
  43. private _parent: Nullable<PhysicsImpostor>;
  44. private _isDisposed = false;
  45. private static _tmpVecs: Vector3[] = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  46. private static _tmpQuat: Quaternion = Quaternion.Identity();
  47. get isDisposed(): boolean {
  48. return this._isDisposed;
  49. }
  50. get mass(): number {
  51. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  52. }
  53. set mass(value: number) {
  54. this.setMass(value);
  55. }
  56. get friction(): number {
  57. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  58. }
  59. set friction(value: number) {
  60. if (!this._physicsEngine) {
  61. return;
  62. }
  63. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  64. }
  65. get restitution(): number {
  66. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  67. }
  68. set restitution(value: number) {
  69. if (!this._physicsEngine) {
  70. return;
  71. }
  72. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  73. }
  74. //set by the physics engine when adding this impostor to the array.
  75. public uniqueId: number;
  76. private _joints: Array<{
  77. joint: PhysicsJoint,
  78. otherImpostor: PhysicsImpostor
  79. }>;
  80. constructor(public object: IPhysicsEnabledObject, public type: number, private _options: PhysicsImpostorParameters = { mass: 0 }, private _scene?: Scene) {
  81. //sanity check!
  82. if (!this.object) {
  83. Tools.Error("No object was provided. A physics object is obligatory");
  84. return;
  85. }
  86. //legacy support for old syntax.
  87. if (!this._scene && object.getScene) {
  88. this._scene = object.getScene()
  89. }
  90. if (!this._scene) {
  91. return;
  92. }
  93. this._physicsEngine = this._scene.getPhysicsEngine();
  94. if (!this._physicsEngine) {
  95. Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.")
  96. } else {
  97. //set the object's quaternion, if not set
  98. if (!this.object.rotationQuaternion) {
  99. if (this.object.rotation) {
  100. this.object.rotationQuaternion = Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  101. } else {
  102. this.object.rotationQuaternion = new Quaternion();
  103. }
  104. }
  105. //default options params
  106. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass
  107. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction
  108. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution
  109. this._joints = [];
  110. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  111. if (!this.object.parent || this._options.ignoreParent) {
  112. this._init();
  113. } else if (this.object.parent.physicsImpostor) {
  114. Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  115. }
  116. }
  117. }
  118. /**
  119. * This function will completly initialize this impostor.
  120. * It will create a new body - but only if this mesh has no parent.
  121. * If it has, this impostor will not be used other than to define the impostor
  122. * of the child mesh.
  123. */
  124. public _init() {
  125. if (!this._physicsEngine) {
  126. return;
  127. }
  128. this._physicsEngine.removeImpostor(this);
  129. this.physicsBody = null;
  130. this._parent = this._parent || this._getPhysicsParent();
  131. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  132. this._physicsEngine.addImpostor(this);
  133. }
  134. }
  135. private _getPhysicsParent(): Nullable<PhysicsImpostor> {
  136. if (this.object.parent instanceof AbstractMesh) {
  137. var parentMesh: AbstractMesh = <AbstractMesh>this.object.parent;
  138. return parentMesh.physicsImpostor;
  139. }
  140. return null;
  141. }
  142. /**
  143. * Should a new body be generated.
  144. */
  145. public isBodyInitRequired(): boolean {
  146. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  147. }
  148. public setScalingUpdated(updated: boolean) {
  149. this.forceUpdate();
  150. }
  151. /**
  152. * Force a regeneration of this or the parent's impostor's body.
  153. * Use under cautious - This will remove all joints already implemented.
  154. */
  155. public forceUpdate() {
  156. this._init();
  157. if (this.parent && !this._options.ignoreParent) {
  158. this.parent.forceUpdate();
  159. }
  160. }
  161. /*public get mesh(): AbstractMesh {
  162. return this._mesh;
  163. }*/
  164. /**
  165. * Gets the body that holds this impostor. Either its own, or its parent.
  166. */
  167. public get physicsBody(): any {
  168. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  169. }
  170. public get parent(): Nullable<PhysicsImpostor> {
  171. return !this._options.ignoreParent && this._parent ? this._parent : null;
  172. }
  173. public set parent(value: Nullable<PhysicsImpostor>) {
  174. this._parent = value;
  175. }
  176. /**
  177. * Set the physics body. Used mainly by the physics engine/plugin
  178. */
  179. public set physicsBody(physicsBody: any) {
  180. if (this._physicsBody && this._physicsEngine) {
  181. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  182. }
  183. this._physicsBody = physicsBody;
  184. this.resetUpdateFlags();
  185. }
  186. public resetUpdateFlags() {
  187. this._bodyUpdateRequired = false;
  188. }
  189. public getObjectExtendSize(): Vector3 {
  190. if (this.object.getBoundingInfo) {
  191. let q = this.object.rotationQuaternion;
  192. //reset rotation
  193. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  194. //calculate the world matrix with no rotation
  195. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  196. let boundingInfo = this.object.getBoundingInfo();
  197. let size = boundingInfo.boundingBox.extendSizeWorld.scale(2)
  198. //bring back the rotation
  199. this.object.rotationQuaternion = q;
  200. //calculate the world matrix with the new rotation
  201. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  202. return size;
  203. } else {
  204. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  205. }
  206. }
  207. public getObjectCenter(): Vector3 {
  208. if (this.object.getBoundingInfo) {
  209. let boundingInfo = this.object.getBoundingInfo();
  210. return boundingInfo.boundingBox.centerWorld;
  211. } else {
  212. return this.object.position;
  213. }
  214. }
  215. /**
  216. * Get a specific parametes from the options parameter.
  217. */
  218. public getParam(paramName: string) {
  219. return (<any>this._options)[paramName];
  220. }
  221. /**
  222. * Sets a specific parameter in the options given to the physics plugin
  223. */
  224. public setParam(paramName: string, value: number) {
  225. (<any>this._options)[paramName] = value;
  226. this._bodyUpdateRequired = true;
  227. }
  228. /**
  229. * Specifically change the body's mass option. Won't recreate the physics body object
  230. */
  231. public setMass(mass: number) {
  232. if (this.getParam("mass") !== mass) {
  233. this.setParam("mass", mass);
  234. }
  235. if (this._physicsEngine) {
  236. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  237. }
  238. }
  239. public getLinearVelocity(): Nullable<Vector3> {
  240. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : Vector3.Zero();
  241. }
  242. public setLinearVelocity(velocity: Nullable<Vector3>) {
  243. if (this._physicsEngine) {
  244. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  245. }
  246. }
  247. public getAngularVelocity(): Nullable<Vector3> {
  248. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : Vector3.Zero();
  249. }
  250. public setAngularVelocity(velocity: Nullable<Vector3>) {
  251. if (this._physicsEngine) {
  252. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  253. }
  254. }
  255. /**
  256. * Execute a function with the physics plugin native code.
  257. * Provide a function the will have two variables - the world object and the physics body object.
  258. */
  259. public executeNativeFunction(func: (world: any, physicsBody: any) => void) {
  260. if (this._physicsEngine) {
  261. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  262. }
  263. }
  264. /**
  265. * Register a function that will be executed before the physics world is stepping forward.
  266. */
  267. public registerBeforePhysicsStep(func: (impostor: PhysicsImpostor) => void): void {
  268. this._onBeforePhysicsStepCallbacks.push(func);
  269. }
  270. public unregisterBeforePhysicsStep(func: (impostor: PhysicsImpostor) => void): void {
  271. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  272. if (index > -1) {
  273. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  274. } else {
  275. Tools.Warn("Function to remove was not found");
  276. }
  277. }
  278. /**
  279. * Register a function that will be executed after the physics step
  280. */
  281. public registerAfterPhysicsStep(func: (impostor: PhysicsImpostor) => void): void {
  282. this._onAfterPhysicsStepCallbacks.push(func);
  283. }
  284. public unregisterAfterPhysicsStep(func: (impostor: PhysicsImpostor) => void): void {
  285. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  286. if (index > -1) {
  287. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  288. } else {
  289. Tools.Warn("Function to remove was not found");
  290. }
  291. }
  292. /**
  293. * register a function that will be executed when this impostor collides against a different body.
  294. */
  295. public registerOnPhysicsCollide(collideAgainst: PhysicsImpostor | Array<PhysicsImpostor>, func: (collider: PhysicsImpostor, collidedAgainst: PhysicsImpostor) => void): void {
  296. var collidedAgainstList: Array<PhysicsImpostor> = collideAgainst instanceof Array ? <Array<PhysicsImpostor>>collideAgainst : [<PhysicsImpostor>collideAgainst]
  297. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  298. }
  299. public unregisterOnPhysicsCollide(collideAgainst: PhysicsImpostor | Array<PhysicsImpostor>, func: (collider: PhysicsImpostor, collidedAgainst: PhysicsImpostor | Array<PhysicsImpostor>) => void): void {
  300. var collidedAgainstList: Array<PhysicsImpostor> = collideAgainst instanceof Array ? <Array<PhysicsImpostor>>collideAgainst : [<PhysicsImpostor>collideAgainst]
  301. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  302. if (index > -1) {
  303. this._onPhysicsCollideCallbacks.splice(index, 1);
  304. } else {
  305. Tools.Warn("Function to remove was not found");
  306. }
  307. }
  308. //temp variables for parent rotation calculations
  309. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  310. private _tmpQuat: Quaternion = new Quaternion();
  311. private _tmpQuat2: Quaternion = new Quaternion();
  312. public getParentsRotation() {
  313. let parent = this.object.parent;
  314. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  315. while (parent) {
  316. if (parent.rotationQuaternion) {
  317. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  318. } else {
  319. Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2)
  320. }
  321. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  322. parent = parent.parent;
  323. }
  324. return this._tmpQuat;
  325. }
  326. /**
  327. * this function is executed by the physics engine.
  328. */
  329. public beforeStep = () => {
  330. if (!this._physicsEngine) {
  331. return;
  332. }
  333. this.object.translate(this._deltaPosition, -1);
  334. this._deltaRotationConjugated && this.object.rotationQuaternion && this.object.rotationQuaternion.multiplyToRef(this._deltaRotationConjugated, this.object.rotationQuaternion);
  335. this.object.computeWorldMatrix(false);
  336. if (this.object.parent && this.object.rotationQuaternion) {
  337. this.getParentsRotation();
  338. this._tmpQuat.multiplyToRef(this.object.rotationQuaternion, this._tmpQuat);
  339. } else {
  340. this._tmpQuat.copyFrom(this.object.rotationQuaternion || new Quaternion());
  341. }
  342. if (!this._options.disableBidirectionalTransformation) {
  343. this.object.rotationQuaternion && this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(this, /*bInfo.boundingBox.centerWorld*/ this.object.getAbsolutePivotPoint(), this._tmpQuat);
  344. }
  345. this._onBeforePhysicsStepCallbacks.forEach((func) => {
  346. func(this);
  347. });
  348. }
  349. /**
  350. * this function is executed by the physics engine.
  351. */
  352. public afterStep = () => {
  353. if (!this._physicsEngine) {
  354. return;
  355. }
  356. this._onAfterPhysicsStepCallbacks.forEach((func) => {
  357. func(this);
  358. });
  359. this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(this);
  360. // object has now its world rotation. needs to be converted to local.
  361. if (this.object.parent && this.object.rotationQuaternion) {
  362. this.getParentsRotation();
  363. this._tmpQuat.conjugateInPlace();
  364. this._tmpQuat.multiplyToRef(this.object.rotationQuaternion, this.object.rotationQuaternion);
  365. }
  366. // take the position set and make it the absolute position of this object.
  367. this.object.setAbsolutePosition(this.object.position);
  368. this._deltaRotation && this.object.rotationQuaternion && this.object.rotationQuaternion.multiplyToRef(this._deltaRotation, this.object.rotationQuaternion);
  369. this.object.translate(this._deltaPosition, 1);
  370. }
  371. /**
  372. * Legacy collision detection event support
  373. */
  374. public onCollideEvent: Nullable<(collider: BABYLON.PhysicsImpostor, collidedWith: BABYLON.PhysicsImpostor) => void> = null;
  375. //event and body object due to cannon's event-based architecture.
  376. public onCollide = (e: { body: any }) => {
  377. if (!this._onPhysicsCollideCallbacks.length && !this.onCollideEvent) {
  378. return;
  379. }
  380. if (!this._physicsEngine) {
  381. return;
  382. }
  383. var otherImpostor = this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  384. if (otherImpostor) {
  385. // Legacy collision detection event support
  386. if (this.onCollideEvent) {
  387. this.onCollideEvent(this, otherImpostor);
  388. }
  389. this._onPhysicsCollideCallbacks.filter((obj) => {
  390. return obj.otherImpostors.indexOf((<PhysicsImpostor>otherImpostor)) !== -1
  391. }).forEach((obj) => {
  392. obj.callback(this, <PhysicsImpostor>otherImpostor);
  393. })
  394. }
  395. }
  396. /**
  397. * Apply a force
  398. */
  399. public applyForce(force: Vector3, contactPoint: Vector3): PhysicsImpostor {
  400. if (this._physicsEngine) {
  401. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  402. }
  403. return this;
  404. }
  405. /**
  406. * Apply an impulse
  407. */
  408. public applyImpulse(force: Vector3, contactPoint: Vector3): PhysicsImpostor {
  409. if (this._physicsEngine) {
  410. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  411. }
  412. return this;
  413. }
  414. /**
  415. * A help function to create a joint.
  416. */
  417. public createJoint(otherImpostor: PhysicsImpostor, jointType: number, jointData: PhysicsJointData): PhysicsImpostor {
  418. var joint = new PhysicsJoint(jointType, jointData);
  419. this.addJoint(otherImpostor, joint);
  420. return this;
  421. }
  422. /**
  423. * Add a joint to this impostor with a different impostor.
  424. */
  425. public addJoint(otherImpostor: PhysicsImpostor, joint: PhysicsJoint): PhysicsImpostor {
  426. this._joints.push({
  427. otherImpostor: otherImpostor,
  428. joint: joint
  429. });
  430. if (this._physicsEngine) {
  431. this._physicsEngine.addJoint(this, otherImpostor, joint);
  432. }
  433. return this;
  434. }
  435. /**
  436. * Will keep this body still, in a sleep mode.
  437. */
  438. public sleep(): PhysicsImpostor {
  439. if (this._physicsEngine) {
  440. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  441. }
  442. return this;
  443. }
  444. /**
  445. * Wake the body up.
  446. */
  447. public wakeUp(): PhysicsImpostor {
  448. if (this._physicsEngine) {
  449. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  450. }
  451. return this;
  452. }
  453. public clone(newObject: IPhysicsEnabledObject): Nullable<PhysicsImpostor> {
  454. if (!newObject) return null;
  455. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  456. }
  457. public dispose(/*disposeChildren: boolean = true*/) {
  458. //no dispose if no physics engine is available.
  459. if (!this._physicsEngine) {
  460. return;
  461. }
  462. this._joints.forEach((j) => {
  463. if (this._physicsEngine) {
  464. this._physicsEngine.removeJoint(this, j.otherImpostor, j.joint);
  465. }
  466. })
  467. //dispose the physics body
  468. this._physicsEngine.removeImpostor(this);
  469. if (this.parent) {
  470. this.parent.forceUpdate();
  471. } else {
  472. /*this._object.getChildMeshes().forEach(function(mesh) {
  473. if (mesh.physicsImpostor) {
  474. if (disposeChildren) {
  475. mesh.physicsImpostor.dispose();
  476. mesh.physicsImpostor = null;
  477. }
  478. }
  479. })*/
  480. }
  481. this._isDisposed = true;
  482. }
  483. public setDeltaPosition(position: Vector3) {
  484. this._deltaPosition.copyFrom(position);
  485. }
  486. public setDeltaRotation(rotation: Quaternion) {
  487. if (!this._deltaRotation) {
  488. this._deltaRotation = new Quaternion();
  489. }
  490. this._deltaRotation.copyFrom(rotation);
  491. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  492. }
  493. public getBoxSizeToRef(result: Vector3): PhysicsImpostor {
  494. if (this._physicsEngine) {
  495. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  496. }
  497. return this;
  498. }
  499. public getRadius(): number {
  500. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  501. }
  502. /**
  503. * Sync a bone with this impostor
  504. * @param bone The bone to sync to the impostor.
  505. * @param boneMesh The mesh that the bone is influencing.
  506. * @param jointPivot The pivot of the joint / bone in local space.
  507. * @param distToJoint Optional distance from the impostor to the joint.
  508. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  509. */
  510. public syncBoneWithImpostor(bone: Bone, boneMesh: AbstractMesh, jointPivot: Vector3, distToJoint?: number, adjustRotation?: Quaternion) {
  511. var tempVec = PhysicsImpostor._tmpVecs[0];
  512. var mesh = <AbstractMesh>this.object;
  513. if (mesh.rotationQuaternion) {
  514. if (adjustRotation) {
  515. var tempQuat = PhysicsImpostor._tmpQuat;
  516. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  517. bone.setRotationQuaternion(tempQuat, Space.WORLD, boneMesh);
  518. } else {
  519. bone.setRotationQuaternion(mesh.rotationQuaternion, Space.WORLD, boneMesh);
  520. }
  521. }
  522. tempVec.x = 0;
  523. tempVec.y = 0;
  524. tempVec.z = 0;
  525. if (jointPivot) {
  526. tempVec.x = jointPivot.x;
  527. tempVec.y = jointPivot.y;
  528. tempVec.z = jointPivot.z;
  529. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  530. if (distToJoint === undefined || distToJoint === null) {
  531. distToJoint = jointPivot.length();
  532. }
  533. tempVec.x *= distToJoint;
  534. tempVec.y *= distToJoint;
  535. tempVec.z *= distToJoint;
  536. }
  537. if (bone.getParent()) {
  538. tempVec.addInPlace(mesh.getAbsolutePosition());
  539. bone.setAbsolutePosition(tempVec, boneMesh);
  540. } else {
  541. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  542. boneMesh.position.x -= tempVec.x;
  543. boneMesh.position.y -= tempVec.y;
  544. boneMesh.position.z -= tempVec.z;
  545. }
  546. }
  547. /**
  548. * Sync impostor to a bone
  549. * @param bone The bone that the impostor will be synced to.
  550. * @param boneMesh The mesh that the bone is influencing.
  551. * @param jointPivot The pivot of the joint / bone in local space.
  552. * @param distToJoint Optional distance from the impostor to the joint.
  553. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  554. * @param boneAxis Optional vector3 axis the bone is aligned with
  555. */
  556. public syncImpostorWithBone(bone: Bone, boneMesh: AbstractMesh, jointPivot: Vector3, distToJoint?: number, adjustRotation?: Quaternion, boneAxis?: Vector3) {
  557. var mesh = <AbstractMesh>this.object;
  558. if (mesh.rotationQuaternion) {
  559. if (adjustRotation) {
  560. var tempQuat = PhysicsImpostor._tmpQuat;
  561. bone.getRotationQuaternionToRef(Space.WORLD, boneMesh, tempQuat);
  562. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  563. } else {
  564. bone.getRotationQuaternionToRef(Space.WORLD, boneMesh, mesh.rotationQuaternion);
  565. }
  566. }
  567. var pos = PhysicsImpostor._tmpVecs[0];
  568. var boneDir = PhysicsImpostor._tmpVecs[1];
  569. if (!boneAxis) {
  570. boneAxis = PhysicsImpostor._tmpVecs[2];
  571. boneAxis.x = 0;
  572. boneAxis.y = 1;
  573. boneAxis.z = 0;
  574. }
  575. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  576. bone.getAbsolutePositionToRef(boneMesh, pos);
  577. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  578. distToJoint = jointPivot.length();
  579. }
  580. if (distToJoint !== undefined && distToJoint !== null) {
  581. pos.x += boneDir.x * distToJoint;
  582. pos.y += boneDir.y * distToJoint;
  583. pos.z += boneDir.z * distToJoint;
  584. }
  585. mesh.setAbsolutePosition(pos);
  586. }
  587. //Impostor types
  588. public static NoImpostor = 0;
  589. public static SphereImpostor = 1;
  590. public static BoxImpostor = 2;
  591. public static PlaneImpostor = 3;
  592. public static MeshImpostor = 4;
  593. public static CylinderImpostor = 7;
  594. public static ParticleImpostor = 8;
  595. public static HeightmapImpostor = 9;
  596. }
  597. }