Node.h 18 KB

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