Node.h 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844
  1. // Copyright (c) 2008-2023 the Urho3D project
  2. // License: MIT
  3. /// \file
  4. #pragma once
  5. #include "../IO/VectorBuffer.h"
  6. #include "../Math/Matrix3x4.h"
  7. #include "../Scene/Animatable.h"
  8. #include <memory>
  9. namespace Urho3D
  10. {
  11. class Component;
  12. class Connection;
  13. class Node;
  14. class Scene;
  15. class SceneResolver;
  16. struct NodeReplicationState;
  17. /// Component and child node creation mode for networking.
  18. enum CreateMode
  19. {
  20. REPLICATED = 0,
  21. LOCAL = 1
  22. };
  23. /// Transform space for translations and rotations.
  24. enum class TransformSpace
  25. {
  26. Local = 0,
  27. Parent,
  28. World
  29. };
  30. using ComponentId = id32;
  31. using NodeId = id32;
  32. /// Internal implementation structure for less performance-critical Node variables.
  33. struct URHO3D_API NodeImpl
  34. {
  35. /// Nodes this node depends on for network updates.
  36. Vector<Node*> dependencyNodes_;
  37. /// Network owner connection.
  38. Connection* owner_;
  39. /// Name.
  40. String name_;
  41. /// Tag strings.
  42. StringVector tags_;
  43. /// Name hash.
  44. StringHash nameHash_;
  45. /// Attribute buffer for network updates.
  46. mutable VectorBuffer attrBuffer_;
  47. };
  48. /// %Scene node that may contain components and child nodes.
  49. class URHO3D_API Node : public Animatable
  50. {
  51. URHO3D_OBJECT(Node, Animatable);
  52. friend class Connection;
  53. public:
  54. /// Construct.
  55. explicit Node(Context* context);
  56. /// Destruct. Any child nodes are detached.
  57. ~Node() override;
  58. /// Register object factory.
  59. /// @nobind
  60. static void RegisterObject(Context* context);
  61. /// Load from binary data. Return true if successful.
  62. bool Load(Deserializer& source) override;
  63. /// Load from XML data. Return true if successful.
  64. bool LoadXML(const XMLElement& source) override;
  65. /// Load from JSON data. Return true if successful.
  66. bool LoadJSON(const JSONValue& source) override;
  67. /// Save as binary data. Return true if successful.
  68. bool Save(Serializer& dest) const override;
  69. /// Save as XML data. Return true if successful.
  70. bool SaveXML(XMLElement& dest) const override;
  71. /// Save as JSON data. Return true if successful.
  72. bool SaveJSON(JSONValue& dest) const override;
  73. /// Apply attribute changes that can not be applied immediately recursively to child nodes and components.
  74. void ApplyAttributes() override;
  75. /// Return whether should save default-valued attributes into XML. Always save node transforms for readability, even if identity.
  76. bool SaveDefaultAttributes() const override { return true; }
  77. /// Mark for attribute check on the next network update.
  78. void MarkNetworkUpdate() override;
  79. /// Add a replication state that is tracking this node.
  80. virtual void AddReplicationState(NodeReplicationState* state);
  81. /// Save to an XML file. Return true if successful.
  82. bool SaveXML(Serializer& dest, const String& indentation = "\t") const;
  83. /// Save to a JSON file. Return true if successful.
  84. bool SaveJSON(Serializer& dest, const String& indentation = "\t") const;
  85. /// Set name of the scene node. Names are not required to be unique.
  86. /// @property
  87. void SetName(const String& name);
  88. /// Set tags. Old tags are overwritten.
  89. void SetTags(const StringVector& tags);
  90. /// Add a tag.
  91. void AddTag(const String& tag);
  92. /// Add tags with the specified separator (; by default).
  93. void AddTags(const String& tags, char separator = ';');
  94. /// Add tags.
  95. void AddTags(const StringVector& tags);
  96. /// Remove tag. Return true if existed.
  97. bool RemoveTag(const String& tag);
  98. /// Remove all tags.
  99. void RemoveAllTags();
  100. /// Set position in parent space. If the scene node is on the root level (is child of the scene itself), this is same as world space.
  101. /// @property
  102. void SetPosition(const Vector3& position);
  103. /// Set position in parent space (for Urho2D).
  104. /// @property
  105. void SetPosition2D(const Vector2& position) { SetPosition(Vector3(position)); }
  106. /// Set position in parent space (for Urho2D).
  107. void SetPosition2D(float x, float y) { SetPosition(Vector3(x, y, 0.0f)); }
  108. /// Set rotation in parent space.
  109. /// @property
  110. void SetRotation(const Quaternion& rotation);
  111. /// Set rotation in parent space (for Urho2D).
  112. /// @property
  113. void SetRotation2D(float rotation) { SetRotation(Quaternion(rotation)); }
  114. /// Set forward direction in parent space. Positive Z axis equals identity rotation.
  115. /// @property
  116. void SetDirection(const Vector3& direction);
  117. /// Set uniform scale in parent space.
  118. void SetScale(float scale);
  119. /// Set scale in parent space.
  120. /// @property
  121. void SetScale(const Vector3& scale);
  122. /// Set scale in parent space (for Urho2D).
  123. /// @property
  124. void SetScale2D(const Vector2& scale) { SetScale(Vector3(scale, 1.0f)); }
  125. /// Set scale in parent space (for Urho2D).
  126. void SetScale2D(float x, float y) { SetScale(Vector3(x, y, 1.0f)); }
  127. /// Set both position and rotation in parent space as an atomic operation. This is faster than setting position and rotation separately.
  128. void SetTransform(const Vector3& position, const Quaternion& rotation);
  129. /// Set position, rotation, and uniform scale in parent space as an atomic operation.
  130. void SetTransform(const Vector3& position, const Quaternion& rotation, float scale);
  131. /// Set position, rotation, and scale in parent space as an atomic operation.
  132. void SetTransform(const Vector3& position, const Quaternion& rotation, const Vector3& scale);
  133. /// Set node transformation in parent space as an atomic operation.
  134. void SetTransform(const Matrix3x4& matrix);
  135. /// Set both position and rotation in parent space as an atomic operation (for Urho2D).
  136. void SetTransform2D(const Vector2& position, float rotation) { SetTransform(Vector3(position), Quaternion(rotation)); }
  137. /// Set position, rotation, and uniform scale in parent space as an atomic operation (for Urho2D).
  138. void SetTransform2D(const Vector2& position, float rotation, float scale)
  139. {
  140. SetTransform(Vector3(position), Quaternion(rotation), scale);
  141. }
  142. /// Set position, rotation, and scale in parent space as an atomic operation (for Urho2D).
  143. void SetTransform2D(const Vector2& position, float rotation, const Vector2& scale)
  144. {
  145. SetTransform(Vector3(position), Quaternion(rotation), Vector3(scale, 1.0f));
  146. }
  147. /// Set position in world space.
  148. /// @property
  149. void SetWorldPosition(const Vector3& position);
  150. /// Set position in world space (for Urho2D).
  151. /// @property
  152. void SetWorldPosition2D(const Vector2& position) { SetWorldPosition(Vector3(position)); }
  153. /// Set position in world space (for Urho2D).
  154. void SetWorldPosition2D(float x, float y) { SetWorldPosition(Vector3(x, y, 0.0f)); }
  155. /// Set rotation in world space.
  156. /// @property
  157. void SetWorldRotation(const Quaternion& rotation);
  158. /// Set rotation in world space (for Urho2D).
  159. /// @property
  160. void SetWorldRotation2D(float rotation) { SetWorldRotation(Quaternion(rotation)); }
  161. /// Set forward direction in world space.
  162. /// @property
  163. void SetWorldDirection(const Vector3& direction);
  164. /// Set uniform scale in world space.
  165. void SetWorldScale(float scale);
  166. /// Set scale in world space.
  167. /// @property
  168. void SetWorldScale(const Vector3& scale);
  169. /// Set scale in world space (for Urho2D).
  170. /// @property
  171. void SetWorldScale2D(const Vector2& scale) { SetWorldScale(Vector3(scale, 1.0f)); }
  172. /// Set scale in world space (for Urho2D).
  173. void SetWorldScale2D(float x, float y) { SetWorldScale(Vector3(x, y, 1.0f)); }
  174. /// Set both position and rotation in world space as an atomic operation.
  175. void SetWorldTransform(const Vector3& position, const Quaternion& rotation);
  176. /// Set position, rotation, and uniform scale in world space as an atomic operation.
  177. void SetWorldTransform(const Vector3& position, const Quaternion& rotation, float scale);
  178. /// Set position, rotation, and scale in world space as an atomic opration.
  179. void SetWorldTransform(const Vector3& position, const Quaternion& rotation, const Vector3& scale);
  180. /// Set position, rotation, and scale in world space as an atomic operation from a transformation matrix.
  181. void SetWorldTransform(const Matrix3x4& worldTransform);
  182. /// Set both position and rotation in world space as an atomic operation (for Urho2D).
  183. void SetWorldTransform2D(const Vector2& position, float rotation)
  184. {
  185. SetWorldTransform(Vector3(position), Quaternion(rotation));
  186. }
  187. /// Set position, rotation, and uniform scale in world space as an atomic operation (for Urho2D).
  188. void SetWorldTransform2D(const Vector2& position, float rotation, float scale)
  189. {
  190. SetWorldTransform(Vector3(position), Quaternion(rotation), scale);
  191. }
  192. /// Set position, rotation, and scale in world space as an atomic opration (for Urho2D).
  193. void SetWorldTransform2D(const Vector2& position, float rotation, const Vector2& scale)
  194. {
  195. SetWorldTransform(Vector3(position), Quaternion(rotation), Vector3(scale, 1.0f));
  196. }
  197. /// Move the scene node in the chosen transform space.
  198. void Translate(const Vector3& delta, TransformSpace space = TransformSpace::Local);
  199. /// Move the scene node in the chosen transform space (for Urho2D).
  200. void Translate2D(const Vector2& delta, TransformSpace space = TransformSpace::Local) { Translate(Vector3(delta), space); }
  201. /// Rotate the scene node in the chosen transform space.
  202. void Rotate(const Quaternion& delta, TransformSpace space = TransformSpace::Local);
  203. /// Rotate the scene node in the chosen transform space (for Urho2D).
  204. void Rotate2D(float delta, TransformSpace space = TransformSpace::Local) { Rotate(Quaternion(delta), space); }
  205. /// Rotate around a point in the chosen transform space.
  206. void RotateAround(const Vector3& point, const Quaternion& delta, TransformSpace space = TransformSpace::Local);
  207. /// Rotate around a point in the chosen transform space (for Urho2D).
  208. void RotateAround2D(const Vector2& point, float delta, TransformSpace space = TransformSpace::Local)
  209. {
  210. RotateAround(Vector3(point), Quaternion(delta), space);
  211. }
  212. /// Rotate around the X axis.
  213. void Pitch(float angle, TransformSpace space = TransformSpace::Local);
  214. /// Rotate around the Y axis.
  215. void Yaw(float angle, TransformSpace space = TransformSpace::Local);
  216. /// Rotate around the Z axis.
  217. void Roll(float angle, TransformSpace space = TransformSpace::Local);
  218. /// Look at a target position in the chosen transform space. Note that the up vector is always specified in world space. Return true if successful, or false if resulted in an illegal rotation, in which case the current rotation remains.
  219. bool LookAt(const Vector3& target, const Vector3& up = Vector3::UP, TransformSpace space = TransformSpace::World);
  220. /// Modify scale in parent space uniformly.
  221. void Scale(float scale);
  222. /// Modify scale in parent space.
  223. void Scale(const Vector3& scale);
  224. /// Modify scale in parent space (for Urho2D).
  225. void Scale2D(const Vector2& scale) { Scale(Vector3(scale, 1.0f)); }
  226. /// Set enabled/disabled state without recursion. Components in a disabled node become effectively disabled regardless of their own enable/disable state.
  227. /// @property
  228. void SetEnabled(bool enable);
  229. /// Set enabled state on self and child nodes. Nodes' own enabled state is remembered (IsEnabledSelf) and can be restored.
  230. void SetDeepEnabled(bool enable);
  231. /// Reset enabled state to the node's remembered state prior to calling SetDeepEnabled.
  232. void ResetDeepEnabled();
  233. /// Set enabled state on self and child nodes. Unlike SetDeepEnabled this does not remember the nodes' own enabled state, but overwrites it.
  234. void SetEnabledRecursive(bool enable);
  235. /// Set owner connection for networking.
  236. /// @manualbind
  237. void SetOwner(Connection* owner);
  238. /// Mark node and child nodes to need world transform recalculation. Notify listener components.
  239. void MarkDirty();
  240. /// Create a child scene node (with specified ID if provided).
  241. Node* CreateChild(const String& name = String::EMPTY, CreateMode mode = REPLICATED, NodeId id = 0, bool temporary = false);
  242. /// Create a temporary child scene node (with specified ID if provided).
  243. Node* CreateTemporaryChild(const String& name = String::EMPTY, CreateMode mode = REPLICATED, NodeId id = 0);
  244. /// Add a child scene node at a specific index. If index is not explicitly specified or is ENDPOS, append the new child at the end.
  245. void AddChild(Node* node, i32 index = ENDPOS);
  246. /// Remove a child scene node.
  247. void RemoveChild(Node* node);
  248. /// Remove all child scene nodes.
  249. void RemoveAllChildren();
  250. /// Remove child scene nodes that match criteria.
  251. void RemoveChildren(bool removeReplicated, bool removeLocal, bool recursive);
  252. /// Create a component to this node (with specified ID if provided).
  253. Component* CreateComponent(StringHash type, CreateMode mode = REPLICATED, ComponentId id = 0);
  254. /// Create a component to this node if it does not exist already.
  255. Component* GetOrCreateComponent(StringHash type, CreateMode mode = REPLICATED, ComponentId id = 0);
  256. /// Clone a component from another node using its create mode. Return the clone if successful or null on failure.
  257. Component* CloneComponent(Component* component, ComponentId id = 0);
  258. /// Clone a component from another node and specify the create mode. Return the clone if successful or null on failure.
  259. Component* CloneComponent(Component* component, CreateMode mode, ComponentId id = 0);
  260. /// Remove a component from this node.
  261. void RemoveComponent(Component* component);
  262. /// Remove the first component of specific type from this node.
  263. void RemoveComponent(StringHash type);
  264. /// Remove components that match criteria.
  265. void RemoveComponents(bool removeReplicated, bool removeLocal);
  266. /// Remove all components of specific type.
  267. void RemoveComponents(StringHash type);
  268. /// Remove all components from this node.
  269. void RemoveAllComponents();
  270. /// Adjust index order of an existing component in this node. index can be ENDPOS.
  271. void ReorderComponent(Component* component, i32 index);
  272. /// Clone scene node, components and child nodes. Return the clone.
  273. Node* Clone(CreateMode mode = REPLICATED);
  274. /// Remove from the parent node. If no other shared pointer references exist, causes immediate deletion.
  275. void Remove();
  276. /// Assign to a new parent scene node. Retains the world transform.
  277. /// @property
  278. void SetParent(Node* parent);
  279. /// Set a user variable.
  280. void SetVar(StringHash key, const Variant& value);
  281. /// Add listener component that is notified of node being dirtied. Can either be in the same node or another.
  282. void AddListener(Component* component);
  283. /// Remove listener component.
  284. void RemoveListener(Component* component);
  285. /// Template version of creating a component.
  286. template <class T> T* CreateComponent(CreateMode mode = REPLICATED, ComponentId id = 0);
  287. /// Template version of getting or creating a component.
  288. template <class T> T* GetOrCreateComponent(CreateMode mode = REPLICATED, ComponentId id = 0);
  289. /// Template version of removing a component.
  290. template <class T> void RemoveComponent();
  291. /// Template version of removing all components of specific type.
  292. template <class T> void RemoveComponents();
  293. /// Return ID.
  294. /// @property{get_id}
  295. NodeId GetID() const { return id_; }
  296. /// Return whether the node is replicated or local to a scene.
  297. /// @property
  298. bool IsReplicated() const;
  299. /// Return name.
  300. /// @property
  301. const String& GetName() const { return impl_->name_; }
  302. /// Return name hash.
  303. StringHash GetNameHash() const { return impl_->nameHash_; }
  304. /// Return all tags.
  305. /// @property
  306. const StringVector& GetTags() const { return impl_->tags_; }
  307. /// Return whether has a specific tag.
  308. bool HasTag(const String& tag) const;
  309. /// Return parent scene node.
  310. /// @property
  311. Node* GetParent() const { return parent_; }
  312. /// Return scene.
  313. /// @property
  314. Scene* GetScene() const { return scene_; }
  315. /// Return whether is a direct or indirect child of specified node.
  316. bool IsChildOf(Node* node) const;
  317. /// Return whether is enabled. Disables nodes effectively disable all their components.
  318. /// @property
  319. bool IsEnabled() const { return enabled_; }
  320. /// Return the node's last own enabled state. May be different than the value returned by IsEnabled when SetDeepEnabled has been used.
  321. /// @property
  322. bool IsEnabledSelf() const { return enabledPrev_; }
  323. /// Return owner connection in networking.
  324. /// @manualbind
  325. Connection* GetOwner() const { return impl_->owner_; }
  326. /// Return position in parent space.
  327. /// @property
  328. const Vector3& GetPosition() const { return position_; }
  329. /// Return position in parent space (for Urho2D).
  330. /// @property
  331. Vector2 GetPosition2D() const { return Vector2(position_.x_, position_.y_); }
  332. /// Return rotation in parent space.
  333. /// @property
  334. const Quaternion& GetRotation() const { return rotation_; }
  335. /// Return rotation in parent space (for Urho2D).
  336. /// @property
  337. float GetRotation2D() const { return rotation_.RollAngle(); }
  338. /// Return forward direction in parent space. Positive Z axis equals identity rotation.
  339. /// @property
  340. Vector3 GetDirection() const { return rotation_ * Vector3::FORWARD; }
  341. /// Return up direction in parent space. Positive Y axis equals identity rotation.
  342. /// @property
  343. Vector3 GetUp() const { return rotation_ * Vector3::UP; }
  344. /// Return right direction in parent space. Positive X axis equals identity rotation.
  345. /// @property
  346. Vector3 GetRight() const { return rotation_ * Vector3::RIGHT; }
  347. /// Return scale in parent space.
  348. /// @property
  349. const Vector3& GetScale() const { return scale_; }
  350. /// Return scale in parent space (for Urho2D).
  351. /// @property
  352. Vector2 GetScale2D() const { return Vector2(scale_.x_, scale_.y_); }
  353. /// Return parent space transform matrix.
  354. /// @property
  355. Matrix3x4 GetTransform() const { return Matrix3x4(position_, rotation_, scale_); }
  356. /// Return position in world space.
  357. /// @property
  358. Vector3 GetWorldPosition() const
  359. {
  360. if (dirty_)
  361. UpdateWorldTransform();
  362. return worldTransform_.Translation();
  363. }
  364. /// Return position in world space (for Urho2D).
  365. /// @property
  366. Vector2 GetWorldPosition2D() const
  367. {
  368. Vector3 worldPosition = GetWorldPosition();
  369. return Vector2(worldPosition.x_, worldPosition.y_);
  370. }
  371. /// Return rotation in world space.
  372. /// @property
  373. Quaternion GetWorldRotation() const
  374. {
  375. if (dirty_)
  376. UpdateWorldTransform();
  377. return worldRotation_;
  378. }
  379. /// Return rotation in world space (for Urho2D).
  380. /// @property
  381. float GetWorldRotation2D() const
  382. {
  383. return GetWorldRotation().RollAngle();
  384. }
  385. /// Return direction in world space.
  386. /// @property
  387. Vector3 GetWorldDirection() const
  388. {
  389. if (dirty_)
  390. UpdateWorldTransform();
  391. return worldRotation_ * Vector3::FORWARD;
  392. }
  393. /// Return node's up vector in world space.
  394. /// @property
  395. Vector3 GetWorldUp() const
  396. {
  397. if (dirty_)
  398. UpdateWorldTransform();
  399. return worldRotation_ * Vector3::UP;
  400. }
  401. /// Return node's right vector in world space.
  402. /// @property
  403. Vector3 GetWorldRight() const
  404. {
  405. if (dirty_)
  406. UpdateWorldTransform();
  407. return worldRotation_ * Vector3::RIGHT;
  408. }
  409. /// Return scale in world space.
  410. /// @property
  411. Vector3 GetWorldScale() const
  412. {
  413. if (dirty_)
  414. UpdateWorldTransform();
  415. return worldTransform_.Scale();
  416. }
  417. /// Return signed scale in world space. Utilized for Urho2D physics.
  418. /// @property
  419. Vector3 GetSignedWorldScale() const;
  420. /// Return scale in world space (for Urho2D).
  421. /// @property
  422. Vector2 GetWorldScale2D() const
  423. {
  424. Vector3 worldScale = GetWorldScale();
  425. return Vector2(worldScale.x_, worldScale.y_);
  426. }
  427. /// Return world space transform matrix.
  428. /// @property
  429. const Matrix3x4& GetWorldTransform() const
  430. {
  431. if (dirty_)
  432. UpdateWorldTransform();
  433. return worldTransform_;
  434. }
  435. /// Convert a local space position to world space.
  436. Vector3 LocalToWorld(const Vector3& position) const;
  437. /// Convert a local space position or rotation to world space.
  438. Vector3 LocalToWorld(const Vector4& vector) const;
  439. /// Convert a local space position or rotation to world space (for Urho2D).
  440. Vector2 LocalToWorld2D(const Vector2& vector) const;
  441. /// Convert a world space position to local space.
  442. Vector3 WorldToLocal(const Vector3& position) const;
  443. /// Convert a world space position or rotation to local space.
  444. Vector3 WorldToLocal(const Vector4& vector) const;
  445. /// Convert a world space position or rotation to local space (for Urho2D).
  446. Vector2 WorldToLocal2D(const Vector2& vector) const;
  447. /// Return whether transform has changed and world transform needs recalculation.
  448. bool IsDirty() const { return dirty_; }
  449. /// Return number of child scene nodes.
  450. i32 GetNumChildren(bool recursive = false) const;
  451. /// Return immediate child scene nodes.
  452. const Vector<SharedPtr<Node>>& GetChildren() const { return children_; }
  453. /// Return child scene nodes, optionally recursive.
  454. void GetChildren(Vector<Node*>& dest, bool recursive = false) const;
  455. /// Return child scene nodes, optionally recursive.
  456. Vector<Node*> GetChildren(bool recursive) const;
  457. /// Return child scene nodes with a specific component.
  458. void GetChildrenWithComponent(Vector<Node*>& dest, StringHash type, bool recursive = false) const;
  459. /// Return child scene nodes with a specific component.
  460. Vector<Node*> GetChildrenWithComponent(StringHash type, bool recursive = false) const;
  461. /// Return child scene nodes with a specific tag.
  462. void GetChildrenWithTag(Vector<Node*>& dest, const String& tag, bool recursive = false) const;
  463. /// Return child scene nodes with a specific tag.
  464. Vector<Node*> GetChildrenWithTag(const String& tag, bool recursive = false) const;
  465. /// Return child scene node by index.
  466. Node* GetChild(i32 index) const;
  467. /// Return child scene node by name.
  468. Node* GetChild(const String& name, bool recursive = false) const;
  469. /// Return child scene node by name.
  470. Node* GetChild(const char* name, bool recursive = false) const;
  471. /// Return child scene node by name hash.
  472. Node* GetChild(StringHash nameHash, bool recursive = false) const;
  473. /// Return number of components.
  474. /// @property
  475. i32 GetNumComponents() const { return components_.Size(); }
  476. /// Return number of non-local components.
  477. i32 GetNumNetworkComponents() const;
  478. /// Return all components.
  479. const Vector<SharedPtr<Component>>& GetComponents() const { return components_; }
  480. /// Return all components of type. Optionally recursive.
  481. void GetComponents(Vector<Component*>& dest, StringHash type, bool recursive = false) const;
  482. /// Return component by type. If there are several, returns the first.
  483. Component* GetComponent(StringHash type, bool recursive = false) const;
  484. /// Return component in parent node. If there are several, returns the first. May optional traverse up to the root node.
  485. Component* GetParentComponent(StringHash type, bool fullTraversal = false) const;
  486. /// Return whether has a specific component.
  487. bool HasComponent(StringHash type) const;
  488. /// Return listener components.
  489. const Vector<WeakPtr<Component>> GetListeners() const { return listeners_; }
  490. /// Return a user variable.
  491. const Variant& GetVar(StringHash key) const;
  492. /// Return all user variables.
  493. const VariantMap& GetVars() const { return vars_; }
  494. /// Return first component derived from class.
  495. template <class T> T* GetDerivedComponent(bool recursive = false) const;
  496. /// Return first component derived from class in the parent node, or if fully traversing then the first node up the tree with one.
  497. template <class T> T* GetParentDerivedComponent(bool fullTraversal = false) const;
  498. /// Return components derived from class.
  499. template <class T> void GetDerivedComponents(Vector<T*>& dest, bool recursive = false, bool clearVector = true) const;
  500. /// Template version of returning child nodes with a specific component.
  501. template <class T> void GetChildrenWithComponent(Vector<Node*>& dest, bool recursive = false) const;
  502. /// Template version of returning a component by type.
  503. template <class T> T* GetComponent(bool recursive = false) const;
  504. /// Template version of returning a parent's component by type.
  505. template <class T> T* GetParentComponent(bool fullTraversal = false) const;
  506. /// Template version of returning all components of type.
  507. template <class T> void GetComponents(Vector<T*>& dest, bool recursive = false) const;
  508. /// Template version of checking whether has a specific component.
  509. template <class T> bool HasComponent() const;
  510. /// Set ID. Called by Scene.
  511. /// @property{set_id}
  512. void SetID(NodeId id);
  513. /// Set scene. Called by Scene.
  514. void SetScene(Scene* scene);
  515. /// Reset scene, ID and owner. Called by Scene.
  516. void ResetScene();
  517. /// Set network position attribute.
  518. void SetNetPositionAttr(const Vector3& value);
  519. /// Set network rotation attribute.
  520. void SetNetRotationAttr(const Vector<byte>& value);
  521. /// Set network parent attribute.
  522. void SetNetParentAttr(const Vector<byte>& value);
  523. /// Return network position attribute.
  524. const Vector3& GetNetPositionAttr() const;
  525. /// Return network rotation attribute.
  526. const Vector<byte>& GetNetRotationAttr() const;
  527. /// Return network parent attribute.
  528. const Vector<byte>& GetNetParentAttr() const;
  529. /// Load components and optionally load child nodes.
  530. bool Load(Deserializer& source, SceneResolver& resolver, bool loadChildren = true, bool rewriteIDs = false,
  531. CreateMode mode = REPLICATED);
  532. /// Load components from XML data and optionally load child nodes.
  533. bool LoadXML(const XMLElement& source, SceneResolver& resolver, bool loadChildren = true, bool rewriteIDs = false,
  534. CreateMode mode = REPLICATED);
  535. /// Load components from XML data and optionally load child nodes.
  536. bool LoadJSON(const JSONValue& source, SceneResolver& resolver, bool loadChildren = true, bool rewriteIDs = false,
  537. CreateMode mode = REPLICATED);
  538. /// Return the depended on nodes to order network updates.
  539. const Vector<Node*>& GetDependencyNodes() const { return impl_->dependencyNodes_; }
  540. /// Prepare network update by comparing attributes and marking replication states dirty as necessary.
  541. void PrepareNetworkUpdate();
  542. /// Clean up all references to a network connection that is about to be removed.
  543. /// @manualbind
  544. void CleanupConnection(Connection* connection);
  545. /// Mark node dirty in scene replication states.
  546. void MarkReplicationDirty();
  547. /// Create a child node with specific ID.
  548. Node* CreateChild(NodeId id, CreateMode mode, bool temporary = false);
  549. /// Add a pre-created component. Using this function from application code is discouraged, as component operation without an owner node may not be well-defined in all cases. Prefer CreateComponent() instead.
  550. void AddComponent(Component* component, ComponentId id, CreateMode mode);
  551. /// Calculate number of non-temporary child nodes.
  552. i32 GetNumPersistentChildren() const;
  553. /// Calculate number of non-temporary components.
  554. i32 GetNumPersistentComponents() const;
  555. /// Set position in parent space silently without marking the node & child nodes dirty. Used by animation code.
  556. void SetPositionSilent(const Vector3& position) { position_ = position; }
  557. /// Set position in parent space silently without marking the node & child nodes dirty. Used by animation code.
  558. void SetRotationSilent(const Quaternion& rotation) { rotation_ = rotation; }
  559. /// Set scale in parent space silently without marking the node & child nodes dirty. Used by animation code.
  560. void SetScaleSilent(const Vector3& scale) { scale_ = scale; }
  561. /// Set local transform silently without marking the node & child nodes dirty. Used by animation code.
  562. void SetTransformSilent(const Vector3& position, const Quaternion& rotation, const Vector3& scale);
  563. protected:
  564. /// Handle attribute animation added.
  565. void OnAttributeAnimationAdded() override;
  566. /// Handle attribute animation removed.
  567. void OnAttributeAnimationRemoved() override;
  568. /// Find target of an attribute animation from object hierarchy by name.
  569. Animatable* FindAttributeAnimationTarget(const String& name, String& outName) override;
  570. private:
  571. /// Set enabled/disabled state with optional recursion. Optionally affect the remembered enable state.
  572. void SetEnabled(bool enable, bool recursive, bool storeSelf);
  573. /// Create component, allowing UnknownComponent if actual type is not supported. Leave typeName empty if not known.
  574. Component* SafeCreateComponent(const String& typeName, StringHash type, CreateMode mode, ComponentId id);
  575. /// Recalculate the world transform.
  576. void UpdateWorldTransform() const;
  577. /// Remove child node by iterator.
  578. void RemoveChild(Vector<SharedPtr<Node>>::Iterator i);
  579. /// Return child nodes recursively.
  580. void GetChildrenRecursive(Vector<Node*>& dest) const;
  581. /// Return child nodes with a specific component recursively.
  582. void GetChildrenWithComponentRecursive(Vector<Node*>& dest, StringHash type) const;
  583. /// Return child nodes with a specific tag recursively.
  584. void GetChildrenWithTagRecursive(Vector<Node*>& dest, const String& tag) const;
  585. /// Return specific components recursively.
  586. void GetComponentsRecursive(Vector<Component*>& dest, StringHash type) const;
  587. /// Clone node recursively.
  588. Node* CloneRecursive(Node* parent, SceneResolver& resolver, CreateMode mode);
  589. /// Remove a component from this node with the specified iterator.
  590. void RemoveComponent(Vector<SharedPtr<Component>>::Iterator i);
  591. /// Handle attribute animation update event.
  592. void HandleAttributeAnimationUpdate(StringHash eventType, VariantMap& eventData);
  593. /// World-space transform matrix.
  594. mutable Matrix3x4 worldTransform_;
  595. /// World transform needs update flag.
  596. mutable bool dirty_;
  597. /// Enabled flag.
  598. bool enabled_;
  599. /// Last SetEnabled flag before any SetDeepEnabled.
  600. bool enabledPrev_;
  601. protected:
  602. /// Network update queued flag.
  603. bool networkUpdate_;
  604. private:
  605. /// Parent scene node.
  606. Node* parent_;
  607. /// Scene (root node).
  608. Scene* scene_;
  609. /// Unique ID within the scene.
  610. NodeId id_;
  611. /// Position.
  612. Vector3 position_;
  613. /// Rotation.
  614. Quaternion rotation_;
  615. /// Scale.
  616. Vector3 scale_;
  617. /// World-space rotation.
  618. mutable Quaternion worldRotation_;
  619. /// Components.
  620. Vector<SharedPtr<Component>> components_;
  621. /// Child scene nodes.
  622. Vector<SharedPtr<Node>> children_;
  623. /// Node listeners.
  624. Vector<WeakPtr<Component>> listeners_;
  625. /// Pointer to implementation.
  626. std::unique_ptr<NodeImpl> impl_;
  627. protected:
  628. /// User variables.
  629. VariantMap vars_;
  630. };
  631. template <class T> T* Node::CreateComponent(CreateMode mode, ComponentId id)
  632. {
  633. return static_cast<T*>(CreateComponent(T::GetTypeStatic(), mode, id));
  634. }
  635. template <class T> T* Node::GetOrCreateComponent(CreateMode mode, ComponentId id)
  636. {
  637. return static_cast<T*>(GetOrCreateComponent(T::GetTypeStatic(), mode, id));
  638. }
  639. template <class T> void Node::RemoveComponent() { RemoveComponent(T::GetTypeStatic()); }
  640. template <class T> void Node::RemoveComponents() { RemoveComponents(T::GetTypeStatic()); }
  641. template <class T> void Node::GetChildrenWithComponent(Vector<Node*>& dest, bool recursive) const
  642. {
  643. GetChildrenWithComponent(dest, T::GetTypeStatic(), recursive);
  644. }
  645. template <class T> T* Node::GetComponent(bool recursive) const { return static_cast<T*>(GetComponent(T::GetTypeStatic(), recursive)); }
  646. template <class T> T* Node::GetParentComponent(bool fullTraversal) const { return static_cast<T*>(GetParentComponent(T::GetTypeStatic(), fullTraversal)); }
  647. template <class T> void Node::GetComponents(Vector<T*>& dest, bool recursive) const
  648. {
  649. GetComponents(reinterpret_cast<Vector<Component*>&>(dest), T::GetTypeStatic(), recursive);
  650. }
  651. template <class T> bool Node::HasComponent() const { return HasComponent(T::GetTypeStatic()); }
  652. template <class T> T* Node::GetDerivedComponent(bool recursive) const
  653. {
  654. for (Vector<SharedPtr<Component>>::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  655. {
  656. T* component = dynamic_cast<T*>(i->Get());
  657. if (component)
  658. return component;
  659. }
  660. if (recursive)
  661. {
  662. for (Vector<SharedPtr<Node>>::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  663. {
  664. T* component = (*i)->GetDerivedComponent<T>(true);
  665. if (component)
  666. return component;
  667. }
  668. }
  669. return nullptr;
  670. }
  671. template <class T> T* Node::GetParentDerivedComponent(bool fullTraversal) const
  672. {
  673. Node* current = GetParent();
  674. while (current)
  675. {
  676. T* soughtComponent = current->GetDerivedComponent<T>();
  677. if (soughtComponent)
  678. return soughtComponent;
  679. if (fullTraversal)
  680. current = current->GetParent();
  681. else
  682. break;
  683. }
  684. return 0;
  685. }
  686. template <class T> void Node::GetDerivedComponents(Vector<T*>& dest, bool recursive, bool clearVector) const
  687. {
  688. if (clearVector)
  689. dest.Clear();
  690. for (Vector<SharedPtr<Component>>::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  691. {
  692. T* component = dynamic_cast<T*>(i->Get());
  693. if (component)
  694. dest.Push(component);
  695. }
  696. if (recursive)
  697. {
  698. for (Vector<SharedPtr<Node>>::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  699. (*i)->GetDerivedComponents<T>(dest, true, false);
  700. }
  701. }
  702. }