Node.cpp 58 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030
  1. //
  2. // Copyright (c) 2008-2015 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 "../Core/Context.h"
  24. #include "../Core/Profiler.h"
  25. #include "../IO/Log.h"
  26. #include "../IO/MemoryBuffer.h"
  27. #include "../Resource/XMLFile.h"
  28. #include "../Resource/JSONFile.h"
  29. #include "../Scene/Component.h"
  30. #include "../Scene/ObjectAnimation.h"
  31. #include "../Scene/ReplicationState.h"
  32. #include "../Scene/Scene.h"
  33. #include "../Scene/SceneEvents.h"
  34. #include "../Scene/SmoothedTransform.h"
  35. #include "../Scene/UnknownComponent.h"
  36. #include "../DebugNew.h"
  37. #ifdef _MSC_VER
  38. #pragma warning(disable:6293)
  39. #endif
  40. namespace Urho3D
  41. {
  42. Node::Node(Context* context) :
  43. Animatable(context),
  44. networkUpdate_(false),
  45. worldTransform_(Matrix3x4::IDENTITY),
  46. dirty_(false),
  47. enabled_(true),
  48. enabledPrev_(true),
  49. parent_(0),
  50. scene_(0),
  51. id_(0),
  52. position_(Vector3::ZERO),
  53. rotation_(Quaternion::IDENTITY),
  54. scale_(Vector3::ONE),
  55. worldRotation_(Quaternion::IDENTITY),
  56. owner_(0)
  57. {
  58. }
  59. Node::~Node()
  60. {
  61. RemoveAllChildren();
  62. RemoveAllComponents();
  63. // Remove from the scene
  64. if (scene_)
  65. scene_->NodeRemoved(this);
  66. }
  67. void Node::RegisterObject(Context* context)
  68. {
  69. context->RegisterFactory<Node>();
  70. URHO3D_ACCESSOR_ATTRIBUTE("Is Enabled", IsEnabled, SetEnabled, bool, true, AM_DEFAULT);
  71. URHO3D_ACCESSOR_ATTRIBUTE("Name", GetName, SetName, String, String::EMPTY, AM_DEFAULT);
  72. URHO3D_ACCESSOR_ATTRIBUTE("Position", GetPosition, SetPosition, Vector3, Vector3::ZERO, AM_FILE);
  73. URHO3D_ACCESSOR_ATTRIBUTE("Rotation", GetRotation, SetRotation, Quaternion, Quaternion::IDENTITY, AM_FILE);
  74. URHO3D_ACCESSOR_ATTRIBUTE("Scale", GetScale, SetScale, Vector3, Vector3::ONE, AM_DEFAULT);
  75. URHO3D_ATTRIBUTE("Variables", VariantMap, vars_, Variant::emptyVariantMap, AM_FILE); // Network replication of vars uses custom data
  76. URHO3D_ACCESSOR_ATTRIBUTE("Network Position", GetNetPositionAttr, SetNetPositionAttr, Vector3, Vector3::ZERO,
  77. AM_NET | AM_LATESTDATA | AM_NOEDIT);
  78. URHO3D_ACCESSOR_ATTRIBUTE("Network Rotation", GetNetRotationAttr, SetNetRotationAttr, PODVector<unsigned char>, Variant::emptyBuffer,
  79. AM_NET | AM_LATESTDATA | AM_NOEDIT);
  80. URHO3D_ACCESSOR_ATTRIBUTE("Network Parent Node", GetNetParentAttr, SetNetParentAttr, PODVector<unsigned char>, Variant::emptyBuffer,
  81. AM_NET | AM_NOEDIT);
  82. }
  83. bool Node::Load(Deserializer& source, bool setInstanceDefault)
  84. {
  85. SceneResolver resolver;
  86. // Read own ID. Will not be applied, only stored for resolving possible references
  87. unsigned nodeID = source.ReadUInt();
  88. resolver.AddNode(nodeID, this);
  89. // Read attributes, components and child nodes
  90. bool success = Load(source, resolver);
  91. if (success)
  92. {
  93. resolver.Resolve();
  94. ApplyAttributes();
  95. }
  96. return success;
  97. }
  98. bool Node::Save(Serializer& dest) const
  99. {
  100. // Write node ID
  101. if (!dest.WriteUInt(id_))
  102. return false;
  103. // Write attributes
  104. if (!Animatable::Save(dest))
  105. return false;
  106. // Write components
  107. dest.WriteVLE(GetNumPersistentComponents());
  108. for (unsigned i = 0; i < components_.Size(); ++i)
  109. {
  110. Component* component = components_[i];
  111. if (component->IsTemporary())
  112. continue;
  113. // Create a separate buffer to be able to skip failing components during deserialization
  114. VectorBuffer compBuffer;
  115. if (!component->Save(compBuffer))
  116. return false;
  117. dest.WriteVLE(compBuffer.GetSize());
  118. dest.Write(compBuffer.GetData(), compBuffer.GetSize());
  119. }
  120. // Write child nodes
  121. dest.WriteVLE(GetNumPersistentChildren());
  122. for (unsigned i = 0; i < children_.Size(); ++i)
  123. {
  124. Node* node = children_[i];
  125. if (node->IsTemporary())
  126. continue;
  127. if (!node->Save(dest))
  128. return false;
  129. }
  130. return true;
  131. }
  132. bool Node::LoadXML(const XMLElement& source, bool setInstanceDefault)
  133. {
  134. SceneResolver resolver;
  135. // Read own ID. Will not be applied, only stored for resolving possible references
  136. unsigned nodeID = source.GetUInt("id");
  137. resolver.AddNode(nodeID, this);
  138. // Read attributes, components and child nodes
  139. bool success = LoadXML(source, resolver);
  140. if (success)
  141. {
  142. resolver.Resolve();
  143. ApplyAttributes();
  144. }
  145. return success;
  146. }
  147. bool Node::LoadJSON(const JSONValue& source, bool setInstanceDefault)
  148. {
  149. SceneResolver resolver;
  150. // Read own ID. Will not be applied, only stored for resolving possible references
  151. unsigned nodeID = source.Get("id").GetUInt();
  152. resolver.AddNode(nodeID, this);
  153. // Read attributes, components and child nodes
  154. bool success = LoadJSON(source, resolver);
  155. if (success)
  156. {
  157. resolver.Resolve();
  158. ApplyAttributes();
  159. }
  160. return success;
  161. }
  162. bool Node::SaveXML(XMLElement& dest) const
  163. {
  164. // Write node ID
  165. if (!dest.SetUInt("id", id_))
  166. return false;
  167. // Write attributes
  168. if (!Animatable::SaveXML(dest))
  169. return false;
  170. // Write components
  171. for (unsigned i = 0; i < components_.Size(); ++i)
  172. {
  173. Component* component = components_[i];
  174. if (component->IsTemporary())
  175. continue;
  176. XMLElement compElem = dest.CreateChild("component");
  177. if (!component->SaveXML(compElem))
  178. return false;
  179. }
  180. // Write child nodes
  181. for (unsigned i = 0; i < children_.Size(); ++i)
  182. {
  183. Node* node = children_[i];
  184. if (node->IsTemporary())
  185. continue;
  186. XMLElement childElem = dest.CreateChild("node");
  187. if (!node->SaveXML(childElem))
  188. return false;
  189. }
  190. return true;
  191. }
  192. bool Node::SaveJSON(JSONValue& dest) const
  193. {
  194. // Write node ID
  195. dest.Set("id", (unsigned) id_);
  196. // Write attributes
  197. if (!Animatable::SaveJSON(dest))
  198. return false;
  199. // Write components
  200. JSONArray componentsArray;
  201. componentsArray.Reserve(components_.Size());
  202. for (unsigned i = 0; i < components_.Size(); ++i)
  203. {
  204. Component* component = components_[i];
  205. if (component->IsTemporary())
  206. continue;
  207. JSONValue compVal;
  208. if (!component->SaveJSON(compVal))
  209. return false;
  210. componentsArray.Push(compVal);
  211. }
  212. dest.Set("components", componentsArray);
  213. // Write child nodes
  214. JSONArray childrenArray;
  215. childrenArray.Reserve(children_.Size());
  216. for (unsigned i = 0; i < children_.Size(); ++i)
  217. {
  218. Node* node = children_[i];
  219. if (node->IsTemporary())
  220. continue;
  221. JSONValue childVal;
  222. if (!node->SaveJSON(childVal))
  223. return false;
  224. childrenArray.Push(childVal);
  225. }
  226. return true;
  227. }
  228. void Node::ApplyAttributes()
  229. {
  230. for (unsigned i = 0; i < components_.Size(); ++i)
  231. components_[i]->ApplyAttributes();
  232. for (unsigned i = 0; i < children_.Size(); ++i)
  233. children_[i]->ApplyAttributes();
  234. }
  235. void Node::MarkNetworkUpdate()
  236. {
  237. if (!networkUpdate_ && scene_ && id_ < FIRST_LOCAL_ID)
  238. {
  239. scene_->MarkNetworkUpdate(this);
  240. networkUpdate_ = true;
  241. }
  242. }
  243. void Node::AddReplicationState(NodeReplicationState* state)
  244. {
  245. if (!networkState_)
  246. AllocateNetworkState();
  247. networkState_->replicationStates_.Push(state);
  248. }
  249. bool Node::SaveXML(Serializer& dest, const String& indentation) const
  250. {
  251. SharedPtr<XMLFile> xml(new XMLFile(context_));
  252. XMLElement rootElem = xml->CreateRoot("node");
  253. if (!SaveXML(rootElem))
  254. return false;
  255. return xml->Save(dest, indentation);
  256. }
  257. bool Node::SaveJSON(Serializer& dest, const String& indentation) const
  258. {
  259. SharedPtr<JSONFile> json(new JSONFile(context_));
  260. JSONValue& rootElem = json->GetRoot();
  261. if (!SaveJSON(rootElem))
  262. return false;
  263. return json->Save(dest, indentation);
  264. }
  265. void Node::SetName(const String& name)
  266. {
  267. if (name != name_)
  268. {
  269. name_ = name;
  270. nameHash_ = name_;
  271. MarkNetworkUpdate();
  272. // Send change event
  273. if (scene_)
  274. {
  275. using namespace NodeNameChanged;
  276. VariantMap& eventData = GetEventDataMap();
  277. eventData[P_SCENE] = scene_;
  278. eventData[P_NODE] = this;
  279. scene_->SendEvent(E_NODENAMECHANGED, eventData);
  280. }
  281. }
  282. }
  283. void Node::SetPosition(const Vector3& position)
  284. {
  285. position_ = position;
  286. MarkDirty();
  287. MarkNetworkUpdate();
  288. }
  289. void Node::SetRotation(const Quaternion& rotation)
  290. {
  291. rotation_ = rotation;
  292. MarkDirty();
  293. MarkNetworkUpdate();
  294. }
  295. void Node::SetDirection(const Vector3& direction)
  296. {
  297. SetRotation(Quaternion(Vector3::FORWARD, direction));
  298. }
  299. void Node::SetScale(float scale)
  300. {
  301. SetScale(Vector3(scale, scale, scale));
  302. }
  303. void Node::SetScale(const Vector3& scale)
  304. {
  305. scale_ = scale;
  306. // Prevent exact zero scale e.g. from momentary edits as this may cause division by zero
  307. // when decomposing the world transform matrix
  308. if (scale_.x_ == 0.0f)
  309. scale_.x_ = M_EPSILON;
  310. if (scale_.y_ == 0.0f)
  311. scale_.y_ = M_EPSILON;
  312. if (scale_.z_ == 0.0f)
  313. scale_.z_ = M_EPSILON;
  314. MarkDirty();
  315. MarkNetworkUpdate();
  316. }
  317. void Node::SetTransform(const Vector3& position, const Quaternion& rotation)
  318. {
  319. position_ = position;
  320. rotation_ = rotation;
  321. MarkDirty();
  322. MarkNetworkUpdate();
  323. }
  324. void Node::SetTransform(const Vector3& position, const Quaternion& rotation, float scale)
  325. {
  326. SetTransform(position, rotation, Vector3(scale, scale, scale));
  327. }
  328. void Node::SetTransform(const Vector3& position, const Quaternion& rotation, const Vector3& scale)
  329. {
  330. position_ = position;
  331. rotation_ = rotation;
  332. scale_ = scale;
  333. MarkDirty();
  334. MarkNetworkUpdate();
  335. }
  336. void Node::SetWorldPosition(const Vector3& position)
  337. {
  338. SetPosition((parent_ == scene_ || !parent_) ? position : parent_->GetWorldTransform().Inverse() * position);
  339. }
  340. void Node::SetWorldRotation(const Quaternion& rotation)
  341. {
  342. SetRotation((parent_ == scene_ || !parent_) ? rotation : parent_->GetWorldRotation().Inverse() * rotation);
  343. }
  344. void Node::SetWorldDirection(const Vector3& direction)
  345. {
  346. Vector3 localDirection = (parent_ == scene_ || !parent_) ? direction : parent_->GetWorldRotation().Inverse() * direction;
  347. SetRotation(Quaternion(Vector3::FORWARD, localDirection));
  348. }
  349. void Node::SetWorldScale(float scale)
  350. {
  351. SetWorldScale(Vector3(scale, scale, scale));
  352. }
  353. void Node::SetWorldScale(const Vector3& scale)
  354. {
  355. SetScale((parent_ == scene_ || !parent_) ? scale : scale / parent_->GetWorldScale());
  356. }
  357. void Node::SetWorldTransform(const Vector3& position, const Quaternion& rotation)
  358. {
  359. SetWorldPosition(position);
  360. SetWorldRotation(rotation);
  361. }
  362. void Node::SetWorldTransform(const Vector3& position, const Quaternion& rotation, float scale)
  363. {
  364. SetWorldPosition(position);
  365. SetWorldRotation(rotation);
  366. SetWorldScale(scale);
  367. }
  368. void Node::SetWorldTransform(const Vector3& position, const Quaternion& rotation, const Vector3& scale)
  369. {
  370. SetWorldPosition(position);
  371. SetWorldRotation(rotation);
  372. SetWorldScale(scale);
  373. }
  374. void Node::Translate(const Vector3& delta, TransformSpace space)
  375. {
  376. switch (space)
  377. {
  378. case TS_LOCAL:
  379. // Note: local space translation disregards local scale for scale-independent movement speed
  380. position_ += rotation_ * delta;
  381. break;
  382. case TS_PARENT:
  383. position_ += delta;
  384. break;
  385. case TS_WORLD:
  386. position_ += (parent_ == scene_ || !parent_) ? delta : parent_->GetWorldTransform().Inverse() * Vector4(delta, 0.0f);
  387. break;
  388. }
  389. MarkDirty();
  390. MarkNetworkUpdate();
  391. }
  392. void Node::Rotate(const Quaternion& delta, TransformSpace space)
  393. {
  394. switch (space)
  395. {
  396. case TS_LOCAL:
  397. rotation_ = (rotation_ * delta).Normalized();
  398. break;
  399. case TS_PARENT:
  400. rotation_ = (delta * rotation_).Normalized();
  401. break;
  402. case TS_WORLD:
  403. if (parent_ == scene_ || !parent_)
  404. rotation_ = (delta * rotation_).Normalized();
  405. else
  406. {
  407. Quaternion worldRotation = GetWorldRotation();
  408. rotation_ = rotation_ * worldRotation.Inverse() * delta * worldRotation;
  409. }
  410. break;
  411. }
  412. MarkDirty();
  413. MarkNetworkUpdate();
  414. }
  415. void Node::RotateAround(const Vector3& point, const Quaternion& delta, TransformSpace space)
  416. {
  417. Vector3 parentSpacePoint;
  418. Quaternion oldRotation = rotation_;
  419. switch (space)
  420. {
  421. case TS_LOCAL:
  422. parentSpacePoint = GetTransform() * point;
  423. rotation_ = (rotation_ * delta).Normalized();
  424. break;
  425. case TS_PARENT:
  426. parentSpacePoint = point;
  427. rotation_ = (delta * rotation_).Normalized();
  428. break;
  429. case TS_WORLD:
  430. if (parent_ == scene_ || !parent_)
  431. {
  432. parentSpacePoint = point;
  433. rotation_ = (delta * rotation_).Normalized();
  434. }
  435. else
  436. {
  437. parentSpacePoint = parent_->GetWorldTransform().Inverse() * point;
  438. Quaternion worldRotation = GetWorldRotation();
  439. rotation_ = rotation_ * worldRotation.Inverse() * delta * worldRotation;
  440. }
  441. break;
  442. }
  443. Vector3 oldRelativePos = oldRotation.Inverse() * (position_ - parentSpacePoint);
  444. position_ = rotation_ * oldRelativePos + parentSpacePoint;
  445. MarkDirty();
  446. MarkNetworkUpdate();
  447. }
  448. void Node::Yaw(float angle, TransformSpace space)
  449. {
  450. Rotate(Quaternion(angle, Vector3::UP), space);
  451. }
  452. void Node::Pitch(float angle, TransformSpace space)
  453. {
  454. Rotate(Quaternion(angle, Vector3::RIGHT), space);
  455. }
  456. void Node::Roll(float angle, TransformSpace space)
  457. {
  458. Rotate(Quaternion(angle, Vector3::FORWARD), space);
  459. }
  460. bool Node::LookAt(const Vector3& target, const Vector3& up, TransformSpace space)
  461. {
  462. Vector3 worldSpaceTarget;
  463. switch (space)
  464. {
  465. case TS_LOCAL:
  466. worldSpaceTarget = GetWorldTransform() * target;
  467. break;
  468. case TS_PARENT:
  469. worldSpaceTarget = (parent_ == scene_ || !parent_) ? target : parent_->GetWorldTransform() * target;
  470. break;
  471. case TS_WORLD:
  472. worldSpaceTarget = target;
  473. break;
  474. }
  475. Vector3 lookDir = worldSpaceTarget - GetWorldPosition();
  476. // Check if target is very close, in that case can not reliably calculate lookat direction
  477. if (lookDir.Equals(Vector3::ZERO))
  478. return false;
  479. Quaternion newRotation;
  480. // Do nothing if setting look rotation failed
  481. if (!newRotation.FromLookRotation(lookDir, up))
  482. return false;
  483. SetWorldRotation(newRotation);
  484. return true;
  485. }
  486. void Node::Scale(float scale)
  487. {
  488. Scale(Vector3(scale, scale, scale));
  489. }
  490. void Node::Scale(const Vector3& scale)
  491. {
  492. scale_ *= scale;
  493. MarkDirty();
  494. MarkNetworkUpdate();
  495. }
  496. void Node::SetEnabled(bool enable)
  497. {
  498. SetEnabled(enable, false, true);
  499. }
  500. void Node::SetDeepEnabled(bool enable)
  501. {
  502. SetEnabled(enable, true, false);
  503. }
  504. void Node::ResetDeepEnabled()
  505. {
  506. SetEnabled(enabledPrev_, false, false);
  507. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  508. (*i)->ResetDeepEnabled();
  509. }
  510. void Node::SetEnabledRecursive(bool enable)
  511. {
  512. SetEnabled(enable, true, true);
  513. }
  514. void Node::SetOwner(Connection* owner)
  515. {
  516. owner_ = owner;
  517. }
  518. void Node::MarkDirty()
  519. {
  520. Node *cur = this;
  521. for (;;)
  522. {
  523. // Precondition:
  524. // a) whenever a node is marked dirty, all its children are marked dirty as well.
  525. // b) whenever a node is cleared from being dirty, all its parents must have been
  526. // cleared as well.
  527. // Therefore if we are recursing here to mark this node dirty, and it already was,
  528. // then all children of this node must also be already dirty, and we don't need to
  529. // reflag them again.
  530. if (cur->dirty_)
  531. return;
  532. cur->dirty_ = true;
  533. // Notify listener components first, then mark child nodes
  534. for (Vector<WeakPtr<Component> >::Iterator i = cur->listeners_.Begin(); i != cur->listeners_.End();)
  535. {
  536. Component *c = *i;
  537. if (c)
  538. {
  539. c->OnMarkedDirty(cur);
  540. ++i;
  541. }
  542. // If listener has expired, erase from list (swap with the last element to avoid O(n^2) behavior)
  543. else
  544. {
  545. *i = cur->listeners_.Back();
  546. cur->listeners_.Pop();
  547. }
  548. }
  549. // Tail call optimization: Don't recurse to mark the first child dirty, but
  550. // instead process it in the context of the current function. If there are more
  551. // than one child, then recurse to the excess children.
  552. Vector<SharedPtr<Node> >::Iterator i = cur->children_.Begin();
  553. if (i != cur->children_.End())
  554. {
  555. Node *next = *i;
  556. for (++i; i != cur->children_.End(); ++i)
  557. (*i)->MarkDirty();
  558. cur = next;
  559. }
  560. else
  561. return;
  562. }
  563. }
  564. Node* Node::CreateChild(const String& name, CreateMode mode, unsigned id)
  565. {
  566. Node* newNode = CreateChild(id, mode);
  567. newNode->SetName(name);
  568. return newNode;
  569. }
  570. void Node::AddChild(Node* node, unsigned index)
  571. {
  572. // Check for illegal or redundant parent assignment
  573. if (!node || node == this || node->parent_ == this)
  574. return;
  575. // Check for possible cyclic parent assignment
  576. Node* parent = parent_;
  577. while (parent)
  578. {
  579. if (parent == node)
  580. return;
  581. parent = parent->parent_;
  582. }
  583. // Keep a shared ptr to the node while transfering
  584. SharedPtr<Node> nodeShared(node);
  585. Node* oldParent = node->parent_;
  586. if (oldParent)
  587. {
  588. // If old parent is in different scene, perform the full removal
  589. if (oldParent->GetScene() != scene_)
  590. oldParent->RemoveChild(node);
  591. else
  592. {
  593. if (scene_)
  594. {
  595. // Otherwise do not remove from the scene during reparenting, just send the necessary change event
  596. using namespace NodeRemoved;
  597. VariantMap& eventData = GetEventDataMap();
  598. eventData[P_SCENE] = scene_;
  599. eventData[P_PARENT] = oldParent;
  600. eventData[P_NODE] = node;
  601. scene_->SendEvent(E_NODEREMOVED, eventData);
  602. }
  603. oldParent->children_.Remove(nodeShared);
  604. }
  605. }
  606. // Add to the child vector, then add to the scene if not added yet
  607. children_.Insert(index, nodeShared);
  608. if (scene_ && node->GetScene() != scene_)
  609. scene_->NodeAdded(node);
  610. node->parent_ = this;
  611. node->MarkDirty();
  612. node->MarkNetworkUpdate();
  613. // Send change event
  614. if (scene_)
  615. {
  616. using namespace NodeAdded;
  617. VariantMap& eventData = GetEventDataMap();
  618. eventData[P_SCENE] = scene_;
  619. eventData[P_PARENT] = this;
  620. eventData[P_NODE] = node;
  621. scene_->SendEvent(E_NODEADDED, eventData);
  622. }
  623. }
  624. void Node::RemoveChild(Node* node)
  625. {
  626. if (!node)
  627. return;
  628. for (Vector<SharedPtr<Node> >::Iterator i = children_.Begin(); i != children_.End(); ++i)
  629. {
  630. if (*i == node)
  631. {
  632. RemoveChild(i);
  633. return;
  634. }
  635. }
  636. }
  637. void Node::RemoveAllChildren()
  638. {
  639. RemoveChildren(true, true, true);
  640. }
  641. void Node::RemoveChildren(bool removeReplicated, bool removeLocal, bool recursive)
  642. {
  643. unsigned numRemoved = 0;
  644. for (unsigned i = children_.Size() - 1; i < children_.Size(); --i)
  645. {
  646. bool remove = false;
  647. Node* childNode = children_[i];
  648. if (recursive)
  649. childNode->RemoveChildren(removeReplicated, removeLocal, true);
  650. if (childNode->GetID() < FIRST_LOCAL_ID && removeReplicated)
  651. remove = true;
  652. else if (childNode->GetID() >= FIRST_LOCAL_ID && removeLocal)
  653. remove = true;
  654. if (remove)
  655. {
  656. RemoveChild(children_.Begin() + i);
  657. ++numRemoved;
  658. }
  659. }
  660. // Mark node dirty in all replication states
  661. if (numRemoved)
  662. MarkReplicationDirty();
  663. }
  664. Component* Node::CreateComponent(StringHash type, CreateMode mode, unsigned id)
  665. {
  666. // Do not attempt to create replicated components to local nodes, as that may lead to component ID overwrite
  667. // as replicated components are synced over
  668. if (id_ >= FIRST_LOCAL_ID && mode == REPLICATED)
  669. mode = LOCAL;
  670. // Check that creation succeeds and that the object in fact is a component
  671. SharedPtr<Component> newComponent = DynamicCast<Component>(context_->CreateObject(type));
  672. if (!newComponent)
  673. {
  674. URHO3D_LOGERROR("Could not create unknown component type " + type.ToString());
  675. return 0;
  676. }
  677. AddComponent(newComponent, id, mode);
  678. return newComponent;
  679. }
  680. Component* Node::GetOrCreateComponent(StringHash type, CreateMode mode, unsigned id)
  681. {
  682. Component* oldComponent = GetComponent(type);
  683. if (oldComponent)
  684. return oldComponent;
  685. else
  686. return CreateComponent(type, mode, id);
  687. }
  688. Component* Node::CloneComponent(Component* component, unsigned id)
  689. {
  690. if (!component)
  691. {
  692. URHO3D_LOGERROR("Null source component given for CloneComponent");
  693. return 0;
  694. }
  695. return CloneComponent(component, component->GetID() < FIRST_LOCAL_ID ? REPLICATED : LOCAL, id);
  696. }
  697. Component* Node::CloneComponent(Component* component, CreateMode mode, unsigned id)
  698. {
  699. if (!component)
  700. {
  701. URHO3D_LOGERROR("Null source component given for CloneComponent");
  702. return 0;
  703. }
  704. Component* cloneComponent = SafeCreateComponent(component->GetTypeName(), component->GetType(), mode, 0);
  705. if (!cloneComponent)
  706. {
  707. URHO3D_LOGERROR("Could not clone component " + component->GetTypeName());
  708. return 0;
  709. }
  710. const Vector<AttributeInfo>* compAttributes = component->GetAttributes();
  711. const Vector<AttributeInfo>* cloneAttributes = cloneComponent->GetAttributes();
  712. if (compAttributes)
  713. {
  714. for (unsigned i = 0; i < compAttributes->Size() && i < cloneAttributes->Size(); ++i)
  715. {
  716. const AttributeInfo& attr = compAttributes->At(i);
  717. const AttributeInfo& cloneAttr = cloneAttributes->At(i);
  718. if (attr.mode_ & AM_FILE)
  719. {
  720. Variant value;
  721. component->OnGetAttribute(attr, value);
  722. // Note: when eg. a ScriptInstance component is cloned, its script object attributes are unique and therefore we
  723. // can not simply refer to the source component's AttributeInfo
  724. cloneComponent->OnSetAttribute(cloneAttr, value);
  725. }
  726. }
  727. cloneComponent->ApplyAttributes();
  728. }
  729. return cloneComponent;
  730. }
  731. void Node::RemoveComponent(Component* component)
  732. {
  733. for (Vector<SharedPtr<Component> >::Iterator i = components_.Begin(); i != components_.End(); ++i)
  734. {
  735. if (*i == component)
  736. {
  737. RemoveComponent(i);
  738. // Mark node dirty in all replication states
  739. MarkReplicationDirty();
  740. return;
  741. }
  742. }
  743. }
  744. void Node::RemoveComponent(StringHash type)
  745. {
  746. for (Vector<SharedPtr<Component> >::Iterator i = components_.Begin(); i != components_.End(); ++i)
  747. {
  748. if ((*i)->GetType() == type)
  749. {
  750. RemoveComponent(i);
  751. // Mark node dirty in all replication states
  752. MarkReplicationDirty();
  753. return;
  754. }
  755. }
  756. }
  757. void Node::RemoveComponents(bool removeReplicated, bool removeLocal)
  758. {
  759. unsigned numRemoved = 0;
  760. for (unsigned i = components_.Size() - 1; i < components_.Size(); --i)
  761. {
  762. bool remove = false;
  763. Component* component = components_[i];
  764. if (component->GetID() < FIRST_LOCAL_ID && removeReplicated)
  765. remove = true;
  766. else if (component->GetID() >= FIRST_LOCAL_ID && removeLocal)
  767. remove = true;
  768. if (remove)
  769. {
  770. RemoveComponent(components_.Begin() + i);
  771. ++numRemoved;
  772. }
  773. }
  774. // Mark node dirty in all replication states
  775. if (numRemoved)
  776. MarkReplicationDirty();
  777. }
  778. void Node::RemoveComponents(StringHash type)
  779. {
  780. unsigned numRemoved = 0;
  781. for (unsigned i = components_.Size() - 1; i < components_.Size(); --i)
  782. {
  783. if (components_[i]->GetType() == type)
  784. {
  785. RemoveComponent(components_.Begin() + i);
  786. ++numRemoved;
  787. }
  788. }
  789. // Mark node dirty in all replication states
  790. if (numRemoved)
  791. MarkReplicationDirty();
  792. }
  793. void Node::RemoveAllComponents()
  794. {
  795. RemoveComponents(true, true);
  796. }
  797. Node* Node::Clone(CreateMode mode)
  798. {
  799. // The scene itself can not be cloned
  800. if (this == scene_ || !parent_)
  801. {
  802. URHO3D_LOGERROR("Can not clone node without a parent");
  803. return 0;
  804. }
  805. URHO3D_PROFILE(CloneNode);
  806. SceneResolver resolver;
  807. Node* clone = CloneRecursive(parent_, resolver, mode);
  808. resolver.Resolve();
  809. clone->ApplyAttributes();
  810. return clone;
  811. }
  812. void Node::Remove()
  813. {
  814. if (parent_)
  815. parent_->RemoveChild(this);
  816. }
  817. void Node::SetParent(Node* parent)
  818. {
  819. if (parent)
  820. {
  821. Matrix3x4 oldWorldTransform = GetWorldTransform();
  822. parent->AddChild(this);
  823. if (parent != scene_)
  824. {
  825. Matrix3x4 newTransform = parent->GetWorldTransform().Inverse() * oldWorldTransform;
  826. SetTransform(newTransform.Translation(), newTransform.Rotation(), newTransform.Scale());
  827. }
  828. else
  829. {
  830. // The root node is assumed to have identity transform, so can disregard it
  831. SetTransform(oldWorldTransform.Translation(), oldWorldTransform.Rotation(), oldWorldTransform.Scale());
  832. }
  833. }
  834. }
  835. void Node::SetVar(StringHash key, const Variant& value)
  836. {
  837. vars_[key] = value;
  838. MarkNetworkUpdate();
  839. }
  840. void Node::AddListener(Component* component)
  841. {
  842. if (!component)
  843. return;
  844. // Check for not adding twice
  845. for (Vector<WeakPtr<Component> >::Iterator i = listeners_.Begin(); i != listeners_.End(); ++i)
  846. {
  847. if (*i == component)
  848. return;
  849. }
  850. listeners_.Push(WeakPtr<Component>(component));
  851. // If the node is currently dirty, notify immediately
  852. if (dirty_)
  853. component->OnMarkedDirty(this);
  854. }
  855. void Node::RemoveListener(Component* component)
  856. {
  857. for (Vector<WeakPtr<Component> >::Iterator i = listeners_.Begin(); i != listeners_.End(); ++i)
  858. {
  859. if (*i == component)
  860. {
  861. listeners_.Erase(i);
  862. return;
  863. }
  864. }
  865. }
  866. Vector3 Node::LocalToWorld(const Vector3& position) const
  867. {
  868. return GetWorldTransform() * position;
  869. }
  870. Vector3 Node::LocalToWorld(const Vector4& vector) const
  871. {
  872. return GetWorldTransform() * vector;
  873. }
  874. Vector2 Node::LocalToWorld2D(const Vector2& vector) const
  875. {
  876. Vector3 result = LocalToWorld(Vector3(vector));
  877. return Vector2(result.x_, result.y_);
  878. }
  879. Vector3 Node::WorldToLocal(const Vector3& position) const
  880. {
  881. return GetWorldTransform().Inverse() * position;
  882. }
  883. Vector3 Node::WorldToLocal(const Vector4& vector) const
  884. {
  885. return GetWorldTransform().Inverse() * vector;
  886. }
  887. Vector2 Node::WorldToLocal2D(const Vector2& vector) const
  888. {
  889. Vector3 result = WorldToLocal(Vector3(vector));
  890. return Vector2(result.x_, result.y_);
  891. }
  892. unsigned Node::GetNumChildren(bool recursive) const
  893. {
  894. if (!recursive)
  895. return children_.Size();
  896. else
  897. {
  898. unsigned allChildren = children_.Size();
  899. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  900. allChildren += (*i)->GetNumChildren(true);
  901. return allChildren;
  902. }
  903. }
  904. void Node::GetChildren(PODVector<Node*>& dest, bool recursive) const
  905. {
  906. dest.Clear();
  907. if (!recursive)
  908. {
  909. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  910. dest.Push(*i);
  911. }
  912. else
  913. GetChildrenRecursive(dest);
  914. }
  915. void Node::GetChildrenWithComponent(PODVector<Node*>& dest, StringHash type, bool recursive) const
  916. {
  917. dest.Clear();
  918. if (!recursive)
  919. {
  920. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  921. {
  922. if ((*i)->HasComponent(type))
  923. dest.Push(*i);
  924. }
  925. }
  926. else
  927. GetChildrenWithComponentRecursive(dest, type);
  928. }
  929. Node* Node::GetChild(unsigned index) const
  930. {
  931. return index < children_.Size() ? children_[index].Get() : 0;
  932. }
  933. Node* Node::GetChild(const String& name, bool recursive) const
  934. {
  935. return GetChild(StringHash(name), recursive);
  936. }
  937. Node* Node::GetChild(const char* name, bool recursive) const
  938. {
  939. return GetChild(StringHash(name), recursive);
  940. }
  941. Node* Node::GetChild(StringHash nameHash, bool recursive) const
  942. {
  943. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  944. {
  945. if ((*i)->GetNameHash() == nameHash)
  946. return *i;
  947. if (recursive)
  948. {
  949. Node* node = (*i)->GetChild(nameHash, true);
  950. if (node)
  951. return node;
  952. }
  953. }
  954. return 0;
  955. }
  956. unsigned Node::GetNumNetworkComponents() const
  957. {
  958. unsigned num = 0;
  959. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  960. {
  961. if ((*i)->GetID() < FIRST_LOCAL_ID)
  962. ++num;
  963. }
  964. return num;
  965. }
  966. void Node::GetComponents(PODVector<Component*>& dest, StringHash type, bool recursive) const
  967. {
  968. dest.Clear();
  969. if (!recursive)
  970. {
  971. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  972. {
  973. if ((*i)->GetType() == type)
  974. dest.Push(*i);
  975. }
  976. }
  977. else
  978. GetComponentsRecursive(dest, type);
  979. }
  980. bool Node::HasComponent(StringHash type) const
  981. {
  982. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  983. {
  984. if ((*i)->GetType() == type)
  985. return true;
  986. }
  987. return false;
  988. }
  989. const Variant& Node::GetVar(StringHash key) const
  990. {
  991. VariantMap::ConstIterator i = vars_.Find(key);
  992. return i != vars_.End() ? i->second_ : Variant::EMPTY;
  993. }
  994. Component* Node::GetComponent(StringHash type, bool recursive) const
  995. {
  996. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  997. {
  998. if ((*i)->GetType() == type)
  999. return *i;
  1000. }
  1001. if (recursive)
  1002. {
  1003. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1004. {
  1005. Component* component = (*i)->GetComponent(type, true);
  1006. if (component)
  1007. return component;
  1008. }
  1009. }
  1010. return 0;
  1011. }
  1012. Component* Node::GetParentComponent(StringHash type, bool fullTraversal) const
  1013. {
  1014. Node* current = GetParent();
  1015. while (current)
  1016. {
  1017. Component* soughtComponent = current->GetComponent(type);
  1018. if (soughtComponent)
  1019. return soughtComponent;
  1020. if (fullTraversal)
  1021. current = current->GetParent();
  1022. else
  1023. break;
  1024. }
  1025. return 0;
  1026. }
  1027. void Node::SetID(unsigned id)
  1028. {
  1029. id_ = id;
  1030. }
  1031. void Node::SetScene(Scene* scene)
  1032. {
  1033. scene_ = scene;
  1034. }
  1035. void Node::ResetScene()
  1036. {
  1037. SetID(0);
  1038. SetScene(0);
  1039. SetOwner(0);
  1040. }
  1041. void Node::SetNetPositionAttr(const Vector3& value)
  1042. {
  1043. SmoothedTransform* transform = GetComponent<SmoothedTransform>();
  1044. if (transform)
  1045. transform->SetTargetPosition(value);
  1046. else
  1047. SetPosition(value);
  1048. }
  1049. void Node::SetNetRotationAttr(const PODVector<unsigned char>& value)
  1050. {
  1051. MemoryBuffer buf(value);
  1052. SmoothedTransform* transform = GetComponent<SmoothedTransform>();
  1053. if (transform)
  1054. transform->SetTargetRotation(buf.ReadPackedQuaternion());
  1055. else
  1056. SetRotation(buf.ReadPackedQuaternion());
  1057. }
  1058. void Node::SetNetParentAttr(const PODVector<unsigned char>& value)
  1059. {
  1060. Scene* scene = GetScene();
  1061. if (!scene)
  1062. return;
  1063. MemoryBuffer buf(value);
  1064. // If nothing in the buffer, parent is the root node
  1065. if (buf.IsEof())
  1066. {
  1067. scene->AddChild(this);
  1068. return;
  1069. }
  1070. unsigned baseNodeID = buf.ReadNetID();
  1071. Node* baseNode = scene->GetNode(baseNodeID);
  1072. if (!baseNode)
  1073. {
  1074. URHO3D_LOGWARNING("Failed to find parent node " + String(baseNodeID));
  1075. return;
  1076. }
  1077. // If buffer contains just an ID, the parent is replicated and we are done
  1078. if (buf.IsEof())
  1079. baseNode->AddChild(this);
  1080. else
  1081. {
  1082. // Else the parent is local and we must find it recursively by name hash
  1083. StringHash nameHash = buf.ReadStringHash();
  1084. Node* parentNode = baseNode->GetChild(nameHash, true);
  1085. if (!parentNode)
  1086. URHO3D_LOGWARNING("Failed to find parent node with name hash " + nameHash.ToString());
  1087. else
  1088. parentNode->AddChild(this);
  1089. }
  1090. }
  1091. const Vector3& Node::GetNetPositionAttr() const
  1092. {
  1093. return position_;
  1094. }
  1095. const PODVector<unsigned char>& Node::GetNetRotationAttr() const
  1096. {
  1097. attrBuffer_.Clear();
  1098. attrBuffer_.WritePackedQuaternion(rotation_);
  1099. return attrBuffer_.GetBuffer();
  1100. }
  1101. const PODVector<unsigned char>& Node::GetNetParentAttr() const
  1102. {
  1103. attrBuffer_.Clear();
  1104. Scene* scene = GetScene();
  1105. if (scene && parent_ && parent_ != scene)
  1106. {
  1107. // If parent is replicated, can write the ID directly
  1108. unsigned parentID = parent_->GetID();
  1109. if (parentID < FIRST_LOCAL_ID)
  1110. attrBuffer_.WriteNetID(parentID);
  1111. else
  1112. {
  1113. // Parent is local: traverse hierarchy to find a non-local base node
  1114. // This iteration always stops due to the scene (root) being non-local
  1115. Node* current = parent_;
  1116. while (current->GetID() >= FIRST_LOCAL_ID)
  1117. current = current->GetParent();
  1118. // Then write the base node ID and the parent's name hash
  1119. attrBuffer_.WriteNetID(current->GetID());
  1120. attrBuffer_.WriteStringHash(parent_->GetNameHash());
  1121. }
  1122. }
  1123. return attrBuffer_.GetBuffer();
  1124. }
  1125. bool Node::Load(Deserializer& source, SceneResolver& resolver, bool readChildren, bool rewriteIDs, CreateMode mode)
  1126. {
  1127. // Remove all children and components first in case this is not a fresh load
  1128. RemoveAllChildren();
  1129. RemoveAllComponents();
  1130. // ID has been read at the parent level
  1131. if (!Animatable::Load(source))
  1132. return false;
  1133. unsigned numComponents = source.ReadVLE();
  1134. for (unsigned i = 0; i < numComponents; ++i)
  1135. {
  1136. VectorBuffer compBuffer(source, source.ReadVLE());
  1137. StringHash compType = compBuffer.ReadStringHash();
  1138. unsigned compID = compBuffer.ReadUInt();
  1139. Component* newComponent = SafeCreateComponent(String::EMPTY, compType,
  1140. (mode == REPLICATED && compID < FIRST_LOCAL_ID) ? REPLICATED : LOCAL, rewriteIDs ? 0 : compID);
  1141. if (newComponent)
  1142. {
  1143. resolver.AddComponent(compID, newComponent);
  1144. // Do not abort if component fails to load, as the component buffer is nested and we can skip to the next
  1145. newComponent->Load(compBuffer);
  1146. }
  1147. }
  1148. if (!readChildren)
  1149. return true;
  1150. unsigned numChildren = source.ReadVLE();
  1151. for (unsigned i = 0; i < numChildren; ++i)
  1152. {
  1153. unsigned nodeID = source.ReadUInt();
  1154. Node* newNode = CreateChild(rewriteIDs ? 0 : nodeID, (mode == REPLICATED && nodeID < FIRST_LOCAL_ID) ? REPLICATED :
  1155. LOCAL);
  1156. resolver.AddNode(nodeID, newNode);
  1157. if (!newNode->Load(source, resolver, readChildren, rewriteIDs, mode))
  1158. return false;
  1159. }
  1160. return true;
  1161. }
  1162. bool Node::LoadXML(const XMLElement& source, SceneResolver& resolver, bool readChildren, bool rewriteIDs, CreateMode mode)
  1163. {
  1164. // Remove all children and components first in case this is not a fresh load
  1165. RemoveAllChildren();
  1166. RemoveAllComponents();
  1167. if (!Animatable::LoadXML(source))
  1168. return false;
  1169. XMLElement compElem = source.GetChild("component");
  1170. while (compElem)
  1171. {
  1172. String typeName = compElem.GetAttribute("type");
  1173. unsigned compID = compElem.GetUInt("id");
  1174. Component* newComponent = SafeCreateComponent(typeName, StringHash(typeName),
  1175. (mode == REPLICATED && compID < FIRST_LOCAL_ID) ? REPLICATED : LOCAL, rewriteIDs ? 0 : compID);
  1176. if (newComponent)
  1177. {
  1178. resolver.AddComponent(compID, newComponent);
  1179. if (!newComponent->LoadXML(compElem))
  1180. return false;
  1181. }
  1182. compElem = compElem.GetNext("component");
  1183. }
  1184. if (!readChildren)
  1185. return true;
  1186. XMLElement childElem = source.GetChild("node");
  1187. while (childElem)
  1188. {
  1189. unsigned nodeID = childElem.GetUInt("id");
  1190. Node* newNode = CreateChild(rewriteIDs ? 0 : nodeID, (mode == REPLICATED && nodeID < FIRST_LOCAL_ID) ? REPLICATED :
  1191. LOCAL);
  1192. resolver.AddNode(nodeID, newNode);
  1193. if (!newNode->LoadXML(childElem, resolver, readChildren, rewriteIDs, mode))
  1194. return false;
  1195. childElem = childElem.GetNext("node");
  1196. }
  1197. return true;
  1198. }
  1199. bool Node::LoadJSON(const JSONValue& source, SceneResolver& resolver, bool readChildren, bool rewriteIDs, CreateMode mode)
  1200. {
  1201. // Remove all children and components first in case this is not a fresh load
  1202. RemoveAllChildren();
  1203. RemoveAllComponents();
  1204. if (!Animatable::LoadJSON(source))
  1205. return false;
  1206. const JSONArray& componentsArray = source.Get("components").GetArray();
  1207. for (unsigned i = 0; i < componentsArray.Size(); i++)
  1208. {
  1209. const JSONValue& compVal = componentsArray.At(i);
  1210. String typeName = compVal.Get("type").GetString();
  1211. unsigned compID = compVal.Get("id").GetUInt();
  1212. Component* newComponent = SafeCreateComponent(typeName, StringHash(typeName),
  1213. (mode == REPLICATED && compID < FIRST_LOCAL_ID) ? REPLICATED : LOCAL, rewriteIDs ? 0 : compID);
  1214. if (newComponent)
  1215. {
  1216. resolver.AddComponent(compID, newComponent);
  1217. if (!newComponent->LoadJSON(compVal))
  1218. return false;
  1219. }
  1220. }
  1221. if (!readChildren)
  1222. return true;
  1223. const JSONArray& childrenArray = source.Get("children").GetArray();
  1224. for (unsigned i = 0; i < childrenArray.Size(); i++)
  1225. {
  1226. const JSONValue& childVal = childrenArray.At(i);
  1227. unsigned nodeID = childVal.Get("id").GetUInt();
  1228. Node* newNode = CreateChild(rewriteIDs ? 0 : nodeID, (mode == REPLICATED && nodeID < FIRST_LOCAL_ID) ? REPLICATED :
  1229. LOCAL);
  1230. resolver.AddNode(nodeID, newNode);
  1231. if (!newNode->LoadJSON(childVal, resolver, readChildren, rewriteIDs, mode))
  1232. return false;
  1233. }
  1234. return true;
  1235. }
  1236. void Node::PrepareNetworkUpdate()
  1237. {
  1238. // Update dependency nodes list first
  1239. dependencyNodes_.Clear();
  1240. // Add the parent node, but if it is local, traverse to the first non-local node
  1241. if (parent_ && parent_ != scene_)
  1242. {
  1243. Node* current = parent_;
  1244. while (current->id_ >= FIRST_LOCAL_ID)
  1245. current = current->parent_;
  1246. if (current && current != scene_)
  1247. dependencyNodes_.Push(current);
  1248. }
  1249. // Let the components add their dependencies
  1250. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  1251. {
  1252. Component* component = *i;
  1253. if (component->GetID() < FIRST_LOCAL_ID)
  1254. component->GetDependencyNodes(dependencyNodes_);
  1255. }
  1256. // Then check for node attribute changes
  1257. if (!networkState_)
  1258. AllocateNetworkState();
  1259. const Vector<AttributeInfo>* attributes = networkState_->attributes_;
  1260. unsigned numAttributes = attributes->Size();
  1261. if (networkState_->currentValues_.Size() != numAttributes)
  1262. {
  1263. networkState_->currentValues_.Resize(numAttributes);
  1264. networkState_->previousValues_.Resize(numAttributes);
  1265. // Copy the default attribute values to the previous state as a starting point
  1266. for (unsigned i = 0; i < numAttributes; ++i)
  1267. networkState_->previousValues_[i] = attributes->At(i).defaultValue_;
  1268. }
  1269. // Check for attribute changes
  1270. for (unsigned i = 0; i < numAttributes; ++i)
  1271. {
  1272. const AttributeInfo& attr = attributes->At(i);
  1273. if (animationEnabled_ && IsAnimatedNetworkAttribute(attr))
  1274. continue;
  1275. OnGetAttribute(attr, networkState_->currentValues_[i]);
  1276. if (networkState_->currentValues_[i] != networkState_->previousValues_[i])
  1277. {
  1278. networkState_->previousValues_[i] = networkState_->currentValues_[i];
  1279. // Mark the attribute dirty in all replication states that are tracking this node
  1280. for (PODVector<ReplicationState*>::Iterator j = networkState_->replicationStates_.Begin();
  1281. j != networkState_->replicationStates_.End(); ++j)
  1282. {
  1283. NodeReplicationState* nodeState = static_cast<NodeReplicationState*>(*j);
  1284. nodeState->dirtyAttributes_.Set(i);
  1285. // Add node to the dirty set if not added yet
  1286. if (!nodeState->markedDirty_)
  1287. {
  1288. nodeState->markedDirty_ = true;
  1289. nodeState->sceneState_->dirtyNodes_.Insert(id_);
  1290. }
  1291. }
  1292. }
  1293. }
  1294. // Finally check for user var changes
  1295. for (VariantMap::ConstIterator i = vars_.Begin(); i != vars_.End(); ++i)
  1296. {
  1297. VariantMap::ConstIterator j = networkState_->previousVars_.Find(i->first_);
  1298. if (j == networkState_->previousVars_.End() || j->second_ != i->second_)
  1299. {
  1300. networkState_->previousVars_[i->first_] = i->second_;
  1301. // Mark the var dirty in all replication states that are tracking this node
  1302. for (PODVector<ReplicationState*>::Iterator j = networkState_->replicationStates_.Begin();
  1303. j != networkState_->replicationStates_.End(); ++j)
  1304. {
  1305. NodeReplicationState* nodeState = static_cast<NodeReplicationState*>(*j);
  1306. nodeState->dirtyVars_.Insert(i->first_);
  1307. if (!nodeState->markedDirty_)
  1308. {
  1309. nodeState->markedDirty_ = true;
  1310. nodeState->sceneState_->dirtyNodes_.Insert(id_);
  1311. }
  1312. }
  1313. }
  1314. }
  1315. networkUpdate_ = false;
  1316. }
  1317. void Node::CleanupConnection(Connection* connection)
  1318. {
  1319. if (owner_ == connection)
  1320. owner_ = 0;
  1321. if (networkState_)
  1322. {
  1323. for (unsigned i = networkState_->replicationStates_.Size() - 1; i < networkState_->replicationStates_.Size(); --i)
  1324. {
  1325. if (networkState_->replicationStates_[i]->connection_ == connection)
  1326. networkState_->replicationStates_.Erase(i);
  1327. }
  1328. }
  1329. }
  1330. void Node::MarkReplicationDirty()
  1331. {
  1332. if (networkState_)
  1333. {
  1334. for (PODVector<ReplicationState*>::Iterator j = networkState_->replicationStates_.Begin();
  1335. j != networkState_->replicationStates_.End(); ++j)
  1336. {
  1337. NodeReplicationState* nodeState = static_cast<NodeReplicationState*>(*j);
  1338. if (!nodeState->markedDirty_)
  1339. {
  1340. nodeState->markedDirty_ = true;
  1341. nodeState->sceneState_->dirtyNodes_.Insert(id_);
  1342. }
  1343. }
  1344. }
  1345. }
  1346. Node* Node::CreateChild(unsigned id, CreateMode mode)
  1347. {
  1348. SharedPtr<Node> newNode(new Node(context_));
  1349. // If zero ID specified, or the ID is already taken, let the scene assign
  1350. if (scene_)
  1351. {
  1352. if (!id || scene_->GetNode(id))
  1353. id = scene_->GetFreeNodeID(mode);
  1354. newNode->SetID(id);
  1355. }
  1356. else
  1357. newNode->SetID(id);
  1358. AddChild(newNode);
  1359. return newNode;
  1360. }
  1361. void Node::AddComponent(Component* component, unsigned id, CreateMode mode)
  1362. {
  1363. if (!component)
  1364. return;
  1365. components_.Push(SharedPtr<Component>(component));
  1366. if (component->GetNode())
  1367. URHO3D_LOGWARNING("Component " + component->GetTypeName() + " already belongs to a node!");
  1368. component->SetNode(this);
  1369. // If zero ID specified, or the ID is already taken, let the scene assign
  1370. if (scene_)
  1371. {
  1372. if (!id || scene_->GetComponent(id))
  1373. id = scene_->GetFreeComponentID(mode);
  1374. component->SetID(id);
  1375. scene_->ComponentAdded(component);
  1376. }
  1377. else
  1378. component->SetID(id);
  1379. component->OnMarkedDirty(this);
  1380. // Check attributes of the new component on next network update, and mark node dirty in all replication states
  1381. component->MarkNetworkUpdate();
  1382. MarkNetworkUpdate();
  1383. MarkReplicationDirty();
  1384. // Send change event
  1385. if (scene_)
  1386. {
  1387. using namespace ComponentAdded;
  1388. VariantMap& eventData = GetEventDataMap();
  1389. eventData[P_SCENE] = scene_;
  1390. eventData[P_NODE] = this;
  1391. eventData[P_COMPONENT] = component;
  1392. scene_->SendEvent(E_COMPONENTADDED, eventData);
  1393. }
  1394. }
  1395. unsigned Node::GetNumPersistentChildren() const
  1396. {
  1397. unsigned ret = 0;
  1398. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1399. {
  1400. if (!(*i)->IsTemporary())
  1401. ++ret;
  1402. }
  1403. return ret;
  1404. }
  1405. unsigned Node::GetNumPersistentComponents() const
  1406. {
  1407. unsigned ret = 0;
  1408. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  1409. {
  1410. if (!(*i)->IsTemporary())
  1411. ++ret;
  1412. }
  1413. return ret;
  1414. }
  1415. void Node::SetTransformSilent(const Vector3& position, const Quaternion& rotation, const Vector3& scale)
  1416. {
  1417. position_ = position;
  1418. rotation_ = rotation;
  1419. scale_ = scale;
  1420. }
  1421. void Node::OnAttributeAnimationAdded()
  1422. {
  1423. if (attributeAnimationInfos_.Size() == 1)
  1424. SubscribeToEvent(GetScene(), E_ATTRIBUTEANIMATIONUPDATE, URHO3D_HANDLER(Node, HandleAttributeAnimationUpdate));
  1425. }
  1426. void Node::OnAttributeAnimationRemoved()
  1427. {
  1428. if (attributeAnimationInfos_.Empty())
  1429. UnsubscribeFromEvent(GetScene(), E_ATTRIBUTEANIMATIONUPDATE);
  1430. }
  1431. Animatable* Node::FindAttributeAnimationTarget(const String& name, String& outName)
  1432. {
  1433. Vector<String> names = name.Split('/');
  1434. // Only attribute name
  1435. if (names.Size() == 1)
  1436. {
  1437. outName = name;
  1438. return this;
  1439. }
  1440. else
  1441. {
  1442. // Name must in following format: "#0/#1/@component#0/attribute"
  1443. Node* node = this;
  1444. unsigned i = 0;
  1445. for (; i < names.Size() - 1; ++i)
  1446. {
  1447. if (names[i].Front() != '#')
  1448. break;
  1449. unsigned index = ToUInt(names[i].Substring(1, names[i].Length() - 1));
  1450. node = node->GetChild(index);
  1451. if (!node)
  1452. {
  1453. URHO3D_LOGERROR("Could not find node by name " + name);
  1454. return 0;
  1455. }
  1456. }
  1457. if (i == names.Size() - 1)
  1458. {
  1459. outName = names.Back();
  1460. return node;
  1461. }
  1462. if (i != names.Size() - 2 || names[i].Front() != '@')
  1463. {
  1464. URHO3D_LOGERROR("Invalid name " + name);
  1465. return 0;
  1466. }
  1467. String componentName = names[i].Substring(1, names[i].Length() - 1);
  1468. Vector<String> componentNames = componentName.Split('#');
  1469. if (componentNames.Size() == 1)
  1470. {
  1471. Component* component = node->GetComponent(StringHash(componentNames.Front()));
  1472. if (!component)
  1473. {
  1474. URHO3D_LOGERROR("Could not find component by name " + name);
  1475. return 0;
  1476. }
  1477. outName = names.Back();
  1478. return component;
  1479. }
  1480. else
  1481. {
  1482. unsigned index = ToUInt(componentNames[1]);
  1483. PODVector<Component*> components;
  1484. node->GetComponents(components, StringHash(componentNames.Front()));
  1485. if (index >= components.Size())
  1486. {
  1487. URHO3D_LOGERROR("Could not find component by name " + name);
  1488. return 0;
  1489. }
  1490. outName = names.Back();
  1491. return components[index];
  1492. }
  1493. }
  1494. }
  1495. void Node::SetEnabled(bool enable, bool recursive, bool storeSelf)
  1496. {
  1497. // The enabled state of the whole scene can not be changed. SetUpdateEnabled() is used instead to start/stop updates.
  1498. if (GetType() == Scene::GetTypeStatic())
  1499. {
  1500. URHO3D_LOGERROR("Can not change enabled state of the Scene");
  1501. return;
  1502. }
  1503. if (storeSelf)
  1504. enabledPrev_ = enable;
  1505. if (enable != enabled_)
  1506. {
  1507. enabled_ = enable;
  1508. MarkNetworkUpdate();
  1509. // Notify listener components of the state change
  1510. for (Vector<WeakPtr<Component> >::Iterator i = listeners_.Begin(); i != listeners_.End();)
  1511. {
  1512. if (*i)
  1513. {
  1514. (*i)->OnNodeSetEnabled(this);
  1515. ++i;
  1516. }
  1517. // If listener has expired, erase from list
  1518. else
  1519. i = listeners_.Erase(i);
  1520. }
  1521. // Send change event
  1522. if (scene_)
  1523. {
  1524. using namespace NodeEnabledChanged;
  1525. VariantMap& eventData = GetEventDataMap();
  1526. eventData[P_SCENE] = scene_;
  1527. eventData[P_NODE] = this;
  1528. scene_->SendEvent(E_NODEENABLEDCHANGED, eventData);
  1529. }
  1530. for (Vector<SharedPtr<Component> >::Iterator i = components_.Begin(); i != components_.End(); ++i)
  1531. {
  1532. (*i)->OnSetEnabled();
  1533. // Send change event for the component
  1534. if (scene_)
  1535. {
  1536. using namespace ComponentEnabledChanged;
  1537. VariantMap& eventData = GetEventDataMap();
  1538. eventData[P_SCENE] = scene_;
  1539. eventData[P_NODE] = this;
  1540. eventData[P_COMPONENT] = (*i);
  1541. scene_->SendEvent(E_COMPONENTENABLEDCHANGED, eventData);
  1542. }
  1543. }
  1544. }
  1545. if (recursive)
  1546. {
  1547. for (Vector<SharedPtr<Node> >::Iterator i = children_.Begin(); i != children_.End(); ++i)
  1548. (*i)->SetEnabled(enable, recursive, storeSelf);
  1549. }
  1550. }
  1551. Component* Node::SafeCreateComponent(const String& typeName, StringHash type, CreateMode mode, unsigned id)
  1552. {
  1553. // Do not attempt to create replicated components to local nodes, as that may lead to component ID overwrite
  1554. // as replicated components are synced over
  1555. if (id_ >= FIRST_LOCAL_ID && mode == REPLICATED)
  1556. mode = LOCAL;
  1557. // First check if factory for type exists
  1558. if (!context_->GetTypeName(type).Empty())
  1559. return CreateComponent(type, mode, id);
  1560. else
  1561. {
  1562. URHO3D_LOGWARNING("Component type " + type.ToString() + " not known, creating UnknownComponent as placeholder");
  1563. // Else create as UnknownComponent
  1564. SharedPtr<UnknownComponent> newComponent(new UnknownComponent(context_));
  1565. if (typeName.Empty() || typeName.StartsWith("Unknown", false))
  1566. newComponent->SetType(type);
  1567. else
  1568. newComponent->SetTypeName(typeName);
  1569. AddComponent(newComponent, id, mode);
  1570. return newComponent;
  1571. }
  1572. }
  1573. void Node::UpdateWorldTransform() const
  1574. {
  1575. Matrix3x4 transform = GetTransform();
  1576. // Assume the root node (scene) has identity transform
  1577. if (parent_ == scene_ || !parent_)
  1578. {
  1579. worldTransform_ = transform;
  1580. worldRotation_ = rotation_;
  1581. }
  1582. else
  1583. {
  1584. worldTransform_ = parent_->GetWorldTransform() * transform;
  1585. worldRotation_ = parent_->GetWorldRotation() * rotation_;
  1586. }
  1587. dirty_ = false;
  1588. }
  1589. void Node::RemoveChild(Vector<SharedPtr<Node> >::Iterator i)
  1590. {
  1591. // Send change event. Do not send when already being destroyed
  1592. Node* child = *i;
  1593. if (Refs() > 0 && scene_)
  1594. {
  1595. using namespace NodeRemoved;
  1596. VariantMap& eventData = GetEventDataMap();
  1597. eventData[P_SCENE] = scene_;
  1598. eventData[P_PARENT] = this;
  1599. eventData[P_NODE] = child;
  1600. scene_->SendEvent(E_NODEREMOVED, eventData);
  1601. }
  1602. child->parent_ = 0;
  1603. child->MarkDirty();
  1604. child->MarkNetworkUpdate();
  1605. if (scene_)
  1606. scene_->NodeRemoved(child);
  1607. children_.Erase(i);
  1608. }
  1609. void Node::GetChildrenRecursive(PODVector<Node*>& dest) const
  1610. {
  1611. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1612. {
  1613. Node* node = *i;
  1614. dest.Push(node);
  1615. if (!node->children_.Empty())
  1616. node->GetChildrenRecursive(dest);
  1617. }
  1618. }
  1619. void Node::GetChildrenWithComponentRecursive(PODVector<Node*>& dest, StringHash type) const
  1620. {
  1621. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1622. {
  1623. Node* node = *i;
  1624. if (node->HasComponent(type))
  1625. dest.Push(node);
  1626. if (!node->children_.Empty())
  1627. node->GetChildrenWithComponentRecursive(dest, type);
  1628. }
  1629. }
  1630. void Node::GetComponentsRecursive(PODVector<Component*>& dest, StringHash type) const
  1631. {
  1632. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  1633. {
  1634. if ((*i)->GetType() == type)
  1635. dest.Push(*i);
  1636. }
  1637. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1638. (*i)->GetComponentsRecursive(dest, type);
  1639. }
  1640. Node* Node::CloneRecursive(Node* parent, SceneResolver& resolver, CreateMode mode)
  1641. {
  1642. // Create clone node
  1643. Node* cloneNode = parent->CreateChild(0, (mode == REPLICATED && id_ < FIRST_LOCAL_ID) ? REPLICATED : LOCAL);
  1644. resolver.AddNode(id_, cloneNode);
  1645. // Copy attributes
  1646. const Vector<AttributeInfo>* attributes = GetAttributes();
  1647. for (unsigned j = 0; j < attributes->Size(); ++j)
  1648. {
  1649. const AttributeInfo& attr = attributes->At(j);
  1650. // Do not copy network-only attributes, as they may have unintended side effects
  1651. if (attr.mode_ & AM_FILE)
  1652. {
  1653. Variant value;
  1654. OnGetAttribute(attr, value);
  1655. cloneNode->OnSetAttribute(attr, value);
  1656. }
  1657. }
  1658. // Clone components
  1659. for (Vector<SharedPtr<Component> >::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
  1660. {
  1661. Component* component = *i;
  1662. if (component->IsTemporary())
  1663. continue;
  1664. Component* cloneComponent = cloneNode->CloneComponent(component,
  1665. (mode == REPLICATED && component->GetID() < FIRST_LOCAL_ID) ? REPLICATED : LOCAL, 0);
  1666. if (cloneComponent)
  1667. resolver.AddComponent(component->GetID(), cloneComponent);
  1668. }
  1669. // Clone child nodes recursively
  1670. for (Vector<SharedPtr<Node> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1671. {
  1672. Node* node = *i;
  1673. if (node->IsTemporary())
  1674. continue;
  1675. node->CloneRecursive(cloneNode, resolver, mode);
  1676. }
  1677. return cloneNode;
  1678. }
  1679. void Node::RemoveComponent(Vector<SharedPtr<Component> >::Iterator i)
  1680. {
  1681. // Send node change event. Do not send when already being destroyed
  1682. if (Refs() > 0 && scene_)
  1683. {
  1684. using namespace ComponentRemoved;
  1685. VariantMap& eventData = GetEventDataMap();
  1686. eventData[P_SCENE] = scene_;
  1687. eventData[P_NODE] = this;
  1688. eventData[P_COMPONENT] = (*i).Get();
  1689. scene_->SendEvent(E_COMPONENTREMOVED, eventData);
  1690. }
  1691. RemoveListener(*i);
  1692. if (scene_)
  1693. scene_->ComponentRemoved(*i);
  1694. (*i)->SetNode(0);
  1695. components_.Erase(i);
  1696. }
  1697. void Node::HandleAttributeAnimationUpdate(StringHash eventType, VariantMap& eventData)
  1698. {
  1699. using namespace AttributeAnimationUpdate;
  1700. UpdateAttributeAnimations(eventData[P_TIMESTEP].GetFloat());
  1701. }
  1702. }