Scene.cpp 26 KB

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