Node.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569
  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. /// Reset all local transformations.
  294. /// </summary>
  295. public void ResetTransformations()
  296. {
  297. _transformations = new Transformations();
  298. OnTransformationsSet();
  299. }
  300. /// <summary>
  301. /// Get / Set the order in which we apply local transformations in this node.
  302. /// </summary>
  303. public TransformOrder TransformationsOrder
  304. {
  305. get { return _transformationsOrder; }
  306. set { _transformationsOrder = value; OnTransformationsSet(); }
  307. }
  308. /// <summary>
  309. /// Get / Set the order in which we apply local rotation in this node.
  310. /// </summary>
  311. public RotationOrder RotationOrder
  312. {
  313. get { return _rotationOrder; }
  314. set { _rotationOrder = value; OnTransformationsSet(); }
  315. }
  316. /// <summary>
  317. /// Get / Set node local position.
  318. /// </summary>
  319. public Vector3 Position
  320. {
  321. get { return _transformations.Position; }
  322. set { _transformations.Position = value; OnTransformationsSet(); }
  323. }
  324. /// <summary>
  325. /// Get / Set node local scale.
  326. /// </summary>
  327. public Vector3 Scale
  328. {
  329. get { return _transformations.Scale; }
  330. set { _transformations.Scale = value; OnTransformationsSet(); }
  331. }
  332. /// <summary>
  333. /// Get / Set node local rotation.
  334. /// </summary>
  335. public Vector3 Rotation
  336. {
  337. get { return _transformations.Rotation; }
  338. set { _transformations.Rotation = value; OnTransformationsSet(); }
  339. }
  340. /// <summary>
  341. /// Alias to access rotation X directly.
  342. /// </summary>
  343. public float RotationX
  344. {
  345. get { return _transformations.Rotation.X; }
  346. set { _transformations.Rotation.X = value; OnTransformationsSet(); }
  347. }
  348. /// <summary>
  349. /// Alias to access rotation Y directly.
  350. /// </summary>
  351. public float RotationY
  352. {
  353. get { return _transformations.Rotation.Y; }
  354. set { _transformations.Rotation.Y = value; OnTransformationsSet(); }
  355. }
  356. /// <summary>
  357. /// Alias to access rotation Z directly.
  358. /// </summary>
  359. public float RotationZ
  360. {
  361. get { return _transformations.Rotation.Z; }
  362. set { _transformations.Rotation.Z = value; OnTransformationsSet(); }
  363. }
  364. /// <summary>
  365. /// Alias to access scale X directly.
  366. /// </summary>
  367. public float ScaleX
  368. {
  369. get { return _transformations.Scale.X; }
  370. set { _transformations.Scale.X = value; OnTransformationsSet(); }
  371. }
  372. /// <summary>
  373. /// Alias to access scale Y directly.
  374. /// </summary>
  375. public float ScaleY
  376. {
  377. get { return _transformations.Scale.Y; }
  378. set { _transformations.Scale.Y = value; OnTransformationsSet(); }
  379. }
  380. /// <summary>
  381. /// Alias to access scale Z directly.
  382. /// </summary>
  383. public float ScaleZ
  384. {
  385. get { return _transformations.Scale.Z; }
  386. set { _transformations.Scale.Z = value; OnTransformationsSet(); }
  387. }
  388. /// <summary>
  389. /// Alias to access position X directly.
  390. /// </summary>
  391. public float PositionX
  392. {
  393. get { return _transformations.Position.X; }
  394. set { _transformations.Position.X = value; OnTransformationsSet(); }
  395. }
  396. /// <summary>
  397. /// Alias to access position Y directly.
  398. /// </summary>
  399. public float PositionY
  400. {
  401. get { return _transformations.Position.Y; }
  402. set { _transformations.Position.Y = value; OnTransformationsSet(); }
  403. }
  404. /// <summary>
  405. /// Alias to access position Z directly.
  406. /// </summary>
  407. public float PositionZ
  408. {
  409. get { return _transformations.Position.Z; }
  410. set { _transformations.Position.Z = value; OnTransformationsSet(); }
  411. }
  412. /// <summary>
  413. /// Move position by vector.
  414. /// </summary>
  415. /// <param name="moveBy">Vector to translate by.</param>
  416. public void Translate(Vector3 moveBy)
  417. {
  418. _transformations.Position += moveBy;
  419. OnTransformationsSet();
  420. }
  421. /// <summary>
  422. /// Called every time one of the child nodes recalculate world transformations.
  423. /// </summary>
  424. /// <param name="node">The child node that updated.</param>
  425. public virtual void OnChildWorldMatrixChange(Node node)
  426. {
  427. }
  428. /// <summary>
  429. /// Return true if this node is empty.
  430. /// </summary>
  431. public bool Empty
  432. {
  433. get { return _childEntities.Count == 0 && _childNodes.Count == 0; }
  434. }
  435. /// <summary>
  436. /// Get bounding box of this node and all its child nodes.
  437. /// </summary>
  438. /// <param name="includeChildNodes">If true, will include bounding box of child nodes. If false, only of entities directly attached to this node.</param>
  439. /// <returns>Bounding box of the node and its children.</returns>
  440. public virtual BoundingBox GetBoundingBox(bool includeChildNodes = true)
  441. {
  442. // if empty skip
  443. if (Empty)
  444. {
  445. return EmptyBoundingBox;
  446. }
  447. // make sure transformations are up-to-date
  448. UpdateTransformations();
  449. // list of points to build bounding box from
  450. List<Vector3> corners = new List<Vector3>();
  451. // apply all child nodes bounding boxes
  452. if (includeChildNodes)
  453. {
  454. foreach (Node child in _childNodes)
  455. {
  456. // skip invisible nodes
  457. if (!child.Visible)
  458. {
  459. continue;
  460. }
  461. // get bounding box
  462. BoundingBox currBox = child.GetBoundingBox();
  463. if (currBox.Min != currBox.Max)
  464. {
  465. corners.Add(currBox.Min);
  466. corners.Add(currBox.Max);
  467. }
  468. }
  469. }
  470. // apply all entities directly under this node
  471. foreach (IEntity entity in _childEntities)
  472. {
  473. // skip invisible entities
  474. if (!entity.Visible)
  475. {
  476. continue;
  477. }
  478. // get entity bounding box
  479. BoundingBox currBox = entity.GetBoundingBox(this, _localTransform, _worldTransform);
  480. if (currBox.Min != currBox.Max)
  481. {
  482. corners.Add(currBox.Min);
  483. corners.Add(currBox.Max);
  484. }
  485. }
  486. // nothing in this node?
  487. if (corners.Count == 0)
  488. {
  489. return EmptyBoundingBox;
  490. }
  491. // return final bounding box
  492. return BoundingBox.CreateFromPoints(corners);
  493. }
  494. }
  495. }