Node.cpp 47 KB

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