Node.cpp 66 KB

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