Scene.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2012 Lasse Öörni
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #include "Precompiled.h"
  24. #include "Component.h"
  25. #include "Context.h"
  26. #include "CoreEvents.h"
  27. #include "File.h"
  28. #include "Log.h"
  29. #include "PackageFile.h"
  30. #include "Profiler.h"
  31. #include "ReplicationState.h"
  32. #include "Scene.h"
  33. #include "SceneEvents.h"
  34. #include "SmoothedTransform.h"
  35. #include "WorkQueue.h"
  36. #include "XMLFile.h"
  37. #include "DebugNew.h"
  38. namespace Urho3D
  39. {
  40. static const int ASYNC_LOAD_MIN_FPS = 30;
  41. static const int ASYNC_LOAD_MAX_MSEC = (int)(1000.0f / ASYNC_LOAD_MIN_FPS);
  42. static const float DEFAULT_SMOOTHING_CONSTANT = 50.0f;
  43. static const float DEFAULT_SNAP_THRESHOLD = 5.0f;
  44. OBJECTTYPESTATIC(Scene);
  45. Scene::Scene(Context* context) :
  46. Node(context),
  47. replicatedNodeID_(FIRST_REPLICATED_ID),
  48. replicatedComponentID_(FIRST_REPLICATED_ID),
  49. localNodeID_(FIRST_LOCAL_ID),
  50. localComponentID_(FIRST_LOCAL_ID),
  51. checksum_(0),
  52. timeScale_(1.0f),
  53. smoothingConstant_(DEFAULT_SMOOTHING_CONSTANT),
  54. snapThreshold_(DEFAULT_SNAP_THRESHOLD),
  55. active_(true),
  56. asyncLoading_(false),
  57. threadedUpdate_(false)
  58. {
  59. // Assign an ID to self so that nodes can refer to this node as a parent
  60. SetID(GetFreeNodeID(REPLICATED));
  61. NodeAdded(this);
  62. SubscribeToEvent(E_UPDATE, HANDLER(Scene, HandleUpdate));
  63. }
  64. Scene::~Scene()
  65. {
  66. RemoveAllChildren();
  67. RemoveAllComponents();
  68. // Remove scene reference and owner from all nodes that still exist
  69. for (HashMap<unsigned, Node*>::Iterator i = replicatedNodes_.Begin(); i != replicatedNodes_.End(); ++i)
  70. {
  71. i->second_->SetID(0);
  72. i->second_->SetScene(0);
  73. i->second_->SetOwner(0);
  74. }
  75. for (HashMap<unsigned, Node*>::Iterator i = localNodes_.Begin(); i != localNodes_.End(); ++i)
  76. {
  77. i->second_->SetID(0);
  78. i->second_->SetScene(0);
  79. i->second_->SetOwner(0);
  80. }
  81. }
  82. void Scene::RegisterObject(Context* context)
  83. {
  84. context->RegisterFactory<Scene>();
  85. REF_ACCESSOR_ATTRIBUTE(Scene, VAR_STRING, "Name", GetName, SetName, String, String(), AM_DEFAULT);
  86. REF_ACCESSOR_ATTRIBUTE(Scene, VAR_VECTOR3, "Position", GetPosition, SetPosition, Vector3, Vector3::ZERO, AM_DEFAULT | AM_LATESTDATA);
  87. REF_ACCESSOR_ATTRIBUTE(Scene, VAR_QUATERNION, "Rotation", GetRotation, SetRotation, Quaternion, Quaternion::IDENTITY, AM_FILE);
  88. REF_ACCESSOR_ATTRIBUTE(Scene, VAR_VECTOR3, "Scale", GetScale, SetScale, Vector3, Vector3::ONE, AM_DEFAULT);
  89. ACCESSOR_ATTRIBUTE(Scene, VAR_FLOAT, "Time Scale", GetTimeScale, SetTimeScale, float, 1.0f, AM_DEFAULT);
  90. ACCESSOR_ATTRIBUTE(Scene, VAR_FLOAT, "Smoothing Constant", GetSmoothingConstant, SetSmoothingConstant, float, DEFAULT_SMOOTHING_CONSTANT, AM_DEFAULT);
  91. ACCESSOR_ATTRIBUTE(Scene, VAR_FLOAT, "Snap Threshold", GetSnapThreshold, SetSnapThreshold, float, DEFAULT_SNAP_THRESHOLD, AM_DEFAULT);
  92. ATTRIBUTE(Scene, VAR_INT, "Next Replicated Node ID", replicatedNodeID_, FIRST_REPLICATED_ID, AM_FILE | AM_NOEDIT);
  93. ATTRIBUTE(Scene, VAR_INT, "Next Replicated Component ID", replicatedComponentID_, FIRST_REPLICATED_ID, AM_FILE | AM_NOEDIT);
  94. ATTRIBUTE(Scene, VAR_INT, "Next Local Node ID", localNodeID_, FIRST_LOCAL_ID, AM_FILE | AM_NOEDIT);
  95. ATTRIBUTE(Scene, VAR_INT, "Next Local Component ID", localComponentID_, FIRST_LOCAL_ID, AM_FILE | AM_NOEDIT);
  96. ATTRIBUTE(Scene, VAR_VARIANTMAP, "Variables", vars_, VariantMap(), AM_FILE); // Network replication of vars uses custom data
  97. ACCESSOR_ATTRIBUTE(Scene, VAR_STRING, "Variable Names", GetVarNamesAttr, SetVarNamesAttr, String, String(), AM_FILE | AM_NOEDIT);
  98. REF_ACCESSOR_ATTRIBUTE(Scene, VAR_BUFFER, "Network Rotation", GetNetRotationAttr, SetNetRotationAttr, PODVector<unsigned char>, PODVector<unsigned char>(), AM_NET | AM_LATESTDATA | AM_NOEDIT);
  99. }
  100. bool Scene::Load(Deserializer& source)
  101. {
  102. PROFILE(LoadScene);
  103. StopAsyncLoading();
  104. // Check ID
  105. if (source.ReadFileID() != "USCN")
  106. {
  107. LOGERROR(source.GetName() + " is not a valid scene file");
  108. return false;
  109. }
  110. LOGINFO("Loading scene from " + source.GetName());
  111. // Load the whole scene, then perform post-load if successfully loaded
  112. if (Node::Load(source))
  113. {
  114. FinishLoading(&source);
  115. return true;
  116. }
  117. else
  118. return false;
  119. }
  120. bool Scene::Save(Serializer& dest)
  121. {
  122. PROFILE(SaveScene);
  123. // Write ID first
  124. if (!dest.WriteFileID("USCN"))
  125. {
  126. LOGERROR("Could not save scene, writing to stream failed");
  127. return false;
  128. }
  129. Deserializer* ptr = dynamic_cast<Deserializer*>(&dest);
  130. if (ptr)
  131. LOGINFO("Saving scene to " + ptr->GetName());
  132. return Node::Save(dest);
  133. }
  134. bool Scene::LoadXML(const XMLElement& source)
  135. {
  136. PROFILE(LoadSceneXML);
  137. StopAsyncLoading();
  138. // Load the whole scene, then perform post-load if successfully loaded
  139. // Note: the scene filename and checksum can not be set, as we only used an XML element
  140. if (Node::LoadXML(source))
  141. {
  142. FinishLoading(0);
  143. return true;
  144. }
  145. else
  146. return false;
  147. }
  148. void Scene::AddReplicationState(NodeReplicationState* state)
  149. {
  150. Node::AddReplicationState(state);
  151. // This is the first update for a new connection. Mark all replicated nodes dirty
  152. for (HashMap<unsigned, Node*>::ConstIterator i = replicatedNodes_.Begin(); i != replicatedNodes_.End(); ++i)
  153. state->sceneState_->dirtyNodes_.Insert(i->first_);
  154. }
  155. bool Scene::LoadXML(Deserializer& source)
  156. {
  157. PROFILE(LoadSceneXML);
  158. StopAsyncLoading();
  159. SharedPtr<XMLFile> xml(new XMLFile(context_));
  160. if (!xml->Load(source))
  161. return false;
  162. LOGINFO("Loading scene from " + source.GetName());
  163. if (Node::LoadXML(xml->GetRoot()))
  164. {
  165. FinishLoading(&source);
  166. return true;
  167. }
  168. else
  169. return false;
  170. }
  171. bool Scene::SaveXML(Serializer& dest)
  172. {
  173. PROFILE(SaveSceneXML);
  174. SharedPtr<XMLFile> xml(new XMLFile(context_));
  175. XMLElement rootElem = xml->CreateRoot("scene");
  176. if (!SaveXML(rootElem))
  177. return false;
  178. Deserializer* ptr = dynamic_cast<Deserializer*>(&dest);
  179. if (ptr)
  180. LOGINFO("Saving scene to " + ptr->GetName());
  181. return xml->Save(dest);
  182. }
  183. bool Scene::LoadAsync(File* file)
  184. {
  185. if (!file)
  186. {
  187. LOGERROR("Null file for async loading");
  188. return false;
  189. }
  190. StopAsyncLoading();
  191. // Check ID
  192. if (file->ReadFileID() != "USCN")
  193. {
  194. LOGERROR(file->GetName() + " is not a valid scene file");
  195. return false;
  196. }
  197. LOGINFO("Loading scene from " + file->GetName());
  198. Clear();
  199. // Store own old ID for resolving possible root node references
  200. unsigned nodeID = file->ReadUInt();
  201. resolver_.AddNode(nodeID, this);
  202. // Load root level components first
  203. if (!Node::Load(*file, resolver_, false))
  204. return false;
  205. // Then prepare for loading all root level child nodes in the async update
  206. asyncLoading_ = true;
  207. asyncProgress_.file_ = file;
  208. asyncProgress_.xmlFile_.Reset();
  209. asyncProgress_.xmlElement_ = XMLElement();
  210. asyncProgress_.loadedNodes_ = 0;
  211. asyncProgress_.totalNodes_ = file->ReadVLE();
  212. return true;
  213. }
  214. bool Scene::LoadAsyncXML(File* file)
  215. {
  216. if (!file)
  217. {
  218. LOGERROR("Null file for async loading");
  219. return false;
  220. }
  221. StopAsyncLoading();
  222. SharedPtr<XMLFile> xml(new XMLFile(context_));
  223. if (!xml->Load(*file))
  224. return false;
  225. LOGINFO("Loading scene from " + file->GetName());
  226. Clear();
  227. XMLElement rootElement = xml->GetRoot();
  228. // Store own old ID for resolving possible root node references
  229. unsigned nodeID = rootElement.GetInt("id");
  230. resolver_.AddNode(nodeID, this);
  231. // Load the root level components first
  232. if (!Node::LoadXML(rootElement, resolver_, false))
  233. return false;
  234. // Then prepare for loading all root level child nodes in the async update
  235. XMLElement childNodeElement = rootElement.GetChild("node");
  236. asyncLoading_ = true;
  237. asyncProgress_.file_ = file;
  238. asyncProgress_.xmlFile_ = xml;
  239. asyncProgress_.xmlElement_ = childNodeElement;
  240. asyncProgress_.loadedNodes_ = 0;
  241. asyncProgress_.totalNodes_ = 0;
  242. // Count the amount of child nodes
  243. while (childNodeElement)
  244. {
  245. ++asyncProgress_.totalNodes_;
  246. childNodeElement = childNodeElement.GetNext("node");
  247. }
  248. return true;
  249. }
  250. void Scene::StopAsyncLoading()
  251. {
  252. asyncLoading_ = false;
  253. asyncProgress_.file_.Reset();
  254. asyncProgress_.xmlFile_.Reset();
  255. asyncProgress_.xmlElement_ = XMLElement();
  256. resolver_.Reset();
  257. }
  258. Node* Scene::Instantiate(Deserializer& source, const Vector3& position, const Quaternion& rotation, CreateMode mode)
  259. {
  260. PROFILE(Instantiate);
  261. SceneResolver resolver;
  262. unsigned nodeID = source.ReadInt();
  263. // Rewrite IDs when instantiating
  264. Node* node = CreateChild(0, mode);
  265. resolver.AddNode(nodeID, node);
  266. if (node->Load(source, resolver, true, true, mode))
  267. {
  268. resolver.Resolve();
  269. node->ApplyAttributes();
  270. node->SetTransform(position, rotation);
  271. return node;
  272. }
  273. else
  274. {
  275. node->Remove();
  276. return 0;
  277. }
  278. }
  279. Node* Scene::InstantiateXML(const XMLElement& source, const Vector3& position, const Quaternion& rotation, CreateMode mode)
  280. {
  281. PROFILE(InstantiateXML);
  282. SceneResolver resolver;
  283. unsigned nodeID = source.GetInt("id");
  284. // Rewrite IDs when instantiating
  285. Node* node = CreateChild(0, mode);
  286. resolver.AddNode(nodeID, node);
  287. if (node->LoadXML(source, resolver, true, true, mode))
  288. {
  289. resolver.Resolve();
  290. node->ApplyAttributes();
  291. node->SetTransform(position, rotation);
  292. return node;
  293. }
  294. else
  295. {
  296. node->Remove();
  297. return 0;
  298. }
  299. }
  300. Node* Scene::InstantiateXML(Deserializer& source, const Vector3& position, const Quaternion& rotation, CreateMode mode)
  301. {
  302. SharedPtr<XMLFile> xml(new XMLFile(context_));
  303. if (!xml->Load(source))
  304. return false;
  305. return InstantiateXML(xml->GetRoot(), position, rotation, mode);
  306. }
  307. void Scene::Clear()
  308. {
  309. StopAsyncLoading();
  310. RemoveAllChildren();
  311. RemoveAllComponents();
  312. fileName_ = String();
  313. checksum_ = 0;
  314. replicatedNodeID_ = FIRST_REPLICATED_ID;
  315. replicatedComponentID_ = FIRST_REPLICATED_ID;
  316. localNodeID_ = FIRST_LOCAL_ID;
  317. localComponentID_ = FIRST_LOCAL_ID;
  318. }
  319. void Scene::SetActive(bool enable)
  320. {
  321. active_ = enable;
  322. }
  323. void Scene::SetTimeScale(float scale)
  324. {
  325. timeScale_ = Max(scale, M_EPSILON);
  326. Node::MarkNetworkUpdate();
  327. }
  328. void Scene::SetSmoothingConstant(float constant)
  329. {
  330. smoothingConstant_ = Max(constant, M_EPSILON);
  331. Node::MarkNetworkUpdate();
  332. }
  333. void Scene::SetSnapThreshold(float threshold)
  334. {
  335. snapThreshold_ = Max(threshold, 0.0f);
  336. Node::MarkNetworkUpdate();
  337. }
  338. void Scene::AddRequiredPackageFile(PackageFile* package)
  339. {
  340. // Do not add packages that failed to load
  341. if (!package || !package->GetNumFiles())
  342. return;
  343. requiredPackageFiles_.Push(SharedPtr<PackageFile>(package));
  344. }
  345. void Scene::ClearRequiredPackageFiles()
  346. {
  347. requiredPackageFiles_.Clear();
  348. }
  349. void Scene::RegisterVar(const String& name)
  350. {
  351. varNames_[ShortStringHash(name)] = name;
  352. }
  353. void Scene::UnregisterVar(const String& name)
  354. {
  355. varNames_.Erase(ShortStringHash(name));
  356. }
  357. void Scene::UnregisterAllVars()
  358. {
  359. varNames_.Clear();
  360. }
  361. Node* Scene::GetNode(unsigned id) const
  362. {
  363. if (id < FIRST_LOCAL_ID)
  364. {
  365. HashMap<unsigned, Node*>::ConstIterator i = replicatedNodes_.Find(id);
  366. if (i != replicatedNodes_.End())
  367. return i->second_;
  368. else
  369. return 0;
  370. }
  371. else
  372. {
  373. HashMap<unsigned, Node*>::ConstIterator i = localNodes_.Find(id);
  374. if (i != localNodes_.End())
  375. return i->second_;
  376. else
  377. return 0;
  378. }
  379. }
  380. Component* Scene::GetComponent(unsigned id) const
  381. {
  382. if (id < FIRST_LOCAL_ID)
  383. {
  384. HashMap<unsigned, Component*>::ConstIterator i = replicatedComponents_.Find(id);
  385. if (i != replicatedComponents_.End())
  386. return i->second_;
  387. else
  388. return 0;
  389. }
  390. else
  391. {
  392. HashMap<unsigned, Component*>::ConstIterator i = localComponents_.Find(id);
  393. if (i != localComponents_.End())
  394. return i->second_;
  395. else
  396. return 0;
  397. }
  398. }
  399. float Scene::GetAsyncProgress() const
  400. {
  401. if (!asyncLoading_ || !asyncProgress_.totalNodes_)
  402. return 1.0f;
  403. else
  404. return (float)asyncProgress_.loadedNodes_ / (float)asyncProgress_.totalNodes_;
  405. }
  406. const String& Scene::GetVarName(ShortStringHash hash) const
  407. {
  408. HashMap<ShortStringHash, String>::ConstIterator i = varNames_.Find(hash);
  409. return i != varNames_.End() ? i->second_ : String::EMPTY;
  410. }
  411. void Scene::Update(float timeStep)
  412. {
  413. if (asyncLoading_)
  414. {
  415. UpdateAsyncLoading();
  416. return;
  417. }
  418. PROFILE(UpdateScene);
  419. timeStep *= timeScale_;
  420. using namespace SceneUpdate;
  421. VariantMap eventData;
  422. eventData[P_SCENE] = (void*)this;
  423. eventData[P_TIMESTEP] = timeStep;
  424. // Update variable timestep logic
  425. SendEvent(E_SCENEUPDATE, eventData);
  426. // Update scene subsystems. If a physics world is present, it will be updated, triggering fixed timestep logic updates
  427. SendEvent(E_SCENESUBSYSTEMUPDATE, eventData);
  428. // Update transform smoothing
  429. {
  430. PROFILE(UpdateSmoothing);
  431. float constant = 1.0f - Clamp(powf(2.0f, -timeStep * smoothingConstant_), 0.0f, 1.0f);
  432. float squaredSnapThreshold = snapThreshold_ * snapThreshold_;
  433. using namespace UpdateSmoothing;
  434. VariantMap eventData;
  435. eventData[P_CONSTANT] = constant;
  436. eventData[P_SQUAREDSNAPTHRESHOLD] = squaredSnapThreshold;
  437. SendEvent(E_UPDATESMOOTHING, eventData);
  438. }
  439. // Post-update variable timestep logic
  440. SendEvent(E_SCENEPOSTUPDATE, eventData);
  441. }
  442. void Scene::BeginThreadedUpdate()
  443. {
  444. // Check the work queue subsystem whether it actually has created worker threads. If not, do not enter threaded mode.
  445. if (GetSubsystem<WorkQueue>()->GetNumThreads())
  446. threadedUpdate_ = true;
  447. }
  448. void Scene::EndThreadedUpdate()
  449. {
  450. if (!threadedUpdate_)
  451. return;
  452. threadedUpdate_ = false;
  453. if (!delayedDirtyComponents_.Empty())
  454. {
  455. PROFILE(EndThreadedUpdate);
  456. for (PODVector<Component*>::ConstIterator i = delayedDirtyComponents_.Begin(); i != delayedDirtyComponents_.End(); ++i)
  457. (*i)->OnMarkedDirty((*i)->GetNode());
  458. delayedDirtyComponents_.Clear();
  459. }
  460. }
  461. void Scene::DelayedMarkedDirty(Component* component)
  462. {
  463. MutexLock lock(sceneMutex_);
  464. delayedDirtyComponents_.Push(component);
  465. }
  466. unsigned Scene::GetFreeNodeID(CreateMode mode)
  467. {
  468. if (mode == REPLICATED)
  469. {
  470. for (;;)
  471. {
  472. if (!replicatedNodes_.Contains(replicatedNodeID_))
  473. return replicatedNodeID_;
  474. if (replicatedNodeID_ != LAST_REPLICATED_ID)
  475. ++replicatedNodeID_;
  476. else
  477. replicatedNodeID_ = FIRST_REPLICATED_ID;
  478. }
  479. }
  480. else
  481. {
  482. for (;;)
  483. {
  484. if (!localNodes_.Contains(localNodeID_))
  485. return localNodeID_;
  486. if (localNodeID_ != LAST_LOCAL_ID)
  487. ++localNodeID_;
  488. else
  489. localNodeID_ = FIRST_LOCAL_ID;
  490. }
  491. }
  492. }
  493. unsigned Scene::GetFreeComponentID(CreateMode mode)
  494. {
  495. if (mode == REPLICATED)
  496. {
  497. for (;;)
  498. {
  499. if (!replicatedComponents_.Contains(replicatedComponentID_))
  500. return replicatedComponentID_;
  501. if (replicatedComponentID_ != LAST_REPLICATED_ID)
  502. ++replicatedComponentID_;
  503. else
  504. replicatedComponentID_ = FIRST_REPLICATED_ID;
  505. }
  506. }
  507. else
  508. {
  509. for (;;)
  510. {
  511. if (!localComponents_.Contains(localComponentID_))
  512. return localComponentID_;
  513. if (localComponentID_ != LAST_LOCAL_ID)
  514. ++localComponentID_;
  515. else
  516. localComponentID_ = FIRST_LOCAL_ID;
  517. }
  518. }
  519. }
  520. void Scene::NodeAdded(Node* node)
  521. {
  522. if (!node || node->GetScene())
  523. return;
  524. node->SetScene(this);
  525. // If we already have an existing node with the same ID, must remove the scene reference from it
  526. unsigned id = node->GetID();
  527. if (id < FIRST_LOCAL_ID)
  528. {
  529. HashMap<unsigned, Node*>::Iterator i = replicatedNodes_.Find(id);
  530. if (i != replicatedNodes_.End() && i->second_ != node)
  531. {
  532. LOGWARNING("Overwriting node with ID " + String(id));
  533. i->second_->SetID(0);
  534. i->second_->SetScene(0);
  535. i->second_->SetOwner(0);
  536. }
  537. replicatedNodes_[id] = node;
  538. MarkNetworkUpdate(node);
  539. MarkReplicationDirty(node);
  540. }
  541. else
  542. {
  543. HashMap<unsigned, Node*>::Iterator i = localNodes_.Find(id);
  544. if (i != localNodes_.End() && i->second_ != node)
  545. {
  546. LOGWARNING("Overwriting node with ID " + String(id));
  547. i->second_->SetID(0);
  548. i->second_->SetScene(0);
  549. i->second_->SetOwner(0);
  550. }
  551. localNodes_[id] = node;
  552. }
  553. }
  554. void Scene::NodeRemoved(Node* node)
  555. {
  556. if (!node || node->GetScene() != this)
  557. return;
  558. unsigned id = node->GetID();
  559. if (id < FIRST_LOCAL_ID)
  560. {
  561. replicatedNodes_.Erase(id);
  562. MarkReplicationDirty(node);
  563. }
  564. else
  565. localNodes_.Erase(id);
  566. node->SetID(0);
  567. node->SetScene(0);
  568. }
  569. void Scene::ComponentAdded(Component* component)
  570. {
  571. if (!component)
  572. return;
  573. unsigned id = component->GetID();
  574. if (id < FIRST_LOCAL_ID)
  575. {
  576. HashMap<unsigned, Component*>::Iterator i = replicatedComponents_.Find(id);
  577. if (i != replicatedComponents_.End() && i->second_ != component)
  578. {
  579. LOGWARNING("Overwriting component with ID " + String(id));
  580. i->second_->SetID(0);
  581. }
  582. replicatedComponents_[id] = component;
  583. }
  584. else
  585. {
  586. HashMap<unsigned, Component*>::Iterator i = localComponents_.Find(id);
  587. if (i != localComponents_.End() && i->second_ != component)
  588. {
  589. LOGWARNING("Overwriting component with ID " + String(id));
  590. i->second_->SetID(0);
  591. }
  592. localComponents_[id] = component;
  593. }
  594. }
  595. void Scene::ComponentRemoved(Component* component)
  596. {
  597. if (!component)
  598. return;
  599. unsigned id = component->GetID();
  600. if (id < FIRST_LOCAL_ID)
  601. replicatedComponents_.Erase(id);
  602. else
  603. localComponents_.Erase(id);
  604. component->SetID(0);
  605. }
  606. void Scene::SetVarNamesAttr(String value)
  607. {
  608. Vector<String> varNames = value.Split(';');
  609. varNames_.Clear();
  610. for (Vector<String>::ConstIterator i = varNames.Begin(); i != varNames.End(); ++i)
  611. varNames_[ShortStringHash(*i)] = *i;
  612. }
  613. String Scene::GetVarNamesAttr() const
  614. {
  615. String ret;
  616. for (HashMap<ShortStringHash, String>::ConstIterator i = varNames_.Begin(); i != varNames_.End(); ++i)
  617. {
  618. if (i != varNames_.Begin())
  619. ret += ';';
  620. ret += i->second_;
  621. }
  622. return ret;
  623. }
  624. void Scene::PrepareNetworkUpdate()
  625. {
  626. for (HashSet<unsigned>::Iterator i = networkUpdateNodes_.Begin(); i != networkUpdateNodes_.End(); ++i)
  627. {
  628. Node* node = GetNode(*i);
  629. if (node)
  630. node->PrepareNetworkUpdate();
  631. }
  632. for (HashSet<unsigned>::Iterator i = networkUpdateComponents_.Begin(); i != networkUpdateComponents_.End(); ++i)
  633. {
  634. Component* component = GetComponent(*i);
  635. if (component)
  636. component->PrepareNetworkUpdate();
  637. }
  638. networkUpdateNodes_.Clear();
  639. networkUpdateComponents_.Clear();
  640. }
  641. void Scene::CleanupConnection(Connection* connection)
  642. {
  643. Node::CleanupConnection(connection);
  644. for (HashMap<unsigned, Node*>::Iterator i = replicatedNodes_.Begin(); i != replicatedNodes_.End(); ++i)
  645. i->second_->CleanupConnection(connection);
  646. for (HashMap<unsigned, Component*>::Iterator i = replicatedComponents_.Begin(); i != replicatedComponents_.End(); ++i)
  647. i->second_->CleanupConnection(connection);
  648. }
  649. void Scene::MarkNetworkUpdate(Node* node)
  650. {
  651. if (node)
  652. networkUpdateNodes_.Insert(node->GetID());
  653. }
  654. void Scene::MarkNetworkUpdate(Component* component)
  655. {
  656. if (component)
  657. networkUpdateComponents_.Insert(component->GetID());
  658. }
  659. void Scene::MarkReplicationDirty(Node* node)
  660. {
  661. unsigned id = node->GetID();
  662. if (id < FIRST_LOCAL_ID && networkState_)
  663. {
  664. for (PODVector<ReplicationState*>::Iterator i = networkState_->replicationStates_.Begin(); i !=
  665. networkState_->replicationStates_.End(); ++i)
  666. {
  667. NodeReplicationState* nodeState = static_cast<NodeReplicationState*>(*i);
  668. nodeState->sceneState_->dirtyNodes_.Insert(id);
  669. }
  670. }
  671. }
  672. void Scene::HandleUpdate(StringHash eventType, VariantMap& eventData)
  673. {
  674. using namespace Update;
  675. if (active_)
  676. Update(eventData[P_TIMESTEP].GetFloat());
  677. }
  678. void Scene::UpdateAsyncLoading()
  679. {
  680. PROFILE(UpdateAsyncLoading);
  681. Timer asyncLoadTimer;
  682. for (;;)
  683. {
  684. if (asyncProgress_.loadedNodes_ >= asyncProgress_.totalNodes_)
  685. {
  686. FinishAsyncLoading();
  687. return;
  688. }
  689. // Read one child node with its full sub-hierarchy from either from binary or XML
  690. if (!asyncProgress_.xmlFile_)
  691. {
  692. unsigned nodeID = asyncProgress_.file_->ReadUInt();
  693. Node* newNode = CreateChild(nodeID, nodeID < FIRST_LOCAL_ID ? REPLICATED : LOCAL);
  694. resolver_.AddNode(nodeID, newNode);
  695. newNode->Load(*asyncProgress_.file_, resolver_);
  696. }
  697. else
  698. {
  699. unsigned nodeID = asyncProgress_.xmlElement_.GetInt("id");
  700. Node* newNode = CreateChild(nodeID, nodeID < FIRST_LOCAL_ID ? REPLICATED : LOCAL);
  701. resolver_.AddNode(nodeID, newNode);
  702. newNode->LoadXML(asyncProgress_.xmlElement_, resolver_);
  703. asyncProgress_.xmlElement_ = asyncProgress_.xmlElement_.GetNext("node");
  704. }
  705. ++asyncProgress_.loadedNodes_;
  706. // Break if time limit exceeded, so that we keep sufficient FPS
  707. if (asyncLoadTimer.GetMSec(false) >= ASYNC_LOAD_MAX_MSEC)
  708. break;
  709. }
  710. using namespace AsyncLoadProgress;
  711. VariantMap eventData;
  712. eventData[P_SCENE] = (void*)this;
  713. eventData[P_PROGRESS] = (float)asyncProgress_.loadedNodes_ / (float)asyncProgress_.totalNodes_;
  714. eventData[P_LOADEDNODES] = asyncProgress_.loadedNodes_;
  715. eventData[P_TOTALNODES] = asyncProgress_.totalNodes_;
  716. SendEvent(E_ASYNCLOADPROGRESS, eventData);
  717. }
  718. void Scene::FinishAsyncLoading()
  719. {
  720. resolver_.Resolve();
  721. ApplyAttributes();
  722. FinishLoading(asyncProgress_.file_);
  723. StopAsyncLoading();
  724. using namespace AsyncLoadFinished;
  725. VariantMap eventData;
  726. eventData[P_SCENE] = (void*)this;
  727. SendEvent(E_ASYNCLOADFINISHED, eventData);
  728. }
  729. void Scene::FinishLoading(Deserializer* source)
  730. {
  731. if (source)
  732. {
  733. fileName_ = source->GetName();
  734. checksum_ = source->GetChecksum();
  735. }
  736. }
  737. void RegisterSceneLibrary(Context* context)
  738. {
  739. Node::RegisterObject(context);
  740. Scene::RegisterObject(context);
  741. SmoothedTransform::RegisterObject(context);
  742. }
  743. }