Node.cpp 52 KB

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