babylon.node.ts 26 KB

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