Node.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035
  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. #include "Precompiled.h"
  24. #include "Component.h"
  25. #include "Context.h"
  26. #include "Log.h"
  27. #include "MemoryBuffer.h"
  28. #include "Scene.h"
  29. #include "XMLElement.h"
  30. #include "DebugNew.h"
  31. // Normalize rotation quaternion after this many incremental updates to prevent distortion
  32. static const int NORMALIZE_ROTATION_EVERY = 32;
  33. OBJECTTYPESTATIC(Node);
  34. Node::Node(Context* context) :
  35. Serializable(context),
  36. id_(0),
  37. parent_(0),
  38. scene_(0),
  39. owner_(0),
  40. position_(Vector3::ZERO),
  41. rotation_(Quaternion::IDENTITY),
  42. scale_(Vector3::ONE),
  43. worldTransform_(Matrix3x4::IDENTITY),
  44. targetPosition_(Vector3::ZERO),
  45. targetRotation_(Quaternion::IDENTITY),
  46. rotateCount_(0),
  47. smoothingMask_(SMOOTH_NONE),
  48. dirty_(false),
  49. smoothed_(false)
  50. {
  51. }
  52. Node::~Node()
  53. {
  54. RemoveAllChildren();
  55. RemoveAllComponents();
  56. // Remove from the scene
  57. if (scene_)
  58. scene_->NodeRemoved(this);
  59. }
  60. void Node::RegisterObject(Context* context)
  61. {
  62. context->RegisterFactory<Node>();
  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_DEFAULT | AM_LATESTDATA);
  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_BUFFER, "Network Rotation", GetNetRotationAttr, SetNetRotationAttr, PODVector<unsigned char>, PODVector<unsigned char>(), AM_NET | AM_LATESTDATA | AM_NOEDIT);
  69. REF_ACCESSOR_ATTRIBUTE(Node, VAR_BUFFER, "Network Parent Node", GetNetParentAttr, SetNetParentAttr, PODVector<unsigned char>, PODVector<unsigned char>(), AM_NET | AM_NOEDIT);
  70. }
  71. void Node::OnEvent(Object* sender, bool broadcast, StringHash eventType, VariantMap& eventData)
  72. {
  73. // Make a weak pointer to self to check for destruction during event handling
  74. WeakPtr<Node> self(this);
  75. // If this is a targeted event, forward it to all components
  76. if (!broadcast)
  77. {
  78. for (unsigned i = components_.Size() - 1; i < components_.Size(); --i)
  79. {
  80. components_[i]->OnEvent(sender, broadcast, eventType, eventData);
  81. if (self.Expired())
  82. return;
  83. }
  84. }
  85. else
  86. Object::OnEvent(sender, broadcast, eventType, eventData);
  87. }
  88. bool Node::Load(Deserializer& source)
  89. {
  90. return Load(source, true);
  91. }
  92. bool Node::Save(Serializer& dest)
  93. {
  94. if (!Serializable::Save(dest))
  95. return false;
  96. dest.WriteVLE(components_.Size());
  97. for (unsigned i = 0; i < components_.Size(); ++i)
  98. {
  99. Component* component = components_[i];
  100. // Create a separate buffer to be able to skip unknown components during deserialization
  101. VectorBuffer compBuffer;
  102. compBuffer.WriteShortStringHash(component->GetType());
  103. compBuffer.WriteUInt(component->GetID());
  104. if (!component->Save(compBuffer))
  105. return false;
  106. dest.WriteVLE(compBuffer.GetSize());
  107. dest.Write(compBuffer.GetData(), compBuffer.GetSize());
  108. }
  109. dest.WriteVLE(children_.Size());
  110. for (unsigned i = 0; i < children_.Size(); ++i)
  111. {
  112. Node* node = children_[i];
  113. dest.WriteUInt(node->GetID());
  114. if (!node->Save(dest))
  115. return false;
  116. }
  117. return true;
  118. }
  119. bool Node::LoadXML(const XMLElement& source)
  120. {
  121. return LoadXML(source, true);
  122. }
  123. bool Node::SaveXML(XMLElement& dest)
  124. {
  125. if (!Serializable::SaveXML(dest))
  126. return false;
  127. for (unsigned i = 0; i < components_.Size(); ++i)
  128. {
  129. Component* component = components_[i];
  130. XMLElement compElem = dest.CreateChild("component");
  131. compElem.SetString("type", component->GetTypeName());
  132. compElem.SetInt("id", component->GetID());
  133. if (!component->SaveXML(compElem))
  134. return false;
  135. }
  136. for (unsigned i = 0; i < children_.Size(); ++i)
  137. {
  138. Node* node = children_[i];
  139. XMLElement childElem = dest.CreateChild("node");
  140. childElem.SetInt("id", node->GetID());
  141. if (!node->SaveXML(childElem))
  142. return false;
  143. }
  144. return true;
  145. }
  146. void Node::ApplyAttributes()
  147. {
  148. for (unsigned i = 0; i < components_.Size(); ++i)
  149. components_[i]->ApplyAttributes();
  150. for (unsigned i = 0; i < children_.Size(); ++i)
  151. children_[i]->ApplyAttributes();
  152. }
  153. void Node::SetName(const String& name)
  154. {
  155. name_ = name;
  156. nameHash_ = StringHash(name);
  157. }
  158. void Node::SetPosition(const Vector3& position)
  159. {
  160. if (!smoothed_)
  161. {
  162. position_ = position;
  163. if (!dirty_)
  164. MarkDirty();
  165. }
  166. else
  167. {
  168. targetPosition_ = position;
  169. smoothingMask_ |= SMOOTH_POSITION;
  170. }
  171. }
  172. void Node::SetRotation(const Quaternion& rotation)
  173. {
  174. if (!smoothed_)
  175. {
  176. rotation_ = rotation;
  177. if (!dirty_)
  178. MarkDirty();
  179. }
  180. else
  181. {
  182. targetRotation_ = rotation;
  183. smoothingMask_ |= SMOOTH_ROTATION;
  184. }
  185. rotateCount_ = 0;
  186. }
  187. void Node::SetDirection(const Vector3& direction)
  188. {
  189. SetRotation(Quaternion(Vector3::FORWARD, direction));
  190. }
  191. void Node::SetScale(float scale)
  192. {
  193. scale_ = Vector3(scale, scale, scale).Abs();
  194. if (!dirty_)
  195. MarkDirty();
  196. }
  197. void Node::SetScale(const Vector3& scale)
  198. {
  199. scale_ = scale.Abs();
  200. if (!dirty_)
  201. MarkDirty();
  202. }
  203. void Node::SetTransform(const Vector3& position, const Quaternion& rotation)
  204. {
  205. if (!smoothed_)
  206. {
  207. position_ = position;
  208. rotation_ = rotation;
  209. if (!dirty_)
  210. MarkDirty();
  211. }
  212. else
  213. {
  214. targetPosition_ = position;
  215. targetRotation_ = rotation;
  216. smoothingMask_ |= SMOOTH_POSITION | SMOOTH_ROTATION;
  217. }
  218. rotateCount_ = 0;
  219. }
  220. void Node::SetTransform(const Vector3& position, const Quaternion& rotation, float scale)
  221. {
  222. if (!smoothed_)
  223. {
  224. position_ = position;
  225. rotation_ = rotation;
  226. }
  227. else
  228. {
  229. targetPosition_ = position;
  230. targetRotation_ = rotation;
  231. smoothingMask_ |= SMOOTH_POSITION | SMOOTH_ROTATION;
  232. }
  233. rotateCount_ = 0;
  234. scale_ = Vector3(scale, scale, scale);
  235. if (!dirty_)
  236. MarkDirty();
  237. }
  238. void Node::SetTransform(const Vector3& position, const Quaternion& rotation, const Vector3& scale)
  239. {
  240. if (!smoothed_)
  241. {
  242. position_ = position;
  243. rotation_ = rotation;
  244. }
  245. else
  246. {
  247. targetPosition_ = position;
  248. targetRotation_ = rotation;
  249. smoothingMask_ |= SMOOTH_POSITION | SMOOTH_ROTATION;
  250. }
  251. rotateCount_ = 0;
  252. scale_ = scale;
  253. if (!dirty_)
  254. MarkDirty();
  255. }
  256. void Node::SnapPosition(const Vector3& position)
  257. {
  258. position_ = position;
  259. targetPosition_ = position;
  260. smoothingMask_ &= ~SMOOTH_POSITION;
  261. if (!dirty_)
  262. MarkDirty();
  263. }
  264. void Node::SnapRotation(const Quaternion& rotation)
  265. {
  266. rotation_ = rotation;
  267. targetRotation_ = rotation;
  268. smoothingMask_ &= ~SMOOTH_ROTATION;
  269. rotateCount_ = 0;
  270. if (!dirty_)
  271. MarkDirty();
  272. }
  273. void Node::Translate(const Vector3& delta)
  274. {
  275. if (!smoothed_)
  276. {
  277. position_ += delta;
  278. if (!dirty_)
  279. MarkDirty();
  280. }
  281. else
  282. {
  283. targetPosition_ += delta;
  284. smoothingMask_ |= SMOOTH_POSITION;
  285. }
  286. }
  287. void Node::TranslateRelative(const Vector3& delta)
  288. {
  289. if (!smoothed_)
  290. {
  291. position_ += rotation_ * delta;
  292. if (!dirty_)
  293. MarkDirty();
  294. }
  295. else
  296. {
  297. targetPosition_ += targetRotation_ * delta;
  298. smoothingMask_ |= SMOOTH_POSITION;
  299. }
  300. }
  301. void Node::Rotate(const Quaternion& delta, bool fixedAxis)
  302. {
  303. if (!smoothed_)
  304. {
  305. if (!fixedAxis)
  306. rotation_ = rotation_ * delta;
  307. else
  308. rotation_ = delta * rotation_;
  309. }
  310. else
  311. {
  312. if (!fixedAxis)
  313. targetRotation_ = targetRotation_ * delta;
  314. else
  315. targetRotation_ = delta * targetRotation_;
  316. smoothingMask_ |= SMOOTH_ROTATION;
  317. }
  318. ++rotateCount_;
  319. if (rotateCount_ >= NORMALIZE_ROTATION_EVERY)
  320. {
  321. if (!smoothed_)
  322. rotation_.Normalize();
  323. else
  324. targetRotation_.Normalize();
  325. rotateCount_ = 0;
  326. }
  327. if (!dirty_)
  328. MarkDirty();
  329. }
  330. void Node::Yaw(float angle, bool fixedAxis)
  331. {
  332. Rotate(Quaternion(angle, Vector3::UP), fixedAxis);
  333. }
  334. void Node::Pitch(float angle, bool fixedAxis)
  335. {
  336. Rotate(Quaternion(angle, Vector3::RIGHT), fixedAxis);
  337. }
  338. void Node::Roll(float angle, bool fixedAxis)
  339. {
  340. Rotate(Quaternion(angle, Vector3::FORWARD), fixedAxis);
  341. }
  342. void Node::Scale(float scale)
  343. {
  344. scale_ *= scale;
  345. if (!dirty_)
  346. MarkDirty();
  347. }
  348. void Node::Scale(const Vector3& scale)
  349. {
  350. scale_ *= scale;
  351. if (!dirty_)
  352. MarkDirty();
  353. }
  354. void Node::SetOwner(Connection* owner)
  355. {
  356. owner_ = owner;
  357. }
  358. void Node::SetSmoothed(bool enable)
  359. {
  360. smoothed_ = enable;
  361. }
  362. void Node::MarkDirty()
  363. {
  364. dirty_ = true;
  365. // Notify listener components first, then mark child nodes
  366. for (Vector<WeakPtr<Component> >::Iterator i = listeners_.Begin(); i != listeners_.End();)
  367. {
  368. if (*i)
  369. {
  370. (*i)->OnMarkedDirty(this);
  371. ++i;
  372. }
  373. // If listener has expired, erase from list
  374. else
  375. i = listeners_.Erase(i);
  376. }
  377. for (Vector<SharedPtr<Node> >::Iterator i = children_.Begin(); i != children_.End(); ++i)
  378. (*i)->MarkDirty();
  379. }
  380. Node* Node::CreateChild(const String& name, CreateMode mode)
  381. {
  382. Node* newNode = CreateChild(0, mode);
  383. newNode->SetName(name);
  384. return newNode;
  385. }
  386. void Node::AddChild(Node* node)
  387. {
  388. // Check for illegal or redundant parent assignment
  389. if (!node || node == this || node->parent_ == this)
  390. return;
  391. // Check for possible cyclic parent assignment
  392. Node* parent = parent_;
  393. while (parent)
  394. {
  395. if (parent == node)
  396. return;
  397. parent = parent->parent_;
  398. }
  399. // Add first, then remove from old parent, to ensure the node does not get deleted
  400. children_.Push(SharedPtr<Node>(node));
  401. if (node->parent_)
  402. node->parent_->RemoveChild(node);
  403. // Add to the scene if not added yet
  404. if (scene_ && !node->GetScene())
  405. scene_->NodeAdded(node);
  406. node->parent_ = this;
  407. node->MarkDirty();
  408. }
  409. void Node::RemoveChild(Node* node)
  410. {
  411. if (!node)
  412. return;
  413. for (Vector<SharedPtr<Node> >::Iterator i = children_.Begin(); i != children_.End(); ++i)
  414. {
  415. if (*i == node)
  416. {
  417. RemoveChild(i);
  418. return;
  419. }
  420. }
  421. }
  422. void Node::RemoveAllChildren()
  423. {
  424. while (children_.Size())
  425. RemoveChild(children_.End() - 1);
  426. }
  427. Component* Node::CreateComponent(ShortStringHash type, CreateMode mode)
  428. {
  429. return CreateComponent(type, 0, mode);
  430. }
  431. Component* Node::GetOrCreateComponent(ShortStringHash type, CreateMode mode)
  432. {
  433. Component* oldComponent = GetComponent(type);
  434. if (oldComponent)
  435. return oldComponent;
  436. else
  437. return CreateComponent(type, 0, mode);
  438. }
  439. void Node::RemoveComponent(Component* component)
  440. {
  441. for (Vector<SharedPtr<Component> >::Iterator i = components_.Begin(); i != components_.End(); ++i)
  442. {
  443. if (*i == component)
  444. {
  445. WeakPtr<Component> componentWeak(*i);
  446. RemoveListener(*i);
  447. if (scene_)
  448. scene_->ComponentRemoved(*i);
  449. components_.Erase(i);
  450. // If the component is still referenced elsewhere, reset its node pointer now
  451. if (componentWeak)
  452. componentWeak->SetNode(0);
  453. return;
  454. }
  455. }
  456. }
  457. void Node::RemoveAllComponents()
  458. {
  459. while (components_.Size())
  460. {
  461. Vector<SharedPtr<Component> >::Iterator i = components_.End() - 1;
  462. WeakPtr<Component> componentWeak(*i);
  463. RemoveListener(*i);
  464. if (scene_)
  465. scene_->ComponentRemoved(*i);
  466. components_.Erase(i);
  467. // If the component is still referenced elsewhere, reset its node pointer now
  468. if (componentWeak)
  469. componentWeak->SetNode(0);
  470. }
  471. }
  472. void Node::AddListener(Component* component)
  473. {
  474. if (!component)
  475. return;
  476. // Check for not adding twice
  477. for (Vector<WeakPtr<Component> >::Iterator i = listeners_.Begin(); i != listeners_.End(); ++i)
  478. {
  479. if (*i == component)
  480. return;
  481. }
  482. listeners_.Push(WeakPtr<Component>(component));
  483. // If the node is currently dirty, notify immediately
  484. if (dirty_)
  485. component->OnMarkedDirty(this);
  486. }
  487. void Node::RemoveListener(Component* component)
  488. {
  489. for (Vector<WeakPtr<Component> >::Iterator i = listeners_.Begin(); i != listeners_.End(); ++i)
  490. {
  491. if (*i == component)
  492. {
  493. listeners_.Erase(i);
  494. return;
  495. }
  496. }
  497. }
  498. void Node::Remove()
  499. {
  500. if (parent_)
  501. parent_->RemoveChild(this);
  502. }
  503. void Node::SetParent(Node* parent)
  504. {
  505. if (parent)
  506. parent->AddChild(this);
  507. }
  508. Matrix3x4 Node::GetWorldTargetTransform() const
  509. {
  510. if (!smoothed_)
  511. return GetWorldTransform();
  512. Matrix3x4 ret(targetPosition_, targetRotation_, scale_);
  513. Node* current = parent_;
  514. while (current)
  515. {
  516. ret = Matrix3x4(current->targetPosition_, current->targetRotation_, current->scale_) * ret;
  517. current = current->parent_;
  518. }
  519. return ret;
  520. }
  521. Vector3 Node::LocalToWorld(const Vector3& position) const
  522. {
  523. return GetWorldTransform() * position;
  524. }
  525. Vector3 Node::LocalToWorld(const Vector4& vector) const
  526. {
  527. return GetWorldTransform() * vector;
  528. }
  529. Vector3 Node::WorldToLocal(const Vector3& position) const
  530. {
  531. return GetWorldTransform().Inverse() * position;
  532. }
  533. Vector3 Node::WorldToLocal(const Vector4& vector) const
  534. {
  535. return GetWorldTransform().Inverse() * vector;
  536. }
  537. unsigned Node::GetNumChildren(bool recursive) const
  538. {
  539. if (!recursive)
  540. return children_.Size();
  541. else
  542. {
  543. unsigned allChildren = children_.Size();
  544. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  545. allChildren += (*i)->GetNumChildren(true);
  546. return allChildren;
  547. }
  548. }
  549. void Node::GetChildren(PODVector<Node*>& dest, bool recursive) const
  550. {
  551. dest.Clear();
  552. if (!recursive)
  553. {
  554. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  555. dest.Push(*i);
  556. }
  557. else
  558. GetChildrenRecursive(dest);
  559. }
  560. void Node::GetChildrenWithComponent(PODVector<Node*>& dest, ShortStringHash type, bool recursive) const
  561. {
  562. dest.Clear();
  563. if (!recursive)
  564. {
  565. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  566. {
  567. if ((*i)->HasComponent(type))
  568. dest.Push(*i);
  569. }
  570. }
  571. else
  572. GetChildrenWithComponentRecursive(dest, type);
  573. }
  574. Node* Node::GetChild(unsigned index) const
  575. {
  576. return index < children_.Size() ? children_[index].Get() : 0;
  577. }
  578. Node* Node::GetChild(const String& name, bool recursive) const
  579. {
  580. return GetChild(StringHash(name), recursive);
  581. }
  582. Node* Node::GetChild(StringHash nameHash, bool recursive) const
  583. {
  584. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  585. {
  586. if ((*i)->GetNameHash() == nameHash)
  587. return *i;
  588. if (recursive)
  589. {
  590. Node* node = (*i)->GetChild(nameHash, true);
  591. if (node)
  592. return node;
  593. }
  594. }
  595. return 0;
  596. }
  597. unsigned Node::GetNumNetworkComponents() const
  598. {
  599. unsigned num = 0;
  600. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  601. {
  602. if ((*i)->GetID() < FIRST_LOCAL_ID)
  603. ++num;
  604. }
  605. return num;
  606. }
  607. void Node::GetComponents(PODVector<Component*>& dest, ShortStringHash type) const
  608. {
  609. dest.Clear();
  610. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  611. {
  612. if ((*i)->GetType() == type)
  613. dest.Push(*i);
  614. }
  615. }
  616. bool Node::HasComponent(ShortStringHash type) const
  617. {
  618. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  619. {
  620. if ((*i)->GetType() == type)
  621. return true;
  622. }
  623. return false;
  624. }
  625. Component* Node::GetComponent(ShortStringHash type) const
  626. {
  627. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  628. {
  629. if ((*i)->GetType() == type)
  630. return *i;
  631. }
  632. return 0;
  633. }
  634. void Node::GetDependencyNodes(PODVector<Node*>& dest) const
  635. {
  636. // Add the parent node, but if it is local, traverse to the first non-local node
  637. if (parent_ && parent_ != scene_)
  638. {
  639. Node* current = parent_;
  640. while (current->id_ >= FIRST_LOCAL_ID)
  641. current = current->parent_;
  642. dest.Push(current);
  643. }
  644. // Then let the components add their dependencies
  645. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  646. (*i)->GetDependencyNodes(dest);
  647. }
  648. void Node::SetID(unsigned id)
  649. {
  650. id_ = id;
  651. }
  652. void Node::SetScene(Scene* scene)
  653. {
  654. scene_ = scene;
  655. }
  656. void Node::SetNetRotationAttr(const PODVector<unsigned char>& value)
  657. {
  658. MemoryBuffer buf(value);
  659. SetRotation(buf.ReadPackedQuaternion());
  660. }
  661. void Node::SetNetParentAttr(const PODVector<unsigned char>& value)
  662. {
  663. Scene* scene = GetScene();
  664. if (!scene)
  665. return;
  666. MemoryBuffer buf(value);
  667. // If nothing in the buffer, parent is the root node
  668. if (buf.IsEof())
  669. {
  670. SetParent(scene);
  671. return;
  672. }
  673. unsigned baseNodeID = buf.ReadNetID();
  674. Node* baseNode = scene->GetNode(baseNodeID);
  675. if (!baseNode)
  676. {
  677. LOGWARNING("Failed to find parent node " + String(baseNodeID));
  678. return;
  679. }
  680. // If buffer contains just an ID, the parent is replicated and we are done
  681. if (buf.IsEof())
  682. SetParent(baseNode);
  683. else
  684. {
  685. // Else the parent is local and we must find it recursively by name hash
  686. StringHash nameHash = buf.ReadStringHash();
  687. Node* parentNode = baseNode->GetChild(nameHash, true);
  688. if (!parentNode)
  689. LOGWARNING("Failed to find parent node with name hash " + nameHash.ToString());
  690. else
  691. SetParent(parentNode);
  692. }
  693. }
  694. const PODVector<unsigned char>& Node::GetNetRotationAttr() const
  695. {
  696. attrBuffer_.Clear();
  697. attrBuffer_.WritePackedQuaternion(rotation_);
  698. return attrBuffer_.GetBuffer();
  699. }
  700. const PODVector<unsigned char>& Node::GetNetParentAttr() const
  701. {
  702. attrBuffer_.Clear();
  703. Scene* scene = GetScene();
  704. if (scene && parent_ && parent_ != scene)
  705. {
  706. // If parent is replicated, can write the ID directly
  707. unsigned parentID = parent_->GetID();
  708. if (parentID < FIRST_LOCAL_ID)
  709. attrBuffer_.WriteNetID(parentID);
  710. else
  711. {
  712. // Parent is local: traverse hierarchy to find a non-local base node
  713. // This iteration always stops due to the scene (root) being non-local
  714. Node* current = parent_;
  715. while (current->GetID() >= FIRST_LOCAL_ID)
  716. current = current->GetParent();
  717. // Then write the base node ID and the parent's name hash
  718. attrBuffer_.WriteVLE(current->GetID());
  719. attrBuffer_.WriteStringHash(parent_->GetNameHash());
  720. }
  721. }
  722. return attrBuffer_.GetBuffer();
  723. }
  724. void Node::UpdateSmoothing(float constant, float squaredSnapThreshold)
  725. {
  726. if (!smoothed_ || !smoothingMask_)
  727. return;
  728. if (smoothingMask_ & SMOOTH_POSITION)
  729. {
  730. // If position snaps, snap everything to the end
  731. float delta = (position_ - targetPosition_).LengthSquared();
  732. if (delta > squaredSnapThreshold)
  733. constant = 1.0f;
  734. if (delta < M_EPSILON || constant >= 1.0f)
  735. {
  736. position_ = targetPosition_;
  737. smoothingMask_ &= ~SMOOTH_POSITION;
  738. }
  739. else
  740. position_ = position_.Lerp(targetPosition_, constant);
  741. }
  742. if (smoothingMask_ & SMOOTH_ROTATION)
  743. {
  744. float delta = (rotation_ - targetRotation_).LengthSquared();
  745. if (delta < M_EPSILON || constant >= 1.0f)
  746. {
  747. rotation_ = targetRotation_;
  748. smoothingMask_ &= ~SMOOTH_ROTATION;
  749. }
  750. else
  751. rotation_ = rotation_.Slerp(targetRotation_, constant);
  752. }
  753. if (!dirty_)
  754. MarkDirty();
  755. }
  756. bool Node::Load(Deserializer& source, bool readChildren)
  757. {
  758. // Remove all children and components first in case this is not a fresh load
  759. RemoveAllChildren();
  760. RemoveAllComponents();
  761. // ID has been read at the parent level
  762. if (!Serializable::Load(source))
  763. return false;
  764. unsigned numComponents = source.ReadVLE();
  765. for (unsigned i = 0; i < numComponents; ++i)
  766. {
  767. VectorBuffer compBuffer(source, source.ReadVLE());
  768. ShortStringHash newType = compBuffer.ReadShortStringHash();
  769. Component* newComponent = CreateComponent(newType, compBuffer.ReadUInt(), REPLICATED);
  770. if (newComponent)
  771. {
  772. if (!newComponent->Load(compBuffer))
  773. return false;
  774. }
  775. }
  776. if (!readChildren)
  777. return true;
  778. unsigned numChildren = source.ReadVLE();
  779. for (unsigned i = 0; i < numChildren; ++i)
  780. {
  781. Node* newNode = CreateChild(source.ReadUInt(), REPLICATED);
  782. if (!newNode->Load(source))
  783. return false;
  784. }
  785. return true;
  786. }
  787. bool Node::LoadXML(const XMLElement& source, bool readChildren)
  788. {
  789. // Remove all children and components first in case this is not a fresh load
  790. RemoveAllChildren();
  791. RemoveAllComponents();
  792. if (!Serializable::LoadXML(source))
  793. return false;
  794. XMLElement compElem = source.GetChild("component");
  795. while (compElem)
  796. {
  797. String typeName = compElem.GetString("type");
  798. Component* newComponent = CreateComponent(ShortStringHash(compElem.GetString("type")), compElem.GetInt("id"), REPLICATED);
  799. if (newComponent)
  800. {
  801. if (!newComponent->LoadXML(compElem))
  802. return false;
  803. }
  804. compElem = compElem.GetNext("component");
  805. }
  806. if (!readChildren)
  807. return true;
  808. XMLElement childElem = source.GetChild("node");
  809. while (childElem)
  810. {
  811. Node* newNode = CreateChild(childElem.GetInt("id"), REPLICATED);
  812. if (!newNode->LoadXML(childElem))
  813. return false;
  814. childElem = childElem.GetNext("node");
  815. }
  816. return true;
  817. }
  818. Component* Node::CreateComponent(ShortStringHash type, unsigned id, CreateMode mode)
  819. {
  820. // Check that creation succeeds and that the object in fact is a component
  821. SharedPtr<Component> newComponent = DynamicCast<Component>(context_->CreateObject(type));
  822. if (!newComponent)
  823. {
  824. LOGERROR("Could not create unknown component type " + type.ToString());
  825. return 0;
  826. }
  827. components_.Push(newComponent);
  828. // If zero ID specified, or the ID is already taken, let the scene assign
  829. if (scene_)
  830. {
  831. if (!id || scene_->GetComponent(id))
  832. id = scene_->GetFreeComponentID(mode);
  833. newComponent->SetID(id);
  834. scene_->ComponentAdded(newComponent);
  835. }
  836. else
  837. newComponent->SetID(id);
  838. newComponent->SetNode(this);
  839. newComponent->OnMarkedDirty(this);
  840. return newComponent;
  841. }
  842. Node* Node::CreateChild(unsigned id, CreateMode mode)
  843. {
  844. SharedPtr<Node> newNode(new Node(context_));
  845. // If zero ID specified, or the ID is already taken, let the scene assign
  846. if (scene_)
  847. {
  848. if (!id || scene_->GetNode(id))
  849. id = scene_->GetFreeNodeID(mode);
  850. newNode->SetID(id);
  851. }
  852. else
  853. newNode->SetID(id);
  854. AddChild(newNode);
  855. return newNode;
  856. }
  857. void Node::UpdateWorldTransform() const
  858. {
  859. if (parent_)
  860. {
  861. if (parent_->dirty_)
  862. parent_->UpdateWorldTransform();
  863. worldTransform_ = parent_->worldTransform_ * Matrix3x4(position_, rotation_, scale_);
  864. }
  865. else
  866. worldTransform_ = Matrix3x4(position_, rotation_, scale_);
  867. dirty_ = false;
  868. }
  869. void Node::RemoveChild(Vector<SharedPtr<Node> >::Iterator i)
  870. {
  871. (*i)->parent_ = 0;
  872. (*i)->MarkDirty();
  873. children_.Erase(i);
  874. }
  875. void Node::GetChildrenRecursive(PODVector<Node*>& dest) const
  876. {
  877. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  878. {
  879. Node* node = *i;
  880. dest.Push(node);
  881. if (!node->children_.Empty())
  882. node->GetChildrenRecursive(dest);
  883. }
  884. }
  885. void Node::GetChildrenWithComponentRecursive(PODVector<Node*>& dest, ShortStringHash type) const
  886. {
  887. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  888. {
  889. Node* node = *i;
  890. if (node->HasComponent(type))
  891. dest.Push(node);
  892. if (!node->children_.Empty())
  893. node->GetChildrenRecursive(dest);
  894. }
  895. }