Node.cpp 50 KB

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