Node.h 18 KB

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