Node.cpp 63 KB

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