Node.cpp 64 KB

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