babylon.node.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  1. module BABYLON {
  2. /**
  3. * Node is the basic class for all scene objects (Mesh, Light Camera).
  4. */
  5. export class Node {
  6. @serialize()
  7. public name: string;
  8. @serialize()
  9. public id: string;
  10. @serialize()
  11. public uniqueId: number;
  12. @serialize()
  13. public state = "";
  14. @serialize()
  15. public metadata: any = null;
  16. public doNotSerialize = false;
  17. public animations = new Array<Animation>();
  18. private _ranges: { [name: string]: Nullable<AnimationRange> } = {};
  19. public onReady: (node: Node) => void;
  20. private _isEnabled = true;
  21. private _isReady = true;
  22. public _currentRenderId = -1;
  23. private _parentRenderId = -1;
  24. public _waitingParentId: Nullable<string>;
  25. private _scene: Scene;
  26. public _cache: any;
  27. private _parentNode: Nullable<Node>;
  28. private _children: Node[];
  29. public set parent(parent: Nullable<Node>) {
  30. if (this._parentNode === parent) {
  31. return;
  32. }
  33. if (this._parentNode) {
  34. var index = this._parentNode._children.indexOf(this);
  35. if (index !== -1) {
  36. this._parentNode._children.splice(index, 1);
  37. }
  38. }
  39. this._parentNode = parent;
  40. if (this._parentNode) {
  41. if (!this._parentNode._children) {
  42. this._parentNode._children = new Array<Node>();
  43. }
  44. this._parentNode._children.push(this);
  45. }
  46. }
  47. public get parent(): Nullable<Node> {
  48. return this._parentNode;
  49. }
  50. public getClassName(): string {
  51. return "Node";
  52. }
  53. /**
  54. * An event triggered when the mesh is disposed.
  55. * @type {BABYLON.Observable}
  56. */
  57. public onDisposeObservable = new Observable<Node>();
  58. private _onDisposeObserver: Nullable<Observer<Node>>;
  59. public set onDispose(callback: () => void) {
  60. if (this._onDisposeObserver) {
  61. this.onDisposeObservable.remove(this._onDisposeObserver);
  62. }
  63. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  64. }
  65. /**
  66. * @constructor
  67. * @param {string} name - the name and id to be given to this node
  68. * @param {BABYLON.Scene} the scene this node will be added to
  69. */
  70. constructor(name: string, scene: Nullable<Scene> = null) {
  71. this.name = name;
  72. this.id = name;
  73. this._scene = <Scene>(scene || Engine.LastCreatedScene);
  74. this.uniqueId = this._scene.getUniqueId();
  75. this._initCache();
  76. }
  77. public getScene(): Scene {
  78. return this._scene;
  79. }
  80. public getEngine(): Engine {
  81. return this._scene.getEngine();
  82. }
  83. // Behaviors
  84. private _behaviors = new Array<Behavior<Node>>();
  85. public addBehavior(behavior: Behavior<Node>): Node {
  86. var index = this._behaviors.indexOf(behavior);
  87. if (index !== -1) {
  88. return this;
  89. }
  90. behavior.init();
  91. if (this._scene.isLoading) {
  92. // We defer the attach when the scene will be loaded
  93. var observer = this._scene.onDataLoadedObservable.add(() => {
  94. behavior.attach(this);
  95. setTimeout(() => {
  96. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  97. this._scene.onDataLoadedObservable.remove(observer);
  98. }, 0);
  99. });
  100. } else {
  101. behavior.attach(this);
  102. }
  103. this._behaviors.push(behavior);
  104. return this;
  105. }
  106. public removeBehavior(behavior: Behavior<Node>): Node {
  107. var index = this._behaviors.indexOf(behavior);
  108. if (index === -1) {
  109. return this;
  110. }
  111. this._behaviors[index].detach();
  112. this._behaviors.splice(index, 1);
  113. return this;
  114. }
  115. public get behaviors(): Behavior<Node>[] {
  116. return this._behaviors;
  117. }
  118. public getBehaviorByName(name: string): Nullable<Behavior<Node>> {
  119. for (var behavior of this._behaviors) {
  120. if (behavior.name === name) {
  121. return behavior;
  122. }
  123. }
  124. return null;
  125. }
  126. // override it in derived class
  127. public getWorldMatrix(): Matrix {
  128. return Matrix.Identity();
  129. }
  130. // override it in derived class if you add new variables to the cache
  131. // and call the parent class method
  132. public _initCache() {
  133. this._cache = {};
  134. this._cache.parent = undefined;
  135. }
  136. public updateCache(force?: boolean): void {
  137. if (!force && this.isSynchronized())
  138. return;
  139. this._cache.parent = this.parent;
  140. this._updateCache();
  141. }
  142. // override it in derived class if you add new variables to the cache
  143. // and call the parent class method if !ignoreParentClass
  144. public _updateCache(ignoreParentClass?: boolean): void {
  145. }
  146. // override it in derived class if you add new variables to the cache
  147. public _isSynchronized(): boolean {
  148. return true;
  149. }
  150. public _markSyncedWithParent() {
  151. if (this.parent) {
  152. this._parentRenderId = this.parent._currentRenderId;
  153. }
  154. }
  155. public isSynchronizedWithParent(): boolean {
  156. if (!this.parent) {
  157. return true;
  158. }
  159. if (this._parentRenderId !== this.parent._currentRenderId) {
  160. return false;
  161. }
  162. return this.parent.isSynchronized();
  163. }
  164. public isSynchronized(updateCache?: boolean): boolean {
  165. var check = this.hasNewParent();
  166. check = check || !this.isSynchronizedWithParent();
  167. check = check || !this._isSynchronized();
  168. if (updateCache)
  169. this.updateCache(true);
  170. return !check;
  171. }
  172. public hasNewParent(update?: boolean): boolean {
  173. if (this._cache.parent === this.parent)
  174. return false;
  175. if (update)
  176. this._cache.parent = this.parent;
  177. return true;
  178. }
  179. /**
  180. * Is this node ready to be used/rendered
  181. * @return {boolean} is it ready
  182. */
  183. public isReady(): boolean {
  184. return this._isReady;
  185. }
  186. /**
  187. * Is this node enabled.
  188. * If the node has a parent and is enabled, the parent will be inspected as well.
  189. * @return {boolean} whether this node (and its parent) is enabled.
  190. * @see setEnabled
  191. */
  192. public isEnabled(): boolean {
  193. if (!this._isEnabled) {
  194. return false;
  195. }
  196. if (this.parent) {
  197. return this.parent.isEnabled();
  198. }
  199. return true;
  200. }
  201. /**
  202. * Set the enabled state of this node.
  203. * @param {boolean} value - the new enabled state
  204. * @see isEnabled
  205. */
  206. public setEnabled(value: boolean): void {
  207. this._isEnabled = value;
  208. }
  209. /**
  210. * Is this node a descendant of the given node.
  211. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  212. * @param {BABYLON.Node} ancestor - The parent node to inspect
  213. * @see parent
  214. */
  215. public isDescendantOf(ancestor: Node): boolean {
  216. if (this.parent) {
  217. if (this.parent === ancestor) {
  218. return true;
  219. }
  220. return this.parent.isDescendantOf(ancestor);
  221. }
  222. return false;
  223. }
  224. /**
  225. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  226. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  227. * @param {boolean} directDescendantsOnly 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.
  228. * @param predicate: an optional predicate that will be called on every evaluated children, the predicate must return true for a given child to be part of the result, otherwise it will be ignored.
  229. */
  230. public _getDescendants(results: Node[], directDescendantsOnly: boolean = false, predicate?: (node: Node) => boolean): void {
  231. if (!this._children) {
  232. return;
  233. }
  234. for (var index = 0; index < this._children.length; index++) {
  235. var item = this._children[index];
  236. if (!predicate || predicate(item)) {
  237. results.push(item);
  238. }
  239. if (!directDescendantsOnly) {
  240. item._getDescendants(results, false, predicate);
  241. }
  242. }
  243. }
  244. /**
  245. * Will return all nodes that have this node as ascendant.
  246. * @param {boolean} directDescendantsOnly 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.
  247. * @param predicate: an optional predicate that will be called on every evaluated children, the predicate must return true for a given child to be part of the result, otherwise it will be ignored.
  248. * @return {BABYLON.Node[]} all children nodes of all types.
  249. */
  250. public getDescendants(directDescendantsOnly?: boolean, predicate?: (node: Node) => boolean): Node[] {
  251. var results = new Array<Node>();
  252. this._getDescendants(results, directDescendantsOnly, predicate);
  253. return results;
  254. }
  255. /**
  256. * Get all child-meshes of this node.
  257. */
  258. public getChildMeshes(directDescendantsOnly?: boolean, predicate?: (node: Node) => boolean): AbstractMesh[] {
  259. var results: Array<AbstractMesh> = [];
  260. this._getDescendants(results, directDescendantsOnly, (node: Node) => {
  261. return ((!predicate || predicate(node)) && (node instanceof AbstractMesh));
  262. });
  263. return results;
  264. }
  265. /**
  266. * Get all child-transformNodes of this node.
  267. */
  268. public getChildTransformNodes(directDescendantsOnly?: boolean, predicate?: (node: Node) => boolean): TransformNode[] {
  269. var results: Array<TransformNode> = [];
  270. this._getDescendants(results, directDescendantsOnly, (node: Node) => {
  271. return ((!predicate || predicate(node)) && (node instanceof TransformNode));
  272. });
  273. return results;
  274. }
  275. /**
  276. * Get all direct children of this node.
  277. */
  278. public getChildren(predicate?: (node: Node) => boolean): Node[] {
  279. return this.getDescendants(true, predicate);
  280. }
  281. public _setReady(state: boolean): void {
  282. if (state === this._isReady) {
  283. return;
  284. }
  285. if (!state) {
  286. this._isReady = false;
  287. return;
  288. }
  289. this._isReady = true;
  290. if (this.onReady) {
  291. this.onReady(this);
  292. }
  293. }
  294. public getAnimationByName(name: string): Nullable<Animation> {
  295. for (var i = 0; i < this.animations.length; i++) {
  296. var animation = this.animations[i];
  297. if (animation.name === name) {
  298. return animation;
  299. }
  300. }
  301. return null;
  302. }
  303. public createAnimationRange(name: string, from: number, to: number): void {
  304. // check name not already in use
  305. if (!this._ranges[name]) {
  306. this._ranges[name] = new AnimationRange(name, from, to);
  307. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  308. if (this.animations[i]) {
  309. this.animations[i].createRange(name, from, to);
  310. }
  311. }
  312. }
  313. }
  314. public deleteAnimationRange(name: string, deleteFrames = true): void {
  315. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  316. if (this.animations[i]) {
  317. this.animations[i].deleteRange(name, deleteFrames);
  318. }
  319. }
  320. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  321. }
  322. public getAnimationRange(name: string): Nullable<AnimationRange> {
  323. return this._ranges[name];
  324. }
  325. public beginAnimation(name: string, loop?: boolean, speedRatio?: number, onAnimationEnd?: () => void): void {
  326. var range = this.getAnimationRange(name);
  327. if (!range) {
  328. return;
  329. }
  330. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  331. }
  332. public serializeAnimationRanges(): any {
  333. var serializationRanges = [];
  334. for (var name in this._ranges) {
  335. var localRange = this._ranges[name];
  336. if (!localRange) {
  337. continue;
  338. }
  339. var range: any = {};
  340. range.name = name;
  341. range.from = localRange.from;
  342. range.to = localRange.to;
  343. serializationRanges.push(range);
  344. }
  345. return serializationRanges;
  346. }
  347. // override it in derived class
  348. public computeWorldMatrix(force?: boolean): Matrix {
  349. return Matrix.Identity();
  350. }
  351. public dispose(): void {
  352. this.parent = null;
  353. // Callback
  354. this.onDisposeObservable.notifyObservers(this);
  355. this.onDisposeObservable.clear();
  356. // Behaviors
  357. for (var behavior of this._behaviors) {
  358. behavior.detach();
  359. }
  360. this._behaviors = [];
  361. }
  362. public static ParseAnimationRanges(node: Node, parsedNode: any, scene: Scene): void {
  363. if (parsedNode.ranges) {
  364. for (var index = 0; index < parsedNode.ranges.length; index++) {
  365. var data = parsedNode.ranges[index];
  366. node.createAnimationRange(data.name, data.from, data.to);
  367. }
  368. }
  369. }
  370. }
  371. }