Scene.cpp 25 KB

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