Node.cpp 63 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253
  1. // Copyright (c) 2008-2022 the Urho3D project
  2. // License: MIT
  3. #include "../Precompiled.h"
  4. #include "../Core/Context.h"
  5. #include "../Core/Profiler.h"
  6. #include "../IO/Log.h"
  7. #include "../IO/MemoryBuffer.h"
  8. #include "../Resource/XMLFile.h"
  9. #include "../Resource/JSONFile.h"
  10. #include "../Scene/Component.h"
  11. #include "../Scene/ObjectAnimation.h"
  12. #include "../Scene/ReplicationState.h"
  13. #include "../Scene/Scene.h"
  14. #include "../Scene/SceneEvents.h"
  15. #include "../Scene/SmoothedTransform.h"
  16. #include "../Scene/UnknownComponent.h"
  17. #include "../DebugNew.h"
  18. using namespace std;
  19. #ifdef _MSC_VER
  20. #pragma warning(disable:6293)
  21. #endif
  22. namespace Urho3D
  23. {
  24. Node::Node(Context* context) :
  25. Animatable(context),
  26. worldTransform_(Matrix3x4::IDENTITY),
  27. dirty_(false),
  28. enabled_(true),
  29. enabledPrev_(true),
  30. networkUpdate_(false),
  31. parent_(nullptr),
  32. scene_(nullptr),
  33. id_(0),
  34. position_(Vector3::ZERO),
  35. rotation_(Quaternion::IDENTITY),
  36. scale_(Vector3::ONE),
  37. worldRotation_(Quaternion::IDENTITY)
  38. {
  39. impl_ = make_unique<NodeImpl>();
  40. impl_->owner_ = nullptr;
  41. }
  42. Node::~Node()
  43. {
  44. RemoveAllChildren();
  45. RemoveAllComponents();
  46. // Remove from the scene
  47. if (scene_)
  48. scene_->NodeRemoved(this);
  49. }
  50. void Node::RegisterObject(Context* context)
  51. {
  52. context->RegisterFactory<Node>();
  53. URHO3D_ACCESSOR_ATTRIBUTE("Is Enabled", IsEnabled, SetEnabled, bool, true, AM_DEFAULT);
  54. URHO3D_ACCESSOR_ATTRIBUTE("Name", GetName, SetName, String, String::EMPTY, AM_DEFAULT);
  55. URHO3D_ACCESSOR_ATTRIBUTE("Tags", GetTags, SetTags, StringVector, Variant::emptyStringVector, AM_DEFAULT);
  56. URHO3D_ACCESSOR_ATTRIBUTE("Position", GetPosition, SetPosition, Vector3, Vector3::ZERO, AM_FILE);
  57. URHO3D_ACCESSOR_ATTRIBUTE("Rotation", GetRotation, SetRotation, Quaternion, Quaternion::IDENTITY, AM_FILE);
  58. URHO3D_ACCESSOR_ATTRIBUTE("Scale", GetScale, SetScale, Vector3, Vector3::ONE, AM_DEFAULT);
  59. URHO3D_ATTRIBUTE("Variables", VariantMap, vars_, Variant::emptyVariantMap, AM_FILE); // Network replication of vars uses custom data
  60. URHO3D_ACCESSOR_ATTRIBUTE("Network Position", GetNetPositionAttr, SetNetPositionAttr, Vector3, Vector3::ZERO,
  61. AM_NET | AM_LATESTDATA | AM_NOEDIT);
  62. URHO3D_ACCESSOR_ATTRIBUTE("Network Rotation", GetNetRotationAttr, SetNetRotationAttr, PODVector<unsigned char>, Variant::emptyBuffer,
  63. AM_NET | AM_LATESTDATA | AM_NOEDIT);
  64. URHO3D_ACCESSOR_ATTRIBUTE("Network Parent Node", GetNetParentAttr, SetNetParentAttr, PODVector<unsigned char>, Variant::emptyBuffer,
  65. AM_NET | AM_NOEDIT);
  66. }
  67. bool Node::Load(Deserializer& source)
  68. {
  69. SceneResolver resolver;
  70. // Read own ID. Will not be applied, only stored for resolving possible references
  71. unsigned nodeID = source.ReadUInt();
  72. resolver.AddNode(nodeID, this);
  73. // Read attributes, components and child nodes
  74. bool success = Load(source, resolver);
  75. if (success)
  76. {
  77. resolver.Resolve();
  78. ApplyAttributes();
  79. }
  80. return success;
  81. }
  82. bool Node::Save(Serializer& dest) const
  83. {
  84. // Write node ID
  85. if (!dest.WriteUInt(id_))
  86. return false;
  87. // Write attributes
  88. if (!Animatable::Save(dest))
  89. return false;
  90. // Write components
  91. dest.WriteVLE(GetNumPersistentComponents());
  92. for (unsigned i = 0; i < components_.Size(); ++i)
  93. {
  94. Component* component = components_[i];
  95. if (component->IsTemporary())
  96. continue;
  97. // Create a separate buffer to be able to skip failing components during deserialization
  98. VectorBuffer compBuffer;
  99. if (!component->Save(compBuffer))
  100. return false;
  101. dest.WriteVLE(compBuffer.GetSize());
  102. dest.Write(compBuffer.GetData(), compBuffer.GetSize());
  103. }
  104. // Write child nodes
  105. dest.WriteVLE(GetNumPersistentChildren());
  106. for (unsigned i = 0; i < children_.Size(); ++i)
  107. {
  108. Node* node = children_[i];
  109. if (node->IsTemporary())
  110. continue;
  111. if (!node->Save(dest))
  112. return false;
  113. }
  114. return true;
  115. }
  116. bool Node::LoadXML(const XMLElement& source)
  117. {
  118. SceneResolver resolver;
  119. // Read own ID. Will not be applied, only stored for resolving possible references
  120. unsigned nodeID = source.GetUInt("id");
  121. resolver.AddNode(nodeID, this);
  122. // Read attributes, components and child nodes
  123. bool success = LoadXML(source, resolver);
  124. if (success)
  125. {
  126. resolver.Resolve();
  127. ApplyAttributes();
  128. }
  129. return success;
  130. }
  131. bool Node::LoadJSON(const JSONValue& source)
  132. {
  133. SceneResolver resolver;
  134. // Read own ID. Will not be applied, only stored for resolving possible references
  135. unsigned nodeID = source.Get("id").GetUInt();
  136. resolver.AddNode(nodeID, this);
  137. // Read attributes, components and child nodes
  138. bool success = LoadJSON(source, resolver);
  139. if (success)
  140. {
  141. resolver.Resolve();
  142. ApplyAttributes();
  143. }
  144. return success;
  145. }
  146. bool Node::SaveXML(XMLElement& dest) const
  147. {
  148. // Write node ID
  149. if (!dest.SetUInt("id", id_))
  150. return false;
  151. // Write attributes
  152. if (!Animatable::SaveXML(dest))
  153. return false;
  154. // Write components
  155. for (unsigned i = 0; i < components_.Size(); ++i)
  156. {
  157. Component* component = components_[i];
  158. if (component->IsTemporary())
  159. continue;
  160. XMLElement compElem = dest.CreateChild("component");
  161. if (!component->SaveXML(compElem))
  162. return false;
  163. }
  164. // Write child nodes
  165. for (unsigned i = 0; i < children_.Size(); ++i)
  166. {
  167. Node* node = children_[i];
  168. if (node->IsTemporary())
  169. continue;
  170. XMLElement childElem = dest.CreateChild("node");
  171. if (!node->SaveXML(childElem))
  172. return false;
  173. }
  174. return true;
  175. }
  176. bool Node::SaveJSON(JSONValue& dest) const
  177. {
  178. // Write node ID
  179. dest.Set("id", id_);
  180. // Write attributes
  181. if (!Animatable::SaveJSON(dest))
  182. return false;
  183. // Write components
  184. JSONArray componentsArray;
  185. componentsArray.Reserve(components_.Size());
  186. for (unsigned i = 0; i < components_.Size(); ++i)
  187. {
  188. Component* component = components_[i];
  189. if (component->IsTemporary())
  190. continue;
  191. JSONValue compVal;
  192. if (!component->SaveJSON(compVal))
  193. return false;
  194. componentsArray.Push(compVal);
  195. }
  196. dest.Set("components", componentsArray);
  197. // Write child nodes
  198. JSONArray childrenArray;
  199. childrenArray.Reserve(children_.Size());
  200. for (unsigned i = 0; i < children_.Size(); ++i)
  201. {
  202. Node* node = children_[i];
  203. if (node->IsTemporary())
  204. continue;
  205. JSONValue childVal;
  206. if (!node->SaveJSON(childVal))
  207. return false;
  208. childrenArray.Push(childVal);
  209. }
  210. dest.Set("children", childrenArray);
  211. return true;
  212. }
  213. void Node::ApplyAttributes()
  214. {
  215. for (unsigned i = 0; i < components_.Size(); ++i)
  216. components_[i]->ApplyAttributes();
  217. for (unsigned i = 0; i < children_.Size(); ++i)
  218. children_[i]->ApplyAttributes();
  219. }
  220. void Node::MarkNetworkUpdate()
  221. {
  222. if (!networkUpdate_ && scene_ && IsReplicated())
  223. {
  224. scene_->MarkNetworkUpdate(this);
  225. networkUpdate_ = true;
  226. }
  227. }
  228. void Node::AddReplicationState(NodeReplicationState* state)
  229. {
  230. if (!networkState_)
  231. AllocateNetworkState();
  232. networkState_->replicationStates_.Push(state);
  233. }
  234. bool Node::SaveXML(Serializer& dest, const String& indentation) const
  235. {
  236. SharedPtr<XMLFile> xml(new XMLFile(context_));
  237. XMLElement rootElem = xml->CreateRoot("node");
  238. if (!SaveXML(rootElem))
  239. return false;
  240. return xml->Save(dest, indentation);
  241. }
  242. bool Node::SaveJSON(Serializer& dest, const String& indentation) const
  243. {
  244. SharedPtr<JSONFile> json(new JSONFile(context_));
  245. JSONValue& rootElem = json->GetRoot();
  246. if (!SaveJSON(rootElem))
  247. return false;
  248. return json->Save(dest, indentation);
  249. }
  250. void Node::SetName(const String& name)
  251. {
  252. if (name != impl_->name_)
  253. {
  254. impl_->name_ = name;
  255. impl_->nameHash_ = name;
  256. MarkNetworkUpdate();
  257. // Send change event
  258. if (scene_)
  259. {
  260. using namespace NodeNameChanged;
  261. VariantMap& eventData = GetEventDataMap();
  262. eventData[P_SCENE] = scene_;
  263. eventData[P_NODE] = this;
  264. scene_->SendEvent(E_NODENAMECHANGED, eventData);
  265. }
  266. }
  267. }
  268. void Node::SetTags(const StringVector& tags)
  269. {
  270. RemoveAllTags();
  271. AddTags(tags);
  272. // MarkNetworkUpdate() already called in RemoveAllTags() / AddTags()
  273. }
  274. void Node::AddTag(const String& tag)
  275. {
  276. // Check if tag empty or already added
  277. if (tag.Empty() || HasTag(tag))
  278. return;
  279. // Add tag
  280. impl_->tags_.Push(tag);
  281. // Cache
  282. if (scene_)
  283. {
  284. scene_->NodeTagAdded(this, tag);
  285. // Send event
  286. using namespace NodeTagAdded;
  287. VariantMap& eventData = GetEventDataMap();
  288. eventData[P_SCENE] = scene_;
  289. eventData[P_NODE] = this;
  290. eventData[P_TAG] = tag;
  291. scene_->SendEvent(E_NODETAGADDED, eventData);
  292. }
  293. // Sync
  294. MarkNetworkUpdate();
  295. }
  296. void Node::AddTags(const String& tags, char separator)
  297. {
  298. StringVector tagVector = tags.Split(separator);
  299. AddTags(tagVector);
  300. }
  301. void Node::AddTags(const StringVector& tags)
  302. {
  303. // This is OK, as MarkNetworkUpdate() early-outs when called multiple times
  304. for (unsigned i = 0; i < tags.Size(); ++i)
  305. AddTag(tags[i]);
  306. }
  307. bool Node::RemoveTag(const String& tag)
  308. {
  309. bool removed = impl_->tags_.Remove(tag);
  310. // Nothing to do
  311. if (!removed)
  312. return false;
  313. // Scene cache update
  314. if (scene_)
  315. {
  316. scene_->NodeTagRemoved(this, tag);
  317. // Send event
  318. using namespace NodeTagRemoved;
  319. VariantMap& eventData = GetEventDataMap();
  320. eventData[P_SCENE] = scene_;
  321. eventData[P_NODE] = this;
  322. eventData[P_TAG] = tag;
  323. scene_->SendEvent(E_NODETAGREMOVED, eventData);
  324. }
  325. // Sync
  326. MarkNetworkUpdate();
  327. return true;
  328. }
  329. void Node::RemoveAllTags()
  330. {
  331. // Clear old scene cache
  332. if (scene_)
  333. {
  334. for (unsigned i = 0; i < impl_->tags_.Size(); ++i)
  335. {
  336. scene_->NodeTagRemoved(this, impl_->tags_[i]);
  337. // Send event
  338. using namespace NodeTagRemoved;
  339. VariantMap& eventData = GetEventDataMap();
  340. eventData[P_SCENE] = scene_;
  341. eventData[P_NODE] = this;
  342. eventData[P_TAG] = impl_->tags_[i];
  343. scene_->SendEvent(E_NODETAGREMOVED, eventData);
  344. }
  345. }
  346. impl_->tags_.Clear();
  347. // Sync
  348. MarkNetworkUpdate();
  349. }
  350. void Node::SetPosition(const Vector3& position)
  351. {
  352. position_ = position;
  353. MarkDirty();
  354. MarkNetworkUpdate();
  355. }
  356. void Node::SetRotation(const Quaternion& rotation)
  357. {
  358. rotation_ = rotation;
  359. MarkDirty();
  360. MarkNetworkUpdate();
  361. }
  362. void Node::SetDirection(const Vector3& direction)
  363. {
  364. SetRotation(Quaternion(Vector3::FORWARD, direction));
  365. }
  366. void Node::SetScale(float scale)
  367. {
  368. SetScale(Vector3(scale, scale, scale));
  369. }
  370. void Node::SetScale(const Vector3& scale)
  371. {
  372. scale_ = scale;
  373. // Prevent exact zero scale e.g. from momentary edits as this may cause division by zero
  374. // when decomposing the world transform matrix
  375. if (scale_.x_ == 0.0f)
  376. scale_.x_ = M_EPSILON;
  377. if (scale_.y_ == 0.0f)
  378. scale_.y_ = M_EPSILON;
  379. if (scale_.z_ == 0.0f)
  380. scale_.z_ = M_EPSILON;
  381. MarkDirty();
  382. MarkNetworkUpdate();
  383. }
  384. void Node::SetTransform(const Vector3& position, const Quaternion& rotation)
  385. {
  386. position_ = position;
  387. rotation_ = rotation;
  388. MarkDirty();
  389. MarkNetworkUpdate();
  390. }
  391. void Node::SetTransform(const Vector3& position, const Quaternion& rotation, float scale)
  392. {
  393. SetTransform(position, rotation, Vector3(scale, scale, scale));
  394. }
  395. void Node::SetTransform(const Vector3& position, const Quaternion& rotation, const Vector3& scale)
  396. {
  397. position_ = position;
  398. rotation_ = rotation;
  399. scale_ = scale;
  400. MarkDirty();
  401. MarkNetworkUpdate();
  402. }
  403. void Node::SetTransform(const Matrix3x4& matrix)
  404. {
  405. SetTransform(matrix.Translation(), matrix.Rotation(), matrix.Scale());
  406. }
  407. void Node::SetWorldPosition(const Vector3& position)
  408. {
  409. SetPosition((parent_ == scene_ || !parent_) ? position : parent_->GetWorldTransform().Inverse() * position);
  410. }
  411. void Node::SetWorldRotation(const Quaternion& rotation)
  412. {
  413. SetRotation((parent_ == scene_ || !parent_) ? rotation : parent_->GetWorldRotation().Inverse() * rotation);
  414. }
  415. void Node::SetWorldDirection(const Vector3& direction)
  416. {
  417. Vector3 localDirection = (parent_ == scene_ || !parent_) ? direction : parent_->GetWorldRotation().Inverse() * direction;
  418. SetRotation(Quaternion(Vector3::FORWARD, localDirection));
  419. }
  420. void Node::SetWorldScale(float scale)
  421. {
  422. SetWorldScale(Vector3(scale, scale, scale));
  423. }
  424. void Node::SetWorldScale(const Vector3& scale)
  425. {
  426. SetScale((parent_ == scene_ || !parent_) ? scale : scale / parent_->GetWorldScale());
  427. }
  428. void Node::SetWorldTransform(const Vector3& position, const Quaternion& rotation)
  429. {
  430. SetWorldPosition(position);
  431. SetWorldRotation(rotation);
  432. }
  433. void Node::SetWorldTransform(const Vector3& position, const Quaternion& rotation, float scale)
  434. {
  435. SetWorldPosition(position);
  436. SetWorldRotation(rotation);
  437. SetWorldScale(scale);
  438. }
  439. void Node::SetWorldTransform(const Vector3& position, const Quaternion& rotation, const Vector3& scale)
  440. {
  441. SetWorldPosition(position);
  442. SetWorldRotation(rotation);
  443. SetWorldScale(scale);
  444. }
  445. void Node::SetWorldTransform(const Matrix3x4& worldTransform)
  446. {
  447. SetWorldTransform(worldTransform.Translation(), worldTransform.Rotation(), worldTransform.Scale());
  448. }
  449. void Node::Translate(const Vector3& delta, TransformSpace space)
  450. {
  451. switch (space)
  452. {
  453. case TS_LOCAL:
  454. // Note: local space translation disregards local scale for scale-independent movement speed
  455. position_ += rotation_ * delta;
  456. break;
  457. case TS_PARENT:
  458. position_ += delta;
  459. break;
  460. case TS_WORLD:
  461. position_ += (parent_ == scene_ || !parent_) ? delta : parent_->GetWorldTransform().Inverse() * Vector4(delta, 0.0f);
  462. break;
  463. }
  464. MarkDirty();
  465. MarkNetworkUpdate();
  466. }
  467. void Node::Rotate(const Quaternion& delta, TransformSpace space)
  468. {
  469. switch (space)
  470. {
  471. case TS_LOCAL:
  472. rotation_ = (rotation_ * delta).Normalized();
  473. break;
  474. case TS_PARENT:
  475. rotation_ = (delta * rotation_).Normalized();
  476. break;
  477. case TS_WORLD:
  478. if (parent_ == scene_ || !parent_)
  479. rotation_ = (delta * rotation_).Normalized();
  480. else
  481. {
  482. Quaternion worldRotation = GetWorldRotation();
  483. rotation_ = rotation_ * worldRotation.Inverse() * delta * worldRotation;
  484. }
  485. break;
  486. }
  487. MarkDirty();
  488. MarkNetworkUpdate();
  489. }
  490. void Node::RotateAround(const Vector3& point, const Quaternion& delta, TransformSpace space)
  491. {
  492. Vector3 parentSpacePoint;
  493. Quaternion oldRotation = rotation_;
  494. switch (space)
  495. {
  496. case TS_LOCAL:
  497. parentSpacePoint = GetTransform() * point;
  498. rotation_ = (rotation_ * delta).Normalized();
  499. break;
  500. case TS_PARENT:
  501. parentSpacePoint = point;
  502. rotation_ = (delta * rotation_).Normalized();
  503. break;
  504. case TS_WORLD:
  505. if (parent_ == scene_ || !parent_)
  506. {
  507. parentSpacePoint = point;
  508. rotation_ = (delta * rotation_).Normalized();
  509. }
  510. else
  511. {
  512. parentSpacePoint = parent_->GetWorldTransform().Inverse() * point;
  513. Quaternion worldRotation = GetWorldRotation();
  514. rotation_ = rotation_ * worldRotation.Inverse() * delta * worldRotation;
  515. }
  516. break;
  517. }
  518. Vector3 oldRelativePos = oldRotation.Inverse() * (position_ - parentSpacePoint);
  519. position_ = rotation_ * oldRelativePos + parentSpacePoint;
  520. MarkDirty();
  521. MarkNetworkUpdate();
  522. }
  523. void Node::Yaw(float angle, TransformSpace space)
  524. {
  525. Rotate(Quaternion(angle, Vector3::UP), space);
  526. }
  527. void Node::Pitch(float angle, TransformSpace space)
  528. {
  529. Rotate(Quaternion(angle, Vector3::RIGHT), space);
  530. }
  531. void Node::Roll(float angle, TransformSpace space)
  532. {
  533. Rotate(Quaternion(angle, Vector3::FORWARD), space);
  534. }
  535. bool Node::LookAt(const Vector3& target, const Vector3& up, TransformSpace space)
  536. {
  537. Vector3 worldSpaceTarget;
  538. switch (space)
  539. {
  540. case TS_LOCAL:
  541. worldSpaceTarget = GetWorldTransform() * target;
  542. break;
  543. case TS_PARENT:
  544. worldSpaceTarget = (parent_ == scene_ || !parent_) ? target : parent_->GetWorldTransform() * target;
  545. break;
  546. case TS_WORLD:
  547. worldSpaceTarget = target;
  548. break;
  549. }
  550. Vector3 lookDir = worldSpaceTarget - GetWorldPosition();
  551. // Check if target is very close, in that case can not reliably calculate lookat direction
  552. if (lookDir.Equals(Vector3::ZERO))
  553. return false;
  554. Quaternion newRotation;
  555. // Do nothing if setting look rotation failed
  556. if (!newRotation.FromLookRotation(lookDir, up))
  557. return false;
  558. SetWorldRotation(newRotation);
  559. return true;
  560. }
  561. void Node::Scale(float scale)
  562. {
  563. Scale(Vector3(scale, scale, scale));
  564. }
  565. void Node::Scale(const Vector3& scale)
  566. {
  567. scale_ *= scale;
  568. MarkDirty();
  569. MarkNetworkUpdate();
  570. }
  571. void Node::SetEnabled(bool enable)
  572. {
  573. SetEnabled(enable, false, true);
  574. }
  575. void Node::SetDeepEnabled(bool enable)
  576. {
  577. SetEnabled(enable, true, false);
  578. }
  579. void Node::ResetDeepEnabled()
  580. {
  581. SetEnabled(enabledPrev_, false, false);
  582. for (Vector<SharedPtr<Node>>::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  583. (*i)->ResetDeepEnabled();
  584. }
  585. void Node::SetEnabledRecursive(bool enable)
  586. {
  587. SetEnabled(enable, true, true);
  588. }
  589. void Node::SetOwner(Connection* owner)
  590. {
  591. impl_->owner_ = owner;
  592. }
  593. void Node::MarkDirty()
  594. {
  595. Node *cur = this;
  596. for (;;)
  597. {
  598. // Precondition:
  599. // a) whenever a node is marked dirty, all its children are marked dirty as well.
  600. // b) whenever a node is cleared from being dirty, all its parents must have been
  601. // cleared as well.
  602. // Therefore if we are recursing here to mark this node dirty, and it already was,
  603. // then all children of this node must also be already dirty, and we don't need to
  604. // reflag them again.
  605. if (cur->dirty_)
  606. return;
  607. cur->dirty_ = true;
  608. // Notify listener components first, then mark child nodes
  609. for (Vector<WeakPtr<Component>>::Iterator i = cur->listeners_.Begin(); i != cur->listeners_.End();)
  610. {
  611. Component *c = *i;
  612. if (c)
  613. {
  614. c->OnMarkedDirty(cur);
  615. ++i;
  616. }
  617. // If listener has expired, erase from list (swap with the last element to avoid O(n^2) behavior)
  618. else
  619. {
  620. *i = cur->listeners_.Back();
  621. cur->listeners_.Pop();
  622. }
  623. }
  624. // Tail call optimization: Don't recurse to mark the first child dirty, but
  625. // instead process it in the context of the current function. If there are more
  626. // than one child, then recurse to the excess children.
  627. Vector<SharedPtr<Node>>::Iterator i = cur->children_.Begin();
  628. if (i != cur->children_.End())
  629. {
  630. Node *next = *i;
  631. for (++i; i != cur->children_.End(); ++i)
  632. (*i)->MarkDirty();
  633. cur = next;
  634. }
  635. else
  636. return;
  637. }
  638. }
  639. Node* Node::CreateChild(const String& name, CreateMode mode, unsigned id, bool temporary)
  640. {
  641. Node* newNode = CreateChild(id, mode, temporary);
  642. newNode->SetName(name);
  643. return newNode;
  644. }
  645. Node* Node::CreateTemporaryChild(const String& name, CreateMode mode, unsigned id)
  646. {
  647. return CreateChild(name, mode, id, true);
  648. }
  649. void Node::AddChild(Node* node, i32 index)
  650. {
  651. assert((index >= 0 && index <= children_.Size()) || index == ENDPOS);
  652. // Check for illegal or redundant parent assignment
  653. if (!node || node == this || node->parent_ == this)
  654. return;
  655. // Check for possible cyclic parent assignment
  656. if (IsChildOf(node))
  657. return;
  658. // Keep a shared ptr to the node while transferring
  659. SharedPtr<Node> nodeShared(node);
  660. Node* oldParent = node->parent_;
  661. if (oldParent)
  662. {
  663. // If old parent is in different scene, perform the full removal
  664. if (oldParent->GetScene() != scene_)
  665. oldParent->RemoveChild(node);
  666. else
  667. {
  668. if (scene_)
  669. {
  670. // Otherwise do not remove from the scene during reparenting, just send the necessary change event
  671. using namespace NodeRemoved;
  672. VariantMap& eventData = GetEventDataMap();
  673. eventData[P_SCENE] = scene_;
  674. eventData[P_PARENT] = oldParent;
  675. eventData[P_NODE] = node;
  676. scene_->SendEvent(E_NODEREMOVED, eventData);
  677. }
  678. oldParent->children_.Remove(nodeShared);
  679. }
  680. }
  681. // Add to the child vector, then add to the scene if not added yet
  682. children_.Insert(index, nodeShared);
  683. if (scene_ && node->GetScene() != scene_)
  684. scene_->NodeAdded(node);
  685. node->parent_ = this;
  686. node->MarkDirty();
  687. node->MarkNetworkUpdate();
  688. // If the child node has components, also mark network update on them to ensure they have a valid NetworkState
  689. for (Vector<SharedPtr<Component>>::Iterator i = node->components_.Begin(); i != node->components_.End(); ++i)
  690. (*i)->MarkNetworkUpdate();
  691. // Send change event
  692. if (scene_)
  693. {
  694. using namespace NodeAdded;
  695. VariantMap& eventData = GetEventDataMap();
  696. eventData[P_SCENE] = scene_;
  697. eventData[P_PARENT] = this;
  698. eventData[P_NODE] = node;
  699. scene_->SendEvent(E_NODEADDED, eventData);
  700. }
  701. }
  702. void Node::RemoveChild(Node* node)
  703. {
  704. if (!node)
  705. return;
  706. for (Vector<SharedPtr<Node>>::Iterator i = children_.Begin(); i != children_.End(); ++i)
  707. {
  708. if (*i == node)
  709. {
  710. RemoveChild(i);
  711. return;
  712. }
  713. }
  714. }
  715. void Node::RemoveAllChildren()
  716. {
  717. RemoveChildren(true, true, true);
  718. }
  719. void Node::RemoveChildren(bool removeReplicated, bool removeLocal, bool recursive)
  720. {
  721. unsigned numRemoved = 0;
  722. for (unsigned i = children_.Size() - 1; i < children_.Size(); --i)
  723. {
  724. bool remove = false;
  725. Node* childNode = children_[i];
  726. if (recursive)
  727. childNode->RemoveChildren(removeReplicated, removeLocal, true);
  728. if (childNode->IsReplicated() && removeReplicated)
  729. remove = true;
  730. else if (!childNode->IsReplicated() && removeLocal)
  731. remove = true;
  732. if (remove)
  733. {
  734. RemoveChild(children_.Begin() + i);
  735. ++numRemoved;
  736. }
  737. }
  738. // Mark node dirty in all replication states
  739. if (numRemoved)
  740. MarkReplicationDirty();
  741. }
  742. Component* Node::CreateComponent(StringHash type, CreateMode mode, unsigned id)
  743. {
  744. // Do not attempt to create replicated components to local nodes, as that may lead to component ID overwrite
  745. // as replicated components are synced over
  746. if (mode == REPLICATED && !IsReplicated())
  747. mode = LOCAL;
  748. // Check that creation succeeds and that the object in fact is a component
  749. SharedPtr<Component> newComponent = DynamicCast<Component>(context_->CreateObject(type));
  750. if (!newComponent)
  751. {
  752. URHO3D_LOGERROR("Could not create unknown component type " + type.ToString());
  753. return nullptr;
  754. }
  755. AddComponent(newComponent, id, mode);
  756. return newComponent;
  757. }
  758. Component* Node::GetOrCreateComponent(StringHash type, CreateMode mode, unsigned id)
  759. {
  760. Component* oldComponent = GetComponent(type);
  761. if (oldComponent)
  762. return oldComponent;
  763. else
  764. return CreateComponent(type, mode, id);
  765. }
  766. Component* Node::CloneComponent(Component* component, unsigned id)
  767. {
  768. if (!component)
  769. {
  770. URHO3D_LOGERROR("Null source component given for CloneComponent");
  771. return nullptr;
  772. }
  773. return CloneComponent(component, component->IsReplicated() ? REPLICATED : LOCAL, id);
  774. }
  775. Component* Node::CloneComponent(Component* component, CreateMode mode, unsigned id)
  776. {
  777. if (!component)
  778. {
  779. URHO3D_LOGERROR("Null source component given for CloneComponent");
  780. return nullptr;
  781. }
  782. Component* cloneComponent = SafeCreateComponent(component->GetTypeName(), component->GetType(), mode, 0);
  783. if (!cloneComponent)
  784. {
  785. URHO3D_LOGERROR("Could not clone component " + component->GetTypeName());
  786. return nullptr;
  787. }
  788. const Vector<AttributeInfo>* compAttributes = component->GetAttributes();
  789. const Vector<AttributeInfo>* cloneAttributes = cloneComponent->GetAttributes();
  790. if (compAttributes)
  791. {
  792. for (unsigned i = 0; i < compAttributes->Size() && i < cloneAttributes->Size(); ++i)
  793. {
  794. const AttributeInfo& attr = compAttributes->At(i);
  795. const AttributeInfo& cloneAttr = cloneAttributes->At(i);
  796. if (attr.mode_ & AM_FILE)
  797. {
  798. Variant value;
  799. component->OnGetAttribute(attr, value);
  800. // Note: when eg. a ScriptInstance component is cloned, its script object attributes are unique and therefore we
  801. // can not simply refer to the source component's AttributeInfo
  802. cloneComponent->OnSetAttribute(cloneAttr, value);
  803. }
  804. }
  805. cloneComponent->ApplyAttributes();
  806. }
  807. if (scene_)
  808. {
  809. using namespace ComponentCloned;
  810. VariantMap& eventData = GetEventDataMap();
  811. eventData[P_SCENE] = scene_;
  812. eventData[P_COMPONENT] = component;
  813. eventData[P_CLONECOMPONENT] = cloneComponent;
  814. scene_->SendEvent(E_COMPONENTCLONED, eventData);
  815. }
  816. return cloneComponent;
  817. }
  818. void Node::RemoveComponent(Component* component)
  819. {
  820. for (Vector<SharedPtr<Component>>::Iterator i = components_.Begin(); i != components_.End(); ++i)
  821. {
  822. if (*i == component)
  823. {
  824. RemoveComponent(i);
  825. // Mark node dirty in all replication states
  826. MarkReplicationDirty();
  827. return;
  828. }
  829. }
  830. }
  831. void Node::RemoveComponent(StringHash type)
  832. {
  833. for (Vector<SharedPtr<Component>>::Iterator i = components_.Begin(); i != components_.End(); ++i)
  834. {
  835. if ((*i)->GetType() == type)
  836. {
  837. RemoveComponent(i);
  838. // Mark node dirty in all replication states
  839. MarkReplicationDirty();
  840. return;
  841. }
  842. }
  843. }
  844. void Node::RemoveComponents(bool removeReplicated, bool removeLocal)
  845. {
  846. unsigned numRemoved = 0;
  847. for (unsigned i = components_.Size() - 1; i < components_.Size(); --i)
  848. {
  849. bool remove = false;
  850. Component* component = components_[i];
  851. if (component->IsReplicated() && removeReplicated)
  852. remove = true;
  853. else if (!component->IsReplicated() && removeLocal)
  854. remove = true;
  855. if (remove)
  856. {
  857. RemoveComponent(components_.Begin() + i);
  858. ++numRemoved;
  859. }
  860. }
  861. // Mark node dirty in all replication states
  862. if (numRemoved)
  863. MarkReplicationDirty();
  864. }
  865. void Node::RemoveComponents(StringHash type)
  866. {
  867. unsigned numRemoved = 0;
  868. for (unsigned i = components_.Size() - 1; i < components_.Size(); --i)
  869. {
  870. if (components_[i]->GetType() == type)
  871. {
  872. RemoveComponent(components_.Begin() + i);
  873. ++numRemoved;
  874. }
  875. }
  876. // Mark node dirty in all replication states
  877. if (numRemoved)
  878. MarkReplicationDirty();
  879. }
  880. void Node::RemoveAllComponents()
  881. {
  882. RemoveComponents(true, true);
  883. }
  884. void Node::ReorderComponent(Component* component, unsigned index)
  885. {
  886. if (!component || component->GetNode() != this)
  887. return;
  888. for (Vector<SharedPtr<Component>>::Iterator i = components_.Begin(); i != components_.End(); ++i)
  889. {
  890. if (*i == component)
  891. {
  892. // Need shared ptr to insert. Also, prevent destruction when removing first
  893. SharedPtr<Component> componentShared(component);
  894. components_.Erase(i);
  895. components_.Insert(index, componentShared);
  896. return;
  897. }
  898. }
  899. }
  900. Node* Node::Clone(CreateMode mode)
  901. {
  902. // The scene itself can not be cloned
  903. if (this == scene_ || !parent_)
  904. {
  905. URHO3D_LOGERROR("Can not clone node without a parent");
  906. return nullptr;
  907. }
  908. URHO3D_PROFILE(CloneNode);
  909. SceneResolver resolver;
  910. Node* clone = CloneRecursive(parent_, resolver, mode);
  911. resolver.Resolve();
  912. clone->ApplyAttributes();
  913. return clone;
  914. }
  915. void Node::Remove()
  916. {
  917. if (parent_)
  918. parent_->RemoveChild(this);
  919. }
  920. void Node::SetParent(Node* parent)
  921. {
  922. if (parent)
  923. {
  924. Matrix3x4 oldWorldTransform = GetWorldTransform();
  925. parent->AddChild(this);
  926. if (parent != scene_)
  927. {
  928. Matrix3x4 newTransform = parent->GetWorldTransform().Inverse() * oldWorldTransform;
  929. SetTransform(newTransform.Translation(), newTransform.Rotation(), newTransform.Scale());
  930. }
  931. else
  932. {
  933. // The root node is assumed to have identity transform, so can disregard it
  934. SetTransform(oldWorldTransform.Translation(), oldWorldTransform.Rotation(), oldWorldTransform.Scale());
  935. }
  936. }
  937. }
  938. void Node::SetVar(StringHash key, const Variant& value)
  939. {
  940. vars_[key] = value;
  941. MarkNetworkUpdate();
  942. }
  943. void Node::AddListener(Component* component)
  944. {
  945. if (!component)
  946. return;
  947. // Check for not adding twice
  948. for (Vector<WeakPtr<Component>>::Iterator i = listeners_.Begin(); i != listeners_.End(); ++i)
  949. {
  950. if (*i == component)
  951. return;
  952. }
  953. listeners_.Push(WeakPtr<Component>(component));
  954. // If the node is currently dirty, notify immediately
  955. if (dirty_)
  956. component->OnMarkedDirty(this);
  957. }
  958. void Node::RemoveListener(Component* component)
  959. {
  960. for (Vector<WeakPtr<Component>>::Iterator i = listeners_.Begin(); i != listeners_.End(); ++i)
  961. {
  962. if (*i == component)
  963. {
  964. listeners_.Erase(i);
  965. return;
  966. }
  967. }
  968. }
  969. Vector3 Node::GetSignedWorldScale() const
  970. {
  971. if (dirty_)
  972. UpdateWorldTransform();
  973. return worldTransform_.SignedScale(worldRotation_.RotationMatrix());
  974. }
  975. Vector3 Node::LocalToWorld(const Vector3& position) const
  976. {
  977. return GetWorldTransform() * position;
  978. }
  979. Vector3 Node::LocalToWorld(const Vector4& vector) const
  980. {
  981. return GetWorldTransform() * vector;
  982. }
  983. Vector2 Node::LocalToWorld2D(const Vector2& vector) const
  984. {
  985. Vector3 result = LocalToWorld(Vector3(vector));
  986. return Vector2(result.x_, result.y_);
  987. }
  988. Vector3 Node::WorldToLocal(const Vector3& position) const
  989. {
  990. return GetWorldTransform().Inverse() * position;
  991. }
  992. Vector3 Node::WorldToLocal(const Vector4& vector) const
  993. {
  994. return GetWorldTransform().Inverse() * vector;
  995. }
  996. Vector2 Node::WorldToLocal2D(const Vector2& vector) const
  997. {
  998. Vector3 result = WorldToLocal(Vector3(vector));
  999. return Vector2(result.x_, result.y_);
  1000. }
  1001. unsigned Node::GetNumChildren(bool recursive) const
  1002. {
  1003. if (!recursive)
  1004. return children_.Size();
  1005. else
  1006. {
  1007. unsigned allChildren = children_.Size();
  1008. for (Vector<SharedPtr<Node>>::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1009. allChildren += (*i)->GetNumChildren(true);
  1010. return allChildren;
  1011. }
  1012. }
  1013. void Node::GetChildren(PODVector<Node*>& dest, bool recursive) const
  1014. {
  1015. dest.Clear();
  1016. if (!recursive)
  1017. {
  1018. for (Vector<SharedPtr<Node>>::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1019. dest.Push(*i);
  1020. }
  1021. else
  1022. GetChildrenRecursive(dest);
  1023. }
  1024. PODVector<Node*> Node::GetChildren(bool recursive) const
  1025. {
  1026. PODVector<Node*> dest;
  1027. GetChildren(dest, recursive);
  1028. return dest;
  1029. }
  1030. void Node::GetChildrenWithComponent(PODVector<Node*>& dest, StringHash type, bool recursive) const
  1031. {
  1032. dest.Clear();
  1033. if (!recursive)
  1034. {
  1035. for (Vector<SharedPtr<Node>>::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1036. {
  1037. if ((*i)->HasComponent(type))
  1038. dest.Push(*i);
  1039. }
  1040. }
  1041. else
  1042. GetChildrenWithComponentRecursive(dest, type);
  1043. }
  1044. PODVector<Node*> Node::GetChildrenWithComponent(StringHash type, bool recursive) const
  1045. {
  1046. PODVector<Node*> dest;
  1047. GetChildrenWithComponent(dest, type, recursive);
  1048. return dest;
  1049. }
  1050. void Node::GetChildrenWithTag(PODVector<Node*>& dest, const String& tag, bool recursive /*= true*/) const
  1051. {
  1052. dest.Clear();
  1053. if (!recursive)
  1054. {
  1055. for (Vector<SharedPtr<Node>>::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1056. {
  1057. if ((*i)->HasTag(tag))
  1058. dest.Push(*i);
  1059. }
  1060. }
  1061. else
  1062. GetChildrenWithTagRecursive(dest, tag);
  1063. }
  1064. PODVector<Node*> Node::GetChildrenWithTag(const String& tag, bool recursive) const
  1065. {
  1066. PODVector<Node*> dest;
  1067. GetChildrenWithTag(dest, tag, recursive);
  1068. return dest;
  1069. }
  1070. Node* Node::GetChild(unsigned index) const
  1071. {
  1072. return index < children_.Size() ? children_[index].Get() : nullptr;
  1073. }
  1074. Node* Node::GetChild(const String& name, bool recursive) const
  1075. {
  1076. return GetChild(StringHash(name), recursive);
  1077. }
  1078. Node* Node::GetChild(const char* name, bool recursive) const
  1079. {
  1080. return GetChild(StringHash(name), recursive);
  1081. }
  1082. Node* Node::GetChild(StringHash nameHash, bool recursive) const
  1083. {
  1084. for (Vector<SharedPtr<Node>>::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1085. {
  1086. if ((*i)->GetNameHash() == nameHash)
  1087. return *i;
  1088. if (recursive)
  1089. {
  1090. Node* node = (*i)->GetChild(nameHash, true);
  1091. if (node)
  1092. return node;
  1093. }
  1094. }
  1095. return nullptr;
  1096. }
  1097. unsigned Node::GetNumNetworkComponents() const
  1098. {
  1099. unsigned num = 0;
  1100. for (Vector<SharedPtr<Component>>::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  1101. {
  1102. if ((*i)->IsReplicated())
  1103. ++num;
  1104. }
  1105. return num;
  1106. }
  1107. void Node::GetComponents(PODVector<Component*>& dest, StringHash type, bool recursive) const
  1108. {
  1109. dest.Clear();
  1110. if (!recursive)
  1111. {
  1112. for (Vector<SharedPtr<Component>>::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  1113. {
  1114. if ((*i)->GetType() == type)
  1115. dest.Push(*i);
  1116. }
  1117. }
  1118. else
  1119. GetComponentsRecursive(dest, type);
  1120. }
  1121. bool Node::HasComponent(StringHash type) const
  1122. {
  1123. for (Vector<SharedPtr<Component>>::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  1124. {
  1125. if ((*i)->GetType() == type)
  1126. return true;
  1127. }
  1128. return false;
  1129. }
  1130. bool Node::IsReplicated() const
  1131. {
  1132. return Scene::IsReplicatedID(id_);
  1133. }
  1134. bool Node::HasTag(const String& tag) const
  1135. {
  1136. return impl_->tags_.Contains(tag);
  1137. }
  1138. bool Node::IsChildOf(Node* node) const
  1139. {
  1140. Node* parent = parent_;
  1141. while (parent)
  1142. {
  1143. if (parent == node)
  1144. return true;
  1145. parent = parent->parent_;
  1146. }
  1147. return false;
  1148. }
  1149. const Variant& Node::GetVar(StringHash key) const
  1150. {
  1151. VariantMap::ConstIterator i = vars_.Find(key);
  1152. return i != vars_.End() ? i->second_ : Variant::EMPTY;
  1153. }
  1154. Component* Node::GetComponent(StringHash type, bool recursive) const
  1155. {
  1156. for (Vector<SharedPtr<Component>>::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  1157. {
  1158. if ((*i)->GetType() == type)
  1159. return *i;
  1160. }
  1161. if (recursive)
  1162. {
  1163. for (Vector<SharedPtr<Node>>::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1164. {
  1165. Component* component = (*i)->GetComponent(type, true);
  1166. if (component)
  1167. return component;
  1168. }
  1169. }
  1170. return nullptr;
  1171. }
  1172. Component* Node::GetParentComponent(StringHash type, bool fullTraversal) const
  1173. {
  1174. Node* current = GetParent();
  1175. while (current)
  1176. {
  1177. Component* soughtComponent = current->GetComponent(type);
  1178. if (soughtComponent)
  1179. return soughtComponent;
  1180. if (fullTraversal)
  1181. current = current->GetParent();
  1182. else
  1183. break;
  1184. }
  1185. return nullptr;
  1186. }
  1187. void Node::SetID(unsigned id)
  1188. {
  1189. id_ = id;
  1190. }
  1191. void Node::SetScene(Scene* scene)
  1192. {
  1193. scene_ = scene;
  1194. }
  1195. void Node::ResetScene()
  1196. {
  1197. SetID(0);
  1198. SetScene(nullptr);
  1199. SetOwner(nullptr);
  1200. }
  1201. void Node::SetNetPositionAttr(const Vector3& value)
  1202. {
  1203. auto* transform = GetComponent<SmoothedTransform>();
  1204. if (transform)
  1205. transform->SetTargetPosition(value);
  1206. else
  1207. SetPosition(value);
  1208. }
  1209. void Node::SetNetRotationAttr(const PODVector<unsigned char>& value)
  1210. {
  1211. MemoryBuffer buf(value);
  1212. auto* transform = GetComponent<SmoothedTransform>();
  1213. if (transform)
  1214. transform->SetTargetRotation(buf.ReadPackedQuaternion());
  1215. else
  1216. SetRotation(buf.ReadPackedQuaternion());
  1217. }
  1218. void Node::SetNetParentAttr(const PODVector<unsigned char>& value)
  1219. {
  1220. Scene* scene = GetScene();
  1221. if (!scene)
  1222. return;
  1223. MemoryBuffer buf(value);
  1224. // If nothing in the buffer, parent is the root node
  1225. if (buf.IsEof())
  1226. {
  1227. scene->AddChild(this);
  1228. return;
  1229. }
  1230. unsigned baseNodeID = buf.ReadNetID();
  1231. Node* baseNode = scene->GetNode(baseNodeID);
  1232. if (!baseNode)
  1233. {
  1234. URHO3D_LOGWARNING("Failed to find parent node " + String(baseNodeID));
  1235. return;
  1236. }
  1237. // If buffer contains just an ID, the parent is replicated and we are done
  1238. if (buf.IsEof())
  1239. baseNode->AddChild(this);
  1240. else
  1241. {
  1242. // Else the parent is local and we must find it recursively by name hash
  1243. StringHash nameHash = buf.ReadStringHash();
  1244. Node* parentNode = baseNode->GetChild(nameHash, true);
  1245. if (!parentNode)
  1246. URHO3D_LOGWARNING("Failed to find parent node with name hash " + nameHash.ToString());
  1247. else
  1248. parentNode->AddChild(this);
  1249. }
  1250. }
  1251. const Vector3& Node::GetNetPositionAttr() const
  1252. {
  1253. return position_;
  1254. }
  1255. const PODVector<unsigned char>& Node::GetNetRotationAttr() const
  1256. {
  1257. impl_->attrBuffer_.Clear();
  1258. impl_->attrBuffer_.WritePackedQuaternion(rotation_);
  1259. return impl_->attrBuffer_.GetBuffer();
  1260. }
  1261. const PODVector<unsigned char>& Node::GetNetParentAttr() const
  1262. {
  1263. impl_->attrBuffer_.Clear();
  1264. Scene* scene = GetScene();
  1265. if (scene && parent_ && parent_ != scene)
  1266. {
  1267. // If parent is replicated, can write the ID directly
  1268. unsigned parentID = parent_->GetID();
  1269. if (Scene::IsReplicatedID(parentID))
  1270. impl_->attrBuffer_.WriteNetID(parentID);
  1271. else
  1272. {
  1273. // Parent is local: traverse hierarchy to find a non-local base node
  1274. // This iteration always stops due to the scene (root) being non-local
  1275. Node* current = parent_;
  1276. while (!current->IsReplicated())
  1277. current = current->GetParent();
  1278. // Then write the base node ID and the parent's name hash
  1279. impl_->attrBuffer_.WriteNetID(current->GetID());
  1280. impl_->attrBuffer_.WriteStringHash(parent_->GetNameHash());
  1281. }
  1282. }
  1283. return impl_->attrBuffer_.GetBuffer();
  1284. }
  1285. bool Node::Load(Deserializer& source, SceneResolver& resolver, bool loadChildren, bool rewriteIDs, CreateMode mode)
  1286. {
  1287. // Remove all children and components first in case this is not a fresh load
  1288. RemoveAllChildren();
  1289. RemoveAllComponents();
  1290. // ID has been read at the parent level
  1291. if (!Animatable::Load(source))
  1292. return false;
  1293. unsigned numComponents = source.ReadVLE();
  1294. for (unsigned i = 0; i < numComponents; ++i)
  1295. {
  1296. VectorBuffer compBuffer(source, source.ReadVLE());
  1297. StringHash compType = compBuffer.ReadStringHash();
  1298. unsigned compID = compBuffer.ReadUInt();
  1299. Component* newComponent = SafeCreateComponent(String::EMPTY, compType,
  1300. (mode == REPLICATED && Scene::IsReplicatedID(compID)) ? REPLICATED : LOCAL, rewriteIDs ? 0 : compID);
  1301. if (newComponent)
  1302. {
  1303. resolver.AddComponent(compID, newComponent);
  1304. // Do not abort if component fails to load, as the component buffer is nested and we can skip to the next
  1305. newComponent->Load(compBuffer);
  1306. }
  1307. }
  1308. if (!loadChildren)
  1309. return true;
  1310. unsigned numChildren = source.ReadVLE();
  1311. for (unsigned i = 0; i < numChildren; ++i)
  1312. {
  1313. unsigned nodeID = source.ReadUInt();
  1314. Node* newNode = CreateChild(rewriteIDs ? 0 : nodeID, (mode == REPLICATED && Scene::IsReplicatedID(nodeID)) ? REPLICATED :
  1315. LOCAL);
  1316. resolver.AddNode(nodeID, newNode);
  1317. if (!newNode->Load(source, resolver, loadChildren, rewriteIDs, mode))
  1318. return false;
  1319. }
  1320. return true;
  1321. }
  1322. bool Node::LoadXML(const XMLElement& source, SceneResolver& resolver, bool loadChildren, bool rewriteIDs, CreateMode mode)
  1323. {
  1324. // Remove all children and components first in case this is not a fresh load
  1325. RemoveAllChildren();
  1326. RemoveAllComponents();
  1327. if (!Animatable::LoadXML(source))
  1328. return false;
  1329. XMLElement compElem = source.GetChild("component");
  1330. while (compElem)
  1331. {
  1332. String typeName = compElem.GetAttribute("type");
  1333. unsigned compID = compElem.GetUInt("id");
  1334. Component* newComponent = SafeCreateComponent(typeName, StringHash(typeName),
  1335. (mode == REPLICATED && Scene::IsReplicatedID(compID)) ? REPLICATED : LOCAL, rewriteIDs ? 0 : compID);
  1336. if (newComponent)
  1337. {
  1338. resolver.AddComponent(compID, newComponent);
  1339. if (!newComponent->LoadXML(compElem))
  1340. return false;
  1341. }
  1342. compElem = compElem.GetNext("component");
  1343. }
  1344. if (!loadChildren)
  1345. return true;
  1346. XMLElement childElem = source.GetChild("node");
  1347. while (childElem)
  1348. {
  1349. unsigned nodeID = childElem.GetUInt("id");
  1350. Node* newNode = CreateChild(rewriteIDs ? 0 : nodeID, (mode == REPLICATED && Scene::IsReplicatedID(nodeID)) ? REPLICATED :
  1351. LOCAL);
  1352. resolver.AddNode(nodeID, newNode);
  1353. if (!newNode->LoadXML(childElem, resolver, loadChildren, rewriteIDs, mode))
  1354. return false;
  1355. childElem = childElem.GetNext("node");
  1356. }
  1357. return true;
  1358. }
  1359. bool Node::LoadJSON(const JSONValue& source, SceneResolver& resolver, bool loadChildren, bool rewriteIDs, CreateMode mode)
  1360. {
  1361. // Remove all children and components first in case this is not a fresh load
  1362. RemoveAllChildren();
  1363. RemoveAllComponents();
  1364. if (!Animatable::LoadJSON(source))
  1365. return false;
  1366. const JSONArray& componentsArray = source.Get("components").GetArray();
  1367. for (unsigned i = 0; i < componentsArray.Size(); i++)
  1368. {
  1369. const JSONValue& compVal = componentsArray.At(i);
  1370. String typeName = compVal.Get("type").GetString();
  1371. unsigned compID = compVal.Get("id").GetUInt();
  1372. Component* newComponent = SafeCreateComponent(typeName, StringHash(typeName),
  1373. (mode == REPLICATED && Scene::IsReplicatedID(compID)) ? REPLICATED : LOCAL, rewriteIDs ? 0 : compID);
  1374. if (newComponent)
  1375. {
  1376. resolver.AddComponent(compID, newComponent);
  1377. if (!newComponent->LoadJSON(compVal))
  1378. return false;
  1379. }
  1380. }
  1381. if (!loadChildren)
  1382. return true;
  1383. const JSONArray& childrenArray = source.Get("children").GetArray();
  1384. for (unsigned i = 0; i < childrenArray.Size(); i++)
  1385. {
  1386. const JSONValue& childVal = childrenArray.At(i);
  1387. unsigned nodeID = childVal.Get("id").GetUInt();
  1388. Node* newNode = CreateChild(rewriteIDs ? 0 : nodeID, (mode == REPLICATED && Scene::IsReplicatedID(nodeID)) ? REPLICATED :
  1389. LOCAL);
  1390. resolver.AddNode(nodeID, newNode);
  1391. if (!newNode->LoadJSON(childVal, resolver, loadChildren, rewriteIDs, mode))
  1392. return false;
  1393. }
  1394. return true;
  1395. }
  1396. void Node::PrepareNetworkUpdate()
  1397. {
  1398. // Update dependency nodes list first
  1399. impl_->dependencyNodes_.Clear();
  1400. // Add the parent node, but if it is local, traverse to the first non-local node
  1401. if (parent_ && parent_ != scene_)
  1402. {
  1403. Node* current = parent_;
  1404. while (!current->IsReplicated())
  1405. current = current->parent_;
  1406. if (current && current != scene_)
  1407. impl_->dependencyNodes_.Push(current);
  1408. }
  1409. // Let the components add their dependencies
  1410. for (Vector<SharedPtr<Component>>::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  1411. {
  1412. Component* component = *i;
  1413. if (component->IsReplicated())
  1414. component->GetDependencyNodes(impl_->dependencyNodes_);
  1415. }
  1416. // Then check for node attribute changes
  1417. if (!networkState_)
  1418. AllocateNetworkState();
  1419. const Vector<AttributeInfo>* attributes = networkState_->attributes_;
  1420. unsigned numAttributes = attributes->Size();
  1421. // Check for attribute changes
  1422. for (unsigned i = 0; i < numAttributes; ++i)
  1423. {
  1424. const AttributeInfo& attr = attributes->At(i);
  1425. if (animationEnabled_ && IsAnimatedNetworkAttribute(attr))
  1426. continue;
  1427. OnGetAttribute(attr, networkState_->currentValues_[i]);
  1428. if (networkState_->currentValues_[i] != networkState_->previousValues_[i])
  1429. {
  1430. networkState_->previousValues_[i] = networkState_->currentValues_[i];
  1431. // Mark the attribute dirty in all replication states that are tracking this node
  1432. for (PODVector<ReplicationState*>::Iterator j = networkState_->replicationStates_.Begin();
  1433. j != networkState_->replicationStates_.End(); ++j)
  1434. {
  1435. auto* nodeState = static_cast<NodeReplicationState*>(*j);
  1436. nodeState->dirtyAttributes_.Set(i);
  1437. // Add node to the dirty set if not added yet
  1438. if (!nodeState->markedDirty_)
  1439. {
  1440. nodeState->markedDirty_ = true;
  1441. nodeState->sceneState_->dirtyNodes_.Insert(id_);
  1442. }
  1443. }
  1444. }
  1445. }
  1446. // Finally check for user var changes
  1447. for (VariantMap::ConstIterator i = vars_.Begin(); i != vars_.End(); ++i)
  1448. {
  1449. VariantMap::ConstIterator j = networkState_->previousVars_.Find(i->first_);
  1450. if (j == networkState_->previousVars_.End() || j->second_ != i->second_)
  1451. {
  1452. networkState_->previousVars_[i->first_] = i->second_;
  1453. // Mark the var dirty in all replication states that are tracking this node
  1454. for (PODVector<ReplicationState*>::Iterator j = networkState_->replicationStates_.Begin();
  1455. j != networkState_->replicationStates_.End(); ++j)
  1456. {
  1457. auto* nodeState = static_cast<NodeReplicationState*>(*j);
  1458. nodeState->dirtyVars_.Insert(i->first_);
  1459. if (!nodeState->markedDirty_)
  1460. {
  1461. nodeState->markedDirty_ = true;
  1462. nodeState->sceneState_->dirtyNodes_.Insert(id_);
  1463. }
  1464. }
  1465. }
  1466. }
  1467. networkUpdate_ = false;
  1468. }
  1469. void Node::CleanupConnection(Connection* connection)
  1470. {
  1471. if (impl_->owner_ == connection)
  1472. impl_->owner_ = nullptr;
  1473. if (networkState_)
  1474. {
  1475. for (unsigned i = networkState_->replicationStates_.Size() - 1; i < networkState_->replicationStates_.Size(); --i)
  1476. {
  1477. if (networkState_->replicationStates_[i]->connection_ == connection)
  1478. networkState_->replicationStates_.Erase(i);
  1479. }
  1480. }
  1481. }
  1482. void Node::MarkReplicationDirty()
  1483. {
  1484. if (networkState_)
  1485. {
  1486. for (PODVector<ReplicationState*>::Iterator j = networkState_->replicationStates_.Begin();
  1487. j != networkState_->replicationStates_.End(); ++j)
  1488. {
  1489. auto* nodeState = static_cast<NodeReplicationState*>(*j);
  1490. if (!nodeState->markedDirty_)
  1491. {
  1492. nodeState->markedDirty_ = true;
  1493. nodeState->sceneState_->dirtyNodes_.Insert(id_);
  1494. }
  1495. }
  1496. }
  1497. }
  1498. Node* Node::CreateChild(unsigned id, CreateMode mode, bool temporary)
  1499. {
  1500. SharedPtr<Node> newNode(new Node(context_));
  1501. newNode->SetTemporary(temporary);
  1502. // If zero ID specified, or the ID is already taken, let the scene assign
  1503. if (scene_)
  1504. {
  1505. if (!id || scene_->GetNode(id))
  1506. id = scene_->GetFreeNodeID(mode);
  1507. newNode->SetID(id);
  1508. }
  1509. else
  1510. newNode->SetID(id);
  1511. AddChild(newNode);
  1512. return newNode;
  1513. }
  1514. void Node::AddComponent(Component* component, unsigned id, CreateMode mode)
  1515. {
  1516. if (!component)
  1517. return;
  1518. components_.Push(SharedPtr<Component>(component));
  1519. if (component->GetNode())
  1520. URHO3D_LOGWARNING("Component " + component->GetTypeName() + " already belongs to a node!");
  1521. component->SetNode(this);
  1522. // If zero ID specified, or the ID is already taken, let the scene assign
  1523. if (scene_)
  1524. {
  1525. if (!id || scene_->GetComponent(id))
  1526. id = scene_->GetFreeComponentID(mode);
  1527. component->SetID(id);
  1528. scene_->ComponentAdded(component);
  1529. }
  1530. else
  1531. component->SetID(id);
  1532. component->OnMarkedDirty(this);
  1533. // Check attributes of the new component on next network update, and mark node dirty in all replication states
  1534. component->MarkNetworkUpdate();
  1535. MarkNetworkUpdate();
  1536. MarkReplicationDirty();
  1537. // Send change event
  1538. if (scene_)
  1539. {
  1540. using namespace ComponentAdded;
  1541. VariantMap& eventData = GetEventDataMap();
  1542. eventData[P_SCENE] = scene_;
  1543. eventData[P_NODE] = this;
  1544. eventData[P_COMPONENT] = component;
  1545. scene_->SendEvent(E_COMPONENTADDED, eventData);
  1546. }
  1547. }
  1548. unsigned Node::GetNumPersistentChildren() const
  1549. {
  1550. unsigned ret = 0;
  1551. for (Vector<SharedPtr<Node>>::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1552. {
  1553. if (!(*i)->IsTemporary())
  1554. ++ret;
  1555. }
  1556. return ret;
  1557. }
  1558. unsigned Node::GetNumPersistentComponents() const
  1559. {
  1560. unsigned ret = 0;
  1561. for (Vector<SharedPtr<Component>>::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  1562. {
  1563. if (!(*i)->IsTemporary())
  1564. ++ret;
  1565. }
  1566. return ret;
  1567. }
  1568. void Node::SetTransformSilent(const Vector3& position, const Quaternion& rotation, const Vector3& scale)
  1569. {
  1570. position_ = position;
  1571. rotation_ = rotation;
  1572. scale_ = scale;
  1573. }
  1574. void Node::OnAttributeAnimationAdded()
  1575. {
  1576. if (attributeAnimationInfos_.Size() == 1)
  1577. SubscribeToEvent(GetScene(), E_ATTRIBUTEANIMATIONUPDATE, URHO3D_HANDLER(Node, HandleAttributeAnimationUpdate));
  1578. }
  1579. void Node::OnAttributeAnimationRemoved()
  1580. {
  1581. if (attributeAnimationInfos_.Empty())
  1582. UnsubscribeFromEvent(GetScene(), E_ATTRIBUTEANIMATIONUPDATE);
  1583. }
  1584. Animatable* Node::FindAttributeAnimationTarget(const String& name, String& outName)
  1585. {
  1586. Vector<String> names = name.Split('/');
  1587. // Only attribute name
  1588. if (names.Size() == 1)
  1589. {
  1590. outName = name;
  1591. return this;
  1592. }
  1593. else
  1594. {
  1595. // Name must in following format: "#0/#1/@component#0/attribute"
  1596. Node* node = this;
  1597. unsigned i = 0;
  1598. for (; i < names.Size() - 1; ++i)
  1599. {
  1600. if (names[i].Front() != '#')
  1601. break;
  1602. String name = names[i].Substring(1, names[i].Length() - 1);
  1603. char s = name.Front();
  1604. if (s >= '0' && s <= '9')
  1605. {
  1606. unsigned index = ToUInt(name);
  1607. node = node->GetChild(index);
  1608. }
  1609. else
  1610. {
  1611. node = node->GetChild(name, true);
  1612. }
  1613. if (!node)
  1614. {
  1615. URHO3D_LOGERROR("Could not find node by name " + name);
  1616. return nullptr;
  1617. }
  1618. }
  1619. if (i == names.Size() - 1)
  1620. {
  1621. outName = names.Back();
  1622. return node;
  1623. }
  1624. if (i != names.Size() - 2 || names[i].Front() != '@')
  1625. {
  1626. URHO3D_LOGERROR("Invalid name " + name);
  1627. return nullptr;
  1628. }
  1629. String componentName = names[i].Substring(1, names[i].Length() - 1);
  1630. Vector<String> componentNames = componentName.Split('#');
  1631. if (componentNames.Size() == 1)
  1632. {
  1633. Component* component = node->GetComponent(StringHash(componentNames.Front()));
  1634. if (!component)
  1635. {
  1636. URHO3D_LOGERROR("Could not find component by name " + name);
  1637. return nullptr;
  1638. }
  1639. outName = names.Back();
  1640. return component;
  1641. }
  1642. else
  1643. {
  1644. unsigned index = ToUInt(componentNames[1]);
  1645. PODVector<Component*> components;
  1646. node->GetComponents(components, StringHash(componentNames.Front()));
  1647. if (index >= components.Size())
  1648. {
  1649. URHO3D_LOGERROR("Could not find component by name " + name);
  1650. return nullptr;
  1651. }
  1652. outName = names.Back();
  1653. return components[index];
  1654. }
  1655. }
  1656. }
  1657. void Node::SetEnabled(bool enable, bool recursive, bool storeSelf)
  1658. {
  1659. // The enabled state of the whole scene can not be changed. SetUpdateEnabled() is used instead to start/stop updates.
  1660. if (GetType() == Scene::GetTypeStatic())
  1661. {
  1662. URHO3D_LOGERROR("Can not change enabled state of the Scene");
  1663. return;
  1664. }
  1665. if (storeSelf)
  1666. enabledPrev_ = enable;
  1667. if (enable != enabled_)
  1668. {
  1669. enabled_ = enable;
  1670. MarkNetworkUpdate();
  1671. // Notify listener components of the state change
  1672. for (Vector<WeakPtr<Component>>::Iterator i = listeners_.Begin(); i != listeners_.End();)
  1673. {
  1674. if (*i)
  1675. {
  1676. (*i)->OnNodeSetEnabled(this);
  1677. ++i;
  1678. }
  1679. // If listener has expired, erase from list
  1680. else
  1681. i = listeners_.Erase(i);
  1682. }
  1683. // Send change event
  1684. if (scene_)
  1685. {
  1686. using namespace NodeEnabledChanged;
  1687. VariantMap& eventData = GetEventDataMap();
  1688. eventData[P_SCENE] = scene_;
  1689. eventData[P_NODE] = this;
  1690. scene_->SendEvent(E_NODEENABLEDCHANGED, eventData);
  1691. }
  1692. for (Vector<SharedPtr<Component>>::Iterator i = components_.Begin(); i != components_.End(); ++i)
  1693. {
  1694. (*i)->OnSetEnabled();
  1695. // Send change event for the component
  1696. if (scene_)
  1697. {
  1698. using namespace ComponentEnabledChanged;
  1699. VariantMap& eventData = GetEventDataMap();
  1700. eventData[P_SCENE] = scene_;
  1701. eventData[P_NODE] = this;
  1702. eventData[P_COMPONENT] = (*i);
  1703. scene_->SendEvent(E_COMPONENTENABLEDCHANGED, eventData);
  1704. }
  1705. }
  1706. }
  1707. if (recursive)
  1708. {
  1709. for (Vector<SharedPtr<Node>>::Iterator i = children_.Begin(); i != children_.End(); ++i)
  1710. (*i)->SetEnabled(enable, recursive, storeSelf);
  1711. }
  1712. }
  1713. Component* Node::SafeCreateComponent(const String& typeName, StringHash type, CreateMode mode, unsigned id)
  1714. {
  1715. // Do not attempt to create replicated components to local nodes, as that may lead to component ID overwrite
  1716. // as replicated components are synced over
  1717. if (mode == REPLICATED && !IsReplicated())
  1718. mode = LOCAL;
  1719. // First check if factory for type exists
  1720. if (!context_->GetTypeName(type).Empty())
  1721. return CreateComponent(type, mode, id);
  1722. else
  1723. {
  1724. URHO3D_LOGWARNING("Component type " + type.ToString() + " not known, creating UnknownComponent as placeholder");
  1725. // Else create as UnknownComponent
  1726. SharedPtr<UnknownComponent> newComponent(new UnknownComponent(context_));
  1727. if (typeName.Empty() || typeName.StartsWith("Unknown", false))
  1728. newComponent->SetType(type);
  1729. else
  1730. newComponent->SetTypeName(typeName);
  1731. AddComponent(newComponent, id, mode);
  1732. return newComponent;
  1733. }
  1734. }
  1735. void Node::UpdateWorldTransform() const
  1736. {
  1737. Matrix3x4 transform = GetTransform();
  1738. // Assume the root node (scene) has identity transform
  1739. if (parent_ == scene_ || !parent_)
  1740. {
  1741. worldTransform_ = transform;
  1742. worldRotation_ = rotation_;
  1743. }
  1744. else
  1745. {
  1746. worldTransform_ = parent_->GetWorldTransform() * transform;
  1747. worldRotation_ = parent_->GetWorldRotation() * rotation_;
  1748. }
  1749. dirty_ = false;
  1750. }
  1751. void Node::RemoveChild(Vector<SharedPtr<Node>>::Iterator i)
  1752. {
  1753. // Keep a shared pointer to the child about to be removed, to make sure the erase from container completes first. Otherwise
  1754. // it would be possible that other child nodes get removed as part of the node's components' cleanup, causing a re-entrant
  1755. // erase and a crash
  1756. SharedPtr<Node> child(*i);
  1757. // Send change event. Do not send when this node is already being destroyed
  1758. if (Refs() > 0 && scene_)
  1759. {
  1760. using namespace NodeRemoved;
  1761. VariantMap& eventData = GetEventDataMap();
  1762. eventData[P_SCENE] = scene_;
  1763. eventData[P_PARENT] = this;
  1764. eventData[P_NODE] = child;
  1765. scene_->SendEvent(E_NODEREMOVED, eventData);
  1766. }
  1767. child->parent_ = nullptr;
  1768. child->MarkDirty();
  1769. child->MarkNetworkUpdate();
  1770. if (scene_)
  1771. scene_->NodeRemoved(child);
  1772. children_.Erase(i);
  1773. }
  1774. void Node::GetChildrenRecursive(PODVector<Node*>& dest) const
  1775. {
  1776. for (Vector<SharedPtr<Node>>::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1777. {
  1778. Node* node = *i;
  1779. dest.Push(node);
  1780. if (!node->children_.Empty())
  1781. node->GetChildrenRecursive(dest);
  1782. }
  1783. }
  1784. void Node::GetChildrenWithComponentRecursive(PODVector<Node*>& dest, StringHash type) const
  1785. {
  1786. for (Vector<SharedPtr<Node>>::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1787. {
  1788. Node* node = *i;
  1789. if (node->HasComponent(type))
  1790. dest.Push(node);
  1791. if (!node->children_.Empty())
  1792. node->GetChildrenWithComponentRecursive(dest, type);
  1793. }
  1794. }
  1795. void Node::GetComponentsRecursive(PODVector<Component*>& dest, StringHash type) const
  1796. {
  1797. for (Vector<SharedPtr<Component>>::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  1798. {
  1799. if ((*i)->GetType() == type)
  1800. dest.Push(*i);
  1801. }
  1802. for (Vector<SharedPtr<Node>>::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1803. (*i)->GetComponentsRecursive(dest, type);
  1804. }
  1805. void Node::GetChildrenWithTagRecursive(PODVector<Node*>& dest, const String& tag) const
  1806. {
  1807. for (Vector<SharedPtr<Node>>::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1808. {
  1809. Node* node = *i;
  1810. if (node->HasTag(tag))
  1811. dest.Push(node);
  1812. if (!node->children_.Empty())
  1813. node->GetChildrenWithTagRecursive(dest, tag);
  1814. }
  1815. }
  1816. Node* Node::CloneRecursive(Node* parent, SceneResolver& resolver, CreateMode mode)
  1817. {
  1818. // Create clone node
  1819. Node* cloneNode = parent->CreateChild(0, (mode == REPLICATED && IsReplicated()) ? REPLICATED : LOCAL);
  1820. resolver.AddNode(id_, cloneNode);
  1821. // Copy attributes
  1822. const Vector<AttributeInfo>* attributes = GetAttributes();
  1823. for (unsigned j = 0; j < attributes->Size(); ++j)
  1824. {
  1825. const AttributeInfo& attr = attributes->At(j);
  1826. // Do not copy network-only attributes, as they may have unintended side effects
  1827. if (attr.mode_ & AM_FILE)
  1828. {
  1829. Variant value;
  1830. OnGetAttribute(attr, value);
  1831. cloneNode->OnSetAttribute(attr, value);
  1832. }
  1833. }
  1834. // Clone components
  1835. for (Vector<SharedPtr<Component>>::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  1836. {
  1837. Component* component = *i;
  1838. if (component->IsTemporary())
  1839. continue;
  1840. Component* cloneComponent = cloneNode->CloneComponent(component,
  1841. (mode == REPLICATED && component->IsReplicated()) ? REPLICATED : LOCAL, 0);
  1842. if (cloneComponent)
  1843. resolver.AddComponent(component->GetID(), cloneComponent);
  1844. }
  1845. // Clone child nodes recursively
  1846. for (Vector<SharedPtr<Node>>::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1847. {
  1848. Node* node = *i;
  1849. if (node->IsTemporary())
  1850. continue;
  1851. node->CloneRecursive(cloneNode, resolver, mode);
  1852. }
  1853. if (scene_)
  1854. {
  1855. using namespace NodeCloned;
  1856. VariantMap& eventData = GetEventDataMap();
  1857. eventData[P_SCENE] = scene_;
  1858. eventData[P_NODE] = this;
  1859. eventData[P_CLONENODE] = cloneNode;
  1860. scene_->SendEvent(E_NODECLONED, eventData);
  1861. }
  1862. return cloneNode;
  1863. }
  1864. void Node::RemoveComponent(Vector<SharedPtr<Component>>::Iterator i)
  1865. {
  1866. // Send node change event. Do not send when already being destroyed
  1867. if (Refs() > 0 && scene_)
  1868. {
  1869. using namespace ComponentRemoved;
  1870. VariantMap& eventData = GetEventDataMap();
  1871. eventData[P_SCENE] = scene_;
  1872. eventData[P_NODE] = this;
  1873. eventData[P_COMPONENT] = (*i).Get();
  1874. scene_->SendEvent(E_COMPONENTREMOVED, eventData);
  1875. }
  1876. RemoveListener(*i);
  1877. if (scene_)
  1878. scene_->ComponentRemoved(*i);
  1879. (*i)->SetNode(nullptr);
  1880. components_.Erase(i);
  1881. }
  1882. void Node::HandleAttributeAnimationUpdate(StringHash eventType, VariantMap& eventData)
  1883. {
  1884. using namespace AttributeAnimationUpdate;
  1885. UpdateAttributeAnimations(eventData[P_TIMESTEP].GetFloat());
  1886. }
  1887. }