Node.h 16 KB

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