Node.cpp 43 KB

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