transformNode.ts 48 KB

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