Scene.cpp 20 KB

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