Node.cpp 33 KB

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