Node.cpp 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494
  1. //
  2. // Copyright (c) 2008-2013 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "Precompiled.h"
  23. #include "Component.h"
  24. #include "Context.h"
  25. #include "Log.h"
  26. #include "MemoryBuffer.h"
  27. #include "Profiler.h"
  28. #include "ReplicationState.h"
  29. #include "Scene.h"
  30. #include "SceneEvents.h"
  31. #include "SmoothedTransform.h"
  32. #include "XMLFile.h"
  33. #include "DebugNew.h"
  34. namespace Urho3D
  35. {
  36. Node::Node(Context* context) :
  37. Serializable(context),
  38. worldTransform_(Matrix3x4::IDENTITY),
  39. dirty_(false),
  40. networkUpdate_(false),
  41. enabled_(true),
  42. parent_(0),
  43. scene_(0),
  44. id_(0),
  45. position_(Vector3::ZERO),
  46. rotation_(Quaternion::IDENTITY),
  47. scale_(Vector3::ONE),
  48. worldRotation_(Quaternion::IDENTITY),
  49. owner_(0)
  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. ACCESSOR_ATTRIBUTE(Node, VAR_BOOL, "Is Enabled", IsEnabled, SetEnabled, bool, true, AM_DEFAULT);
  64. REF_ACCESSOR_ATTRIBUTE(Node, VAR_STRING, "Name", GetName, SetName, String, String::EMPTY, AM_DEFAULT);
  65. REF_ACCESSOR_ATTRIBUTE(Node, VAR_VECTOR3, "Position", GetPosition, SetPosition, Vector3, Vector3::ZERO, AM_FILE);
  66. REF_ACCESSOR_ATTRIBUTE(Node, VAR_QUATERNION, "Rotation", GetRotation, SetRotation, Quaternion, Quaternion::IDENTITY, AM_FILE);
  67. REF_ACCESSOR_ATTRIBUTE(Node, VAR_VECTOR3, "Scale", GetScale, SetScale, Vector3, Vector3::ONE, AM_DEFAULT);
  68. ATTRIBUTE(Node, VAR_VARIANTMAP, "Variables", vars_, Variant::emptyVariantMap, AM_FILE); // Network replication of vars uses custom data
  69. REF_ACCESSOR_ATTRIBUTE(Node, VAR_VECTOR3, "Network Position", GetNetPositionAttr, SetNetPositionAttr, Vector3, Vector3::ZERO, AM_NET | AM_LATESTDATA | AM_NOEDIT);
  70. REF_ACCESSOR_ATTRIBUTE(Node, VAR_BUFFER, "Network Rotation", GetNetRotationAttr, SetNetRotationAttr, PODVector<unsigned char>, Variant::emptyBuffer, AM_NET | AM_LATESTDATA | AM_NOEDIT);
  71. REF_ACCESSOR_ATTRIBUTE(Node, VAR_BUFFER, "Network Parent Node", GetNetParentAttr, SetNetParentAttr, PODVector<unsigned char>, Variant::emptyBuffer, AM_NET | AM_NOEDIT);
  72. }
  73. void Node::OnSetAttribute(const AttributeInfo& attr, const Variant& src)
  74. {
  75. Serializable::OnSetAttribute(attr, src);
  76. MarkNetworkUpdate();
  77. }
  78. bool Node::Load(Deserializer& source, bool setInstanceDefault)
  79. {
  80. SceneResolver resolver;
  81. // Read own ID. Will not be applied, only stored for resolving possible references
  82. unsigned nodeID = source.ReadInt();
  83. resolver.AddNode(nodeID, this);
  84. // Read attributes, components and child nodes
  85. bool success = Load(source, resolver);
  86. if (success)
  87. {
  88. resolver.Resolve();
  89. ApplyAttributes();
  90. }
  91. return success;
  92. }
  93. bool Node::Save(Serializer& dest) const
  94. {
  95. // Write node ID
  96. if (!dest.WriteUInt(id_))
  97. return false;
  98. // Write attributes
  99. if (!Serializable::Save(dest))
  100. return false;
  101. // Write components
  102. dest.WriteVLE(GetNumPersistentComponents());
  103. for (unsigned i = 0; i < components_.Size(); ++i)
  104. {
  105. Component* component = components_[i];
  106. if (component->IsTemporary())
  107. continue;
  108. // Create a separate buffer to be able to skip unknown components during deserialization
  109. VectorBuffer compBuffer;
  110. if (!component->Save(compBuffer))
  111. return false;
  112. dest.WriteVLE(compBuffer.GetSize());
  113. dest.Write(compBuffer.GetData(), compBuffer.GetSize());
  114. }
  115. // Write child nodes
  116. dest.WriteVLE(GetNumPersistentChildren());
  117. for (unsigned i = 0; i < children_.Size(); ++i)
  118. {
  119. Node* node = children_[i];
  120. if (node->IsTemporary())
  121. continue;
  122. if (!node->Save(dest))
  123. return false;
  124. }
  125. return true;
  126. }
  127. bool Node::LoadXML(const XMLElement& source, bool setInstanceDefault)
  128. {
  129. SceneResolver resolver;
  130. // Read own ID. Will not be applied, only stored for resolving possible references
  131. unsigned nodeID = source.GetInt("id");
  132. resolver.AddNode(nodeID, this);
  133. // Read attributes, components and child nodes
  134. bool success = LoadXML(source, resolver);
  135. if (success)
  136. {
  137. resolver.Resolve();
  138. ApplyAttributes();
  139. }
  140. return success;
  141. }
  142. bool Node::SaveXML(XMLElement& dest) const
  143. {
  144. // Write node ID
  145. if (!dest.SetInt("id", id_))
  146. return false;
  147. // Write attributes
  148. if (!Serializable::SaveXML(dest))
  149. return false;
  150. // Write components
  151. for (unsigned i = 0; i < components_.Size(); ++i)
  152. {
  153. Component* component = components_[i];
  154. if (component->IsTemporary())
  155. continue;
  156. XMLElement compElem = dest.CreateChild("component");
  157. if (!component->SaveXML(compElem))
  158. return false;
  159. }
  160. // Write child nodes
  161. for (unsigned i = 0; i < children_.Size(); ++i)
  162. {
  163. Node* node = children_[i];
  164. if (node->IsTemporary())
  165. continue;
  166. XMLElement childElem = dest.CreateChild("node");
  167. if (!node->SaveXML(childElem))
  168. return false;
  169. }
  170. return true;
  171. }
  172. void Node::ApplyAttributes()
  173. {
  174. for (unsigned i = 0; i < components_.Size(); ++i)
  175. components_[i]->ApplyAttributes();
  176. for (unsigned i = 0; i < children_.Size(); ++i)
  177. children_[i]->ApplyAttributes();
  178. }
  179. void Node::AddReplicationState(NodeReplicationState* state)
  180. {
  181. if (!networkState_)
  182. AllocateNetworkState();
  183. networkState_->replicationStates_.Push(state);
  184. }
  185. bool Node::SaveXML(Serializer& dest) const
  186. {
  187. SharedPtr<XMLFile> xml(new XMLFile(context_));
  188. XMLElement rootElem = xml->CreateRoot("node");
  189. if (!SaveXML(rootElem))
  190. return false;
  191. return xml->Save(dest);
  192. }
  193. void Node::SetName(const String& name)
  194. {
  195. if (name != name_)
  196. {
  197. name_ = name;
  198. nameHash_ = name_;
  199. MarkNetworkUpdate();
  200. // Send change event
  201. if (scene_)
  202. {
  203. using namespace NodeNameChanged;
  204. VariantMap eventData;
  205. eventData[P_SCENE] = (void*)scene_;
  206. eventData[P_NODE] = (void*)this;
  207. scene_->SendEvent(E_NODENAMECHANGED, eventData);
  208. }
  209. }
  210. }
  211. void Node::SetPosition(const Vector3& position)
  212. {
  213. position_ = position;
  214. MarkDirty();
  215. MarkNetworkUpdate();
  216. }
  217. void Node::SetRotation(const Quaternion& rotation)
  218. {
  219. rotation_ = rotation;
  220. MarkDirty();
  221. MarkNetworkUpdate();
  222. }
  223. void Node::SetDirection(const Vector3& direction)
  224. {
  225. SetRotation(Quaternion(Vector3::FORWARD, direction));
  226. }
  227. void Node::SetScale(float scale)
  228. {
  229. SetScale(Vector3(scale, scale, scale));
  230. }
  231. void Node::SetScale(const Vector3& scale)
  232. {
  233. scale_ = scale.Abs();
  234. MarkDirty();
  235. MarkNetworkUpdate();
  236. }
  237. void Node::SetTransform(const Vector3& position, const Quaternion& rotation)
  238. {
  239. position_ = position;
  240. rotation_ = rotation;
  241. MarkDirty();
  242. MarkNetworkUpdate();
  243. }
  244. void Node::SetTransform(const Vector3& position, const Quaternion& rotation, float scale)
  245. {
  246. SetTransform(position, rotation, Vector3(scale, scale, scale));
  247. }
  248. void Node::SetTransform(const Vector3& position, const Quaternion& rotation, const Vector3& scale)
  249. {
  250. position_ = position;
  251. rotation_ = rotation;
  252. scale_ = scale;
  253. MarkDirty();
  254. MarkNetworkUpdate();
  255. }
  256. void Node::SetWorldPosition(const Vector3& position)
  257. {
  258. SetPosition((parent_ == scene_ || !parent_) ? position : parent_->GetWorldTransform().Inverse() * position);
  259. }
  260. void Node::SetWorldRotation(const Quaternion& rotation)
  261. {
  262. SetRotation((parent_ == scene_ || !parent_) ? rotation : parent_->GetWorldRotation().Inverse() * rotation);
  263. }
  264. void Node::SetWorldDirection(const Vector3& direction)
  265. {
  266. Vector3 localDirection = (parent_ == scene_ || !parent_) ? direction : parent_->GetWorldRotation().Inverse() * direction;
  267. SetRotation(Quaternion(Vector3::FORWARD, localDirection));
  268. }
  269. void Node::SetWorldScale(float scale)
  270. {
  271. SetWorldScale(Vector3(scale, scale, scale));
  272. }
  273. void Node::SetWorldScale(const Vector3& scale)
  274. {
  275. SetScale((parent_ == scene_ || !parent_) ? scale : scale / parent_->GetWorldScale());
  276. }
  277. void Node::SetWorldTransform(const Vector3& position, const Quaternion& rotation)
  278. {
  279. SetWorldPosition(position);
  280. SetWorldRotation(rotation);
  281. }
  282. void Node::SetWorldTransform(const Vector3& position, const Quaternion& rotation, float scale)
  283. {
  284. SetWorldPosition(position);
  285. SetWorldRotation(rotation);
  286. SetWorldScale(scale);
  287. }
  288. void Node::SetWorldTransform(const Vector3& position, const Quaternion& rotation, const Vector3& scale)
  289. {
  290. SetWorldPosition(position);
  291. SetWorldRotation(rotation);
  292. SetWorldScale(scale);
  293. }
  294. void Node::Translate(const Vector3& delta)
  295. {
  296. position_ += delta;
  297. MarkDirty();
  298. MarkNetworkUpdate();
  299. }
  300. void Node::TranslateRelative(const Vector3& delta)
  301. {
  302. position_ += rotation_ * delta;
  303. MarkDirty();
  304. MarkNetworkUpdate();
  305. }
  306. void Node::Rotate(const Quaternion& delta, bool fixedAxis)
  307. {
  308. if (!fixedAxis)
  309. rotation_ = (rotation_ * delta).Normalized();
  310. else
  311. rotation_ = (delta * rotation_).Normalized();
  312. MarkDirty();
  313. MarkNetworkUpdate();
  314. }
  315. void Node::Yaw(float angle, bool fixedAxis)
  316. {
  317. Rotate(Quaternion(angle, Vector3::UP), fixedAxis);
  318. }
  319. void Node::Pitch(float angle, bool fixedAxis)
  320. {
  321. Rotate(Quaternion(angle, Vector3::RIGHT), fixedAxis);
  322. }
  323. void Node::Roll(float angle, bool fixedAxis)
  324. {
  325. Rotate(Quaternion(angle, Vector3::FORWARD), fixedAxis);
  326. }
  327. void Node::LookAt(const Vector3& target, const Vector3& upAxis)
  328. {
  329. Vector3 targetZ = (target - GetWorldPosition()).Normalized();
  330. Vector3 targetX = upAxis.CrossProduct(targetZ).Normalized();
  331. Vector3 targetY = targetZ.CrossProduct(targetX).Normalized();
  332. Quaternion rotation(targetX, targetY, targetZ);
  333. SetRotation((parent_ == scene_ || !parent_) ? rotation : parent_->GetWorldRotation().Inverse() * rotation);
  334. }
  335. void Node::Scale(float scale)
  336. {
  337. Scale(Vector3(scale, scale, scale));
  338. }
  339. void Node::Scale(const Vector3& scale)
  340. {
  341. scale_ *= scale;
  342. MarkDirty();
  343. MarkNetworkUpdate();
  344. }
  345. void Node::SetEnabled(bool enable)
  346. {
  347. SetEnabled(enable, false);
  348. }
  349. void Node::SetEnabled(bool enable, bool recursive)
  350. {
  351. // The enabled state of the whole scene can not be changed. SetUpdateEnabled() is used instead to start/stop updates.
  352. if (GetType() == Scene::GetTypeStatic())
  353. {
  354. LOGERROR("Can not change enabled state of the Scene");
  355. return;
  356. }
  357. if (enable != enabled_)
  358. {
  359. enabled_ = enable;
  360. MarkNetworkUpdate();
  361. // Notify listener components of the state change
  362. for (Vector<WeakPtr<Component> >::Iterator i = listeners_.Begin(); i != listeners_.End();)
  363. {
  364. if (*i)
  365. {
  366. (*i)->OnNodeSetEnabled(this);
  367. ++i;
  368. }
  369. // If listener has expired, erase from list
  370. else
  371. i = listeners_.Erase(i);
  372. }
  373. // Send change event
  374. if (scene_)
  375. {
  376. using namespace NodeEnabledChanged;
  377. VariantMap eventData;
  378. eventData[P_SCENE] = (void*)scene_;
  379. eventData[P_NODE] = (void*)this;
  380. scene_->SendEvent(E_NODEENABLEDCHANGED, eventData);
  381. }
  382. for (Vector<SharedPtr<Component> >::Iterator i = components_.Begin(); i != components_.End(); ++i)
  383. {
  384. (*i)->OnSetEnabled();
  385. // Send change event for the component
  386. if (scene_)
  387. {
  388. using namespace ComponentEnabledChanged;
  389. VariantMap eventData;
  390. eventData[P_SCENE] = (void*)scene_;
  391. eventData[P_NODE] = (void*)this;
  392. eventData[P_COMPONENT] = (void*)(*i);
  393. scene_->SendEvent(E_COMPONENTENABLEDCHANGED, eventData);
  394. }
  395. }
  396. }
  397. if (recursive)
  398. {
  399. for (Vector<SharedPtr<Node> >::Iterator i = children_.Begin(); i != children_.End(); ++i)
  400. (*i)->SetEnabled(enable, recursive);
  401. }
  402. }
  403. void Node::SetOwner(Connection* owner)
  404. {
  405. owner_ = owner;
  406. }
  407. void Node::MarkDirty()
  408. {
  409. if (dirty_)
  410. return;
  411. dirty_ = true;
  412. // Notify listener components first, then mark child nodes
  413. for (Vector<WeakPtr<Component> >::Iterator i = listeners_.Begin(); i != listeners_.End();)
  414. {
  415. if (*i)
  416. {
  417. (*i)->OnMarkedDirty(this);
  418. ++i;
  419. }
  420. // If listener has expired, erase from list
  421. else
  422. i = listeners_.Erase(i);
  423. }
  424. for (Vector<SharedPtr<Node> >::Iterator i = children_.Begin(); i != children_.End(); ++i)
  425. (*i)->MarkDirty();
  426. }
  427. Node* Node::CreateChild(const String& name, CreateMode mode, unsigned id)
  428. {
  429. Node* newNode = CreateChild(id, mode);
  430. newNode->SetName(name);
  431. return newNode;
  432. }
  433. void Node::AddChild(Node* node)
  434. {
  435. // Check for illegal or redundant parent assignment
  436. if (!node || node == this || node->parent_ == this)
  437. return;
  438. // Check for possible cyclic parent assignment
  439. Node* parent = parent_;
  440. while (parent)
  441. {
  442. if (parent == node)
  443. return;
  444. parent = parent->parent_;
  445. }
  446. // Add first, then remove from old parent, to ensure the node does not get deleted
  447. children_.Push(SharedPtr<Node>(node));
  448. node->Remove();
  449. // Add to the scene if not added yet
  450. if (scene_ && node->GetScene() != scene_)
  451. scene_->NodeAdded(node);
  452. node->parent_ = this;
  453. node->MarkDirty();
  454. node->MarkNetworkUpdate();
  455. // Send change event
  456. if (scene_)
  457. {
  458. using namespace NodeAdded;
  459. VariantMap eventData;
  460. eventData[P_SCENE] = (void*)scene_;
  461. eventData[P_PARENT] = (void*)this;
  462. eventData[P_NODE] = (void*)node;
  463. scene_->SendEvent(E_NODEADDED, eventData);
  464. }
  465. }
  466. void Node::RemoveChild(Node* node)
  467. {
  468. if (!node)
  469. return;
  470. for (Vector<SharedPtr<Node> >::Iterator i = children_.Begin(); i != children_.End(); ++i)
  471. {
  472. if (*i == node)
  473. {
  474. RemoveChild(i);
  475. return;
  476. }
  477. }
  478. }
  479. void Node::RemoveAllChildren()
  480. {
  481. RemoveChildren(true, true, true);
  482. }
  483. void Node::RemoveChildren(bool removeReplicated, bool removeLocal, bool recursive)
  484. {
  485. unsigned numRemoved = 0;
  486. for (unsigned i = children_.Size() - 1; i < children_.Size(); --i)
  487. {
  488. bool remove = false;
  489. Node* childNode = children_[i];
  490. if (recursive)
  491. childNode->RemoveChildren(removeReplicated, removeLocal, true);
  492. if (childNode->GetID() < FIRST_LOCAL_ID && removeReplicated)
  493. remove = true;
  494. else if (childNode->GetID() >= FIRST_LOCAL_ID && removeLocal)
  495. remove = true;
  496. if (remove)
  497. {
  498. RemoveChild(children_.Begin() + i);
  499. ++numRemoved;
  500. }
  501. }
  502. // Mark node dirty in all replication states
  503. if (numRemoved)
  504. MarkReplicationDirty();
  505. }
  506. Component* Node::CreateComponent(ShortStringHash type, CreateMode mode, unsigned id)
  507. {
  508. // Check that creation succeeds and that the object in fact is a component
  509. SharedPtr<Component> newComponent = DynamicCast<Component>(context_->CreateObject(type));
  510. if (!newComponent)
  511. {
  512. LOGERROR("Could not create unknown component type " + type.ToString());
  513. return 0;
  514. }
  515. AddComponent(newComponent, id, mode);
  516. return newComponent;
  517. }
  518. Component* Node::GetOrCreateComponent(ShortStringHash type, CreateMode mode, unsigned id)
  519. {
  520. Component* oldComponent = GetComponent(type);
  521. if (oldComponent)
  522. return oldComponent;
  523. else
  524. return CreateComponent(type, mode, id);
  525. }
  526. void Node::RemoveComponent(Component* component)
  527. {
  528. for (Vector<SharedPtr<Component> >::Iterator i = components_.Begin(); i != components_.End(); ++i)
  529. {
  530. if (*i == component)
  531. {
  532. RemoveComponent(i);
  533. // Mark node dirty in all replication states
  534. MarkReplicationDirty();
  535. return;
  536. }
  537. }
  538. }
  539. void Node::RemoveComponent(ShortStringHash type)
  540. {
  541. for (Vector<SharedPtr<Component> >::Iterator i = components_.Begin(); i != components_.End(); ++i)
  542. {
  543. if ((*i)->GetType() == type)
  544. {
  545. RemoveComponent(i);
  546. // Mark node dirty in all replication states
  547. MarkReplicationDirty();
  548. return;
  549. }
  550. }
  551. }
  552. void Node::RemoveAllComponents()
  553. {
  554. RemoveComponents(true, true);
  555. }
  556. void Node::RemoveComponents(bool removeReplicated, bool removeLocal)
  557. {
  558. unsigned numRemoved = 0;
  559. for (unsigned i = components_.Size() - 1; i < components_.Size(); --i)
  560. {
  561. bool remove = false;
  562. Component* component = components_[i];
  563. if (component->GetID() < FIRST_LOCAL_ID && removeReplicated)
  564. remove = true;
  565. else if (component->GetID() >= FIRST_LOCAL_ID && removeLocal)
  566. remove = true;
  567. if (remove)
  568. {
  569. RemoveComponent(components_.Begin() + i);
  570. ++numRemoved;
  571. }
  572. }
  573. // Mark node dirty in all replication states
  574. if (numRemoved)
  575. MarkReplicationDirty();
  576. }
  577. Node* Node::Clone(CreateMode mode)
  578. {
  579. // The scene itself can not be cloned
  580. if (this == scene_ || !parent_)
  581. {
  582. LOGERROR("Can not clone node without a parent");
  583. return 0;
  584. }
  585. PROFILE(CloneNode);
  586. SceneResolver resolver;
  587. Node* clone = CloneRecursive(parent_, resolver, mode);
  588. resolver.Resolve();
  589. clone->ApplyAttributes();
  590. return clone;
  591. }
  592. void Node::Remove()
  593. {
  594. if (parent_)
  595. parent_->RemoveChild(this);
  596. }
  597. void Node::SetParent(Node* parent)
  598. {
  599. if (parent)
  600. {
  601. Matrix3x4 oldWorldTransform = GetWorldTransform();
  602. parent->AddChild(this);
  603. if (parent != scene_)
  604. {
  605. Matrix3x4 newTransform = parent->GetWorldTransform().Inverse() * oldWorldTransform;
  606. SetTransform(newTransform.Translation(), newTransform.Rotation(), newTransform.Scale());
  607. }
  608. else
  609. {
  610. // The root node is assumed to have identity transform, so can disregard it
  611. SetTransform(oldWorldTransform.Translation(), oldWorldTransform.Rotation(), oldWorldTransform.Scale());
  612. }
  613. }
  614. }
  615. void Node::SetVar(ShortStringHash key, const Variant& value)
  616. {
  617. vars_[key] = value;
  618. MarkNetworkUpdate();
  619. }
  620. void Node::AddListener(Component* component)
  621. {
  622. if (!component)
  623. return;
  624. // Check for not adding twice
  625. for (Vector<WeakPtr<Component> >::Iterator i = listeners_.Begin(); i != listeners_.End(); ++i)
  626. {
  627. if (*i == component)
  628. return;
  629. }
  630. listeners_.Push(WeakPtr<Component>(component));
  631. // If the node is currently dirty, notify immediately
  632. if (dirty_)
  633. component->OnMarkedDirty(this);
  634. }
  635. void Node::RemoveListener(Component* component)
  636. {
  637. for (Vector<WeakPtr<Component> >::Iterator i = listeners_.Begin(); i != listeners_.End(); ++i)
  638. {
  639. if (*i == component)
  640. {
  641. listeners_.Erase(i);
  642. return;
  643. }
  644. }
  645. }
  646. Vector3 Node::LocalToWorld(const Vector3& position) const
  647. {
  648. return GetWorldTransform() * position;
  649. }
  650. Vector3 Node::LocalToWorld(const Vector4& vector) const
  651. {
  652. return GetWorldTransform() * vector;
  653. }
  654. Vector3 Node::WorldToLocal(const Vector3& position) const
  655. {
  656. return GetWorldTransform().Inverse() * position;
  657. }
  658. Vector3 Node::WorldToLocal(const Vector4& vector) const
  659. {
  660. return GetWorldTransform().Inverse() * vector;
  661. }
  662. unsigned Node::GetNumChildren(bool recursive) const
  663. {
  664. if (!recursive)
  665. return children_.Size();
  666. else
  667. {
  668. unsigned allChildren = children_.Size();
  669. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  670. allChildren += (*i)->GetNumChildren(true);
  671. return allChildren;
  672. }
  673. }
  674. void Node::GetChildren(PODVector<Node*>& dest, bool recursive) const
  675. {
  676. dest.Clear();
  677. if (!recursive)
  678. {
  679. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  680. dest.Push(*i);
  681. }
  682. else
  683. GetChildrenRecursive(dest);
  684. }
  685. void Node::GetChildrenWithComponent(PODVector<Node*>& dest, ShortStringHash type, bool recursive) const
  686. {
  687. dest.Clear();
  688. if (!recursive)
  689. {
  690. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  691. {
  692. if ((*i)->HasComponent(type))
  693. dest.Push(*i);
  694. }
  695. }
  696. else
  697. GetChildrenWithComponentRecursive(dest, type);
  698. }
  699. Node* Node::GetChild(unsigned index) const
  700. {
  701. return index < children_.Size() ? children_[index].Get() : 0;
  702. }
  703. Node* Node::GetChild(const String& name, bool recursive) const
  704. {
  705. return GetChild(StringHash(name), recursive);
  706. }
  707. Node* Node::GetChild(const char* name, bool recursive) const
  708. {
  709. return GetChild(StringHash(name), recursive);
  710. }
  711. Node* Node::GetChild(StringHash nameHash, bool recursive) const
  712. {
  713. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  714. {
  715. if ((*i)->GetNameHash() == nameHash)
  716. return *i;
  717. if (recursive)
  718. {
  719. Node* node = (*i)->GetChild(nameHash, true);
  720. if (node)
  721. return node;
  722. }
  723. }
  724. return 0;
  725. }
  726. unsigned Node::GetNumNetworkComponents() const
  727. {
  728. unsigned num = 0;
  729. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  730. {
  731. if ((*i)->GetID() < FIRST_LOCAL_ID)
  732. ++num;
  733. }
  734. return num;
  735. }
  736. void Node::GetComponents(PODVector<Component*>& dest, ShortStringHash type, bool recursive) const
  737. {
  738. dest.Clear();
  739. if (!recursive)
  740. {
  741. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  742. {
  743. if ((*i)->GetType() == type)
  744. dest.Push(*i);
  745. }
  746. }
  747. else
  748. GetComponentsRecursive(dest, type);
  749. }
  750. bool Node::HasComponent(ShortStringHash type) const
  751. {
  752. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  753. {
  754. if ((*i)->GetType() == type)
  755. return true;
  756. }
  757. return false;
  758. }
  759. const Variant& Node::GetVar(ShortStringHash key) const
  760. {
  761. VariantMap::ConstIterator i = vars_.Find(key);
  762. return i != vars_.End() ? i->second_ : Variant::EMPTY;
  763. }
  764. Component* Node::GetComponent(ShortStringHash type) const
  765. {
  766. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  767. {
  768. if ((*i)->GetType() == type)
  769. return *i;
  770. }
  771. return 0;
  772. }
  773. void Node::SetID(unsigned id)
  774. {
  775. id_ = id;
  776. }
  777. void Node::SetScene(Scene* scene)
  778. {
  779. scene_ = scene;
  780. }
  781. void Node::ResetScene()
  782. {
  783. SetID(0);
  784. SetScene(0);
  785. SetOwner(0);
  786. }
  787. void Node::SetNetPositionAttr(const Vector3& value)
  788. {
  789. SmoothedTransform* transform = GetComponent<SmoothedTransform>();
  790. if (transform)
  791. transform->SetTargetPosition(value);
  792. else
  793. SetPosition(value);
  794. }
  795. void Node::SetNetRotationAttr(const PODVector<unsigned char>& value)
  796. {
  797. MemoryBuffer buf(value);
  798. SmoothedTransform* transform = GetComponent<SmoothedTransform>();
  799. if (transform)
  800. transform->SetTargetRotation(buf.ReadPackedQuaternion());
  801. else
  802. SetRotation(buf.ReadPackedQuaternion());
  803. }
  804. void Node::SetNetParentAttr(const PODVector<unsigned char>& value)
  805. {
  806. Scene* scene = GetScene();
  807. if (!scene)
  808. return;
  809. MemoryBuffer buf(value);
  810. // If nothing in the buffer, parent is the root node
  811. if (buf.IsEof())
  812. {
  813. scene->AddChild(this);
  814. return;
  815. }
  816. unsigned baseNodeID = buf.ReadNetID();
  817. Node* baseNode = scene->GetNode(baseNodeID);
  818. if (!baseNode)
  819. {
  820. LOGWARNING("Failed to find parent node " + String(baseNodeID));
  821. return;
  822. }
  823. // If buffer contains just an ID, the parent is replicated and we are done
  824. if (buf.IsEof())
  825. baseNode->AddChild(this);
  826. else
  827. {
  828. // Else the parent is local and we must find it recursively by name hash
  829. StringHash nameHash = buf.ReadStringHash();
  830. Node* parentNode = baseNode->GetChild(nameHash, true);
  831. if (!parentNode)
  832. LOGWARNING("Failed to find parent node with name hash " + nameHash.ToString());
  833. else
  834. parentNode->AddChild(this);
  835. }
  836. }
  837. const Vector3& Node::GetNetPositionAttr() const
  838. {
  839. return position_;
  840. }
  841. const PODVector<unsigned char>& Node::GetNetRotationAttr() const
  842. {
  843. attrBuffer_.Clear();
  844. attrBuffer_.WritePackedQuaternion(rotation_);
  845. return attrBuffer_.GetBuffer();
  846. }
  847. const PODVector<unsigned char>& Node::GetNetParentAttr() const
  848. {
  849. attrBuffer_.Clear();
  850. Scene* scene = GetScene();
  851. if (scene && parent_ && parent_ != scene)
  852. {
  853. // If parent is replicated, can write the ID directly
  854. unsigned parentID = parent_->GetID();
  855. if (parentID < FIRST_LOCAL_ID)
  856. attrBuffer_.WriteNetID(parentID);
  857. else
  858. {
  859. // Parent is local: traverse hierarchy to find a non-local base node
  860. // This iteration always stops due to the scene (root) being non-local
  861. Node* current = parent_;
  862. while (current->GetID() >= FIRST_LOCAL_ID)
  863. current = current->GetParent();
  864. // Then write the base node ID and the parent's name hash
  865. attrBuffer_.WriteNetID(current->GetID());
  866. attrBuffer_.WriteStringHash(parent_->GetNameHash());
  867. }
  868. }
  869. return attrBuffer_.GetBuffer();
  870. }
  871. bool Node::Load(Deserializer& source, SceneResolver& resolver, bool readChildren, bool rewriteIDs, CreateMode mode)
  872. {
  873. // Remove all children and components first in case this is not a fresh load
  874. RemoveAllChildren();
  875. RemoveAllComponents();
  876. // ID has been read at the parent level
  877. if (!Serializable::Load(source))
  878. return false;
  879. unsigned numComponents = source.ReadVLE();
  880. for (unsigned i = 0; i < numComponents; ++i)
  881. {
  882. VectorBuffer compBuffer(source, source.ReadVLE());
  883. ShortStringHash compType = compBuffer.ReadShortStringHash();
  884. unsigned compID = compBuffer.ReadUInt();
  885. Component* newComponent = CreateComponent(compType,
  886. (mode == REPLICATED && compID < FIRST_LOCAL_ID) ? REPLICATED : LOCAL, rewriteIDs ? 0 : compID);
  887. if (newComponent)
  888. {
  889. resolver.AddComponent(compID, newComponent);
  890. // Do not abort if component fails to load, as the component buffer is nested and we can skip to the next
  891. newComponent->Load(compBuffer);
  892. }
  893. }
  894. if (!readChildren)
  895. return true;
  896. unsigned numChildren = source.ReadVLE();
  897. for (unsigned i = 0; i < numChildren; ++i)
  898. {
  899. unsigned nodeID = source.ReadUInt();
  900. Node* newNode = CreateChild(rewriteIDs ? 0 : nodeID, (mode == REPLICATED && nodeID < FIRST_LOCAL_ID) ? REPLICATED :
  901. LOCAL);
  902. resolver.AddNode(nodeID, newNode);
  903. if (!newNode->Load(source, resolver, readChildren, rewriteIDs, mode))
  904. return false;
  905. }
  906. return true;
  907. }
  908. bool Node::LoadXML(const XMLElement& source, SceneResolver& resolver, bool readChildren, bool rewriteIDs, CreateMode mode)
  909. {
  910. // Remove all children and components first in case this is not a fresh load
  911. RemoveAllChildren();
  912. RemoveAllComponents();
  913. if (!Serializable::LoadXML(source))
  914. return false;
  915. XMLElement compElem = source.GetChild("component");
  916. while (compElem)
  917. {
  918. String typeName = compElem.GetAttribute("type");
  919. unsigned compID = compElem.GetInt("id");
  920. Component* newComponent = CreateComponent(typeName,
  921. (mode == REPLICATED && compID < FIRST_LOCAL_ID) ? REPLICATED : LOCAL, rewriteIDs ? 0 : compID);
  922. if (newComponent)
  923. {
  924. resolver.AddComponent(compID, newComponent);
  925. if (!newComponent->LoadXML(compElem))
  926. return false;
  927. }
  928. compElem = compElem.GetNext("component");
  929. }
  930. if (!readChildren)
  931. return true;
  932. XMLElement childElem = source.GetChild("node");
  933. while (childElem)
  934. {
  935. unsigned nodeID = childElem.GetInt("id");
  936. Node* newNode = CreateChild(rewriteIDs ? 0 : nodeID, (mode == REPLICATED && nodeID < FIRST_LOCAL_ID) ? REPLICATED :
  937. LOCAL);
  938. resolver.AddNode(nodeID, newNode);
  939. if (!newNode->LoadXML(childElem, resolver, readChildren, rewriteIDs, mode))
  940. return false;
  941. childElem = childElem.GetNext("node");
  942. }
  943. return true;
  944. }
  945. void Node::PrepareNetworkUpdate()
  946. {
  947. // Update dependency nodes list first
  948. dependencyNodes_.Clear();
  949. // Add the parent node, but if it is local, traverse to the first non-local node
  950. if (parent_ && parent_ != scene_)
  951. {
  952. Node* current = parent_;
  953. while (current->id_ >= FIRST_LOCAL_ID)
  954. current = current->parent_;
  955. if (current && current != scene_)
  956. dependencyNodes_.Push(current);
  957. }
  958. // Let the components add their dependencies
  959. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  960. {
  961. Component* component = *i;
  962. if (component->GetID() < FIRST_LOCAL_ID)
  963. component->GetDependencyNodes(dependencyNodes_);
  964. }
  965. // Then check for node attribute changes
  966. if (!networkState_)
  967. AllocateNetworkState();
  968. const Vector<AttributeInfo>* attributes = networkState_->attributes_;
  969. unsigned numAttributes = attributes->Size();
  970. if (networkState_->currentValues_.Size() != numAttributes)
  971. {
  972. networkState_->currentValues_.Resize(numAttributes);
  973. networkState_->previousValues_.Resize(numAttributes);
  974. // Copy the default attribute values to the previous state as a starting point
  975. for (unsigned i = 0; i < numAttributes; ++i)
  976. networkState_->previousValues_[i] = attributes->At(i).defaultValue_;
  977. }
  978. // Check for attribute changes
  979. for (unsigned i = 0; i < numAttributes; ++i)
  980. {
  981. const AttributeInfo& attr = attributes->At(i);
  982. OnGetAttribute(attr, networkState_->currentValues_[i]);
  983. if (networkState_->currentValues_[i] != networkState_->previousValues_[i])
  984. {
  985. networkState_->previousValues_[i] = networkState_->currentValues_[i];
  986. // Mark the attribute dirty in all replication states that are tracking this node
  987. for (PODVector<ReplicationState*>::Iterator j = networkState_->replicationStates_.Begin(); j !=
  988. networkState_->replicationStates_.End();
  989. ++j)
  990. {
  991. NodeReplicationState* nodeState = static_cast<NodeReplicationState*>(*j);
  992. nodeState->dirtyAttributes_.Set(i);
  993. // Add node to the dirty set if not added yet
  994. if (!nodeState->markedDirty_)
  995. {
  996. nodeState->markedDirty_ = true;
  997. nodeState->sceneState_->dirtyNodes_.Insert(id_);
  998. }
  999. }
  1000. }
  1001. }
  1002. // Finally check for user var changes
  1003. for (VariantMap::ConstIterator i = vars_.Begin(); i != vars_.End(); ++i)
  1004. {
  1005. VariantMap::ConstIterator j = networkState_->previousVars_.Find(i->first_);
  1006. if (j == networkState_->previousVars_.End() || j->second_ != i->second_)
  1007. {
  1008. networkState_->previousVars_[i->first_] = i->second_;
  1009. // Mark the var dirty in all replication states that are tracking this node
  1010. for (PODVector<ReplicationState*>::Iterator j = networkState_->replicationStates_.Begin(); j !=
  1011. networkState_->replicationStates_.End(); ++j)
  1012. {
  1013. NodeReplicationState* nodeState = static_cast<NodeReplicationState*>(*j);
  1014. nodeState->dirtyVars_.Insert(i->first_);
  1015. if (!nodeState->markedDirty_)
  1016. {
  1017. nodeState->markedDirty_ = true;
  1018. nodeState->sceneState_->dirtyNodes_.Insert(id_);
  1019. }
  1020. }
  1021. }
  1022. }
  1023. networkUpdate_ = false;
  1024. }
  1025. void Node::CleanupConnection(Connection* connection)
  1026. {
  1027. if (owner_ == connection)
  1028. owner_ = 0;
  1029. if (networkState_)
  1030. {
  1031. for (unsigned i = networkState_->replicationStates_.Size() - 1; i < networkState_->replicationStates_.Size(); --i)
  1032. {
  1033. if (networkState_->replicationStates_[i]->connection_ == connection)
  1034. networkState_->replicationStates_.Erase(i);
  1035. }
  1036. }
  1037. }
  1038. void Node::MarkNetworkUpdate()
  1039. {
  1040. if (!networkUpdate_ && scene_ && id_ < FIRST_LOCAL_ID)
  1041. {
  1042. scene_->MarkNetworkUpdate(this);
  1043. networkUpdate_ = true;
  1044. }
  1045. }
  1046. void Node::MarkReplicationDirty()
  1047. {
  1048. if (networkState_)
  1049. {
  1050. for (PODVector<ReplicationState*>::Iterator j = networkState_->replicationStates_.Begin(); j !=
  1051. networkState_->replicationStates_.End(); ++j)
  1052. {
  1053. NodeReplicationState* nodeState = static_cast<NodeReplicationState*>(*j);
  1054. if (!nodeState->markedDirty_)
  1055. {
  1056. nodeState->markedDirty_ = true;
  1057. nodeState->sceneState_->dirtyNodes_.Insert(id_);
  1058. }
  1059. }
  1060. }
  1061. }
  1062. Node* Node::CreateChild(unsigned id, CreateMode mode)
  1063. {
  1064. SharedPtr<Node> newNode(new Node(context_));
  1065. // If zero ID specified, or the ID is already taken, let the scene assign
  1066. if (scene_)
  1067. {
  1068. if (!id || scene_->GetNode(id))
  1069. id = scene_->GetFreeNodeID(mode);
  1070. newNode->SetID(id);
  1071. }
  1072. else
  1073. newNode->SetID(id);
  1074. AddChild(newNode);
  1075. return newNode;
  1076. }
  1077. void Node::AddComponent(Component* component, unsigned id, CreateMode mode)
  1078. {
  1079. if (!component)
  1080. return;
  1081. components_.Push(SharedPtr<Component>(component));
  1082. // If zero ID specified, or the ID is already taken, let the scene assign
  1083. if (scene_)
  1084. {
  1085. if (!id || scene_->GetComponent(id))
  1086. id = scene_->GetFreeComponentID(mode);
  1087. component->SetID(id);
  1088. scene_->ComponentAdded(component);
  1089. }
  1090. else
  1091. component->SetID(id);
  1092. component->SetNode(this);
  1093. component->OnMarkedDirty(this);
  1094. // Check attributes of the new component on next network update, and mark node dirty in all replication states
  1095. component->MarkNetworkUpdate();
  1096. MarkNetworkUpdate();
  1097. MarkReplicationDirty();
  1098. // Send change event
  1099. if (scene_)
  1100. {
  1101. using namespace ComponentAdded;
  1102. VariantMap eventData;
  1103. eventData[P_SCENE] = (void*)scene_;
  1104. eventData[P_NODE] = (void*)this;
  1105. eventData[P_COMPONENT] = (void*)component;
  1106. scene_->SendEvent(E_COMPONENTADDED, eventData);
  1107. }
  1108. }
  1109. unsigned Node::GetNumPersistentChildren() const
  1110. {
  1111. unsigned ret = 0;
  1112. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1113. {
  1114. if (!(*i)->IsTemporary())
  1115. ++ret;
  1116. }
  1117. return ret;
  1118. }
  1119. unsigned Node::GetNumPersistentComponents() const
  1120. {
  1121. unsigned ret = 0;
  1122. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  1123. {
  1124. if (!(*i)->IsTemporary())
  1125. ++ret;
  1126. }
  1127. return ret;
  1128. }
  1129. void Node::UpdateWorldTransform() const
  1130. {
  1131. Matrix3x4 transform = GetTransform();
  1132. // Assume the root node (scene) has identity transform
  1133. if (parent_ == scene_ || !parent_)
  1134. {
  1135. worldTransform_ = transform;
  1136. worldRotation_ = rotation_;
  1137. }
  1138. else
  1139. {
  1140. worldTransform_ = parent_->GetWorldTransform() * transform;
  1141. worldRotation_ = parent_->GetWorldRotation() * rotation_;
  1142. }
  1143. dirty_ = false;
  1144. }
  1145. void Node::RemoveChild(Vector<SharedPtr<Node> >::Iterator i)
  1146. {
  1147. // Send change event. Do not send when already being destroyed
  1148. if (Refs() > 0 && scene_)
  1149. {
  1150. using namespace NodeRemoved;
  1151. VariantMap eventData;
  1152. eventData[P_SCENE] = (void*)scene_;
  1153. eventData[P_PARENT] = (void*)this;
  1154. eventData[P_NODE] = (void*)(*i).Get();
  1155. scene_->SendEvent(E_NODEREMOVED, eventData);
  1156. }
  1157. (*i)->parent_ = 0;
  1158. (*i)->MarkDirty();
  1159. (*i)->MarkNetworkUpdate();
  1160. children_.Erase(i);
  1161. }
  1162. void Node::GetChildrenRecursive(PODVector<Node*>& dest) const
  1163. {
  1164. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1165. {
  1166. Node* node = *i;
  1167. dest.Push(node);
  1168. if (!node->children_.Empty())
  1169. node->GetChildrenRecursive(dest);
  1170. }
  1171. }
  1172. void Node::GetChildrenWithComponentRecursive(PODVector<Node*>& dest, ShortStringHash type) const
  1173. {
  1174. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1175. {
  1176. Node* node = *i;
  1177. if (node->HasComponent(type))
  1178. dest.Push(node);
  1179. if (!node->children_.Empty())
  1180. node->GetChildrenWithComponentRecursive(dest, type);
  1181. }
  1182. }
  1183. void Node::GetComponentsRecursive(PODVector<Component*>& dest, ShortStringHash type) const
  1184. {
  1185. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  1186. {
  1187. if ((*i)->GetType() == type)
  1188. dest.Push(*i);
  1189. }
  1190. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1191. (*i)->GetComponentsRecursive(dest, type);
  1192. }
  1193. Node* Node::CloneRecursive(Node* parent, SceneResolver& resolver, CreateMode mode)
  1194. {
  1195. // Create clone node
  1196. Node* cloneNode = parent->CreateChild(0, (mode == REPLICATED && id_ < FIRST_LOCAL_ID) ? REPLICATED : LOCAL);
  1197. resolver.AddNode(id_, cloneNode);
  1198. // Copy attributes
  1199. unsigned numAttributes = GetNumAttributes();
  1200. for (unsigned j = 0; j < numAttributes; ++j)
  1201. cloneNode->SetAttribute(j, GetAttribute(j));
  1202. // Clone components
  1203. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  1204. {
  1205. Component* component = *i;
  1206. Component* cloneComponent = cloneNode->CreateComponent(component->GetType(), (mode == REPLICATED && component->GetID() <
  1207. FIRST_LOCAL_ID) ? REPLICATED : LOCAL);
  1208. if (!cloneComponent)
  1209. {
  1210. LOGERROR("Could not clone component " + component->GetTypeName());
  1211. continue;
  1212. }
  1213. resolver.AddComponent(component->GetID(), cloneComponent);
  1214. numAttributes = component->GetNumAttributes();
  1215. for (unsigned j = 0; j < numAttributes; ++j)
  1216. cloneComponent->SetAttribute(j, component->GetAttribute(j));
  1217. }
  1218. // Clone child nodes recursively
  1219. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1220. {
  1221. Node* node = *i;
  1222. node->CloneRecursive(cloneNode, resolver, mode);
  1223. }
  1224. return cloneNode;
  1225. }
  1226. void Node::RemoveComponent(Vector<SharedPtr<Component> >::Iterator i)
  1227. {
  1228. WeakPtr<Component> componentWeak(*i);
  1229. // Send node change event. Do not send when already being destroyed
  1230. if (Refs() > 0 && scene_)
  1231. {
  1232. using namespace ComponentRemoved;
  1233. VariantMap eventData;
  1234. eventData[P_SCENE] = (void*)scene_;
  1235. eventData[P_NODE] = (void*)this;
  1236. eventData[P_COMPONENT] = (void*)(*i).Get();
  1237. scene_->SendEvent(E_COMPONENTREMOVED, eventData);
  1238. }
  1239. RemoveListener(*i);
  1240. if (scene_)
  1241. scene_->ComponentRemoved(*i);
  1242. components_.Erase(i);
  1243. // If the component is still referenced elsewhere, reset its node pointer now
  1244. if (componentWeak)
  1245. componentWeak->SetNode(0);
  1246. }
  1247. }