Node.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748
  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 "Scene.h"
  28. #include "StringUtils.h"
  29. #include "VectorBuffer.h"
  30. #include "XMLElement.h"
  31. #include "DebugNew.h"
  32. // Normalize rotation quaternion after this many incremental updates to prevent distortion
  33. static const int NORMALIZE_ROTATION_EVERY = 32;
  34. OBJECTTYPESTATIC(Node);
  35. Node::Node(Context* context) :
  36. Serializable(context),
  37. id_(0),
  38. parent_(0),
  39. scene_(0),
  40. position_(Vector3::ZERO),
  41. rotation_(Quaternion::IDENTITY),
  42. scale_(Vector3::UNITY),
  43. worldTransform_(Matrix4x3::IDENTITY),
  44. rotateCount_(0),
  45. dirty_(false)
  46. {
  47. }
  48. Node::~Node()
  49. {
  50. RemoveAllChildren();
  51. RemoveAllComponents();
  52. // Remove from the scene
  53. if (scene_)
  54. scene_->NodeRemoved(this);
  55. }
  56. void Node::RegisterObject(Context* context)
  57. {
  58. context->RegisterFactory<Node>();
  59. ATTRIBUTE(Node, VAR_STRING, "Name", name_, std::string());
  60. ATTRIBUTE(Node, VAR_VECTOR3, "Position", position_, Vector3::ZERO);
  61. ATTRIBUTE(Node, VAR_QUATERNION, "Rotation", rotation_, Quaternion::IDENTITY);
  62. ATTRIBUTE(Node, VAR_VECTOR3, "Scale", scale_, Vector3::UNITY);
  63. }
  64. void Node::OnEvent(Object* sender, bool broadcast, StringHash eventType, VariantMap& eventData)
  65. {
  66. // Make a weak pointer to self to check for destruction during event handling
  67. WeakPtr<Node> self(this);
  68. // If this is a targeted event, forward it to all components
  69. if (!broadcast)
  70. {
  71. for (unsigned i = components_.size() - 1; i < components_.size(); --i)
  72. {
  73. components_[i]->OnEvent(sender, broadcast, eventType, eventData);
  74. if (self.IsExpired())
  75. return;
  76. }
  77. }
  78. else
  79. Object::OnEvent(sender, broadcast, eventType, eventData);
  80. }
  81. void Node::OnSetAttribute(const AttributeInfo& attr, const Variant& value)
  82. {
  83. switch (attr.offset_)
  84. {
  85. case offsetof(Node, name_):
  86. SetName(value.GetString());
  87. break;
  88. case offsetof(Node, position_):
  89. case offsetof(Node, rotation_):
  90. case offsetof(Node, scale_):
  91. Serializable::OnSetAttribute(attr, value);
  92. // If transform changes, dirty the node as applicable
  93. if (!dirty_)
  94. MarkDirty();
  95. break;
  96. default:
  97. Serializable::OnSetAttribute(attr, value);
  98. break;
  99. }
  100. }
  101. bool Node::Load(Deserializer& source)
  102. {
  103. // Remove all children and components first in case this is not a fresh load
  104. RemoveAllChildren();
  105. RemoveAllComponents();
  106. // ID has been read at the parent level
  107. if (!Serializable::Load(source))
  108. return false;
  109. unsigned numComponents = source.ReadVLE();
  110. for (unsigned i = 0; i < numComponents; ++i)
  111. {
  112. VectorBuffer compBuffer(source, source.ReadVLE());
  113. ShortStringHash newType = compBuffer.ReadShortStringHash();
  114. Component* newComponent = CreateComponent(newType, compBuffer.ReadUInt());
  115. if (newComponent)
  116. {
  117. if (!newComponent->Load(compBuffer))
  118. return false;
  119. }
  120. }
  121. unsigned numChildren = source.ReadVLE();
  122. for (unsigned i = 0; i < numChildren; ++i)
  123. {
  124. Node* newNode = CreateChild(source.ReadUInt());
  125. if (!newNode->Load(source))
  126. return false;
  127. }
  128. return true;
  129. }
  130. bool Node::Save(Serializer& dest)
  131. {
  132. if (!Serializable::Save(dest))
  133. return false;
  134. dest.WriteVLE(components_.size());
  135. for (unsigned i = 0; i < components_.size(); ++i)
  136. {
  137. Component* component = components_[i];
  138. // Create a separate buffer to be able to skip unknown components during deserialization
  139. VectorBuffer compBuffer;
  140. compBuffer.WriteShortStringHash(component->GetType());
  141. compBuffer.WriteUInt(component->GetID());
  142. if (!component->Save(compBuffer))
  143. return false;
  144. dest.WriteVLE(compBuffer.GetSize());
  145. dest.Write(compBuffer.GetData(), compBuffer.GetSize());
  146. }
  147. dest.WriteVLE(children_.size());
  148. for (unsigned i = 0; i < children_.size(); ++i)
  149. {
  150. Node* node = children_[i];
  151. dest.WriteUInt(node->GetID());
  152. if (!node->Save(dest))
  153. return false;
  154. }
  155. return true;
  156. }
  157. bool Node::LoadXML(const XMLElement& source)
  158. {
  159. // Remove all children and components first in case this is not a fresh load
  160. RemoveAllChildren();
  161. RemoveAllComponents();
  162. if (!Serializable::LoadXML(source))
  163. return false;
  164. XMLElement compElem = source.GetChildElement("component");
  165. while (compElem)
  166. {
  167. std::string typeName = compElem.GetString("type");
  168. Component* newComponent = CreateComponent(ShortStringHash(compElem.GetString("type")), compElem.GetInt("id"));
  169. if (newComponent)
  170. {
  171. if (!newComponent->LoadXML(compElem))
  172. return false;
  173. }
  174. compElem = compElem.GetNextElement("component");
  175. }
  176. XMLElement childElem = source.GetChildElement("node");
  177. while (childElem)
  178. {
  179. Node* newNode = CreateChild(compElem.GetInt("id"));
  180. if (!newNode->LoadXML(childElem))
  181. return false;
  182. childElem = childElem.GetNextElement("node");
  183. }
  184. return true;
  185. }
  186. bool Node::SaveXML(XMLElement& dest)
  187. {
  188. if (!Serializable::SaveXML(dest))
  189. return false;
  190. for (unsigned i = 0; i < components_.size(); ++i)
  191. {
  192. Component* component = components_[i];
  193. XMLElement compElem = dest.CreateChildElement("component");
  194. compElem.SetString("type", component->GetTypeNameStr());
  195. compElem.SetInt("id", component->GetID());
  196. if (!component->SaveXML(compElem))
  197. return false;
  198. }
  199. for (unsigned i = 0; i < children_.size(); ++i)
  200. {
  201. Node* node = children_[i];
  202. XMLElement childElem = dest.CreateChildElement("node");
  203. childElem.SetInt("id", node->GetID());
  204. if (!node->SaveXML(childElem))
  205. return false;
  206. }
  207. return true;
  208. }
  209. void Node::PostLoad()
  210. {
  211. for (unsigned i = 0; i < components_.size(); ++i)
  212. components_[i]->PostLoad();
  213. for (unsigned i = 0; i < children_.size(); ++i)
  214. children_[i]->PostLoad();
  215. }
  216. void Node::SetName(const std::string& name)
  217. {
  218. name_ = name;
  219. nameHash_ = StringHash(name);
  220. }
  221. void Node::SetPosition(const Vector3& position)
  222. {
  223. position_ = position;
  224. if (!dirty_)
  225. MarkDirty();
  226. }
  227. void Node::SetRotation(const Quaternion& rotation)
  228. {
  229. rotation_ = rotation;
  230. rotateCount_ = 0;
  231. if (!dirty_)
  232. MarkDirty();
  233. }
  234. void Node::SetDirection(const Vector3& direction)
  235. {
  236. SetRotation(Quaternion(Vector3::FORWARD, direction));
  237. }
  238. void Node::SetScale(float scale)
  239. {
  240. scale_ = Vector3(scale, scale, scale);
  241. if (!dirty_)
  242. MarkDirty();
  243. }
  244. void Node::SetScale(const Vector3& scale)
  245. {
  246. scale_ = scale;
  247. if (!dirty_)
  248. MarkDirty();
  249. }
  250. void Node::SetTransform(const Vector3& position, const Quaternion& rotation)
  251. {
  252. position_ = position;
  253. rotation_ = rotation;
  254. rotateCount_ = 0;
  255. if (!dirty_)
  256. MarkDirty();
  257. }
  258. void Node::SetTransform(const Vector3& position, const Quaternion& rotation, float scale)
  259. {
  260. position_ = position;
  261. rotation_ = rotation;
  262. scale_ = Vector3(scale, scale, scale);
  263. rotateCount_ = 0;
  264. if (!dirty_)
  265. MarkDirty();
  266. }
  267. void Node::SetTransform(const Vector3& position, const Quaternion& rotation, const Vector3& scale)
  268. {
  269. position_ = position;
  270. rotation_ = rotation;
  271. scale_ = scale;
  272. rotateCount_ = 0;
  273. if (!dirty_)
  274. MarkDirty();
  275. }
  276. void Node::Translate(const Vector3& delta)
  277. {
  278. position_ += delta;
  279. if (!dirty_)
  280. MarkDirty();
  281. }
  282. void Node::TranslateRelative(const Vector3& delta)
  283. {
  284. position_ += rotation_ * delta;
  285. if (!dirty_)
  286. MarkDirty();
  287. }
  288. void Node::Rotate(const Quaternion& delta, bool fixedAxis)
  289. {
  290. if (!fixedAxis)
  291. rotation_ = rotation_ * delta;
  292. else
  293. rotation_ = delta * rotation_;
  294. ++rotateCount_;
  295. if (rotateCount_ >= NORMALIZE_ROTATION_EVERY)
  296. {
  297. rotation_.Normalize();
  298. rotateCount_ = 0;
  299. }
  300. if (!dirty_)
  301. MarkDirty();
  302. }
  303. void Node::Yaw(float angle, bool fixedAxis)
  304. {
  305. Rotate(Quaternion(angle, Vector3::UP), fixedAxis);
  306. }
  307. void Node::Pitch(float angle, bool fixedAxis)
  308. {
  309. Rotate(Quaternion(angle, Vector3::RIGHT), fixedAxis);
  310. }
  311. void Node::Roll(float angle, bool fixedAxis)
  312. {
  313. Rotate(Quaternion(angle, Vector3::FORWARD), fixedAxis);
  314. }
  315. void Node::Scale(float scale)
  316. {
  317. scale_ *= scale;
  318. if (!dirty_)
  319. MarkDirty();
  320. }
  321. void Node::Scale(const Vector3& scale)
  322. {
  323. scale_ *= scale;
  324. if (!dirty_)
  325. MarkDirty();
  326. }
  327. void Node::MarkDirty()
  328. {
  329. dirty_ = true;
  330. // Notify listener components first, then mark child nodes
  331. for (std::vector<WeakPtr<Component> >::iterator i = listeners_.begin(); i != listeners_.end();)
  332. {
  333. if (*i)
  334. {
  335. (*i)->OnMarkedDirty(this);
  336. ++i;
  337. }
  338. // If listener has expired, erase from list
  339. else
  340. i = listeners_.erase(i);
  341. }
  342. for (std::vector<SharedPtr<Node> >::iterator i = children_.begin(); i != children_.end(); ++i)
  343. (*i)->MarkDirty();
  344. }
  345. Node* Node::CreateChild(const std::string& name)
  346. {
  347. SharedPtr<Node> newNode(new Node(context_));
  348. newNode->SetName(name);
  349. AddChild(newNode);
  350. return newNode;
  351. }
  352. void Node::AddChild(Node* node)
  353. {
  354. // Check for illegal parent assignments, including attempt to reparent the scene
  355. if ((!node) || (node == this) || (node->parent_ == this) || (parent_ == node) || (scene_ == node))
  356. return;
  357. // Add first, then remove from old parent, to ensure the node does not get deleted
  358. children_.push_back(SharedPtr<Node>(node));
  359. if (node->parent_)
  360. node->parent_->RemoveChild(node);
  361. // Add to the scene if not added yet
  362. if ((scene_) && (!node->GetScene()))
  363. scene_->NodeAdded(node);
  364. node->parent_ = this;
  365. node->MarkDirty();
  366. }
  367. void Node::RemoveChild(Node* node)
  368. {
  369. if (!node)
  370. return;
  371. for (std::vector<SharedPtr<Node> >::iterator i = children_.begin(); i != children_.end(); ++i)
  372. {
  373. if (i->GetPtr() == node)
  374. {
  375. RemoveChild(i);
  376. return;
  377. }
  378. }
  379. }
  380. void Node::RemoveAllChildren()
  381. {
  382. while (children_.size())
  383. RemoveChild(children_.end() - 1);
  384. }
  385. void Node::SetParent(Node* parent)
  386. {
  387. if (parent)
  388. parent->AddChild(this);
  389. }
  390. Component* Node::CreateComponent(ShortStringHash type)
  391. {
  392. return CreateComponent(type, 0);
  393. }
  394. Component* Node::GetOrCreateComponent(ShortStringHash type)
  395. {
  396. Component* oldComponent = GetComponent(type);
  397. if (oldComponent)
  398. return oldComponent;
  399. else
  400. return CreateComponent(type, 0);
  401. }
  402. void Node::RemoveComponent(Component* component)
  403. {
  404. for (std::vector<SharedPtr<Component> >::iterator i = components_.begin(); i != components_.end(); ++i)
  405. {
  406. if (*i == component)
  407. {
  408. WeakPtr<Component> componentWeak(*i);
  409. RemoveListener(*i);
  410. if (scene_)
  411. scene_->ComponentRemoved(*i);
  412. components_.erase(i);
  413. // If the component is still referenced elsewhere, reset its node pointer now
  414. if (componentWeak)
  415. componentWeak->SetNode(0);
  416. return;
  417. }
  418. }
  419. }
  420. void Node::RemoveAllComponents()
  421. {
  422. while (components_.size())
  423. {
  424. std::vector<SharedPtr<Component> >::iterator i = components_.end() - 1;
  425. WeakPtr<Component> componentWeak(*i);
  426. RemoveListener(*i);
  427. if (scene_)
  428. scene_->ComponentRemoved(*i);
  429. components_.erase(i);
  430. // If the component is still referenced elsewhere, reset its node pointer now
  431. if (componentWeak)
  432. componentWeak->SetNode(0);
  433. }
  434. }
  435. void Node::AddListener(Component* component)
  436. {
  437. if (!component)
  438. return;
  439. // Check for not adding twice
  440. for (std::vector<WeakPtr<Component> >::iterator i = listeners_.begin(); i != listeners_.end(); ++i)
  441. {
  442. if ((*i) == component)
  443. return;
  444. }
  445. listeners_.push_back(WeakPtr<Component>(component));
  446. // If the node is currently dirty, notify immediately
  447. if (dirty_)
  448. component->OnMarkedDirty(this);
  449. }
  450. void Node::RemoveListener(Component* component)
  451. {
  452. for (std::vector<WeakPtr<Component> >::iterator i = listeners_.begin(); i != listeners_.end(); ++i)
  453. {
  454. if ((*i) == component)
  455. {
  456. listeners_.erase(i);
  457. return;
  458. }
  459. }
  460. }
  461. void Node::Remove()
  462. {
  463. if (parent_)
  464. parent_->RemoveChild(this);
  465. }
  466. unsigned Node::GetNumChildren(bool recursive) const
  467. {
  468. if (!recursive)
  469. return children_.size();
  470. else
  471. {
  472. unsigned allChildren = children_.size();
  473. for (std::vector<SharedPtr<Node> >::const_iterator i = children_.begin(); i != children_.end(); ++i)
  474. allChildren += (*i)->GetNumChildren(true);
  475. return allChildren;
  476. }
  477. }
  478. void Node::GetChildren(std::vector<Node*>& dest, bool recursive) const
  479. {
  480. dest.clear();
  481. if (!recursive)
  482. {
  483. for (std::vector<SharedPtr<Node> >::const_iterator i = children_.begin(); i != children_.end(); ++i)
  484. dest.push_back(*i);
  485. }
  486. else
  487. GetChildrenRecursive(dest);
  488. }
  489. void Node::GetChildrenWithComponent(std::vector<Node*>& dest, ShortStringHash type, bool recursive) const
  490. {
  491. dest.clear();
  492. if (!recursive)
  493. {
  494. for (std::vector<SharedPtr<Node> >::const_iterator i = children_.begin(); i != children_.end(); ++i)
  495. {
  496. if ((*i)->HasComponent(type))
  497. dest.push_back(*i);
  498. }
  499. }
  500. else
  501. GetChildrenWithComponentRecursive(dest, type);
  502. }
  503. Node* Node::GetChild(unsigned index) const
  504. {
  505. return index < children_.size() ? children_[index].GetPtr() : 0;
  506. }
  507. Node* Node::GetChild(const std::string& name, bool recursive) const
  508. {
  509. return GetChild(StringHash(name), recursive);
  510. }
  511. Node* Node::GetChild(StringHash nameHash, bool recursive) const
  512. {
  513. for (std::vector<SharedPtr<Node> >::const_iterator i = children_.begin(); i != children_.end(); ++i)
  514. {
  515. if ((*i)->GetNameHash() == nameHash)
  516. return *i;
  517. if (recursive)
  518. {
  519. Node* node = (*i)->GetChild(nameHash, true);
  520. if (node)
  521. return node;
  522. }
  523. }
  524. return 0;
  525. }
  526. void Node::GetComponents(std::vector<Component*>& dest, ShortStringHash type) const
  527. {
  528. dest.clear();
  529. for (std::vector<SharedPtr<Component> >::const_iterator i = components_.begin(); i != components_.end(); ++i)
  530. {
  531. if ((*i)->GetType() == type)
  532. dest.push_back(*i);
  533. }
  534. }
  535. bool Node::HasComponent(ShortStringHash type) const
  536. {
  537. for (std::vector<SharedPtr<Component> >::const_iterator i = components_.begin(); i != components_.end(); ++i)
  538. {
  539. if ((*i)->GetType() == type)
  540. return true;
  541. }
  542. return false;
  543. }
  544. Component* Node::GetComponent(unsigned index) const
  545. {
  546. return index < components_.size() ? components_[index].GetPtr() : 0;
  547. }
  548. Component* Node::GetComponent(ShortStringHash type, unsigned index) const
  549. {
  550. unsigned cmpIndex = 0;
  551. for (std::vector<SharedPtr<Component> >::const_iterator i = components_.begin(); i != components_.end(); ++i)
  552. {
  553. if ((*i)->GetType() == type)
  554. {
  555. if (cmpIndex == index)
  556. return *i;
  557. ++cmpIndex;
  558. }
  559. }
  560. return 0;
  561. }
  562. Component* Node::CreateComponent(ShortStringHash type, unsigned id)
  563. {
  564. // Make sure the object in question is a component
  565. SharedPtr<Component> newComponent = DynamicCast<Component>(CreateObject(type));
  566. if (!newComponent)
  567. {
  568. LOGERROR("Could not create unknown component type " + ToString(type));
  569. return 0;
  570. }
  571. // If zero ID specified, the scene will auto-assign
  572. newComponent->SetID(id);
  573. components_.push_back(newComponent);
  574. if (scene_)
  575. scene_->ComponentAdded(newComponent);
  576. newComponent->SetNode(this);
  577. newComponent->OnMarkedDirty(this);
  578. return newComponent;
  579. }
  580. Node* Node::CreateChild(unsigned id)
  581. {
  582. SharedPtr<Node> newNode(new Node(context_));
  583. newNode->SetID(id);
  584. AddChild(newNode);
  585. return newNode;
  586. }
  587. void Node::UpdateWorldTransform()
  588. {
  589. // For now, assume that the Scene has identity transform so that we skip one matrix multiply. However in the future
  590. // we may want dynamic root nodes for large worlds
  591. if ((parent_) && (parent_ != scene_))
  592. {
  593. if (parent_->dirty_)
  594. parent_->UpdateWorldTransform();
  595. worldTransform_ = parent_->worldTransform_ * Matrix4x3(position_, rotation_, scale_);
  596. }
  597. else
  598. worldTransform_ = Matrix4x3(position_, rotation_, scale_);
  599. dirty_ = false;
  600. }
  601. void Node::RemoveChild(std::vector<SharedPtr<Node> >::iterator i)
  602. {
  603. (*i)->parent_ = 0;
  604. (*i)->MarkDirty();
  605. children_.erase(i);
  606. }
  607. void Node::GetChildrenRecursive(std::vector<Node*>& dest) const
  608. {
  609. for (std::vector<SharedPtr<Node> >::const_iterator i = children_.begin(); i != children_.end(); ++i)
  610. {
  611. Node* node = *i;
  612. dest.push_back(node);
  613. if (!node->children_.empty())
  614. node->GetChildrenRecursive(dest);
  615. }
  616. }
  617. void Node::GetChildrenWithComponentRecursive(std::vector<Node*>& dest, ShortStringHash type) const
  618. {
  619. for (std::vector<SharedPtr<Node> >::const_iterator i = children_.begin(); i != children_.end(); ++i)
  620. {
  621. Node* node = *i;
  622. if (node->HasComponent(type))
  623. dest.push_back(node);
  624. if (!node->children_.empty())
  625. node->GetChildrenRecursive(dest);
  626. }
  627. }
  628. void Node::SetID(unsigned id)
  629. {
  630. id_ = id;
  631. }
  632. void Node::setScene(Scene* scene)
  633. {
  634. scene_ = scene;
  635. }