Node.cpp 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2012 Lasse Öörni
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #include "Precompiled.h"
  24. #include "Component.h"
  25. #include "Context.h"
  26. #include "Log.h"
  27. #include "MemoryBuffer.h"
  28. #include "Profiler.h"
  29. #include "ReplicationState.h"
  30. #include "Scene.h"
  31. #include "SmoothedTransform.h"
  32. #include "XMLFile.h"
  33. #include "DebugNew.h"
  34. // Normalize rotation quaternion after this many incremental updates to prevent distortion
  35. namespace Urho3D
  36. {
  37. static const int NORMALIZE_ROTATION_EVERY = 32;
  38. OBJECTTYPESTATIC(Node);
  39. Node::Node(Context* context) :
  40. Serializable(context),
  41. worldTransform_(Matrix3x4::IDENTITY),
  42. dirty_(false),
  43. networkUpdate_(false),
  44. rotateCount_(0),
  45. parent_(0),
  46. scene_(0),
  47. id_(0),
  48. position_(Vector3::ZERO),
  49. rotation_(Quaternion::IDENTITY),
  50. scale_(Vector3::ONE),
  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. /// \todo When position/rotation updates are received from the network, route to SmoothedTransform if exists
  66. REF_ACCESSOR_ATTRIBUTE(Node, VAR_STRING, "Name", GetName, SetName, String, String(), 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_, VariantMap(), 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>, PODVector<unsigned char>(), AM_NET | AM_LATESTDATA | AM_NOEDIT);
  73. REF_ACCESSOR_ATTRIBUTE(Node, VAR_BUFFER, "Network Parent Node", GetNetParentAttr, SetNetParentAttr, PODVector<unsigned char>, PODVector<unsigned char>(), AM_NET | AM_NOEDIT);
  74. }
  75. void Node::OnSetAttribute(const AttributeInfo& attr, const Variant& src)
  76. {
  77. Serializable::OnSetAttribute(attr, src);
  78. MarkNetworkUpdate();
  79. }
  80. bool Node::Load(Deserializer& source)
  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)
  96. {
  97. // Write node ID
  98. if (!dest.WriteUInt(id_))
  99. return false;
  100. // Write attributes
  101. if (!Serializable::Save(dest))
  102. return false;
  103. // Write components
  104. dest.WriteVLE(components_.Size());
  105. for (unsigned i = 0; i < components_.Size(); ++i)
  106. {
  107. Component* component = components_[i];
  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(children_.Size());
  117. for (unsigned i = 0; i < children_.Size(); ++i)
  118. {
  119. Node* node = children_[i];
  120. if (!node->Save(dest))
  121. return false;
  122. }
  123. return true;
  124. }
  125. bool Node::LoadXML(const XMLElement& source)
  126. {
  127. SceneResolver resolver;
  128. // Read own ID. Will not be applied, only stored for resolving possible references
  129. unsigned nodeID = source.GetInt("id");
  130. resolver.AddNode(nodeID, this);
  131. // Read attributes, components and child nodes
  132. bool success = LoadXML(source, resolver);
  133. if (success)
  134. {
  135. resolver.Resolve();
  136. ApplyAttributes();
  137. }
  138. return success;
  139. }
  140. bool Node::SaveXML(XMLElement& dest)
  141. {
  142. // Write node ID
  143. if (!dest.SetInt("id", id_))
  144. return false;
  145. // Write attributes
  146. if (!Serializable::SaveXML(dest))
  147. return false;
  148. // Write components
  149. for (unsigned i = 0; i < components_.Size(); ++i)
  150. {
  151. Component* component = components_[i];
  152. XMLElement compElem = dest.CreateChild("component");
  153. if (!component->SaveXML(compElem))
  154. return false;
  155. }
  156. // Write child nodes
  157. for (unsigned i = 0; i < children_.Size(); ++i)
  158. {
  159. Node* node = children_[i];
  160. XMLElement childElem = dest.CreateChild("node");
  161. if (!node->SaveXML(childElem))
  162. return false;
  163. }
  164. return true;
  165. }
  166. void Node::ApplyAttributes()
  167. {
  168. for (unsigned i = 0; i < components_.Size(); ++i)
  169. components_[i]->ApplyAttributes();
  170. for (unsigned i = 0; i < children_.Size(); ++i)
  171. children_[i]->ApplyAttributes();
  172. }
  173. void Node::AddReplicationState(NodeReplicationState* state)
  174. {
  175. if (!networkState_)
  176. AllocateNetworkState();
  177. networkState_->replicationStates_.Push(state);
  178. }
  179. bool Node::SaveXML(Serializer& dest)
  180. {
  181. SharedPtr<XMLFile> xml(new XMLFile(context_));
  182. XMLElement rootElem = xml->CreateRoot("node");
  183. if (!SaveXML(rootElem))
  184. return false;
  185. return xml->Save(dest);
  186. }
  187. void Node::SetName(const String& name)
  188. {
  189. name_ = name;
  190. nameHash_ = StringHash(name);
  191. MarkNetworkUpdate();
  192. }
  193. void Node::SetPosition(const Vector3& position)
  194. {
  195. position_ = position;
  196. if (!dirty_)
  197. MarkDirty();
  198. MarkNetworkUpdate();
  199. }
  200. void Node::SetRotation(const Quaternion& rotation)
  201. {
  202. rotation_ = rotation;
  203. rotateCount_ = 0;
  204. if (!dirty_)
  205. MarkDirty();
  206. MarkNetworkUpdate();
  207. }
  208. void Node::SetDirection(const Vector3& direction)
  209. {
  210. SetRotation(Quaternion(Vector3::FORWARD, direction));
  211. }
  212. void Node::SetScale(float scale)
  213. {
  214. scale_ = Vector3(scale, scale, scale).Abs();
  215. if (!dirty_)
  216. MarkDirty();
  217. MarkNetworkUpdate();
  218. }
  219. void Node::SetScale(const Vector3& scale)
  220. {
  221. scale_ = scale.Abs();
  222. if (!dirty_)
  223. MarkDirty();
  224. MarkNetworkUpdate();
  225. }
  226. void Node::SetTransform(const Vector3& position, const Quaternion& rotation)
  227. {
  228. position_ = position;
  229. rotation_ = rotation;
  230. rotateCount_ = 0;
  231. if (!dirty_)
  232. MarkDirty();
  233. MarkNetworkUpdate();
  234. }
  235. void Node::SetTransform(const Vector3& position, const Quaternion& rotation, float scale)
  236. {
  237. position_ = position;
  238. rotation_ = rotation;
  239. rotateCount_ = 0;
  240. scale_ = Vector3(scale, scale, scale);
  241. if (!dirty_)
  242. MarkDirty();
  243. MarkNetworkUpdate();
  244. }
  245. void Node::SetTransform(const Vector3& position, const Quaternion& rotation, const Vector3& scale)
  246. {
  247. position_ = position;
  248. rotation_ = rotation;
  249. rotateCount_ = 0;
  250. scale_ = scale;
  251. if (!dirty_)
  252. MarkDirty();
  253. MarkNetworkUpdate();
  254. }
  255. void Node::SetWorldPosition(const Vector3& position)
  256. {
  257. if (!parent_)
  258. SetPosition(position);
  259. else
  260. SetPosition(parent_->GetWorldTransform().Inverse() * position);
  261. }
  262. void Node::SetWorldRotation(const Quaternion& rotation)
  263. {
  264. if (!parent_)
  265. SetRotation(rotation);
  266. else
  267. SetRotation(parent_->GetWorldRotation().Inverse() * rotation);
  268. }
  269. void Node::SetWorldDirection(const Vector3& direction)
  270. {
  271. Vector3 localDirection;
  272. if (!parent_)
  273. localDirection = direction;
  274. else
  275. localDirection = parent_->GetWorldTransform().Inverse() * direction;
  276. SetRotation(Quaternion(Vector3::FORWARD, localDirection));
  277. }
  278. void Node::SetWorldScale(float scale)
  279. {
  280. if (!parent_)
  281. SetScale(scale);
  282. else
  283. {
  284. Vector3 parentWorldScale = parent_->GetWorldScale();
  285. SetScale(Vector3(scale / parentWorldScale.x_, scale / parentWorldScale.y_, scale / parentWorldScale.z_));
  286. }
  287. }
  288. void Node::SetWorldScale(const Vector3& scale)
  289. {
  290. if (!parent_)
  291. SetScale(scale);
  292. else
  293. SetScale(scale / parent_->GetWorldScale());
  294. }
  295. void Node::SetWorldTransform(const Vector3& position, const Quaternion& rotation)
  296. {
  297. SetWorldPosition(position);
  298. SetWorldRotation(rotation);
  299. }
  300. void Node::SetWorldTransform(const Vector3& position, const Quaternion& rotation, float scale)
  301. {
  302. SetWorldPosition(position);
  303. SetWorldRotation(rotation);
  304. SetWorldScale(scale);
  305. }
  306. void Node::SetWorldTransform(const Vector3& position, const Quaternion& rotation, const Vector3& scale)
  307. {
  308. SetWorldPosition(position);
  309. SetWorldRotation(rotation);
  310. SetWorldScale(scale);
  311. }
  312. void Node::Translate(const Vector3& delta)
  313. {
  314. position_ += delta;
  315. if (!dirty_)
  316. MarkDirty();
  317. MarkNetworkUpdate();
  318. }
  319. void Node::TranslateRelative(const Vector3& delta)
  320. {
  321. position_ += rotation_ * delta;
  322. if (!dirty_)
  323. MarkDirty();
  324. MarkNetworkUpdate();
  325. }
  326. void Node::Rotate(const Quaternion& delta, bool fixedAxis)
  327. {
  328. if (!fixedAxis)
  329. rotation_ = rotation_ * delta;
  330. else
  331. rotation_ = delta * rotation_;
  332. ++rotateCount_;
  333. if (rotateCount_ >= NORMALIZE_ROTATION_EVERY)
  334. {
  335. rotation_.Normalize();
  336. rotateCount_ = 0;
  337. }
  338. if (!dirty_)
  339. MarkDirty();
  340. MarkNetworkUpdate();
  341. }
  342. void Node::Yaw(float angle, bool fixedAxis)
  343. {
  344. Rotate(Quaternion(angle, Vector3::UP), fixedAxis);
  345. }
  346. void Node::Pitch(float angle, bool fixedAxis)
  347. {
  348. Rotate(Quaternion(angle, Vector3::RIGHT), fixedAxis);
  349. }
  350. void Node::Roll(float angle, bool fixedAxis)
  351. {
  352. Rotate(Quaternion(angle, Vector3::FORWARD), fixedAxis);
  353. }
  354. void Node::LookAt(const Vector3& target, const Vector3& upAxis, bool worldSpace)
  355. {
  356. Vector3 targetZ;
  357. if (worldSpace)
  358. targetZ = (target - GetWorldPosition()).Normalized();
  359. else
  360. targetZ = (target - position_).Normalized();
  361. Vector3 targetX = upAxis.CrossProduct(targetZ).Normalized();
  362. Vector3 targetY = targetZ.CrossProduct(targetX).Normalized();
  363. if (!worldSpace || !parent_)
  364. SetRotation(Quaternion(targetX, targetY, targetZ));
  365. else
  366. SetRotation(parent_->GetWorldRotation().Inverse() * Quaternion(targetX, targetY, targetZ));
  367. }
  368. void Node::Scale(float scale)
  369. {
  370. scale_ *= scale;
  371. if (!dirty_)
  372. MarkDirty();
  373. MarkNetworkUpdate();
  374. }
  375. void Node::Scale(const Vector3& scale)
  376. {
  377. scale_ *= scale;
  378. if (!dirty_)
  379. MarkDirty();
  380. MarkNetworkUpdate();
  381. }
  382. void Node::SetOwner(Connection* owner)
  383. {
  384. owner_ = owner;
  385. }
  386. void Node::MarkDirty()
  387. {
  388. dirty_ = true;
  389. // Notify listener components first, then mark child nodes
  390. for (Vector<WeakPtr<Component> >::Iterator i = listeners_.Begin(); i != listeners_.End();)
  391. {
  392. if (*i)
  393. {
  394. (*i)->OnMarkedDirty(this);
  395. ++i;
  396. }
  397. // If listener has expired, erase from list
  398. else
  399. i = listeners_.Erase(i);
  400. }
  401. for (Vector<SharedPtr<Node> >::Iterator i = children_.Begin(); i != children_.End(); ++i)
  402. (*i)->MarkDirty();
  403. }
  404. Node* Node::CreateChild(const String& name, CreateMode mode)
  405. {
  406. Node* newNode = CreateChild(0, mode);
  407. newNode->SetName(name);
  408. return newNode;
  409. }
  410. void Node::AddChild(Node* node)
  411. {
  412. // Check for illegal or redundant parent assignment
  413. if (!node || node == this || node->parent_ == this)
  414. return;
  415. // Check for possible cyclic parent assignment
  416. Node* parent = parent_;
  417. while (parent)
  418. {
  419. if (parent == node)
  420. return;
  421. parent = parent->parent_;
  422. }
  423. // Add first, then remove from old parent, to ensure the node does not get deleted
  424. children_.Push(SharedPtr<Node>(node));
  425. if (node->parent_)
  426. node->parent_->RemoveChild(node);
  427. // Add to the scene if not added yet
  428. if (scene_ && !node->GetScene())
  429. scene_->NodeAdded(node);
  430. node->parent_ = this;
  431. node->MarkDirty();
  432. node->MarkNetworkUpdate();
  433. }
  434. void Node::RemoveChild(Node* node)
  435. {
  436. if (!node)
  437. return;
  438. for (Vector<SharedPtr<Node> >::Iterator i = children_.Begin(); i != children_.End(); ++i)
  439. {
  440. if (*i == node)
  441. {
  442. RemoveChild(i);
  443. return;
  444. }
  445. }
  446. }
  447. void Node::RemoveAllChildren()
  448. {
  449. while (children_.Size())
  450. RemoveChild(children_.End() - 1);
  451. }
  452. Component* Node::CreateComponent(ShortStringHash type, CreateMode mode)
  453. {
  454. return CreateComponent(type, 0, mode);
  455. }
  456. Component* Node::GetOrCreateComponent(ShortStringHash type, CreateMode mode)
  457. {
  458. Component* oldComponent = GetComponent(type);
  459. if (oldComponent)
  460. return oldComponent;
  461. else
  462. return CreateComponent(type, 0, mode);
  463. }
  464. void Node::RemoveComponent(Component* component)
  465. {
  466. for (Vector<SharedPtr<Component> >::Iterator i = components_.Begin(); i != components_.End(); ++i)
  467. {
  468. if (*i == component)
  469. {
  470. WeakPtr<Component> componentWeak(*i);
  471. RemoveListener(*i);
  472. if (scene_)
  473. scene_->ComponentRemoved(*i);
  474. components_.Erase(i);
  475. // If the component is still referenced elsewhere, reset its node pointer now
  476. if (componentWeak)
  477. componentWeak->SetNode(0);
  478. // Mark node dirty in all replication states
  479. MarkReplicationDirty();
  480. return;
  481. }
  482. }
  483. }
  484. void Node::RemoveComponent(ShortStringHash type)
  485. {
  486. for (Vector<SharedPtr<Component> >::Iterator i = components_.Begin(); i != components_.End(); ++i)
  487. {
  488. if ((*i)->GetType() == type)
  489. {
  490. WeakPtr<Component> componentWeak(*i);
  491. RemoveListener(*i);
  492. if (scene_)
  493. scene_->ComponentRemoved(*i);
  494. components_.Erase(i);
  495. // If the component is still referenced elsewhere, reset its node pointer now
  496. if (componentWeak)
  497. componentWeak->SetNode(0);
  498. // Mark node dirty in all replication states
  499. MarkReplicationDirty();
  500. return;
  501. }
  502. }
  503. }
  504. void Node::RemoveAllComponents()
  505. {
  506. if (components_.Empty())
  507. return;
  508. while (components_.Size())
  509. {
  510. Vector<SharedPtr<Component> >::Iterator i = components_.End() - 1;
  511. WeakPtr<Component> componentWeak(*i);
  512. RemoveListener(*i);
  513. if (scene_)
  514. scene_->ComponentRemoved(*i);
  515. components_.Erase(i);
  516. // If the component is still referenced elsewhere, reset its node pointer now
  517. if (componentWeak)
  518. componentWeak->SetNode(0);
  519. }
  520. // Mark node dirty in all replication states
  521. MarkReplicationDirty();
  522. }
  523. Node* Node::Clone(CreateMode mode)
  524. {
  525. // The scene itself can not be cloned
  526. if (this == scene_ || !parent_)
  527. return 0;
  528. PROFILE(CloneNode);
  529. SceneResolver resolver;
  530. Node* clone = CloneRecursive(parent_, resolver, mode);
  531. resolver.Resolve();
  532. clone->ApplyAttributes();
  533. return clone;
  534. }
  535. void Node::Remove()
  536. {
  537. if (parent_)
  538. parent_->RemoveChild(this);
  539. }
  540. void Node::SetParent(Node* parent)
  541. {
  542. if (parent)
  543. {
  544. Vector3 worldPosition;
  545. Quaternion worldRotation;
  546. Vector3 worldScale;
  547. GetWorldTransform().Decompose(worldPosition, worldRotation, worldScale);
  548. parent->AddChild(this);
  549. SetWorldTransform(worldPosition, worldRotation, worldScale);
  550. }
  551. }
  552. void Node::SetVar(ShortStringHash key, const Variant& value)
  553. {
  554. vars_[key] = value;
  555. MarkNetworkUpdate();
  556. }
  557. void Node::AddListener(Component* component)
  558. {
  559. if (!component)
  560. return;
  561. // Check for not adding twice
  562. for (Vector<WeakPtr<Component> >::Iterator i = listeners_.Begin(); i != listeners_.End(); ++i)
  563. {
  564. if (*i == component)
  565. return;
  566. }
  567. listeners_.Push(WeakPtr<Component>(component));
  568. // If the node is currently dirty, notify immediately
  569. if (dirty_)
  570. component->OnMarkedDirty(this);
  571. }
  572. void Node::RemoveListener(Component* component)
  573. {
  574. for (Vector<WeakPtr<Component> >::Iterator i = listeners_.Begin(); i != listeners_.End(); ++i)
  575. {
  576. if (*i == component)
  577. {
  578. listeners_.Erase(i);
  579. return;
  580. }
  581. }
  582. }
  583. Vector3 Node::LocalToWorld(const Vector3& position) const
  584. {
  585. return GetWorldTransform() * position;
  586. }
  587. Vector3 Node::LocalToWorld(const Vector4& vector) const
  588. {
  589. return GetWorldTransform() * vector;
  590. }
  591. Vector3 Node::WorldToLocal(const Vector3& position) const
  592. {
  593. return GetWorldTransform().Inverse() * position;
  594. }
  595. Vector3 Node::WorldToLocal(const Vector4& vector) const
  596. {
  597. return GetWorldTransform().Inverse() * vector;
  598. }
  599. unsigned Node::GetNumChildren(bool recursive) const
  600. {
  601. if (!recursive)
  602. return children_.Size();
  603. else
  604. {
  605. unsigned allChildren = children_.Size();
  606. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  607. allChildren += (*i)->GetNumChildren(true);
  608. return allChildren;
  609. }
  610. }
  611. void Node::GetChildren(PODVector<Node*>& dest, bool recursive) const
  612. {
  613. dest.Clear();
  614. if (!recursive)
  615. {
  616. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  617. dest.Push(*i);
  618. }
  619. else
  620. GetChildrenRecursive(dest);
  621. }
  622. void Node::GetChildrenWithComponent(PODVector<Node*>& dest, ShortStringHash type, bool recursive) const
  623. {
  624. dest.Clear();
  625. if (!recursive)
  626. {
  627. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  628. {
  629. if ((*i)->HasComponent(type))
  630. dest.Push(*i);
  631. }
  632. }
  633. else
  634. GetChildrenWithComponentRecursive(dest, type);
  635. }
  636. Node* Node::GetChild(unsigned index) const
  637. {
  638. return index < children_.Size() ? children_[index].Get() : 0;
  639. }
  640. Node* Node::GetChild(const String& name, bool recursive) const
  641. {
  642. return GetChild(StringHash(name), recursive);
  643. }
  644. Node* Node::GetChild(StringHash nameHash, bool recursive) const
  645. {
  646. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  647. {
  648. if ((*i)->GetNameHash() == nameHash)
  649. return *i;
  650. if (recursive)
  651. {
  652. Node* node = (*i)->GetChild(nameHash, true);
  653. if (node)
  654. return node;
  655. }
  656. }
  657. return 0;
  658. }
  659. unsigned Node::GetNumNetworkComponents() const
  660. {
  661. unsigned num = 0;
  662. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  663. {
  664. if ((*i)->GetID() < FIRST_LOCAL_ID)
  665. ++num;
  666. }
  667. return num;
  668. }
  669. void Node::GetComponents(PODVector<Component*>& dest, ShortStringHash type) const
  670. {
  671. dest.Clear();
  672. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  673. {
  674. if ((*i)->GetType() == type)
  675. dest.Push(*i);
  676. }
  677. }
  678. bool Node::HasComponent(ShortStringHash type) const
  679. {
  680. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  681. {
  682. if ((*i)->GetType() == type)
  683. return true;
  684. }
  685. return false;
  686. }
  687. const Variant& Node::GetVar(ShortStringHash key) const
  688. {
  689. VariantMap::ConstIterator i = vars_.Find(key);
  690. if (i != vars_.End())
  691. return i->second_;
  692. else
  693. return Variant::EMPTY;
  694. }
  695. Component* Node::GetComponent(ShortStringHash type) const
  696. {
  697. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  698. {
  699. if ((*i)->GetType() == type)
  700. return *i;
  701. }
  702. return 0;
  703. }
  704. void Node::SetID(unsigned id)
  705. {
  706. id_ = id;
  707. }
  708. void Node::SetScene(Scene* scene)
  709. {
  710. scene_ = scene;
  711. }
  712. void Node::SetNetPositionAttr(const Vector3& value)
  713. {
  714. SmoothedTransform* transform = GetComponent<SmoothedTransform>();
  715. if (transform)
  716. transform->SetTargetPosition(value);
  717. else
  718. SetPosition(value);
  719. }
  720. void Node::SetNetRotationAttr(const PODVector<unsigned char>& value)
  721. {
  722. MemoryBuffer buf(value);
  723. SmoothedTransform* transform = GetComponent<SmoothedTransform>();
  724. if (transform)
  725. transform->SetTargetRotation(buf.ReadPackedQuaternion());
  726. else
  727. SetRotation(buf.ReadPackedQuaternion());
  728. }
  729. void Node::SetNetParentAttr(const PODVector<unsigned char>& value)
  730. {
  731. Scene* scene = GetScene();
  732. if (!scene)
  733. return;
  734. MemoryBuffer buf(value);
  735. // If nothing in the buffer, parent is the root node
  736. if (buf.IsEof())
  737. {
  738. scene->AddChild(this);
  739. return;
  740. }
  741. unsigned baseNodeID = buf.ReadNetID();
  742. Node* baseNode = scene->GetNode(baseNodeID);
  743. if (!baseNode)
  744. {
  745. LOGWARNING("Failed to find parent node " + String(baseNodeID));
  746. return;
  747. }
  748. // If buffer contains just an ID, the parent is replicated and we are done
  749. if (buf.IsEof())
  750. baseNode->AddChild(this);
  751. else
  752. {
  753. // Else the parent is local and we must find it recursively by name hash
  754. StringHash nameHash = buf.ReadStringHash();
  755. Node* parentNode = baseNode->GetChild(nameHash, true);
  756. if (!parentNode)
  757. LOGWARNING("Failed to find parent node with name hash " + nameHash.ToString());
  758. else
  759. parentNode->AddChild(this);
  760. }
  761. }
  762. const Vector3& Node::GetNetPositionAttr() const
  763. {
  764. return position_;
  765. }
  766. const PODVector<unsigned char>& Node::GetNetRotationAttr() const
  767. {
  768. attrBuffer_.Clear();
  769. attrBuffer_.WritePackedQuaternion(rotation_);
  770. return attrBuffer_.GetBuffer();
  771. }
  772. const PODVector<unsigned char>& Node::GetNetParentAttr() const
  773. {
  774. attrBuffer_.Clear();
  775. Scene* scene = GetScene();
  776. if (scene && parent_ && parent_ != scene)
  777. {
  778. // If parent is replicated, can write the ID directly
  779. unsigned parentID = parent_->GetID();
  780. if (parentID < FIRST_LOCAL_ID)
  781. attrBuffer_.WriteNetID(parentID);
  782. else
  783. {
  784. // Parent is local: traverse hierarchy to find a non-local base node
  785. // This iteration always stops due to the scene (root) being non-local
  786. Node* current = parent_;
  787. while (current->GetID() >= FIRST_LOCAL_ID)
  788. current = current->GetParent();
  789. // Then write the base node ID and the parent's name hash
  790. attrBuffer_.WriteVLE(current->GetID());
  791. attrBuffer_.WriteStringHash(parent_->GetNameHash());
  792. }
  793. }
  794. return attrBuffer_.GetBuffer();
  795. }
  796. bool Node::Load(Deserializer& source, SceneResolver& resolver, bool readChildren, bool rewriteIDs, CreateMode mode)
  797. {
  798. // Remove all children and components first in case this is not a fresh load
  799. RemoveAllChildren();
  800. RemoveAllComponents();
  801. // ID has been read at the parent level
  802. if (!Serializable::Load(source))
  803. return false;
  804. unsigned numComponents = source.ReadVLE();
  805. for (unsigned i = 0; i < numComponents; ++i)
  806. {
  807. VectorBuffer compBuffer(source, source.ReadVLE());
  808. ShortStringHash compType = compBuffer.ReadShortStringHash();
  809. unsigned compID = compBuffer.ReadUInt();
  810. Component* newComponent = CreateComponent(compType, rewriteIDs ? 0 : compID, (mode == REPLICATED &&
  811. compID < FIRST_LOCAL_ID) ? REPLICATED : LOCAL);
  812. if (newComponent)
  813. {
  814. resolver.AddComponent(compID, newComponent);
  815. if (!newComponent->Load(compBuffer))
  816. return false;
  817. }
  818. }
  819. if (!readChildren)
  820. return true;
  821. unsigned numChildren = source.ReadVLE();
  822. for (unsigned i = 0; i < numChildren; ++i)
  823. {
  824. unsigned nodeID = source.ReadUInt();
  825. Node* newNode = CreateChild(rewriteIDs ? 0 : nodeID, (mode == REPLICATED && nodeID < FIRST_LOCAL_ID) ? REPLICATED :
  826. LOCAL);
  827. resolver.AddNode(nodeID, newNode);
  828. if (!newNode->Load(source, resolver, readChildren, rewriteIDs, mode))
  829. return false;
  830. }
  831. return true;
  832. }
  833. bool Node::LoadXML(const XMLElement& source, SceneResolver& resolver, bool readChildren, bool rewriteIDs, CreateMode mode)
  834. {
  835. // Remove all children and components first in case this is not a fresh load
  836. RemoveAllChildren();
  837. RemoveAllComponents();
  838. if (!Serializable::LoadXML(source))
  839. return false;
  840. XMLElement compElem = source.GetChild("component");
  841. while (compElem)
  842. {
  843. String typeName = compElem.GetAttribute("type");
  844. unsigned compID = compElem.GetInt("id");
  845. Component* newComponent = CreateComponent(ShortStringHash(typeName), rewriteIDs ? 0 : compID, (mode == REPLICATED &&
  846. compID < FIRST_LOCAL_ID) ? REPLICATED : LOCAL);
  847. if (newComponent)
  848. {
  849. resolver.AddComponent(compID, newComponent);
  850. if (!newComponent->LoadXML(compElem))
  851. return false;
  852. }
  853. compElem = compElem.GetNext("component");
  854. }
  855. if (!readChildren)
  856. return true;
  857. XMLElement childElem = source.GetChild("node");
  858. while (childElem)
  859. {
  860. unsigned nodeID = childElem.GetInt("id");
  861. Node* newNode = CreateChild(rewriteIDs ? 0 : nodeID, (mode == REPLICATED && nodeID < FIRST_LOCAL_ID) ? REPLICATED :
  862. LOCAL);
  863. resolver.AddNode(nodeID, newNode);
  864. if (!newNode->LoadXML(childElem, resolver, readChildren, rewriteIDs, mode))
  865. return false;
  866. childElem = childElem.GetNext("node");
  867. }
  868. return true;
  869. }
  870. void Node::PrepareNetworkUpdate()
  871. {
  872. // Update dependency nodes list first
  873. dependencyNodes_.Clear();
  874. // Add the parent node, but if it is local, traverse to the first non-local node
  875. if (parent_ && parent_ != scene_)
  876. {
  877. Node* current = parent_;
  878. while (current->id_ >= FIRST_LOCAL_ID)
  879. current = current->parent_;
  880. if (current && current != scene_)
  881. dependencyNodes_.Push(current);
  882. }
  883. // Let the components add their dependencies
  884. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  885. {
  886. Component* component = *i;
  887. if (component->GetID() < FIRST_LOCAL_ID)
  888. component->GetDependencyNodes(dependencyNodes_);
  889. }
  890. // Then check for node attribute changes
  891. if (!networkState_)
  892. AllocateNetworkState();
  893. const Vector<AttributeInfo>* attributes = networkState_->attributes_;
  894. unsigned numAttributes = attributes->Size();
  895. if (networkState_->currentValues_.Size() != numAttributes)
  896. {
  897. networkState_->currentValues_.Resize(numAttributes);
  898. networkState_->previousValues_.Resize(numAttributes);
  899. // Copy the default attribute values to the previous state as a starting point
  900. for (unsigned i = 0; i < numAttributes; ++i)
  901. networkState_->previousValues_[i] = attributes->At(i).defaultValue_;
  902. }
  903. // Check for attribute changes
  904. for (unsigned i = 0; i < numAttributes; ++i)
  905. {
  906. const AttributeInfo& attr = attributes->At(i);
  907. OnGetAttribute(attr, networkState_->currentValues_[i]);
  908. if (networkState_->currentValues_[i] != networkState_->previousValues_[i])
  909. {
  910. networkState_->previousValues_[i] = networkState_->currentValues_[i];
  911. // Mark the attribute dirty in all replication states that are tracking this node
  912. for (PODVector<ReplicationState*>::Iterator j = networkState_->replicationStates_.Begin(); j !=
  913. networkState_->replicationStates_.End();
  914. ++j)
  915. {
  916. NodeReplicationState* nodeState = static_cast<NodeReplicationState*>(*j);
  917. nodeState->dirtyAttributes_.Set(i);
  918. // Add node to the dirty set if not added yet
  919. if (!nodeState->markedDirty_)
  920. {
  921. nodeState->markedDirty_ = true;
  922. nodeState->sceneState_->dirtyNodes_.Insert(id_);
  923. }
  924. }
  925. }
  926. }
  927. // Finally check for user var changes
  928. for (VariantMap::ConstIterator i = vars_.Begin(); i != vars_.End(); ++i)
  929. {
  930. VariantMap::ConstIterator j = networkState_->previousVars_.Find(i->first_);
  931. if (j == networkState_->previousVars_.End() || j->second_ != i->second_)
  932. {
  933. networkState_->previousVars_[i->first_] = i->second_;
  934. // Mark the var dirty in all replication states that are tracking this node
  935. for (PODVector<ReplicationState*>::Iterator j = networkState_->replicationStates_.Begin(); j !=
  936. networkState_->replicationStates_.End(); ++j)
  937. {
  938. NodeReplicationState* nodeState = static_cast<NodeReplicationState*>(*j);
  939. nodeState->dirtyVars_.Insert(i->first_);
  940. if (!nodeState->markedDirty_)
  941. {
  942. nodeState->markedDirty_ = true;
  943. nodeState->sceneState_->dirtyNodes_.Insert(id_);
  944. }
  945. }
  946. }
  947. }
  948. networkUpdate_ = false;
  949. }
  950. void Node::CleanupConnection(Connection* connection)
  951. {
  952. if (owner_ == connection)
  953. owner_ = 0;
  954. if (networkState_)
  955. {
  956. for (unsigned i = networkState_->replicationStates_.Size() - 1; i < networkState_->replicationStates_.Size(); --i)
  957. {
  958. if (networkState_->replicationStates_[i]->connection_ == connection)
  959. networkState_->replicationStates_.Erase(i);
  960. }
  961. }
  962. }
  963. void Node::MarkNetworkUpdate()
  964. {
  965. if (id_ < FIRST_LOCAL_ID && !networkUpdate_ && scene_)
  966. {
  967. scene_->MarkNetworkUpdate(this);
  968. networkUpdate_ = true;
  969. }
  970. }
  971. void Node::MarkReplicationDirty()
  972. {
  973. if (networkState_)
  974. {
  975. for (PODVector<ReplicationState*>::Iterator j = networkState_->replicationStates_.Begin(); j !=
  976. networkState_->replicationStates_.End(); ++j)
  977. {
  978. NodeReplicationState* nodeState = static_cast<NodeReplicationState*>(*j);
  979. if (!nodeState->markedDirty_)
  980. {
  981. nodeState->markedDirty_ = true;
  982. nodeState->sceneState_->dirtyNodes_.Insert(id_);
  983. }
  984. }
  985. }
  986. }
  987. Component* Node::CreateComponent(ShortStringHash type, unsigned id, CreateMode mode)
  988. {
  989. // Check that creation succeeds and that the object in fact is a component
  990. SharedPtr<Component> newComponent = DynamicCast<Component>(context_->CreateObject(type));
  991. if (!newComponent)
  992. {
  993. LOGERROR("Could not create unknown component type " + type.ToString());
  994. return 0;
  995. }
  996. AddComponent(newComponent, id, mode);
  997. return newComponent;
  998. }
  999. Node* Node::CreateChild(unsigned id, CreateMode mode)
  1000. {
  1001. SharedPtr<Node> newNode(new Node(context_));
  1002. // If zero ID specified, or the ID is already taken, let the scene assign
  1003. if (scene_)
  1004. {
  1005. if (!id || scene_->GetNode(id))
  1006. id = scene_->GetFreeNodeID(mode);
  1007. newNode->SetID(id);
  1008. }
  1009. else
  1010. newNode->SetID(id);
  1011. AddChild(newNode);
  1012. return newNode;
  1013. }
  1014. void Node::AddComponent(Component* component, unsigned id, CreateMode mode)
  1015. {
  1016. if (!component)
  1017. return;
  1018. components_.Push(SharedPtr<Component>(component));
  1019. // If zero ID specified, or the ID is already taken, let the scene assign
  1020. if (scene_)
  1021. {
  1022. if (!id || scene_->GetComponent(id))
  1023. id = scene_->GetFreeComponentID(mode);
  1024. component->SetID(id);
  1025. scene_->ComponentAdded(component);
  1026. }
  1027. else
  1028. component->SetID(id);
  1029. component->SetNode(this);
  1030. component->OnMarkedDirty(this);
  1031. // Check attributes of the new component on next network update, and mark node dirty in all replication states
  1032. component->MarkNetworkUpdate();
  1033. MarkNetworkUpdate();
  1034. MarkReplicationDirty();
  1035. }
  1036. void Node::UpdateWorldTransform() const
  1037. {
  1038. if (parent_)
  1039. {
  1040. if (parent_->dirty_)
  1041. parent_->UpdateWorldTransform();
  1042. worldTransform_ = parent_->worldTransform_ * Matrix3x4(position_, rotation_, scale_);
  1043. }
  1044. else
  1045. worldTransform_ = Matrix3x4(position_, rotation_, scale_);
  1046. dirty_ = false;
  1047. }
  1048. void Node::RemoveChild(Vector<SharedPtr<Node> >::Iterator i)
  1049. {
  1050. (*i)->parent_ = 0;
  1051. (*i)->MarkDirty();
  1052. (*i)->MarkNetworkUpdate();
  1053. children_.Erase(i);
  1054. }
  1055. void Node::GetChildrenRecursive(PODVector<Node*>& dest) const
  1056. {
  1057. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1058. {
  1059. Node* node = *i;
  1060. dest.Push(node);
  1061. if (!node->children_.Empty())
  1062. node->GetChildrenRecursive(dest);
  1063. }
  1064. }
  1065. void Node::GetChildrenWithComponentRecursive(PODVector<Node*>& dest, ShortStringHash type) const
  1066. {
  1067. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1068. {
  1069. Node* node = *i;
  1070. if (node->HasComponent(type))
  1071. dest.Push(node);
  1072. if (!node->children_.Empty())
  1073. node->GetChildrenRecursive(dest);
  1074. }
  1075. }
  1076. Node* Node::CloneRecursive(Node* parent, SceneResolver& resolver, CreateMode mode)
  1077. {
  1078. // Create clone node
  1079. Node* cloneNode = parent->CreateChild(0, (mode == REPLICATED && id_ < FIRST_LOCAL_ID) ? REPLICATED : LOCAL);
  1080. resolver.AddNode(id_, cloneNode);
  1081. // Copy attributes
  1082. unsigned numAttributes = GetNumAttributes();
  1083. for (unsigned j = 0; j < numAttributes; ++j)
  1084. cloneNode->SetAttribute(j, GetAttribute(j));
  1085. // Clone components
  1086. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  1087. {
  1088. Component* component = *i;
  1089. Component* cloneComponent = cloneNode->CreateComponent(component->GetType(), (mode == REPLICATED && component->GetID() <
  1090. FIRST_LOCAL_ID) ? REPLICATED : LOCAL);
  1091. if (!cloneComponent)
  1092. {
  1093. LOGERROR("Could not clone component " + component->GetTypeName());
  1094. continue;
  1095. }
  1096. resolver.AddComponent(component->GetID(), cloneComponent);
  1097. numAttributes = component->GetNumAttributes();
  1098. for (unsigned j = 0; j < numAttributes; ++j)
  1099. cloneComponent->SetAttribute(j, component->GetAttribute(j));
  1100. }
  1101. // Clone child nodes recursively
  1102. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1103. {
  1104. Node* node = *i;
  1105. node->CloneRecursive(cloneNode, resolver, mode);
  1106. }
  1107. return cloneNode;
  1108. }
  1109. }