babylon.node.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644
  1. module BABYLON {
  2. /**
  3. * Node is the basic class for all scene objects (Mesh, Light Camera).
  4. */
  5. export class Node {
  6. /**
  7. * Gets or sets the name of the node
  8. */
  9. @serialize()
  10. public name: string;
  11. /**
  12. * Gets or sets the id of the node
  13. */
  14. @serialize()
  15. public id: string;
  16. /**
  17. * Gets or sets the unique id of the node
  18. */
  19. @serialize()
  20. public uniqueId: number;
  21. /**
  22. * Gets or sets a string used to store user defined state for the node
  23. */
  24. @serialize()
  25. public state = "";
  26. /**
  27. * Gets or sets an object used to store user defined information for the node
  28. */
  29. @serialize()
  30. public metadata: any = null;
  31. /**
  32. * Gets or sets a boolean used to define if the node must be serialized
  33. */
  34. public doNotSerialize = false;
  35. /** @hidden */
  36. public _isDisposed = false;
  37. /**
  38. * Gets a list of Animations associated with the node
  39. */
  40. public animations = new Array<Animation>();
  41. private _ranges: { [name: string]: Nullable<AnimationRange> } = {};
  42. /**
  43. * Callback raised when the node is ready to be used
  44. */
  45. public onReady: (node: Node) => void;
  46. private _isEnabled = true;
  47. private _isReady = true;
  48. /** @hidden */
  49. public _currentRenderId = -1;
  50. private _parentRenderId = -1;
  51. protected _childRenderId = -1;
  52. /** @hidden */
  53. public _waitingParentId: Nullable<string>;
  54. private _scene: Scene;
  55. /** @hidden */
  56. public _cache: any;
  57. private _parentNode: Nullable<Node>;
  58. private _children: Node[];
  59. /**
  60. * Gets a boolean indicating if the node has been disposed
  61. * @returns true if the node was disposed
  62. */
  63. public isDisposed(): boolean {
  64. return this._isDisposed;
  65. }
  66. /**
  67. * Gets or sets the parent of the node
  68. */
  69. public set parent(parent: Nullable<Node>) {
  70. if (this._parentNode === parent) {
  71. return;
  72. }
  73. // Remove self from list of children of parent
  74. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  75. var index = this._parentNode._children.indexOf(this);
  76. if (index !== -1) {
  77. this._parentNode._children.splice(index, 1);
  78. }
  79. }
  80. // Store new parent
  81. this._parentNode = parent;
  82. // Add as child to new parent
  83. if (this._parentNode) {
  84. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  85. this._parentNode._children = new Array<Node>();
  86. }
  87. this._parentNode._children.push(this);
  88. }
  89. }
  90. public get parent(): Nullable<Node> {
  91. return this._parentNode;
  92. }
  93. private _animationPropertiesOverride: Nullable<AnimationPropertiesOverride> = null;
  94. /**
  95. * Gets or sets the animation properties override
  96. */
  97. public get animationPropertiesOverride(): Nullable<AnimationPropertiesOverride> {
  98. if (!this._animationPropertiesOverride) {
  99. return this._scene.animationPropertiesOverride;
  100. }
  101. return this._animationPropertiesOverride;
  102. }
  103. public set animationPropertiesOverride(value: Nullable<AnimationPropertiesOverride>) {
  104. this._animationPropertiesOverride = value;
  105. }
  106. /**
  107. * Gets a string idenfifying the name of the class
  108. * @returns "Node" string
  109. */
  110. public getClassName(): string {
  111. return "Node";
  112. }
  113. /**
  114. * An event triggered when the mesh is disposed
  115. */
  116. public onDisposeObservable = new Observable<Node>();
  117. private _onDisposeObserver: Nullable<Observer<Node>>;
  118. /**
  119. * Sets a callback that will be raised when the node will be disposed
  120. */
  121. public set onDispose(callback: () => void) {
  122. if (this._onDisposeObserver) {
  123. this.onDisposeObservable.remove(this._onDisposeObserver);
  124. }
  125. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  126. }
  127. /**
  128. * Creates a new Node
  129. * @param {string} name - the name and id to be given to this node
  130. * @param {BABYLON.Scene} the scene this node will be added to
  131. */
  132. constructor(name: string, scene: Nullable<Scene> = null) {
  133. this.name = name;
  134. this.id = name;
  135. this._scene = <Scene>(scene || Engine.LastCreatedScene);
  136. this.uniqueId = this._scene.getUniqueId();
  137. this._initCache();
  138. }
  139. /**
  140. * Gets the scene of the node
  141. * @returns a {BABYLON.Scene}
  142. */
  143. public getScene(): Scene {
  144. return this._scene;
  145. }
  146. /**
  147. * Gets the engine of the node
  148. * @returns a {BABYLON.Engine}
  149. */
  150. public getEngine(): Engine {
  151. return this._scene.getEngine();
  152. }
  153. // Behaviors
  154. private _behaviors = new Array<Behavior<Node>>();
  155. /**
  156. * Attach a behavior to the node
  157. * @see http://doc.babylonjs.com/features/behaviour
  158. * @param behavior defines the behavior to attach
  159. * @returns the current Node
  160. */
  161. public addBehavior(behavior: Behavior<Node>): Node {
  162. var index = this._behaviors.indexOf(behavior);
  163. if (index !== -1) {
  164. return this;
  165. }
  166. behavior.init();
  167. if (this._scene.isLoading) {
  168. // We defer the attach when the scene will be loaded
  169. var observer = this._scene.onDataLoadedObservable.add(() => {
  170. behavior.attach(this);
  171. setTimeout(() => {
  172. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  173. this._scene.onDataLoadedObservable.remove(observer);
  174. }, 0);
  175. });
  176. } else {
  177. behavior.attach(this);
  178. }
  179. this._behaviors.push(behavior);
  180. return this;
  181. }
  182. /**
  183. * Remove an attached behavior
  184. * @see http://doc.babylonjs.com/features/behaviour
  185. * @param behavior defines the behavior to attach
  186. * @returns the current Node
  187. */
  188. public removeBehavior(behavior: Behavior<Node>): Node {
  189. var index = this._behaviors.indexOf(behavior);
  190. if (index === -1) {
  191. return this;
  192. }
  193. this._behaviors[index].detach();
  194. this._behaviors.splice(index, 1);
  195. return this;
  196. }
  197. /**
  198. * Gets the list of attached behaviors
  199. * @see http://doc.babylonjs.com/features/behaviour
  200. */
  201. public get behaviors(): Behavior<Node>[] {
  202. return this._behaviors;
  203. }
  204. /**
  205. * Gets an attached behavior by name
  206. * @param name defines the name of the behavior to look for
  207. * @see http://doc.babylonjs.com/features/behaviour
  208. * @returns null if behavior was not found else the requested behavior
  209. */
  210. public getBehaviorByName(name: string): Nullable<Behavior<Node>> {
  211. for (var behavior of this._behaviors) {
  212. if (behavior.name === name) {
  213. return behavior;
  214. }
  215. }
  216. return null;
  217. }
  218. /**
  219. * Returns the world matrix of the node
  220. * @returns a matrix containing the node's world matrix
  221. */
  222. public getWorldMatrix(): Matrix {
  223. return Matrix.Identity();
  224. }
  225. /** @hidden */
  226. public _getWorldMatrixDeterminant(): number {
  227. return 1;
  228. }
  229. // override it in derived class if you add new variables to the cache
  230. // and call the parent class method
  231. /** @hidden */
  232. public _initCache() {
  233. this._cache = {};
  234. this._cache.parent = undefined;
  235. }
  236. /** @hidden */
  237. public updateCache(force?: boolean): void {
  238. if (!force && this.isSynchronized())
  239. return;
  240. this._cache.parent = this.parent;
  241. this._updateCache();
  242. }
  243. // override it in derived class if you add new variables to the cache
  244. // and call the parent class method if !ignoreParentClass
  245. /** @hidden */
  246. public _updateCache(ignoreParentClass?: boolean): void {
  247. }
  248. // override it in derived class if you add new variables to the cache
  249. /** @hidden */
  250. public _isSynchronized(): boolean {
  251. return true;
  252. }
  253. /** @hidden */
  254. public _markSyncedWithParent() {
  255. if (this.parent) {
  256. this._parentRenderId = this.parent._childRenderId;
  257. }
  258. }
  259. /** @hidden */
  260. public isSynchronizedWithParent(): boolean {
  261. if (!this.parent) {
  262. return true;
  263. }
  264. if (this._parentRenderId !== this.parent._childRenderId) {
  265. return false;
  266. }
  267. return this.parent.isSynchronized();
  268. }
  269. /** @hidden */
  270. public isSynchronized(updateCache?: boolean): boolean {
  271. var check = this.hasNewParent();
  272. check = check || !this.isSynchronizedWithParent();
  273. check = check || !this._isSynchronized();
  274. if (updateCache)
  275. this.updateCache(true);
  276. return !check;
  277. }
  278. /** @hidden */
  279. public hasNewParent(update?: boolean): boolean {
  280. if (this._cache.parent === this.parent)
  281. return false;
  282. if (update)
  283. this._cache.parent = this.parent;
  284. return true;
  285. }
  286. /**
  287. * Is this node ready to be used/rendered
  288. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  289. * @return true if the node is ready
  290. */
  291. public isReady(completeCheck = false): boolean {
  292. return this._isReady;
  293. }
  294. /**
  295. * Is this node enabled?
  296. * 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
  297. * @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
  298. * @return whether this node (and its parent) is enabled
  299. */
  300. public isEnabled(checkAncestors: boolean = true): boolean {
  301. if (checkAncestors === false) {
  302. return this._isEnabled;
  303. }
  304. if (this._isEnabled === false) {
  305. return false;
  306. }
  307. if (this.parent !== undefined && this.parent !== null) {
  308. return this.parent.isEnabled(checkAncestors);
  309. }
  310. return true;
  311. }
  312. /**
  313. * Set the enabled state of this node
  314. * @param value defines the new enabled state
  315. */
  316. public setEnabled(value: boolean): void {
  317. this._isEnabled = value;
  318. }
  319. /**
  320. * Is this node a descendant of the given node?
  321. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  322. * @param ancestor defines the parent node to inspect
  323. * @returns a boolean indicating if this node is a descendant of the given node
  324. */
  325. public isDescendantOf(ancestor: Node): boolean {
  326. if (this.parent) {
  327. if (this.parent === ancestor) {
  328. return true;
  329. }
  330. return this.parent.isDescendantOf(ancestor);
  331. }
  332. return false;
  333. }
  334. /** @hidden */
  335. public _getDescendants(results: Node[], directDescendantsOnly: boolean = false, predicate?: (node: Node) => boolean): void {
  336. if (!this._children) {
  337. return;
  338. }
  339. for (var index = 0; index < this._children.length; index++) {
  340. var item = this._children[index];
  341. if (!predicate || predicate(item)) {
  342. results.push(item);
  343. }
  344. if (!directDescendantsOnly) {
  345. item._getDescendants(results, false, predicate);
  346. }
  347. }
  348. }
  349. /**
  350. * Will return all nodes that have this node as ascendant
  351. * @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
  352. * @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
  353. * @return all children nodes of all types
  354. */
  355. public getDescendants(directDescendantsOnly?: boolean, predicate?: (node: Node) => boolean): Node[] {
  356. var results = new Array<Node>();
  357. this._getDescendants(results, directDescendantsOnly, predicate);
  358. return results;
  359. }
  360. /**
  361. * Get all child-meshes of this node
  362. * @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
  363. * @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
  364. * @returns an array of {BABYLON.AbstractMesh}
  365. */
  366. public getChildMeshes(directDescendantsOnly?: boolean, predicate?: (node: Node) => boolean): AbstractMesh[] {
  367. var results: Array<AbstractMesh> = [];
  368. this._getDescendants(results, directDescendantsOnly, (node: Node) => {
  369. return ((!predicate || predicate(node)) && (node instanceof AbstractMesh));
  370. });
  371. return results;
  372. }
  373. /**
  374. * Get all child-transformNodes of this node
  375. * @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
  376. * @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
  377. * @returns an array of {BABYLON.TransformNode}
  378. */
  379. public getChildTransformNodes(directDescendantsOnly?: boolean, predicate?: (node: Node) => boolean): TransformNode[] {
  380. var results: Array<TransformNode> = [];
  381. this._getDescendants(results, directDescendantsOnly, (node: Node) => {
  382. return ((!predicate || predicate(node)) && (node instanceof TransformNode));
  383. });
  384. return results;
  385. }
  386. /**
  387. * Get all direct children of this node
  388. * @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
  389. * @returns an array of {BABYLON.Node}
  390. */
  391. public getChildren(predicate?: (node: Node) => boolean): Node[] {
  392. return this.getDescendants(true, predicate);
  393. }
  394. /** @hidden */
  395. public _setReady(state: boolean): void {
  396. if (state === this._isReady) {
  397. return;
  398. }
  399. if (!state) {
  400. this._isReady = false;
  401. return;
  402. }
  403. if (this.onReady) {
  404. this.onReady(this);
  405. }
  406. this._isReady = true;
  407. }
  408. /**
  409. * Get an animation by name
  410. * @param name defines the name of the animation to look for
  411. * @returns null if not found else the requested animation
  412. */
  413. public getAnimationByName(name: string): Nullable<Animation> {
  414. for (var i = 0; i < this.animations.length; i++) {
  415. var animation = this.animations[i];
  416. if (animation.name === name) {
  417. return animation;
  418. }
  419. }
  420. return null;
  421. }
  422. /**
  423. * Creates an animation range for this node
  424. * @param name defines the name of the range
  425. * @param from defines the starting key
  426. * @param to defines the end key
  427. */
  428. public createAnimationRange(name: string, from: number, to: number): void {
  429. // check name not already in use
  430. if (!this._ranges[name]) {
  431. this._ranges[name] = new AnimationRange(name, from, to);
  432. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  433. if (this.animations[i]) {
  434. this.animations[i].createRange(name, from, to);
  435. }
  436. }
  437. }
  438. }
  439. /**
  440. * Delete a specific animation range
  441. * @param name defines the name of the range to delete
  442. * @param deleteFrames defines if animation frames from the range must be deleted as well
  443. */
  444. public deleteAnimationRange(name: string, deleteFrames = true): void {
  445. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  446. if (this.animations[i]) {
  447. this.animations[i].deleteRange(name, deleteFrames);
  448. }
  449. }
  450. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  451. }
  452. /**
  453. * Get an animation range by name
  454. * @param name defines the name of the animation range to look for
  455. * @returns null if not found else the requested animation range
  456. */
  457. public getAnimationRange(name: string): Nullable<AnimationRange> {
  458. return this._ranges[name];
  459. }
  460. /**
  461. * Will start the animation sequence
  462. * @param name defines the range frames for animation sequence
  463. * @param loop defines if the animation should loop (false by default)
  464. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  465. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  466. * @returns the object created for this animation. If range does not exist, it will return null
  467. */
  468. public beginAnimation(name: string, loop?: boolean, speedRatio?: number, onAnimationEnd?: () => void): Nullable<Animatable> {
  469. var range = this.getAnimationRange(name);
  470. if (!range) {
  471. return null;
  472. }
  473. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  474. }
  475. /**
  476. * Serialize animation ranges into a JSON compatible object
  477. * @returns serialization object
  478. */
  479. public serializeAnimationRanges(): any {
  480. var serializationRanges = [];
  481. for (var name in this._ranges) {
  482. var localRange = this._ranges[name];
  483. if (!localRange) {
  484. continue;
  485. }
  486. var range: any = {};
  487. range.name = name;
  488. range.from = localRange.from;
  489. range.to = localRange.to;
  490. serializationRanges.push(range);
  491. }
  492. return serializationRanges;
  493. }
  494. /**
  495. * Computes the world matrix of the node
  496. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  497. * @returns the world matrix
  498. */
  499. public computeWorldMatrix(force?: boolean): Matrix {
  500. return Matrix.Identity();
  501. }
  502. /**
  503. * Releases resources associated with this node.
  504. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  505. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  506. */
  507. public dispose(doNotRecurse?: boolean, disposeMaterialAndTextures = false): void {
  508. if (!doNotRecurse) {
  509. const nodes = this.getDescendants(true);
  510. for (const node of nodes) {
  511. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  512. }
  513. } else {
  514. const transformNodes = this.getChildTransformNodes(true);
  515. for (const transformNode of transformNodes) {
  516. transformNode.parent = null;
  517. transformNode.computeWorldMatrix(true);
  518. }
  519. }
  520. this.parent = null;
  521. // Callback
  522. this.onDisposeObservable.notifyObservers(this);
  523. this.onDisposeObservable.clear();
  524. // Behaviors
  525. for (var behavior of this._behaviors) {
  526. behavior.detach();
  527. }
  528. this._behaviors = [];
  529. this._isDisposed = true;
  530. }
  531. /**
  532. * Parse animation range data from a serialization object and store them into a given node
  533. * @param node defines where to store the animation ranges
  534. * @param parsedNode defines the serialization object to read data from
  535. * @param scene defines the hosting scene
  536. */
  537. public static ParseAnimationRanges(node: Node, parsedNode: any, scene: Scene): void {
  538. if (parsedNode.ranges) {
  539. for (var index = 0; index < parsedNode.ranges.length; index++) {
  540. var data = parsedNode.ranges[index];
  541. node.createAnimationRange(data.name, data.from, data.to);
  542. }
  543. }
  544. }
  545. }
  546. }