node.ts 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839
  1. import { Scene } from "./scene";
  2. import { Nullable } from "./types";
  3. import { Matrix, Vector3 } from "./Maths/math";
  4. import { Engine } from "./Engines/engine";
  5. import { IBehaviorAware, Behavior } from "./Behaviors/behavior";
  6. import { serialize } from "./Misc/decorators";
  7. import { Observable, Observer } from "./Misc/observable";
  8. import { EngineStore } from "./Engines/engineStore";
  9. import { _DevTools } from './Misc/devTools';
  10. import { AbstractActionManager } from './Actions/abstractActionManager';
  11. import { IInspectable } from './Misc/iInspectable';
  12. import { Tools } from './Misc/tools';
  13. declare type Animatable = import("./Animations/animatable").Animatable;
  14. declare type AnimationPropertiesOverride = import("./Animations/animationPropertiesOverride").AnimationPropertiesOverride;
  15. declare type Animation = import("./Animations/animation").Animation;
  16. declare type AnimationRange = import("./Animations/animationRange").AnimationRange;
  17. declare type AbstractMesh = import("./Meshes/abstractMesh").AbstractMesh;
  18. /**
  19. * Defines how a node can be built from a string name.
  20. */
  21. export type NodeConstructor = (name: string, scene: Scene, options?: any) => () => Node;
  22. /**
  23. * Node is the basic class for all scene objects (Mesh, Light, Camera.)
  24. */
  25. export class Node implements IBehaviorAware<Node> {
  26. /** @hidden */
  27. public static _AnimationRangeFactory = (name: string, from: number, to: number): AnimationRange => {
  28. throw _DevTools.WarnImport("AnimationRange");
  29. }
  30. private static _NodeConstructors: { [key: string]: any } = {};
  31. /**
  32. * Add a new node constructor
  33. * @param type defines the type name of the node to construct
  34. * @param constructorFunc defines the constructor function
  35. */
  36. public static AddNodeConstructor(type: string, constructorFunc: NodeConstructor) {
  37. this._NodeConstructors[type] = constructorFunc;
  38. }
  39. /**
  40. * Returns a node constructor based on type name
  41. * @param type defines the type name
  42. * @param name defines the new node name
  43. * @param scene defines the hosting scene
  44. * @param options defines optional options to transmit to constructors
  45. * @returns the new constructor or null
  46. */
  47. public static Construct(type: string, name: string, scene: Scene, options?: any): Nullable<() => Node> {
  48. let constructorFunc = this._NodeConstructors[type];
  49. if (!constructorFunc) {
  50. return null;
  51. }
  52. return constructorFunc(name, scene, options);
  53. }
  54. /**
  55. * Gets or sets the name of the node
  56. */
  57. @serialize()
  58. public name: string;
  59. /**
  60. * Gets or sets the id of the node
  61. */
  62. @serialize()
  63. public id: string;
  64. /**
  65. * Gets or sets the unique id of the node
  66. */
  67. @serialize()
  68. public uniqueId: number;
  69. /**
  70. * Gets or sets a string used to store user defined state for the node
  71. */
  72. @serialize()
  73. public state = "";
  74. /**
  75. * Gets or sets an object used to store user defined information for the node
  76. */
  77. @serialize()
  78. public metadata: any = null;
  79. /**
  80. * For internal use only. Please do not use.
  81. */
  82. public reservedDataStore: any = null;
  83. /**
  84. * List of inspectable custom properties (used by the Inspector)
  85. * @see https://doc.babylonjs.com/how_to/debug_layer#extensibility
  86. */
  87. public inspectableCustomProperties: IInspectable[];
  88. /**
  89. * Gets or sets a boolean used to define if the node must be serialized
  90. */
  91. public doNotSerialize = false;
  92. /** @hidden */
  93. public _isDisposed = false;
  94. /**
  95. * Gets a list of Animations associated with the node
  96. */
  97. public animations = new Array<Animation>();
  98. protected _ranges: { [name: string]: Nullable<AnimationRange> } = {};
  99. /**
  100. * Callback raised when the node is ready to be used
  101. */
  102. public onReady: (node: Node) => void;
  103. private _isEnabled = true;
  104. private _isParentEnabled = true;
  105. private _isReady = true;
  106. /** @hidden */
  107. public _currentRenderId = -1;
  108. private _parentUpdateId = -1;
  109. protected _childUpdateId = -1;
  110. /** @hidden */
  111. public _waitingParentId: Nullable<string>;
  112. /** @hidden */
  113. public _scene: Scene;
  114. /** @hidden */
  115. public _cache: any;
  116. private _parentNode: Nullable<Node>;
  117. private _children: Node[];
  118. /** @hidden */
  119. public _worldMatrix = Matrix.Identity();
  120. /** @hidden */
  121. public _worldMatrixDeterminant = 0;
  122. /** @hidden */
  123. public _worldMatrixDeterminantIsDirty = true;
  124. /** @hidden */
  125. private _sceneRootNodesIndex = -1;
  126. /**
  127. * Gets a boolean indicating if the node has been disposed
  128. * @returns true if the node was disposed
  129. */
  130. public isDisposed(): boolean {
  131. return this._isDisposed;
  132. }
  133. /**
  134. * Gets or sets the parent of the node (without keeping the current position in the scene)
  135. * @see https://doc.babylonjs.com/how_to/parenting
  136. */
  137. public set parent(parent: Nullable<Node>) {
  138. if (this._parentNode === parent) {
  139. return;
  140. }
  141. const previousParentNode = this._parentNode;
  142. // Remove self from list of children of parent
  143. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  144. var index = this._parentNode._children.indexOf(this);
  145. if (index !== -1) {
  146. this._parentNode._children.splice(index, 1);
  147. }
  148. if (!parent && !this._isDisposed) {
  149. this.addToSceneRootNodes();
  150. }
  151. }
  152. // Store new parent
  153. this._parentNode = parent;
  154. // Add as child to new parent
  155. if (this._parentNode) {
  156. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  157. this._parentNode._children = new Array<Node>();
  158. }
  159. this._parentNode._children.push(this);
  160. if (!previousParentNode) {
  161. this.removeFromSceneRootNodes();
  162. }
  163. }
  164. // Enabled state
  165. this._syncParentEnabledState();
  166. }
  167. public get parent(): Nullable<Node> {
  168. return this._parentNode;
  169. }
  170. private addToSceneRootNodes() {
  171. if (this._sceneRootNodesIndex === -1) {
  172. this._sceneRootNodesIndex = this._scene.rootNodes.length;
  173. this._scene.rootNodes.push(this);
  174. }
  175. }
  176. private removeFromSceneRootNodes() {
  177. if (this._sceneRootNodesIndex !== -1) {
  178. const rootNodes = this._scene.rootNodes;
  179. const lastIdx = rootNodes.length - 1;
  180. rootNodes[this._sceneRootNodesIndex] = rootNodes[lastIdx];
  181. rootNodes[this._sceneRootNodesIndex]._sceneRootNodesIndex = this._sceneRootNodesIndex;
  182. this._scene.rootNodes.pop();
  183. this._sceneRootNodesIndex = -1;
  184. }
  185. }
  186. private _animationPropertiesOverride: Nullable<AnimationPropertiesOverride> = null;
  187. /**
  188. * Gets or sets the animation properties override
  189. */
  190. public get animationPropertiesOverride(): Nullable<AnimationPropertiesOverride> {
  191. if (!this._animationPropertiesOverride) {
  192. return this._scene.animationPropertiesOverride;
  193. }
  194. return this._animationPropertiesOverride;
  195. }
  196. public set animationPropertiesOverride(value: Nullable<AnimationPropertiesOverride>) {
  197. this._animationPropertiesOverride = value;
  198. }
  199. /**
  200. * Gets a string idenfifying the name of the class
  201. * @returns "Node" string
  202. */
  203. public getClassName(): string {
  204. return "Node";
  205. }
  206. /** @hidden */
  207. public readonly _isNode = true;
  208. /**
  209. * An event triggered when the mesh is disposed
  210. */
  211. public onDisposeObservable = new Observable<Node>();
  212. private _onDisposeObserver: Nullable<Observer<Node>>;
  213. /**
  214. * Sets a callback that will be raised when the node will be disposed
  215. */
  216. public set onDispose(callback: () => void) {
  217. if (this._onDisposeObserver) {
  218. this.onDisposeObservable.remove(this._onDisposeObserver);
  219. }
  220. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  221. }
  222. /**
  223. * Creates a new Node
  224. * @param name the name and id to be given to this node
  225. * @param scene the scene this node will be added to
  226. * @param addToRootNodes the node will be added to scene.rootNodes
  227. */
  228. constructor(name: string, scene: Nullable<Scene> = null, addToRootNodes = true) {
  229. this.name = name;
  230. this.id = name;
  231. this._scene = <Scene>(scene || EngineStore.LastCreatedScene);
  232. this.uniqueId = this._scene.getUniqueId();
  233. this._initCache();
  234. if (addToRootNodes) {
  235. this.addToSceneRootNodes();
  236. }
  237. }
  238. /**
  239. * Gets the scene of the node
  240. * @returns a scene
  241. */
  242. public getScene(): Scene {
  243. return this._scene;
  244. }
  245. /**
  246. * Gets the engine of the node
  247. * @returns a Engine
  248. */
  249. public getEngine(): Engine {
  250. return this._scene.getEngine();
  251. }
  252. // Behaviors
  253. private _behaviors = new Array<Behavior<Node>>();
  254. /**
  255. * Attach a behavior to the node
  256. * @see http://doc.babylonjs.com/features/behaviour
  257. * @param behavior defines the behavior to attach
  258. * @param attachImmediately defines that the behavior must be attached even if the scene is still loading
  259. * @returns the current Node
  260. */
  261. public addBehavior(behavior: Behavior<Node>, attachImmediately = false): Node {
  262. var index = this._behaviors.indexOf(behavior);
  263. if (index !== -1) {
  264. return this;
  265. }
  266. behavior.init();
  267. if (this._scene.isLoading && !attachImmediately) {
  268. // We defer the attach when the scene will be loaded
  269. this._scene.onDataLoadedObservable.addOnce(() => {
  270. behavior.attach(this);
  271. });
  272. } else {
  273. behavior.attach(this);
  274. }
  275. this._behaviors.push(behavior);
  276. return this;
  277. }
  278. /**
  279. * Remove an attached behavior
  280. * @see http://doc.babylonjs.com/features/behaviour
  281. * @param behavior defines the behavior to attach
  282. * @returns the current Node
  283. */
  284. public removeBehavior(behavior: Behavior<Node>): Node {
  285. var index = this._behaviors.indexOf(behavior);
  286. if (index === -1) {
  287. return this;
  288. }
  289. this._behaviors[index].detach();
  290. this._behaviors.splice(index, 1);
  291. return this;
  292. }
  293. /**
  294. * Gets the list of attached behaviors
  295. * @see http://doc.babylonjs.com/features/behaviour
  296. */
  297. public get behaviors(): Behavior<Node>[] {
  298. return this._behaviors;
  299. }
  300. /**
  301. * Gets an attached behavior by name
  302. * @param name defines the name of the behavior to look for
  303. * @see http://doc.babylonjs.com/features/behaviour
  304. * @returns null if behavior was not found else the requested behavior
  305. */
  306. public getBehaviorByName(name: string): Nullable<Behavior<Node>> {
  307. for (var behavior of this._behaviors) {
  308. if (behavior.name === name) {
  309. return behavior;
  310. }
  311. }
  312. return null;
  313. }
  314. /**
  315. * Returns the latest update of the World matrix
  316. * @returns a Matrix
  317. */
  318. public getWorldMatrix(): Matrix {
  319. if (this._currentRenderId !== this._scene.getRenderId()) {
  320. this.computeWorldMatrix();
  321. }
  322. return this._worldMatrix;
  323. }
  324. /** @hidden */
  325. public _getWorldMatrixDeterminant(): number {
  326. if (this._worldMatrixDeterminantIsDirty) {
  327. this._worldMatrixDeterminantIsDirty = false;
  328. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  329. }
  330. return this._worldMatrixDeterminant;
  331. }
  332. /**
  333. * Returns directly the latest state of the mesh World matrix.
  334. * A Matrix is returned.
  335. */
  336. public get worldMatrixFromCache(): Matrix {
  337. return this._worldMatrix;
  338. }
  339. // override it in derived class if you add new variables to the cache
  340. // and call the parent class method
  341. /** @hidden */
  342. public _initCache() {
  343. this._cache = {};
  344. this._cache.parent = undefined;
  345. }
  346. /** @hidden */
  347. public updateCache(force?: boolean): void {
  348. if (!force && this.isSynchronized()) {
  349. return;
  350. }
  351. this._cache.parent = this.parent;
  352. this._updateCache();
  353. }
  354. /** @hidden */
  355. public _getActionManagerForTrigger(trigger?: number, initialCall = true): Nullable<AbstractActionManager> {
  356. if (!this.parent) {
  357. return null;
  358. }
  359. return this.parent._getActionManagerForTrigger(trigger, false);
  360. }
  361. // override it in derived class if you add new variables to the cache
  362. // and call the parent class method if !ignoreParentClass
  363. /** @hidden */
  364. public _updateCache(ignoreParentClass?: boolean): void {
  365. }
  366. // override it in derived class if you add new variables to the cache
  367. /** @hidden */
  368. public _isSynchronized(): boolean {
  369. return true;
  370. }
  371. /** @hidden */
  372. public _markSyncedWithParent() {
  373. if (this._parentNode) {
  374. this._parentUpdateId = this._parentNode._childUpdateId;
  375. }
  376. }
  377. /** @hidden */
  378. public isSynchronizedWithParent(): boolean {
  379. if (!this._parentNode) {
  380. return true;
  381. }
  382. if (this._parentUpdateId !== this._parentNode._childUpdateId) {
  383. return false;
  384. }
  385. return this._parentNode.isSynchronized();
  386. }
  387. /** @hidden */
  388. public isSynchronized(): boolean {
  389. if (this._cache.parent != this._parentNode) {
  390. this._cache.parent = this._parentNode;
  391. return false;
  392. }
  393. if (this._parentNode && !this.isSynchronizedWithParent()) {
  394. return false;
  395. }
  396. return this._isSynchronized();
  397. }
  398. /**
  399. * Is this node ready to be used/rendered
  400. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  401. * @return true if the node is ready
  402. */
  403. public isReady(completeCheck = false): boolean {
  404. return this._isReady;
  405. }
  406. /**
  407. * Is this node enabled?
  408. * If the node has a parent, all ancestors will be checked and false will be returned if any are false (not enabled), otherwise will return true
  409. * @param checkAncestors indicates if this method should check the ancestors. The default is to check the ancestors. If set to false, the method will return the value of this node without checking ancestors
  410. * @return whether this node (and its parent) is enabled
  411. */
  412. public isEnabled(checkAncestors: boolean = true): boolean {
  413. if (checkAncestors === false) {
  414. return this._isEnabled;
  415. }
  416. if (!this._isEnabled) {
  417. return false;
  418. }
  419. return this._isParentEnabled;
  420. }
  421. /** @hidden */
  422. protected _syncParentEnabledState() {
  423. this._isParentEnabled = this._parentNode ? this._parentNode.isEnabled() : true;
  424. if (this._children) {
  425. this._children.forEach((c) => {
  426. c._syncParentEnabledState(); // Force children to update accordingly
  427. });
  428. }
  429. }
  430. /**
  431. * Set the enabled state of this node
  432. * @param value defines the new enabled state
  433. */
  434. public setEnabled(value: boolean): void {
  435. this._isEnabled = value;
  436. this._syncParentEnabledState();
  437. }
  438. /**
  439. * Is this node a descendant of the given node?
  440. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  441. * @param ancestor defines the parent node to inspect
  442. * @returns a boolean indicating if this node is a descendant of the given node
  443. */
  444. public isDescendantOf(ancestor: Node): boolean {
  445. if (this.parent) {
  446. if (this.parent === ancestor) {
  447. return true;
  448. }
  449. return this.parent.isDescendantOf(ancestor);
  450. }
  451. return false;
  452. }
  453. /** @hidden */
  454. public _getDescendants(results: Node[], directDescendantsOnly: boolean = false, predicate?: (node: Node) => boolean): void {
  455. if (!this._children) {
  456. return;
  457. }
  458. for (var index = 0; index < this._children.length; index++) {
  459. var item = this._children[index];
  460. if (!predicate || predicate(item)) {
  461. results.push(item);
  462. }
  463. if (!directDescendantsOnly) {
  464. item._getDescendants(results, false, predicate);
  465. }
  466. }
  467. }
  468. /**
  469. * Will return all nodes that have this node as ascendant
  470. * @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
  471. * @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
  472. * @return all children nodes of all types
  473. */
  474. public getDescendants(directDescendantsOnly?: boolean, predicate?: (node: Node) => boolean): Node[] {
  475. var results = new Array<Node>();
  476. this._getDescendants(results, directDescendantsOnly, predicate);
  477. return results;
  478. }
  479. /**
  480. * Get all child-meshes of this node
  481. * @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 (Default: false)
  482. * @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
  483. * @returns an array of AbstractMesh
  484. */
  485. public getChildMeshes(directDescendantsOnly?: boolean, predicate?: (node: Node) => boolean): AbstractMesh[] {
  486. var results: Array<AbstractMesh> = [];
  487. this._getDescendants(results, directDescendantsOnly, (node: Node) => {
  488. return ((!predicate || predicate(node)) && ((<AbstractMesh>node).cullingStrategy !== undefined));
  489. });
  490. return results;
  491. }
  492. /**
  493. * Get all direct children of this node
  494. * @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
  495. * @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 (Default: true)
  496. * @returns an array of Node
  497. */
  498. public getChildren(predicate?: (node: Node) => boolean, directDescendantsOnly = true): Node[] {
  499. return this.getDescendants(directDescendantsOnly, predicate);
  500. }
  501. /** @hidden */
  502. public _setReady(state: boolean): void {
  503. if (state === this._isReady) {
  504. return;
  505. }
  506. if (!state) {
  507. this._isReady = false;
  508. return;
  509. }
  510. if (this.onReady) {
  511. this.onReady(this);
  512. }
  513. this._isReady = true;
  514. }
  515. /**
  516. * Get an animation by name
  517. * @param name defines the name of the animation to look for
  518. * @returns null if not found else the requested animation
  519. */
  520. public getAnimationByName(name: string): Nullable<Animation> {
  521. for (var i = 0; i < this.animations.length; i++) {
  522. var animation = this.animations[i];
  523. if (animation.name === name) {
  524. return animation;
  525. }
  526. }
  527. return null;
  528. }
  529. /**
  530. * Creates an animation range for this node
  531. * @param name defines the name of the range
  532. * @param from defines the starting key
  533. * @param to defines the end key
  534. */
  535. public createAnimationRange(name: string, from: number, to: number): void {
  536. // check name not already in use
  537. if (!this._ranges[name]) {
  538. this._ranges[name] = Node._AnimationRangeFactory(name, from, to);
  539. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  540. if (this.animations[i]) {
  541. this.animations[i].createRange(name, from, to);
  542. }
  543. }
  544. }
  545. }
  546. /**
  547. * Delete a specific animation range
  548. * @param name defines the name of the range to delete
  549. * @param deleteFrames defines if animation frames from the range must be deleted as well
  550. */
  551. public deleteAnimationRange(name: string, deleteFrames = true): void {
  552. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  553. if (this.animations[i]) {
  554. this.animations[i].deleteRange(name, deleteFrames);
  555. }
  556. }
  557. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  558. }
  559. /**
  560. * Get an animation range by name
  561. * @param name defines the name of the animation range to look for
  562. * @returns null if not found else the requested animation range
  563. */
  564. public getAnimationRange(name: string): Nullable<AnimationRange> {
  565. return this._ranges[name];
  566. }
  567. /**
  568. * Gets the list of all animation ranges defined on this node
  569. * @returns an array
  570. */
  571. public getAnimationRanges(): Nullable<AnimationRange>[] {
  572. var animationRanges: Nullable<AnimationRange>[] = [];
  573. var name: string;
  574. for (name in this._ranges) {
  575. animationRanges.push(this._ranges[name]);
  576. }
  577. return animationRanges;
  578. }
  579. /**
  580. * Will start the animation sequence
  581. * @param name defines the range frames for animation sequence
  582. * @param loop defines if the animation should loop (false by default)
  583. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  584. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  585. * @returns the object created for this animation. If range does not exist, it will return null
  586. */
  587. public beginAnimation(name: string, loop?: boolean, speedRatio?: number, onAnimationEnd?: () => void): Nullable<Animatable> {
  588. var range = this.getAnimationRange(name);
  589. if (!range) {
  590. return null;
  591. }
  592. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  593. }
  594. /**
  595. * Serialize animation ranges into a JSON compatible object
  596. * @returns serialization object
  597. */
  598. public serializeAnimationRanges(): any {
  599. var serializationRanges = [];
  600. for (var name in this._ranges) {
  601. var localRange = this._ranges[name];
  602. if (!localRange) {
  603. continue;
  604. }
  605. var range: any = {};
  606. range.name = name;
  607. range.from = localRange.from;
  608. range.to = localRange.to;
  609. serializationRanges.push(range);
  610. }
  611. return serializationRanges;
  612. }
  613. /**
  614. * Computes the world matrix of the node
  615. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  616. * @returns the world matrix
  617. */
  618. public computeWorldMatrix(force?: boolean): Matrix {
  619. if (!this._worldMatrix) {
  620. this._worldMatrix = Matrix.Identity();
  621. }
  622. return this._worldMatrix;
  623. }
  624. /**
  625. * Releases resources associated with this node.
  626. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  627. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  628. */
  629. public dispose(doNotRecurse?: boolean, disposeMaterialAndTextures = false): void {
  630. this._isDisposed = true;
  631. if (!doNotRecurse) {
  632. const nodes = this.getDescendants(true);
  633. for (const node of nodes) {
  634. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  635. }
  636. }
  637. if (!this.parent) {
  638. this.removeFromSceneRootNodes();
  639. } else {
  640. this.parent = null;
  641. }
  642. // Callback
  643. this.onDisposeObservable.notifyObservers(this);
  644. this.onDisposeObservable.clear();
  645. // Behaviors
  646. for (var behavior of this._behaviors) {
  647. behavior.detach();
  648. }
  649. this._behaviors = [];
  650. }
  651. protected _getBoudingInfoMin(){
  652. return new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  653. }
  654. protected _getBoudingInfoMax(){
  655. return new Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  656. }
  657. /**
  658. * Parse animation range data from a serialization object and store them into a given node
  659. * @param node defines where to store the animation ranges
  660. * @param parsedNode defines the serialization object to read data from
  661. * @param scene defines the hosting scene
  662. */
  663. public static ParseAnimationRanges(node: Node, parsedNode: any, scene: Scene): void {
  664. if (parsedNode.ranges) {
  665. for (var index = 0; index < parsedNode.ranges.length; index++) {
  666. var data = parsedNode.ranges[index];
  667. node.createAnimationRange(data.name, data.from, data.to);
  668. }
  669. }
  670. }
  671. /**
  672. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  673. * @param includeDescendants Include bounding info from descendants as well (true by default)
  674. * @param predicate defines a callback function that can be customize to filter what meshes should be included in the list used to compute the bounding vectors
  675. * @returns the new bounding vectors
  676. */
  677. public getHierarchyBoundingVectors(includeDescendants = true, predicate: Nullable<(abstractMesh: AbstractMesh) => boolean> = null): { min: Vector3, max: Vector3 } {
  678. // Ensures that all world matrix will be recomputed.
  679. this.getScene().incrementRenderId();
  680. this.computeWorldMatrix(true);
  681. let min = this._getBoudingInfoMin();
  682. let max = this._getBoudingInfoMax();
  683. if (includeDescendants) {
  684. let descendants = this.getDescendants(false);
  685. for (var descendant of descendants) {
  686. let childMesh = <AbstractMesh>descendant;
  687. childMesh.computeWorldMatrix(true);
  688. // Filters meshes based on custom predicate function.
  689. if (predicate && !predicate(childMesh)) {
  690. continue;
  691. }
  692. //make sure we have the needed params to get mix and max
  693. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  694. continue;
  695. }
  696. let childBoundingInfo = childMesh.getBoundingInfo();
  697. let boundingBox = childBoundingInfo.boundingBox;
  698. var minBox = boundingBox.minimumWorld;
  699. var maxBox = boundingBox.maximumWorld;
  700. Tools.CheckExtends(minBox, min, max);
  701. Tools.CheckExtends(maxBox, min, max);
  702. }
  703. }
  704. return {
  705. min: min,
  706. max: max
  707. };
  708. }
  709. }