babylon.transformNode.ts 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162
  1. module BABYLON {
  2. /**
  3. * A TransformNode is an object that is not rendered but can be used as a center of transformation. This can decrease memory usage and increase rendering speed compared to using an empty mesh as a parent and is less complicated than using a pivot matrix.
  4. * @see https://doc.babylonjs.com/how_to/transformnode
  5. */
  6. export class TransformNode extends Node {
  7. // Statics
  8. /**
  9. * Object will not rotate to face the camera
  10. */
  11. public static BILLBOARDMODE_NONE = 0;
  12. /**
  13. * Object will rotate to face the camera but only on the x axis
  14. */
  15. public static BILLBOARDMODE_X = 1;
  16. /**
  17. * Object will rotate to face the camera but only on the y axis
  18. */
  19. public static BILLBOARDMODE_Y = 2;
  20. /**
  21. * Object will rotate to face the camera but only on the z axis
  22. */
  23. public static BILLBOARDMODE_Z = 4;
  24. /**
  25. * Object will rotate to face the camera
  26. */
  27. public static BILLBOARDMODE_ALL = 7;
  28. private _forward = new Vector3(0, 0, 1);
  29. private _forwardInverted = new Vector3(0, 0, -1);
  30. private _up = new Vector3(0, 1, 0);
  31. private _right = new Vector3(1, 0, 0);
  32. private _rightInverted = new Vector3(-1, 0, 0);
  33. // Properties
  34. @serializeAsVector3("position")
  35. private _position = Vector3.Zero();
  36. @serializeAsVector3("rotation")
  37. private _rotation = Vector3.Zero();
  38. @serializeAsQuaternion("rotationQuaternion")
  39. private _rotationQuaternion: Nullable<Quaternion>;
  40. @serializeAsVector3("scaling")
  41. protected _scaling = Vector3.One();
  42. protected _isDirty = false;
  43. private _transformToBoneReferal: Nullable<TransformNode>;
  44. /**
  45. * Set the billboard mode. Default is 0.
  46. *
  47. * | Value | Type | Description |
  48. * | --- | --- | --- |
  49. * | 0 | BILLBOARDMODE_NONE | |
  50. * | 1 | BILLBOARDMODE_X | |
  51. * | 2 | BILLBOARDMODE_Y | |
  52. * | 4 | BILLBOARDMODE_Z | |
  53. * | 7 | BILLBOARDMODE_ALL | |
  54. *
  55. */
  56. @serialize()
  57. public billboardMode = TransformNode.BILLBOARDMODE_NONE;
  58. /**
  59. * Multiplication factor on scale x/y/z when computing the world matrix. Eg. for a 1x1x1 cube setting this to 2 will make it a 2x2x2 cube
  60. */
  61. @serialize()
  62. public scalingDeterminant = 1;
  63. /**
  64. * Sets the distance of the object to max, often used by skybox
  65. */
  66. @serialize()
  67. public infiniteDistance = false;
  68. /**
  69. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  70. * By default the system will update normals to compensate
  71. */
  72. @serialize()
  73. public ignoreNonUniformScaling = false;
  74. // Cache
  75. /** @hidden */
  76. public _poseMatrix: Matrix;
  77. private _localWorld = Matrix.Zero();
  78. private _absolutePosition = Vector3.Zero();
  79. private _pivotMatrix = Matrix.Identity();
  80. private _pivotMatrixInverse: Matrix;
  81. protected _postMultiplyPivotMatrix = false;
  82. protected _isWorldMatrixFrozen = false;
  83. /** @hidden */
  84. public _indexInSceneTransformNodesArray = -1;
  85. /**
  86. * An event triggered after the world matrix is updated
  87. */
  88. public onAfterWorldMatrixUpdateObservable = new Observable<TransformNode>();
  89. constructor(name: string, scene: Nullable<Scene> = null, isPure = true) {
  90. super(name, scene);
  91. if (isPure) {
  92. this.getScene().addTransformNode(this);
  93. }
  94. }
  95. /**
  96. * Gets a string identifying the name of the class
  97. * @returns "TransformNode" string
  98. */
  99. public getClassName(): string {
  100. return "TransformNode";
  101. }
  102. /**
  103. * Gets or set the node position (default is (0.0, 0.0, 0.0))
  104. */
  105. public get position(): Vector3 {
  106. return this._position;
  107. }
  108. public set position(newPosition: Vector3) {
  109. this._position = newPosition;
  110. this._isDirty = true;
  111. }
  112. /**
  113. * Gets or sets the rotation property : a Vector3 defining the rotation value in radians around each local axis X, Y, Z (default is (0.0, 0.0, 0.0)).
  114. * If rotation quaternion is set, this Vector3 will be ignored and copy from the quaternion
  115. */
  116. public get rotation(): Vector3 {
  117. return this._rotation;
  118. }
  119. public set rotation(newRotation: Vector3) {
  120. this._rotation = newRotation;
  121. this._isDirty = true;
  122. }
  123. /**
  124. * Gets or sets the scaling property : a Vector3 defining the node scaling along each local axis X, Y, Z (default is (0.0, 0.0, 0.0)).
  125. */
  126. public get scaling(): Vector3 {
  127. return this._scaling;
  128. }
  129. public set scaling(newScaling: Vector3) {
  130. this._scaling = newScaling;
  131. this._isDirty = true;
  132. }
  133. /**
  134. * Gets or sets the rotation Quaternion property : this a Quaternion object defining the node rotation by using a unit quaternion (null by default).
  135. * If set, only the rotationQuaternion is then used to compute the node rotation (ie. node.rotation will be ignored)
  136. */
  137. public get rotationQuaternion(): Nullable<Quaternion> {
  138. return this._rotationQuaternion;
  139. }
  140. public set rotationQuaternion(quaternion: Nullable<Quaternion>) {
  141. this._rotationQuaternion = quaternion;
  142. //reset the rotation vector.
  143. if (quaternion) {
  144. this.rotation.setAll(0.0);
  145. }
  146. }
  147. /**
  148. * The forward direction of that transform in world space.
  149. */
  150. public get forward(): Vector3 {
  151. return Vector3.Normalize(Vector3.TransformNormal(
  152. this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward,
  153. this.getWorldMatrix()
  154. ));
  155. }
  156. /**
  157. * The up direction of that transform in world space.
  158. */
  159. public get up(): Vector3 {
  160. return Vector3.Normalize(Vector3.TransformNormal(
  161. this._up,
  162. this.getWorldMatrix()
  163. ));
  164. }
  165. /**
  166. * The right direction of that transform in world space.
  167. */
  168. public get right(): Vector3 {
  169. return Vector3.Normalize(Vector3.TransformNormal(
  170. this.getScene().useRightHandedSystem ? this._rightInverted : this._right,
  171. this.getWorldMatrix()
  172. ));
  173. }
  174. /**
  175. * Copies the parameter passed Matrix into the mesh Pose matrix.
  176. * @param matrix the matrix to copy the pose from
  177. * @returns this TransformNode.
  178. */
  179. public updatePoseMatrix(matrix: Matrix): TransformNode {
  180. this._poseMatrix.copyFrom(matrix);
  181. return this;
  182. }
  183. /**
  184. * Returns the mesh Pose matrix.
  185. * @returns the pose matrix
  186. */
  187. public getPoseMatrix(): Matrix {
  188. return this._poseMatrix;
  189. }
  190. /** @hidden */
  191. public _isSynchronized(): boolean {
  192. if (this._isDirty) {
  193. return false;
  194. }
  195. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  196. return false;
  197. }
  198. if (this._cache.pivotMatrixUpdated) {
  199. return false;
  200. }
  201. if (this.infiniteDistance) {
  202. return false;
  203. }
  204. if (!this._cache.position.equals(this._position)) {
  205. return false;
  206. }
  207. if (this._rotationQuaternion) {
  208. if (!this._cache.rotationQuaternion.equals(this._rotationQuaternion)) {
  209. return false;
  210. }
  211. }
  212. if (!this._cache.rotation.equals(this._rotation)) {
  213. return false;
  214. }
  215. if (!this._cache.scaling.equals(this._scaling)) {
  216. return false;
  217. }
  218. return true;
  219. }
  220. /** @hidden */
  221. public _initCache() {
  222. super._initCache();
  223. this._cache.localMatrixUpdated = false;
  224. this._cache.position = Vector3.Zero();
  225. this._cache.scaling = Vector3.Zero();
  226. this._cache.rotation = Vector3.Zero();
  227. this._cache.rotationQuaternion = new Quaternion(0, 0, 0, 0);
  228. this._cache.billboardMode = -1;
  229. }
  230. /**
  231. * Flag the transform node as dirty (Forcing it to update everything)
  232. * @param property if set to "rotation" the objects rotationQuaternion will be set to null
  233. * @returns this transform node
  234. */
  235. public markAsDirty(property: string): TransformNode {
  236. if (property === "rotation") {
  237. this.rotationQuaternion = null;
  238. }
  239. this._currentRenderId = Number.MAX_VALUE;
  240. this._isDirty = true;
  241. return this;
  242. }
  243. /**
  244. * Returns the current mesh absolute position.
  245. * Returns a Vector3.
  246. */
  247. public get absolutePosition(): Vector3 {
  248. return this._absolutePosition;
  249. }
  250. /**
  251. * Sets a new matrix to apply before all other transformation
  252. * @param matrix defines the transform matrix
  253. * @returns the current TransformNode
  254. */
  255. public setPreTransformMatrix(matrix: Matrix): TransformNode {
  256. return this.setPivotMatrix(matrix, false);
  257. }
  258. /**
  259. * Sets a new pivot matrix to the current node
  260. * @param matrix defines the new pivot matrix to use
  261. * @param postMultiplyPivotMatrix defines if the pivot matrix must be cancelled in the world matrix. When this parameter is set to true (default), the inverse of the pivot matrix is also applied at the end to cancel the transformation effect
  262. * @returns the current TransformNode
  263. */
  264. public setPivotMatrix(matrix: DeepImmutable<Matrix>, postMultiplyPivotMatrix = true): TransformNode {
  265. this._pivotMatrix.copyFrom(matrix);
  266. this._cache.pivotMatrixUpdated = true;
  267. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  268. if (this._postMultiplyPivotMatrix) {
  269. if (!this._pivotMatrixInverse) {
  270. this._pivotMatrixInverse = Matrix.Invert(this._pivotMatrix);
  271. } else {
  272. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  273. }
  274. }
  275. return this;
  276. }
  277. /**
  278. * Returns the mesh pivot matrix.
  279. * Default : Identity.
  280. * @returns the matrix
  281. */
  282. public getPivotMatrix(): Matrix {
  283. return this._pivotMatrix;
  284. }
  285. /**
  286. * Prevents the World matrix to be computed any longer.
  287. * @returns the TransformNode.
  288. */
  289. public freezeWorldMatrix(): TransformNode {
  290. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  291. this.computeWorldMatrix(true);
  292. this._isWorldMatrixFrozen = true;
  293. return this;
  294. }
  295. /**
  296. * Allows back the World matrix computation.
  297. * @returns the TransformNode.
  298. */
  299. public unfreezeWorldMatrix() {
  300. this._isWorldMatrixFrozen = false;
  301. this.computeWorldMatrix(true);
  302. return this;
  303. }
  304. /**
  305. * True if the World matrix has been frozen.
  306. */
  307. public get isWorldMatrixFrozen(): boolean {
  308. return this._isWorldMatrixFrozen;
  309. }
  310. /**
  311. * Retuns the mesh absolute position in the World.
  312. * @returns a Vector3.
  313. */
  314. public getAbsolutePosition(): Vector3 {
  315. this.computeWorldMatrix();
  316. return this._absolutePosition;
  317. }
  318. /**
  319. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  320. * @param absolutePosition the absolute position to set
  321. * @returns the TransformNode.
  322. */
  323. public setAbsolutePosition(absolutePosition: Vector3): TransformNode {
  324. if (!absolutePosition) {
  325. return this;
  326. }
  327. var absolutePositionX;
  328. var absolutePositionY;
  329. var absolutePositionZ;
  330. if (absolutePosition.x === undefined) {
  331. if (arguments.length < 3) {
  332. return this;
  333. }
  334. absolutePositionX = arguments[0];
  335. absolutePositionY = arguments[1];
  336. absolutePositionZ = arguments[2];
  337. }
  338. else {
  339. absolutePositionX = absolutePosition.x;
  340. absolutePositionY = absolutePosition.y;
  341. absolutePositionZ = absolutePosition.z;
  342. }
  343. if (this.parent) {
  344. const invertParentWorldMatrix = Tmp.Matrix[0];
  345. this.parent.getWorldMatrix().invertToRef(invertParentWorldMatrix);
  346. Vector3.TransformCoordinatesFromFloatsToRef(absolutePositionX, absolutePositionY, absolutePositionZ, invertParentWorldMatrix, this.position);
  347. } else {
  348. this.position.x = absolutePositionX;
  349. this.position.y = absolutePositionY;
  350. this.position.z = absolutePositionZ;
  351. }
  352. return this;
  353. }
  354. /**
  355. * Sets the mesh position in its local space.
  356. * @param vector3 the position to set in localspace
  357. * @returns the TransformNode.
  358. */
  359. public setPositionWithLocalVector(vector3: Vector3): TransformNode {
  360. this.computeWorldMatrix();
  361. this.position = Vector3.TransformNormal(vector3, this._localWorld);
  362. return this;
  363. }
  364. /**
  365. * Returns the mesh position in the local space from the current World matrix values.
  366. * @returns a new Vector3.
  367. */
  368. public getPositionExpressedInLocalSpace(): Vector3 {
  369. this.computeWorldMatrix();
  370. const invLocalWorldMatrix = Tmp.Matrix[0];
  371. this._localWorld.invertToRef(invLocalWorldMatrix);
  372. return Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  373. }
  374. /**
  375. * Translates the mesh along the passed Vector3 in its local space.
  376. * @param vector3 the distance to translate in localspace
  377. * @returns the TransformNode.
  378. */
  379. public locallyTranslate(vector3: Vector3): TransformNode {
  380. this.computeWorldMatrix(true);
  381. this.position = Vector3.TransformCoordinates(vector3, this._localWorld);
  382. return this;
  383. }
  384. private static _lookAtVectorCache = new Vector3(0, 0, 0);
  385. /**
  386. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  387. * @param targetPoint the position (must be in same space as current mesh) to look at
  388. * @param yawCor optional yaw (y-axis) correction in radians
  389. * @param pitchCor optional pitch (x-axis) correction in radians
  390. * @param rollCor optional roll (z-axis) correction in radians
  391. * @param space the choosen space of the target
  392. * @returns the TransformNode.
  393. */
  394. public lookAt(targetPoint: Vector3, yawCor: number = 0, pitchCor: number = 0, rollCor: number = 0, space: Space = Space.LOCAL): TransformNode {
  395. var dv = TransformNode._lookAtVectorCache;
  396. var pos = space === Space.LOCAL ? this.position : this.getAbsolutePosition();
  397. targetPoint.subtractToRef(pos, dv);
  398. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  399. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  400. var pitch = Math.atan2(dv.y, len);
  401. if (this.rotationQuaternion) {
  402. Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  403. }
  404. else {
  405. this.rotation.x = pitch + pitchCor;
  406. this.rotation.y = yaw + yawCor;
  407. this.rotation.z = rollCor;
  408. }
  409. // Correct for parent's rotation offset
  410. if (space === Space.WORLD && this.parent) {
  411. if (this.rotationQuaternion) {
  412. // Get local rotation matrix of the looking object
  413. var rotationMatrix = Tmp.Matrix[0];
  414. this.rotationQuaternion.toRotationMatrix(rotationMatrix);
  415. // Offset rotation by parent's inverted rotation matrix to correct in world space
  416. var parentRotationMatrix = Tmp.Matrix[1];
  417. this.parent.getWorldMatrix().getRotationMatrixToRef(parentRotationMatrix);
  418. parentRotationMatrix.invert();
  419. rotationMatrix.multiplyToRef(parentRotationMatrix, rotationMatrix);
  420. this.rotationQuaternion.fromRotationMatrix(rotationMatrix);
  421. }else {
  422. // Get local rotation matrix of the looking object
  423. var quaternionRotation = Tmp.Quaternion[0];
  424. Quaternion.FromEulerVectorToRef(this.rotation, quaternionRotation);
  425. var rotationMatrix = Tmp.Matrix[0];
  426. quaternionRotation.toRotationMatrix(rotationMatrix);
  427. // Offset rotation by parent's inverted rotation matrix to correct in world space
  428. var parentRotationMatrix = Tmp.Matrix[1];
  429. this.parent.getWorldMatrix().getRotationMatrixToRef(parentRotationMatrix);
  430. parentRotationMatrix.invert();
  431. rotationMatrix.multiplyToRef(parentRotationMatrix, rotationMatrix);
  432. quaternionRotation.fromRotationMatrix(rotationMatrix);
  433. quaternionRotation.toEulerAnglesToRef(this.rotation);
  434. }
  435. }
  436. return this;
  437. }
  438. /**
  439. * Returns a new Vector3 that is the localAxis, expressed in the mesh local space, rotated like the mesh.
  440. * This Vector3 is expressed in the World space.
  441. * @param localAxis axis to rotate
  442. * @returns a new Vector3 that is the localAxis, expressed in the mesh local space, rotated like the mesh.
  443. */
  444. public getDirection(localAxis: Vector3): Vector3 {
  445. var result = Vector3.Zero();
  446. this.getDirectionToRef(localAxis, result);
  447. return result;
  448. }
  449. /**
  450. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  451. * localAxis is expressed in the mesh local space.
  452. * result is computed in the Wordl space from the mesh World matrix.
  453. * @param localAxis axis to rotate
  454. * @param result the resulting transformnode
  455. * @returns this TransformNode.
  456. */
  457. public getDirectionToRef(localAxis: Vector3, result: Vector3): TransformNode {
  458. Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  459. return this;
  460. }
  461. /**
  462. * Sets a new pivot point to the current node
  463. * @param point defines the new pivot point to use
  464. * @param space defines if the point is in world or local space (local by default)
  465. * @returns the current TransformNode
  466. */
  467. public setPivotPoint(point: Vector3, space: Space = Space.LOCAL): TransformNode {
  468. if (this.getScene().getRenderId() == 0) {
  469. this.computeWorldMatrix(true);
  470. }
  471. var wm = this.getWorldMatrix();
  472. if (space == Space.WORLD) {
  473. var tmat = Tmp.Matrix[0];
  474. wm.invertToRef(tmat);
  475. point = Vector3.TransformCoordinates(point, tmat);
  476. }
  477. return this.setPivotMatrix(Matrix.Translation(-point.x, -point.y, -point.z), true);
  478. }
  479. /**
  480. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  481. * @returns the pivot point
  482. */
  483. public getPivotPoint(): Vector3 {
  484. var point = Vector3.Zero();
  485. this.getPivotPointToRef(point);
  486. return point;
  487. }
  488. /**
  489. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  490. * @param result the vector3 to store the result
  491. * @returns this TransformNode.
  492. */
  493. public getPivotPointToRef(result: Vector3): TransformNode {
  494. result.x = -this._pivotMatrix.m[12];
  495. result.y = -this._pivotMatrix.m[13];
  496. result.z = -this._pivotMatrix.m[14];
  497. return this;
  498. }
  499. /**
  500. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  501. * @returns a new Vector3 set with the mesh pivot point World coordinates.
  502. */
  503. public getAbsolutePivotPoint(): Vector3 {
  504. var point = Vector3.Zero();
  505. this.getAbsolutePivotPointToRef(point);
  506. return point;
  507. }
  508. /**
  509. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  510. * @param result vector3 to store the result
  511. * @returns this TransformNode.
  512. */
  513. public getAbsolutePivotPointToRef(result: Vector3): TransformNode {
  514. result.x = this._pivotMatrix.m[12];
  515. result.y = this._pivotMatrix.m[13];
  516. result.z = this._pivotMatrix.m[14];
  517. this.getPivotPointToRef(result);
  518. Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  519. return this;
  520. }
  521. /**
  522. * Defines the passed node as the parent of the current node.
  523. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  524. * @param node the node ot set as the parent
  525. * @returns this TransformNode.
  526. */
  527. public setParent(node: Nullable<Node>): TransformNode {
  528. if (!node && !this.parent) {
  529. return this;
  530. }
  531. var quatRotation = Tmp.Quaternion[0];
  532. var position = Tmp.Vector3[0];
  533. var scale = Tmp.Vector3[1];
  534. if (!node) {
  535. if (this.parent && this.parent.computeWorldMatrix) {
  536. this.parent.computeWorldMatrix(true);
  537. }
  538. this.computeWorldMatrix(true);
  539. this.getWorldMatrix().decompose(scale, quatRotation, position);
  540. } else {
  541. var diffMatrix = Tmp.Matrix[0];
  542. var invParentMatrix = Tmp.Matrix[1];
  543. this.computeWorldMatrix(true);
  544. node.computeWorldMatrix(true);
  545. node.getWorldMatrix().invertToRef(invParentMatrix);
  546. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  547. diffMatrix.decompose(scale, quatRotation, position);
  548. }
  549. if (this.rotationQuaternion) {
  550. this.rotationQuaternion.copyFrom(quatRotation);
  551. } else {
  552. quatRotation.toEulerAnglesToRef(this.rotation);
  553. }
  554. this.scaling.copyFrom(scale);
  555. this.position.copyFrom(position);
  556. this.parent = node;
  557. return this;
  558. }
  559. private _nonUniformScaling = false;
  560. /**
  561. * True if the scaling property of this object is non uniform eg. (1,2,1)
  562. */
  563. public get nonUniformScaling(): boolean {
  564. return this._nonUniformScaling;
  565. }
  566. /** @hidden */
  567. public _updateNonUniformScalingState(value: boolean): boolean {
  568. if (this._nonUniformScaling === value) {
  569. return false;
  570. }
  571. this._nonUniformScaling = value;
  572. return true;
  573. }
  574. /**
  575. * Attach the current TransformNode to another TransformNode associated with a bone
  576. * @param bone Bone affecting the TransformNode
  577. * @param affectedTransformNode TransformNode associated with the bone
  578. * @returns this object
  579. */
  580. public attachToBone(bone: Bone, affectedTransformNode: TransformNode): TransformNode {
  581. this._transformToBoneReferal = affectedTransformNode;
  582. this.parent = bone;
  583. if (bone.getWorldMatrix().determinant() < 0) {
  584. this.scalingDeterminant *= -1;
  585. }
  586. return this;
  587. }
  588. /**
  589. * Detach the transform node if its associated with a bone
  590. * @returns this object
  591. */
  592. public detachFromBone(): TransformNode {
  593. if (!this.parent) {
  594. return this;
  595. }
  596. if (this.parent.getWorldMatrix().determinant() < 0) {
  597. this.scalingDeterminant *= -1;
  598. }
  599. this._transformToBoneReferal = null;
  600. this.parent = null;
  601. return this;
  602. }
  603. private static _rotationAxisCache = new Quaternion();
  604. /**
  605. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  606. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  607. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  608. * The passed axis is also normalized.
  609. * @param axis the axis to rotate around
  610. * @param amount the amount to rotate in radians
  611. * @param space Space to rotate in (Default: local)
  612. * @returns the TransformNode.
  613. */
  614. public rotate(axis: Vector3, amount: number, space?: Space): TransformNode {
  615. axis.normalize();
  616. if (!this.rotationQuaternion) {
  617. this.rotationQuaternion = this.rotation.toQuaternion();
  618. this.rotation.setAll(0);
  619. }
  620. var rotationQuaternion: Quaternion;
  621. if (!space || (space as any) === Space.LOCAL) {
  622. rotationQuaternion = Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  623. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  624. }
  625. else {
  626. if (this.parent) {
  627. const invertParentWorldMatrix = Tmp.Matrix[0];
  628. this.parent.getWorldMatrix().invertToRef(invertParentWorldMatrix);
  629. axis = Vector3.TransformNormal(axis, invertParentWorldMatrix);
  630. }
  631. rotationQuaternion = Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  632. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  633. }
  634. return this;
  635. }
  636. /**
  637. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  638. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  639. * The passed axis is also normalized. .
  640. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  641. * @param point the point to rotate around
  642. * @param axis the axis to rotate around
  643. * @param amount the amount to rotate in radians
  644. * @returns the TransformNode
  645. */
  646. public rotateAround(point: Vector3, axis: Vector3, amount: number): TransformNode {
  647. axis.normalize();
  648. if (!this.rotationQuaternion) {
  649. this.rotationQuaternion = Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  650. this.rotation.setAll(0);
  651. }
  652. const tmpVector = Tmp.Vector3[0];
  653. const finalScale = Tmp.Vector3[1];
  654. const finalTranslation = Tmp.Vector3[2];
  655. const finalRotation = Tmp.Quaternion[0];
  656. const translationMatrix = Tmp.Matrix[0]; // T
  657. const translationMatrixInv = Tmp.Matrix[1]; // T'
  658. const rotationMatrix = Tmp.Matrix[2]; // R
  659. const finalMatrix = Tmp.Matrix[3]; // T' x R x T
  660. point.subtractToRef(this.position, tmpVector);
  661. Matrix.TranslationToRef(tmpVector.x, tmpVector.y, tmpVector.z, translationMatrix); // T
  662. Matrix.TranslationToRef(-tmpVector.x, -tmpVector.y, -tmpVector.z, translationMatrixInv); // T'
  663. Matrix.RotationAxisToRef(axis, amount, rotationMatrix); // R
  664. translationMatrixInv.multiplyToRef(rotationMatrix, finalMatrix); // T' x R
  665. finalMatrix.multiplyToRef(translationMatrix, finalMatrix); // T' x R x T
  666. finalMatrix.decompose(finalScale, finalRotation, finalTranslation);
  667. this.position.addInPlace(finalTranslation);
  668. finalRotation.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  669. return this;
  670. }
  671. /**
  672. * Translates the mesh along the axis vector for the passed distance in the given space.
  673. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  674. * @param axis the axis to translate in
  675. * @param distance the distance to translate
  676. * @param space Space to rotate in (Default: local)
  677. * @returns the TransformNode.
  678. */
  679. public translate(axis: Vector3, distance: number, space?: Space): TransformNode {
  680. var displacementVector = axis.scale(distance);
  681. if (!space || (space as any) === Space.LOCAL) {
  682. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  683. this.setPositionWithLocalVector(tempV3);
  684. }
  685. else {
  686. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  687. }
  688. return this;
  689. }
  690. /**
  691. * Adds a rotation step to the mesh current rotation.
  692. * x, y, z are Euler angles expressed in radians.
  693. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  694. * This means this rotation is made in the mesh local space only.
  695. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  696. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  697. * ```javascript
  698. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  699. * ```
  700. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  701. * 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.
  702. * @param x Rotation to add
  703. * @param y Rotation to add
  704. * @param z Rotation to add
  705. * @returns the TransformNode.
  706. */
  707. public addRotation(x: number, y: number, z: number): TransformNode {
  708. var rotationQuaternion;
  709. if (this.rotationQuaternion) {
  710. rotationQuaternion = this.rotationQuaternion;
  711. }
  712. else {
  713. rotationQuaternion = Tmp.Quaternion[1];
  714. Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  715. }
  716. var accumulation = Tmp.Quaternion[0];
  717. Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  718. rotationQuaternion.multiplyInPlace(accumulation);
  719. if (!this.rotationQuaternion) {
  720. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  721. }
  722. return this;
  723. }
  724. /**
  725. * Computes the world matrix of the node
  726. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  727. * @returns the world matrix
  728. */
  729. public computeWorldMatrix(force?: boolean): Matrix {
  730. if (this._isWorldMatrixFrozen) {
  731. return this._worldMatrix;
  732. }
  733. if (!force && this.isSynchronized()) {
  734. this._currentRenderId = this.getScene().getRenderId();
  735. return this._worldMatrix;
  736. }
  737. this._updateCache();
  738. this._cache.position.copyFrom(this.position);
  739. this._cache.scaling.copyFrom(this.scaling);
  740. this._cache.pivotMatrixUpdated = false;
  741. this._cache.billboardMode = this.billboardMode;
  742. this._currentRenderId = this.getScene().getRenderId();
  743. this._childRenderId = this.getScene().getRenderId();
  744. this._isDirty = false;
  745. // Scaling
  746. Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, Tmp.Matrix[1]);
  747. // Rotation
  748. //rotate, if quaternion is set and rotation was used
  749. if (this.rotationQuaternion) {
  750. var len = this.rotation.length();
  751. if (len) {
  752. this.rotationQuaternion.multiplyInPlace(Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  753. this.rotation.copyFromFloats(0, 0, 0);
  754. }
  755. }
  756. if (this.rotationQuaternion) {
  757. this.rotationQuaternion.toRotationMatrix(Tmp.Matrix[0]);
  758. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  759. } else {
  760. Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, Tmp.Matrix[0]);
  761. this._cache.rotation.copyFrom(this.rotation);
  762. }
  763. // Translation
  764. let camera = (<Camera>this.getScene().activeCamera);
  765. if (this.infiniteDistance && !this.parent && camera) {
  766. var cameraWorldMatrix = camera.getWorldMatrix();
  767. var cameraGlobalPosition = new Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  768. Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y,
  769. this.position.z + cameraGlobalPosition.z, Tmp.Matrix[2]);
  770. } else {
  771. Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, Tmp.Matrix[2]);
  772. }
  773. // Composing transformations
  774. this._pivotMatrix.multiplyToRef(Tmp.Matrix[1], Tmp.Matrix[4]);
  775. Tmp.Matrix[4].multiplyToRef(Tmp.Matrix[0], Tmp.Matrix[5]);
  776. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  777. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  778. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  779. // Need to decompose each rotation here
  780. var currentPosition = Tmp.Vector3[3];
  781. if (this.parent && this.parent.getWorldMatrix) {
  782. if (this._transformToBoneReferal) {
  783. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), Tmp.Matrix[6]);
  784. Vector3.TransformCoordinatesToRef(this.position, Tmp.Matrix[6], currentPosition);
  785. } else {
  786. Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  787. }
  788. } else {
  789. currentPosition.copyFrom(this.position);
  790. }
  791. currentPosition.subtractInPlace(camera.globalPosition);
  792. var finalEuler = Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  793. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  794. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  795. }
  796. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  797. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  798. }
  799. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  800. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  801. }
  802. Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, Tmp.Matrix[0]);
  803. } else {
  804. Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  805. Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  806. Tmp.Matrix[1].invertToRef(Tmp.Matrix[0]);
  807. }
  808. Tmp.Matrix[1].copyFrom(Tmp.Matrix[5]);
  809. Tmp.Matrix[1].multiplyToRef(Tmp.Matrix[0], Tmp.Matrix[5]);
  810. }
  811. // Post multiply inverse of pivotMatrix
  812. if (this._postMultiplyPivotMatrix) {
  813. Tmp.Matrix[5].multiplyToRef(this._pivotMatrixInverse, Tmp.Matrix[5]);
  814. }
  815. // Local world
  816. Tmp.Matrix[5].multiplyToRef(Tmp.Matrix[2], this._localWorld);
  817. // Parent
  818. if (this.parent && this.parent.getWorldMatrix) {
  819. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  820. if (this._transformToBoneReferal) {
  821. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), Tmp.Matrix[6]);
  822. Tmp.Matrix[5].copyFrom(Tmp.Matrix[6]);
  823. } else {
  824. Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  825. }
  826. this._localWorld.getTranslationToRef(Tmp.Vector3[5]);
  827. Vector3.TransformCoordinatesToRef(Tmp.Vector3[5], Tmp.Matrix[5], Tmp.Vector3[5]);
  828. this._worldMatrix.copyFrom(this._localWorld);
  829. this._worldMatrix.setTranslation(Tmp.Vector3[5]);
  830. } else {
  831. if (this._transformToBoneReferal) {
  832. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), Tmp.Matrix[6]);
  833. Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  834. } else {
  835. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  836. }
  837. }
  838. this._markSyncedWithParent();
  839. } else {
  840. this._worldMatrix.copyFrom(this._localWorld);
  841. }
  842. // Normal matrix
  843. if (!this.ignoreNonUniformScaling) {
  844. if (this.scaling.isNonUniform) {
  845. this._updateNonUniformScalingState(true);
  846. } else if (this.parent && (<TransformNode>this.parent)._nonUniformScaling) {
  847. this._updateNonUniformScalingState((<TransformNode>this.parent)._nonUniformScaling);
  848. } else {
  849. this._updateNonUniformScalingState(false);
  850. }
  851. } else {
  852. this._updateNonUniformScalingState(false);
  853. }
  854. this._afterComputeWorldMatrix();
  855. // Absolute position
  856. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  857. // Callbacks
  858. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  859. if (!this._poseMatrix) {
  860. this._poseMatrix = Matrix.Invert(this._worldMatrix);
  861. }
  862. // Cache the determinant
  863. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  864. return this._worldMatrix;
  865. }
  866. protected _afterComputeWorldMatrix(): void {
  867. }
  868. /**
  869. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  870. * @param func callback function to add
  871. *
  872. * @returns the TransformNode.
  873. */
  874. public registerAfterWorldMatrixUpdate(func: (mesh: TransformNode) => void): TransformNode {
  875. this.onAfterWorldMatrixUpdateObservable.add(func);
  876. return this;
  877. }
  878. /**
  879. * Removes a registered callback function.
  880. * @param func callback function to remove
  881. * @returns the TransformNode.
  882. */
  883. public unregisterAfterWorldMatrixUpdate(func: (mesh: TransformNode) => void): TransformNode {
  884. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  885. return this;
  886. }
  887. /**
  888. * Gets the position of the current mesh in camera space
  889. * @param camera defines the camera to use
  890. * @returns a position
  891. */
  892. public getPositionInCameraSpace(camera: Nullable<Camera> = null): Vector3 {
  893. if (!camera) {
  894. camera = (<Camera>this.getScene().activeCamera);
  895. }
  896. return Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  897. }
  898. /**
  899. * Returns the distance from the mesh to the active camera
  900. * @param camera defines the camera to use
  901. * @returns the distance
  902. */
  903. public getDistanceToCamera(camera: Nullable<Camera> = null): number {
  904. if (!camera) {
  905. camera = (<Camera>this.getScene().activeCamera);
  906. }
  907. return this.absolutePosition.subtract(camera.position).length();
  908. }
  909. /**
  910. * Clone the current transform node
  911. * @param name Name of the new clone
  912. * @param newParent New parent for the clone
  913. * @param doNotCloneChildren Do not clone children hierarchy
  914. * @returns the new transform node
  915. */
  916. public clone(name: string, newParent: Node, doNotCloneChildren?: boolean): Nullable<TransformNode> {
  917. var result = SerializationHelper.Clone(() => new TransformNode(name, this.getScene()), this);
  918. result.name = name;
  919. result.id = name;
  920. if (newParent) {
  921. result.parent = newParent;
  922. }
  923. if (!doNotCloneChildren) {
  924. // Children
  925. let directDescendants = this.getDescendants(true);
  926. for (let index = 0; index < directDescendants.length; index++) {
  927. var child = directDescendants[index];
  928. if ((<any>child).clone) {
  929. (<any>child).clone(name + "." + child.name, result);
  930. }
  931. }
  932. }
  933. return result;
  934. }
  935. /**
  936. * Serializes the objects information.
  937. * @param currentSerializationObject defines the object to serialize in
  938. * @returns the serialized object
  939. */
  940. public serialize(currentSerializationObject?: any): any {
  941. let serializationObject = SerializationHelper.Serialize(this, currentSerializationObject);
  942. serializationObject.type = this.getClassName();
  943. // Parent
  944. if (this.parent) {
  945. serializationObject.parentId = this.parent.id;
  946. }
  947. if (Tags && Tags.HasTags(this)) {
  948. serializationObject.tags = Tags.GetTags(this);
  949. }
  950. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  951. serializationObject.isEnabled = this.isEnabled();
  952. // Parent
  953. if (this.parent) {
  954. serializationObject.parentId = this.parent.id;
  955. }
  956. return serializationObject;
  957. }
  958. // Statics
  959. /**
  960. * Returns a new TransformNode object parsed from the source provided.
  961. * @param parsedTransformNode is the source.
  962. * @param scene the scne the object belongs to
  963. * @param rootUrl is a string, it's the root URL to prefix the `delayLoadingFile` property with
  964. * @returns a new TransformNode object parsed from the source provided.
  965. */
  966. public static Parse(parsedTransformNode: any, scene: Scene, rootUrl: string): TransformNode {
  967. var transformNode = SerializationHelper.Parse(() => new TransformNode(parsedTransformNode.name, scene), parsedTransformNode, scene, rootUrl);
  968. if (Tags) {
  969. Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  970. }
  971. if (parsedTransformNode.localMatrix) {
  972. transformNode.setPreTransformMatrix(Matrix.FromArray(parsedTransformNode.localMatrix));
  973. } else if (parsedTransformNode.pivotMatrix) {
  974. transformNode.setPivotMatrix(Matrix.FromArray(parsedTransformNode.pivotMatrix));
  975. }
  976. transformNode.setEnabled(parsedTransformNode.isEnabled);
  977. // Parent
  978. if (parsedTransformNode.parentId) {
  979. transformNode._waitingParentId = parsedTransformNode.parentId;
  980. }
  981. return transformNode;
  982. }
  983. /**
  984. * Releases resources associated with this transform node.
  985. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  986. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  987. */
  988. public dispose(doNotRecurse?: boolean, disposeMaterialAndTextures = false): void {
  989. // Animations
  990. this.getScene().stopAnimation(this);
  991. // Remove from scene
  992. this.getScene().removeTransformNode(this);
  993. this.onAfterWorldMatrixUpdateObservable.clear();
  994. super.dispose(doNotRecurse, disposeMaterialAndTextures);
  995. }
  996. }
  997. }