Node.h 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  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.
  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 world position.
  116. void LookAt(const Vector3& target, const Vector3& upAxis = Vector3::UP);
  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. if (dirty_)
  191. UpdateWorldTransform();
  192. return worldTransform_.Translation();
  193. }
  194. /// Return rotation in world space.
  195. Quaternion GetWorldRotation() const
  196. {
  197. if (dirty_)
  198. UpdateWorldTransform();
  199. return worldRotation_;
  200. }
  201. /// Return direction in world space.
  202. Vector3 GetWorldDirection() const
  203. {
  204. if (dirty_)
  205. UpdateWorldTransform();
  206. return worldRotation_ * Vector3::FORWARD;
  207. }
  208. /// Return scale in world space.
  209. Vector3 GetWorldScale() const
  210. {
  211. if (dirty_)
  212. UpdateWorldTransform();
  213. return worldTransform_.Scale();
  214. }
  215. /// Return transform matrix in world space.
  216. const Matrix3x4& GetWorldTransform() const
  217. {
  218. if (dirty_)
  219. UpdateWorldTransform();
  220. return worldTransform_;
  221. }
  222. /// Convert a local space position to world space.
  223. Vector3 LocalToWorld(const Vector3& position) const;
  224. /// Convert a local space position or rotation to world space.
  225. Vector3 LocalToWorld(const Vector4& vector) const;
  226. /// Convert a world space position to local space.
  227. Vector3 WorldToLocal(const Vector3& position) const;
  228. /// Convert a world space position or rotation to local space.
  229. Vector3 WorldToLocal(const Vector4& vector) const;
  230. /// Return whether transform has changed and world transform needs recalculation.
  231. bool IsDirty() const { return dirty_; }
  232. /// Return number of child scene nodes.
  233. unsigned GetNumChildren(bool recursive = false) const;
  234. /// Return immediate child scene nodes.
  235. const Vector<SharedPtr<Node> >& GetChildren() const { return children_; }
  236. /// Return child scene nodes, optionally recursive.
  237. void GetChildren(PODVector<Node*>& dest, bool recursive = false) const;
  238. /// Return child scene nodes with a specific component.
  239. void GetChildrenWithComponent(PODVector<Node*>& dest, ShortStringHash type, bool recursive = false) const;
  240. /// Return child scene node by index.
  241. Node* GetChild(unsigned index) const;
  242. /// Return child scene node by name.
  243. Node* GetChild(const String& name, bool recursive = false) const;
  244. /// Return child scene node by name.
  245. Node* GetChild(const char* name, bool recursive = false) const;
  246. /// Return child scene node by name hash.
  247. Node* GetChild(StringHash nameHash, bool recursive = false) const;
  248. /// Return number of components.
  249. unsigned GetNumComponents() const { return components_.Size(); }
  250. /// Return number of non-local components.
  251. unsigned GetNumNetworkComponents() const;
  252. /// Return all components.
  253. const Vector<SharedPtr<Component> >& GetComponents() const { return components_; }
  254. /// Return all components of type. Optionally recursive.
  255. void GetComponents(PODVector<Component*>& dest, ShortStringHash type, bool recursive = false) const;
  256. /// Return component by type. If there are several, returns the first.
  257. Component* GetComponent(ShortStringHash type) const;
  258. /// Return whether has a specific component.
  259. bool HasComponent(ShortStringHash type) const;
  260. /// Return listener components.
  261. const Vector<WeakPtr<Component> > GetListeners() const { return listeners_; }
  262. /// Return a user variable.
  263. const Variant& GetVar(ShortStringHash key) const;
  264. /// Return all user variables.
  265. const VariantMap& GetVars() const { return vars_; }
  266. /// Return first component derived from class.
  267. template <class T> T* GetDerivedComponent() const;
  268. /// Return components derived from class.
  269. template <class T> void GetDerivedComponents(PODVector<T*>& dest) const;
  270. /// Template version of returning child nodes with a specific component.
  271. template <class T> void GetChildrenWithComponent(PODVector<Node*>& dest, bool recursive = false) const;
  272. /// Template version of returning a component by type.
  273. template <class T> T* GetComponent() const;
  274. /// Template version of returning all components of type.
  275. template <class T> void GetComponents(PODVector<T*>& dest, bool recursive = false) const;
  276. /// Template version of checking whether has a specific component.
  277. template <class T> bool HasComponent() const;
  278. /// Set ID. Called by Scene.
  279. void SetID(unsigned id);
  280. /// Set scene. Called by Scene.
  281. void SetScene(Scene* scene);
  282. /// Reset scene. Called by Scene.
  283. void ResetScene();
  284. /// Set network position attribute.
  285. void SetNetPositionAttr(const Vector3& value);
  286. /// Set network rotation attribute.
  287. void SetNetRotationAttr(const PODVector<unsigned char>& value);
  288. /// Set network parent attribute.
  289. void SetNetParentAttr(const PODVector<unsigned char>& value);
  290. /// Return network position attribute.
  291. const Vector3& GetNetPositionAttr() const;
  292. /// Return network rotation attribute.
  293. const PODVector<unsigned char>& GetNetRotationAttr() const;
  294. /// Return network parent attribute.
  295. const PODVector<unsigned char>& GetNetParentAttr() const;
  296. /// Load components and optionally load child nodes.
  297. bool Load(Deserializer& source, SceneResolver& resolver, bool loadChildren = true, bool rewriteIDs = false, CreateMode mode = REPLICATED);
  298. /// Load components from XML data and optionally load child nodes.
  299. bool LoadXML(const XMLElement& source, SceneResolver& resolver, bool loadChildren = true, bool rewriteIDs = false, CreateMode mode = REPLICATED);
  300. /// Return the depended on nodes to order network updates.
  301. const PODVector<Node*>& GetDependencyNodes() const { return dependencyNodes_; }
  302. /// Prepare network update by comparing attributes and marking replication states dirty as necessary.
  303. void PrepareNetworkUpdate();
  304. /// Clean up all references to a network connection that is about to be removed.
  305. void CleanupConnection(Connection* connection);
  306. /// Mark for attribute check on the next network update.
  307. void MarkNetworkUpdate();
  308. /// Mark node dirty in scene replication states.
  309. void MarkReplicationDirty();
  310. /// Create a child node with specific ID.
  311. Node* CreateChild(unsigned id, CreateMode mode);
  312. /// Add a pre-created component.
  313. void AddComponent(Component* component, unsigned id, CreateMode mode);
  314. /// Calculate number of non-temporary child nodes.
  315. unsigned GetNumPersistentChildren() const;
  316. /// Calculate number of non-temporary components.
  317. unsigned GetNumPersistentComponents() const;
  318. protected:
  319. /// User variables.
  320. VariantMap vars_;
  321. private:
  322. /// Recalculate the world transform.
  323. void UpdateWorldTransform() const;
  324. /// Remove child node by iterator.
  325. void RemoveChild(Vector<SharedPtr<Node> >::Iterator i);
  326. /// Return child nodes recursively.
  327. void GetChildrenRecursive(PODVector<Node*>& dest) const;
  328. /// Return child nodes with a specific component recursively.
  329. void GetChildrenWithComponentRecursive(PODVector<Node*>& dest, ShortStringHash type) const;
  330. /// Return specific components recursively.
  331. void GetComponentsRecursive(PODVector<Component*>& dest, ShortStringHash type) const;
  332. /// Clone node recursively.
  333. Node* CloneRecursive(Node* parent, SceneResolver& resolver, CreateMode mode);
  334. /// Remove a component from this node with the specified iterator.
  335. void RemoveComponent(Vector<SharedPtr<Component> >::Iterator i);
  336. /// World-space transform matrix.
  337. mutable Matrix3x4 worldTransform_;
  338. /// World transform needs update flag.
  339. mutable bool dirty_;
  340. /// Network update queued flag.
  341. bool networkUpdate_;
  342. /// Enabled flag.
  343. bool enabled_;
  344. /// Parent scene node.
  345. Node* parent_;
  346. /// Scene (root node.)
  347. Scene* scene_;
  348. /// Unique ID within the scene.
  349. unsigned id_;
  350. /// Position.
  351. Vector3 position_;
  352. /// Rotation.
  353. Quaternion rotation_;
  354. /// Scale.
  355. Vector3 scale_;
  356. /// World-space rotation.
  357. mutable Quaternion worldRotation_;
  358. /// Components.
  359. Vector<SharedPtr<Component> > components_;
  360. /// Child scene nodes.
  361. Vector<SharedPtr<Node> > children_;
  362. /// Node listeners.
  363. Vector<WeakPtr<Component> > listeners_;
  364. /// Nodes this node depends on for network updates.
  365. PODVector<Node*> dependencyNodes_;
  366. /// Network owner connection.
  367. Connection* owner_;
  368. /// Name.
  369. String name_;
  370. /// Name hash.
  371. StringHash nameHash_;
  372. /// Attribute buffer for network updates.
  373. mutable VectorBuffer attrBuffer_;
  374. };
  375. template <class T> T* Node::CreateComponent(CreateMode mode, unsigned id) { return static_cast<T*>(CreateComponent(T::GetTypeStatic(), mode, id)); }
  376. template <class T> T* Node::GetOrCreateComponent(CreateMode mode, unsigned id) { return static_cast<T*>(GetOrCreateComponent(T::GetTypeStatic(), mode, id)); }
  377. template <class T> void Node::GetChildrenWithComponent(PODVector<Node*>& dest, bool recursive) const { GetChildrenWithComponent(dest, T::GetTypeStatic(), recursive); }
  378. template <class T> T* Node::GetComponent() const { return static_cast<T*>(GetComponent(T::GetTypeStatic())); }
  379. template <class T> void Node::GetComponents(PODVector<T*>& dest, bool recursive) const { GetComponents(reinterpret_cast<PODVector<Component*>&>(dest), T::GetTypeStatic(), recursive); }
  380. template <class T> bool Node::HasComponent() const { return HasComponent(T::GetTypeStatic()); }
  381. template <class T> T* Node::GetDerivedComponent() const
  382. {
  383. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  384. {
  385. T* component = dynamic_cast<T*>(i->Get());
  386. if (component)
  387. return component;
  388. }
  389. return 0;
  390. }
  391. template <class T> void Node::GetDerivedComponents(PODVector<T*>& dest) const
  392. {
  393. dest.Clear();
  394. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  395. {
  396. T* component = dynamic_cast<T*>(i->Get());
  397. if (component)
  398. dest.Push(component);
  399. }
  400. }
  401. }