babylon.node.ts 26 KB

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