Node.cpp 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320
  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. {
  528. LOGERROR("Can not clone node without a parent");
  529. return 0;
  530. }
  531. PROFILE(CloneNode);
  532. SceneResolver resolver;
  533. Node* clone = CloneRecursive(parent_, resolver, mode);
  534. resolver.Resolve();
  535. clone->ApplyAttributes();
  536. return clone;
  537. }
  538. void Node::Remove()
  539. {
  540. if (parent_)
  541. parent_->RemoveChild(this);
  542. }
  543. void Node::SetParent(Node* parent)
  544. {
  545. if (parent)
  546. {
  547. Vector3 worldPosition;
  548. Quaternion worldRotation;
  549. Vector3 worldScale;
  550. GetWorldTransform().Decompose(worldPosition, worldRotation, worldScale);
  551. parent->AddChild(this);
  552. SetWorldTransform(worldPosition, worldRotation, worldScale);
  553. }
  554. }
  555. void Node::SetVar(ShortStringHash key, const Variant& value)
  556. {
  557. vars_[key] = value;
  558. MarkNetworkUpdate();
  559. }
  560. void Node::AddListener(Component* component)
  561. {
  562. if (!component)
  563. return;
  564. // Check for not adding twice
  565. for (Vector<WeakPtr<Component> >::Iterator i = listeners_.Begin(); i != listeners_.End(); ++i)
  566. {
  567. if (*i == component)
  568. return;
  569. }
  570. listeners_.Push(WeakPtr<Component>(component));
  571. // If the node is currently dirty, notify immediately
  572. if (dirty_)
  573. component->OnMarkedDirty(this);
  574. }
  575. void Node::RemoveListener(Component* component)
  576. {
  577. for (Vector<WeakPtr<Component> >::Iterator i = listeners_.Begin(); i != listeners_.End(); ++i)
  578. {
  579. if (*i == component)
  580. {
  581. listeners_.Erase(i);
  582. return;
  583. }
  584. }
  585. }
  586. Vector3 Node::LocalToWorld(const Vector3& position) const
  587. {
  588. return GetWorldTransform() * position;
  589. }
  590. Vector3 Node::LocalToWorld(const Vector4& vector) const
  591. {
  592. return GetWorldTransform() * vector;
  593. }
  594. Vector3 Node::WorldToLocal(const Vector3& position) const
  595. {
  596. return GetWorldTransform().Inverse() * position;
  597. }
  598. Vector3 Node::WorldToLocal(const Vector4& vector) const
  599. {
  600. return GetWorldTransform().Inverse() * vector;
  601. }
  602. unsigned Node::GetNumChildren(bool recursive) const
  603. {
  604. if (!recursive)
  605. return children_.Size();
  606. else
  607. {
  608. unsigned allChildren = children_.Size();
  609. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  610. allChildren += (*i)->GetNumChildren(true);
  611. return allChildren;
  612. }
  613. }
  614. void Node::GetChildren(PODVector<Node*>& dest, bool recursive) const
  615. {
  616. dest.Clear();
  617. if (!recursive)
  618. {
  619. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  620. dest.Push(*i);
  621. }
  622. else
  623. GetChildrenRecursive(dest);
  624. }
  625. void Node::GetChildrenWithComponent(PODVector<Node*>& dest, ShortStringHash type, bool recursive) const
  626. {
  627. dest.Clear();
  628. if (!recursive)
  629. {
  630. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  631. {
  632. if ((*i)->HasComponent(type))
  633. dest.Push(*i);
  634. }
  635. }
  636. else
  637. GetChildrenWithComponentRecursive(dest, type);
  638. }
  639. Node* Node::GetChild(unsigned index) const
  640. {
  641. return index < children_.Size() ? children_[index].Get() : 0;
  642. }
  643. Node* Node::GetChild(const String& name, bool recursive) const
  644. {
  645. return GetChild(StringHash(name), recursive);
  646. }
  647. Node* Node::GetChild(StringHash nameHash, bool recursive) const
  648. {
  649. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  650. {
  651. if ((*i)->GetNameHash() == nameHash)
  652. return *i;
  653. if (recursive)
  654. {
  655. Node* node = (*i)->GetChild(nameHash, true);
  656. if (node)
  657. return node;
  658. }
  659. }
  660. return 0;
  661. }
  662. unsigned Node::GetNumNetworkComponents() const
  663. {
  664. unsigned num = 0;
  665. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  666. {
  667. if ((*i)->GetID() < FIRST_LOCAL_ID)
  668. ++num;
  669. }
  670. return num;
  671. }
  672. void Node::GetComponents(PODVector<Component*>& dest, ShortStringHash type) const
  673. {
  674. dest.Clear();
  675. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  676. {
  677. if ((*i)->GetType() == type)
  678. dest.Push(*i);
  679. }
  680. }
  681. bool Node::HasComponent(ShortStringHash type) const
  682. {
  683. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  684. {
  685. if ((*i)->GetType() == type)
  686. return true;
  687. }
  688. return false;
  689. }
  690. const Variant& Node::GetVar(ShortStringHash key) const
  691. {
  692. VariantMap::ConstIterator i = vars_.Find(key);
  693. if (i != vars_.End())
  694. return i->second_;
  695. else
  696. return Variant::EMPTY;
  697. }
  698. Component* Node::GetComponent(ShortStringHash type) const
  699. {
  700. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  701. {
  702. if ((*i)->GetType() == type)
  703. return *i;
  704. }
  705. return 0;
  706. }
  707. void Node::SetID(unsigned id)
  708. {
  709. id_ = id;
  710. }
  711. void Node::SetScene(Scene* scene)
  712. {
  713. scene_ = scene;
  714. }
  715. void Node::SetNetPositionAttr(const Vector3& value)
  716. {
  717. SmoothedTransform* transform = GetComponent<SmoothedTransform>();
  718. if (transform)
  719. transform->SetTargetPosition(value);
  720. else
  721. SetPosition(value);
  722. }
  723. void Node::SetNetRotationAttr(const PODVector<unsigned char>& value)
  724. {
  725. MemoryBuffer buf(value);
  726. SmoothedTransform* transform = GetComponent<SmoothedTransform>();
  727. if (transform)
  728. transform->SetTargetRotation(buf.ReadPackedQuaternion());
  729. else
  730. SetRotation(buf.ReadPackedQuaternion());
  731. }
  732. void Node::SetNetParentAttr(const PODVector<unsigned char>& value)
  733. {
  734. Scene* scene = GetScene();
  735. if (!scene)
  736. return;
  737. MemoryBuffer buf(value);
  738. // If nothing in the buffer, parent is the root node
  739. if (buf.IsEof())
  740. {
  741. scene->AddChild(this);
  742. return;
  743. }
  744. unsigned baseNodeID = buf.ReadNetID();
  745. Node* baseNode = scene->GetNode(baseNodeID);
  746. if (!baseNode)
  747. {
  748. LOGWARNING("Failed to find parent node " + String(baseNodeID));
  749. return;
  750. }
  751. // If buffer contains just an ID, the parent is replicated and we are done
  752. if (buf.IsEof())
  753. baseNode->AddChild(this);
  754. else
  755. {
  756. // Else the parent is local and we must find it recursively by name hash
  757. StringHash nameHash = buf.ReadStringHash();
  758. Node* parentNode = baseNode->GetChild(nameHash, true);
  759. if (!parentNode)
  760. LOGWARNING("Failed to find parent node with name hash " + nameHash.ToString());
  761. else
  762. parentNode->AddChild(this);
  763. }
  764. }
  765. const Vector3& Node::GetNetPositionAttr() const
  766. {
  767. return position_;
  768. }
  769. const PODVector<unsigned char>& Node::GetNetRotationAttr() const
  770. {
  771. attrBuffer_.Clear();
  772. attrBuffer_.WritePackedQuaternion(rotation_);
  773. return attrBuffer_.GetBuffer();
  774. }
  775. const PODVector<unsigned char>& Node::GetNetParentAttr() const
  776. {
  777. attrBuffer_.Clear();
  778. Scene* scene = GetScene();
  779. if (scene && parent_ && parent_ != scene)
  780. {
  781. // If parent is replicated, can write the ID directly
  782. unsigned parentID = parent_->GetID();
  783. if (parentID < FIRST_LOCAL_ID)
  784. attrBuffer_.WriteNetID(parentID);
  785. else
  786. {
  787. // Parent is local: traverse hierarchy to find a non-local base node
  788. // This iteration always stops due to the scene (root) being non-local
  789. Node* current = parent_;
  790. while (current->GetID() >= FIRST_LOCAL_ID)
  791. current = current->GetParent();
  792. // Then write the base node ID and the parent's name hash
  793. attrBuffer_.WriteVLE(current->GetID());
  794. attrBuffer_.WriteStringHash(parent_->GetNameHash());
  795. }
  796. }
  797. return attrBuffer_.GetBuffer();
  798. }
  799. bool Node::Load(Deserializer& source, SceneResolver& resolver, bool readChildren, bool rewriteIDs, CreateMode mode)
  800. {
  801. // Remove all children and components first in case this is not a fresh load
  802. RemoveAllChildren();
  803. RemoveAllComponents();
  804. // ID has been read at the parent level
  805. if (!Serializable::Load(source))
  806. return false;
  807. unsigned numComponents = source.ReadVLE();
  808. for (unsigned i = 0; i < numComponents; ++i)
  809. {
  810. VectorBuffer compBuffer(source, source.ReadVLE());
  811. ShortStringHash compType = compBuffer.ReadShortStringHash();
  812. unsigned compID = compBuffer.ReadUInt();
  813. Component* newComponent = CreateComponent(compType, rewriteIDs ? 0 : compID, (mode == REPLICATED &&
  814. compID < FIRST_LOCAL_ID) ? REPLICATED : LOCAL);
  815. if (newComponent)
  816. {
  817. resolver.AddComponent(compID, newComponent);
  818. if (!newComponent->Load(compBuffer))
  819. return false;
  820. }
  821. }
  822. if (!readChildren)
  823. return true;
  824. unsigned numChildren = source.ReadVLE();
  825. for (unsigned i = 0; i < numChildren; ++i)
  826. {
  827. unsigned nodeID = source.ReadUInt();
  828. Node* newNode = CreateChild(rewriteIDs ? 0 : nodeID, (mode == REPLICATED && nodeID < FIRST_LOCAL_ID) ? REPLICATED :
  829. LOCAL);
  830. resolver.AddNode(nodeID, newNode);
  831. if (!newNode->Load(source, resolver, readChildren, rewriteIDs, mode))
  832. return false;
  833. }
  834. return true;
  835. }
  836. bool Node::LoadXML(const XMLElement& source, SceneResolver& resolver, bool readChildren, bool rewriteIDs, CreateMode mode)
  837. {
  838. // Remove all children and components first in case this is not a fresh load
  839. RemoveAllChildren();
  840. RemoveAllComponents();
  841. if (!Serializable::LoadXML(source))
  842. return false;
  843. XMLElement compElem = source.GetChild("component");
  844. while (compElem)
  845. {
  846. String typeName = compElem.GetAttribute("type");
  847. unsigned compID = compElem.GetInt("id");
  848. Component* newComponent = CreateComponent(ShortStringHash(typeName), rewriteIDs ? 0 : compID, (mode == REPLICATED &&
  849. compID < FIRST_LOCAL_ID) ? REPLICATED : LOCAL);
  850. if (newComponent)
  851. {
  852. resolver.AddComponent(compID, newComponent);
  853. if (!newComponent->LoadXML(compElem))
  854. return false;
  855. }
  856. compElem = compElem.GetNext("component");
  857. }
  858. if (!readChildren)
  859. return true;
  860. XMLElement childElem = source.GetChild("node");
  861. while (childElem)
  862. {
  863. unsigned nodeID = childElem.GetInt("id");
  864. Node* newNode = CreateChild(rewriteIDs ? 0 : nodeID, (mode == REPLICATED && nodeID < FIRST_LOCAL_ID) ? REPLICATED :
  865. LOCAL);
  866. resolver.AddNode(nodeID, newNode);
  867. if (!newNode->LoadXML(childElem, resolver, readChildren, rewriteIDs, mode))
  868. return false;
  869. childElem = childElem.GetNext("node");
  870. }
  871. return true;
  872. }
  873. void Node::PrepareNetworkUpdate()
  874. {
  875. // Update dependency nodes list first
  876. dependencyNodes_.Clear();
  877. // Add the parent node, but if it is local, traverse to the first non-local node
  878. if (parent_ && parent_ != scene_)
  879. {
  880. Node* current = parent_;
  881. while (current->id_ >= FIRST_LOCAL_ID)
  882. current = current->parent_;
  883. if (current && current != scene_)
  884. dependencyNodes_.Push(current);
  885. }
  886. // Let the components add their dependencies
  887. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  888. {
  889. Component* component = *i;
  890. if (component->GetID() < FIRST_LOCAL_ID)
  891. component->GetDependencyNodes(dependencyNodes_);
  892. }
  893. // Then check for node attribute changes
  894. if (!networkState_)
  895. AllocateNetworkState();
  896. const Vector<AttributeInfo>* attributes = networkState_->attributes_;
  897. unsigned numAttributes = attributes->Size();
  898. if (networkState_->currentValues_.Size() != numAttributes)
  899. {
  900. networkState_->currentValues_.Resize(numAttributes);
  901. networkState_->previousValues_.Resize(numAttributes);
  902. // Copy the default attribute values to the previous state as a starting point
  903. for (unsigned i = 0; i < numAttributes; ++i)
  904. networkState_->previousValues_[i] = attributes->At(i).defaultValue_;
  905. }
  906. // Check for attribute changes
  907. for (unsigned i = 0; i < numAttributes; ++i)
  908. {
  909. const AttributeInfo& attr = attributes->At(i);
  910. OnGetAttribute(attr, networkState_->currentValues_[i]);
  911. if (networkState_->currentValues_[i] != networkState_->previousValues_[i])
  912. {
  913. networkState_->previousValues_[i] = networkState_->currentValues_[i];
  914. // Mark the attribute dirty in all replication states that are tracking this node
  915. for (PODVector<ReplicationState*>::Iterator j = networkState_->replicationStates_.Begin(); j !=
  916. networkState_->replicationStates_.End();
  917. ++j)
  918. {
  919. NodeReplicationState* nodeState = static_cast<NodeReplicationState*>(*j);
  920. nodeState->dirtyAttributes_.Set(i);
  921. // Add node to the dirty set if not added yet
  922. if (!nodeState->markedDirty_)
  923. {
  924. nodeState->markedDirty_ = true;
  925. nodeState->sceneState_->dirtyNodes_.Insert(id_);
  926. }
  927. }
  928. }
  929. }
  930. // Finally check for user var changes
  931. for (VariantMap::ConstIterator i = vars_.Begin(); i != vars_.End(); ++i)
  932. {
  933. VariantMap::ConstIterator j = networkState_->previousVars_.Find(i->first_);
  934. if (j == networkState_->previousVars_.End() || j->second_ != i->second_)
  935. {
  936. networkState_->previousVars_[i->first_] = i->second_;
  937. // Mark the var dirty in all replication states that are tracking this node
  938. for (PODVector<ReplicationState*>::Iterator j = networkState_->replicationStates_.Begin(); j !=
  939. networkState_->replicationStates_.End(); ++j)
  940. {
  941. NodeReplicationState* nodeState = static_cast<NodeReplicationState*>(*j);
  942. nodeState->dirtyVars_.Insert(i->first_);
  943. if (!nodeState->markedDirty_)
  944. {
  945. nodeState->markedDirty_ = true;
  946. nodeState->sceneState_->dirtyNodes_.Insert(id_);
  947. }
  948. }
  949. }
  950. }
  951. networkUpdate_ = false;
  952. }
  953. void Node::CleanupConnection(Connection* connection)
  954. {
  955. if (owner_ == connection)
  956. owner_ = 0;
  957. if (networkState_)
  958. {
  959. for (unsigned i = networkState_->replicationStates_.Size() - 1; i < networkState_->replicationStates_.Size(); --i)
  960. {
  961. if (networkState_->replicationStates_[i]->connection_ == connection)
  962. networkState_->replicationStates_.Erase(i);
  963. }
  964. }
  965. }
  966. void Node::MarkNetworkUpdate()
  967. {
  968. if (id_ < FIRST_LOCAL_ID && !networkUpdate_ && scene_)
  969. {
  970. scene_->MarkNetworkUpdate(this);
  971. networkUpdate_ = true;
  972. }
  973. }
  974. void Node::MarkReplicationDirty()
  975. {
  976. if (networkState_)
  977. {
  978. for (PODVector<ReplicationState*>::Iterator j = networkState_->replicationStates_.Begin(); j !=
  979. networkState_->replicationStates_.End(); ++j)
  980. {
  981. NodeReplicationState* nodeState = static_cast<NodeReplicationState*>(*j);
  982. if (!nodeState->markedDirty_)
  983. {
  984. nodeState->markedDirty_ = true;
  985. nodeState->sceneState_->dirtyNodes_.Insert(id_);
  986. }
  987. }
  988. }
  989. }
  990. Component* Node::CreateComponent(ShortStringHash type, unsigned id, CreateMode mode)
  991. {
  992. // Check that creation succeeds and that the object in fact is a component
  993. SharedPtr<Component> newComponent = DynamicCast<Component>(context_->CreateObject(type));
  994. if (!newComponent)
  995. {
  996. LOGERROR("Could not create unknown component type " + type.ToString());
  997. return 0;
  998. }
  999. AddComponent(newComponent, id, mode);
  1000. return newComponent;
  1001. }
  1002. Node* Node::CreateChild(unsigned id, CreateMode mode)
  1003. {
  1004. SharedPtr<Node> newNode(new Node(context_));
  1005. // If zero ID specified, or the ID is already taken, let the scene assign
  1006. if (scene_)
  1007. {
  1008. if (!id || scene_->GetNode(id))
  1009. id = scene_->GetFreeNodeID(mode);
  1010. newNode->SetID(id);
  1011. }
  1012. else
  1013. newNode->SetID(id);
  1014. AddChild(newNode);
  1015. return newNode;
  1016. }
  1017. void Node::AddComponent(Component* component, unsigned id, CreateMode mode)
  1018. {
  1019. if (!component)
  1020. return;
  1021. components_.Push(SharedPtr<Component>(component));
  1022. // If zero ID specified, or the ID is already taken, let the scene assign
  1023. if (scene_)
  1024. {
  1025. if (!id || scene_->GetComponent(id))
  1026. id = scene_->GetFreeComponentID(mode);
  1027. component->SetID(id);
  1028. scene_->ComponentAdded(component);
  1029. }
  1030. else
  1031. component->SetID(id);
  1032. component->SetNode(this);
  1033. component->OnMarkedDirty(this);
  1034. // Check attributes of the new component on next network update, and mark node dirty in all replication states
  1035. component->MarkNetworkUpdate();
  1036. MarkNetworkUpdate();
  1037. MarkReplicationDirty();
  1038. }
  1039. void Node::UpdateWorldTransform() const
  1040. {
  1041. if (parent_)
  1042. {
  1043. if (parent_->dirty_)
  1044. parent_->UpdateWorldTransform();
  1045. worldTransform_ = parent_->worldTransform_ * Matrix3x4(position_, rotation_, scale_);
  1046. }
  1047. else
  1048. worldTransform_ = Matrix3x4(position_, rotation_, scale_);
  1049. dirty_ = false;
  1050. }
  1051. void Node::RemoveChild(Vector<SharedPtr<Node> >::Iterator i)
  1052. {
  1053. (*i)->parent_ = 0;
  1054. (*i)->MarkDirty();
  1055. (*i)->MarkNetworkUpdate();
  1056. children_.Erase(i);
  1057. }
  1058. void Node::GetChildrenRecursive(PODVector<Node*>& dest) const
  1059. {
  1060. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1061. {
  1062. Node* node = *i;
  1063. dest.Push(node);
  1064. if (!node->children_.Empty())
  1065. node->GetChildrenRecursive(dest);
  1066. }
  1067. }
  1068. void Node::GetChildrenWithComponentRecursive(PODVector<Node*>& dest, ShortStringHash type) const
  1069. {
  1070. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1071. {
  1072. Node* node = *i;
  1073. if (node->HasComponent(type))
  1074. dest.Push(node);
  1075. if (!node->children_.Empty())
  1076. node->GetChildrenRecursive(dest);
  1077. }
  1078. }
  1079. Node* Node::CloneRecursive(Node* parent, SceneResolver& resolver, CreateMode mode)
  1080. {
  1081. // Create clone node
  1082. Node* cloneNode = parent->CreateChild(0, (mode == REPLICATED && id_ < FIRST_LOCAL_ID) ? REPLICATED : LOCAL);
  1083. resolver.AddNode(id_, cloneNode);
  1084. // Copy attributes
  1085. unsigned numAttributes = GetNumAttributes();
  1086. for (unsigned j = 0; j < numAttributes; ++j)
  1087. cloneNode->SetAttribute(j, GetAttribute(j));
  1088. // Clone components
  1089. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  1090. {
  1091. Component* component = *i;
  1092. Component* cloneComponent = cloneNode->CreateComponent(component->GetType(), (mode == REPLICATED && component->GetID() <
  1093. FIRST_LOCAL_ID) ? REPLICATED : LOCAL);
  1094. if (!cloneComponent)
  1095. {
  1096. LOGERROR("Could not clone component " + component->GetTypeName());
  1097. continue;
  1098. }
  1099. resolver.AddComponent(component->GetID(), cloneComponent);
  1100. numAttributes = component->GetNumAttributes();
  1101. for (unsigned j = 0; j < numAttributes; ++j)
  1102. cloneComponent->SetAttribute(j, component->GetAttribute(j));
  1103. }
  1104. // Clone child nodes recursively
  1105. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1106. {
  1107. Node* node = *i;
  1108. node->CloneRecursive(cloneNode, resolver, mode);
  1109. }
  1110. return cloneNode;
  1111. }
  1112. }