Node.cpp 34 KB

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