Node.cpp 63 KB

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