Node.h 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  1. //
  2. // Copyright (c) 2008-2013 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #pragma once
  23. #include "Matrix3x4.h"
  24. #include "Serializable.h"
  25. #include "VectorBuffer.h"
  26. namespace Urho3D
  27. {
  28. class Component;
  29. class Connection;
  30. class Scene;
  31. class SceneResolver;
  32. struct NodeReplicationState;
  33. /// Component and child node creation mode for networking.
  34. enum CreateMode
  35. {
  36. REPLICATED = 0,
  37. LOCAL = 1
  38. };
  39. /// %Scene node that may contain components and child nodes.
  40. class URHO3D_API Node : public Serializable
  41. {
  42. OBJECT(Node);
  43. friend class Connection;
  44. public:
  45. /// Construct.
  46. Node(Context* context);
  47. /// Destruct. Any child nodes are detached.
  48. virtual ~Node();
  49. /// Register object factory.
  50. static void RegisterObject(Context* context);
  51. /// Handle attribute write access.
  52. virtual void OnSetAttribute(const AttributeInfo& attr, const Variant& src);
  53. /// Load from binary data. Return true if successful.
  54. virtual bool Load(Deserializer& source, bool setInstanceDefault = false);
  55. /// Load from XML data. Return true if successful.
  56. virtual bool LoadXML(const XMLElement& source, bool setInstanceDefault = false);
  57. /// Save as binary data. Return true if successful.
  58. virtual bool Save(Serializer& dest) const;
  59. /// Save as XML data. Return true if successful.
  60. virtual bool SaveXML(XMLElement& dest) const;
  61. /// Apply attribute changes that can not be applied immediately recursively to child nodes and components.
  62. virtual void ApplyAttributes();
  63. /// Return whether should save default-valued attributes into XML. Always save node transforms for readability, even if identity.
  64. virtual bool SaveDefaultAttributes() const { return true; }
  65. /// Add a replication state that is tracking this node.
  66. virtual void AddReplicationState(NodeReplicationState* state);
  67. /// Save to an XML file. Return true if successful.
  68. bool SaveXML(Serializer& dest) const;
  69. /// Set name of the scene node. Names are not required to be unique.
  70. void SetName(const String& name);
  71. /// Set position in parent space. If the scene node is on the root level (is child of the scene itself), this is same as world space.
  72. void SetPosition(const Vector3& position);
  73. /// Set rotation in parent space.
  74. void SetRotation(const Quaternion& rotation);
  75. /// Set forward direction in parent space. Positive Z axis equals identity rotation.
  76. void SetDirection(const Vector3& direction);
  77. /// Set uniform scale in parent space.
  78. void SetScale(float scale);
  79. /// Set scale in parent space.
  80. void SetScale(const Vector3& scale);
  81. /// Set both position and rotation in parent space as an atomic operation. This is faster than setting position and rotation separately.
  82. void SetTransform(const Vector3& position, const Quaternion& rotation);
  83. /// Set both position, rotation and uniform scale in parent space as an atomic operation.
  84. void SetTransform(const Vector3& position, const Quaternion& rotation, float scale);
  85. /// Set both position, rotation and scale in parent space as an atomic operation.
  86. void SetTransform(const Vector3& position, const Quaternion& rotation, const Vector3& scale);
  87. /// Set position in world space.
  88. void SetWorldPosition(const Vector3& position);
  89. /// Set rotation in world space.
  90. void SetWorldRotation(const Quaternion& rotation);
  91. /// Set forward direction in world space.
  92. void SetWorldDirection(const Vector3& direction);
  93. /// Set uniform scale in world space.
  94. void SetWorldScale(float scale);
  95. /// Set scale in world space.
  96. void SetWorldScale(const Vector3& scale);
  97. /// Set both position and rotation in world space as an atomic operation.
  98. void SetWorldTransform(const Vector3& position, const Quaternion& rotation);
  99. /// Set both position, rotation and uniform scale in world space as an atomic operation.
  100. void SetWorldTransform(const Vector3& position, const Quaternion& rotation, float scale);
  101. /// Set both position, rotation and scale in world space as an atomic opration.
  102. void SetWorldTransform(const Vector3& position, const Quaternion& rotation, const Vector3& scale);
  103. /// Move the scene node in parent space, which is the same as world space if the scene node is on the root level.
  104. void Translate(const Vector3& delta);
  105. /// Move the scene node in parent space relative to its current rotation.
  106. void TranslateRelative(const Vector3& delta);
  107. /// Rotate the scene node in parent space either relative to its current rotation axes, or a fixed axis.
  108. void Rotate(const Quaternion& delta, bool fixedAxis = false);
  109. /// Rotate around the X axis.
  110. void Pitch(float angle, bool fixedAxis = false);
  111. /// Rotate around the Y axis.
  112. void Yaw(float angle, bool fixedAxis = false);
  113. /// Rotate around the Z axis.
  114. void Roll(float angle, bool fixedAxis = false);
  115. /// Look at a target world position.
  116. void LookAt(const Vector3& target, const Vector3& upAxis = Vector3::UP);
  117. /// Modify scale in parent space uniformly.
  118. void Scale(float scale);
  119. /// Modify scale in parent space.
  120. void Scale(const Vector3& scale);
  121. /// Set enabled/disabled state without recursion. Components in a disabled node become effectively disabled regardless of their own enable/disable state.
  122. void SetEnabled(bool enable);
  123. /// Set enabled/disabled state with optional recursion.
  124. void SetEnabled(bool enable, bool recursive);
  125. /// Set owner connection for networking.
  126. void SetOwner(Connection* owner);
  127. /// Mark node and child nodes to need world transform recalculation. Notify listener components.
  128. void MarkDirty();
  129. /// Create a child scene node (with specified ID if provided).
  130. Node* CreateChild(const String& name = String::EMPTY, CreateMode mode = REPLICATED, unsigned id = 0);
  131. /// Add a child scene node.
  132. void AddChild(Node* node);
  133. /// Remove a child scene node.
  134. void RemoveChild(Node* node);
  135. /// Remove all child scene nodes.
  136. void RemoveAllChildren();
  137. /// Remove child scene nodes that match criteria.
  138. void RemoveChildren(bool removeReplicated, bool removeLocal, bool recursive);
  139. /// Create a component to this node (with specified ID if provided).
  140. Component* CreateComponent(ShortStringHash type, CreateMode mode = REPLICATED, unsigned id = 0);
  141. /// Create a component to this node if it does not exist already.
  142. Component* GetOrCreateComponent(ShortStringHash type, CreateMode mode = REPLICATED, unsigned id = 0);
  143. /// Remove a component from this node.
  144. void RemoveComponent(Component* component);
  145. /// Remove the first component of specific type from this node.
  146. void RemoveComponent(ShortStringHash type);
  147. /// Remove all components from this node.
  148. void RemoveAllComponents();
  149. /// Remove components that match criteria.
  150. void RemoveComponents(bool removeReplicated, bool removeLocal);
  151. /// Clone scene node, components and child nodes. Return the clone.
  152. Node* Clone(CreateMode mode = REPLICATED);
  153. /// Remove from the parent node. If no other shared pointer references exist, causes immediate deletion.
  154. void Remove();
  155. /// Set parent scene node. Retains the world transform.
  156. void SetParent(Node* parent);
  157. /// Set a user variable.
  158. void SetVar(ShortStringHash key, const Variant& value);
  159. /// Add listener component that is notified of node being dirtied. Can either be in the same node or another.
  160. void AddListener(Component* component);
  161. /// Remove listener component.
  162. void RemoveListener(Component* component);
  163. /// Template version of creating a component.
  164. template <class T> T* CreateComponent(CreateMode mode = REPLICATED, unsigned id = 0);
  165. /// Template version of getting or creating a component.
  166. template <class T> T* GetOrCreateComponent(CreateMode mode = REPLICATED, unsigned id = 0);
  167. /// Template version of removing a component.
  168. template <class T> void RemoveComponent();
  169. /// Return ID.
  170. unsigned GetID() const { return id_; }
  171. /// Return name.
  172. const String& GetName() const { return name_; }
  173. /// Return name hash.
  174. StringHash GetNameHash() const { return nameHash_; }
  175. /// Return parent scene node.
  176. Node* GetParent() const { return parent_; }
  177. /// Return scene.
  178. Scene* GetScene() const { return scene_; }
  179. /// Return whether is enabled. Disables nodes effectively disable all their components.
  180. bool IsEnabled() const { return enabled_; }
  181. /// Return owner connection in networking.
  182. Connection* GetOwner() const { return owner_; }
  183. /// Return position in parent space.
  184. const Vector3& GetPosition() const { return position_; }
  185. /// Return rotation in parent space.
  186. const Quaternion& GetRotation() const { return rotation_; }
  187. /// Return forward direction in parent space. Positive Z axis equals identity rotation.
  188. Vector3 GetDirection() const { return rotation_ * Vector3::FORWARD; }
  189. /// Return scale in parent space.
  190. const Vector3& GetScale() const { return scale_; }
  191. /// Return parent space transform matrix.
  192. Matrix3x4 GetTransform() const { return Matrix3x4(position_, rotation_, scale_); }
  193. /// Return position in world space.
  194. Vector3 GetWorldPosition() const
  195. {
  196. if (dirty_)
  197. UpdateWorldTransform();
  198. return worldTransform_.Translation();
  199. }
  200. /// Return rotation in world space.
  201. Quaternion GetWorldRotation() const
  202. {
  203. if (dirty_)
  204. UpdateWorldTransform();
  205. return worldRotation_;
  206. }
  207. /// Return direction in world space.
  208. Vector3 GetWorldDirection() const
  209. {
  210. if (dirty_)
  211. UpdateWorldTransform();
  212. return worldRotation_ * Vector3::FORWARD;
  213. }
  214. /// Return scale in world space.
  215. Vector3 GetWorldScale() const
  216. {
  217. if (dirty_)
  218. UpdateWorldTransform();
  219. return worldTransform_.Scale();
  220. }
  221. /// Return world space transform matrix.
  222. const Matrix3x4& GetWorldTransform() const
  223. {
  224. if (dirty_)
  225. UpdateWorldTransform();
  226. return worldTransform_;
  227. }
  228. /// Convert a local space position to world space.
  229. Vector3 LocalToWorld(const Vector3& position) const;
  230. /// Convert a local space position or rotation to world space.
  231. Vector3 LocalToWorld(const Vector4& vector) const;
  232. /// Convert a world space position to local space.
  233. Vector3 WorldToLocal(const Vector3& position) const;
  234. /// Convert a world space position or rotation to local space.
  235. Vector3 WorldToLocal(const Vector4& vector) const;
  236. /// Return whether transform has changed and world transform needs recalculation.
  237. bool IsDirty() const { return dirty_; }
  238. /// Return number of child scene nodes.
  239. unsigned GetNumChildren(bool recursive = false) const;
  240. /// Return immediate child scene nodes.
  241. const Vector<SharedPtr<Node> >& GetChildren() const { return children_; }
  242. /// Return child scene nodes, optionally recursive.
  243. void GetChildren(PODVector<Node*>& dest, bool recursive = false) const;
  244. /// Return child scene nodes with a specific component.
  245. void GetChildrenWithComponent(PODVector<Node*>& dest, ShortStringHash type, bool recursive = false) const;
  246. /// Return child scene node by index.
  247. Node* GetChild(unsigned index) const;
  248. /// Return child scene node by name.
  249. Node* GetChild(const String& name, bool recursive = false) const;
  250. /// Return child scene node by name.
  251. Node* GetChild(const char* name, bool recursive = false) const;
  252. /// Return child scene node by name hash.
  253. Node* GetChild(StringHash nameHash, bool recursive = false) const;
  254. /// Return number of components.
  255. unsigned GetNumComponents() const { return components_.Size(); }
  256. /// Return number of non-local components.
  257. unsigned GetNumNetworkComponents() const;
  258. /// Return all components.
  259. const Vector<SharedPtr<Component> >& GetComponents() const { return components_; }
  260. /// Return all components of type. Optionally recursive.
  261. void GetComponents(PODVector<Component*>& dest, ShortStringHash type, bool recursive = false) const;
  262. /// Return component by type. If there are several, returns the first.
  263. Component* GetComponent(ShortStringHash type) const;
  264. /// Return whether has a specific component.
  265. bool HasComponent(ShortStringHash type) const;
  266. /// Return listener components.
  267. const Vector<WeakPtr<Component> > GetListeners() const { return listeners_; }
  268. /// Return a user variable.
  269. const Variant& GetVar(ShortStringHash key) const;
  270. /// Return all user variables.
  271. const VariantMap& GetVars() const { return vars_; }
  272. /// Return first component derived from class.
  273. template <class T> T* GetDerivedComponent() const;
  274. /// Return components derived from class.
  275. template <class T> void GetDerivedComponents(PODVector<T*>& dest) const;
  276. /// Template version of returning child nodes with a specific component.
  277. template <class T> void GetChildrenWithComponent(PODVector<Node*>& dest, bool recursive = false) const;
  278. /// Template version of returning a component by type.
  279. template <class T> T* GetComponent() const;
  280. /// Template version of returning all components of type.
  281. template <class T> void GetComponents(PODVector<T*>& dest, bool recursive = false) const;
  282. /// Template version of checking whether has a specific component.
  283. template <class T> bool HasComponent() const;
  284. /// Set ID. Called by Scene.
  285. void SetID(unsigned id);
  286. /// Set scene. Called by Scene.
  287. void SetScene(Scene* scene);
  288. /// Reset scene. Called by Scene.
  289. void ResetScene();
  290. /// Set network position attribute.
  291. void SetNetPositionAttr(const Vector3& value);
  292. /// Set network rotation attribute.
  293. void SetNetRotationAttr(const PODVector<unsigned char>& value);
  294. /// Set network parent attribute.
  295. void SetNetParentAttr(const PODVector<unsigned char>& value);
  296. /// Return network position attribute.
  297. const Vector3& GetNetPositionAttr() const;
  298. /// Return network rotation attribute.
  299. const PODVector<unsigned char>& GetNetRotationAttr() const;
  300. /// Return network parent attribute.
  301. const PODVector<unsigned char>& GetNetParentAttr() const;
  302. /// Load components and optionally load child nodes.
  303. bool Load(Deserializer& source, SceneResolver& resolver, bool loadChildren = true, bool rewriteIDs = false, CreateMode mode = REPLICATED);
  304. /// Load components from XML data and optionally load child nodes.
  305. bool LoadXML(const XMLElement& source, SceneResolver& resolver, bool loadChildren = true, bool rewriteIDs = false, CreateMode mode = REPLICATED);
  306. /// Return the depended on nodes to order network updates.
  307. const PODVector<Node*>& GetDependencyNodes() const { return dependencyNodes_; }
  308. /// Prepare network update by comparing attributes and marking replication states dirty as necessary.
  309. void PrepareNetworkUpdate();
  310. /// Clean up all references to a network connection that is about to be removed.
  311. void CleanupConnection(Connection* connection);
  312. /// Mark for attribute check on the next network update.
  313. void MarkNetworkUpdate();
  314. /// Mark node dirty in scene replication states.
  315. void MarkReplicationDirty();
  316. /// Create a child node with specific ID.
  317. Node* CreateChild(unsigned id, CreateMode mode);
  318. /// Add a pre-created component.
  319. void AddComponent(Component* component, unsigned id, CreateMode mode);
  320. /// Calculate number of non-temporary child nodes.
  321. unsigned GetNumPersistentChildren() const;
  322. /// Calculate number of non-temporary components.
  323. unsigned GetNumPersistentComponents() const;
  324. protected:
  325. /// User variables.
  326. VariantMap vars_;
  327. private:
  328. /// Recalculate the world transform.
  329. void UpdateWorldTransform() const;
  330. /// Remove child node by iterator.
  331. void RemoveChild(Vector<SharedPtr<Node> >::Iterator i);
  332. /// Return child nodes recursively.
  333. void GetChildrenRecursive(PODVector<Node*>& dest) const;
  334. /// Return child nodes with a specific component recursively.
  335. void GetChildrenWithComponentRecursive(PODVector<Node*>& dest, ShortStringHash type) const;
  336. /// Return specific components recursively.
  337. void GetComponentsRecursive(PODVector<Component*>& dest, ShortStringHash type) const;
  338. /// Clone node recursively.
  339. Node* CloneRecursive(Node* parent, SceneResolver& resolver, CreateMode mode);
  340. /// Remove a component from this node with the specified iterator.
  341. void RemoveComponent(Vector<SharedPtr<Component> >::Iterator i);
  342. /// World-space transform matrix.
  343. mutable Matrix3x4 worldTransform_;
  344. /// World transform needs update flag.
  345. mutable bool dirty_;
  346. /// Network update queued flag.
  347. bool networkUpdate_;
  348. /// Enabled flag.
  349. bool enabled_;
  350. /// Parent scene node.
  351. Node* parent_;
  352. /// Scene (root node.)
  353. Scene* scene_;
  354. /// Unique ID within the scene.
  355. unsigned id_;
  356. /// Position.
  357. Vector3 position_;
  358. /// Rotation.
  359. Quaternion rotation_;
  360. /// Scale.
  361. Vector3 scale_;
  362. /// World-space rotation.
  363. mutable Quaternion worldRotation_;
  364. /// Components.
  365. Vector<SharedPtr<Component> > components_;
  366. /// Child scene nodes.
  367. Vector<SharedPtr<Node> > children_;
  368. /// Node listeners.
  369. Vector<WeakPtr<Component> > listeners_;
  370. /// Nodes this node depends on for network updates.
  371. PODVector<Node*> dependencyNodes_;
  372. /// Network owner connection.
  373. Connection* owner_;
  374. /// Name.
  375. String name_;
  376. /// Name hash.
  377. StringHash nameHash_;
  378. /// Attribute buffer for network updates.
  379. mutable VectorBuffer attrBuffer_;
  380. };
  381. template <class T> T* Node::CreateComponent(CreateMode mode, unsigned id) { return static_cast<T*>(CreateComponent(T::GetTypeStatic(), mode, id)); }
  382. template <class T> T* Node::GetOrCreateComponent(CreateMode mode, unsigned id) { return static_cast<T*>(GetOrCreateComponent(T::GetTypeStatic(), mode, id)); }
  383. template <class T> void Node::RemoveComponent() { RemoveComponent(T::GetTypeStatic()); }
  384. template <class T> void Node::GetChildrenWithComponent(PODVector<Node*>& dest, bool recursive) const { GetChildrenWithComponent(dest, T::GetTypeStatic(), recursive); }
  385. template <class T> T* Node::GetComponent() const { return static_cast<T*>(GetComponent(T::GetTypeStatic())); }
  386. template <class T> void Node::GetComponents(PODVector<T*>& dest, bool recursive) const { GetComponents(reinterpret_cast<PODVector<Component*>&>(dest), T::GetTypeStatic(), recursive); }
  387. template <class T> bool Node::HasComponent() const { return HasComponent(T::GetTypeStatic()); }
  388. template <class T> T* Node::GetDerivedComponent() const
  389. {
  390. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  391. {
  392. T* component = dynamic_cast<T*>(i->Get());
  393. if (component)
  394. return component;
  395. }
  396. return 0;
  397. }
  398. template <class T> void Node::GetDerivedComponents(PODVector<T*>& dest) const
  399. {
  400. dest.Clear();
  401. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  402. {
  403. T* component = dynamic_cast<T*>(i->Get());
  404. if (component)
  405. dest.Push(component);
  406. }
  407. }
  408. }