Scene.cpp 28 KB

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