Scene.cpp 27 KB

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