Node.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632
  1. #region File Description
  2. //-----------------------------------------------------------------------------
  3. // A node is the basic container in the scene graph. Its basically a point in
  4. // transformations that can contain child nodes (and inherit transformations),
  5. // and contain renderable entities to draw inside.
  6. //
  7. // Author: Ronen Ness.
  8. // Since: 2017.
  9. //-----------------------------------------------------------------------------
  10. #endregion
  11. using Microsoft.Xna.Framework;
  12. using System.Collections.Generic;
  13. namespace MonoGameSceneGraph
  14. {
  15. /// <summary>
  16. /// A node with transformations, you can attach renderable entities to it, or append
  17. /// child nodes to inherit transformations.
  18. /// </summary>
  19. public class Node
  20. {
  21. /// <summary>
  22. /// Parent node.
  23. /// </summary>
  24. protected Node _parent = null;
  25. /// <summary>
  26. /// Node's transformations.
  27. /// </summary>
  28. protected Transformations _transformations = new Transformations();
  29. /// <summary>
  30. /// Is this node currently visible?
  31. /// </summary>
  32. public virtual bool Visible { get; set; }
  33. /// <summary>
  34. /// Optional identifier we can give to nodes.
  35. /// </summary>
  36. public string Identifier;
  37. /// <summary>
  38. /// Optional user data we can attach to nodes.
  39. /// </summary>
  40. public object UserData;
  41. /// <summary>
  42. /// Const return value for null bounding box.
  43. /// </summary>
  44. private static readonly BoundingBox EmptyBoundingBox = new BoundingBox();
  45. /// <summary>
  46. /// The order in which we apply transformations when building the matrix for this node.
  47. /// </summary>
  48. protected TransformOrder _transformationsOrder = TransformOrder.ScaleRotationPosition;
  49. /// <summary>
  50. /// The order in which we apply rotation when building the matrix for this node.
  51. /// </summary>
  52. protected RotationOrder _rotationOrder = RotationOrder.RotateYXZ;
  53. /// <summary>
  54. /// Local transformations matrix, eg the result of the current local transformations.
  55. /// </summary>
  56. protected Matrix _localTransform = Matrix.Identity;
  57. /// <summary>
  58. /// World transformations matrix, eg the result of the local transformations multiplied with parent transformations.
  59. /// </summary>
  60. protected Matrix _worldTransform = Matrix.Identity;
  61. /// <summary>
  62. /// Child nodes under this node.
  63. /// </summary>
  64. protected List<Node> _childNodes = new List<Node>();
  65. /// <summary>
  66. /// Child entities under this node.
  67. /// </summary>
  68. protected List<IEntity> _childEntities = new List<IEntity>();
  69. /// <summary>
  70. /// Turns true when the transformations of this node changes.
  71. /// </summary>
  72. protected bool _isDirty = true;
  73. /// <summary>
  74. /// This number increment every time we update transformations.
  75. /// We use it to check if our parent's transformations had been changed since last
  76. /// time this node was rendered, and if so, we re-apply parent updated transformations.
  77. /// </summary>
  78. protected uint _transformVersion = 0;
  79. /// <summary>
  80. /// The last transformations version we got from our parent.
  81. /// </summary>
  82. protected uint _parentLastTransformVersion = 0;
  83. /// <summary>
  84. /// Get parent node.
  85. /// </summary>
  86. public Node Parent { get { return _parent; } }
  87. /// <summary>
  88. /// Transformation version is a special identifier that changes whenever the world transformations
  89. /// of this node changes. Its not necessarily a sequence, but if you check this number for changes every
  90. /// frame its a good indication of transformation change.
  91. /// </summary>
  92. public uint TransformVersion { get { return _transformVersion; } }
  93. /// <summary>
  94. /// Create the new node.
  95. /// </summary>
  96. public Node()
  97. {
  98. Visible = true;
  99. }
  100. /// <summary>
  101. /// Draw the node and its children.
  102. /// </summary>
  103. public virtual void Draw()
  104. {
  105. // not visible? skip
  106. if (!Visible)
  107. {
  108. return;
  109. }
  110. // update transformations (only if needed, testing logic is inside)
  111. UpdateTransformations();
  112. // draw all child nodes
  113. foreach (Node node in _childNodes)
  114. {
  115. node.Draw();
  116. }
  117. // draw all child entities
  118. foreach (IEntity entity in _childEntities)
  119. {
  120. entity.Draw(this, _localTransform, _worldTransform);
  121. }
  122. }
  123. /// <summary>
  124. /// Add an entity to this node.
  125. /// </summary>
  126. /// <param name="entity">Entity to add.</param>
  127. public void AddEntity(IEntity entity)
  128. {
  129. _childEntities.Add(entity);
  130. }
  131. /// <summary>
  132. /// Remove an entity from this node.
  133. /// </summary>
  134. /// <param name="entity">Entity to add.</param>
  135. public void RemoveEntity(IEntity entity)
  136. {
  137. _childEntities.Remove(entity);
  138. }
  139. /// <summary>
  140. /// Add a child node to this node.
  141. /// </summary>
  142. /// <param name="node">Node to add.</param>
  143. public void AddChildNode(Node node)
  144. {
  145. // node already got a parent?
  146. if (node._parent != null)
  147. {
  148. throw new System.Exception("Can't add a node that already have a parent.");
  149. }
  150. // add node to children list
  151. _childNodes.Add(node);
  152. // set self as node's parent
  153. node.SetParent(this);
  154. }
  155. /// <summary>
  156. /// Remove a child node from this node.
  157. /// </summary>
  158. /// <param name="node">Node to add.</param>
  159. public void RemoveChildNode(Node node)
  160. {
  161. // make sure the node is a child of this node
  162. if (node._parent != this)
  163. {
  164. throw new System.Exception("Can't remove a node that don't belong to this parent.");
  165. }
  166. // remove node from children list
  167. _childNodes.Remove(node);
  168. // clear node parent
  169. node.SetParent(null);
  170. }
  171. /// <summary>
  172. /// Find and return first child node by identifier.
  173. /// </summary>
  174. /// <param name="identifier">Node identifier to search for.</param>
  175. /// <param name="searchInChildren">If true, will also search recurisvely in children.</param>
  176. /// <returns>Node with given identifier or null if not found.</returns>
  177. public Node FindChildNode(string identifier, bool searchInChildren = true)
  178. {
  179. foreach (Node node in _childNodes)
  180. {
  181. // search in direct children
  182. if (node.Identifier == identifier)
  183. {
  184. return node;
  185. }
  186. // recursive search
  187. if (searchInChildren)
  188. {
  189. Node foundInChild = node.FindChildNode(identifier, searchInChildren);
  190. if (foundInChild != null)
  191. {
  192. return foundInChild;
  193. }
  194. }
  195. }
  196. // if got here it means we didn't find any child node with given identifier
  197. return null;
  198. }
  199. /// <summary>
  200. /// Remove this node from its parent.
  201. /// </summary>
  202. public void RemoveFromParent()
  203. {
  204. // don't have a parent?
  205. if (_parent == null)
  206. {
  207. throw new System.Exception("Can't remove an orphan node from parent.");
  208. }
  209. // remove from parent
  210. _parent.RemoveChildNode(this);
  211. }
  212. /// <summary>
  213. /// Called when the world matrix of this node is actually recalculated (invoked after the calculation).
  214. /// </summary>
  215. protected virtual void OnWorldMatrixChange()
  216. {
  217. // update transformations version
  218. _transformVersion++;
  219. // notify parent
  220. if (_parent != null)
  221. {
  222. _parent.OnChildWorldMatrixChange(this);
  223. }
  224. }
  225. /// <summary>
  226. /// Called when local transformations are set, eg when Position, Rotation, Scale etc. is changed.
  227. /// We use this to set this node as "dirty", eg that we need to update local transformations.
  228. /// </summary>
  229. protected virtual void OnTransformationsSet()
  230. {
  231. _isDirty = true;
  232. }
  233. /// <summary>
  234. /// Set the parent of this node.
  235. /// </summary>
  236. /// <param name="newParent">New parent node to set, or null for no parent.</param>
  237. protected virtual void SetParent(Node newParent)
  238. {
  239. // set parent
  240. _parent = newParent;
  241. // set our parents last transformations version to make sure we'll update world transformations next frame.
  242. _parentLastTransformVersion = newParent != null ? newParent._transformVersion - 1 : 1;
  243. }
  244. /// <summary>
  245. /// Calc final transformations for current frame.
  246. /// This uses an indicator to know if an update is needed, so no harm is done if you call it multiple times.
  247. /// </summary>
  248. protected virtual void UpdateTransformations()
  249. {
  250. // if local transformations are dirty, we need to update them
  251. if (_isDirty)
  252. {
  253. _localTransform = _transformations.BuildMatrix(_transformationsOrder, _rotationOrder);
  254. }
  255. // if local transformations are dirty, or parent transformations are out-of-date, update world transformations
  256. if (_isDirty ||
  257. (_parent != null && _parentLastTransformVersion != _parent._transformVersion) ||
  258. (_parent == null && _parentLastTransformVersion != 0))
  259. {
  260. // if we got parent, apply its transformations
  261. if (_parent != null)
  262. {
  263. _worldTransform = _localTransform * _parent._worldTransform;
  264. _parentLastTransformVersion = _parent._transformVersion;
  265. }
  266. // if not, world transformations are the same as local, and reset parent last transformations version
  267. else
  268. {
  269. _worldTransform = _localTransform;
  270. _parentLastTransformVersion = 0;
  271. }
  272. // called the function that mark world matrix change (increase transformation version etc)
  273. OnWorldMatrixChange();
  274. }
  275. // no longer dirty
  276. _isDirty = false;
  277. }
  278. /// <summary>
  279. /// Return local transformations matrix (note: will recalculate if needed).
  280. /// </summary>
  281. public Matrix LocalTransformations
  282. {
  283. get { UpdateTransformations(); return _localTransform; }
  284. }
  285. /// <summary>
  286. /// Return world transformations matrix (note: will recalculate if needed).
  287. /// </summary>
  288. public Matrix WorldTransformations
  289. {
  290. get { UpdateTransformations(); return _worldTransform; }
  291. }
  292. /// <summary>
  293. /// Get position in world space.
  294. /// </summary>
  295. /// <remarks>Naive implementation using world matrix decompose. For better performance, override this with your own cached version.</remarks>
  296. public virtual Vector3 WorldPosition
  297. {
  298. get
  299. {
  300. Vector3 pos; Vector3 scale; Quaternion rot;
  301. WorldTransformations.Decompose(out scale, out rot, out pos);
  302. return pos;
  303. }
  304. }
  305. /// <summary>
  306. /// Get Rotastion in world space.
  307. /// </summary>
  308. /// <remarks>Naive implementation using world matrix decompose. For better performance, override this with your own cached version.</remarks>
  309. public virtual Quaternion WorldRotation
  310. {
  311. get
  312. {
  313. Vector3 pos; Vector3 scale; Quaternion rot;
  314. WorldTransformations.Decompose(out scale, out rot, out pos);
  315. return rot;
  316. }
  317. }
  318. /// <summary>
  319. /// Get Scale in world space.
  320. /// </summary>
  321. /// <remarks>Naive implementation using world matrix decompose. For better performance, override this with your own cached version.</remarks>
  322. public virtual Vector3 WorldScale
  323. {
  324. get
  325. {
  326. Vector3 pos; Vector3 scale; Quaternion rot;
  327. WorldTransformations.Decompose(out scale, out rot, out pos);
  328. return scale;
  329. }
  330. }
  331. /// <summary>
  332. /// Force update transformations for this node and its children.
  333. /// </summary>
  334. public void ForceUpdate()
  335. {
  336. // not visible? skip
  337. if (!Visible)
  338. {
  339. return;
  340. }
  341. // update transformations (only if needed, testing logic is inside)
  342. UpdateTransformations();
  343. // draw all child nodes
  344. foreach (Node node in _childNodes)
  345. {
  346. node.ForceUpdate();
  347. }
  348. }
  349. /// <summary>
  350. /// Reset all local transformations.
  351. /// </summary>
  352. public void ResetTransformations()
  353. {
  354. _transformations = new Transformations();
  355. OnTransformationsSet();
  356. }
  357. /// <summary>
  358. /// Get / Set the order in which we apply local transformations in this node.
  359. /// </summary>
  360. public TransformOrder TransformationsOrder
  361. {
  362. get { return _transformationsOrder; }
  363. set { _transformationsOrder = value; OnTransformationsSet(); }
  364. }
  365. /// <summary>
  366. /// Get / Set the order in which we apply local rotation in this node.
  367. /// </summary>
  368. public RotationOrder RotationOrder
  369. {
  370. get { return _rotationOrder; }
  371. set { _rotationOrder = value; OnTransformationsSet(); }
  372. }
  373. /// <summary>
  374. /// Get / Set node local position.
  375. /// </summary>
  376. public Vector3 Position
  377. {
  378. get { return _transformations.Position; }
  379. set { _transformations.Position = value; OnTransformationsSet(); }
  380. }
  381. /// <summary>
  382. /// Get / Set node local scale.
  383. /// </summary>
  384. public Vector3 Scale
  385. {
  386. get { return _transformations.Scale; }
  387. set { _transformations.Scale = value; OnTransformationsSet(); }
  388. }
  389. /// <summary>
  390. /// Get / Set node local rotation.
  391. /// </summary>
  392. public Vector3 Rotation
  393. {
  394. get { return _transformations.Rotation; }
  395. set { _transformations.Rotation = value; OnTransformationsSet(); }
  396. }
  397. /// <summary>
  398. /// Alias to access rotation X directly.
  399. /// </summary>
  400. public float RotationX
  401. {
  402. get { return _transformations.Rotation.X; }
  403. set { _transformations.Rotation.X = value; OnTransformationsSet(); }
  404. }
  405. /// <summary>
  406. /// Alias to access rotation Y directly.
  407. /// </summary>
  408. public float RotationY
  409. {
  410. get { return _transformations.Rotation.Y; }
  411. set { _transformations.Rotation.Y = value; OnTransformationsSet(); }
  412. }
  413. /// <summary>
  414. /// Alias to access rotation Z directly.
  415. /// </summary>
  416. public float RotationZ
  417. {
  418. get { return _transformations.Rotation.Z; }
  419. set { _transformations.Rotation.Z = value; OnTransformationsSet(); }
  420. }
  421. /// <summary>
  422. /// Alias to access scale X directly.
  423. /// </summary>
  424. public float ScaleX
  425. {
  426. get { return _transformations.Scale.X; }
  427. set { _transformations.Scale.X = value; OnTransformationsSet(); }
  428. }
  429. /// <summary>
  430. /// Alias to access scale Y directly.
  431. /// </summary>
  432. public float ScaleY
  433. {
  434. get { return _transformations.Scale.Y; }
  435. set { _transformations.Scale.Y = value; OnTransformationsSet(); }
  436. }
  437. /// <summary>
  438. /// Alias to access scale Z directly.
  439. /// </summary>
  440. public float ScaleZ
  441. {
  442. get { return _transformations.Scale.Z; }
  443. set { _transformations.Scale.Z = value; OnTransformationsSet(); }
  444. }
  445. /// <summary>
  446. /// Alias to access position X directly.
  447. /// </summary>
  448. public float PositionX
  449. {
  450. get { return _transformations.Position.X; }
  451. set { _transformations.Position.X = value; OnTransformationsSet(); }
  452. }
  453. /// <summary>
  454. /// Alias to access position Y directly.
  455. /// </summary>
  456. public float PositionY
  457. {
  458. get { return _transformations.Position.Y; }
  459. set { _transformations.Position.Y = value; OnTransformationsSet(); }
  460. }
  461. /// <summary>
  462. /// Alias to access position Z directly.
  463. /// </summary>
  464. public float PositionZ
  465. {
  466. get { return _transformations.Position.Z; }
  467. set { _transformations.Position.Z = value; OnTransformationsSet(); }
  468. }
  469. /// <summary>
  470. /// Move position by vector.
  471. /// </summary>
  472. /// <param name="moveBy">Vector to translate by.</param>
  473. public void Translate(Vector3 moveBy)
  474. {
  475. _transformations.Position += moveBy;
  476. OnTransformationsSet();
  477. }
  478. /// <summary>
  479. /// Called every time one of the child nodes recalculate world transformations.
  480. /// </summary>
  481. /// <param name="node">The child node that updated.</param>
  482. public virtual void OnChildWorldMatrixChange(Node node)
  483. {
  484. }
  485. /// <summary>
  486. /// Return true if this node is empty.
  487. /// </summary>
  488. public bool Empty
  489. {
  490. get { return _childEntities.Count == 0 && _childNodes.Count == 0; }
  491. }
  492. /// <summary>
  493. /// Get bounding box of this node and all its child nodes.
  494. /// </summary>
  495. /// <param name="includeChildNodes">If true, will include bounding box of child nodes. If false, only of entities directly attached to this node.</param>
  496. /// <returns>Bounding box of the node and its children.</returns>
  497. public virtual BoundingBox GetBoundingBox(bool includeChildNodes = true)
  498. {
  499. // if empty skip
  500. if (Empty)
  501. {
  502. return EmptyBoundingBox;
  503. }
  504. // make sure transformations are up-to-date
  505. UpdateTransformations();
  506. // list of points to build bounding box from
  507. List<Vector3> corners = new List<Vector3>();
  508. // apply all child nodes bounding boxes
  509. if (includeChildNodes)
  510. {
  511. foreach (Node child in _childNodes)
  512. {
  513. // skip invisible nodes
  514. if (!child.Visible)
  515. {
  516. continue;
  517. }
  518. // get bounding box
  519. BoundingBox currBox = child.GetBoundingBox();
  520. if (currBox.Min != currBox.Max)
  521. {
  522. corners.Add(currBox.Min);
  523. corners.Add(currBox.Max);
  524. }
  525. }
  526. }
  527. // apply all entities directly under this node
  528. foreach (IEntity entity in _childEntities)
  529. {
  530. // skip invisible entities
  531. if (!entity.Visible)
  532. {
  533. continue;
  534. }
  535. // get entity bounding box
  536. BoundingBox currBox = entity.GetBoundingBox(this, _localTransform, _worldTransform);
  537. if (currBox.Min != currBox.Max)
  538. {
  539. corners.Add(currBox.Min);
  540. corners.Add(currBox.Max);
  541. }
  542. }
  543. // nothing in this node?
  544. if (corners.Count == 0)
  545. {
  546. return EmptyBoundingBox;
  547. }
  548. // return final bounding box
  549. return BoundingBox.CreateFromPoints(corners);
  550. }
  551. }
  552. }