Node.cpp 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664
  1. //
  2. // Copyright (c) 2008-2014 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "Precompiled.h"
  23. #include "Component.h"
  24. #include "Context.h"
  25. #include "Log.h"
  26. #include "MemoryBuffer.h"
  27. #include "ObjectAnimation.h"
  28. #include "Profiler.h"
  29. #include "ReplicationState.h"
  30. #include "Scene.h"
  31. #include "SceneEvents.h"
  32. #include "SmoothedTransform.h"
  33. #include "UnknownComponent.h"
  34. #include "XMLFile.h"
  35. #include "DebugNew.h"
  36. namespace Urho3D
  37. {
  38. Node::Node(Context* context) :
  39. Animatable(context),
  40. worldTransform_(Matrix3x4::IDENTITY),
  41. dirty_(false),
  42. networkUpdate_(false),
  43. enabled_(true),
  44. parent_(0),
  45. scene_(0),
  46. id_(0),
  47. position_(Vector3::ZERO),
  48. rotation_(Quaternion::IDENTITY),
  49. scale_(Vector3::ONE),
  50. worldRotation_(Quaternion::IDENTITY),
  51. owner_(0)
  52. {
  53. }
  54. Node::~Node()
  55. {
  56. RemoveAllChildren();
  57. RemoveAllComponents();
  58. // Remove from the scene
  59. if (scene_)
  60. scene_->NodeRemoved(this);
  61. }
  62. void Node::RegisterObject(Context* context)
  63. {
  64. context->RegisterFactory<Node>();
  65. ACCESSOR_ATTRIBUTE(Node, VAR_BOOL, "Is Enabled", IsEnabled, SetEnabled, bool, true, AM_DEFAULT);
  66. REF_ACCESSOR_ATTRIBUTE(Node, VAR_STRING, "Name", GetName, SetName, String, String::EMPTY, AM_DEFAULT);
  67. REF_ACCESSOR_ATTRIBUTE(Node, VAR_VECTOR3, "Position", GetPosition, SetPosition, Vector3, Vector3::ZERO, AM_FILE);
  68. REF_ACCESSOR_ATTRIBUTE(Node, VAR_QUATERNION, "Rotation", GetRotation, SetRotation, Quaternion, Quaternion::IDENTITY, AM_FILE);
  69. REF_ACCESSOR_ATTRIBUTE(Node, VAR_VECTOR3, "Scale", GetScale, SetScale, Vector3, Vector3::ONE, AM_DEFAULT);
  70. ATTRIBUTE(Node, VAR_VARIANTMAP, "Variables", vars_, Variant::emptyVariantMap, AM_FILE); // Network replication of vars uses custom data
  71. REF_ACCESSOR_ATTRIBUTE(Node, VAR_VECTOR3, "Network Position", GetNetPositionAttr, SetNetPositionAttr, Vector3, Vector3::ZERO, AM_NET | AM_LATESTDATA | AM_NOEDIT);
  72. REF_ACCESSOR_ATTRIBUTE(Node, VAR_BUFFER, "Network Rotation", GetNetRotationAttr, SetNetRotationAttr, PODVector<unsigned char>, Variant::emptyBuffer, AM_NET | AM_LATESTDATA | AM_NOEDIT);
  73. REF_ACCESSOR_ATTRIBUTE(Node, VAR_BUFFER, "Network Parent Node", GetNetParentAttr, SetNetParentAttr, PODVector<unsigned char>, Variant::emptyBuffer, AM_NET | AM_NOEDIT);
  74. }
  75. void Node::OnSetAttribute(const AttributeInfo& attr, const Variant& src)
  76. {
  77. Animatable::OnSetAttribute(attr, src);
  78. MarkNetworkUpdate();
  79. }
  80. bool Node::Load(Deserializer& source, bool setInstanceDefault)
  81. {
  82. SceneResolver resolver;
  83. // Read own ID. Will not be applied, only stored for resolving possible references
  84. unsigned nodeID = source.ReadInt();
  85. resolver.AddNode(nodeID, this);
  86. // Read attributes, components and child nodes
  87. bool success = Load(source, resolver);
  88. if (success)
  89. {
  90. resolver.Resolve();
  91. ApplyAttributes();
  92. }
  93. return success;
  94. }
  95. bool Node::Save(Serializer& dest) const
  96. {
  97. // Write node ID
  98. if (!dest.WriteUInt(id_))
  99. return false;
  100. // Write attributes
  101. if (!Animatable::Save(dest))
  102. return false;
  103. // Write components
  104. dest.WriteVLE(GetNumPersistentComponents());
  105. for (unsigned i = 0; i < components_.Size(); ++i)
  106. {
  107. Component* component = components_[i];
  108. if (component->IsTemporary())
  109. continue;
  110. // Create a separate buffer to be able to skip failing components during deserialization
  111. VectorBuffer compBuffer;
  112. if (!component->Save(compBuffer))
  113. return false;
  114. dest.WriteVLE(compBuffer.GetSize());
  115. dest.Write(compBuffer.GetData(), compBuffer.GetSize());
  116. }
  117. // Write child nodes
  118. dest.WriteVLE(GetNumPersistentChildren());
  119. for (unsigned i = 0; i < children_.Size(); ++i)
  120. {
  121. Node* node = children_[i];
  122. if (node->IsTemporary())
  123. continue;
  124. if (!node->Save(dest))
  125. return false;
  126. }
  127. return true;
  128. }
  129. bool Node::LoadXML(const XMLElement& source, bool setInstanceDefault)
  130. {
  131. SceneResolver resolver;
  132. // Read own ID. Will not be applied, only stored for resolving possible references
  133. unsigned nodeID = source.GetInt("id");
  134. resolver.AddNode(nodeID, this);
  135. // Read attributes, components and child nodes
  136. bool success = LoadXML(source, resolver);
  137. if (success)
  138. {
  139. resolver.Resolve();
  140. ApplyAttributes();
  141. }
  142. return success;
  143. }
  144. bool Node::SaveXML(XMLElement& dest) const
  145. {
  146. // Write node ID
  147. if (!dest.SetInt("id", id_))
  148. return false;
  149. // Write attributes
  150. if (!Animatable::SaveXML(dest))
  151. return false;
  152. // Write components
  153. for (unsigned i = 0; i < components_.Size(); ++i)
  154. {
  155. Component* component = components_[i];
  156. if (component->IsTemporary())
  157. continue;
  158. XMLElement compElem = dest.CreateChild("component");
  159. if (!component->SaveXML(compElem))
  160. return false;
  161. }
  162. // Write child nodes
  163. for (unsigned i = 0; i < children_.Size(); ++i)
  164. {
  165. Node* node = children_[i];
  166. if (node->IsTemporary())
  167. continue;
  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::AddReplicationState(NodeReplicationState* state)
  182. {
  183. if (!networkState_)
  184. AllocateNetworkState();
  185. networkState_->replicationStates_.Push(state);
  186. }
  187. bool Node::SaveXML(Serializer& dest) const
  188. {
  189. SharedPtr<XMLFile> xml(new XMLFile(context_));
  190. XMLElement rootElem = xml->CreateRoot("node");
  191. if (!SaveXML(rootElem))
  192. return false;
  193. return xml->Save(dest);
  194. }
  195. void Node::SetName(const String& name)
  196. {
  197. if (name != name_)
  198. {
  199. name_ = name;
  200. nameHash_ = name_;
  201. MarkNetworkUpdate();
  202. // Send change event
  203. if (scene_)
  204. {
  205. using namespace NodeNameChanged;
  206. VariantMap& eventData = GetEventDataMap();
  207. eventData[P_SCENE] = scene_;
  208. eventData[P_NODE] = this;
  209. scene_->SendEvent(E_NODENAMECHANGED, eventData);
  210. }
  211. }
  212. }
  213. void Node::SetPosition(const Vector3& position)
  214. {
  215. position_ = position;
  216. MarkDirty();
  217. MarkNetworkUpdate();
  218. }
  219. void Node::SetRotation(const Quaternion& rotation)
  220. {
  221. rotation_ = rotation;
  222. MarkDirty();
  223. MarkNetworkUpdate();
  224. }
  225. void Node::SetDirection(const Vector3& direction)
  226. {
  227. SetRotation(Quaternion(Vector3::FORWARD, direction));
  228. }
  229. void Node::SetScale(float scale)
  230. {
  231. SetScale(Vector3(scale, scale, scale));
  232. }
  233. void Node::SetScale(const Vector3& scale)
  234. {
  235. scale_ = scale.Abs();
  236. MarkDirty();
  237. MarkNetworkUpdate();
  238. }
  239. void Node::SetTransform(const Vector3& position, const Quaternion& rotation)
  240. {
  241. position_ = position;
  242. rotation_ = rotation;
  243. MarkDirty();
  244. MarkNetworkUpdate();
  245. }
  246. void Node::SetTransform(const Vector3& position, const Quaternion& rotation, float scale)
  247. {
  248. SetTransform(position, rotation, Vector3(scale, scale, scale));
  249. }
  250. void Node::SetTransform(const Vector3& position, const Quaternion& rotation, const Vector3& scale)
  251. {
  252. position_ = position;
  253. rotation_ = rotation;
  254. scale_ = scale;
  255. MarkDirty();
  256. MarkNetworkUpdate();
  257. }
  258. void Node::SetWorldPosition(const Vector3& position)
  259. {
  260. SetPosition((parent_ == scene_ || !parent_) ? position : parent_->GetWorldTransform().Inverse() * position);
  261. }
  262. void Node::SetWorldRotation(const Quaternion& rotation)
  263. {
  264. SetRotation((parent_ == scene_ || !parent_) ? rotation : parent_->GetWorldRotation().Inverse() * rotation);
  265. }
  266. void Node::SetWorldDirection(const Vector3& direction)
  267. {
  268. Vector3 localDirection = (parent_ == scene_ || !parent_) ? direction : parent_->GetWorldRotation().Inverse() * direction;
  269. SetRotation(Quaternion(Vector3::FORWARD, localDirection));
  270. }
  271. void Node::SetWorldScale(float scale)
  272. {
  273. SetWorldScale(Vector3(scale, scale, scale));
  274. }
  275. void Node::SetWorldScale(const Vector3& scale)
  276. {
  277. SetScale((parent_ == scene_ || !parent_) ? scale : scale / parent_->GetWorldScale());
  278. }
  279. void Node::SetWorldTransform(const Vector3& position, const Quaternion& rotation)
  280. {
  281. SetWorldPosition(position);
  282. SetWorldRotation(rotation);
  283. }
  284. void Node::SetWorldTransform(const Vector3& position, const Quaternion& rotation, float scale)
  285. {
  286. SetWorldPosition(position);
  287. SetWorldRotation(rotation);
  288. SetWorldScale(scale);
  289. }
  290. void Node::SetWorldTransform(const Vector3& position, const Quaternion& rotation, const Vector3& scale)
  291. {
  292. SetWorldPosition(position);
  293. SetWorldRotation(rotation);
  294. SetWorldScale(scale);
  295. }
  296. void Node::Translate(const Vector3& delta, TransformSpace space)
  297. {
  298. switch (space)
  299. {
  300. case TS_LOCAL:
  301. // Note: local space translation disregards local scale for scale-independent movement speed
  302. position_ += rotation_ * delta;
  303. break;
  304. case TS_PARENT:
  305. position_ += delta;
  306. break;
  307. case TS_WORLD:
  308. position_ += (parent_ == scene_ || !parent_) ? delta : parent_->GetWorldTransform().Inverse() * Vector4(delta, 0.0f);
  309. break;
  310. }
  311. MarkDirty();
  312. MarkNetworkUpdate();
  313. }
  314. void Node::Rotate(const Quaternion& delta, TransformSpace space)
  315. {
  316. switch (space)
  317. {
  318. case TS_LOCAL:
  319. rotation_ = (rotation_ * delta).Normalized();
  320. break;
  321. case TS_PARENT:
  322. rotation_ = (delta * rotation_).Normalized();
  323. break;
  324. case TS_WORLD:
  325. if (parent_ == scene_ || !parent_)
  326. rotation_ = (delta * rotation_).Normalized();
  327. else
  328. {
  329. Quaternion worldRotation = GetWorldRotation();
  330. rotation_ = rotation_ * worldRotation.Inverse() * delta * worldRotation;
  331. }
  332. break;
  333. }
  334. MarkDirty();
  335. MarkNetworkUpdate();
  336. }
  337. void Node::RotateAround(const Vector3& point, const Quaternion& delta, TransformSpace space)
  338. {
  339. Vector3 parentSpacePoint;
  340. Quaternion oldRotation = rotation_;
  341. switch (space)
  342. {
  343. case TS_LOCAL:
  344. parentSpacePoint = GetTransform() * point;
  345. rotation_ = (rotation_ * delta).Normalized();
  346. break;
  347. case TS_PARENT:
  348. parentSpacePoint = point;
  349. rotation_ = (delta * rotation_).Normalized();
  350. break;
  351. case TS_WORLD:
  352. if (parent_ == scene_ || !parent_)
  353. {
  354. parentSpacePoint = point;
  355. rotation_ = (delta * rotation_).Normalized();
  356. }
  357. else
  358. {
  359. parentSpacePoint = parent_->GetWorldTransform().Inverse() * point;
  360. Quaternion worldRotation = GetWorldRotation();
  361. rotation_ = rotation_ * worldRotation.Inverse() * delta * worldRotation;
  362. }
  363. break;
  364. }
  365. Vector3 oldRelativePos = oldRotation.Inverse() * (position_ - parentSpacePoint);
  366. position_ = rotation_ * oldRelativePos + parentSpacePoint;
  367. MarkDirty();
  368. MarkNetworkUpdate();
  369. }
  370. void Node::Yaw(float angle, TransformSpace space)
  371. {
  372. Rotate(Quaternion(angle, Vector3::UP), space);
  373. }
  374. void Node::Pitch(float angle, TransformSpace space)
  375. {
  376. Rotate(Quaternion(angle, Vector3::RIGHT), space);
  377. }
  378. void Node::Roll(float angle, TransformSpace space)
  379. {
  380. Rotate(Quaternion(angle, Vector3::FORWARD), space);
  381. }
  382. bool Node::LookAt(const Vector3& target, const Vector3& up, TransformSpace space)
  383. {
  384. Vector3 worldSpaceTarget;
  385. switch (space)
  386. {
  387. case TS_LOCAL:
  388. worldSpaceTarget = GetWorldTransform() * target;
  389. break;
  390. case TS_PARENT:
  391. worldSpaceTarget = (parent_ == scene_ || !parent_) ? target : parent_->GetWorldTransform() * target;
  392. break;
  393. case TS_WORLD:
  394. worldSpaceTarget = target;
  395. break;
  396. }
  397. Vector3 lookDir = target - GetWorldPosition();
  398. // Check if target is very close, in that case can not reliably calculate lookat direction
  399. if (lookDir.Equals(Vector3::ZERO))
  400. return false;
  401. Quaternion newRotation;
  402. // Do nothing if setting look rotation failed
  403. if (!newRotation.FromLookRotation(lookDir, up))
  404. return false;
  405. SetWorldRotation(newRotation);
  406. return true;
  407. }
  408. void Node::Scale(float scale)
  409. {
  410. Scale(Vector3(scale, scale, scale));
  411. }
  412. void Node::Scale(const Vector3& scale)
  413. {
  414. scale_ *= scale;
  415. MarkDirty();
  416. MarkNetworkUpdate();
  417. }
  418. void Node::SetEnabled(bool enable)
  419. {
  420. SetEnabled(enable, false);
  421. }
  422. void Node::SetEnabled(bool enable, bool recursive)
  423. {
  424. // The enabled state of the whole scene can not be changed. SetUpdateEnabled() is used instead to start/stop updates.
  425. if (GetType() == Scene::GetTypeStatic())
  426. {
  427. LOGERROR("Can not change enabled state of the Scene");
  428. return;
  429. }
  430. if (enable != enabled_)
  431. {
  432. enabled_ = enable;
  433. MarkNetworkUpdate();
  434. // Notify listener components of the state change
  435. for (Vector<WeakPtr<Component> >::Iterator i = listeners_.Begin(); i != listeners_.End();)
  436. {
  437. if (*i)
  438. {
  439. (*i)->OnNodeSetEnabled(this);
  440. ++i;
  441. }
  442. // If listener has expired, erase from list
  443. else
  444. i = listeners_.Erase(i);
  445. }
  446. // Send change event
  447. if (scene_)
  448. {
  449. using namespace NodeEnabledChanged;
  450. VariantMap& eventData = GetEventDataMap();
  451. eventData[P_SCENE] = scene_;
  452. eventData[P_NODE] = this;
  453. scene_->SendEvent(E_NODEENABLEDCHANGED, eventData);
  454. }
  455. for (Vector<SharedPtr<Component> >::Iterator i = components_.Begin(); i != components_.End(); ++i)
  456. {
  457. (*i)->OnSetEnabled();
  458. // Send change event for the component
  459. if (scene_)
  460. {
  461. using namespace ComponentEnabledChanged;
  462. VariantMap& eventData = GetEventDataMap();
  463. eventData[P_SCENE] = scene_;
  464. eventData[P_NODE] = this;
  465. eventData[P_COMPONENT] = (*i);
  466. scene_->SendEvent(E_COMPONENTENABLEDCHANGED, eventData);
  467. }
  468. }
  469. }
  470. if (recursive)
  471. {
  472. for (Vector<SharedPtr<Node> >::Iterator i = children_.Begin(); i != children_.End(); ++i)
  473. (*i)->SetEnabled(enable, recursive);
  474. }
  475. }
  476. void Node::SetOwner(Connection* owner)
  477. {
  478. owner_ = owner;
  479. }
  480. void Node::MarkDirty()
  481. {
  482. if (dirty_)
  483. return;
  484. dirty_ = true;
  485. // Notify listener components first, then mark child nodes
  486. for (Vector<WeakPtr<Component> >::Iterator i = listeners_.Begin(); i != listeners_.End();)
  487. {
  488. if (*i)
  489. {
  490. (*i)->OnMarkedDirty(this);
  491. ++i;
  492. }
  493. // If listener has expired, erase from list
  494. else
  495. i = listeners_.Erase(i);
  496. }
  497. for (Vector<SharedPtr<Node> >::Iterator i = children_.Begin(); i != children_.End(); ++i)
  498. (*i)->MarkDirty();
  499. }
  500. Node* Node::CreateChild(const String& name, CreateMode mode, unsigned id)
  501. {
  502. Node* newNode = CreateChild(id, mode);
  503. newNode->SetName(name);
  504. return newNode;
  505. }
  506. void Node::AddChild(Node* node, unsigned index)
  507. {
  508. // Check for illegal or redundant parent assignment
  509. if (!node || node == this || node->parent_ == this)
  510. return;
  511. // Check for possible cyclic parent assignment
  512. Node* parent = parent_;
  513. while (parent)
  514. {
  515. if (parent == node)
  516. return;
  517. parent = parent->parent_;
  518. }
  519. // Add first, then remove from old parent, to ensure the node does not get deleted
  520. children_.Insert(index, SharedPtr<Node>(node));
  521. node->Remove();
  522. // Add to the scene if not added yet
  523. if (scene_ && node->GetScene() != scene_)
  524. scene_->NodeAdded(node);
  525. node->parent_ = this;
  526. node->MarkDirty();
  527. node->MarkNetworkUpdate();
  528. // Send change event
  529. if (scene_)
  530. {
  531. using namespace NodeAdded;
  532. VariantMap& eventData = GetEventDataMap();
  533. eventData[P_SCENE] = scene_;
  534. eventData[P_PARENT] = this;
  535. eventData[P_NODE] = node;
  536. scene_->SendEvent(E_NODEADDED, eventData);
  537. }
  538. }
  539. void Node::RemoveChild(Node* node)
  540. {
  541. if (!node)
  542. return;
  543. for (Vector<SharedPtr<Node> >::Iterator i = children_.Begin(); i != children_.End(); ++i)
  544. {
  545. if (*i == node)
  546. {
  547. RemoveChild(i);
  548. return;
  549. }
  550. }
  551. }
  552. void Node::RemoveAllChildren()
  553. {
  554. RemoveChildren(true, true, true);
  555. }
  556. void Node::RemoveChildren(bool removeReplicated, bool removeLocal, bool recursive)
  557. {
  558. unsigned numRemoved = 0;
  559. for (unsigned i = children_.Size() - 1; i < children_.Size(); --i)
  560. {
  561. bool remove = false;
  562. Node* childNode = children_[i];
  563. if (recursive)
  564. childNode->RemoveChildren(removeReplicated, removeLocal, true);
  565. if (childNode->GetID() < FIRST_LOCAL_ID && removeReplicated)
  566. remove = true;
  567. else if (childNode->GetID() >= FIRST_LOCAL_ID && removeLocal)
  568. remove = true;
  569. if (remove)
  570. {
  571. RemoveChild(children_.Begin() + i);
  572. ++numRemoved;
  573. }
  574. }
  575. // Mark node dirty in all replication states
  576. if (numRemoved)
  577. MarkReplicationDirty();
  578. }
  579. Component* Node::CreateComponent(ShortStringHash type, CreateMode mode, unsigned id)
  580. {
  581. // Check that creation succeeds and that the object in fact is a component
  582. SharedPtr<Component> newComponent = DynamicCast<Component>(context_->CreateObject(type));
  583. if (!newComponent)
  584. {
  585. LOGERROR("Could not create unknown component type " + type.ToString());
  586. return 0;
  587. }
  588. AddComponent(newComponent, id, mode);
  589. return newComponent;
  590. }
  591. Component* Node::GetOrCreateComponent(ShortStringHash type, CreateMode mode, unsigned id)
  592. {
  593. Component* oldComponent = GetComponent(type);
  594. if (oldComponent)
  595. return oldComponent;
  596. else
  597. return CreateComponent(type, mode, id);
  598. }
  599. void Node::RemoveComponent(Component* component)
  600. {
  601. for (Vector<SharedPtr<Component> >::Iterator i = components_.Begin(); i != components_.End(); ++i)
  602. {
  603. if (*i == component)
  604. {
  605. RemoveComponent(i);
  606. // Mark node dirty in all replication states
  607. MarkReplicationDirty();
  608. return;
  609. }
  610. }
  611. }
  612. void Node::RemoveComponent(ShortStringHash type)
  613. {
  614. for (Vector<SharedPtr<Component> >::Iterator i = components_.Begin(); i != components_.End(); ++i)
  615. {
  616. if ((*i)->GetType() == type)
  617. {
  618. RemoveComponent(i);
  619. // Mark node dirty in all replication states
  620. MarkReplicationDirty();
  621. return;
  622. }
  623. }
  624. }
  625. void Node::RemoveAllComponents()
  626. {
  627. RemoveComponents(true, true);
  628. }
  629. void Node::RemoveComponents(bool removeReplicated, bool removeLocal)
  630. {
  631. unsigned numRemoved = 0;
  632. for (unsigned i = components_.Size() - 1; i < components_.Size(); --i)
  633. {
  634. bool remove = false;
  635. Component* component = components_[i];
  636. if (component->GetID() < FIRST_LOCAL_ID && removeReplicated)
  637. remove = true;
  638. else if (component->GetID() >= FIRST_LOCAL_ID && removeLocal)
  639. remove = true;
  640. if (remove)
  641. {
  642. RemoveComponent(components_.Begin() + i);
  643. ++numRemoved;
  644. }
  645. }
  646. // Mark node dirty in all replication states
  647. if (numRemoved)
  648. MarkReplicationDirty();
  649. }
  650. Node* Node::Clone(CreateMode mode)
  651. {
  652. // The scene itself can not be cloned
  653. if (this == scene_ || !parent_)
  654. {
  655. LOGERROR("Can not clone node without a parent");
  656. return 0;
  657. }
  658. PROFILE(CloneNode);
  659. SceneResolver resolver;
  660. Node* clone = CloneRecursive(parent_, resolver, mode);
  661. resolver.Resolve();
  662. clone->ApplyAttributes();
  663. return clone;
  664. }
  665. void Node::Remove()
  666. {
  667. if (parent_)
  668. parent_->RemoveChild(this);
  669. }
  670. void Node::SetParent(Node* parent)
  671. {
  672. if (parent)
  673. {
  674. Matrix3x4 oldWorldTransform = GetWorldTransform();
  675. parent->AddChild(this);
  676. if (parent != scene_)
  677. {
  678. Matrix3x4 newTransform = parent->GetWorldTransform().Inverse() * oldWorldTransform;
  679. SetTransform(newTransform.Translation(), newTransform.Rotation(), newTransform.Scale());
  680. }
  681. else
  682. {
  683. // The root node is assumed to have identity transform, so can disregard it
  684. SetTransform(oldWorldTransform.Translation(), oldWorldTransform.Rotation(), oldWorldTransform.Scale());
  685. }
  686. }
  687. }
  688. void Node::SetVar(ShortStringHash key, const Variant& value)
  689. {
  690. vars_[key] = value;
  691. MarkNetworkUpdate();
  692. }
  693. void Node::AddListener(Component* component)
  694. {
  695. if (!component)
  696. return;
  697. // Check for not adding twice
  698. for (Vector<WeakPtr<Component> >::Iterator i = listeners_.Begin(); i != listeners_.End(); ++i)
  699. {
  700. if (*i == component)
  701. return;
  702. }
  703. listeners_.Push(WeakPtr<Component>(component));
  704. // If the node is currently dirty, notify immediately
  705. if (dirty_)
  706. component->OnMarkedDirty(this);
  707. }
  708. void Node::RemoveListener(Component* component)
  709. {
  710. for (Vector<WeakPtr<Component> >::Iterator i = listeners_.Begin(); i != listeners_.End(); ++i)
  711. {
  712. if (*i == component)
  713. {
  714. listeners_.Erase(i);
  715. return;
  716. }
  717. }
  718. }
  719. Vector3 Node::LocalToWorld(const Vector3& position) const
  720. {
  721. return GetWorldTransform() * position;
  722. }
  723. Vector3 Node::LocalToWorld(const Vector4& vector) const
  724. {
  725. return GetWorldTransform() * vector;
  726. }
  727. Vector3 Node::WorldToLocal(const Vector3& position) const
  728. {
  729. return GetWorldTransform().Inverse() * position;
  730. }
  731. Vector3 Node::WorldToLocal(const Vector4& vector) const
  732. {
  733. return GetWorldTransform().Inverse() * vector;
  734. }
  735. unsigned Node::GetNumChildren(bool recursive) const
  736. {
  737. if (!recursive)
  738. return children_.Size();
  739. else
  740. {
  741. unsigned allChildren = children_.Size();
  742. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  743. allChildren += (*i)->GetNumChildren(true);
  744. return allChildren;
  745. }
  746. }
  747. void Node::GetChildren(PODVector<Node*>& dest, bool recursive) const
  748. {
  749. dest.Clear();
  750. if (!recursive)
  751. {
  752. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  753. dest.Push(*i);
  754. }
  755. else
  756. GetChildrenRecursive(dest);
  757. }
  758. void Node::GetChildrenWithComponent(PODVector<Node*>& dest, ShortStringHash type, bool recursive) const
  759. {
  760. dest.Clear();
  761. if (!recursive)
  762. {
  763. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  764. {
  765. if ((*i)->HasComponent(type))
  766. dest.Push(*i);
  767. }
  768. }
  769. else
  770. GetChildrenWithComponentRecursive(dest, type);
  771. }
  772. Node* Node::GetChild(unsigned index) const
  773. {
  774. return index < children_.Size() ? children_[index].Get() : 0;
  775. }
  776. Node* Node::GetChild(const String& name, bool recursive) const
  777. {
  778. return GetChild(StringHash(name), recursive);
  779. }
  780. Node* Node::GetChild(const char* name, bool recursive) const
  781. {
  782. return GetChild(StringHash(name), recursive);
  783. }
  784. Node* Node::GetChild(StringHash nameHash, bool recursive) const
  785. {
  786. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  787. {
  788. if ((*i)->GetNameHash() == nameHash)
  789. return *i;
  790. if (recursive)
  791. {
  792. Node* node = (*i)->GetChild(nameHash, true);
  793. if (node)
  794. return node;
  795. }
  796. }
  797. return 0;
  798. }
  799. unsigned Node::GetNumNetworkComponents() const
  800. {
  801. unsigned num = 0;
  802. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  803. {
  804. if ((*i)->GetID() < FIRST_LOCAL_ID)
  805. ++num;
  806. }
  807. return num;
  808. }
  809. void Node::GetComponents(PODVector<Component*>& dest, ShortStringHash type, bool recursive) const
  810. {
  811. dest.Clear();
  812. if (!recursive)
  813. {
  814. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  815. {
  816. if ((*i)->GetType() == type)
  817. dest.Push(*i);
  818. }
  819. }
  820. else
  821. GetComponentsRecursive(dest, type);
  822. }
  823. bool Node::HasComponent(ShortStringHash type) const
  824. {
  825. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  826. {
  827. if ((*i)->GetType() == type)
  828. return true;
  829. }
  830. return false;
  831. }
  832. const Variant& Node::GetVar(ShortStringHash key) const
  833. {
  834. VariantMap::ConstIterator i = vars_.Find(key);
  835. return i != vars_.End() ? i->second_ : Variant::EMPTY;
  836. }
  837. Component* Node::GetComponent(ShortStringHash type) const
  838. {
  839. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  840. {
  841. if ((*i)->GetType() == type)
  842. return *i;
  843. }
  844. return 0;
  845. }
  846. void Node::SetID(unsigned id)
  847. {
  848. id_ = id;
  849. }
  850. void Node::SetScene(Scene* scene)
  851. {
  852. scene_ = scene;
  853. }
  854. void Node::ResetScene()
  855. {
  856. SetID(0);
  857. SetScene(0);
  858. SetOwner(0);
  859. }
  860. void Node::SetNetPositionAttr(const Vector3& value)
  861. {
  862. SmoothedTransform* transform = GetComponent<SmoothedTransform>();
  863. if (transform)
  864. transform->SetTargetPosition(value);
  865. else
  866. SetPosition(value);
  867. }
  868. void Node::SetNetRotationAttr(const PODVector<unsigned char>& value)
  869. {
  870. MemoryBuffer buf(value);
  871. SmoothedTransform* transform = GetComponent<SmoothedTransform>();
  872. if (transform)
  873. transform->SetTargetRotation(buf.ReadPackedQuaternion());
  874. else
  875. SetRotation(buf.ReadPackedQuaternion());
  876. }
  877. void Node::SetNetParentAttr(const PODVector<unsigned char>& value)
  878. {
  879. Scene* scene = GetScene();
  880. if (!scene)
  881. return;
  882. MemoryBuffer buf(value);
  883. // If nothing in the buffer, parent is the root node
  884. if (buf.IsEof())
  885. {
  886. scene->AddChild(this);
  887. return;
  888. }
  889. unsigned baseNodeID = buf.ReadNetID();
  890. Node* baseNode = scene->GetNode(baseNodeID);
  891. if (!baseNode)
  892. {
  893. LOGWARNING("Failed to find parent node " + String(baseNodeID));
  894. return;
  895. }
  896. // If buffer contains just an ID, the parent is replicated and we are done
  897. if (buf.IsEof())
  898. baseNode->AddChild(this);
  899. else
  900. {
  901. // Else the parent is local and we must find it recursively by name hash
  902. StringHash nameHash = buf.ReadStringHash();
  903. Node* parentNode = baseNode->GetChild(nameHash, true);
  904. if (!parentNode)
  905. LOGWARNING("Failed to find parent node with name hash " + nameHash.ToString());
  906. else
  907. parentNode->AddChild(this);
  908. }
  909. }
  910. const Vector3& Node::GetNetPositionAttr() const
  911. {
  912. return position_;
  913. }
  914. const PODVector<unsigned char>& Node::GetNetRotationAttr() const
  915. {
  916. attrBuffer_.Clear();
  917. attrBuffer_.WritePackedQuaternion(rotation_);
  918. return attrBuffer_.GetBuffer();
  919. }
  920. const PODVector<unsigned char>& Node::GetNetParentAttr() const
  921. {
  922. attrBuffer_.Clear();
  923. Scene* scene = GetScene();
  924. if (scene && parent_ && parent_ != scene)
  925. {
  926. // If parent is replicated, can write the ID directly
  927. unsigned parentID = parent_->GetID();
  928. if (parentID < FIRST_LOCAL_ID)
  929. attrBuffer_.WriteNetID(parentID);
  930. else
  931. {
  932. // Parent is local: traverse hierarchy to find a non-local base node
  933. // This iteration always stops due to the scene (root) being non-local
  934. Node* current = parent_;
  935. while (current->GetID() >= FIRST_LOCAL_ID)
  936. current = current->GetParent();
  937. // Then write the base node ID and the parent's name hash
  938. attrBuffer_.WriteNetID(current->GetID());
  939. attrBuffer_.WriteStringHash(parent_->GetNameHash());
  940. }
  941. }
  942. return attrBuffer_.GetBuffer();
  943. }
  944. bool Node::Load(Deserializer& source, SceneResolver& resolver, bool readChildren, bool rewriteIDs, CreateMode mode)
  945. {
  946. // Remove all children and components first in case this is not a fresh load
  947. RemoveAllChildren();
  948. RemoveAllComponents();
  949. // ID has been read at the parent level
  950. if (!Animatable::Load(source))
  951. return false;
  952. unsigned numComponents = source.ReadVLE();
  953. for (unsigned i = 0; i < numComponents; ++i)
  954. {
  955. VectorBuffer compBuffer(source, source.ReadVLE());
  956. ShortStringHash compType = compBuffer.ReadShortStringHash();
  957. unsigned compID = compBuffer.ReadUInt();
  958. Component* newComponent = SafeCreateComponent(String::EMPTY, compType,
  959. (mode == REPLICATED && compID < FIRST_LOCAL_ID) ? REPLICATED : LOCAL, rewriteIDs ? 0 : compID);
  960. if (newComponent)
  961. {
  962. resolver.AddComponent(compID, newComponent);
  963. // Do not abort if component fails to load, as the component buffer is nested and we can skip to the next
  964. newComponent->Load(compBuffer);
  965. }
  966. }
  967. if (!readChildren)
  968. return true;
  969. unsigned numChildren = source.ReadVLE();
  970. for (unsigned i = 0; i < numChildren; ++i)
  971. {
  972. unsigned nodeID = source.ReadUInt();
  973. Node* newNode = CreateChild(rewriteIDs ? 0 : nodeID, (mode == REPLICATED && nodeID < FIRST_LOCAL_ID) ? REPLICATED :
  974. LOCAL);
  975. resolver.AddNode(nodeID, newNode);
  976. if (!newNode->Load(source, resolver, readChildren, rewriteIDs, mode))
  977. return false;
  978. }
  979. return true;
  980. }
  981. bool Node::LoadXML(const XMLElement& source, SceneResolver& resolver, bool readChildren, bool rewriteIDs, CreateMode mode)
  982. {
  983. // Remove all children and components first in case this is not a fresh load
  984. RemoveAllChildren();
  985. RemoveAllComponents();
  986. if (!Animatable::LoadXML(source))
  987. return false;
  988. XMLElement compElem = source.GetChild("component");
  989. while (compElem)
  990. {
  991. String typeName = compElem.GetAttribute("type");
  992. unsigned compID = compElem.GetInt("id");
  993. Component* newComponent = SafeCreateComponent(typeName, ShortStringHash(typeName),
  994. (mode == REPLICATED && compID < FIRST_LOCAL_ID) ? REPLICATED : LOCAL, rewriteIDs ? 0 : compID);
  995. if (newComponent)
  996. {
  997. resolver.AddComponent(compID, newComponent);
  998. if (!newComponent->LoadXML(compElem))
  999. return false;
  1000. }
  1001. compElem = compElem.GetNext("component");
  1002. }
  1003. if (!readChildren)
  1004. return true;
  1005. XMLElement childElem = source.GetChild("node");
  1006. while (childElem)
  1007. {
  1008. unsigned nodeID = childElem.GetInt("id");
  1009. Node* newNode = CreateChild(rewriteIDs ? 0 : nodeID, (mode == REPLICATED && nodeID < FIRST_LOCAL_ID) ? REPLICATED :
  1010. LOCAL);
  1011. resolver.AddNode(nodeID, newNode);
  1012. if (!newNode->LoadXML(childElem, resolver, readChildren, rewriteIDs, mode))
  1013. return false;
  1014. childElem = childElem.GetNext("node");
  1015. }
  1016. return true;
  1017. }
  1018. void Node::PrepareNetworkUpdate()
  1019. {
  1020. // Update dependency nodes list first
  1021. dependencyNodes_.Clear();
  1022. // Add the parent node, but if it is local, traverse to the first non-local node
  1023. if (parent_ && parent_ != scene_)
  1024. {
  1025. Node* current = parent_;
  1026. while (current->id_ >= FIRST_LOCAL_ID)
  1027. current = current->parent_;
  1028. if (current && current != scene_)
  1029. dependencyNodes_.Push(current);
  1030. }
  1031. // Let the components add their dependencies
  1032. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  1033. {
  1034. Component* component = *i;
  1035. if (component->GetID() < FIRST_LOCAL_ID)
  1036. component->GetDependencyNodes(dependencyNodes_);
  1037. }
  1038. // Then check for node attribute changes
  1039. if (!networkState_)
  1040. AllocateNetworkState();
  1041. const Vector<AttributeInfo>* attributes = networkState_->attributes_;
  1042. unsigned numAttributes = attributes->Size();
  1043. if (networkState_->currentValues_.Size() != numAttributes)
  1044. {
  1045. networkState_->currentValues_.Resize(numAttributes);
  1046. networkState_->previousValues_.Resize(numAttributes);
  1047. // Copy the default attribute values to the previous state as a starting point
  1048. for (unsigned i = 0; i < numAttributes; ++i)
  1049. networkState_->previousValues_[i] = attributes->At(i).defaultValue_;
  1050. }
  1051. // Check for attribute changes
  1052. for (unsigned i = 0; i < numAttributes; ++i)
  1053. {
  1054. const AttributeInfo& attr = attributes->At(i);
  1055. if (animationEnabled_ && IsAnimatedNetworkAttribute(attr))
  1056. continue;
  1057. OnGetAttribute(attr, networkState_->currentValues_[i]);
  1058. if (networkState_->currentValues_[i] != networkState_->previousValues_[i])
  1059. {
  1060. networkState_->previousValues_[i] = networkState_->currentValues_[i];
  1061. // Mark the attribute dirty in all replication states that are tracking this node
  1062. for (PODVector<ReplicationState*>::Iterator j = networkState_->replicationStates_.Begin(); j !=
  1063. networkState_->replicationStates_.End();
  1064. ++j)
  1065. {
  1066. NodeReplicationState* nodeState = static_cast<NodeReplicationState*>(*j);
  1067. nodeState->dirtyAttributes_.Set(i);
  1068. // Add node to the dirty set if not added yet
  1069. if (!nodeState->markedDirty_)
  1070. {
  1071. nodeState->markedDirty_ = true;
  1072. nodeState->sceneState_->dirtyNodes_.Insert(id_);
  1073. }
  1074. }
  1075. }
  1076. }
  1077. // Finally check for user var changes
  1078. for (VariantMap::ConstIterator i = vars_.Begin(); i != vars_.End(); ++i)
  1079. {
  1080. VariantMap::ConstIterator j = networkState_->previousVars_.Find(i->first_);
  1081. if (j == networkState_->previousVars_.End() || j->second_ != i->second_)
  1082. {
  1083. networkState_->previousVars_[i->first_] = i->second_;
  1084. // Mark the var dirty in all replication states that are tracking this node
  1085. for (PODVector<ReplicationState*>::Iterator j = networkState_->replicationStates_.Begin(); j !=
  1086. networkState_->replicationStates_.End(); ++j)
  1087. {
  1088. NodeReplicationState* nodeState = static_cast<NodeReplicationState*>(*j);
  1089. nodeState->dirtyVars_.Insert(i->first_);
  1090. if (!nodeState->markedDirty_)
  1091. {
  1092. nodeState->markedDirty_ = true;
  1093. nodeState->sceneState_->dirtyNodes_.Insert(id_);
  1094. }
  1095. }
  1096. }
  1097. }
  1098. networkUpdate_ = false;
  1099. }
  1100. void Node::CleanupConnection(Connection* connection)
  1101. {
  1102. if (owner_ == connection)
  1103. owner_ = 0;
  1104. if (networkState_)
  1105. {
  1106. for (unsigned i = networkState_->replicationStates_.Size() - 1; i < networkState_->replicationStates_.Size(); --i)
  1107. {
  1108. if (networkState_->replicationStates_[i]->connection_ == connection)
  1109. networkState_->replicationStates_.Erase(i);
  1110. }
  1111. }
  1112. }
  1113. void Node::MarkNetworkUpdate()
  1114. {
  1115. if (!networkUpdate_ && scene_ && id_ < FIRST_LOCAL_ID)
  1116. {
  1117. scene_->MarkNetworkUpdate(this);
  1118. networkUpdate_ = true;
  1119. }
  1120. }
  1121. void Node::MarkReplicationDirty()
  1122. {
  1123. if (networkState_)
  1124. {
  1125. for (PODVector<ReplicationState*>::Iterator j = networkState_->replicationStates_.Begin(); j !=
  1126. networkState_->replicationStates_.End(); ++j)
  1127. {
  1128. NodeReplicationState* nodeState = static_cast<NodeReplicationState*>(*j);
  1129. if (!nodeState->markedDirty_)
  1130. {
  1131. nodeState->markedDirty_ = true;
  1132. nodeState->sceneState_->dirtyNodes_.Insert(id_);
  1133. }
  1134. }
  1135. }
  1136. }
  1137. Node* Node::CreateChild(unsigned id, CreateMode mode)
  1138. {
  1139. SharedPtr<Node> newNode(new Node(context_));
  1140. // If zero ID specified, or the ID is already taken, let the scene assign
  1141. if (scene_)
  1142. {
  1143. if (!id || scene_->GetNode(id))
  1144. id = scene_->GetFreeNodeID(mode);
  1145. newNode->SetID(id);
  1146. }
  1147. else
  1148. newNode->SetID(id);
  1149. AddChild(newNode);
  1150. return newNode;
  1151. }
  1152. void Node::AddComponent(Component* component, unsigned id, CreateMode mode)
  1153. {
  1154. if (!component)
  1155. return;
  1156. components_.Push(SharedPtr<Component>(component));
  1157. // If zero ID specified, or the ID is already taken, let the scene assign
  1158. if (scene_)
  1159. {
  1160. if (!id || scene_->GetComponent(id))
  1161. id = scene_->GetFreeComponentID(mode);
  1162. component->SetID(id);
  1163. scene_->ComponentAdded(component);
  1164. }
  1165. else
  1166. component->SetID(id);
  1167. component->SetNode(this);
  1168. component->OnMarkedDirty(this);
  1169. // Check attributes of the new component on next network update, and mark node dirty in all replication states
  1170. component->MarkNetworkUpdate();
  1171. MarkNetworkUpdate();
  1172. MarkReplicationDirty();
  1173. // Send change event
  1174. if (scene_)
  1175. {
  1176. using namespace ComponentAdded;
  1177. VariantMap& eventData = GetEventDataMap();
  1178. eventData[P_SCENE] = scene_;
  1179. eventData[P_NODE] = this;
  1180. eventData[P_COMPONENT] = component;
  1181. scene_->SendEvent(E_COMPONENTADDED, eventData);
  1182. }
  1183. }
  1184. unsigned Node::GetNumPersistentChildren() const
  1185. {
  1186. unsigned ret = 0;
  1187. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1188. {
  1189. if (!(*i)->IsTemporary())
  1190. ++ret;
  1191. }
  1192. return ret;
  1193. }
  1194. unsigned Node::GetNumPersistentComponents() const
  1195. {
  1196. unsigned ret = 0;
  1197. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  1198. {
  1199. if (!(*i)->IsTemporary())
  1200. ++ret;
  1201. }
  1202. return ret;
  1203. }
  1204. void Node::OnObjectAnimationAdded(ObjectAnimation* objectAnimation)
  1205. {
  1206. Animatable::OnObjectAnimationAdded(objectAnimation);
  1207. const HashMap<String, SharedPtr<ObjectAnimation> >& childObjectAnimations = objectAnimation->GetObjectAnimations();
  1208. for (HashMap<String, SharedPtr<ObjectAnimation> >::ConstIterator i = childObjectAnimations.Begin(); i != childObjectAnimations.End(); ++i)
  1209. {
  1210. Node* child = GetChild(i->first_);
  1211. if (child)
  1212. child->SetObjectAnimation(i->second_);
  1213. }
  1214. }
  1215. void Node::OnObjectAnimationRemoved(ObjectAnimation* objectAnimation)
  1216. {
  1217. Animatable::OnObjectAnimationRemoved(objectAnimation);
  1218. const HashMap<String, SharedPtr<ObjectAnimation> >& childObjectAnimations = objectAnimation->GetObjectAnimations();
  1219. for (HashMap<String, SharedPtr<ObjectAnimation> >::ConstIterator i = childObjectAnimations.Begin(); i != childObjectAnimations.End(); ++i)
  1220. {
  1221. Node* child = GetChild(i->first_);
  1222. if (child && child->GetObjectAnimation() == i->second_)
  1223. child->SetObjectAnimation(0);
  1224. }
  1225. }
  1226. void Node::OnAttributeAnimationAdded()
  1227. {
  1228. if (attributeAnimationInstances_.Size() == 1)
  1229. SubscribeToEvent(GetScene(), E_SCENEPOSTUPDATE, HANDLER(Node, HandleScenePostUpdate));
  1230. }
  1231. void Node::OnAttributeAnimationRemoved()
  1232. {
  1233. if (attributeAnimationInstances_.Empty())
  1234. UnsubscribeFromEvent(GetScene(), E_SCENEPOSTUPDATE);
  1235. }
  1236. Component* Node::SafeCreateComponent(const String& typeName, ShortStringHash type, CreateMode mode, unsigned id)
  1237. {
  1238. // First check if factory for type exists
  1239. if (!context_->GetTypeName(type).Empty())
  1240. return CreateComponent(type, mode, id);
  1241. else
  1242. {
  1243. LOGWARNING("Component type " + type.ToString() + " not known, creating UnknownComponent as placeholder");
  1244. // Else create as UnknownComponent
  1245. SharedPtr<UnknownComponent> newComponent(new UnknownComponent(context_));
  1246. if (typeName.Empty() || typeName.StartsWith("Unknown", false))
  1247. newComponent->SetType(type);
  1248. else
  1249. newComponent->SetTypeName(typeName);
  1250. AddComponent(newComponent, id, mode);
  1251. return newComponent;
  1252. }
  1253. }
  1254. void Node::UpdateWorldTransform() const
  1255. {
  1256. Matrix3x4 transform = GetTransform();
  1257. // Assume the root node (scene) has identity transform
  1258. if (parent_ == scene_ || !parent_)
  1259. {
  1260. worldTransform_ = transform;
  1261. worldRotation_ = rotation_;
  1262. }
  1263. else
  1264. {
  1265. worldTransform_ = parent_->GetWorldTransform() * transform;
  1266. worldRotation_ = parent_->GetWorldRotation() * rotation_;
  1267. }
  1268. dirty_ = false;
  1269. }
  1270. void Node::RemoveChild(Vector<SharedPtr<Node> >::Iterator i)
  1271. {
  1272. // Send change event. Do not send when already being destroyed
  1273. if (Refs() > 0 && scene_)
  1274. {
  1275. using namespace NodeRemoved;
  1276. VariantMap& eventData = GetEventDataMap();
  1277. eventData[P_SCENE] = scene_;
  1278. eventData[P_PARENT] = this;
  1279. eventData[P_NODE] = (*i).Get();
  1280. scene_->SendEvent(E_NODEREMOVED, eventData);
  1281. }
  1282. (*i)->parent_ = 0;
  1283. (*i)->MarkDirty();
  1284. (*i)->MarkNetworkUpdate();
  1285. children_.Erase(i);
  1286. }
  1287. void Node::GetChildrenRecursive(PODVector<Node*>& dest) const
  1288. {
  1289. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1290. {
  1291. Node* node = *i;
  1292. dest.Push(node);
  1293. if (!node->children_.Empty())
  1294. node->GetChildrenRecursive(dest);
  1295. }
  1296. }
  1297. void Node::GetChildrenWithComponentRecursive(PODVector<Node*>& dest, ShortStringHash type) const
  1298. {
  1299. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1300. {
  1301. Node* node = *i;
  1302. if (node->HasComponent(type))
  1303. dest.Push(node);
  1304. if (!node->children_.Empty())
  1305. node->GetChildrenWithComponentRecursive(dest, type);
  1306. }
  1307. }
  1308. void Node::GetComponentsRecursive(PODVector<Component*>& dest, ShortStringHash type) const
  1309. {
  1310. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  1311. {
  1312. if ((*i)->GetType() == type)
  1313. dest.Push(*i);
  1314. }
  1315. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1316. (*i)->GetComponentsRecursive(dest, type);
  1317. }
  1318. Node* Node::CloneRecursive(Node* parent, SceneResolver& resolver, CreateMode mode)
  1319. {
  1320. // Create clone node
  1321. Node* cloneNode = parent->CreateChild(0, (mode == REPLICATED && id_ < FIRST_LOCAL_ID) ? REPLICATED : LOCAL);
  1322. resolver.AddNode(id_, cloneNode);
  1323. // Copy attributes
  1324. const Vector<AttributeInfo>* attributes = GetAttributes();
  1325. for (unsigned j = 0; j < attributes->Size(); ++j)
  1326. {
  1327. const AttributeInfo& attr = attributes->At(j);
  1328. // Do not copy network-only attributes, as they may have unintended side effects
  1329. if (attr.mode_ & AM_FILE)
  1330. cloneNode->SetAttribute(j, GetAttribute(j));
  1331. }
  1332. // Clone components
  1333. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  1334. {
  1335. Component* component = *i;
  1336. Component* cloneComponent = cloneNode->SafeCreateComponent(component->GetTypeName(), component->GetType(),
  1337. (mode == REPLICATED && component->GetID() < FIRST_LOCAL_ID) ? REPLICATED : LOCAL, 0);
  1338. if (!cloneComponent)
  1339. {
  1340. LOGERROR("Could not clone component " + component->GetTypeName());
  1341. continue;
  1342. }
  1343. resolver.AddComponent(component->GetID(), cloneComponent);
  1344. const Vector<AttributeInfo>* compAttributes = component->GetAttributes();
  1345. if (compAttributes)
  1346. {
  1347. for (unsigned j = 0; j < compAttributes->Size(); ++j)
  1348. {
  1349. const AttributeInfo& attr = compAttributes->At(j);
  1350. if (attr.mode_ & AM_FILE)
  1351. cloneComponent->SetAttribute(j, component->GetAttribute(j));
  1352. }
  1353. }
  1354. }
  1355. // Clone child nodes recursively
  1356. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1357. {
  1358. Node* node = *i;
  1359. node->CloneRecursive(cloneNode, resolver, mode);
  1360. }
  1361. return cloneNode;
  1362. }
  1363. void Node::RemoveComponent(Vector<SharedPtr<Component> >::Iterator i)
  1364. {
  1365. WeakPtr<Component> componentWeak(*i);
  1366. // Send node change event. Do not send when already being destroyed
  1367. if (Refs() > 0 && scene_)
  1368. {
  1369. using namespace ComponentRemoved;
  1370. VariantMap& eventData = GetEventDataMap();
  1371. eventData[P_SCENE] = scene_;
  1372. eventData[P_NODE] = this;
  1373. eventData[P_COMPONENT] = (*i).Get();
  1374. scene_->SendEvent(E_COMPONENTREMOVED, eventData);
  1375. }
  1376. RemoveListener(*i);
  1377. if (scene_)
  1378. scene_->ComponentRemoved(*i);
  1379. components_.Erase(i);
  1380. // If the component is still referenced elsewhere, reset its node pointer now
  1381. if (componentWeak)
  1382. componentWeak->SetNode(0);
  1383. }
  1384. void Node::HandleScenePostUpdate(StringHash eventType, VariantMap& eventData)
  1385. {
  1386. using namespace ScenePostUpdate;
  1387. UpdateAttributeAnimations(eventData[P_TIMESTEP].GetFloat());
  1388. }
  1389. }