babylon.transformNode.ts 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983
  1. module BABYLON {
  2. export class TransformNode extends Node {
  3. // Statics
  4. public static BILLBOARDMODE_NONE = 0;
  5. public static BILLBOARDMODE_X = 1;
  6. public static BILLBOARDMODE_Y = 2;
  7. public static BILLBOARDMODE_Z = 4;
  8. public static BILLBOARDMODE_ALL = 7;
  9. // Properties
  10. @serializeAsVector3()
  11. private _rotation = Vector3.Zero();
  12. @serializeAsQuaternion()
  13. private _rotationQuaternion: Nullable<Quaternion>;
  14. @serializeAsVector3()
  15. protected _scaling = Vector3.One();
  16. protected _isDirty = false;
  17. private _transformToBoneReferal: Nullable<TransformNode>;
  18. @serialize()
  19. public billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  20. @serialize()
  21. public scalingDeterminant = 1;
  22. @serialize()
  23. public infiniteDistance = false;
  24. @serializeAsVector3()
  25. public position = Vector3.Zero();
  26. // Cache
  27. public _poseMatrix: Matrix;
  28. private _localWorld = Matrix.Zero();
  29. public _worldMatrix = Matrix.Zero();
  30. public _worldMatrixDeterminant = 0;
  31. private _absolutePosition = Vector3.Zero();
  32. private _pivotMatrix = Matrix.Identity();
  33. private _pivotMatrixInverse: Matrix;
  34. private _postMultiplyPivotMatrix = false;
  35. protected _isWorldMatrixFrozen = false;
  36. /**
  37. * An event triggered after the world matrix is updated
  38. * @type {BABYLON.Observable}
  39. */
  40. public onAfterWorldMatrixUpdateObservable = new Observable<TransformNode>();
  41. constructor(name: string, scene: Nullable<Scene> = null, isPure = true) {
  42. super(name, scene);
  43. if (isPure) {
  44. this.getScene().addTransformNode(this);
  45. }
  46. }
  47. /**
  48. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  49. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  50. * Default : (0.0, 0.0, 0.0)
  51. */
  52. public get rotation(): Vector3 {
  53. return this._rotation;
  54. }
  55. public set rotation(newRotation: Vector3) {
  56. this._rotation = newRotation;
  57. }
  58. /**
  59. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  60. * Default : (1.0, 1.0, 1.0)
  61. */
  62. public get scaling(): Vector3 {
  63. return this._scaling;
  64. }
  65. /**
  66. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  67. * Default : (1.0, 1.0, 1.0)
  68. */
  69. public set scaling(newScaling: Vector3) {
  70. this._scaling = newScaling;
  71. }
  72. /**
  73. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  74. * It's null by default.
  75. * If set, only the rotationQuaternion is then used to compute the mesh rotation and its property `.rotation\ is then ignored and set to (0.0, 0.0, 0.0)
  76. */
  77. public get rotationQuaternion(): Nullable<Quaternion> {
  78. return this._rotationQuaternion;
  79. }
  80. public set rotationQuaternion(quaternion: Nullable<Quaternion>) {
  81. this._rotationQuaternion = quaternion;
  82. //reset the rotation vector.
  83. if (quaternion && this.rotation.length()) {
  84. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  85. }
  86. }
  87. /**
  88. * Returns the latest update of the World matrix
  89. * Returns a Matrix.
  90. */
  91. public getWorldMatrix(): Matrix {
  92. if (this._currentRenderId !== this.getScene().getRenderId()) {
  93. this.computeWorldMatrix();
  94. }
  95. return this._worldMatrix;
  96. }
  97. /**
  98. * Returns the latest update of the World matrix determinant.
  99. */
  100. protected _getWorldMatrixDeterminant(): number {
  101. return this._worldMatrixDeterminant;
  102. }
  103. /**
  104. * Returns directly the latest state of the mesh World matrix.
  105. * A Matrix is returned.
  106. */
  107. public get worldMatrixFromCache(): Matrix {
  108. return this._worldMatrix;
  109. }
  110. /**
  111. * Copies the paramater passed Matrix into the mesh Pose matrix.
  112. * Returns the AbstractMesh.
  113. */
  114. public updatePoseMatrix(matrix: Matrix): TransformNode {
  115. this._poseMatrix.copyFrom(matrix);
  116. return this;
  117. }
  118. /**
  119. * Returns the mesh Pose matrix.
  120. * Returned object : Matrix
  121. */
  122. public getPoseMatrix(): Matrix {
  123. return this._poseMatrix;
  124. }
  125. public _isSynchronized(): boolean {
  126. if (this._isDirty) {
  127. return false;
  128. }
  129. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  130. return false;
  131. if (this._cache.pivotMatrixUpdated) {
  132. return false;
  133. }
  134. if (this.infiniteDistance) {
  135. return false;
  136. }
  137. if (!this._cache.position.equals(this.position))
  138. return false;
  139. if (this.rotationQuaternion) {
  140. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  141. return false;
  142. }
  143. if (!this._cache.rotation.equals(this.rotation))
  144. return false;
  145. if (!this._cache.scaling.equals(this.scaling))
  146. return false;
  147. return true;
  148. }
  149. public _initCache() {
  150. super._initCache();
  151. this._cache.localMatrixUpdated = false;
  152. this._cache.position = Vector3.Zero();
  153. this._cache.scaling = Vector3.Zero();
  154. this._cache.rotation = Vector3.Zero();
  155. this._cache.rotationQuaternion = new Quaternion(0, 0, 0, 0);
  156. this._cache.billboardMode = -1;
  157. }
  158. public markAsDirty(property: string): TransformNode {
  159. if (property === "rotation") {
  160. this.rotationQuaternion = null;
  161. }
  162. this._currentRenderId = Number.MAX_VALUE;
  163. this._isDirty = true;
  164. return this;
  165. }
  166. /**
  167. * Returns the current mesh absolute position.
  168. * Retuns a Vector3.
  169. */
  170. public get absolutePosition(): Vector3 {
  171. return this._absolutePosition;
  172. }
  173. /**
  174. * Sets a new pivot matrix to the mesh.
  175. * Returns the AbstractMesh.
  176. */
  177. public setPivotMatrix(matrix: Matrix, postMultiplyPivotMatrix = false): TransformNode {
  178. this._pivotMatrix = matrix.clone();
  179. this._cache.pivotMatrixUpdated = true;
  180. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  181. if (this._postMultiplyPivotMatrix) {
  182. this._pivotMatrixInverse = Matrix.Invert(matrix);
  183. }
  184. return this;
  185. }
  186. /**
  187. * Returns the mesh pivot matrix.
  188. * Default : Identity.
  189. * A Matrix is returned.
  190. */
  191. public getPivotMatrix(): Matrix {
  192. return this._pivotMatrix;
  193. }
  194. /**
  195. * Prevents the World matrix to be computed any longer.
  196. * Returns the AbstractMesh.
  197. */
  198. public freezeWorldMatrix(): TransformNode {
  199. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  200. this.computeWorldMatrix(true);
  201. this._isWorldMatrixFrozen = true;
  202. return this;
  203. }
  204. /**
  205. * Allows back the World matrix computation.
  206. * Returns the AbstractMesh.
  207. */
  208. public unfreezeWorldMatrix() {
  209. this._isWorldMatrixFrozen = false;
  210. this.computeWorldMatrix(true);
  211. return this;
  212. }
  213. /**
  214. * True if the World matrix has been frozen.
  215. * Returns a boolean.
  216. */
  217. public get isWorldMatrixFrozen(): boolean {
  218. return this._isWorldMatrixFrozen;
  219. }
  220. /**
  221. * Retuns the mesh absolute position in the World.
  222. * Returns a Vector3.
  223. */
  224. public getAbsolutePosition(): Vector3 {
  225. this.computeWorldMatrix();
  226. return this._absolutePosition;
  227. }
  228. /**
  229. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  230. * Returns the AbstractMesh.
  231. */
  232. public setAbsolutePosition(absolutePosition: Vector3): TransformNode {
  233. if (!absolutePosition) {
  234. return this;
  235. }
  236. var absolutePositionX;
  237. var absolutePositionY;
  238. var absolutePositionZ;
  239. if (absolutePosition.x === undefined) {
  240. if (arguments.length < 3) {
  241. return this;
  242. }
  243. absolutePositionX = arguments[0];
  244. absolutePositionY = arguments[1];
  245. absolutePositionZ = arguments[2];
  246. }
  247. else {
  248. absolutePositionX = absolutePosition.x;
  249. absolutePositionY = absolutePosition.y;
  250. absolutePositionZ = absolutePosition.z;
  251. }
  252. if (this.parent) {
  253. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  254. invertParentWorldMatrix.invert();
  255. var worldPosition = new Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  256. this.position = Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  257. } else {
  258. this.position.x = absolutePositionX;
  259. this.position.y = absolutePositionY;
  260. this.position.z = absolutePositionZ;
  261. }
  262. return this;
  263. }
  264. /**
  265. * Sets the mesh position in its local space.
  266. * Returns the AbstractMesh.
  267. */
  268. public setPositionWithLocalVector(vector3: Vector3): TransformNode {
  269. this.computeWorldMatrix();
  270. this.position = Vector3.TransformNormal(vector3, this._localWorld);
  271. return this;
  272. }
  273. /**
  274. * Returns the mesh position in the local space from the current World matrix values.
  275. * Returns a new Vector3.
  276. */
  277. public getPositionExpressedInLocalSpace(): Vector3 {
  278. this.computeWorldMatrix();
  279. var invLocalWorldMatrix = this._localWorld.clone();
  280. invLocalWorldMatrix.invert();
  281. return Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  282. }
  283. /**
  284. * Translates the mesh along the passed Vector3 in its local space.
  285. * Returns the AbstractMesh.
  286. */
  287. public locallyTranslate(vector3: Vector3): TransformNode {
  288. this.computeWorldMatrix(true);
  289. this.position = Vector3.TransformCoordinates(vector3, this._localWorld);
  290. return this;
  291. }
  292. private static _lookAtVectorCache = new Vector3(0, 0, 0);
  293. /**
  294. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  295. * @param targetPoint the position (must be in same space as current mesh) to look at
  296. * @param yawCor optional yaw (y-axis) correction in radians
  297. * @param pitchCor optional pitch (x-axis) correction in radians
  298. * @param rollCor optional roll (z-axis) correction in radians
  299. * @param space the choosen space of the target
  300. * @returns the TransformNode.
  301. */
  302. public lookAt(targetPoint: Vector3, yawCor: number = 0, pitchCor: number = 0, rollCor: number = 0, space: Space = Space.LOCAL): TransformNode {
  303. var dv = AbstractMesh._lookAtVectorCache;
  304. var pos = space === Space.LOCAL ? this.position : this.getAbsolutePosition();
  305. targetPoint.subtractToRef(pos, dv);
  306. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  307. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  308. var pitch = Math.atan2(dv.y, len);
  309. if (this.rotationQuaternion) {
  310. Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  311. }
  312. else {
  313. this.rotation.x = pitch + pitchCor;
  314. this.rotation.y = yaw + yawCor;
  315. this.rotation.z = rollCor;
  316. }
  317. return this;
  318. }
  319. /**
  320. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  321. * This Vector3 is expressed in the World space.
  322. */
  323. public getDirection(localAxis: Vector3): Vector3 {
  324. var result = Vector3.Zero();
  325. this.getDirectionToRef(localAxis, result);
  326. return result;
  327. }
  328. /**
  329. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  330. * localAxis is expressed in the mesh local space.
  331. * result is computed in the Wordl space from the mesh World matrix.
  332. * Returns the AbstractMesh.
  333. */
  334. public getDirectionToRef(localAxis: Vector3, result: Vector3): TransformNode {
  335. Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  336. return this;
  337. }
  338. public setPivotPoint(point: Vector3, space: Space = Space.LOCAL): TransformNode {
  339. if (this.getScene().getRenderId() == 0) {
  340. this.computeWorldMatrix(true);
  341. }
  342. var wm = this.getWorldMatrix();
  343. if (space == Space.WORLD) {
  344. var tmat = Tmp.Matrix[0];
  345. wm.invertToRef(tmat);
  346. point = Vector3.TransformCoordinates(point, tmat);
  347. }
  348. Vector3.TransformCoordinatesToRef(point, wm, this.position);
  349. this._pivotMatrix.m[12] = -point.x;
  350. this._pivotMatrix.m[13] = -point.y;
  351. this._pivotMatrix.m[14] = -point.z;
  352. this._cache.pivotMatrixUpdated = true;
  353. return this;
  354. }
  355. /**
  356. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  357. */
  358. public getPivotPoint(): Vector3 {
  359. var point = Vector3.Zero();
  360. this.getPivotPointToRef(point);
  361. return point;
  362. }
  363. /**
  364. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  365. * Returns the AbstractMesh.
  366. */
  367. public getPivotPointToRef(result: Vector3): TransformNode {
  368. result.x = -this._pivotMatrix.m[12];
  369. result.y = -this._pivotMatrix.m[13];
  370. result.z = -this._pivotMatrix.m[14];
  371. return this;
  372. }
  373. /**
  374. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  375. */
  376. public getAbsolutePivotPoint(): Vector3 {
  377. var point = Vector3.Zero();
  378. this.getAbsolutePivotPointToRef(point);
  379. return point;
  380. }
  381. /**
  382. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  383. * Returns the AbstractMesh.
  384. */
  385. public getAbsolutePivotPointToRef(result: Vector3): TransformNode {
  386. result.x = this._pivotMatrix.m[12];
  387. result.y = this._pivotMatrix.m[13];
  388. result.z = this._pivotMatrix.m[14];
  389. this.getPivotPointToRef(result);
  390. Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  391. return this;
  392. }
  393. /**
  394. * Defines the passed node as the parent of the current node.
  395. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  396. * Returns the TransformNode.
  397. */
  398. public setParent(node: Nullable<Node>): TransformNode {
  399. if (node === null) {
  400. var rotation = Tmp.Quaternion[0];
  401. var position = Tmp.Vector3[0];
  402. var scale = Tmp.Vector3[1];
  403. if (this.parent && this.parent.computeWorldMatrix) {
  404. this.parent.computeWorldMatrix(true);
  405. }
  406. this.computeWorldMatrix(true);
  407. this.getWorldMatrix().decompose(scale, rotation, position);
  408. if (this.rotationQuaternion) {
  409. this.rotationQuaternion.copyFrom(rotation);
  410. } else {
  411. rotation.toEulerAnglesToRef(this.rotation);
  412. }
  413. this.scaling.x = scale.x;
  414. this.scaling.y = scale.y;
  415. this.scaling.z = scale.z;
  416. this.position.x = position.x;
  417. this.position.y = position.y;
  418. this.position.z = position.z;
  419. } else {
  420. var rotation = Tmp.Quaternion[0];
  421. var position = Tmp.Vector3[0];
  422. var scale = Tmp.Vector3[1];
  423. var diffMatrix = Tmp.Matrix[0];
  424. var invParentMatrix = Tmp.Matrix[1];
  425. this.computeWorldMatrix(true);
  426. node.computeWorldMatrix(true);
  427. node.getWorldMatrix().invertToRef(invParentMatrix);
  428. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  429. diffMatrix.decompose(scale, rotation, position);
  430. if (this.rotationQuaternion) {
  431. this.rotationQuaternion.copyFrom(rotation);
  432. } else {
  433. rotation.toEulerAnglesToRef(this.rotation);
  434. }
  435. this.position.x = position.x;
  436. this.position.y = position.y;
  437. this.position.z = position.z;
  438. this.scaling.x = scale.x;
  439. this.scaling.y = scale.y;
  440. this.scaling.z = scale.z;
  441. }
  442. this.parent = node;
  443. return this;
  444. }
  445. private _nonUniformScaling = false;
  446. public get nonUniformScaling(): boolean {
  447. return this._nonUniformScaling;
  448. }
  449. public _updateNonUniformScalingState(value: boolean): boolean {
  450. if (this._nonUniformScaling === value) {
  451. return false;
  452. }
  453. this._nonUniformScaling = true;
  454. return true;
  455. }
  456. /**
  457. * Attach the current TransformNode to another TransformNode associated with a bone
  458. * @param bone Bone affecting the TransformNode
  459. * @param affectedTransformNode TransformNode associated with the bone
  460. */
  461. public attachToBone(bone: Bone, affectedTransformNode: TransformNode): TransformNode {
  462. this._transformToBoneReferal = affectedTransformNode;
  463. this.parent = bone;
  464. if (bone.getWorldMatrix().determinant() < 0) {
  465. this.scalingDeterminant *= -1;
  466. }
  467. return this;
  468. }
  469. public detachFromBone(): TransformNode {
  470. if (!this.parent) {
  471. return this;
  472. }
  473. if (this.parent.getWorldMatrix().determinant() < 0) {
  474. this.scalingDeterminant *= -1;
  475. }
  476. this._transformToBoneReferal = null;
  477. this.parent = null;
  478. return this;
  479. }
  480. private static _rotationAxisCache = new Quaternion();
  481. /**
  482. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  483. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  484. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  485. * The passed axis is also normalized.
  486. * Returns the AbstractMesh.
  487. */
  488. public rotate(axis: Vector3, amount: number, space?: Space): TransformNode {
  489. axis.normalize();
  490. if (!this.rotationQuaternion) {
  491. this.rotationQuaternion = Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  492. this.rotation = Vector3.Zero();
  493. }
  494. var rotationQuaternion: Quaternion;
  495. if (!space || (space as any) === Space.LOCAL) {
  496. rotationQuaternion = Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  497. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  498. }
  499. else {
  500. if (this.parent) {
  501. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  502. invertParentWorldMatrix.invert();
  503. axis = Vector3.TransformNormal(axis, invertParentWorldMatrix);
  504. }
  505. rotationQuaternion = Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  506. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  507. }
  508. return this;
  509. }
  510. /**
  511. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  512. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  513. * The passed axis is also normalized.
  514. * Returns the AbstractMesh.
  515. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  516. */
  517. public rotateAround(point: Vector3, axis: Vector3, amount: number): TransformNode {
  518. axis.normalize();
  519. if (!this.rotationQuaternion) {
  520. this.rotationQuaternion = Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  521. this.rotation.copyFromFloats(0, 0, 0);
  522. }
  523. point.subtractToRef(this.position, Tmp.Vector3[0]);
  524. Matrix.TranslationToRef(Tmp.Vector3[0].x, Tmp.Vector3[0].y, Tmp.Vector3[0].z, Tmp.Matrix[0]);
  525. Tmp.Matrix[0].invertToRef(Tmp.Matrix[2]);
  526. Matrix.RotationAxisToRef(axis, amount, Tmp.Matrix[1]);
  527. Tmp.Matrix[2].multiplyToRef(Tmp.Matrix[1], Tmp.Matrix[2]);
  528. Tmp.Matrix[2].multiplyToRef(Tmp.Matrix[0], Tmp.Matrix[2]);
  529. Tmp.Matrix[2].decompose(Tmp.Vector3[0], Tmp.Quaternion[0], Tmp.Vector3[1]);
  530. this.position.addInPlace(Tmp.Vector3[1]);
  531. Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  532. return this;
  533. }
  534. /**
  535. * Translates the mesh along the axis vector for the passed distance in the given space.
  536. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  537. * Returns the AbstractMesh.
  538. */
  539. public translate(axis: Vector3, distance: number, space?: Space): TransformNode {
  540. var displacementVector = axis.scale(distance);
  541. if (!space || (space as any) === Space.LOCAL) {
  542. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  543. this.setPositionWithLocalVector(tempV3);
  544. }
  545. else {
  546. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  547. }
  548. return this;
  549. }
  550. /**
  551. * Adds a rotation step to the mesh current rotation.
  552. * x, y, z are Euler angles expressed in radians.
  553. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  554. * This means this rotation is made in the mesh local space only.
  555. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  556. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  557. * ```javascript
  558. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  559. * ```
  560. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  561. * Under the hood, only quaternions are used. So it's a little faster is you use .rotationQuaternion because it doesn't need to translate them back to Euler angles.
  562. * Returns the AbstractMesh.
  563. */
  564. public addRotation(x: number, y: number, z: number): TransformNode {
  565. var rotationQuaternion;
  566. if (this.rotationQuaternion) {
  567. rotationQuaternion = this.rotationQuaternion;
  568. }
  569. else {
  570. rotationQuaternion = Tmp.Quaternion[1];
  571. Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  572. }
  573. var accumulation = Tmp.Quaternion[0];
  574. Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  575. rotationQuaternion.multiplyInPlace(accumulation);
  576. if (!this.rotationQuaternion) {
  577. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  578. }
  579. return this;
  580. }
  581. /**
  582. * Computes the mesh World matrix and returns it.
  583. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  584. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  585. * If the parameter `force`is set to `true`, the actual computation is done.
  586. * Returns the mesh World Matrix.
  587. */
  588. public computeWorldMatrix(force?: boolean): Matrix {
  589. if (this._isWorldMatrixFrozen) {
  590. return this._worldMatrix;
  591. }
  592. if (!force && this.isSynchronized(true)) {
  593. return this._worldMatrix;
  594. }
  595. this._cache.position.copyFrom(this.position);
  596. this._cache.scaling.copyFrom(this.scaling);
  597. this._cache.pivotMatrixUpdated = false;
  598. this._cache.billboardMode = this.billboardMode;
  599. this._currentRenderId = this.getScene().getRenderId();
  600. this._isDirty = false;
  601. // Scaling
  602. Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, Tmp.Matrix[1]);
  603. // Rotation
  604. //rotate, if quaternion is set and rotation was used
  605. if (this.rotationQuaternion) {
  606. var len = this.rotation.length();
  607. if (len) {
  608. this.rotationQuaternion.multiplyInPlace(Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z))
  609. this.rotation.copyFromFloats(0, 0, 0);
  610. }
  611. }
  612. if (this.rotationQuaternion) {
  613. this.rotationQuaternion.toRotationMatrix(Tmp.Matrix[0]);
  614. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  615. } else {
  616. Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, Tmp.Matrix[0]);
  617. this._cache.rotation.copyFrom(this.rotation);
  618. }
  619. // Translation
  620. let camera = (<Camera>this.getScene().activeCamera);
  621. if (this.infiniteDistance && !this.parent && camera) {
  622. var cameraWorldMatrix = camera.getWorldMatrix();
  623. var cameraGlobalPosition = new Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  624. Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y,
  625. this.position.z + cameraGlobalPosition.z, Tmp.Matrix[2]);
  626. } else {
  627. Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, Tmp.Matrix[2]);
  628. }
  629. // Composing transformations
  630. this._pivotMatrix.multiplyToRef(Tmp.Matrix[1], Tmp.Matrix[4]);
  631. Tmp.Matrix[4].multiplyToRef(Tmp.Matrix[0], Tmp.Matrix[5]);
  632. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  633. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && camera) {
  634. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  635. // Need to decompose each rotation here
  636. var currentPosition = Tmp.Vector3[3];
  637. if (this.parent && this.parent.getWorldMatrix) {
  638. if (this._transformToBoneReferal) {
  639. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), Tmp.Matrix[6]);
  640. Vector3.TransformCoordinatesToRef(this.position, Tmp.Matrix[6], currentPosition);
  641. } else {
  642. Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  643. }
  644. } else {
  645. currentPosition.copyFrom(this.position);
  646. }
  647. currentPosition.subtractInPlace(camera.globalPosition);
  648. var finalEuler = Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  649. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_X) === AbstractMesh.BILLBOARDMODE_X) {
  650. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  651. }
  652. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Y) === AbstractMesh.BILLBOARDMODE_Y) {
  653. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  654. }
  655. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Z) === AbstractMesh.BILLBOARDMODE_Z) {
  656. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  657. }
  658. Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, Tmp.Matrix[0]);
  659. } else {
  660. Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  661. Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  662. Tmp.Matrix[1].invertToRef(Tmp.Matrix[0]);
  663. }
  664. Tmp.Matrix[1].copyFrom(Tmp.Matrix[5]);
  665. Tmp.Matrix[1].multiplyToRef(Tmp.Matrix[0], Tmp.Matrix[5]);
  666. }
  667. // Local world
  668. Tmp.Matrix[5].multiplyToRef(Tmp.Matrix[2], this._localWorld);
  669. // Parent
  670. if (this.parent && this.parent.getWorldMatrix) {
  671. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE) {
  672. if (this._transformToBoneReferal) {
  673. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), Tmp.Matrix[6]);
  674. Tmp.Matrix[5].copyFrom(Tmp.Matrix[6]);
  675. } else {
  676. Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  677. }
  678. this._localWorld.getTranslationToRef(Tmp.Vector3[5]);
  679. Vector3.TransformCoordinatesToRef(Tmp.Vector3[5], Tmp.Matrix[5], Tmp.Vector3[5]);
  680. this._worldMatrix.copyFrom(this._localWorld);
  681. this._worldMatrix.setTranslation(Tmp.Vector3[5]);
  682. } else {
  683. if (this._transformToBoneReferal) {
  684. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), Tmp.Matrix[6]);
  685. Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  686. } else {
  687. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  688. }
  689. }
  690. this._markSyncedWithParent();
  691. } else {
  692. this._worldMatrix.copyFrom(this._localWorld);
  693. }
  694. // Post multiply inverse of pivotMatrix
  695. if (this._postMultiplyPivotMatrix) {
  696. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  697. }
  698. // Normal matrix
  699. if (this.scaling.isNonUniform) {
  700. this._updateNonUniformScalingState(true);
  701. } else if (this.parent && (<TransformNode>this.parent)._nonUniformScaling) {
  702. this._updateNonUniformScalingState((<TransformNode>this.parent)._nonUniformScaling);
  703. } else {
  704. this._updateNonUniformScalingState(false);
  705. }
  706. this._afterComputeWorldMatrix();
  707. // Absolute position
  708. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  709. // Callbacks
  710. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  711. if (!this._poseMatrix) {
  712. this._poseMatrix = Matrix.Invert(this._worldMatrix);
  713. }
  714. // Cache the determinant
  715. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  716. return this._worldMatrix;
  717. }
  718. protected _afterComputeWorldMatrix(): void {
  719. }
  720. /**
  721. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  722. * @param func: callback function to add
  723. *
  724. * Returns the TransformNode.
  725. */
  726. public registerAfterWorldMatrixUpdate(func: (mesh: TransformNode) => void): TransformNode {
  727. this.onAfterWorldMatrixUpdateObservable.add(func);
  728. return this;
  729. }
  730. /**
  731. * Removes a registered callback function.
  732. * Returns the TransformNode.
  733. */
  734. public unregisterAfterWorldMatrixUpdate(func: (mesh: TransformNode) => void): TransformNode {
  735. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  736. return this;
  737. }
  738. /**
  739. * Clone the current transform node
  740. * Returns the new transform node
  741. * @param name Name of the new clone
  742. * @param newParent New parent for the clone
  743. * @param doNotCloneChildren Do not clone children hierarchy
  744. */
  745. public clone(name: string, newParent: Node, doNotCloneChildren?: boolean): Nullable<TransformNode> {
  746. var result = SerializationHelper.Clone(() => new TransformNode(name, this.getScene()), this);
  747. result.name = name;
  748. result.id = name;
  749. if (newParent) {
  750. result.parent = newParent;
  751. }
  752. if (!doNotCloneChildren) {
  753. // Children
  754. let directDescendants = this.getDescendants(true);
  755. for (let index = 0; index < directDescendants.length; index++) {
  756. var child = directDescendants[index];
  757. if ((<any>child).clone) {
  758. (<any>child).clone(name + "." + child.name, result);
  759. }
  760. }
  761. }
  762. return result;
  763. }
  764. public serialize(currentSerializationObject?: any): any {
  765. let serializationObject = SerializationHelper.Serialize(this, currentSerializationObject);
  766. serializationObject.type = this.getClassName();
  767. // Parent
  768. if (this.parent) {
  769. serializationObject.parentId = this.parent.id;
  770. }
  771. if (Tags && Tags.HasTags(this)) {
  772. serializationObject.tags = Tags.GetTags(this);
  773. }
  774. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  775. serializationObject.isEnabled = this.isEnabled();
  776. // Parent
  777. if (this.parent) {
  778. serializationObject.parentId = this.parent.id;
  779. }
  780. return serializationObject;
  781. }
  782. // Statics
  783. /**
  784. * Returns a new TransformNode object parsed from the source provided.
  785. * The parameter `parsedMesh` is the source.
  786. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  787. */
  788. public static Parse(parsedTransformNode: any, scene: Scene, rootUrl: string): TransformNode {
  789. var transformNode = SerializationHelper.Parse(() => new TransformNode(parsedTransformNode.name, scene), parsedTransformNode, scene, rootUrl);
  790. if (Tags) {
  791. Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  792. }
  793. if (parsedTransformNode.localMatrix) {
  794. transformNode.setPivotMatrix(Matrix.FromArray(parsedTransformNode.localMatrix));
  795. } else if (parsedTransformNode.pivotMatrix) {
  796. transformNode.setPivotMatrix(Matrix.FromArray(parsedTransformNode.pivotMatrix));
  797. }
  798. transformNode.setEnabled(parsedTransformNode.isEnabled);
  799. // Parent
  800. if (parsedTransformNode.parentId) {
  801. transformNode._waitingParentId = parsedTransformNode.parentId;
  802. }
  803. return transformNode;
  804. }
  805. /**
  806. * Disposes the TransformNode.
  807. * By default, all the children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  808. * Returns nothing.
  809. */
  810. public dispose(doNotRecurse?: boolean): void {
  811. // Animations
  812. this.getScene().stopAnimation(this);
  813. // Remove from scene
  814. this.getScene().removeTransformNode(this);
  815. if (!doNotRecurse) {
  816. // Children
  817. var objects = this.getDescendants(true);
  818. for (var index = 0; index < objects.length; index++) {
  819. objects[index].dispose();
  820. }
  821. } else {
  822. var childMeshes = this.getChildMeshes(true);
  823. for (index = 0; index < childMeshes.length; index++) {
  824. var child = childMeshes[index];
  825. child.parent = null;
  826. child.computeWorldMatrix(true);
  827. }
  828. }
  829. this.onAfterWorldMatrixUpdateObservable.clear();
  830. super.dispose();
  831. }
  832. }
  833. }