2
0

Scene.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2012 Lasse Öörni
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #include "Precompiled.h"
  24. #include "Component.h"
  25. #include "Context.h"
  26. #include "CoreEvents.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 "WorkQueue.h"
  36. #include "XMLFile.h"
  37. #include "DebugNew.h"
  38. static const int ASYNC_LOAD_MIN_FPS = 30;
  39. static const int ASYNC_LOAD_MAX_MSEC = (int)(1000.0f / ASYNC_LOAD_MIN_FPS);
  40. static const float DEFAULT_SMOOTHING_CONSTANT = 50.0f;
  41. static const float DEFAULT_SNAP_THRESHOLD = 5.0f;
  42. static const String emptyVarName;
  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. smoothingConstant_(DEFAULT_SMOOTHING_CONSTANT),
  51. snapThreshold_(DEFAULT_SNAP_THRESHOLD),
  52. checksum_(0),
  53. active_(true),
  54. asyncLoading_(false),
  55. threadedUpdate_(false)
  56. {
  57. // Assign an ID to self so that nodes can refer to this node as a parent
  58. SetID(GetFreeNodeID(REPLICATED));
  59. NodeAdded(this);
  60. SubscribeToEvent(E_UPDATE, HANDLER(Scene, HandleUpdate));
  61. }
  62. Scene::~Scene()
  63. {
  64. // Remove scene reference and owner from all nodes that still exist
  65. for (HashMap<unsigned, Node*>::Iterator i = replicatedNodes_.Begin(); i != replicatedNodes_.End(); ++i)
  66. {
  67. i->second_->SetScene(0);
  68. i->second_->SetOwner(0);
  69. }
  70. for (HashMap<unsigned, Node*>::Iterator i = localNodes_.Begin(); i != localNodes_.End(); ++i)
  71. {
  72. i->second_->SetScene(0);
  73. i->second_->SetOwner(0);
  74. }
  75. }
  76. void Scene::RegisterObject(Context* context)
  77. {
  78. context->RegisterFactory<Scene>();
  79. REF_ACCESSOR_ATTRIBUTE(Scene, VAR_STRING, "Name", GetName, SetName, String, String(), AM_DEFAULT);
  80. REF_ACCESSOR_ATTRIBUTE(Scene, VAR_VECTOR3, "Position", GetPosition, SetPosition, Vector3, Vector3::ZERO, AM_DEFAULT | AM_LATESTDATA);
  81. REF_ACCESSOR_ATTRIBUTE(Scene, VAR_QUATERNION, "Rotation", GetRotation, SetRotation, Quaternion, Quaternion::IDENTITY, AM_FILE);
  82. REF_ACCESSOR_ATTRIBUTE(Scene, VAR_VECTOR3, "Scale", GetScale, SetScale, Vector3, Vector3::ONE, AM_DEFAULT);
  83. ACCESSOR_ATTRIBUTE(Scene, VAR_FLOAT, "Smoothing Constant", GetSmoothingConstant, SetSmoothingConstant, float, DEFAULT_SMOOTHING_CONSTANT, AM_DEFAULT);
  84. ACCESSOR_ATTRIBUTE(Scene, VAR_FLOAT, "Snap Threshold", GetSnapThreshold, SetSnapThreshold, float, DEFAULT_SNAP_THRESHOLD, AM_DEFAULT);
  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_, VariantMap(), AM_FILE); // Network replication of vars uses custom data
  90. ACCESSOR_ATTRIBUTE(Scene, VAR_STRING, "Variable Names", GetVarNamesAttr, SetVarNamesAttr, String, String(), AM_FILE | AM_NOEDIT);
  91. REF_ACCESSOR_ATTRIBUTE(Scene, VAR_BUFFER, "Network Rotation", GetNetRotationAttr, SetNetRotationAttr, PODVector<unsigned char>, PODVector<unsigned char>(), 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_.xmlFile_.Reset();
  202. asyncProgress_.xmlElement_ = XMLElement();
  203. asyncProgress_.loadedNodes_ = 0;
  204. asyncProgress_.totalNodes_ = file->ReadVLE();
  205. return true;
  206. }
  207. bool Scene::LoadAsyncXML(File* file)
  208. {
  209. if (!file)
  210. {
  211. LOGERROR("Null file for async loading");
  212. return false;
  213. }
  214. StopAsyncLoading();
  215. SharedPtr<XMLFile> xml(new XMLFile(context_));
  216. if (!xml->Load(*file))
  217. return false;
  218. LOGINFO("Loading scene from " + file->GetName());
  219. Clear();
  220. XMLElement rootElement = xml->GetRoot();
  221. // Store own old ID for resolving possible root node references
  222. unsigned nodeID = rootElement.GetInt("id");
  223. resolver_.AddNode(nodeID, this);
  224. // Load the root level components first
  225. if (!Node::LoadXML(rootElement, resolver_, false))
  226. return false;
  227. // Then prepare for loading all root level child nodes in the async update
  228. XMLElement childNodeElement = rootElement.GetChild("node");
  229. asyncLoading_ = true;
  230. asyncProgress_.file_ = file;
  231. asyncProgress_.xmlFile_ = xml;
  232. asyncProgress_.xmlElement_ = childNodeElement;
  233. asyncProgress_.loadedNodes_ = 0;
  234. asyncProgress_.totalNodes_ = 0;
  235. // Count the amount of child nodes
  236. while (childNodeElement)
  237. {
  238. ++asyncProgress_.totalNodes_;
  239. childNodeElement = childNodeElement.GetNext("node");
  240. }
  241. return true;
  242. }
  243. void Scene::StopAsyncLoading()
  244. {
  245. asyncLoading_ = false;
  246. asyncProgress_.file_.Reset();
  247. asyncProgress_.xmlFile_.Reset();
  248. asyncProgress_.xmlElement_ = XMLElement();
  249. resolver_.Reset();
  250. }
  251. Node* Scene::Instantiate(Deserializer& source, const Vector3& position, const Quaternion& rotation, CreateMode mode)
  252. {
  253. PROFILE(Instantiate);
  254. SceneResolver resolver;
  255. unsigned nodeID = source.ReadInt();
  256. // Rewrite IDs when instantiating
  257. Node* node = CreateChild(0, mode);
  258. resolver.AddNode(nodeID, node);
  259. if (node->Load(source, resolver, true, true, mode))
  260. {
  261. resolver.Resolve();
  262. node->ApplyAttributes();
  263. node->SetTransform(position, rotation);
  264. return node;
  265. }
  266. else
  267. {
  268. node->Remove();
  269. return 0;
  270. }
  271. }
  272. Node* Scene::InstantiateXML(const XMLElement& source, const Vector3& position, const Quaternion& rotation, CreateMode mode)
  273. {
  274. PROFILE(InstantiateXML);
  275. SceneResolver resolver;
  276. unsigned nodeID = source.GetInt("id");
  277. // Rewrite IDs when instantiating
  278. Node* node = CreateChild(0, mode);
  279. resolver.AddNode(nodeID, node);
  280. if (node->LoadXML(source, resolver, true, true, mode))
  281. {
  282. resolver.Resolve();
  283. node->ApplyAttributes();
  284. node->SetTransform(position, rotation);
  285. return node;
  286. }
  287. else
  288. {
  289. node->Remove();
  290. return 0;
  291. }
  292. }
  293. Node* Scene::InstantiateXML(Deserializer& source, const Vector3& position, const Quaternion& rotation, CreateMode mode)
  294. {
  295. SharedPtr<XMLFile> xml(new XMLFile(context_));
  296. if (!xml->Load(source))
  297. return false;
  298. return InstantiateXML(xml->GetRoot(), position, rotation, mode);
  299. }
  300. void Scene::Clear()
  301. {
  302. StopAsyncLoading();
  303. RemoveAllChildren();
  304. RemoveAllComponents();
  305. fileName_ = String();
  306. checksum_ = 0;
  307. }
  308. void Scene::SetActive(bool enable)
  309. {
  310. active_ = enable;
  311. }
  312. void Scene::SetSmoothingConstant(float constant)
  313. {
  314. smoothingConstant_ = Max(constant, M_EPSILON);
  315. }
  316. void Scene::SetSnapThreshold(float threshold)
  317. {
  318. snapThreshold_ = Max(threshold, 0.0f);
  319. }
  320. void Scene::AddRequiredPackageFile(PackageFile* package)
  321. {
  322. // Do not add packages that failed to load
  323. if (!package || !package->GetNumFiles())
  324. return;
  325. requiredPackageFiles_.Push(SharedPtr<PackageFile>(package));
  326. }
  327. void Scene::ClearRequiredPackageFiles()
  328. {
  329. requiredPackageFiles_.Clear();
  330. }
  331. void Scene::RegisterVar(const String& name)
  332. {
  333. varNames_[ShortStringHash(name)] = name;
  334. }
  335. void Scene::UnregisterVar(const String& name)
  336. {
  337. varNames_.Erase(ShortStringHash(name));
  338. }
  339. void Scene::UnregisterAllVars()
  340. {
  341. varNames_.Clear();
  342. }
  343. Node* Scene::GetNode(unsigned id) const
  344. {
  345. if (id < FIRST_LOCAL_ID)
  346. {
  347. HashMap<unsigned, Node*>::ConstIterator i = replicatedNodes_.Find(id);
  348. if (i != replicatedNodes_.End())
  349. return i->second_;
  350. else
  351. return 0;
  352. }
  353. else
  354. {
  355. HashMap<unsigned, Node*>::ConstIterator i = localNodes_.Find(id);
  356. if (i != localNodes_.End())
  357. return i->second_;
  358. else
  359. return 0;
  360. }
  361. }
  362. Component* Scene::GetComponent(unsigned id) const
  363. {
  364. if (id < FIRST_LOCAL_ID)
  365. {
  366. HashMap<unsigned, Component*>::ConstIterator i = replicatedComponents_.Find(id);
  367. if (i != replicatedComponents_.End())
  368. return i->second_;
  369. else
  370. return 0;
  371. }
  372. else
  373. {
  374. HashMap<unsigned, Component*>::ConstIterator i = localComponents_.Find(id);
  375. if (i != localComponents_.End())
  376. return i->second_;
  377. else
  378. return 0;
  379. }
  380. }
  381. float Scene::GetAsyncProgress() const
  382. {
  383. if (!asyncLoading_ || !asyncProgress_.totalNodes_)
  384. return 1.0f;
  385. else
  386. return (float)asyncProgress_.loadedNodes_ / (float)asyncProgress_.totalNodes_;
  387. }
  388. const String& Scene::GetVarName(ShortStringHash hash) const
  389. {
  390. HashMap<ShortStringHash, String>::ConstIterator i = varNames_.Find(hash);
  391. return i != varNames_.End() ? i->second_ : emptyVarName;
  392. }
  393. void Scene::Update(float timeStep)
  394. {
  395. if (asyncLoading_)
  396. {
  397. UpdateAsyncLoading();
  398. return;
  399. }
  400. PROFILE(UpdateScene);
  401. using namespace SceneUpdate;
  402. VariantMap eventData;
  403. eventData[P_SCENE] = (void*)this;
  404. eventData[P_TIMESTEP] = timeStep;
  405. // Update variable timestep logic
  406. SendEvent(E_SCENEUPDATE, eventData);
  407. // Update scene subsystems. If a physics world is present, it will be updated, triggering fixed timestep logic updates
  408. SendEvent(E_SCENESUBSYSTEMUPDATE, eventData);
  409. // Update transform smoothing
  410. {
  411. PROFILE(UpdateSmoothing);
  412. float constant = 1.0f - Clamp(powf(2.0f, -timeStep * smoothingConstant_), 0.0f, 1.0f);
  413. float squaredSnapThreshold = snapThreshold_ * snapThreshold_;
  414. using namespace UpdateSmoothing;
  415. VariantMap eventData;
  416. eventData[P_CONSTANT] = constant;
  417. eventData[P_SQUAREDSNAPTHRESHOLD] = squaredSnapThreshold;
  418. SendEvent(E_UPDATESMOOTHING, eventData);
  419. }
  420. // Post-update variable timestep logic
  421. SendEvent(E_SCENEPOSTUPDATE, eventData);
  422. }
  423. void Scene::BeginThreadedUpdate()
  424. {
  425. // Check the work queue subsystem whether it actually has created worker threads. If not, do not enter threaded mode.
  426. if (GetSubsystem<WorkQueue>()->GetNumThreads())
  427. threadedUpdate_ = true;
  428. }
  429. void Scene::EndThreadedUpdate()
  430. {
  431. if (!threadedUpdate_)
  432. return;
  433. threadedUpdate_ = false;
  434. if (!delayedDirtyComponents_.Empty())
  435. {
  436. PROFILE(EndThreadedUpdate);
  437. for (PODVector<Component*>::ConstIterator i = delayedDirtyComponents_.Begin(); i != delayedDirtyComponents_.End(); ++i)
  438. (*i)->OnMarkedDirty((*i)->GetNode());
  439. delayedDirtyComponents_.Clear();
  440. }
  441. }
  442. void Scene::DelayedMarkedDirty(Component* component)
  443. {
  444. MutexLock lock(sceneMutex_);
  445. delayedDirtyComponents_.Push(component);
  446. }
  447. unsigned Scene::GetFreeNodeID(CreateMode mode)
  448. {
  449. if (mode == REPLICATED)
  450. {
  451. for (;;)
  452. {
  453. if (!replicatedNodes_.Contains(replicatedNodeID_))
  454. return replicatedNodeID_;
  455. if (replicatedNodeID_ != LAST_REPLICATED_ID)
  456. ++replicatedNodeID_;
  457. else
  458. replicatedNodeID_ = FIRST_REPLICATED_ID;
  459. }
  460. }
  461. else
  462. {
  463. for (;;)
  464. {
  465. if (!localNodes_.Contains(localNodeID_))
  466. return localNodeID_;
  467. if (localNodeID_ != LAST_LOCAL_ID)
  468. ++localNodeID_;
  469. else
  470. localNodeID_ = FIRST_LOCAL_ID;
  471. }
  472. }
  473. }
  474. unsigned Scene::GetFreeComponentID(CreateMode mode)
  475. {
  476. if (mode == REPLICATED)
  477. {
  478. for (;;)
  479. {
  480. if (!replicatedComponents_.Contains(replicatedComponentID_))
  481. return replicatedComponentID_;
  482. if (replicatedComponentID_ != LAST_REPLICATED_ID)
  483. ++replicatedComponentID_;
  484. else
  485. replicatedComponentID_ = FIRST_REPLICATED_ID;
  486. }
  487. }
  488. else
  489. {
  490. for (;;)
  491. {
  492. if (!localComponents_.Contains(localComponentID_))
  493. return localComponentID_;
  494. if (localComponentID_ != LAST_LOCAL_ID)
  495. ++localComponentID_;
  496. else
  497. localComponentID_ = FIRST_LOCAL_ID;
  498. }
  499. }
  500. }
  501. void Scene::NodeAdded(Node* node)
  502. {
  503. if (!node || node->GetScene())
  504. return;
  505. node->SetScene(this);
  506. // If we already have an existing node with the same ID, must remove the scene reference from it
  507. unsigned id = node->GetID();
  508. if (id < FIRST_LOCAL_ID)
  509. {
  510. HashMap<unsigned, Node*>::Iterator i = replicatedNodes_.Find(id);
  511. if (i != replicatedNodes_.End() && i->second_ != node)
  512. {
  513. LOGWARNING("Overwriting node with ID " + String(id));
  514. i->second_->SetScene(0);
  515. i->second_->SetOwner(0);
  516. }
  517. replicatedNodes_[id] = node;
  518. MarkNetworkUpdate(node);
  519. MarkReplicationDirty(node);
  520. }
  521. else
  522. {
  523. HashMap<unsigned, Node*>::Iterator i = localNodes_.Find(id);
  524. if (i != localNodes_.End() && i->second_ != node)
  525. {
  526. LOGWARNING("Overwriting node with ID " + String(id));
  527. i->second_->SetScene(0);
  528. i->second_->SetOwner(0);
  529. }
  530. localNodes_[id] = node;
  531. }
  532. }
  533. void Scene::NodeRemoved(Node* node)
  534. {
  535. if (!node || node->GetScene() != this)
  536. return;
  537. unsigned id = node->GetID();
  538. if (id < FIRST_LOCAL_ID)
  539. {
  540. replicatedNodes_.Erase(id);
  541. MarkReplicationDirty(node);
  542. }
  543. else
  544. localNodes_.Erase(id);
  545. node->SetID(0);
  546. node->SetScene(0);
  547. }
  548. void Scene::ComponentAdded(Component* component)
  549. {
  550. if (!component)
  551. return;
  552. unsigned id = component->GetID();
  553. if (id < FIRST_LOCAL_ID)
  554. {
  555. HashMap<unsigned, Component*>::Iterator i = replicatedComponents_.Find(id);
  556. if (i != replicatedComponents_.End() && i->second_ != component)
  557. LOGWARNING("Overwriting component with ID " + String(id));
  558. replicatedComponents_[id] = component;
  559. }
  560. else
  561. {
  562. HashMap<unsigned, Component*>::Iterator i = localComponents_.Find(id);
  563. if (i != localComponents_.End() && i->second_ != component)
  564. LOGWARNING("Overwriting component with ID " + String(id));
  565. localComponents_[id] = component;
  566. }
  567. }
  568. void Scene::ComponentRemoved(Component* component)
  569. {
  570. if (!component)
  571. return;
  572. unsigned id = component->GetID();
  573. if (id < FIRST_LOCAL_ID)
  574. replicatedComponents_.Erase(id);
  575. else
  576. localComponents_.Erase(id);
  577. component->SetID(0);
  578. }
  579. void Scene::SetVarNamesAttr(String value)
  580. {
  581. Vector<String> varNames = value.Split(';');
  582. varNames_.Clear();
  583. for (Vector<String>::ConstIterator i = varNames.Begin(); i != varNames.End(); ++i)
  584. varNames_[ShortStringHash(*i)] = *i;
  585. }
  586. String Scene::GetVarNamesAttr() const
  587. {
  588. String ret;
  589. for (HashMap<ShortStringHash, String>::ConstIterator i = varNames_.Begin(); i != varNames_.End(); ++i)
  590. {
  591. if (i != varNames_.Begin())
  592. ret += ';';
  593. ret += i->second_;
  594. }
  595. return ret;
  596. }
  597. void Scene::PrepareNetworkUpdate()
  598. {
  599. for (HashSet<unsigned>::Iterator i = networkUpdateNodes_.Begin(); i != networkUpdateNodes_.End(); ++i)
  600. {
  601. Node* node = GetNode(*i);
  602. if (node)
  603. node->PrepareNetworkUpdate();
  604. }
  605. for (HashSet<unsigned>::Iterator i = networkUpdateComponents_.Begin(); i != networkUpdateComponents_.End(); ++i)
  606. {
  607. Component* component = GetComponent(*i);
  608. if (component)
  609. component->PrepareNetworkUpdate();
  610. }
  611. networkUpdateNodes_.Clear();
  612. networkUpdateComponents_.Clear();
  613. }
  614. void Scene::CleanupConnection(Connection* connection)
  615. {
  616. Node::CleanupConnection(connection);
  617. for (HashMap<unsigned, Node*>::Iterator i = replicatedNodes_.Begin(); i != replicatedNodes_.End(); ++i)
  618. i->second_->CleanupConnection(connection);
  619. for (HashMap<unsigned, Component*>::Iterator i = replicatedComponents_.Begin(); i != replicatedComponents_.End(); ++i)
  620. i->second_->CleanupConnection(connection);
  621. }
  622. void Scene::MarkNetworkUpdate(Node* node)
  623. {
  624. if (node)
  625. networkUpdateNodes_.Insert(node->GetID());
  626. }
  627. void Scene::MarkNetworkUpdate(Component* component)
  628. {
  629. if (component)
  630. networkUpdateComponents_.Insert(component->GetID());
  631. }
  632. void Scene::MarkReplicationDirty(Node* node)
  633. {
  634. unsigned id = node->GetID();
  635. if (id < FIRST_LOCAL_ID && networkState_)
  636. {
  637. for (PODVector<ReplicationState*>::Iterator i = networkState_->replicationStates_.Begin(); i !=
  638. networkState_->replicationStates_.End(); ++i)
  639. {
  640. NodeReplicationState* nodeState = static_cast<NodeReplicationState*>(*i);
  641. nodeState->sceneState_->dirtyNodes_.Insert(id);
  642. }
  643. }
  644. }
  645. void Scene::HandleUpdate(StringHash eventType, VariantMap& eventData)
  646. {
  647. using namespace Update;
  648. if (active_)
  649. Update(eventData[P_TIMESTEP].GetFloat());
  650. }
  651. void Scene::UpdateAsyncLoading()
  652. {
  653. PROFILE(UpdateAsyncLoading);
  654. Timer asyncLoadTimer;
  655. for (;;)
  656. {
  657. if (asyncProgress_.loadedNodes_ >= asyncProgress_.totalNodes_)
  658. {
  659. FinishAsyncLoading();
  660. return;
  661. }
  662. // Read one child node with its full sub-hierarchy from either from binary or XML
  663. if (!asyncProgress_.xmlFile_)
  664. {
  665. unsigned nodeID = asyncProgress_.file_->ReadUInt();
  666. Node* newNode = CreateChild(nodeID, nodeID < FIRST_LOCAL_ID ? REPLICATED : LOCAL);
  667. resolver_.AddNode(nodeID, newNode);
  668. newNode->Load(*asyncProgress_.file_, resolver_);
  669. }
  670. else
  671. {
  672. unsigned nodeID = asyncProgress_.xmlElement_.GetInt("id");
  673. Node* newNode = CreateChild(nodeID, nodeID < FIRST_LOCAL_ID ? REPLICATED : LOCAL);
  674. resolver_.AddNode(nodeID, newNode);
  675. newNode->LoadXML(asyncProgress_.xmlElement_, resolver_);
  676. asyncProgress_.xmlElement_ = asyncProgress_.xmlElement_.GetNext("node");
  677. }
  678. ++asyncProgress_.loadedNodes_;
  679. // Break if time limit exceeded, so that we keep sufficient FPS
  680. if (asyncLoadTimer.GetMSec(false) >= ASYNC_LOAD_MAX_MSEC)
  681. break;
  682. }
  683. using namespace AsyncLoadProgress;
  684. VariantMap eventData;
  685. eventData[P_SCENE] = (void*)this;
  686. eventData[P_PROGRESS] = (float)asyncProgress_.loadedNodes_ / (float)asyncProgress_.totalNodes_;
  687. eventData[P_LOADEDNODES] = asyncProgress_.loadedNodes_;
  688. eventData[P_TOTALNODES] = asyncProgress_.totalNodes_;
  689. SendEvent(E_ASYNCLOADPROGRESS, eventData);
  690. }
  691. void Scene::FinishAsyncLoading()
  692. {
  693. resolver_.Resolve();
  694. ApplyAttributes();
  695. FinishLoading(asyncProgress_.file_);
  696. StopAsyncLoading();
  697. using namespace AsyncLoadFinished;
  698. VariantMap eventData;
  699. eventData[P_SCENE] = (void*)this;
  700. SendEvent(E_ASYNCLOADFINISHED, eventData);
  701. }
  702. void Scene::FinishLoading(Deserializer* source)
  703. {
  704. if (source)
  705. {
  706. fileName_ = source->GetName();
  707. checksum_ = source->GetChecksum();
  708. }
  709. }
  710. void RegisterSceneLibrary(Context* context)
  711. {
  712. Node::RegisterObject(context);
  713. Scene::RegisterObject(context);
  714. SmoothedTransform::RegisterObject(context);
  715. }