Node.cpp 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120
  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 "Scene.h"
  30. #include "SmoothedTransform.h"
  31. #include "XMLFile.h"
  32. #include "DebugNew.h"
  33. // Normalize rotation quaternion after this many incremental updates to prevent distortion
  34. static const int NORMALIZE_ROTATION_EVERY = 32;
  35. OBJECTTYPESTATIC(Node);
  36. Node::Node(Context* context) :
  37. Serializable(context),
  38. id_(0),
  39. parent_(0),
  40. scene_(0),
  41. owner_(0),
  42. position_(Vector3::ZERO),
  43. rotation_(Quaternion::IDENTITY),
  44. scale_(Vector3::ONE),
  45. worldTransform_(Matrix3x4::IDENTITY),
  46. dependencyFrameNumber_(0),
  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. bool Node::SaveXML(Serializer& dest)
  183. {
  184. SharedPtr<XMLFile> xml(new XMLFile(context_));
  185. XMLElement rootElem = xml->CreateRoot("node");
  186. if (!SaveXML(rootElem))
  187. return false;
  188. return xml->Save(dest);
  189. }
  190. void Node::SetName(const String& name)
  191. {
  192. name_ = name;
  193. nameHash_ = StringHash(name);
  194. }
  195. void Node::SetPosition(const Vector3& position)
  196. {
  197. position_ = position;
  198. if (!dirty_)
  199. MarkDirty();
  200. }
  201. void Node::SetRotation(const Quaternion& rotation)
  202. {
  203. rotation_ = rotation;
  204. if (!dirty_)
  205. MarkDirty();
  206. rotateCount_ = 0;
  207. }
  208. void Node::SetDirection(const Vector3& direction)
  209. {
  210. SetRotation(Quaternion(Vector3::FORWARD, direction));
  211. }
  212. void Node::SetScale(float scale)
  213. {
  214. scale_ = Vector3(scale, scale, scale).Abs();
  215. if (!dirty_)
  216. MarkDirty();
  217. }
  218. void Node::SetScale(const Vector3& scale)
  219. {
  220. scale_ = scale.Abs();
  221. if (!dirty_)
  222. MarkDirty();
  223. }
  224. void Node::SetTransform(const Vector3& position, const Quaternion& rotation)
  225. {
  226. position_ = position;
  227. rotation_ = rotation;
  228. if (!dirty_)
  229. MarkDirty();
  230. rotateCount_ = 0;
  231. }
  232. void Node::SetTransform(const Vector3& position, const Quaternion& rotation, float scale)
  233. {
  234. position_ = position;
  235. rotation_ = rotation;
  236. scale_ = Vector3(scale, scale, scale);
  237. if (!dirty_)
  238. MarkDirty();
  239. rotateCount_ = 0;
  240. }
  241. void Node::SetTransform(const Vector3& position, const Quaternion& rotation, const Vector3& scale)
  242. {
  243. position_ = position;
  244. rotation_ = rotation;
  245. scale_ = scale;
  246. if (!dirty_)
  247. MarkDirty();
  248. rotateCount_ = 0;
  249. }
  250. void Node::SetWorldPosition(const Vector3& position)
  251. {
  252. if (!parent_)
  253. SetPosition(position);
  254. else
  255. SetPosition(parent_->GetWorldTransform().Inverse() * position);
  256. }
  257. void Node::SetWorldRotation(const Quaternion& rotation)
  258. {
  259. if (!parent_)
  260. SetRotation(rotation);
  261. else
  262. SetRotation(parent_->GetWorldRotation().Inverse() * rotation);
  263. }
  264. void Node::SetWorldDirection(const Vector3& direction)
  265. {
  266. Vector3 localDirection;
  267. if (!parent_)
  268. localDirection = direction;
  269. else
  270. localDirection = parent_->GetWorldTransform().Inverse() * direction;
  271. SetRotation(Quaternion(Vector3::FORWARD, localDirection));
  272. }
  273. void Node::SetWorldScale(float scale)
  274. {
  275. if (!parent_)
  276. SetScale(scale);
  277. else
  278. {
  279. Vector3 parentWorldScale = parent_->GetWorldScale();
  280. SetScale(Vector3(scale / parentWorldScale.x_, scale / parentWorldScale.y_, scale / parentWorldScale.z_));
  281. }
  282. }
  283. void Node::SetWorldScale(const Vector3& scale)
  284. {
  285. if (!parent_)
  286. SetScale(scale);
  287. else
  288. SetScale(scale / parent_->GetWorldScale());
  289. }
  290. void Node::SetWorldTransform(const Vector3& position, const Quaternion& rotation)
  291. {
  292. SetWorldPosition(position);
  293. SetWorldRotation(rotation);
  294. }
  295. void Node::SetWorldTransform(const Vector3& position, const Quaternion& rotation, float scale)
  296. {
  297. SetWorldPosition(position);
  298. SetWorldRotation(rotation);
  299. SetWorldScale(scale);
  300. }
  301. void Node::SetWorldTransform(const Vector3& position, const Quaternion& rotation, const Vector3& scale)
  302. {
  303. SetWorldPosition(position);
  304. SetWorldRotation(rotation);
  305. SetWorldScale(scale);
  306. }
  307. void Node::Translate(const Vector3& delta)
  308. {
  309. position_ += delta;
  310. if (!dirty_)
  311. MarkDirty();
  312. }
  313. void Node::TranslateRelative(const Vector3& delta)
  314. {
  315. position_ += rotation_ * delta;
  316. if (!dirty_)
  317. MarkDirty();
  318. }
  319. void Node::Rotate(const Quaternion& delta, bool fixedAxis)
  320. {
  321. if (!fixedAxis)
  322. rotation_ = rotation_ * delta;
  323. else
  324. rotation_ = delta * rotation_;
  325. ++rotateCount_;
  326. if (rotateCount_ >= NORMALIZE_ROTATION_EVERY)
  327. {
  328. rotation_.Normalize();
  329. rotateCount_ = 0;
  330. }
  331. if (!dirty_)
  332. MarkDirty();
  333. }
  334. void Node::Yaw(float angle, bool fixedAxis)
  335. {
  336. Rotate(Quaternion(angle, Vector3::UP), fixedAxis);
  337. }
  338. void Node::Pitch(float angle, bool fixedAxis)
  339. {
  340. Rotate(Quaternion(angle, Vector3::RIGHT), fixedAxis);
  341. }
  342. void Node::Roll(float angle, bool fixedAxis)
  343. {
  344. Rotate(Quaternion(angle, Vector3::FORWARD), fixedAxis);
  345. }
  346. void Node::LookAt(const Vector3& target, const Vector3& upAxis, bool worldSpace)
  347. {
  348. Vector3 targetZ;
  349. if (worldSpace)
  350. targetZ = (target - GetWorldPosition()).Normalized();
  351. else
  352. targetZ = (target - position_).Normalized();
  353. Vector3 targetX = upAxis.CrossProduct(targetZ).Normalized();
  354. Vector3 targetY = targetZ.CrossProduct(targetX).Normalized();
  355. if (!worldSpace || !parent_)
  356. SetRotation(Quaternion(targetX, targetY, targetZ));
  357. else
  358. SetRotation(parent_->GetWorldRotation().Inverse() * Quaternion(targetX, targetY, targetZ));
  359. }
  360. void Node::Scale(float scale)
  361. {
  362. scale_ *= scale;
  363. if (!dirty_)
  364. MarkDirty();
  365. }
  366. void Node::Scale(const Vector3& scale)
  367. {
  368. scale_ *= scale;
  369. if (!dirty_)
  370. MarkDirty();
  371. }
  372. void Node::SetOwner(Connection* owner)
  373. {
  374. owner_ = owner;
  375. }
  376. void Node::MarkDirty()
  377. {
  378. dirty_ = true;
  379. // Notify listener components first, then mark child nodes
  380. for (Vector<WeakPtr<Component> >::Iterator i = listeners_.Begin(); i != listeners_.End();)
  381. {
  382. if (*i)
  383. {
  384. (*i)->OnMarkedDirty(this);
  385. ++i;
  386. }
  387. // If listener has expired, erase from list
  388. else
  389. i = listeners_.Erase(i);
  390. }
  391. for (Vector<SharedPtr<Node> >::Iterator i = children_.Begin(); i != children_.End(); ++i)
  392. (*i)->MarkDirty();
  393. }
  394. Node* Node::CreateChild(const String& name, CreateMode mode)
  395. {
  396. Node* newNode = CreateChild(0, mode);
  397. newNode->SetName(name);
  398. return newNode;
  399. }
  400. void Node::AddChild(Node* node)
  401. {
  402. // Check for illegal or redundant parent assignment
  403. if (!node || node == this || node->parent_ == this)
  404. return;
  405. // Check for possible cyclic parent assignment
  406. Node* parent = parent_;
  407. while (parent)
  408. {
  409. if (parent == node)
  410. return;
  411. parent = parent->parent_;
  412. }
  413. // Add first, then remove from old parent, to ensure the node does not get deleted
  414. children_.Push(SharedPtr<Node>(node));
  415. if (node->parent_)
  416. node->parent_->RemoveChild(node);
  417. // Add to the scene if not added yet
  418. if (scene_ && !node->GetScene())
  419. scene_->NodeAdded(node);
  420. node->parent_ = this;
  421. node->MarkDirty();
  422. }
  423. void Node::RemoveChild(Node* node)
  424. {
  425. if (!node)
  426. return;
  427. for (Vector<SharedPtr<Node> >::Iterator i = children_.Begin(); i != children_.End(); ++i)
  428. {
  429. if (*i == node)
  430. {
  431. RemoveChild(i);
  432. return;
  433. }
  434. }
  435. }
  436. void Node::RemoveAllChildren()
  437. {
  438. while (children_.Size())
  439. RemoveChild(children_.End() - 1);
  440. }
  441. Component* Node::CreateComponent(ShortStringHash type, CreateMode mode)
  442. {
  443. return CreateComponent(type, 0, mode);
  444. }
  445. Component* Node::GetOrCreateComponent(ShortStringHash type, CreateMode mode)
  446. {
  447. Component* oldComponent = GetComponent(type);
  448. if (oldComponent)
  449. return oldComponent;
  450. else
  451. return CreateComponent(type, 0, mode);
  452. }
  453. void Node::RemoveComponent(Component* component)
  454. {
  455. for (Vector<SharedPtr<Component> >::Iterator i = components_.Begin(); i != components_.End(); ++i)
  456. {
  457. if (*i == component)
  458. {
  459. WeakPtr<Component> componentWeak(*i);
  460. RemoveListener(*i);
  461. if (scene_)
  462. scene_->ComponentRemoved(*i);
  463. components_.Erase(i);
  464. // If the component is still referenced elsewhere, reset its node pointer now
  465. if (componentWeak)
  466. componentWeak->SetNode(0);
  467. return;
  468. }
  469. }
  470. }
  471. void Node::RemoveAllComponents()
  472. {
  473. while (components_.Size())
  474. {
  475. Vector<SharedPtr<Component> >::Iterator i = components_.End() - 1;
  476. WeakPtr<Component> componentWeak(*i);
  477. RemoveListener(*i);
  478. if (scene_)
  479. scene_->ComponentRemoved(*i);
  480. components_.Erase(i);
  481. // If the component is still referenced elsewhere, reset its node pointer now
  482. if (componentWeak)
  483. componentWeak->SetNode(0);
  484. }
  485. }
  486. Node* Node::Clone(CreateMode mode)
  487. {
  488. // The scene itself can not be cloned
  489. if (this == scene_ || !parent_)
  490. return 0;
  491. PROFILE(CloneNode);
  492. SceneResolver resolver;
  493. Node* clone = CloneRecursive(parent_, resolver, mode);
  494. resolver.Resolve();
  495. clone->ApplyAttributes();
  496. return clone;
  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. {
  507. Vector3 worldPosition;
  508. Quaternion worldRotation;
  509. Vector3 worldScale;
  510. GetWorldTransform().Decompose(worldPosition, worldRotation, worldScale);
  511. parent->AddChild(this);
  512. SetWorldTransform(worldPosition, worldRotation, worldScale);
  513. }
  514. }
  515. void Node::AddListener(Component* component)
  516. {
  517. if (!component)
  518. return;
  519. // Check for not adding twice
  520. for (Vector<WeakPtr<Component> >::Iterator i = listeners_.Begin(); i != listeners_.End(); ++i)
  521. {
  522. if (*i == component)
  523. return;
  524. }
  525. listeners_.Push(WeakPtr<Component>(component));
  526. // If the node is currently dirty, notify immediately
  527. if (dirty_)
  528. component->OnMarkedDirty(this);
  529. }
  530. void Node::RemoveListener(Component* component)
  531. {
  532. for (Vector<WeakPtr<Component> >::Iterator i = listeners_.Begin(); i != listeners_.End(); ++i)
  533. {
  534. if (*i == component)
  535. {
  536. listeners_.Erase(i);
  537. return;
  538. }
  539. }
  540. }
  541. Vector3 Node::LocalToWorld(const Vector3& position) const
  542. {
  543. return GetWorldTransform() * position;
  544. }
  545. Vector3 Node::LocalToWorld(const Vector4& vector) const
  546. {
  547. return GetWorldTransform() * vector;
  548. }
  549. Vector3 Node::WorldToLocal(const Vector3& position) const
  550. {
  551. return GetWorldTransform().Inverse() * position;
  552. }
  553. Vector3 Node::WorldToLocal(const Vector4& vector) const
  554. {
  555. return GetWorldTransform().Inverse() * vector;
  556. }
  557. unsigned Node::GetNumChildren(bool recursive) const
  558. {
  559. if (!recursive)
  560. return children_.Size();
  561. else
  562. {
  563. unsigned allChildren = children_.Size();
  564. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  565. allChildren += (*i)->GetNumChildren(true);
  566. return allChildren;
  567. }
  568. }
  569. void Node::GetChildren(PODVector<Node*>& dest, bool recursive) const
  570. {
  571. dest.Clear();
  572. if (!recursive)
  573. {
  574. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  575. dest.Push(*i);
  576. }
  577. else
  578. GetChildrenRecursive(dest);
  579. }
  580. void Node::GetChildrenWithComponent(PODVector<Node*>& dest, ShortStringHash type, bool recursive) const
  581. {
  582. dest.Clear();
  583. if (!recursive)
  584. {
  585. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  586. {
  587. if ((*i)->HasComponent(type))
  588. dest.Push(*i);
  589. }
  590. }
  591. else
  592. GetChildrenWithComponentRecursive(dest, type);
  593. }
  594. Node* Node::GetChild(unsigned index) const
  595. {
  596. return index < children_.Size() ? children_[index].Get() : 0;
  597. }
  598. Node* Node::GetChild(const String& name, bool recursive) const
  599. {
  600. return GetChild(StringHash(name), recursive);
  601. }
  602. Node* Node::GetChild(StringHash nameHash, bool recursive) const
  603. {
  604. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  605. {
  606. if ((*i)->GetNameHash() == nameHash)
  607. return *i;
  608. if (recursive)
  609. {
  610. Node* node = (*i)->GetChild(nameHash, true);
  611. if (node)
  612. return node;
  613. }
  614. }
  615. return 0;
  616. }
  617. unsigned Node::GetNumNetworkComponents() const
  618. {
  619. unsigned num = 0;
  620. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  621. {
  622. if ((*i)->GetID() < FIRST_LOCAL_ID)
  623. ++num;
  624. }
  625. return num;
  626. }
  627. void Node::GetComponents(PODVector<Component*>& dest, ShortStringHash type) const
  628. {
  629. dest.Clear();
  630. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  631. {
  632. if ((*i)->GetType() == type)
  633. dest.Push(*i);
  634. }
  635. }
  636. bool Node::HasComponent(ShortStringHash type) const
  637. {
  638. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  639. {
  640. if ((*i)->GetType() == type)
  641. return true;
  642. }
  643. return false;
  644. }
  645. Component* Node::GetComponent(ShortStringHash type) const
  646. {
  647. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  648. {
  649. if ((*i)->GetType() == type)
  650. return *i;
  651. }
  652. return 0;
  653. }
  654. const PODVector<Node*>& Node::GetDependencyNodes(unsigned frameNumber) const
  655. {
  656. if (frameNumber != dependencyFrameNumber_)
  657. {
  658. dependencyNodes_.Clear();
  659. // Add the parent node, but if it is local, traverse to the first non-local node
  660. if (parent_ && parent_ != scene_)
  661. {
  662. Node* current = parent_;
  663. while (current->id_ >= FIRST_LOCAL_ID)
  664. current = current->parent_;
  665. if (current && current != scene_)
  666. dependencyNodes_.Push(current);
  667. }
  668. // Then let the components add their dependencies
  669. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  670. (*i)->GetDependencyNodes(dependencyNodes_);
  671. dependencyFrameNumber_ = frameNumber;
  672. }
  673. return dependencyNodes_;
  674. }
  675. void Node::SetID(unsigned id)
  676. {
  677. id_ = id;
  678. }
  679. void Node::SetScene(Scene* scene)
  680. {
  681. scene_ = scene;
  682. }
  683. void Node::SetNetPositionAttr(const Vector3& value)
  684. {
  685. SmoothedTransform* transform = GetComponent<SmoothedTransform>();
  686. if (transform)
  687. transform->SetTargetPosition(value);
  688. else
  689. SetPosition(value);
  690. }
  691. void Node::SetNetRotationAttr(const PODVector<unsigned char>& value)
  692. {
  693. MemoryBuffer buf(value);
  694. SmoothedTransform* transform = GetComponent<SmoothedTransform>();
  695. if (transform)
  696. transform->SetTargetRotation(buf.ReadPackedQuaternion());
  697. else
  698. SetRotation(buf.ReadPackedQuaternion());
  699. }
  700. void Node::SetNetParentAttr(const PODVector<unsigned char>& value)
  701. {
  702. Scene* scene = GetScene();
  703. if (!scene)
  704. return;
  705. MemoryBuffer buf(value);
  706. // If nothing in the buffer, parent is the root node
  707. if (buf.IsEof())
  708. {
  709. scene->AddChild(this);
  710. return;
  711. }
  712. unsigned baseNodeID = buf.ReadNetID();
  713. Node* baseNode = scene->GetNode(baseNodeID);
  714. if (!baseNode)
  715. {
  716. LOGWARNING("Failed to find parent node " + String(baseNodeID));
  717. return;
  718. }
  719. // If buffer contains just an ID, the parent is replicated and we are done
  720. if (buf.IsEof())
  721. baseNode->AddChild(this);
  722. else
  723. {
  724. // Else the parent is local and we must find it recursively by name hash
  725. StringHash nameHash = buf.ReadStringHash();
  726. Node* parentNode = baseNode->GetChild(nameHash, true);
  727. if (!parentNode)
  728. LOGWARNING("Failed to find parent node with name hash " + nameHash.ToString());
  729. else
  730. parentNode->AddChild(this);
  731. }
  732. }
  733. const Vector3& Node::GetNetPositionAttr() const
  734. {
  735. return position_;
  736. }
  737. const PODVector<unsigned char>& Node::GetNetRotationAttr() const
  738. {
  739. attrBuffer_.Clear();
  740. attrBuffer_.WritePackedQuaternion(rotation_);
  741. return attrBuffer_.GetBuffer();
  742. }
  743. const PODVector<unsigned char>& Node::GetNetParentAttr() const
  744. {
  745. attrBuffer_.Clear();
  746. Scene* scene = GetScene();
  747. if (scene && parent_ && parent_ != scene)
  748. {
  749. // If parent is replicated, can write the ID directly
  750. unsigned parentID = parent_->GetID();
  751. if (parentID < FIRST_LOCAL_ID)
  752. attrBuffer_.WriteNetID(parentID);
  753. else
  754. {
  755. // Parent is local: traverse hierarchy to find a non-local base node
  756. // This iteration always stops due to the scene (root) being non-local
  757. Node* current = parent_;
  758. while (current->GetID() >= FIRST_LOCAL_ID)
  759. current = current->GetParent();
  760. // Then write the base node ID and the parent's name hash
  761. attrBuffer_.WriteVLE(current->GetID());
  762. attrBuffer_.WriteStringHash(parent_->GetNameHash());
  763. }
  764. }
  765. return attrBuffer_.GetBuffer();
  766. }
  767. bool Node::Load(Deserializer& source, SceneResolver& resolver, bool readChildren, bool rewriteIDs, CreateMode mode)
  768. {
  769. // Remove all children and components first in case this is not a fresh load
  770. RemoveAllChildren();
  771. RemoveAllComponents();
  772. // ID has been read at the parent level
  773. if (!Serializable::Load(source))
  774. return false;
  775. unsigned numComponents = source.ReadVLE();
  776. for (unsigned i = 0; i < numComponents; ++i)
  777. {
  778. VectorBuffer compBuffer(source, source.ReadVLE());
  779. ShortStringHash compType = compBuffer.ReadShortStringHash();
  780. unsigned compID = compBuffer.ReadUInt();
  781. Component* newComponent = CreateComponent(compType, rewriteIDs ? 0 : compID, (mode == REPLICATED &&
  782. compID < FIRST_LOCAL_ID) ? REPLICATED : LOCAL);
  783. if (newComponent)
  784. {
  785. resolver.AddComponent(compID, newComponent);
  786. if (!newComponent->Load(compBuffer))
  787. return false;
  788. }
  789. }
  790. if (!readChildren)
  791. return true;
  792. unsigned numChildren = source.ReadVLE();
  793. for (unsigned i = 0; i < numChildren; ++i)
  794. {
  795. unsigned nodeID = source.ReadUInt();
  796. Node* newNode = CreateChild(rewriteIDs ? 0 : nodeID, (mode == REPLICATED && nodeID < FIRST_LOCAL_ID) ? REPLICATED :
  797. LOCAL);
  798. resolver.AddNode(nodeID, newNode);
  799. if (!newNode->Load(source, resolver, readChildren, rewriteIDs, mode))
  800. return false;
  801. }
  802. return true;
  803. }
  804. bool Node::LoadXML(const XMLElement& source, SceneResolver& resolver, bool readChildren, bool rewriteIDs, CreateMode mode)
  805. {
  806. // Remove all children and components first in case this is not a fresh load
  807. RemoveAllChildren();
  808. RemoveAllComponents();
  809. if (!Serializable::LoadXML(source))
  810. return false;
  811. XMLElement compElem = source.GetChild("component");
  812. while (compElem)
  813. {
  814. String typeName = compElem.GetAttribute("type");
  815. unsigned compID = compElem.GetInt("id");
  816. Component* newComponent = CreateComponent(ShortStringHash(typeName), rewriteIDs ? 0 : compID, (mode == REPLICATED &&
  817. compID < FIRST_LOCAL_ID) ? REPLICATED : LOCAL);
  818. if (newComponent)
  819. {
  820. resolver.AddComponent(compID, newComponent);
  821. if (!newComponent->LoadXML(compElem))
  822. return false;
  823. }
  824. compElem = compElem.GetNext("component");
  825. }
  826. if (!readChildren)
  827. return true;
  828. XMLElement childElem = source.GetChild("node");
  829. while (childElem)
  830. {
  831. unsigned nodeID = childElem.GetInt("id");
  832. Node* newNode = CreateChild(rewriteIDs ? 0 : nodeID, (mode == REPLICATED && nodeID < FIRST_LOCAL_ID) ? REPLICATED :
  833. LOCAL);
  834. resolver.AddNode(nodeID, newNode);
  835. if (!newNode->LoadXML(childElem, resolver, readChildren, rewriteIDs, mode))
  836. return false;
  837. childElem = childElem.GetNext("node");
  838. }
  839. return true;
  840. }
  841. Component* Node::CreateComponent(ShortStringHash type, unsigned id, CreateMode mode)
  842. {
  843. // Check that creation succeeds and that the object in fact is a component
  844. SharedPtr<Component> newComponent = DynamicCast<Component>(context_->CreateObject(type));
  845. if (!newComponent)
  846. {
  847. LOGERROR("Could not create unknown component type " + type.ToString());
  848. return 0;
  849. }
  850. components_.Push(newComponent);
  851. // If zero ID specified, or the ID is already taken, let the scene assign
  852. if (scene_)
  853. {
  854. if (!id || scene_->GetComponent(id))
  855. id = scene_->GetFreeComponentID(mode);
  856. newComponent->SetID(id);
  857. scene_->ComponentAdded(newComponent);
  858. }
  859. else
  860. newComponent->SetID(id);
  861. newComponent->SetNode(this);
  862. newComponent->OnMarkedDirty(this);
  863. return newComponent;
  864. }
  865. Node* Node::CreateChild(unsigned id, CreateMode mode)
  866. {
  867. SharedPtr<Node> newNode(new Node(context_));
  868. // If zero ID specified, or the ID is already taken, let the scene assign
  869. if (scene_)
  870. {
  871. if (!id || scene_->GetNode(id))
  872. id = scene_->GetFreeNodeID(mode);
  873. newNode->SetID(id);
  874. }
  875. else
  876. newNode->SetID(id);
  877. AddChild(newNode);
  878. return newNode;
  879. }
  880. void Node::UpdateWorldTransform() const
  881. {
  882. if (parent_)
  883. {
  884. if (parent_->dirty_)
  885. parent_->UpdateWorldTransform();
  886. worldTransform_ = parent_->worldTransform_ * Matrix3x4(position_, rotation_, scale_);
  887. }
  888. else
  889. worldTransform_ = Matrix3x4(position_, rotation_, scale_);
  890. dirty_ = false;
  891. }
  892. void Node::RemoveChild(Vector<SharedPtr<Node> >::Iterator i)
  893. {
  894. (*i)->parent_ = 0;
  895. (*i)->MarkDirty();
  896. children_.Erase(i);
  897. }
  898. void Node::GetChildrenRecursive(PODVector<Node*>& dest) const
  899. {
  900. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  901. {
  902. Node* node = *i;
  903. dest.Push(node);
  904. if (!node->children_.Empty())
  905. node->GetChildrenRecursive(dest);
  906. }
  907. }
  908. void Node::GetChildrenWithComponentRecursive(PODVector<Node*>& dest, ShortStringHash type) const
  909. {
  910. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  911. {
  912. Node* node = *i;
  913. if (node->HasComponent(type))
  914. dest.Push(node);
  915. if (!node->children_.Empty())
  916. node->GetChildrenRecursive(dest);
  917. }
  918. }
  919. Node* Node::CloneRecursive(Node* parent, SceneResolver& resolver, CreateMode mode)
  920. {
  921. // Create clone node
  922. Node* cloneNode = parent->CreateChild(0, (mode == REPLICATED && id_ < FIRST_LOCAL_ID) ? REPLICATED : LOCAL);
  923. resolver.AddNode(id_, cloneNode);
  924. // Copy attributes
  925. unsigned numAttributes = GetNumAttributes();
  926. for (unsigned j = 0; j < numAttributes; ++j)
  927. cloneNode->SetAttribute(j, GetAttribute(j));
  928. // Clone components
  929. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  930. {
  931. Component* component = *i;
  932. Component* cloneComponent = cloneNode->CreateComponent(component->GetType(), (mode == REPLICATED && component->GetID() <
  933. FIRST_LOCAL_ID) ? REPLICATED : LOCAL);
  934. if (!cloneComponent)
  935. {
  936. LOGERROR("Could not clone component " + component->GetTypeName());
  937. continue;
  938. }
  939. resolver.AddComponent(component->GetID(), cloneComponent);
  940. numAttributes = component->GetNumAttributes();
  941. for (unsigned j = 0; j < numAttributes; ++j)
  942. cloneComponent->SetAttribute(j, component->GetAttribute(j));
  943. }
  944. // Clone child nodes recursively
  945. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  946. {
  947. Node* node = *i;
  948. node->CloneRecursive(cloneNode, resolver, mode);
  949. }
  950. return cloneNode;
  951. }