Node.cpp 37 KB

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