Node.cpp 38 KB

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