Node.cpp 42 KB

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