Node.cpp 46 KB

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