Scene.cpp 25 KB

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