Node.h 18 KB

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