babylon.transformNode.ts 40 KB

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