Node.cpp 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184
  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. void Node::AddListener(Component* component)
  586. {
  587. if (!component)
  588. return;
  589. // Check for not adding twice
  590. for (Vector<WeakPtr<Component> >::Iterator i = listeners_.Begin(); i != listeners_.End(); ++i)
  591. {
  592. if (*i == component)
  593. return;
  594. }
  595. listeners_.Push(WeakPtr<Component>(component));
  596. // If the node is currently dirty, notify immediately
  597. if (dirty_)
  598. component->OnMarkedDirty(this);
  599. }
  600. void Node::RemoveListener(Component* component)
  601. {
  602. for (Vector<WeakPtr<Component> >::Iterator i = listeners_.Begin(); i != listeners_.End(); ++i)
  603. {
  604. if (*i == component)
  605. {
  606. listeners_.Erase(i);
  607. return;
  608. }
  609. }
  610. }
  611. void Node::Remove()
  612. {
  613. if (parent_)
  614. parent_->RemoveChild(this);
  615. }
  616. void Node::SetParent(Node* parent)
  617. {
  618. if (parent)
  619. {
  620. Vector3 worldPosition;
  621. Quaternion worldRotation;
  622. Vector3 worldScale;
  623. GetWorldTransform().Decompose(worldPosition, worldRotation, worldScale);
  624. parent->AddChild(this);
  625. SetWorldTransform(worldPosition, worldRotation, worldScale);
  626. }
  627. }
  628. Matrix3x4 Node::GetWorldTargetTransform() const
  629. {
  630. if (!smoothed_)
  631. return GetWorldTransform();
  632. Matrix3x4 ret(targetPosition_, targetRotation_, scale_);
  633. Node* current = parent_;
  634. while (current)
  635. {
  636. ret = Matrix3x4(current->targetPosition_, current->targetRotation_, current->scale_) * ret;
  637. current = current->parent_;
  638. }
  639. return ret;
  640. }
  641. Vector3 Node::LocalToWorld(const Vector3& position) const
  642. {
  643. return GetWorldTransform() * position;
  644. }
  645. Vector3 Node::LocalToWorld(const Vector4& vector) const
  646. {
  647. return GetWorldTransform() * vector;
  648. }
  649. Vector3 Node::WorldToLocal(const Vector3& position) const
  650. {
  651. return GetWorldTransform().Inverse() * position;
  652. }
  653. Vector3 Node::WorldToLocal(const Vector4& vector) const
  654. {
  655. return GetWorldTransform().Inverse() * vector;
  656. }
  657. unsigned Node::GetNumChildren(bool recursive) const
  658. {
  659. if (!recursive)
  660. return children_.Size();
  661. else
  662. {
  663. unsigned allChildren = children_.Size();
  664. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  665. allChildren += (*i)->GetNumChildren(true);
  666. return allChildren;
  667. }
  668. }
  669. void Node::GetChildren(PODVector<Node*>& dest, bool recursive) const
  670. {
  671. dest.Clear();
  672. if (!recursive)
  673. {
  674. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  675. dest.Push(*i);
  676. }
  677. else
  678. GetChildrenRecursive(dest);
  679. }
  680. void Node::GetChildrenWithComponent(PODVector<Node*>& dest, ShortStringHash type, 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. {
  687. if ((*i)->HasComponent(type))
  688. dest.Push(*i);
  689. }
  690. }
  691. else
  692. GetChildrenWithComponentRecursive(dest, type);
  693. }
  694. Node* Node::GetChild(unsigned index) const
  695. {
  696. return index < children_.Size() ? children_[index].Get() : 0;
  697. }
  698. Node* Node::GetChild(const String& name, bool recursive) const
  699. {
  700. return GetChild(StringHash(name), recursive);
  701. }
  702. Node* Node::GetChild(StringHash nameHash, bool recursive) const
  703. {
  704. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  705. {
  706. if ((*i)->GetNameHash() == nameHash)
  707. return *i;
  708. if (recursive)
  709. {
  710. Node* node = (*i)->GetChild(nameHash, true);
  711. if (node)
  712. return node;
  713. }
  714. }
  715. return 0;
  716. }
  717. unsigned Node::GetNumNetworkComponents() const
  718. {
  719. unsigned num = 0;
  720. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  721. {
  722. if ((*i)->GetID() < FIRST_LOCAL_ID)
  723. ++num;
  724. }
  725. return num;
  726. }
  727. void Node::GetComponents(PODVector<Component*>& dest, ShortStringHash type) const
  728. {
  729. dest.Clear();
  730. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  731. {
  732. if ((*i)->GetType() == type)
  733. dest.Push(*i);
  734. }
  735. }
  736. bool Node::HasComponent(ShortStringHash type) const
  737. {
  738. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  739. {
  740. if ((*i)->GetType() == type)
  741. return true;
  742. }
  743. return false;
  744. }
  745. Component* Node::GetComponent(ShortStringHash type) const
  746. {
  747. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  748. {
  749. if ((*i)->GetType() == type)
  750. return *i;
  751. }
  752. return 0;
  753. }
  754. void Node::GetDependencyNodes(PODVector<Node*>& dest) const
  755. {
  756. // Add the parent node, but if it is local, traverse to the first non-local node
  757. if (parent_ && parent_ != scene_)
  758. {
  759. Node* current = parent_;
  760. while (current->id_ >= FIRST_LOCAL_ID)
  761. current = current->parent_;
  762. dest.Push(current);
  763. }
  764. // Then let the components add their dependencies
  765. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  766. (*i)->GetDependencyNodes(dest);
  767. }
  768. void Node::SetID(unsigned id)
  769. {
  770. id_ = id;
  771. }
  772. void Node::SetScene(Scene* scene)
  773. {
  774. scene_ = scene;
  775. }
  776. void Node::SetNetRotationAttr(const PODVector<unsigned char>& value)
  777. {
  778. MemoryBuffer buf(value);
  779. SetRotation(buf.ReadPackedQuaternion());
  780. }
  781. void Node::SetNetParentAttr(const PODVector<unsigned char>& value)
  782. {
  783. Scene* scene = GetScene();
  784. if (!scene)
  785. return;
  786. MemoryBuffer buf(value);
  787. // If nothing in the buffer, parent is the root node
  788. if (buf.IsEof())
  789. {
  790. scene->AddChild(this);
  791. return;
  792. }
  793. unsigned baseNodeID = buf.ReadNetID();
  794. Node* baseNode = scene->GetNode(baseNodeID);
  795. if (!baseNode)
  796. {
  797. LOGWARNING("Failed to find parent node " + String(baseNodeID));
  798. return;
  799. }
  800. // If buffer contains just an ID, the parent is replicated and we are done
  801. if (buf.IsEof())
  802. baseNode->AddChild(this);
  803. else
  804. {
  805. // Else the parent is local and we must find it recursively by name hash
  806. StringHash nameHash = buf.ReadStringHash();
  807. Node* parentNode = baseNode->GetChild(nameHash, true);
  808. if (!parentNode)
  809. LOGWARNING("Failed to find parent node with name hash " + nameHash.ToString());
  810. else
  811. parentNode->AddChild(this);
  812. }
  813. }
  814. const PODVector<unsigned char>& Node::GetNetRotationAttr() const
  815. {
  816. attrBuffer_.Clear();
  817. attrBuffer_.WritePackedQuaternion(rotation_);
  818. return attrBuffer_.GetBuffer();
  819. }
  820. const PODVector<unsigned char>& Node::GetNetParentAttr() const
  821. {
  822. attrBuffer_.Clear();
  823. Scene* scene = GetScene();
  824. if (scene && parent_ && parent_ != scene)
  825. {
  826. // If parent is replicated, can write the ID directly
  827. unsigned parentID = parent_->GetID();
  828. if (parentID < FIRST_LOCAL_ID)
  829. attrBuffer_.WriteNetID(parentID);
  830. else
  831. {
  832. // Parent is local: traverse hierarchy to find a non-local base node
  833. // This iteration always stops due to the scene (root) being non-local
  834. Node* current = parent_;
  835. while (current->GetID() >= FIRST_LOCAL_ID)
  836. current = current->GetParent();
  837. // Then write the base node ID and the parent's name hash
  838. attrBuffer_.WriteVLE(current->GetID());
  839. attrBuffer_.WriteStringHash(parent_->GetNameHash());
  840. }
  841. }
  842. return attrBuffer_.GetBuffer();
  843. }
  844. void Node::UpdateSmoothing(float constant, float squaredSnapThreshold)
  845. {
  846. if (!smoothed_ || !smoothingMask_)
  847. return;
  848. if (smoothingMask_ & SMOOTH_POSITION)
  849. {
  850. // If position snaps, snap everything to the end
  851. float delta = (position_ - targetPosition_).LengthSquared();
  852. if (delta > squaredSnapThreshold)
  853. constant = 1.0f;
  854. if (delta < M_EPSILON || constant >= 1.0f)
  855. {
  856. position_ = targetPosition_;
  857. smoothingMask_ &= ~SMOOTH_POSITION;
  858. }
  859. else
  860. position_ = position_.Lerp(targetPosition_, constant);
  861. }
  862. if (smoothingMask_ & SMOOTH_ROTATION)
  863. {
  864. float delta = (rotation_ - targetRotation_).LengthSquared();
  865. if (delta < M_EPSILON || constant >= 1.0f)
  866. {
  867. rotation_ = targetRotation_;
  868. smoothingMask_ &= ~SMOOTH_ROTATION;
  869. }
  870. else
  871. rotation_ = rotation_.Slerp(targetRotation_, constant);
  872. }
  873. if (!dirty_)
  874. MarkDirty();
  875. }
  876. bool Node::Load(Deserializer& source, SceneResolver& resolver, bool readChildren)
  877. {
  878. // Remove all children and components first in case this is not a fresh load
  879. RemoveAllChildren();
  880. RemoveAllComponents();
  881. // ID has been read at the parent level
  882. if (!Serializable::Load(source))
  883. return false;
  884. unsigned numComponents = source.ReadVLE();
  885. for (unsigned i = 0; i < numComponents; ++i)
  886. {
  887. VectorBuffer compBuffer(source, source.ReadVLE());
  888. ShortStringHash compType = compBuffer.ReadShortStringHash();
  889. unsigned compID = compBuffer.ReadUInt();
  890. Component* newComponent = CreateComponent(compType, compID, compID < FIRST_LOCAL_ID ? REPLICATED : LOCAL);
  891. if (newComponent)
  892. {
  893. resolver.AddComponent(compID, newComponent);
  894. if (!newComponent->Load(compBuffer))
  895. return false;
  896. }
  897. }
  898. if (!readChildren)
  899. return true;
  900. unsigned numChildren = source.ReadVLE();
  901. for (unsigned i = 0; i < numChildren; ++i)
  902. {
  903. unsigned nodeID = source.ReadUInt();
  904. Node* newNode = CreateChild(nodeID, nodeID < FIRST_LOCAL_ID ? REPLICATED : LOCAL);
  905. resolver.AddNode(nodeID, newNode);
  906. if (!newNode->Load(source, resolver))
  907. return false;
  908. }
  909. return true;
  910. }
  911. bool Node::LoadXML(const XMLElement& source, SceneResolver& resolver, bool readChildren)
  912. {
  913. // Remove all children and components first in case this is not a fresh load
  914. RemoveAllChildren();
  915. RemoveAllComponents();
  916. if (!Serializable::LoadXML(source))
  917. return false;
  918. XMLElement compElem = source.GetChild("component");
  919. while (compElem)
  920. {
  921. String typeName = compElem.GetString("type");
  922. unsigned compID = compElem.GetInt("id");
  923. Component* newComponent = CreateComponent(ShortStringHash(typeName), compID, compID < FIRST_LOCAL_ID ? REPLICATED : LOCAL);
  924. if (newComponent)
  925. {
  926. resolver.AddComponent(compID, newComponent);
  927. if (!newComponent->LoadXML(compElem))
  928. return false;
  929. }
  930. compElem = compElem.GetNext("component");
  931. }
  932. if (!readChildren)
  933. return true;
  934. XMLElement childElem = source.GetChild("node");
  935. while (childElem)
  936. {
  937. unsigned nodeID = childElem.GetInt("id");
  938. Node* newNode = CreateChild(nodeID, nodeID < FIRST_LOCAL_ID ? REPLICATED : LOCAL);
  939. resolver.AddNode(nodeID, newNode);
  940. if (!newNode->LoadXML(childElem, resolver))
  941. return false;
  942. childElem = childElem.GetNext("node");
  943. }
  944. return true;
  945. }
  946. Component* Node::CreateComponent(ShortStringHash type, unsigned id, CreateMode mode)
  947. {
  948. // Check that creation succeeds and that the object in fact is a component
  949. SharedPtr<Component> newComponent = DynamicCast<Component>(context_->CreateObject(type));
  950. if (!newComponent)
  951. {
  952. LOGERROR("Could not create unknown component type " + type.ToString());
  953. return 0;
  954. }
  955. components_.Push(newComponent);
  956. // If zero ID specified, or the ID is already taken, let the scene assign
  957. if (scene_)
  958. {
  959. if (!id || scene_->GetComponent(id))
  960. id = scene_->GetFreeComponentID(mode);
  961. newComponent->SetID(id);
  962. scene_->ComponentAdded(newComponent);
  963. }
  964. else
  965. newComponent->SetID(id);
  966. newComponent->SetNode(this);
  967. newComponent->OnMarkedDirty(this);
  968. return newComponent;
  969. }
  970. Node* Node::CreateChild(unsigned id, CreateMode mode)
  971. {
  972. SharedPtr<Node> newNode(new Node(context_));
  973. // If zero ID specified, or the ID is already taken, let the scene assign
  974. if (scene_)
  975. {
  976. if (!id || scene_->GetNode(id))
  977. id = scene_->GetFreeNodeID(mode);
  978. newNode->SetID(id);
  979. }
  980. else
  981. newNode->SetID(id);
  982. AddChild(newNode);
  983. return newNode;
  984. }
  985. void Node::UpdateWorldTransform() const
  986. {
  987. if (parent_)
  988. {
  989. if (parent_->dirty_)
  990. parent_->UpdateWorldTransform();
  991. worldTransform_ = parent_->worldTransform_ * Matrix3x4(position_, rotation_, scale_);
  992. }
  993. else
  994. worldTransform_ = Matrix3x4(position_, rotation_, scale_);
  995. dirty_ = false;
  996. }
  997. void Node::RemoveChild(Vector<SharedPtr<Node> >::Iterator i)
  998. {
  999. (*i)->parent_ = 0;
  1000. (*i)->MarkDirty();
  1001. children_.Erase(i);
  1002. }
  1003. void Node::GetChildrenRecursive(PODVector<Node*>& dest) const
  1004. {
  1005. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1006. {
  1007. Node* node = *i;
  1008. dest.Push(node);
  1009. if (!node->children_.Empty())
  1010. node->GetChildrenRecursive(dest);
  1011. }
  1012. }
  1013. void Node::GetChildrenWithComponentRecursive(PODVector<Node*>& dest, ShortStringHash type) const
  1014. {
  1015. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1016. {
  1017. Node* node = *i;
  1018. if (node->HasComponent(type))
  1019. dest.Push(node);
  1020. if (!node->children_.Empty())
  1021. node->GetChildrenRecursive(dest);
  1022. }
  1023. }