Node.cpp 64 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261
  1. //
  2. // Copyright (c) 2008-2017 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, bool temporary)
  651. {
  652. Node* newNode = CreateChild(id, mode, temporary);
  653. newNode->SetName(name);
  654. return newNode;
  655. }
  656. Node* Node::CreateTemporaryChild(const String& name, CreateMode mode, unsigned id)
  657. {
  658. return CreateChild(name, mode, id, true);
  659. }
  660. void Node::AddChild(Node* node, unsigned index)
  661. {
  662. // Check for illegal or redundant parent assignment
  663. if (!node || node == this || node->parent_ == this)
  664. return;
  665. // Check for possible cyclic parent assignment
  666. if (IsChildOf(node))
  667. return;
  668. // Keep a shared ptr to the node while transferring
  669. SharedPtr<Node> nodeShared(node);
  670. Node* oldParent = node->parent_;
  671. if (oldParent)
  672. {
  673. // If old parent is in different scene, perform the full removal
  674. if (oldParent->GetScene() != scene_)
  675. oldParent->RemoveChild(node);
  676. else
  677. {
  678. if (scene_)
  679. {
  680. // Otherwise do not remove from the scene during reparenting, just send the necessary change event
  681. using namespace NodeRemoved;
  682. VariantMap& eventData = GetEventDataMap();
  683. eventData[P_SCENE] = scene_;
  684. eventData[P_PARENT] = oldParent;
  685. eventData[P_NODE] = node;
  686. scene_->SendEvent(E_NODEREMOVED, eventData);
  687. }
  688. oldParent->children_.Remove(nodeShared);
  689. }
  690. }
  691. // Add to the child vector, then add to the scene if not added yet
  692. children_.Insert(index, nodeShared);
  693. if (scene_ && node->GetScene() != scene_)
  694. scene_->NodeAdded(node);
  695. node->parent_ = this;
  696. node->MarkDirty();
  697. node->MarkNetworkUpdate();
  698. // If the child node has components, also mark network update on them to ensure they have a valid NetworkState
  699. for (Vector<SharedPtr<Component> >::Iterator i = node->components_.Begin(); i != node->components_.End(); ++i)
  700. (*i)->MarkNetworkUpdate();
  701. // Send change event
  702. if (scene_)
  703. {
  704. using namespace NodeAdded;
  705. VariantMap& eventData = GetEventDataMap();
  706. eventData[P_SCENE] = scene_;
  707. eventData[P_PARENT] = this;
  708. eventData[P_NODE] = node;
  709. scene_->SendEvent(E_NODEADDED, eventData);
  710. }
  711. }
  712. void Node::RemoveChild(Node* node)
  713. {
  714. if (!node)
  715. return;
  716. for (Vector<SharedPtr<Node> >::Iterator i = children_.Begin(); i != children_.End(); ++i)
  717. {
  718. if (*i == node)
  719. {
  720. RemoveChild(i);
  721. return;
  722. }
  723. }
  724. }
  725. void Node::RemoveAllChildren()
  726. {
  727. RemoveChildren(true, true, true);
  728. }
  729. void Node::RemoveChildren(bool removeReplicated, bool removeLocal, bool recursive)
  730. {
  731. unsigned numRemoved = 0;
  732. for (unsigned i = children_.Size() - 1; i < children_.Size(); --i)
  733. {
  734. bool remove = false;
  735. Node* childNode = children_[i];
  736. if (recursive)
  737. childNode->RemoveChildren(removeReplicated, removeLocal, true);
  738. if (childNode->GetID() < FIRST_LOCAL_ID && removeReplicated)
  739. remove = true;
  740. else if (childNode->GetID() >= FIRST_LOCAL_ID && removeLocal)
  741. remove = true;
  742. if (remove)
  743. {
  744. RemoveChild(children_.Begin() + i);
  745. ++numRemoved;
  746. }
  747. }
  748. // Mark node dirty in all replication states
  749. if (numRemoved)
  750. MarkReplicationDirty();
  751. }
  752. Component* Node::CreateComponent(StringHash type, CreateMode mode, unsigned id)
  753. {
  754. // Do not attempt to create replicated components to local nodes, as that may lead to component ID overwrite
  755. // as replicated components are synced over
  756. if (id_ >= FIRST_LOCAL_ID && mode == REPLICATED)
  757. mode = LOCAL;
  758. // Check that creation succeeds and that the object in fact is a component
  759. SharedPtr<Component> newComponent = DynamicCast<Component>(context_->CreateObject(type));
  760. if (!newComponent)
  761. {
  762. URHO3D_LOGERROR("Could not create unknown component type " + type.ToString());
  763. return 0;
  764. }
  765. AddComponent(newComponent, id, mode);
  766. return newComponent;
  767. }
  768. Component* Node::GetOrCreateComponent(StringHash type, CreateMode mode, unsigned id)
  769. {
  770. Component* oldComponent = GetComponent(type);
  771. if (oldComponent)
  772. return oldComponent;
  773. else
  774. return CreateComponent(type, mode, id);
  775. }
  776. Component* Node::CloneComponent(Component* component, unsigned id)
  777. {
  778. if (!component)
  779. {
  780. URHO3D_LOGERROR("Null source component given for CloneComponent");
  781. return 0;
  782. }
  783. return CloneComponent(component, component->GetID() < FIRST_LOCAL_ID ? REPLICATED : LOCAL, id);
  784. }
  785. Component* Node::CloneComponent(Component* component, CreateMode mode, unsigned id)
  786. {
  787. if (!component)
  788. {
  789. URHO3D_LOGERROR("Null source component given for CloneComponent");
  790. return 0;
  791. }
  792. Component* cloneComponent = SafeCreateComponent(component->GetTypeName(), component->GetType(), mode, 0);
  793. if (!cloneComponent)
  794. {
  795. URHO3D_LOGERROR("Could not clone component " + component->GetTypeName());
  796. return 0;
  797. }
  798. const Vector<AttributeInfo>* compAttributes = component->GetAttributes();
  799. const Vector<AttributeInfo>* cloneAttributes = cloneComponent->GetAttributes();
  800. if (compAttributes)
  801. {
  802. for (unsigned i = 0; i < compAttributes->Size() && i < cloneAttributes->Size(); ++i)
  803. {
  804. const AttributeInfo& attr = compAttributes->At(i);
  805. const AttributeInfo& cloneAttr = cloneAttributes->At(i);
  806. if (attr.mode_ & AM_FILE)
  807. {
  808. Variant value;
  809. component->OnGetAttribute(attr, value);
  810. // Note: when eg. a ScriptInstance component is cloned, its script object attributes are unique and therefore we
  811. // can not simply refer to the source component's AttributeInfo
  812. cloneComponent->OnSetAttribute(cloneAttr, value);
  813. }
  814. }
  815. cloneComponent->ApplyAttributes();
  816. }
  817. {
  818. using namespace ComponentCloned;
  819. VariantMap& eventData = GetEventDataMap();
  820. eventData[P_SCENE] = scene_;
  821. eventData[P_COMPONENT] = component;
  822. eventData[P_CLONECOMPONENT] = cloneComponent;
  823. scene_->SendEvent(E_COMPONENTCLONED, eventData);
  824. }
  825. return cloneComponent;
  826. }
  827. void Node::RemoveComponent(Component* component)
  828. {
  829. for (Vector<SharedPtr<Component> >::Iterator i = components_.Begin(); i != components_.End(); ++i)
  830. {
  831. if (*i == component)
  832. {
  833. RemoveComponent(i);
  834. // Mark node dirty in all replication states
  835. MarkReplicationDirty();
  836. return;
  837. }
  838. }
  839. }
  840. void Node::RemoveComponent(StringHash type)
  841. {
  842. for (Vector<SharedPtr<Component> >::Iterator i = components_.Begin(); i != components_.End(); ++i)
  843. {
  844. if ((*i)->GetType() == type)
  845. {
  846. RemoveComponent(i);
  847. // Mark node dirty in all replication states
  848. MarkReplicationDirty();
  849. return;
  850. }
  851. }
  852. }
  853. void Node::RemoveComponents(bool removeReplicated, bool removeLocal)
  854. {
  855. unsigned numRemoved = 0;
  856. for (unsigned i = components_.Size() - 1; i < components_.Size(); --i)
  857. {
  858. bool remove = false;
  859. Component* component = components_[i];
  860. if (component->GetID() < FIRST_LOCAL_ID && removeReplicated)
  861. remove = true;
  862. else if (component->GetID() >= FIRST_LOCAL_ID && removeLocal)
  863. remove = true;
  864. if (remove)
  865. {
  866. RemoveComponent(components_.Begin() + i);
  867. ++numRemoved;
  868. }
  869. }
  870. // Mark node dirty in all replication states
  871. if (numRemoved)
  872. MarkReplicationDirty();
  873. }
  874. void Node::RemoveComponents(StringHash type)
  875. {
  876. unsigned numRemoved = 0;
  877. for (unsigned i = components_.Size() - 1; i < components_.Size(); --i)
  878. {
  879. if (components_[i]->GetType() == type)
  880. {
  881. RemoveComponent(components_.Begin() + i);
  882. ++numRemoved;
  883. }
  884. }
  885. // Mark node dirty in all replication states
  886. if (numRemoved)
  887. MarkReplicationDirty();
  888. }
  889. void Node::RemoveAllComponents()
  890. {
  891. RemoveComponents(true, true);
  892. }
  893. void Node::ReorderComponent(Component* component, unsigned index)
  894. {
  895. if (!component || component->GetNode() != this)
  896. return;
  897. for (Vector<SharedPtr<Component> >::Iterator i = components_.Begin(); i != components_.End(); ++i)
  898. {
  899. if (*i == component)
  900. {
  901. // Need shared ptr to insert. Also, prevent destruction when removing first
  902. SharedPtr<Component> componentShared(component);
  903. components_.Erase(i);
  904. components_.Insert(index, componentShared);
  905. return;
  906. }
  907. }
  908. }
  909. Node* Node::Clone(CreateMode mode)
  910. {
  911. // The scene itself can not be cloned
  912. if (this == scene_ || !parent_)
  913. {
  914. URHO3D_LOGERROR("Can not clone node without a parent");
  915. return 0;
  916. }
  917. URHO3D_PROFILE(CloneNode);
  918. SceneResolver resolver;
  919. Node* clone = CloneRecursive(parent_, resolver, mode);
  920. resolver.Resolve();
  921. clone->ApplyAttributes();
  922. return clone;
  923. }
  924. void Node::Remove()
  925. {
  926. if (parent_)
  927. parent_->RemoveChild(this);
  928. }
  929. void Node::SetParent(Node* parent)
  930. {
  931. if (parent)
  932. {
  933. Matrix3x4 oldWorldTransform = GetWorldTransform();
  934. parent->AddChild(this);
  935. if (parent != scene_)
  936. {
  937. Matrix3x4 newTransform = parent->GetWorldTransform().Inverse() * oldWorldTransform;
  938. SetTransform(newTransform.Translation(), newTransform.Rotation(), newTransform.Scale());
  939. }
  940. else
  941. {
  942. // The root node is assumed to have identity transform, so can disregard it
  943. SetTransform(oldWorldTransform.Translation(), oldWorldTransform.Rotation(), oldWorldTransform.Scale());
  944. }
  945. }
  946. }
  947. void Node::SetVar(StringHash key, const Variant& value)
  948. {
  949. vars_[key] = value;
  950. MarkNetworkUpdate();
  951. }
  952. void Node::AddListener(Component* component)
  953. {
  954. if (!component)
  955. return;
  956. // Check for not adding twice
  957. for (Vector<WeakPtr<Component> >::Iterator i = listeners_.Begin(); i != listeners_.End(); ++i)
  958. {
  959. if (*i == component)
  960. return;
  961. }
  962. listeners_.Push(WeakPtr<Component>(component));
  963. // If the node is currently dirty, notify immediately
  964. if (dirty_)
  965. component->OnMarkedDirty(this);
  966. }
  967. void Node::RemoveListener(Component* component)
  968. {
  969. for (Vector<WeakPtr<Component> >::Iterator i = listeners_.Begin(); i != listeners_.End(); ++i)
  970. {
  971. if (*i == component)
  972. {
  973. listeners_.Erase(i);
  974. return;
  975. }
  976. }
  977. }
  978. Vector3 Node::GetSignedWorldScale() const
  979. {
  980. if (dirty_)
  981. UpdateWorldTransform();
  982. Vector3 scale = worldTransform_.Scale();
  983. Matrix3 rot = worldRotation_.RotationMatrix();
  984. scale.x_ *= Sign(rot.m00_) * Sign(worldTransform_.m00_);
  985. scale.y_ *= Sign(rot.m11_) * Sign(worldTransform_.m11_);
  986. scale.z_ *= Sign(rot.m22_) * Sign(worldTransform_.m22_);
  987. return scale;
  988. }
  989. Vector3 Node::LocalToWorld(const Vector3& position) const
  990. {
  991. return GetWorldTransform() * position;
  992. }
  993. Vector3 Node::LocalToWorld(const Vector4& vector) const
  994. {
  995. return GetWorldTransform() * vector;
  996. }
  997. Vector2 Node::LocalToWorld2D(const Vector2& vector) const
  998. {
  999. Vector3 result = LocalToWorld(Vector3(vector));
  1000. return Vector2(result.x_, result.y_);
  1001. }
  1002. Vector3 Node::WorldToLocal(const Vector3& position) const
  1003. {
  1004. return GetWorldTransform().Inverse() * position;
  1005. }
  1006. Vector3 Node::WorldToLocal(const Vector4& vector) const
  1007. {
  1008. return GetWorldTransform().Inverse() * vector;
  1009. }
  1010. Vector2 Node::WorldToLocal2D(const Vector2& vector) const
  1011. {
  1012. Vector3 result = WorldToLocal(Vector3(vector));
  1013. return Vector2(result.x_, result.y_);
  1014. }
  1015. unsigned Node::GetNumChildren(bool recursive) const
  1016. {
  1017. if (!recursive)
  1018. return children_.Size();
  1019. else
  1020. {
  1021. unsigned allChildren = children_.Size();
  1022. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1023. allChildren += (*i)->GetNumChildren(true);
  1024. return allChildren;
  1025. }
  1026. }
  1027. void Node::GetChildren(PODVector<Node*>& dest, bool recursive) const
  1028. {
  1029. dest.Clear();
  1030. if (!recursive)
  1031. {
  1032. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1033. dest.Push(*i);
  1034. }
  1035. else
  1036. GetChildrenRecursive(dest);
  1037. }
  1038. PODVector<Node*> Node::GetChildren(bool recursive) const
  1039. {
  1040. PODVector<Node*> dest;
  1041. GetChildren(dest, recursive);
  1042. return dest;
  1043. }
  1044. void Node::GetChildrenWithComponent(PODVector<Node*>& dest, StringHash type, bool recursive) const
  1045. {
  1046. dest.Clear();
  1047. if (!recursive)
  1048. {
  1049. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1050. {
  1051. if ((*i)->HasComponent(type))
  1052. dest.Push(*i);
  1053. }
  1054. }
  1055. else
  1056. GetChildrenWithComponentRecursive(dest, type);
  1057. }
  1058. PODVector<Node*> Node::GetChildrenWithComponent(StringHash type, bool recursive) const
  1059. {
  1060. PODVector<Node*> dest;
  1061. GetChildrenWithComponent(dest, type, recursive);
  1062. return dest;
  1063. }
  1064. void Node::GetChildrenWithTag(PODVector<Node*>& dest, const String& tag, bool recursive /*= true*/) const
  1065. {
  1066. dest.Clear();
  1067. if (!recursive)
  1068. {
  1069. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1070. {
  1071. if ((*i)->HasTag(tag))
  1072. dest.Push(*i);
  1073. }
  1074. }
  1075. else
  1076. GetChildrenWithTagRecursive(dest, tag);
  1077. }
  1078. PODVector<Node*> Node::GetChildrenWithTag(const String& tag, bool recursive) const
  1079. {
  1080. PODVector<Node*> dest;
  1081. GetChildrenWithTag(dest, tag, recursive);
  1082. return dest;
  1083. }
  1084. Node* Node::GetChild(unsigned index) const
  1085. {
  1086. return index < children_.Size() ? children_[index].Get() : 0;
  1087. }
  1088. Node* Node::GetChild(const String& name, bool recursive) const
  1089. {
  1090. return GetChild(StringHash(name), recursive);
  1091. }
  1092. Node* Node::GetChild(const char* name, bool recursive) const
  1093. {
  1094. return GetChild(StringHash(name), recursive);
  1095. }
  1096. Node* Node::GetChild(StringHash nameHash, bool recursive) const
  1097. {
  1098. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1099. {
  1100. if ((*i)->GetNameHash() == nameHash)
  1101. return *i;
  1102. if (recursive)
  1103. {
  1104. Node* node = (*i)->GetChild(nameHash, true);
  1105. if (node)
  1106. return node;
  1107. }
  1108. }
  1109. return 0;
  1110. }
  1111. unsigned Node::GetNumNetworkComponents() const
  1112. {
  1113. unsigned num = 0;
  1114. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  1115. {
  1116. if ((*i)->GetID() < FIRST_LOCAL_ID)
  1117. ++num;
  1118. }
  1119. return num;
  1120. }
  1121. void Node::GetComponents(PODVector<Component*>& dest, StringHash type, bool recursive) const
  1122. {
  1123. dest.Clear();
  1124. if (!recursive)
  1125. {
  1126. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  1127. {
  1128. if ((*i)->GetType() == type)
  1129. dest.Push(*i);
  1130. }
  1131. }
  1132. else
  1133. GetComponentsRecursive(dest, type);
  1134. }
  1135. bool Node::HasComponent(StringHash type) const
  1136. {
  1137. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  1138. {
  1139. if ((*i)->GetType() == type)
  1140. return true;
  1141. }
  1142. return false;
  1143. }
  1144. bool Node::HasTag(const String& tag) const
  1145. {
  1146. return impl_->tags_.Contains(tag);
  1147. }
  1148. bool Node::IsChildOf(Node* node) const
  1149. {
  1150. Node* parent = parent_;
  1151. while (parent)
  1152. {
  1153. if (parent == node)
  1154. return true;
  1155. parent = parent->parent_;
  1156. }
  1157. return false;
  1158. }
  1159. const Variant& Node::GetVar(StringHash key) const
  1160. {
  1161. VariantMap::ConstIterator i = vars_.Find(key);
  1162. return i != vars_.End() ? i->second_ : Variant::EMPTY;
  1163. }
  1164. Component* Node::GetComponent(StringHash type, bool recursive) const
  1165. {
  1166. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  1167. {
  1168. if ((*i)->GetType() == type)
  1169. return *i;
  1170. }
  1171. if (recursive)
  1172. {
  1173. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1174. {
  1175. Component* component = (*i)->GetComponent(type, true);
  1176. if (component)
  1177. return component;
  1178. }
  1179. }
  1180. return 0;
  1181. }
  1182. Component* Node::GetParentComponent(StringHash type, bool fullTraversal) const
  1183. {
  1184. Node* current = GetParent();
  1185. while (current)
  1186. {
  1187. Component* soughtComponent = current->GetComponent(type);
  1188. if (soughtComponent)
  1189. return soughtComponent;
  1190. if (fullTraversal)
  1191. current = current->GetParent();
  1192. else
  1193. break;
  1194. }
  1195. return 0;
  1196. }
  1197. void Node::SetID(unsigned id)
  1198. {
  1199. id_ = id;
  1200. }
  1201. void Node::SetScene(Scene* scene)
  1202. {
  1203. scene_ = scene;
  1204. }
  1205. void Node::ResetScene()
  1206. {
  1207. SetID(0);
  1208. SetScene(0);
  1209. SetOwner(0);
  1210. }
  1211. void Node::SetNetPositionAttr(const Vector3& value)
  1212. {
  1213. SmoothedTransform* transform = GetComponent<SmoothedTransform>();
  1214. if (transform)
  1215. transform->SetTargetPosition(value);
  1216. else
  1217. SetPosition(value);
  1218. }
  1219. void Node::SetNetRotationAttr(const PODVector<unsigned char>& value)
  1220. {
  1221. MemoryBuffer buf(value);
  1222. SmoothedTransform* transform = GetComponent<SmoothedTransform>();
  1223. if (transform)
  1224. transform->SetTargetRotation(buf.ReadPackedQuaternion());
  1225. else
  1226. SetRotation(buf.ReadPackedQuaternion());
  1227. }
  1228. void Node::SetNetParentAttr(const PODVector<unsigned char>& value)
  1229. {
  1230. Scene* scene = GetScene();
  1231. if (!scene)
  1232. return;
  1233. MemoryBuffer buf(value);
  1234. // If nothing in the buffer, parent is the root node
  1235. if (buf.IsEof())
  1236. {
  1237. scene->AddChild(this);
  1238. return;
  1239. }
  1240. unsigned baseNodeID = buf.ReadNetID();
  1241. Node* baseNode = scene->GetNode(baseNodeID);
  1242. if (!baseNode)
  1243. {
  1244. URHO3D_LOGWARNING("Failed to find parent node " + String(baseNodeID));
  1245. return;
  1246. }
  1247. // If buffer contains just an ID, the parent is replicated and we are done
  1248. if (buf.IsEof())
  1249. baseNode->AddChild(this);
  1250. else
  1251. {
  1252. // Else the parent is local and we must find it recursively by name hash
  1253. StringHash nameHash = buf.ReadStringHash();
  1254. Node* parentNode = baseNode->GetChild(nameHash, true);
  1255. if (!parentNode)
  1256. URHO3D_LOGWARNING("Failed to find parent node with name hash " + nameHash.ToString());
  1257. else
  1258. parentNode->AddChild(this);
  1259. }
  1260. }
  1261. const Vector3& Node::GetNetPositionAttr() const
  1262. {
  1263. return position_;
  1264. }
  1265. const PODVector<unsigned char>& Node::GetNetRotationAttr() const
  1266. {
  1267. impl_->attrBuffer_.Clear();
  1268. impl_->attrBuffer_.WritePackedQuaternion(rotation_);
  1269. return impl_->attrBuffer_.GetBuffer();
  1270. }
  1271. const PODVector<unsigned char>& Node::GetNetParentAttr() const
  1272. {
  1273. impl_->attrBuffer_.Clear();
  1274. Scene* scene = GetScene();
  1275. if (scene && parent_ && parent_ != scene)
  1276. {
  1277. // If parent is replicated, can write the ID directly
  1278. unsigned parentID = parent_->GetID();
  1279. if (parentID < FIRST_LOCAL_ID)
  1280. impl_->attrBuffer_.WriteNetID(parentID);
  1281. else
  1282. {
  1283. // Parent is local: traverse hierarchy to find a non-local base node
  1284. // This iteration always stops due to the scene (root) being non-local
  1285. Node* current = parent_;
  1286. while (current->GetID() >= FIRST_LOCAL_ID)
  1287. current = current->GetParent();
  1288. // Then write the base node ID and the parent's name hash
  1289. impl_->attrBuffer_.WriteNetID(current->GetID());
  1290. impl_->attrBuffer_.WriteStringHash(parent_->GetNameHash());
  1291. }
  1292. }
  1293. return impl_->attrBuffer_.GetBuffer();
  1294. }
  1295. bool Node::Load(Deserializer& source, SceneResolver& resolver, bool readChildren, bool rewriteIDs, CreateMode mode)
  1296. {
  1297. // Remove all children and components first in case this is not a fresh load
  1298. RemoveAllChildren();
  1299. RemoveAllComponents();
  1300. // ID has been read at the parent level
  1301. if (!Animatable::Load(source))
  1302. return false;
  1303. unsigned numComponents = source.ReadVLE();
  1304. for (unsigned i = 0; i < numComponents; ++i)
  1305. {
  1306. VectorBuffer compBuffer(source, source.ReadVLE());
  1307. StringHash compType = compBuffer.ReadStringHash();
  1308. unsigned compID = compBuffer.ReadUInt();
  1309. Component* newComponent = SafeCreateComponent(String::EMPTY, compType,
  1310. (mode == REPLICATED && compID < FIRST_LOCAL_ID) ? REPLICATED : LOCAL, rewriteIDs ? 0 : compID);
  1311. if (newComponent)
  1312. {
  1313. resolver.AddComponent(compID, newComponent);
  1314. // Do not abort if component fails to load, as the component buffer is nested and we can skip to the next
  1315. newComponent->Load(compBuffer);
  1316. }
  1317. }
  1318. if (!readChildren)
  1319. return true;
  1320. unsigned numChildren = source.ReadVLE();
  1321. for (unsigned i = 0; i < numChildren; ++i)
  1322. {
  1323. unsigned nodeID = source.ReadUInt();
  1324. Node* newNode = CreateChild(rewriteIDs ? 0 : nodeID, (mode == REPLICATED && nodeID < FIRST_LOCAL_ID) ? REPLICATED :
  1325. LOCAL);
  1326. resolver.AddNode(nodeID, newNode);
  1327. if (!newNode->Load(source, resolver, readChildren, rewriteIDs, mode))
  1328. return false;
  1329. }
  1330. return true;
  1331. }
  1332. bool Node::LoadXML(const XMLElement& source, SceneResolver& resolver, bool readChildren, bool rewriteIDs, CreateMode mode)
  1333. {
  1334. // Remove all children and components first in case this is not a fresh load
  1335. RemoveAllChildren();
  1336. RemoveAllComponents();
  1337. if (!Animatable::LoadXML(source))
  1338. return false;
  1339. XMLElement compElem = source.GetChild("component");
  1340. while (compElem)
  1341. {
  1342. String typeName = compElem.GetAttribute("type");
  1343. unsigned compID = compElem.GetUInt("id");
  1344. Component* newComponent = SafeCreateComponent(typeName, StringHash(typeName),
  1345. (mode == REPLICATED && compID < FIRST_LOCAL_ID) ? REPLICATED : LOCAL, rewriteIDs ? 0 : compID);
  1346. if (newComponent)
  1347. {
  1348. resolver.AddComponent(compID, newComponent);
  1349. if (!newComponent->LoadXML(compElem))
  1350. return false;
  1351. }
  1352. compElem = compElem.GetNext("component");
  1353. }
  1354. if (!readChildren)
  1355. return true;
  1356. XMLElement childElem = source.GetChild("node");
  1357. while (childElem)
  1358. {
  1359. unsigned nodeID = childElem.GetUInt("id");
  1360. Node* newNode = CreateChild(rewriteIDs ? 0 : nodeID, (mode == REPLICATED && nodeID < FIRST_LOCAL_ID) ? REPLICATED :
  1361. LOCAL);
  1362. resolver.AddNode(nodeID, newNode);
  1363. if (!newNode->LoadXML(childElem, resolver, readChildren, rewriteIDs, mode))
  1364. return false;
  1365. childElem = childElem.GetNext("node");
  1366. }
  1367. return true;
  1368. }
  1369. bool Node::LoadJSON(const JSONValue& source, SceneResolver& resolver, bool readChildren, bool rewriteIDs, CreateMode mode)
  1370. {
  1371. // Remove all children and components first in case this is not a fresh load
  1372. RemoveAllChildren();
  1373. RemoveAllComponents();
  1374. if (!Animatable::LoadJSON(source))
  1375. return false;
  1376. const JSONArray& componentsArray = source.Get("components").GetArray();
  1377. for (unsigned i = 0; i < componentsArray.Size(); i++)
  1378. {
  1379. const JSONValue& compVal = componentsArray.At(i);
  1380. String typeName = compVal.Get("type").GetString();
  1381. unsigned compID = compVal.Get("id").GetUInt();
  1382. Component* newComponent = SafeCreateComponent(typeName, StringHash(typeName),
  1383. (mode == REPLICATED && compID < FIRST_LOCAL_ID) ? REPLICATED : LOCAL, rewriteIDs ? 0 : compID);
  1384. if (newComponent)
  1385. {
  1386. resolver.AddComponent(compID, newComponent);
  1387. if (!newComponent->LoadJSON(compVal))
  1388. return false;
  1389. }
  1390. }
  1391. if (!readChildren)
  1392. return true;
  1393. const JSONArray& childrenArray = source.Get("children").GetArray();
  1394. for (unsigned i = 0; i < childrenArray.Size(); i++)
  1395. {
  1396. const JSONValue& childVal = childrenArray.At(i);
  1397. unsigned nodeID = childVal.Get("id").GetUInt();
  1398. Node* newNode = CreateChild(rewriteIDs ? 0 : nodeID, (mode == REPLICATED && nodeID < FIRST_LOCAL_ID) ? REPLICATED :
  1399. LOCAL);
  1400. resolver.AddNode(nodeID, newNode);
  1401. if (!newNode->LoadJSON(childVal, resolver, readChildren, rewriteIDs, mode))
  1402. return false;
  1403. }
  1404. return true;
  1405. }
  1406. void Node::PrepareNetworkUpdate()
  1407. {
  1408. // Update dependency nodes list first
  1409. impl_->dependencyNodes_.Clear();
  1410. // Add the parent node, but if it is local, traverse to the first non-local node
  1411. if (parent_ && parent_ != scene_)
  1412. {
  1413. Node* current = parent_;
  1414. while (current->id_ >= FIRST_LOCAL_ID)
  1415. current = current->parent_;
  1416. if (current && current != scene_)
  1417. impl_->dependencyNodes_.Push(current);
  1418. }
  1419. // Let the components add their dependencies
  1420. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  1421. {
  1422. Component* component = *i;
  1423. if (component->GetID() < FIRST_LOCAL_ID)
  1424. component->GetDependencyNodes(impl_->dependencyNodes_);
  1425. }
  1426. // Then check for node attribute changes
  1427. if (!networkState_)
  1428. AllocateNetworkState();
  1429. const Vector<AttributeInfo>* attributes = networkState_->attributes_;
  1430. unsigned numAttributes = attributes->Size();
  1431. // Check for attribute changes
  1432. for (unsigned i = 0; i < numAttributes; ++i)
  1433. {
  1434. const AttributeInfo& attr = attributes->At(i);
  1435. if (animationEnabled_ && IsAnimatedNetworkAttribute(attr))
  1436. continue;
  1437. OnGetAttribute(attr, networkState_->currentValues_[i]);
  1438. if (networkState_->currentValues_[i] != networkState_->previousValues_[i])
  1439. {
  1440. networkState_->previousValues_[i] = networkState_->currentValues_[i];
  1441. // Mark the attribute dirty in all replication states that are tracking this node
  1442. for (PODVector<ReplicationState*>::Iterator j = networkState_->replicationStates_.Begin();
  1443. j != networkState_->replicationStates_.End(); ++j)
  1444. {
  1445. NodeReplicationState* nodeState = static_cast<NodeReplicationState*>(*j);
  1446. nodeState->dirtyAttributes_.Set(i);
  1447. // Add node to the dirty set if not added yet
  1448. if (!nodeState->markedDirty_)
  1449. {
  1450. nodeState->markedDirty_ = true;
  1451. nodeState->sceneState_->dirtyNodes_.Insert(id_);
  1452. }
  1453. }
  1454. }
  1455. }
  1456. // Finally check for user var changes
  1457. for (VariantMap::ConstIterator i = vars_.Begin(); i != vars_.End(); ++i)
  1458. {
  1459. VariantMap::ConstIterator j = networkState_->previousVars_.Find(i->first_);
  1460. if (j == networkState_->previousVars_.End() || j->second_ != i->second_)
  1461. {
  1462. networkState_->previousVars_[i->first_] = i->second_;
  1463. // Mark the var dirty in all replication states that are tracking this node
  1464. for (PODVector<ReplicationState*>::Iterator j = networkState_->replicationStates_.Begin();
  1465. j != networkState_->replicationStates_.End(); ++j)
  1466. {
  1467. NodeReplicationState* nodeState = static_cast<NodeReplicationState*>(*j);
  1468. nodeState->dirtyVars_.Insert(i->first_);
  1469. if (!nodeState->markedDirty_)
  1470. {
  1471. nodeState->markedDirty_ = true;
  1472. nodeState->sceneState_->dirtyNodes_.Insert(id_);
  1473. }
  1474. }
  1475. }
  1476. }
  1477. networkUpdate_ = false;
  1478. }
  1479. void Node::CleanupConnection(Connection* connection)
  1480. {
  1481. if (impl_->owner_ == connection)
  1482. impl_->owner_ = 0;
  1483. if (networkState_)
  1484. {
  1485. for (unsigned i = networkState_->replicationStates_.Size() - 1; i < networkState_->replicationStates_.Size(); --i)
  1486. {
  1487. if (networkState_->replicationStates_[i]->connection_ == connection)
  1488. networkState_->replicationStates_.Erase(i);
  1489. }
  1490. }
  1491. }
  1492. void Node::MarkReplicationDirty()
  1493. {
  1494. if (networkState_)
  1495. {
  1496. for (PODVector<ReplicationState*>::Iterator j = networkState_->replicationStates_.Begin();
  1497. j != networkState_->replicationStates_.End(); ++j)
  1498. {
  1499. NodeReplicationState* nodeState = static_cast<NodeReplicationState*>(*j);
  1500. if (!nodeState->markedDirty_)
  1501. {
  1502. nodeState->markedDirty_ = true;
  1503. nodeState->sceneState_->dirtyNodes_.Insert(id_);
  1504. }
  1505. }
  1506. }
  1507. }
  1508. Node* Node::CreateChild(unsigned id, CreateMode mode, bool temporary)
  1509. {
  1510. SharedPtr<Node> newNode(new Node(context_));
  1511. newNode->SetTemporary(temporary);
  1512. // If zero ID specified, or the ID is already taken, let the scene assign
  1513. if (scene_)
  1514. {
  1515. if (!id || scene_->GetNode(id))
  1516. id = scene_->GetFreeNodeID(mode);
  1517. newNode->SetID(id);
  1518. }
  1519. else
  1520. newNode->SetID(id);
  1521. AddChild(newNode);
  1522. return newNode;
  1523. }
  1524. void Node::AddComponent(Component* component, unsigned id, CreateMode mode)
  1525. {
  1526. if (!component)
  1527. return;
  1528. components_.Push(SharedPtr<Component>(component));
  1529. if (component->GetNode())
  1530. URHO3D_LOGWARNING("Component " + component->GetTypeName() + " already belongs to a node!");
  1531. component->SetNode(this);
  1532. // If zero ID specified, or the ID is already taken, let the scene assign
  1533. if (scene_)
  1534. {
  1535. if (!id || scene_->GetComponent(id))
  1536. id = scene_->GetFreeComponentID(mode);
  1537. component->SetID(id);
  1538. scene_->ComponentAdded(component);
  1539. }
  1540. else
  1541. component->SetID(id);
  1542. component->OnMarkedDirty(this);
  1543. // Check attributes of the new component on next network update, and mark node dirty in all replication states
  1544. component->MarkNetworkUpdate();
  1545. MarkNetworkUpdate();
  1546. MarkReplicationDirty();
  1547. // Send change event
  1548. if (scene_)
  1549. {
  1550. using namespace ComponentAdded;
  1551. VariantMap& eventData = GetEventDataMap();
  1552. eventData[P_SCENE] = scene_;
  1553. eventData[P_NODE] = this;
  1554. eventData[P_COMPONENT] = component;
  1555. scene_->SendEvent(E_COMPONENTADDED, eventData);
  1556. }
  1557. }
  1558. unsigned Node::GetNumPersistentChildren() const
  1559. {
  1560. unsigned ret = 0;
  1561. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1562. {
  1563. if (!(*i)->IsTemporary())
  1564. ++ret;
  1565. }
  1566. return ret;
  1567. }
  1568. unsigned Node::GetNumPersistentComponents() const
  1569. {
  1570. unsigned ret = 0;
  1571. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  1572. {
  1573. if (!(*i)->IsTemporary())
  1574. ++ret;
  1575. }
  1576. return ret;
  1577. }
  1578. void Node::SetTransformSilent(const Vector3& position, const Quaternion& rotation, const Vector3& scale)
  1579. {
  1580. position_ = position;
  1581. rotation_ = rotation;
  1582. scale_ = scale;
  1583. }
  1584. void Node::OnAttributeAnimationAdded()
  1585. {
  1586. if (attributeAnimationInfos_.Size() == 1)
  1587. SubscribeToEvent(GetScene(), E_ATTRIBUTEANIMATIONUPDATE, URHO3D_HANDLER(Node, HandleAttributeAnimationUpdate));
  1588. }
  1589. void Node::OnAttributeAnimationRemoved()
  1590. {
  1591. if (attributeAnimationInfos_.Empty())
  1592. UnsubscribeFromEvent(GetScene(), E_ATTRIBUTEANIMATIONUPDATE);
  1593. }
  1594. Animatable* Node::FindAttributeAnimationTarget(const String& name, String& outName)
  1595. {
  1596. Vector<String> names = name.Split('/');
  1597. // Only attribute name
  1598. if (names.Size() == 1)
  1599. {
  1600. outName = name;
  1601. return this;
  1602. }
  1603. else
  1604. {
  1605. // Name must in following format: "#0/#1/@component#0/attribute"
  1606. Node* node = this;
  1607. unsigned i = 0;
  1608. for (; i < names.Size() - 1; ++i)
  1609. {
  1610. if (names[i].Front() != '#')
  1611. break;
  1612. String name = names[i].Substring(1, names[i].Length() - 1);
  1613. char s = name.Front();
  1614. if (s >= '0' && s <= '9')
  1615. {
  1616. unsigned index = ToUInt(name);
  1617. node = node->GetChild(index);
  1618. }
  1619. else
  1620. {
  1621. node = node->GetChild(name, true);
  1622. }
  1623. if (!node)
  1624. {
  1625. URHO3D_LOGERROR("Could not find node by name " + name);
  1626. return 0;
  1627. }
  1628. }
  1629. if (i == names.Size() - 1)
  1630. {
  1631. outName = names.Back();
  1632. return node;
  1633. }
  1634. if (i != names.Size() - 2 || names[i].Front() != '@')
  1635. {
  1636. URHO3D_LOGERROR("Invalid name " + name);
  1637. return 0;
  1638. }
  1639. String componentName = names[i].Substring(1, names[i].Length() - 1);
  1640. Vector<String> componentNames = componentName.Split('#');
  1641. if (componentNames.Size() == 1)
  1642. {
  1643. Component* component = node->GetComponent(StringHash(componentNames.Front()));
  1644. if (!component)
  1645. {
  1646. URHO3D_LOGERROR("Could not find component by name " + name);
  1647. return 0;
  1648. }
  1649. outName = names.Back();
  1650. return component;
  1651. }
  1652. else
  1653. {
  1654. unsigned index = ToUInt(componentNames[1]);
  1655. PODVector<Component*> components;
  1656. node->GetComponents(components, StringHash(componentNames.Front()));
  1657. if (index >= components.Size())
  1658. {
  1659. URHO3D_LOGERROR("Could not find component by name " + name);
  1660. return 0;
  1661. }
  1662. outName = names.Back();
  1663. return components[index];
  1664. }
  1665. }
  1666. }
  1667. void Node::SetEnabled(bool enable, bool recursive, bool storeSelf)
  1668. {
  1669. // The enabled state of the whole scene can not be changed. SetUpdateEnabled() is used instead to start/stop updates.
  1670. if (GetType() == Scene::GetTypeStatic())
  1671. {
  1672. URHO3D_LOGERROR("Can not change enabled state of the Scene");
  1673. return;
  1674. }
  1675. if (storeSelf)
  1676. enabledPrev_ = enable;
  1677. if (enable != enabled_)
  1678. {
  1679. enabled_ = enable;
  1680. MarkNetworkUpdate();
  1681. // Notify listener components of the state change
  1682. for (Vector<WeakPtr<Component> >::Iterator i = listeners_.Begin(); i != listeners_.End();)
  1683. {
  1684. if (*i)
  1685. {
  1686. (*i)->OnNodeSetEnabled(this);
  1687. ++i;
  1688. }
  1689. // If listener has expired, erase from list
  1690. else
  1691. i = listeners_.Erase(i);
  1692. }
  1693. // Send change event
  1694. if (scene_)
  1695. {
  1696. using namespace NodeEnabledChanged;
  1697. VariantMap& eventData = GetEventDataMap();
  1698. eventData[P_SCENE] = scene_;
  1699. eventData[P_NODE] = this;
  1700. scene_->SendEvent(E_NODEENABLEDCHANGED, eventData);
  1701. }
  1702. for (Vector<SharedPtr<Component> >::Iterator i = components_.Begin(); i != components_.End(); ++i)
  1703. {
  1704. (*i)->OnSetEnabled();
  1705. // Send change event for the component
  1706. if (scene_)
  1707. {
  1708. using namespace ComponentEnabledChanged;
  1709. VariantMap& eventData = GetEventDataMap();
  1710. eventData[P_SCENE] = scene_;
  1711. eventData[P_NODE] = this;
  1712. eventData[P_COMPONENT] = (*i);
  1713. scene_->SendEvent(E_COMPONENTENABLEDCHANGED, eventData);
  1714. }
  1715. }
  1716. }
  1717. if (recursive)
  1718. {
  1719. for (Vector<SharedPtr<Node> >::Iterator i = children_.Begin(); i != children_.End(); ++i)
  1720. (*i)->SetEnabled(enable, recursive, storeSelf);
  1721. }
  1722. }
  1723. Component* Node::SafeCreateComponent(const String& typeName, StringHash type, CreateMode mode, unsigned id)
  1724. {
  1725. // Do not attempt to create replicated components to local nodes, as that may lead to component ID overwrite
  1726. // as replicated components are synced over
  1727. if (id_ >= FIRST_LOCAL_ID && mode == REPLICATED)
  1728. mode = LOCAL;
  1729. // First check if factory for type exists
  1730. if (!context_->GetTypeName(type).Empty())
  1731. return CreateComponent(type, mode, id);
  1732. else
  1733. {
  1734. URHO3D_LOGWARNING("Component type " + type.ToString() + " not known, creating UnknownComponent as placeholder");
  1735. // Else create as UnknownComponent
  1736. SharedPtr<UnknownComponent> newComponent(new UnknownComponent(context_));
  1737. if (typeName.Empty() || typeName.StartsWith("Unknown", false))
  1738. newComponent->SetType(type);
  1739. else
  1740. newComponent->SetTypeName(typeName);
  1741. AddComponent(newComponent, id, mode);
  1742. return newComponent;
  1743. }
  1744. }
  1745. void Node::UpdateWorldTransform() const
  1746. {
  1747. Matrix3x4 transform = GetTransform();
  1748. // Assume the root node (scene) has identity transform
  1749. if (parent_ == scene_ || !parent_)
  1750. {
  1751. worldTransform_ = transform;
  1752. worldRotation_ = rotation_;
  1753. }
  1754. else
  1755. {
  1756. worldTransform_ = parent_->GetWorldTransform() * transform;
  1757. worldRotation_ = parent_->GetWorldRotation() * rotation_;
  1758. }
  1759. dirty_ = false;
  1760. }
  1761. void Node::RemoveChild(Vector<SharedPtr<Node> >::Iterator i)
  1762. {
  1763. // Keep a shared pointer to the child about to be removed, to make sure the erase from container completes first. Otherwise
  1764. // it would be possible that other child nodes get removed as part of the node's components' cleanup, causing a re-entrant
  1765. // erase and a crash
  1766. SharedPtr<Node> child(*i);
  1767. // Send change event. Do not send when this node is already being destroyed
  1768. if (Refs() > 0 && scene_)
  1769. {
  1770. using namespace NodeRemoved;
  1771. VariantMap& eventData = GetEventDataMap();
  1772. eventData[P_SCENE] = scene_;
  1773. eventData[P_PARENT] = this;
  1774. eventData[P_NODE] = child;
  1775. scene_->SendEvent(E_NODEREMOVED, eventData);
  1776. }
  1777. child->parent_ = 0;
  1778. child->MarkDirty();
  1779. child->MarkNetworkUpdate();
  1780. if (scene_)
  1781. scene_->NodeRemoved(child);
  1782. children_.Erase(i);
  1783. }
  1784. void Node::GetChildrenRecursive(PODVector<Node*>& dest) const
  1785. {
  1786. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1787. {
  1788. Node* node = *i;
  1789. dest.Push(node);
  1790. if (!node->children_.Empty())
  1791. node->GetChildrenRecursive(dest);
  1792. }
  1793. }
  1794. void Node::GetChildrenWithComponentRecursive(PODVector<Node*>& dest, StringHash type) const
  1795. {
  1796. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1797. {
  1798. Node* node = *i;
  1799. if (node->HasComponent(type))
  1800. dest.Push(node);
  1801. if (!node->children_.Empty())
  1802. node->GetChildrenWithComponentRecursive(dest, type);
  1803. }
  1804. }
  1805. void Node::GetComponentsRecursive(PODVector<Component*>& dest, StringHash type) const
  1806. {
  1807. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  1808. {
  1809. if ((*i)->GetType() == type)
  1810. dest.Push(*i);
  1811. }
  1812. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1813. (*i)->GetComponentsRecursive(dest, type);
  1814. }
  1815. void Node::GetChildrenWithTagRecursive(PODVector<Node*>& dest, const String& tag) const
  1816. {
  1817. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1818. {
  1819. Node* node = *i;
  1820. if (node->HasTag(tag))
  1821. dest.Push(node);
  1822. if (!node->children_.Empty())
  1823. node->GetChildrenWithTagRecursive(dest, tag);
  1824. }
  1825. }
  1826. Node* Node::CloneRecursive(Node* parent, SceneResolver& resolver, CreateMode mode)
  1827. {
  1828. // Create clone node
  1829. Node* cloneNode = parent->CreateChild(0, (mode == REPLICATED && id_ < FIRST_LOCAL_ID) ? REPLICATED : LOCAL);
  1830. resolver.AddNode(id_, cloneNode);
  1831. // Copy attributes
  1832. const Vector<AttributeInfo>* attributes = GetAttributes();
  1833. for (unsigned j = 0; j < attributes->Size(); ++j)
  1834. {
  1835. const AttributeInfo& attr = attributes->At(j);
  1836. // Do not copy network-only attributes, as they may have unintended side effects
  1837. if (attr.mode_ & AM_FILE)
  1838. {
  1839. Variant value;
  1840. OnGetAttribute(attr, value);
  1841. cloneNode->OnSetAttribute(attr, value);
  1842. }
  1843. }
  1844. // Clone components
  1845. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  1846. {
  1847. Component* component = *i;
  1848. if (component->IsTemporary())
  1849. continue;
  1850. Component* cloneComponent = cloneNode->CloneComponent(component,
  1851. (mode == REPLICATED && component->GetID() < FIRST_LOCAL_ID) ? REPLICATED : LOCAL, 0);
  1852. if (cloneComponent)
  1853. resolver.AddComponent(component->GetID(), cloneComponent);
  1854. }
  1855. // Clone child nodes recursively
  1856. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1857. {
  1858. Node* node = *i;
  1859. if (node->IsTemporary())
  1860. continue;
  1861. node->CloneRecursive(cloneNode, resolver, mode);
  1862. }
  1863. {
  1864. using namespace NodeCloned;
  1865. VariantMap& eventData = GetEventDataMap();
  1866. eventData[P_SCENE] = scene_;
  1867. eventData[P_NODE] = this;
  1868. eventData[P_CLONENODE] = cloneNode;
  1869. scene_->SendEvent(E_NODECLONED, eventData);
  1870. }
  1871. return cloneNode;
  1872. }
  1873. void Node::RemoveComponent(Vector<SharedPtr<Component> >::Iterator i)
  1874. {
  1875. // Send node change event. Do not send when already being destroyed
  1876. if (Refs() > 0 && scene_)
  1877. {
  1878. using namespace ComponentRemoved;
  1879. VariantMap& eventData = GetEventDataMap();
  1880. eventData[P_SCENE] = scene_;
  1881. eventData[P_NODE] = this;
  1882. eventData[P_COMPONENT] = (*i).Get();
  1883. scene_->SendEvent(E_COMPONENTREMOVED, eventData);
  1884. }
  1885. RemoveListener(*i);
  1886. if (scene_)
  1887. scene_->ComponentRemoved(*i);
  1888. (*i)->SetNode(0);
  1889. components_.Erase(i);
  1890. }
  1891. void Node::HandleAttributeAnimationUpdate(StringHash eventType, VariantMap& eventData)
  1892. {
  1893. using namespace AttributeAnimationUpdate;
  1894. UpdateAttributeAnimations(eventData[P_TIMESTEP].GetFloat());
  1895. }
  1896. }