Node.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  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 bool IsVisible = true;
  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. /// The order in which we apply transformations when building the matrix for this node.
  43. /// </summary>
  44. protected TransformOrder _transformationsOrder = TransformOrder.ScaleRotationPosition;
  45. /// <summary>
  46. /// The order in which we apply rotation when building the matrix for this node.
  47. /// </summary>
  48. protected RotationOrder _rotationOrder = RotationOrder.RotateYXZ;
  49. /// <summary>
  50. /// Local transformations matrix, eg the result of the current local transformations.
  51. /// </summary>
  52. protected Matrix _localTransform = Matrix.Identity;
  53. /// <summary>
  54. /// World transformations matrix, eg the result of the local transformations multiplied with parent transformations.
  55. /// </summary>
  56. protected Matrix _worldTransform = Matrix.Identity;
  57. /// <summary>
  58. /// Child nodes under this node.
  59. /// </summary>
  60. protected List<Node> _childNodes = new List<Node>();
  61. /// <summary>
  62. /// Child entities under this node.
  63. /// </summary>
  64. protected List<IEntity> _childEntities = new List<IEntity>();
  65. /// <summary>
  66. /// Turns true when the transformations of this node changes.
  67. /// </summary>
  68. protected bool _isDirty = true;
  69. /// <summary>
  70. /// This number increment every time we update transformations.
  71. /// We use it to check if our parent's transformations had been changed since last
  72. /// time this node was rendered, and if so, we re-apply parent updated transformations.
  73. /// </summary>
  74. protected uint _transformVersion = 0;
  75. /// <summary>
  76. /// The last transformations version we got from our parent.
  77. /// </summary>
  78. protected uint _parentLastTransformVersion = 0;
  79. /// <summary>
  80. /// Get parent node.
  81. /// </summary>
  82. public Node Parent { get { return _parent; } }
  83. /// <summary>
  84. /// Transformation version is a special identifier that changes whenever the world transformations
  85. /// of this node changes. Its not necessarily a sequence, but if you check this number for changes every
  86. /// frame its a good indication of transformation change.
  87. /// </summary>
  88. public uint TransformVersion { get { return _transformVersion; } }
  89. /// <summary>
  90. /// Draw the node and its children.
  91. /// </summary>
  92. public virtual void Draw()
  93. {
  94. // not visible? skip
  95. if (!IsVisible)
  96. {
  97. return;
  98. }
  99. // update transformations (only if needed, testing logic is inside)
  100. UpdateTransformations();
  101. // draw all child nodes
  102. foreach (Node node in _childNodes)
  103. {
  104. node.Draw();
  105. }
  106. // draw all child entities
  107. foreach (IEntity entity in _childEntities)
  108. {
  109. entity.Draw(this, _localTransform, _worldTransform);
  110. }
  111. }
  112. /// <summary>
  113. /// Add an entity to this node.
  114. /// </summary>
  115. /// <param name="entity">Entity to add.</param>
  116. public void AddEntity(IEntity entity)
  117. {
  118. _childEntities.Add(entity);
  119. }
  120. /// <summary>
  121. /// Remove an entity from this node.
  122. /// </summary>
  123. /// <param name="entity">Entity to add.</param>
  124. public void RemoveEntity(IEntity entity)
  125. {
  126. _childEntities.Remove(entity);
  127. }
  128. /// <summary>
  129. /// Add a child node to this node.
  130. /// </summary>
  131. /// <param name="node">Node to add.</param>
  132. public void AddChildNode(Node node)
  133. {
  134. // node already got a parent?
  135. if (node._parent != null)
  136. {
  137. throw new System.Exception("Can't add a node that already have a parent.");
  138. }
  139. // add node to children list
  140. _childNodes.Add(node);
  141. // set self as node's parent
  142. node.SetParent(this);
  143. }
  144. /// <summary>
  145. /// Remove a child node from this node.
  146. /// </summary>
  147. /// <param name="node">Node to add.</param>
  148. public void RemoveChildNode(Node node)
  149. {
  150. // make sure the node is a child of this node
  151. if (node._parent != this)
  152. {
  153. throw new System.Exception("Can't remove a node that don't belong to this parent.");
  154. }
  155. // remove node from children list
  156. _childNodes.Remove(node);
  157. // clear node parent
  158. node.SetParent(null);
  159. }
  160. /// <summary>
  161. /// Find and return first child node by identifier.
  162. /// </summary>
  163. /// <param name="identifier">Node identifier to search for.</param>
  164. /// <param name="searchInChildren">If true, will also search recurisvely in children.</param>
  165. /// <returns>Node with given identifier or null if not found.</returns>
  166. public Node FindChildNode(string identifier, bool searchInChildren = true)
  167. {
  168. foreach (Node node in _childNodes)
  169. {
  170. // search in direct children
  171. if (node.Identifier == identifier)
  172. {
  173. return node;
  174. }
  175. // recursive search
  176. if (searchInChildren)
  177. {
  178. Node foundInChild = node.FindChildNode(identifier, searchInChildren);
  179. if (foundInChild != null)
  180. {
  181. return foundInChild;
  182. }
  183. }
  184. }
  185. // if got here it means we didn't find any child node with given identifier
  186. return null;
  187. }
  188. /// <summary>
  189. /// Remove this node from its parent.
  190. /// </summary>
  191. public void RemoveFromParent()
  192. {
  193. // don't have a parent?
  194. if (_parent == null)
  195. {
  196. throw new System.Exception("Can't remove an orphan node from parent.");
  197. }
  198. // remove from parent
  199. _parent.RemoveChildNode(this);
  200. }
  201. /// <summary>
  202. /// Called when the world matrix of this node is actually recalculated (invoked after the calculation).
  203. /// </summary>
  204. protected virtual void OnWorldMatrixChange()
  205. {
  206. // update transformations version
  207. _transformVersion++;
  208. // notify parent
  209. if (_parent != null)
  210. {
  211. _parent.OnChildWorldMatrixChange(this);
  212. }
  213. }
  214. /// <summary>
  215. /// Called when local transformations are set, eg when Position, Rotation, Scale etc. is changed.
  216. /// We use this to set this node as "dirty", eg that we need to update local transformations.
  217. /// </summary>
  218. protected virtual void OnTransformationsSet()
  219. {
  220. _isDirty = true;
  221. }
  222. /// <summary>
  223. /// Set the parent of this node.
  224. /// </summary>
  225. /// <param name="newParent">New parent node to set, or null for no parent.</param>
  226. protected virtual void SetParent(Node newParent)
  227. {
  228. // set parent
  229. _parent = newParent;
  230. // set our parents last transformations version to make sure we'll update world transformations next frame.
  231. _parentLastTransformVersion = newParent != null ? newParent._transformVersion - 1 : 1;
  232. }
  233. /// <summary>
  234. /// Calc final transformations for current frame.
  235. /// This uses an indicator to know if an update is needed, so no harm is done if you call it multiple times.
  236. /// </summary>
  237. protected virtual void UpdateTransformations()
  238. {
  239. // if local transformations are dirty, we need to update them
  240. if (_isDirty)
  241. {
  242. _localTransform = _transformations.BuildMatrix(_transformationsOrder, _rotationOrder);
  243. }
  244. // if local transformations are dirty, or parent transformations are out-of-date, update world transformations
  245. if (_isDirty ||
  246. (_parent != null && _parentLastTransformVersion != _parent._transformVersion) ||
  247. (_parent == null && _parentLastTransformVersion != 0))
  248. {
  249. // if we got parent, apply its transformations
  250. if (_parent != null)
  251. {
  252. _worldTransform = _localTransform * _parent._worldTransform;
  253. _parentLastTransformVersion = _parent._transformVersion;
  254. }
  255. // if not, world transformations are the same as local, and reset parent last transformations version
  256. else
  257. {
  258. _worldTransform = _localTransform;
  259. _parentLastTransformVersion = 0;
  260. }
  261. // called the function that mark world matrix change (increase transformation version etc)
  262. OnWorldMatrixChange();
  263. }
  264. // no longer dirty
  265. _isDirty = false;
  266. }
  267. /// <summary>
  268. /// Return local transformations matrix (note: will recalculate if needed).
  269. /// </summary>
  270. public Matrix LocalTransformations
  271. {
  272. get { UpdateTransformations(); return _localTransform; }
  273. }
  274. /// <summary>
  275. /// Return world transformations matrix (note: will recalculate if needed).
  276. /// </summary>
  277. public Matrix WorldTransformations
  278. {
  279. get { UpdateTransformations(); return _worldTransform; }
  280. }
  281. /// <summary>
  282. /// Reset all local transformations.
  283. /// </summary>
  284. public void ResetTransformations()
  285. {
  286. _transformations = new Transformations();
  287. OnTransformationsSet();
  288. }
  289. /// <summary>
  290. /// Get / Set the order in which we apply local transformations in this node.
  291. /// </summary>
  292. public TransformOrder TransformationsOrder
  293. {
  294. get { return _transformationsOrder; }
  295. set { _transformationsOrder = value; OnTransformationsSet(); }
  296. }
  297. /// <summary>
  298. /// Get / Set the order in which we apply local rotation in this node.
  299. /// </summary>
  300. public RotationOrder RotationOrder
  301. {
  302. get { return _rotationOrder; }
  303. set { _rotationOrder = value; OnTransformationsSet(); }
  304. }
  305. /// <summary>
  306. /// Get / Set node local position.
  307. /// </summary>
  308. public Vector3 Position
  309. {
  310. get { return _transformations.Position; }
  311. set { _transformations.Position = value; OnTransformationsSet(); }
  312. }
  313. /// <summary>
  314. /// Get / Set node local scale.
  315. /// </summary>
  316. public Vector3 Scale
  317. {
  318. get { return _transformations.Scale; }
  319. set { _transformations.Scale = value; OnTransformationsSet(); }
  320. }
  321. /// <summary>
  322. /// Get / Set node local rotation.
  323. /// </summary>
  324. public Vector3 Rotation
  325. {
  326. get { return _transformations.Rotation; }
  327. set { _transformations.Rotation = value; OnTransformationsSet(); }
  328. }
  329. /// <summary>
  330. /// Alias to access rotation X directly.
  331. /// </summary>
  332. public float RotationX
  333. {
  334. get { return _transformations.Rotation.X; }
  335. set { _transformations.Rotation.X = value; OnTransformationsSet(); }
  336. }
  337. /// <summary>
  338. /// Alias to access rotation Y directly.
  339. /// </summary>
  340. public float RotationY
  341. {
  342. get { return _transformations.Rotation.Y; }
  343. set { _transformations.Rotation.Y = value; OnTransformationsSet(); }
  344. }
  345. /// <summary>
  346. /// Alias to access rotation Z directly.
  347. /// </summary>
  348. public float RotationZ
  349. {
  350. get { return _transformations.Rotation.Z; }
  351. set { _transformations.Rotation.Z = value; OnTransformationsSet(); }
  352. }
  353. /// <summary>
  354. /// Alias to access scale X directly.
  355. /// </summary>
  356. public float ScaleX
  357. {
  358. get { return _transformations.Scale.X; }
  359. set { _transformations.Scale.X = value; OnTransformationsSet(); }
  360. }
  361. /// <summary>
  362. /// Alias to access scale Y directly.
  363. /// </summary>
  364. public float ScaleY
  365. {
  366. get { return _transformations.Scale.Y; }
  367. set { _transformations.Scale.Y = value; OnTransformationsSet(); }
  368. }
  369. /// <summary>
  370. /// Alias to access scale Z directly.
  371. /// </summary>
  372. public float ScaleZ
  373. {
  374. get { return _transformations.Scale.Z; }
  375. set { _transformations.Scale.Z = value; OnTransformationsSet(); }
  376. }
  377. /// <summary>
  378. /// Alias to access position X directly.
  379. /// </summary>
  380. public float PositionX
  381. {
  382. get { return _transformations.Position.X; }
  383. set { _transformations.Position.X = value; OnTransformationsSet(); }
  384. }
  385. /// <summary>
  386. /// Alias to access position Y directly.
  387. /// </summary>
  388. public float PositionY
  389. {
  390. get { return _transformations.Position.Y; }
  391. set { _transformations.Position.Y = value; OnTransformationsSet(); }
  392. }
  393. /// <summary>
  394. /// Alias to access position Z directly.
  395. /// </summary>
  396. public float PositionZ
  397. {
  398. get { return _transformations.Position.Z; }
  399. set { _transformations.Position.Z = value; OnTransformationsSet(); }
  400. }
  401. /// <summary>
  402. /// Move position by vector.
  403. /// </summary>
  404. /// <param name="moveBy">Vector to translate by.</param>
  405. public void Translate(Vector3 moveBy)
  406. {
  407. _transformations.Position += moveBy;
  408. OnTransformationsSet();
  409. }
  410. /// <summary>
  411. /// Called every time one of the child nodes recalculate world transformations.
  412. /// </summary>
  413. /// <param name="node">The child node that updated.</param>
  414. public virtual void OnChildWorldMatrixChange(Node node)
  415. {
  416. }
  417. /// <summary>
  418. /// Get bounding box of this node and all its child nodes.
  419. /// </summary>
  420. /// <param name="includeChildNodes">If true, will include bounding box of child nodes. If false, only of entities directly attached to this node.</param>
  421. /// <returns>Bounding box of the node and its children.</returns>
  422. public virtual BoundingBox GetBoundingBox(bool includeChildNodes = true)
  423. {
  424. // make sure transformations are up-to-date
  425. UpdateTransformations();
  426. // initialize minimum and maximum corners of the bounding box to max and min values
  427. Vector3 min = new Vector3(float.MaxValue, float.MaxValue, float.MaxValue);
  428. Vector3 max = new Vector3(float.MinValue, float.MinValue, float.MinValue);
  429. // apply all child nodes bounding boxes
  430. if (includeChildNodes)
  431. {
  432. foreach (Node child in _childNodes)
  433. {
  434. BoundingBox curr = child.GetBoundingBox();
  435. min = Vector3.Min(min, curr.Min);
  436. max = Vector3.Max(max, curr.Max);
  437. }
  438. }
  439. // apply all entities directly under this node
  440. foreach (IEntity entity in _childEntities)
  441. {
  442. BoundingBox curr = entity.GetBoundingBox(this, _localTransform, _worldTransform);
  443. min = Vector3.Min(min, curr.Min);
  444. max = Vector3.Max(max, curr.Max);
  445. }
  446. // return final bounding box
  447. return new BoundingBox(min, max);
  448. }
  449. }
  450. }