Node.cpp 65 KB

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