Node.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221
  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. #include "Precompiled.h"
  24. #include "Component.h"
  25. #include "Context.h"
  26. #include "Log.h"
  27. #include "MemoryBuffer.h"
  28. #include "Profiler.h"
  29. #include "ReplicationState.h"
  30. #include "Scene.h"
  31. #include "SmoothedTransform.h"
  32. #include "XMLFile.h"
  33. #include "DebugNew.h"
  34. // Normalize rotation quaternion after this many incremental updates to prevent distortion
  35. static const int NORMALIZE_ROTATION_EVERY = 32;
  36. OBJECTTYPESTATIC(Node);
  37. Node::Node(Context* context) :
  38. Serializable(context),
  39. id_(0),
  40. parent_(0),
  41. scene_(0),
  42. owner_(0),
  43. position_(Vector3::ZERO),
  44. rotation_(Quaternion::IDENTITY),
  45. scale_(Vector3::ONE),
  46. worldTransform_(Matrix3x4::IDENTITY),
  47. rotateCount_(0),
  48. dirty_(false)
  49. {
  50. }
  51. Node::~Node()
  52. {
  53. RemoveAllChildren();
  54. RemoveAllComponents();
  55. // Remove from the scene
  56. if (scene_)
  57. scene_->NodeRemoved(this);
  58. }
  59. void Node::RegisterObject(Context* context)
  60. {
  61. context->RegisterFactory<Node>();
  62. /// \todo When position/rotation updates are received from the network, route to SmoothedTransform if exists
  63. REF_ACCESSOR_ATTRIBUTE(Node, VAR_STRING, "Name", GetName, SetName, String, String(), AM_DEFAULT);
  64. REF_ACCESSOR_ATTRIBUTE(Node, VAR_VECTOR3, "Position", GetPosition, SetPosition, Vector3, Vector3::ZERO, AM_FILE);
  65. REF_ACCESSOR_ATTRIBUTE(Node, VAR_QUATERNION, "Rotation", GetRotation, SetRotation, Quaternion, Quaternion::IDENTITY, AM_FILE);
  66. REF_ACCESSOR_ATTRIBUTE(Node, VAR_VECTOR3, "Scale", GetScale, SetScale, Vector3, Vector3::ONE, AM_DEFAULT);
  67. ATTRIBUTE(Node, VAR_VARIANTMAP, "Variables", vars_, VariantMap(), AM_FILE); // Network replication of vars uses custom data
  68. REF_ACCESSOR_ATTRIBUTE(Node, VAR_VECTOR3, "Network Position", GetNetPositionAttr, SetNetPositionAttr, Vector3, Vector3::ZERO, AM_NET | AM_LATESTDATA | AM_NOEDIT);
  69. REF_ACCESSOR_ATTRIBUTE(Node, VAR_BUFFER, "Network Rotation", GetNetRotationAttr, SetNetRotationAttr, PODVector<unsigned char>, PODVector<unsigned char>(), AM_NET | AM_LATESTDATA | AM_NOEDIT);
  70. REF_ACCESSOR_ATTRIBUTE(Node, VAR_BUFFER, "Network Parent Node", GetNetParentAttr, SetNetParentAttr, PODVector<unsigned char>, PODVector<unsigned char>(), AM_NET | AM_NOEDIT);
  71. }
  72. void Node::OnEvent(Object* sender, bool broadcast, StringHash eventType, VariantMap& eventData)
  73. {
  74. // Make a weak pointer to self to check for destruction during event handling
  75. WeakPtr<Node> self(this);
  76. // If this is a targeted event, forward it to all components
  77. if (!broadcast)
  78. {
  79. for (unsigned i = components_.Size() - 1; i < components_.Size(); --i)
  80. {
  81. components_[i]->OnEvent(sender, broadcast, eventType, eventData);
  82. if (self.Expired())
  83. return;
  84. }
  85. }
  86. else
  87. Object::OnEvent(sender, broadcast, eventType, eventData);
  88. }
  89. bool Node::Load(Deserializer& source)
  90. {
  91. SceneResolver resolver;
  92. // Read own ID. Will not be applied, only stored for resolving possible references
  93. unsigned nodeID = source.ReadInt();
  94. resolver.AddNode(nodeID, this);
  95. // Read attributes, components and child nodes
  96. bool success = Load(source, resolver);
  97. if (success)
  98. {
  99. resolver.Resolve();
  100. ApplyAttributes();
  101. }
  102. return success;
  103. }
  104. bool Node::Save(Serializer& dest)
  105. {
  106. // Write node ID
  107. if (!dest.WriteUInt(id_))
  108. return false;
  109. // Write attributes
  110. if (!Serializable::Save(dest))
  111. return false;
  112. // Write components
  113. dest.WriteVLE(components_.Size());
  114. for (unsigned i = 0; i < components_.Size(); ++i)
  115. {
  116. Component* component = components_[i];
  117. // Create a separate buffer to be able to skip unknown components during deserialization
  118. VectorBuffer compBuffer;
  119. if (!component->Save(compBuffer))
  120. return false;
  121. dest.WriteVLE(compBuffer.GetSize());
  122. dest.Write(compBuffer.GetData(), compBuffer.GetSize());
  123. }
  124. // Write child nodes
  125. dest.WriteVLE(children_.Size());
  126. for (unsigned i = 0; i < children_.Size(); ++i)
  127. {
  128. Node* node = children_[i];
  129. if (!node->Save(dest))
  130. return false;
  131. }
  132. return true;
  133. }
  134. bool Node::LoadXML(const XMLElement& source)
  135. {
  136. SceneResolver resolver;
  137. // Read own ID. Will not be applied, only stored for resolving possible references
  138. unsigned nodeID = source.GetInt("id");
  139. resolver.AddNode(nodeID, this);
  140. // Read attributes, components and child nodes
  141. bool success = LoadXML(source, resolver);
  142. if (success)
  143. {
  144. resolver.Resolve();
  145. ApplyAttributes();
  146. }
  147. return success;
  148. }
  149. bool Node::SaveXML(XMLElement& dest)
  150. {
  151. // Write node ID
  152. if (!dest.SetInt("id", id_))
  153. return false;
  154. // Write attributes
  155. if (!Serializable::SaveXML(dest))
  156. return false;
  157. // Write components
  158. for (unsigned i = 0; i < components_.Size(); ++i)
  159. {
  160. Component* component = components_[i];
  161. XMLElement compElem = dest.CreateChild("component");
  162. if (!component->SaveXML(compElem))
  163. return false;
  164. }
  165. // Write child nodes
  166. for (unsigned i = 0; i < children_.Size(); ++i)
  167. {
  168. Node* node = children_[i];
  169. XMLElement childElem = dest.CreateChild("node");
  170. if (!node->SaveXML(childElem))
  171. return false;
  172. }
  173. return true;
  174. }
  175. void Node::ApplyAttributes()
  176. {
  177. for (unsigned i = 0; i < components_.Size(); ++i)
  178. components_[i]->ApplyAttributes();
  179. for (unsigned i = 0; i < children_.Size(); ++i)
  180. children_[i]->ApplyAttributes();
  181. }
  182. void Node::AddReplicationState(NodeReplicationState* state)
  183. {
  184. replicationStates_.Push(state);
  185. }
  186. bool Node::SaveXML(Serializer& dest)
  187. {
  188. SharedPtr<XMLFile> xml(new XMLFile(context_));
  189. XMLElement rootElem = xml->CreateRoot("node");
  190. if (!SaveXML(rootElem))
  191. return false;
  192. return xml->Save(dest);
  193. }
  194. void Node::SetName(const String& name)
  195. {
  196. name_ = name;
  197. nameHash_ = StringHash(name);
  198. }
  199. void Node::SetPosition(const Vector3& position)
  200. {
  201. position_ = position;
  202. if (!dirty_)
  203. MarkDirty();
  204. }
  205. void Node::SetRotation(const Quaternion& rotation)
  206. {
  207. rotation_ = rotation;
  208. if (!dirty_)
  209. MarkDirty();
  210. rotateCount_ = 0;
  211. }
  212. void Node::SetDirection(const Vector3& direction)
  213. {
  214. SetRotation(Quaternion(Vector3::FORWARD, direction));
  215. }
  216. void Node::SetScale(float scale)
  217. {
  218. scale_ = Vector3(scale, scale, scale).Abs();
  219. if (!dirty_)
  220. MarkDirty();
  221. }
  222. void Node::SetScale(const Vector3& scale)
  223. {
  224. scale_ = scale.Abs();
  225. if (!dirty_)
  226. MarkDirty();
  227. }
  228. void Node::SetTransform(const Vector3& position, const Quaternion& rotation)
  229. {
  230. position_ = position;
  231. rotation_ = rotation;
  232. if (!dirty_)
  233. MarkDirty();
  234. rotateCount_ = 0;
  235. }
  236. void Node::SetTransform(const Vector3& position, const Quaternion& rotation, float scale)
  237. {
  238. position_ = position;
  239. rotation_ = rotation;
  240. scale_ = Vector3(scale, scale, scale);
  241. if (!dirty_)
  242. MarkDirty();
  243. rotateCount_ = 0;
  244. }
  245. void Node::SetTransform(const Vector3& position, const Quaternion& rotation, const Vector3& scale)
  246. {
  247. position_ = position;
  248. rotation_ = rotation;
  249. scale_ = scale;
  250. if (!dirty_)
  251. MarkDirty();
  252. rotateCount_ = 0;
  253. }
  254. void Node::SetWorldPosition(const Vector3& position)
  255. {
  256. if (!parent_)
  257. SetPosition(position);
  258. else
  259. SetPosition(parent_->GetWorldTransform().Inverse() * position);
  260. }
  261. void Node::SetWorldRotation(const Quaternion& rotation)
  262. {
  263. if (!parent_)
  264. SetRotation(rotation);
  265. else
  266. SetRotation(parent_->GetWorldRotation().Inverse() * rotation);
  267. }
  268. void Node::SetWorldDirection(const Vector3& direction)
  269. {
  270. Vector3 localDirection;
  271. if (!parent_)
  272. localDirection = direction;
  273. else
  274. localDirection = parent_->GetWorldTransform().Inverse() * direction;
  275. SetRotation(Quaternion(Vector3::FORWARD, localDirection));
  276. }
  277. void Node::SetWorldScale(float scale)
  278. {
  279. if (!parent_)
  280. SetScale(scale);
  281. else
  282. {
  283. Vector3 parentWorldScale = parent_->GetWorldScale();
  284. SetScale(Vector3(scale / parentWorldScale.x_, scale / parentWorldScale.y_, scale / parentWorldScale.z_));
  285. }
  286. }
  287. void Node::SetWorldScale(const Vector3& scale)
  288. {
  289. if (!parent_)
  290. SetScale(scale);
  291. else
  292. SetScale(scale / parent_->GetWorldScale());
  293. }
  294. void Node::SetWorldTransform(const Vector3& position, const Quaternion& rotation)
  295. {
  296. SetWorldPosition(position);
  297. SetWorldRotation(rotation);
  298. }
  299. void Node::SetWorldTransform(const Vector3& position, const Quaternion& rotation, float scale)
  300. {
  301. SetWorldPosition(position);
  302. SetWorldRotation(rotation);
  303. SetWorldScale(scale);
  304. }
  305. void Node::SetWorldTransform(const Vector3& position, const Quaternion& rotation, const Vector3& scale)
  306. {
  307. SetWorldPosition(position);
  308. SetWorldRotation(rotation);
  309. SetWorldScale(scale);
  310. }
  311. void Node::Translate(const Vector3& delta)
  312. {
  313. position_ += delta;
  314. if (!dirty_)
  315. MarkDirty();
  316. }
  317. void Node::TranslateRelative(const Vector3& delta)
  318. {
  319. position_ += rotation_ * delta;
  320. if (!dirty_)
  321. MarkDirty();
  322. }
  323. void Node::Rotate(const Quaternion& delta, bool fixedAxis)
  324. {
  325. if (!fixedAxis)
  326. rotation_ = rotation_ * delta;
  327. else
  328. rotation_ = delta * rotation_;
  329. ++rotateCount_;
  330. if (rotateCount_ >= NORMALIZE_ROTATION_EVERY)
  331. {
  332. rotation_.Normalize();
  333. rotateCount_ = 0;
  334. }
  335. if (!dirty_)
  336. MarkDirty();
  337. }
  338. void Node::Yaw(float angle, bool fixedAxis)
  339. {
  340. Rotate(Quaternion(angle, Vector3::UP), fixedAxis);
  341. }
  342. void Node::Pitch(float angle, bool fixedAxis)
  343. {
  344. Rotate(Quaternion(angle, Vector3::RIGHT), fixedAxis);
  345. }
  346. void Node::Roll(float angle, bool fixedAxis)
  347. {
  348. Rotate(Quaternion(angle, Vector3::FORWARD), fixedAxis);
  349. }
  350. void Node::LookAt(const Vector3& target, const Vector3& upAxis, bool worldSpace)
  351. {
  352. Vector3 targetZ;
  353. if (worldSpace)
  354. targetZ = (target - GetWorldPosition()).Normalized();
  355. else
  356. targetZ = (target - position_).Normalized();
  357. Vector3 targetX = upAxis.CrossProduct(targetZ).Normalized();
  358. Vector3 targetY = targetZ.CrossProduct(targetX).Normalized();
  359. if (!worldSpace || !parent_)
  360. SetRotation(Quaternion(targetX, targetY, targetZ));
  361. else
  362. SetRotation(parent_->GetWorldRotation().Inverse() * Quaternion(targetX, targetY, targetZ));
  363. }
  364. void Node::Scale(float scale)
  365. {
  366. scale_ *= scale;
  367. if (!dirty_)
  368. MarkDirty();
  369. }
  370. void Node::Scale(const Vector3& scale)
  371. {
  372. scale_ *= scale;
  373. if (!dirty_)
  374. MarkDirty();
  375. }
  376. void Node::SetOwner(Connection* owner)
  377. {
  378. owner_ = owner;
  379. }
  380. void Node::MarkDirty()
  381. {
  382. dirty_ = true;
  383. // Notify listener components first, then mark child nodes
  384. for (Vector<WeakPtr<Component> >::Iterator i = listeners_.Begin(); i != listeners_.End();)
  385. {
  386. if (*i)
  387. {
  388. (*i)->OnMarkedDirty(this);
  389. ++i;
  390. }
  391. // If listener has expired, erase from list
  392. else
  393. i = listeners_.Erase(i);
  394. }
  395. for (Vector<SharedPtr<Node> >::Iterator i = children_.Begin(); i != children_.End(); ++i)
  396. (*i)->MarkDirty();
  397. }
  398. Node* Node::CreateChild(const String& name, CreateMode mode)
  399. {
  400. Node* newNode = CreateChild(0, mode);
  401. newNode->SetName(name);
  402. return newNode;
  403. }
  404. void Node::AddChild(Node* node)
  405. {
  406. // Check for illegal or redundant parent assignment
  407. if (!node || node == this || node->parent_ == this)
  408. return;
  409. // Check for possible cyclic parent assignment
  410. Node* parent = parent_;
  411. while (parent)
  412. {
  413. if (parent == node)
  414. return;
  415. parent = parent->parent_;
  416. }
  417. // Add first, then remove from old parent, to ensure the node does not get deleted
  418. children_.Push(SharedPtr<Node>(node));
  419. if (node->parent_)
  420. node->parent_->RemoveChild(node);
  421. // Add to the scene if not added yet
  422. if (scene_ && !node->GetScene())
  423. scene_->NodeAdded(node);
  424. node->parent_ = this;
  425. node->MarkDirty();
  426. }
  427. void Node::RemoveChild(Node* node)
  428. {
  429. if (!node)
  430. return;
  431. for (Vector<SharedPtr<Node> >::Iterator i = children_.Begin(); i != children_.End(); ++i)
  432. {
  433. if (*i == node)
  434. {
  435. RemoveChild(i);
  436. return;
  437. }
  438. }
  439. }
  440. void Node::RemoveAllChildren()
  441. {
  442. while (children_.Size())
  443. RemoveChild(children_.End() - 1);
  444. }
  445. Component* Node::CreateComponent(ShortStringHash type, CreateMode mode)
  446. {
  447. return CreateComponent(type, 0, mode);
  448. }
  449. Component* Node::GetOrCreateComponent(ShortStringHash type, CreateMode mode)
  450. {
  451. Component* oldComponent = GetComponent(type);
  452. if (oldComponent)
  453. return oldComponent;
  454. else
  455. return CreateComponent(type, 0, mode);
  456. }
  457. void Node::RemoveComponent(Component* component)
  458. {
  459. for (Vector<SharedPtr<Component> >::Iterator i = components_.Begin(); i != components_.End(); ++i)
  460. {
  461. if (*i == component)
  462. {
  463. WeakPtr<Component> componentWeak(*i);
  464. RemoveListener(*i);
  465. if (scene_)
  466. scene_->ComponentRemoved(*i);
  467. components_.Erase(i);
  468. // If the component is still referenced elsewhere, reset its node pointer now
  469. if (componentWeak)
  470. componentWeak->SetNode(0);
  471. // Mark node dirty in all replication states
  472. MarkReplicationDirty();
  473. return;
  474. }
  475. }
  476. }
  477. void Node::RemoveAllComponents()
  478. {
  479. if (components_.Empty())
  480. return;
  481. while (components_.Size())
  482. {
  483. Vector<SharedPtr<Component> >::Iterator i = components_.End() - 1;
  484. WeakPtr<Component> componentWeak(*i);
  485. RemoveListener(*i);
  486. if (scene_)
  487. scene_->ComponentRemoved(*i);
  488. components_.Erase(i);
  489. // If the component is still referenced elsewhere, reset its node pointer now
  490. if (componentWeak)
  491. componentWeak->SetNode(0);
  492. }
  493. // Mark node dirty in all replication states
  494. MarkReplicationDirty();
  495. }
  496. Node* Node::Clone(CreateMode mode)
  497. {
  498. // The scene itself can not be cloned
  499. if (this == scene_ || !parent_)
  500. return 0;
  501. PROFILE(CloneNode);
  502. SceneResolver resolver;
  503. Node* clone = CloneRecursive(parent_, resolver, mode);
  504. resolver.Resolve();
  505. clone->ApplyAttributes();
  506. return clone;
  507. }
  508. void Node::Remove()
  509. {
  510. if (parent_)
  511. parent_->RemoveChild(this);
  512. }
  513. void Node::SetParent(Node* parent)
  514. {
  515. if (parent)
  516. {
  517. Vector3 worldPosition;
  518. Quaternion worldRotation;
  519. Vector3 worldScale;
  520. GetWorldTransform().Decompose(worldPosition, worldRotation, worldScale);
  521. parent->AddChild(this);
  522. SetWorldTransform(worldPosition, worldRotation, worldScale);
  523. }
  524. }
  525. void Node::AddListener(Component* component)
  526. {
  527. if (!component)
  528. return;
  529. // Check for not adding twice
  530. for (Vector<WeakPtr<Component> >::Iterator i = listeners_.Begin(); i != listeners_.End(); ++i)
  531. {
  532. if (*i == component)
  533. return;
  534. }
  535. listeners_.Push(WeakPtr<Component>(component));
  536. // If the node is currently dirty, notify immediately
  537. if (dirty_)
  538. component->OnMarkedDirty(this);
  539. }
  540. void Node::RemoveListener(Component* component)
  541. {
  542. for (Vector<WeakPtr<Component> >::Iterator i = listeners_.Begin(); i != listeners_.End(); ++i)
  543. {
  544. if (*i == component)
  545. {
  546. listeners_.Erase(i);
  547. return;
  548. }
  549. }
  550. }
  551. Vector3 Node::LocalToWorld(const Vector3& position) const
  552. {
  553. return GetWorldTransform() * position;
  554. }
  555. Vector3 Node::LocalToWorld(const Vector4& vector) const
  556. {
  557. return GetWorldTransform() * vector;
  558. }
  559. Vector3 Node::WorldToLocal(const Vector3& position) const
  560. {
  561. return GetWorldTransform().Inverse() * position;
  562. }
  563. Vector3 Node::WorldToLocal(const Vector4& vector) const
  564. {
  565. return GetWorldTransform().Inverse() * vector;
  566. }
  567. unsigned Node::GetNumChildren(bool recursive) const
  568. {
  569. if (!recursive)
  570. return children_.Size();
  571. else
  572. {
  573. unsigned allChildren = children_.Size();
  574. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  575. allChildren += (*i)->GetNumChildren(true);
  576. return allChildren;
  577. }
  578. }
  579. void Node::GetChildren(PODVector<Node*>& dest, bool recursive) const
  580. {
  581. dest.Clear();
  582. if (!recursive)
  583. {
  584. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  585. dest.Push(*i);
  586. }
  587. else
  588. GetChildrenRecursive(dest);
  589. }
  590. void Node::GetChildrenWithComponent(PODVector<Node*>& dest, ShortStringHash type, bool recursive) const
  591. {
  592. dest.Clear();
  593. if (!recursive)
  594. {
  595. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  596. {
  597. if ((*i)->HasComponent(type))
  598. dest.Push(*i);
  599. }
  600. }
  601. else
  602. GetChildrenWithComponentRecursive(dest, type);
  603. }
  604. Node* Node::GetChild(unsigned index) const
  605. {
  606. return index < children_.Size() ? children_[index].Get() : 0;
  607. }
  608. Node* Node::GetChild(const String& name, bool recursive) const
  609. {
  610. return GetChild(StringHash(name), recursive);
  611. }
  612. Node* Node::GetChild(StringHash nameHash, bool recursive) const
  613. {
  614. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  615. {
  616. if ((*i)->GetNameHash() == nameHash)
  617. return *i;
  618. if (recursive)
  619. {
  620. Node* node = (*i)->GetChild(nameHash, true);
  621. if (node)
  622. return node;
  623. }
  624. }
  625. return 0;
  626. }
  627. unsigned Node::GetNumNetworkComponents() const
  628. {
  629. unsigned num = 0;
  630. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  631. {
  632. if ((*i)->GetID() < FIRST_LOCAL_ID)
  633. ++num;
  634. }
  635. return num;
  636. }
  637. void Node::GetComponents(PODVector<Component*>& dest, ShortStringHash type) const
  638. {
  639. dest.Clear();
  640. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  641. {
  642. if ((*i)->GetType() == type)
  643. dest.Push(*i);
  644. }
  645. }
  646. bool Node::HasComponent(ShortStringHash type) const
  647. {
  648. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  649. {
  650. if ((*i)->GetType() == type)
  651. return true;
  652. }
  653. return false;
  654. }
  655. Component* Node::GetComponent(ShortStringHash type) const
  656. {
  657. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  658. {
  659. if ((*i)->GetType() == type)
  660. return *i;
  661. }
  662. return 0;
  663. }
  664. void Node::PrepareNetworkUpdate()
  665. {
  666. // Process dependencies first
  667. dependencyNodes_.Clear();
  668. // Add the parent node, but if it is local, traverse to the first non-local node
  669. if (parent_ && parent_ != scene_)
  670. {
  671. Node* current = parent_;
  672. while (current->id_ >= FIRST_LOCAL_ID)
  673. current = current->parent_;
  674. if (current && current != scene_)
  675. dependencyNodes_.Push(current);
  676. }
  677. // Then let the components add their dependencies
  678. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  679. (*i)->GetDependencyNodes(dependencyNodes_);
  680. const Vector<AttributeInfo>* attributes = GetNetworkAttributes();
  681. if (attributes)
  682. {
  683. unsigned numAttributes = attributes->Size();
  684. if (currentState_.Size() != numAttributes)
  685. {
  686. currentState_.Resize(numAttributes);
  687. previousState_.Resize(numAttributes);
  688. // Copy the default attribute values to the previous state as a starting point
  689. for (unsigned i = 0; i < numAttributes; ++i)
  690. previousState_[i] = attributes->At(i).defaultValue_;
  691. }
  692. // Check for attribute changes
  693. for (unsigned i = 0; i < numAttributes; ++i)
  694. {
  695. const AttributeInfo& attr = attributes->At(i);
  696. OnGetAttribute(attr, currentState_[i]);
  697. if (currentState_[i] != previousState_[i])
  698. {
  699. previousState_[i] = currentState_[i];
  700. // Mark the attribute dirty in all replication states that are tracking this node
  701. for (PODVector<NodeReplicationState*>::Iterator j = replicationStates_.Begin(); j != replicationStates_.End();
  702. ++j)
  703. {
  704. (*j)->dirtyAttributes_.Set(i);
  705. // Add node to the dirty set if not added yet
  706. if (!(*j)->markedDirty_)
  707. {
  708. (*j)->markedDirty_ = true;
  709. (*j)->sceneState_->dirtyNodes_.Insert(id_);
  710. }
  711. }
  712. }
  713. }
  714. }
  715. // Check for user var changes
  716. for (VariantMap::ConstIterator i = vars_.Begin(); i != vars_.End(); ++i)
  717. {
  718. VariantMap::ConstIterator j = previousVars_.Find(i->first_);
  719. if (j == previousVars_.End() || j->second_ != i->second_)
  720. {
  721. previousVars_[i->first_] = i->second_;
  722. // Mark the var dirty in all replication states that are tracking this node
  723. for (PODVector<NodeReplicationState*>::Iterator j = replicationStates_.Begin(); j != replicationStates_.End(); ++j)
  724. {
  725. (*j)->dirtyVars_.Insert(i->first_);
  726. if (!(*j)->markedDirty_)
  727. {
  728. (*j)->markedDirty_ = true;
  729. (*j)->sceneState_->dirtyNodes_.Insert(id_);
  730. }
  731. }
  732. }
  733. }
  734. }
  735. void Node::CleanupConnection(Connection* connection)
  736. {
  737. if (owner_ == connection)
  738. owner_ = 0;
  739. for (unsigned i = replicationStates_.Size() - 1; i < replicationStates_.Size(); --i)
  740. {
  741. if (replicationStates_[i]->connection_ == connection)
  742. replicationStates_.Erase(i);
  743. }
  744. }
  745. void Node::MarkReplicationDirty()
  746. {
  747. for (PODVector<NodeReplicationState*>::Iterator j = replicationStates_.Begin(); j != replicationStates_.End(); ++j)
  748. {
  749. // Add component's parent node to the dirty set if not added yet
  750. if (!(*j)->markedDirty_)
  751. {
  752. (*j)->markedDirty_ = true;
  753. (*j)->sceneState_->dirtyNodes_.Insert(id_);
  754. }
  755. }
  756. }
  757. void Node::SetID(unsigned id)
  758. {
  759. id_ = id;
  760. }
  761. void Node::SetScene(Scene* scene)
  762. {
  763. scene_ = scene;
  764. }
  765. void Node::SetNetPositionAttr(const Vector3& value)
  766. {
  767. SmoothedTransform* transform = GetComponent<SmoothedTransform>();
  768. if (transform)
  769. transform->SetTargetPosition(value);
  770. else
  771. SetPosition(value);
  772. }
  773. void Node::SetNetRotationAttr(const PODVector<unsigned char>& value)
  774. {
  775. MemoryBuffer buf(value);
  776. SmoothedTransform* transform = GetComponent<SmoothedTransform>();
  777. if (transform)
  778. transform->SetTargetRotation(buf.ReadPackedQuaternion());
  779. else
  780. SetRotation(buf.ReadPackedQuaternion());
  781. }
  782. void Node::SetNetParentAttr(const PODVector<unsigned char>& value)
  783. {
  784. Scene* scene = GetScene();
  785. if (!scene)
  786. return;
  787. MemoryBuffer buf(value);
  788. // If nothing in the buffer, parent is the root node
  789. if (buf.IsEof())
  790. {
  791. scene->AddChild(this);
  792. return;
  793. }
  794. unsigned baseNodeID = buf.ReadNetID();
  795. Node* baseNode = scene->GetNode(baseNodeID);
  796. if (!baseNode)
  797. {
  798. LOGWARNING("Failed to find parent node " + String(baseNodeID));
  799. return;
  800. }
  801. // If buffer contains just an ID, the parent is replicated and we are done
  802. if (buf.IsEof())
  803. baseNode->AddChild(this);
  804. else
  805. {
  806. // Else the parent is local and we must find it recursively by name hash
  807. StringHash nameHash = buf.ReadStringHash();
  808. Node* parentNode = baseNode->GetChild(nameHash, true);
  809. if (!parentNode)
  810. LOGWARNING("Failed to find parent node with name hash " + nameHash.ToString());
  811. else
  812. parentNode->AddChild(this);
  813. }
  814. }
  815. const Vector3& Node::GetNetPositionAttr() const
  816. {
  817. return position_;
  818. }
  819. const PODVector<unsigned char>& Node::GetNetRotationAttr() const
  820. {
  821. attrBuffer_.Clear();
  822. attrBuffer_.WritePackedQuaternion(rotation_);
  823. return attrBuffer_.GetBuffer();
  824. }
  825. const PODVector<unsigned char>& Node::GetNetParentAttr() const
  826. {
  827. attrBuffer_.Clear();
  828. Scene* scene = GetScene();
  829. if (scene && parent_ && parent_ != scene)
  830. {
  831. // If parent is replicated, can write the ID directly
  832. unsigned parentID = parent_->GetID();
  833. if (parentID < FIRST_LOCAL_ID)
  834. attrBuffer_.WriteNetID(parentID);
  835. else
  836. {
  837. // Parent is local: traverse hierarchy to find a non-local base node
  838. // This iteration always stops due to the scene (root) being non-local
  839. Node* current = parent_;
  840. while (current->GetID() >= FIRST_LOCAL_ID)
  841. current = current->GetParent();
  842. // Then write the base node ID and the parent's name hash
  843. attrBuffer_.WriteVLE(current->GetID());
  844. attrBuffer_.WriteStringHash(parent_->GetNameHash());
  845. }
  846. }
  847. return attrBuffer_.GetBuffer();
  848. }
  849. bool Node::Load(Deserializer& source, SceneResolver& resolver, bool readChildren, bool rewriteIDs, CreateMode mode)
  850. {
  851. // Remove all children and components first in case this is not a fresh load
  852. RemoveAllChildren();
  853. RemoveAllComponents();
  854. // ID has been read at the parent level
  855. if (!Serializable::Load(source))
  856. return false;
  857. unsigned numComponents = source.ReadVLE();
  858. for (unsigned i = 0; i < numComponents; ++i)
  859. {
  860. VectorBuffer compBuffer(source, source.ReadVLE());
  861. ShortStringHash compType = compBuffer.ReadShortStringHash();
  862. unsigned compID = compBuffer.ReadUInt();
  863. Component* newComponent = CreateComponent(compType, rewriteIDs ? 0 : compID, (mode == REPLICATED &&
  864. compID < FIRST_LOCAL_ID) ? REPLICATED : LOCAL);
  865. if (newComponent)
  866. {
  867. resolver.AddComponent(compID, newComponent);
  868. if (!newComponent->Load(compBuffer))
  869. return false;
  870. }
  871. }
  872. if (!readChildren)
  873. return true;
  874. unsigned numChildren = source.ReadVLE();
  875. for (unsigned i = 0; i < numChildren; ++i)
  876. {
  877. unsigned nodeID = source.ReadUInt();
  878. Node* newNode = CreateChild(rewriteIDs ? 0 : nodeID, (mode == REPLICATED && nodeID < FIRST_LOCAL_ID) ? REPLICATED :
  879. LOCAL);
  880. resolver.AddNode(nodeID, newNode);
  881. if (!newNode->Load(source, resolver, readChildren, rewriteIDs, mode))
  882. return false;
  883. }
  884. return true;
  885. }
  886. bool Node::LoadXML(const XMLElement& source, SceneResolver& resolver, bool readChildren, bool rewriteIDs, CreateMode mode)
  887. {
  888. // Remove all children and components first in case this is not a fresh load
  889. RemoveAllChildren();
  890. RemoveAllComponents();
  891. if (!Serializable::LoadXML(source))
  892. return false;
  893. XMLElement compElem = source.GetChild("component");
  894. while (compElem)
  895. {
  896. String typeName = compElem.GetAttribute("type");
  897. unsigned compID = compElem.GetInt("id");
  898. Component* newComponent = CreateComponent(ShortStringHash(typeName), rewriteIDs ? 0 : compID, (mode == REPLICATED &&
  899. compID < FIRST_LOCAL_ID) ? REPLICATED : LOCAL);
  900. if (newComponent)
  901. {
  902. resolver.AddComponent(compID, newComponent);
  903. if (!newComponent->LoadXML(compElem))
  904. return false;
  905. }
  906. compElem = compElem.GetNext("component");
  907. }
  908. if (!readChildren)
  909. return true;
  910. XMLElement childElem = source.GetChild("node");
  911. while (childElem)
  912. {
  913. unsigned nodeID = childElem.GetInt("id");
  914. Node* newNode = CreateChild(rewriteIDs ? 0 : nodeID, (mode == REPLICATED && nodeID < FIRST_LOCAL_ID) ? REPLICATED :
  915. LOCAL);
  916. resolver.AddNode(nodeID, newNode);
  917. if (!newNode->LoadXML(childElem, resolver, readChildren, rewriteIDs, mode))
  918. return false;
  919. childElem = childElem.GetNext("node");
  920. }
  921. return true;
  922. }
  923. Component* Node::CreateComponent(ShortStringHash type, unsigned id, CreateMode mode)
  924. {
  925. // Check that creation succeeds and that the object in fact is a component
  926. SharedPtr<Component> newComponent = DynamicCast<Component>(context_->CreateObject(type));
  927. if (!newComponent)
  928. {
  929. LOGERROR("Could not create unknown component type " + type.ToString());
  930. return 0;
  931. }
  932. components_.Push(newComponent);
  933. // If zero ID specified, or the ID is already taken, let the scene assign
  934. if (scene_)
  935. {
  936. if (!id || scene_->GetComponent(id))
  937. id = scene_->GetFreeComponentID(mode);
  938. newComponent->SetID(id);
  939. scene_->ComponentAdded(newComponent);
  940. }
  941. else
  942. newComponent->SetID(id);
  943. newComponent->SetNode(this);
  944. newComponent->OnMarkedDirty(this);
  945. // Mark node dirty in all replication states
  946. MarkReplicationDirty();
  947. return newComponent;
  948. }
  949. Node* Node::CreateChild(unsigned id, CreateMode mode)
  950. {
  951. SharedPtr<Node> newNode(new Node(context_));
  952. // If zero ID specified, or the ID is already taken, let the scene assign
  953. if (scene_)
  954. {
  955. if (!id || scene_->GetNode(id))
  956. id = scene_->GetFreeNodeID(mode);
  957. newNode->SetID(id);
  958. }
  959. else
  960. newNode->SetID(id);
  961. AddChild(newNode);
  962. return newNode;
  963. }
  964. void Node::UpdateWorldTransform() const
  965. {
  966. if (parent_)
  967. {
  968. if (parent_->dirty_)
  969. parent_->UpdateWorldTransform();
  970. worldTransform_ = parent_->worldTransform_ * Matrix3x4(position_, rotation_, scale_);
  971. }
  972. else
  973. worldTransform_ = Matrix3x4(position_, rotation_, scale_);
  974. dirty_ = false;
  975. }
  976. void Node::RemoveChild(Vector<SharedPtr<Node> >::Iterator i)
  977. {
  978. (*i)->parent_ = 0;
  979. (*i)->MarkDirty();
  980. children_.Erase(i);
  981. }
  982. void Node::GetChildrenRecursive(PODVector<Node*>& dest) const
  983. {
  984. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  985. {
  986. Node* node = *i;
  987. dest.Push(node);
  988. if (!node->children_.Empty())
  989. node->GetChildrenRecursive(dest);
  990. }
  991. }
  992. void Node::GetChildrenWithComponentRecursive(PODVector<Node*>& dest, ShortStringHash type) const
  993. {
  994. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  995. {
  996. Node* node = *i;
  997. if (node->HasComponent(type))
  998. dest.Push(node);
  999. if (!node->children_.Empty())
  1000. node->GetChildrenRecursive(dest);
  1001. }
  1002. }
  1003. Node* Node::CloneRecursive(Node* parent, SceneResolver& resolver, CreateMode mode)
  1004. {
  1005. // Create clone node
  1006. Node* cloneNode = parent->CreateChild(0, (mode == REPLICATED && id_ < FIRST_LOCAL_ID) ? REPLICATED : LOCAL);
  1007. resolver.AddNode(id_, cloneNode);
  1008. // Copy attributes
  1009. unsigned numAttributes = GetNumAttributes();
  1010. for (unsigned j = 0; j < numAttributes; ++j)
  1011. cloneNode->SetAttribute(j, GetAttribute(j));
  1012. // Clone components
  1013. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  1014. {
  1015. Component* component = *i;
  1016. Component* cloneComponent = cloneNode->CreateComponent(component->GetType(), (mode == REPLICATED && component->GetID() <
  1017. FIRST_LOCAL_ID) ? REPLICATED : LOCAL);
  1018. if (!cloneComponent)
  1019. {
  1020. LOGERROR("Could not clone component " + component->GetTypeName());
  1021. continue;
  1022. }
  1023. resolver.AddComponent(component->GetID(), cloneComponent);
  1024. numAttributes = component->GetNumAttributes();
  1025. for (unsigned j = 0; j < numAttributes; ++j)
  1026. cloneComponent->SetAttribute(j, component->GetAttribute(j));
  1027. }
  1028. // Clone child nodes recursively
  1029. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1030. {
  1031. Node* node = *i;
  1032. node->CloneRecursive(cloneNode, resolver, mode);
  1033. }
  1034. return cloneNode;
  1035. }