Node.h 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  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 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);
  55. /// Load from XML data. Return true if successful.
  56. virtual bool LoadXML(const XMLElement& source);
  57. /// Save as binary data. Return true if successful.
  58. virtual bool Save(Serializer& dest);
  59. /// Save as XML data. Return true if successful.
  60. virtual bool SaveXML(XMLElement& dest);
  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);
  69. /// Set name.
  70. void SetName(const String& name);
  71. /// Set position relative to parent node.
  72. void SetPosition(const Vector3& position);
  73. /// Set rotation relative to parent node.
  74. void SetRotation(const Quaternion& rotation);
  75. /// Set direction relative to parent node. Positive Z equals identity.
  76. void SetDirection(const Vector3& direction);
  77. /// Set uniform scale relative to parent node.
  78. void SetScale(float scale);
  79. /// Set scale relative to parent node.
  80. void SetScale(const Vector3& scale);
  81. /// Set transform relative to parent node.
  82. void SetTransform(const Vector3& position, const Quaternion& rotation);
  83. /// Set transform relative to parent node.
  84. void SetTransform(const Vector3& position, const Quaternion& rotation, float scale);
  85. /// Set transform relative to parent node.
  86. void SetTransform(const Vector3& position, const Quaternion& rotation, const Vector3& scale);
  87. /// Set position relative to world space.
  88. void SetWorldPosition(const Vector3& position);
  89. /// Set rotation relative to world space.
  90. void SetWorldRotation(const Quaternion& rotation);
  91. /// Set direction relative to world space.
  92. void SetWorldDirection(const Vector3& direction);
  93. /// Set uniform scale relative to world space.
  94. void SetWorldScale(float scale);
  95. /// Set scale relative to world space.
  96. void SetWorldScale(const Vector3& scale);
  97. /// Set transform relative to world space.
  98. void SetWorldTransform(const Vector3& position, const Quaternion& rotation);
  99. /// Set transform relative to world space.
  100. void SetWorldTransform(const Vector3& position, const Quaternion& rotation, float scale);
  101. /// Set transform relative to world space.
  102. void SetWorldTransform(const Vector3& position, const Quaternion& rotation, const Vector3& scale);
  103. /// Move the scene node.
  104. void Translate(const Vector3& delta);
  105. /// Move the scene node relative to its rotation.
  106. void TranslateRelative(const Vector3& delta);
  107. /// Rotate the scene node.
  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 position.
  116. void LookAt(const Vector3& target, const Vector3& upAxis = Vector3::UP, bool worldSpace = false);
  117. /// Modify scale uniformly.
  118. void Scale(float scale);
  119. /// Modify scale.
  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. /// Create a component to this node (with specified ID if provided).
  138. Component* CreateComponent(ShortStringHash type, CreateMode mode = REPLICATED, unsigned id = 0);
  139. /// Create a component to this node if it does not exist already.
  140. Component* GetOrCreateComponent(ShortStringHash type, CreateMode mode = REPLICATED, unsigned id = 0);
  141. /// Remove a component from this node.
  142. void RemoveComponent(Component* component);
  143. /// Remove the first component of specific type from this node.
  144. void RemoveComponent(ShortStringHash type);
  145. /// Remove all components from this node.
  146. void RemoveAllComponents();
  147. /// Clone scene node, components and child nodes. Return the clone.
  148. Node* Clone(CreateMode mode = REPLICATED);
  149. /// Remove from the parent node. If no other shared pointer references exist, causes immediate deletion.
  150. void Remove();
  151. /// Set parent scene node. Retains the world transform.
  152. void SetParent(Node* parent);
  153. /// Set a user variable.
  154. void SetVar(ShortStringHash key, const Variant& value);
  155. /// Add listener component that is notified of node being dirtied. Can either be in the same node or another.
  156. void AddListener(Component* component);
  157. /// Remove listener component.
  158. void RemoveListener(Component* component);
  159. /// Template version of creating a component.
  160. template <class T> T* CreateComponent(CreateMode mode = REPLICATED, unsigned id = 0);
  161. /// Template version of getting or creating a component.
  162. template <class T> T* GetOrCreateComponent(CreateMode mode = REPLICATED, unsigned id = 0);
  163. /// Return ID.
  164. unsigned GetID() const { return id_; }
  165. /// Return name.
  166. const String& GetName() const { return name_; }
  167. /// Return name hash.
  168. StringHash GetNameHash() const { return nameHash_; }
  169. /// Return parent scene node.
  170. Node* GetParent() const { return parent_; }
  171. /// Return scene.
  172. Scene* GetScene() const { return scene_; }
  173. /// Return whether is enabled. Disables nodes effectively disable all their components.
  174. bool IsEnabled() const { return enabled_; }
  175. /// Return owner connection in networking.
  176. Connection* GetOwner() const { return owner_; }
  177. /// Return position relative to parent node.
  178. const Vector3& GetPosition() const { return position_; }
  179. /// Return rotation relative to parent node.
  180. const Quaternion& GetRotation() const { return rotation_; }
  181. /// Return direction relative to parent node. Identity rotation equals positive Z.
  182. Vector3 GetDirection() const { return rotation_ * Vector3::FORWARD; }
  183. /// Return scale relative to parent node.
  184. const Vector3& GetScale() const { return scale_; }
  185. /// Return transform matrix relative to parent node.
  186. Matrix3x4 GetTransform() const { return Matrix3x4(position_, rotation_, scale_); }
  187. /// Return position in world space.
  188. Vector3 GetWorldPosition() const
  189. {
  190. return GetWorldTransform().Translation();
  191. }
  192. /// Return rotation in world space.
  193. Quaternion GetWorldRotation() const
  194. {
  195. return GetWorldTransform().Rotation();
  196. }
  197. /// Return direction in world space.
  198. Vector3 GetWorldDirection() const
  199. {
  200. return GetWorldTransform().RotationMatrix() * Vector3::FORWARD;
  201. }
  202. /// Return scale in world space.
  203. Vector3 GetWorldScale() const
  204. {
  205. return GetWorldTransform().Scale();
  206. }
  207. /// Return transform matrix in world space.
  208. const Matrix3x4& GetWorldTransform() const
  209. {
  210. if (dirty_)
  211. UpdateWorldTransform();
  212. return worldTransform_;
  213. }
  214. /// Convert a local space position to world space.
  215. Vector3 LocalToWorld(const Vector3& position) const;
  216. /// Convert a local space position or rotation to world space.
  217. Vector3 LocalToWorld(const Vector4& vector) const;
  218. /// Convert a world space position to local space.
  219. Vector3 WorldToLocal(const Vector3& position) const;
  220. /// Convert a world space position or rotation to local space.
  221. Vector3 WorldToLocal(const Vector4& vector) const;
  222. /// Return whether transform has changed and world transform needs recalculation.
  223. bool IsDirty() const { return dirty_; }
  224. /// Return number of child scene nodes.
  225. unsigned GetNumChildren(bool recursive = false) const;
  226. /// Return immediate child scene nodes.
  227. const Vector<SharedPtr<Node> >& GetChildren() const { return children_; }
  228. /// Return child scene nodes, optionally recursive.
  229. void GetChildren(PODVector<Node*>& dest, bool recursive = false) const;
  230. /// Return child scene nodes with a specific component.
  231. void GetChildrenWithComponent(PODVector<Node*>& dest, ShortStringHash type, bool recursive = false) const;
  232. /// Return child scene node by index.
  233. Node* GetChild(unsigned index) const;
  234. /// Return child scene node by name.
  235. Node* GetChild(const String& name, bool recursive = false) const;
  236. /// Return child scene node by name.
  237. Node* GetChild(const char* name, bool recursive = false) const;
  238. /// Return child scene node by name hash.
  239. Node* GetChild(StringHash nameHash, bool recursive = false) const;
  240. /// Return number of components.
  241. unsigned GetNumComponents() const { return components_.Size(); }
  242. /// Return number of non-local components.
  243. unsigned GetNumNetworkComponents() const;
  244. /// Return all components.
  245. const Vector<SharedPtr<Component> >& GetComponents() const { return components_; }
  246. /// Return all components of type. Optionally recursive.
  247. void GetComponents(PODVector<Component*>& dest, ShortStringHash type, bool recursive = false) const;
  248. /// Return component by type. If there are several, returns the first.
  249. Component* GetComponent(ShortStringHash type) const;
  250. /// Return whether has a specific component.
  251. bool HasComponent(ShortStringHash type) const;
  252. /// Return listener components.
  253. const Vector<WeakPtr<Component> > GetListeners() const { return listeners_; }
  254. /// Return a user variable.
  255. const Variant& GetVar(ShortStringHash key) const;
  256. /// Return all user variables.
  257. const VariantMap& GetVars() const { return vars_; }
  258. /// Return first component derived from class.
  259. template <class T> T* GetDerivedComponent() const;
  260. /// Return components derived from class.
  261. template <class T> void GetDerivedComponents(PODVector<T*>& dest) const;
  262. /// Template version of returning child nodes with a specific component.
  263. template <class T> void GetChildrenWithComponent(PODVector<Node*>& dest, bool recursive = false) const;
  264. /// Template version of returning a component by type.
  265. template <class T> T* GetComponent() const;
  266. /// Template version of returning all components of type.
  267. template <class T> void GetComponents(PODVector<T*>& dest, bool recursive = false) const;
  268. /// Template version of checking whether has a specific component.
  269. template <class T> bool HasComponent() const;
  270. /// Set ID. Called by Scene.
  271. void SetID(unsigned id);
  272. /// Set scene. Called by Scene.
  273. void SetScene(Scene* scene);
  274. /// Reset scene. Called by Scene.
  275. void ResetScene();
  276. /// Set network position attribute.
  277. void SetNetPositionAttr(const Vector3& value);
  278. /// Set network rotation attribute.
  279. void SetNetRotationAttr(const PODVector<unsigned char>& value);
  280. /// Set network parent attribute.
  281. void SetNetParentAttr(const PODVector<unsigned char>& value);
  282. /// Return network position attribute.
  283. const Vector3& GetNetPositionAttr() const;
  284. /// Return network rotation attribute.
  285. const PODVector<unsigned char>& GetNetRotationAttr() const;
  286. /// Return network parent attribute.
  287. const PODVector<unsigned char>& GetNetParentAttr() const;
  288. /// Load components and optionally load child nodes.
  289. bool Load(Deserializer& source, SceneResolver& resolver, bool loadChildren = true, bool rewriteIDs = false, CreateMode mode = REPLICATED);
  290. /// Load components from XML data and optionally load child nodes.
  291. bool LoadXML(const XMLElement& source, SceneResolver& resolver, bool loadChildren = true, bool rewriteIDs = false, CreateMode mode = REPLICATED);
  292. /// Return the depended on nodes to order network updates.
  293. const PODVector<Node*>& GetDependencyNodes() const { return dependencyNodes_; }
  294. /// Prepare network update by comparing attributes and marking replication states dirty as necessary.
  295. void PrepareNetworkUpdate();
  296. /// Clean up all references to a network connection that is about to be removed.
  297. void CleanupConnection(Connection* connection);
  298. /// Mark for attribute check on the next network update.
  299. void MarkNetworkUpdate();
  300. /// Mark node dirty in scene replication states.
  301. void MarkReplicationDirty();
  302. /// Create a child node with specific ID.
  303. Node* CreateChild(unsigned id, CreateMode mode);
  304. /// Add a pre-created component.
  305. void AddComponent(Component* component, unsigned id, CreateMode mode);
  306. protected:
  307. /// User variables.
  308. VariantMap vars_;
  309. private:
  310. /// Recalculate the world transform.
  311. void UpdateWorldTransform() const;
  312. /// Remove child node by iterator.
  313. void RemoveChild(Vector<SharedPtr<Node> >::Iterator i);
  314. /// Return child nodes recursively.
  315. void GetChildrenRecursive(PODVector<Node*>& dest) const;
  316. /// Return child nodes with a specific component recursively.
  317. void GetChildrenWithComponentRecursive(PODVector<Node*>& dest, ShortStringHash type) const;
  318. /// Return specific components recursively.
  319. void GetComponentsRecursive(PODVector<Component*>& dest, ShortStringHash type) const;
  320. /// Clone node recursively.
  321. Node* CloneRecursive(Node* parent, SceneResolver& resolver, CreateMode mode);
  322. /// Remove a component from this node with the specified iterator.
  323. void RemoveComponent(Vector<SharedPtr<Component> >::Iterator i);
  324. /// World-space transform matrix.
  325. mutable Matrix3x4 worldTransform_;
  326. /// World transform needs update flag.
  327. mutable bool dirty_;
  328. /// Network update queued flag.
  329. bool networkUpdate_;
  330. /// Enabled flag.
  331. bool enabled_;
  332. /// Parent scene node.
  333. Node* parent_;
  334. /// Scene (root node.)
  335. Scene* scene_;
  336. /// Unique ID within the scene.
  337. unsigned id_;
  338. /// Position.
  339. Vector3 position_;
  340. /// Rotation.
  341. Quaternion rotation_;
  342. /// Scale.
  343. Vector3 scale_;
  344. /// Components.
  345. Vector<SharedPtr<Component> > components_;
  346. /// Child scene nodes.
  347. Vector<SharedPtr<Node> > children_;
  348. /// Node listeners.
  349. Vector<WeakPtr<Component> > listeners_;
  350. /// Nodes this node depends on for network updates.
  351. PODVector<Node*> dependencyNodes_;
  352. /// Network owner connection.
  353. Connection* owner_;
  354. /// Name.
  355. String name_;
  356. /// Name hash.
  357. StringHash nameHash_;
  358. /// Attribute buffer for network updates.
  359. mutable VectorBuffer attrBuffer_;
  360. };
  361. template <class T> T* Node::CreateComponent(CreateMode mode, unsigned id) { return static_cast<T*>(CreateComponent(T::GetTypeStatic(), mode, id)); }
  362. template <class T> T* Node::GetOrCreateComponent(CreateMode mode, unsigned id) { return static_cast<T*>(GetOrCreateComponent(T::GetTypeStatic(), mode, id)); }
  363. template <class T> void Node::GetChildrenWithComponent(PODVector<Node*>& dest, bool recursive) const { GetChildrenWithComponent(dest, T::GetTypeStatic(), recursive); }
  364. template <class T> T* Node::GetComponent() const { return static_cast<T*>(GetComponent(T::GetTypeStatic())); }
  365. template <class T> void Node::GetComponents(PODVector<T*>& dest, bool recursive) const { GetComponents(reinterpret_cast<PODVector<Component*>&>(dest), T::GetTypeStatic(), recursive); }
  366. template <class T> bool Node::HasComponent() const { return HasComponent(T::GetTypeStatic()); }
  367. template <class T> T* Node::GetDerivedComponent() const
  368. {
  369. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  370. {
  371. T* component = dynamic_cast<T*>(i->Get());
  372. if (component)
  373. return component;
  374. }
  375. return 0;
  376. }
  377. template <class T> void Node::GetDerivedComponents(PODVector<T*>& dest) const
  378. {
  379. dest.Clear();
  380. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  381. {
  382. T* component = dynamic_cast<T*>(i->Get());
  383. if (component)
  384. dest.Push(component);
  385. }
  386. }
  387. }