Scene.cpp 27 KB

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