Node.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  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. /// Component and child node creation mode for networking.
  32. enum CreateMode
  33. {
  34. REPLICATED = 0,
  35. LOCAL = 1
  36. };
  37. /// %Scene node that may contain components and child nodes.
  38. class Node : public Serializable
  39. {
  40. OBJECT(Node);
  41. friend class Connection;
  42. public:
  43. /// Construct.
  44. Node(Context* context);
  45. /// Destruct. Any child nodes are detached.
  46. virtual ~Node();
  47. /// Register object factory.
  48. static void RegisterObject(Context* context);
  49. /// Handle event. Targeted events will be forwarded to all components.
  50. virtual void OnEvent(Object* sender, bool broadcast, StringHash eventType, VariantMap& eventData);
  51. /// Load from binary data. Return true if successful.
  52. virtual bool Load(Deserializer& source);
  53. /// Load from XML data. Return true if successful.
  54. virtual bool LoadXML(const XMLElement& source);
  55. /// Save as binary data. Return true if successful.
  56. virtual bool Save(Serializer& dest);
  57. /// Save as XML data. Return true if successful.
  58. virtual bool SaveXML(XMLElement& dest);
  59. /// Apply attribute changes that can not be applied immediately recursively to child nodes and components.
  60. virtual void ApplyAttributes();
  61. /// Save to an XML file. Return true if successful.
  62. bool SaveXML(Serializer& dest);
  63. /// %Set name.
  64. void SetName(const String& name);
  65. /// %Set position relative to parent node.
  66. void SetPosition(const Vector3& position);
  67. /// %Set rotation relative to parent node.
  68. void SetRotation(const Quaternion& rotation);
  69. /// %Set direction relative to parent node. Positive Z equals identity.
  70. void SetDirection(const Vector3& direction);
  71. /// %Set uniform scale relative to parent node.
  72. void SetScale(float scale);
  73. /// %Set scale relative to parent node.
  74. void SetScale(const Vector3& scale);
  75. /// %Set transform relative to parent node.
  76. void SetTransform(const Vector3& position, const Quaternion& rotation);
  77. /// %Set transform relative to parent node.
  78. void SetTransform(const Vector3& position, const Quaternion& rotation, float scale);
  79. /// %Set transform relative to parent node.
  80. void SetTransform(const Vector3& position, const Quaternion& rotation, const Vector3& scale);
  81. /// %Set position relative to world space.
  82. void SetWorldPosition(const Vector3& position);
  83. /// %Set rotation relative to world space.
  84. void SetWorldRotation(const Quaternion& rotation);
  85. /// %Set direction relative to world space.
  86. void SetWorldDirection(const Vector3& direction);
  87. /// %Set uniform scale relative to world space.
  88. void SetWorldScale(float scale);
  89. /// %Set scale relative to world space.
  90. void SetWorldScale(const Vector3& scale);
  91. /// %Set transform relative to world space.
  92. void SetWorldTransform(const Vector3& position, const Quaternion& rotation);
  93. /// %Set transform relative to world space.
  94. void SetWorldTransform(const Vector3& position, const Quaternion& rotation, float scale);
  95. /// %Set transform relative to world space.
  96. void SetWorldTransform(const Vector3& position, const Quaternion& rotation, const Vector3& scale);
  97. /// Move the scene node.
  98. void Translate(const Vector3& delta);
  99. /// Move the scene node relative to its rotation.
  100. void TranslateRelative(const Vector3& delta);
  101. /// Rotate the scene node.
  102. void Rotate(const Quaternion& delta, bool fixedAxis = false);
  103. /// Rotate around the X axis.
  104. void Pitch(float angle, bool fixedAxis = false);
  105. /// Rotate around the Y axis.
  106. void Yaw(float angle, bool fixedAxis = false);
  107. /// Rotate around the Z axis.
  108. void Roll(float angle, bool fixedAxis = false);
  109. /// Look at a target position.
  110. void LookAt(const Vector3& target, const Vector3& upAxis = Vector3::UP, bool worldSpace = false);
  111. /// Modify scale uniformly.
  112. void Scale(float scale);
  113. /// Modify scale.
  114. void Scale(const Vector3& scale);
  115. /// %Set owner connection for networking.
  116. void SetOwner(Connection* owner);
  117. /// Mark node and child nodes to need world transform recalculation. Notify listener components.
  118. void MarkDirty();
  119. /// Create a child scene node.
  120. Node* CreateChild(const String& name = String(), CreateMode mode = REPLICATED);
  121. /// Add a child scene node.
  122. void AddChild(Node* node);
  123. /// Remove a child scene node.
  124. void RemoveChild(Node* node);
  125. /// Remove all child scene nodes.
  126. void RemoveAllChildren();
  127. /// Create a component to this node.
  128. Component* CreateComponent(ShortStringHash type, CreateMode mode = REPLICATED);
  129. /// Create a component to this node if it does not exist already.
  130. Component* GetOrCreateComponent(ShortStringHash type, CreateMode mode = REPLICATED);
  131. /// Remove a component from this node.
  132. void RemoveComponent(Component* component);
  133. /// Remove all components from this node.
  134. void RemoveAllComponents();
  135. /// Clone scene node, components and child nodes. Return the clone.
  136. Node* Clone(CreateMode mode = REPLICATED);
  137. /// Remove from the parent node. If no other shared pointer references exist, causes immediate deletion.
  138. void Remove();
  139. /// %Set parent scene node. Retains the world transform.
  140. void SetParent(Node* parent);
  141. /// Add listener component that is notified of node being dirtied. Can either be in the same node or another.
  142. void AddListener(Component* component);
  143. /// Remove listener component.
  144. void RemoveListener(Component* component);
  145. /// Template version of creating a component.
  146. template <class T> T* CreateComponent(CreateMode mode = REPLICATED);
  147. /// Template version of getting or creating a component.
  148. template <class T> T* GetOrCreateComponent(CreateMode mode = REPLICATED);
  149. /// Return ID.
  150. unsigned GetID() const { return id_; }
  151. /// Return name.
  152. const String& GetName() const { return name_; }
  153. /// Return name hash.
  154. StringHash GetNameHash() const { return nameHash_; }
  155. /// Return parent scene node.
  156. Node* GetParent() const { return parent_; }
  157. /// Return scene.
  158. Scene* GetScene() const { return scene_; }
  159. /// Return owner connection in networking.
  160. Connection* GetOwner() const { return owner_; }
  161. /// Return position relative to parent node.
  162. const Vector3& GetPosition() const { return position_; }
  163. /// Return rotation relative to parent node.
  164. const Quaternion& GetRotation() const { return rotation_; }
  165. /// Return direction relative to parent node. Identity rotation equals positive Z.
  166. Vector3 GetDirection() const { return rotation_ * Vector3::FORWARD; }
  167. /// Return scale relative to parent node.
  168. const Vector3& GetScale() const { return scale_; }
  169. /// Return transform matrix relative to parent node.
  170. Matrix3x4 GetTransform() const { return Matrix3x4(position_, rotation_, scale_); }
  171. /// Return position in world space.
  172. Vector3 GetWorldPosition() const
  173. {
  174. if (dirty_)
  175. UpdateWorldTransform();
  176. return worldTransform_.Translation();
  177. }
  178. /// Return rotation in world space.
  179. Quaternion GetWorldRotation() const
  180. {
  181. if (dirty_)
  182. UpdateWorldTransform();
  183. return worldTransform_.Rotation();
  184. }
  185. /// Return direction in world space.
  186. Vector3 GetWorldDirection() const
  187. {
  188. if (dirty_)
  189. UpdateWorldTransform();
  190. return worldTransform_.RotationMatrix() * Vector3::FORWARD;
  191. }
  192. /// Return scale in world space.
  193. Vector3 GetWorldScale() const
  194. {
  195. if (dirty_)
  196. UpdateWorldTransform();
  197. return worldTransform_.Scale();
  198. }
  199. /// Return transform matrix in world space.
  200. const Matrix3x4& GetWorldTransform() const
  201. {
  202. if (dirty_)
  203. UpdateWorldTransform();
  204. return worldTransform_;
  205. }
  206. /// Convert a local space position to world space.
  207. Vector3 LocalToWorld(const Vector3& position) const;
  208. /// Convert a local space position or rotation to world space.
  209. Vector3 LocalToWorld(const Vector4& vector) const;
  210. /// Convert a world space position to local space.
  211. Vector3 WorldToLocal(const Vector3& position) const;
  212. /// Convert a world space position or rotation to local space.
  213. Vector3 WorldToLocal(const Vector4& vector) const;
  214. /// Return whether transform has changed and world transform needs recalculation.
  215. bool IsDirty() const { return dirty_; }
  216. /// Return number of child scene nodes.
  217. unsigned GetNumChildren(bool recursive = false) const;
  218. /// Return immediate child scene nodes.
  219. const Vector<SharedPtr<Node> >& GetChildren() const { return children_; }
  220. /// Return child scene nodes, optionally recursive.
  221. void GetChildren(PODVector<Node*>& dest, bool recursive = false) const;
  222. /// Return child scene nodes with a specific component.
  223. void GetChildrenWithComponent(PODVector<Node*>& dest, ShortStringHash type, bool recursive = false) const;
  224. /// Return child scene node by index.
  225. Node* GetChild(unsigned index) const;
  226. /// Return child scene node by name.
  227. Node* GetChild(const String& name, bool recursive = false) const;
  228. /// Return child scene node by name hash.
  229. Node* GetChild(StringHash nameHash, bool recursive = false) const;
  230. /// Return number of components.
  231. unsigned GetNumComponents() const { return components_.Size(); }
  232. /// Return number of non-local components.
  233. unsigned GetNumNetworkComponents() const;
  234. /// Return all components.
  235. const Vector<SharedPtr<Component> >& GetComponents() const { return components_; }
  236. /// Return all components of type.
  237. void GetComponents(PODVector<Component*>& dest, ShortStringHash type) const;
  238. /// Return component by type. If there are several, returns the first.
  239. Component* GetComponent(ShortStringHash type) const;
  240. /// Return whether has a specific component.
  241. bool HasComponent(ShortStringHash type) const;
  242. /// Return listener components.
  243. const Vector<WeakPtr<Component> > GetListeners() const { return listeners_; }
  244. /// Return user variables.
  245. VariantMap& GetVars() { return vars_; }
  246. /// Return the depended on nodes to order network updates.
  247. const PODVector<Node*>& GetDependencyNodes(unsigned frameNumber) const;
  248. /// Return first component derived from class.
  249. template <class T> T* GetDerivedComponent() const;
  250. /// Return components derived from class.
  251. template <class T> void GetDerivedComponents(PODVector<T*>& dest) const;
  252. /// Template version of returning child nodes with a specific component.
  253. template <class T> void GetChildrenWithComponent(PODVector<Node*>& dest, bool recursive = false) const;
  254. /// Template version of returning a component by type.
  255. template <class T> T* GetComponent() const;
  256. /// Template version of returning all components of type.
  257. template <class T> void GetComponents(PODVector<T*>& dest) const;
  258. /// Template version of checking whether has a specific component.
  259. template <class T> bool HasComponent() const;
  260. /// %Set ID. Called by Scene.
  261. void SetID(unsigned id);
  262. /// %Set scene. Called by Scene.
  263. void SetScene(Scene* scene);
  264. /// %Set network position attribute.
  265. void SetNetPositionAttr(const Vector3& value);
  266. /// %Set network rotation attribute.
  267. void SetNetRotationAttr(const PODVector<unsigned char>& value);
  268. /// %Set network parent attribute.
  269. void SetNetParentAttr(const PODVector<unsigned char>& value);
  270. /// Return network position attribute.
  271. const Vector3& GetNetPositionAttr() const;
  272. /// Return network rotation attribute.
  273. const PODVector<unsigned char>& GetNetRotationAttr() const;
  274. /// Return network parent attribute.
  275. const PODVector<unsigned char>& GetNetParentAttr() const;
  276. /// Load components and optionally load child nodes.
  277. bool Load(Deserializer& source, SceneResolver& resolver, bool loadChildren = true, bool rewriteIDs = false, CreateMode mode = REPLICATED);
  278. /// Load components from XML data and optionally load child nodes.
  279. bool LoadXML(const XMLElement& source, SceneResolver& resolver, bool loadChildren = true, bool rewriteIDs = false, CreateMode mode = REPLICATED);
  280. /// User variables.
  281. VariantMap vars_;
  282. protected:
  283. /// Create a component with specific ID.
  284. Component* CreateComponent(ShortStringHash type, unsigned id, CreateMode mode);
  285. /// Create a child node with specific ID.
  286. Node* CreateChild(unsigned id, CreateMode mode);
  287. private:
  288. /// Recalculate the world transform.
  289. void UpdateWorldTransform() const;
  290. /// Remove child node by iterator.
  291. void RemoveChild(Vector<SharedPtr<Node> >::Iterator i);
  292. /// Return child nodes recursively.
  293. void GetChildrenRecursive(PODVector<Node*>& dest) const;
  294. /// Return child nodes with a specific component recursively.
  295. void GetChildrenWithComponentRecursive(PODVector<Node*>& dest, ShortStringHash type) const;
  296. /// Clone node recursively.
  297. Node* CloneRecursive(Node* parent, SceneResolver& resolver, CreateMode mode);
  298. /// Unique ID within the scene.
  299. unsigned id_;
  300. /// Parent scene node.
  301. Node* parent_;
  302. /// Scene (root node.)
  303. Scene* scene_;
  304. /// Owner connection in networking.
  305. Connection* owner_;
  306. /// Position.
  307. Vector3 position_;
  308. /// Rotation.
  309. Quaternion rotation_;
  310. /// Scale.
  311. Vector3 scale_;
  312. /// World-space transform matrix.
  313. mutable Matrix3x4 worldTransform_;
  314. /// Name.
  315. String name_;
  316. /// Name hash.
  317. StringHash nameHash_;
  318. /// Child scene nodes.
  319. Vector<SharedPtr<Node> > children_;
  320. /// Components.
  321. Vector<SharedPtr<Component> > components_;
  322. /// Node listeners.
  323. Vector<WeakPtr<Component> > listeners_;
  324. /// Nodes this node depends on for network updates.
  325. mutable PODVector<Node*> dependencyNodes_;
  326. /// Attribute buffer for network updates.
  327. mutable VectorBuffer attrBuffer_;
  328. /// Dependency nodes update framenumber.
  329. mutable unsigned dependencyFrameNumber_;
  330. /// Consecutive rotation count for rotation renormalization.
  331. unsigned char rotateCount_;
  332. /// World transform needs update flag.
  333. mutable bool dirty_;
  334. };
  335. template <class T> T* Node::CreateComponent(CreateMode mode) { return static_cast<T*>(CreateComponent(T::GetTypeStatic(), mode)); }
  336. template <class T> T* Node::GetOrCreateComponent(CreateMode mode) { return static_cast<T*>(GetOrCreateComponent(T::GetTypeStatic(), mode)); }
  337. template <class T> void Node::GetChildrenWithComponent(PODVector<Node*>& dest, bool recursive) const { GetChildrenWithComponent(dest, T::GetTypeStatic(), recursive); }
  338. template <class T> T* Node::GetComponent() const { return static_cast<T*>(GetComponent(T::GetTypeStatic())); }
  339. template <class T> void Node::GetComponents(PODVector<T*>& dest) const { GetComponents(reinterpret_cast<PODVector<Component*>&>(dest), T::GetTypeStatic()); }
  340. template <class T> bool Node::HasComponent() const { return HasComponent(T::GetTypeStatic()); }
  341. template <class T> T* Node::GetDerivedComponent() const
  342. {
  343. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  344. {
  345. T* component = dynamic_cast<T*>(i->Get());
  346. if (component)
  347. return component;
  348. }
  349. return 0;
  350. }
  351. template <class T> void Node::GetDerivedComponents(PODVector<T*>& dest) const
  352. {
  353. dest.Clear();
  354. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  355. {
  356. T* component = dynamic_cast<T*>(i->Get());
  357. if (component)
  358. dest.Push(component);
  359. }
  360. }