Node.cpp 64 KB

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