Node.cpp 44 KB

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