Node.cpp 37 KB

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