Scene.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2011 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 "Scene.h"
  32. #include "SceneEvents.h"
  33. #include "WorkQueue.h"
  34. #include "XMLFile.h"
  35. static const int ASYNC_LOAD_MIN_FPS = 50;
  36. static const int ASYNC_LOAD_MAX_MSEC = (int)(1000.0f / ASYNC_LOAD_MIN_FPS);
  37. static const float DEFAULT_SMOOTHING_CONSTANT = 50.0f;
  38. static const float DEFAULT_SNAP_THRESHOLD = 1.0f;
  39. static const String emptyVarName;
  40. OBJECTTYPESTATIC(Scene);
  41. Scene::Scene(Context* context) :
  42. Node(context),
  43. replicatedNodeID_(FIRST_REPLICATED_ID),
  44. replicatedComponentID_(FIRST_REPLICATED_ID),
  45. localNodeID_(FIRST_LOCAL_ID),
  46. localComponentID_(FIRST_LOCAL_ID),
  47. smoothingConstant_(DEFAULT_SMOOTHING_CONSTANT),
  48. snapThreshold_(DEFAULT_SNAP_THRESHOLD),
  49. checksum_(0),
  50. active_(true),
  51. asyncLoading_(false),
  52. threadedUpdate_(false)
  53. {
  54. // Assign an ID to self so that nodes can refer to this node as a parent
  55. SetID(GetFreeNodeID(REPLICATED));
  56. NodeAdded(this);
  57. SubscribeToEvent(E_UPDATE, HANDLER(Scene, HandleUpdate));
  58. }
  59. Scene::~Scene()
  60. {
  61. // Remove scene reference and owner from all nodes that still exist
  62. for (Map<unsigned, Node*>::Iterator i = allNodes_.Begin(); i != allNodes_.End(); ++i)
  63. {
  64. i->second_->SetScene(0);
  65. i->second_->SetOwner(0);
  66. }
  67. }
  68. void Scene::RegisterObject(Context* context)
  69. {
  70. context->RegisterFactory<Scene>();
  71. REF_ACCESSOR_ATTRIBUTE(Scene, VAR_STRING, "Name", GetName, SetName, String, String(), AM_DEFAULT);
  72. REF_ACCESSOR_ATTRIBUTE(Scene, VAR_VECTOR3, "Position", GetPosition, SetPosition, Vector3, Vector3::ZERO, AM_DEFAULT | AM_LATESTDATA);
  73. REF_ACCESSOR_ATTRIBUTE(Scene, VAR_QUATERNION, "Rotation", GetRotation, SetRotation, Quaternion, Quaternion::IDENTITY, AM_FILE);
  74. REF_ACCESSOR_ATTRIBUTE(Scene, VAR_VECTOR3, "Scale", GetScale, SetScale, Vector3, Vector3::ONE, AM_DEFAULT);
  75. ACCESSOR_ATTRIBUTE(Scene, VAR_FLOAT, "Smoothing Constant", GetSmoothingConstant, SetSmoothingConstant, float, DEFAULT_SMOOTHING_CONSTANT, AM_DEFAULT);
  76. ACCESSOR_ATTRIBUTE(Scene, VAR_FLOAT, "Snap Threshold", GetSnapThreshold, SetSnapThreshold, float, DEFAULT_SNAP_THRESHOLD, AM_DEFAULT);
  77. ATTRIBUTE(Scene, VAR_INT, "Next Replicated Node ID", replicatedNodeID_, FIRST_REPLICATED_ID, AM_FILE | AM_NOEDIT);
  78. ATTRIBUTE(Scene, VAR_INT, "Next Replicated Component ID", replicatedComponentID_, FIRST_REPLICATED_ID, AM_FILE | AM_NOEDIT);
  79. ATTRIBUTE(Scene, VAR_INT, "Next Local Node ID", localNodeID_, FIRST_LOCAL_ID, AM_FILE | AM_NOEDIT);
  80. ATTRIBUTE(Scene, VAR_INT, "Next Local Component ID", localComponentID_, FIRST_LOCAL_ID, AM_FILE | AM_NOEDIT);
  81. ATTRIBUTE(Scene, VAR_VARIANTMAP, "Variables", vars_, VariantMap(), AM_FILE); // Network replication of vars uses custom data
  82. ACCESSOR_ATTRIBUTE(Scene, VAR_STRING, "Variable Names", GetVarNamesAttr, SetVarNamesAttr, String, String(), AM_FILE | AM_NOEDIT);
  83. REF_ACCESSOR_ATTRIBUTE(Scene, VAR_BUFFER, "Network Rotation", GetNetRotationAttr, SetNetRotationAttr, PODVector<unsigned char>, PODVector<unsigned char>(), AM_NET | AM_LATESTDATA | AM_NOEDIT);
  84. }
  85. bool Scene::Load(Deserializer& source)
  86. {
  87. StopAsyncLoading();
  88. // Check ID
  89. if (source.ReadFileID() != "USCN")
  90. {
  91. LOGERROR(source.GetName() + " is not a valid scene file");
  92. return false;
  93. }
  94. LOGINFO("Loading scene from " + source.GetName());
  95. // Load the whole scene, then perform post-load if successfully loaded
  96. if (Node::Load(source))
  97. {
  98. FinishLoading(&source);
  99. return true;
  100. }
  101. else
  102. return false;
  103. }
  104. bool Scene::Save(Serializer& dest)
  105. {
  106. // Write ID first
  107. if (!dest.WriteFileID("USCN"))
  108. {
  109. LOGERROR("Could not save scene, writing to stream failed");
  110. return false;
  111. }
  112. Deserializer* ptr = dynamic_cast<Deserializer*>(&dest);
  113. if (ptr)
  114. LOGINFO("Saving scene to " + ptr->GetName());
  115. return Node::Save(dest);
  116. }
  117. bool Scene::LoadXML(const XMLElement& source)
  118. {
  119. StopAsyncLoading();
  120. // Load the whole scene, then perform post-load if successfully loaded
  121. // Note: the scene filename and checksum can not be set, as we only used an XML element
  122. if (Node::LoadXML(source))
  123. {
  124. FinishLoading(0);
  125. return true;
  126. }
  127. else
  128. return false;
  129. }
  130. bool Scene::LoadXML(Deserializer& source)
  131. {
  132. StopAsyncLoading();
  133. SharedPtr<XMLFile> xml(new XMLFile(context_));
  134. if (!xml->Load(source))
  135. return false;
  136. LOGINFO("Loading scene from " + source.GetName());
  137. // Load the whole scene, then perform post-load if successfully loaded
  138. if (Node::LoadXML(xml->GetRoot()))
  139. {
  140. FinishLoading(&source);
  141. return true;
  142. }
  143. else
  144. return false;
  145. }
  146. bool Scene::SaveXML(Serializer& dest)
  147. {
  148. SharedPtr<XMLFile> xml(new XMLFile(context_));
  149. XMLElement rootElem = xml->CreateRoot("scene");
  150. if (!SaveXML(rootElem))
  151. return false;
  152. Deserializer* ptr = dynamic_cast<Deserializer*>(&dest);
  153. if (ptr)
  154. LOGINFO("Saving scene to " + ptr->GetName());
  155. return xml->Save(dest);
  156. }
  157. bool Scene::LoadAsync(File* file)
  158. {
  159. if (!file)
  160. {
  161. LOGERROR("Null file for async loading");
  162. return false;
  163. }
  164. StopAsyncLoading();
  165. // Check ID
  166. if (file->ReadFileID() != "USCN")
  167. {
  168. LOGERROR(file->GetName() + " is not a valid scene file");
  169. return false;
  170. }
  171. LOGINFO("Loading scene from " + file->GetName());
  172. // Clear the previous scene and load the root level components first
  173. Clear();
  174. if (!Node::Load(*file, resolver_, false))
  175. return false;
  176. // Then prepare for loading all root level child nodes in the async update
  177. asyncLoading_ = true;
  178. asyncProgress_.file_ = file;
  179. asyncProgress_.xmlFile_.Reset();
  180. asyncProgress_.xmlElement_ = XMLElement();
  181. asyncProgress_.loadedNodes_ = 0;
  182. asyncProgress_.totalNodes_ = file->ReadVLE();
  183. return true;
  184. }
  185. bool Scene::LoadAsyncXML(File* file)
  186. {
  187. if (!file)
  188. {
  189. LOGERROR("Null file for async loading");
  190. return false;
  191. }
  192. StopAsyncLoading();
  193. SharedPtr<XMLFile> xmlFile(new XMLFile(context_));
  194. if (!xmlFile->Load(*file))
  195. return false;
  196. LOGINFO("Loading scene from " + file->GetName());
  197. // Clear the previous scene and load the root level components first
  198. Clear();
  199. XMLElement rootElement = xmlFile->GetRoot();
  200. if (!Node::LoadXML(rootElement, resolver_, false))
  201. return false;
  202. // Then prepare for loading all root level child nodes in the async update
  203. XMLElement childNodeElement = rootElement.GetChild("node");
  204. asyncLoading_ = true;
  205. asyncProgress_.file_ = file;
  206. asyncProgress_.xmlFile_ = xmlFile;
  207. asyncProgress_.xmlElement_ = childNodeElement;
  208. asyncProgress_.loadedNodes_ = 0;
  209. asyncProgress_.totalNodes_ = 0;
  210. // Count the amount of child nodes
  211. while (childNodeElement)
  212. {
  213. ++asyncProgress_.totalNodes_;
  214. childNodeElement = childNodeElement.GetNext("node");
  215. }
  216. return true;
  217. }
  218. void Scene::StopAsyncLoading()
  219. {
  220. asyncLoading_ = false;
  221. asyncProgress_.file_.Reset();
  222. asyncProgress_.xmlFile_.Reset();
  223. asyncProgress_.xmlElement_ = XMLElement();
  224. }
  225. void Scene::Clear()
  226. {
  227. StopAsyncLoading();
  228. RemoveAllChildren();
  229. RemoveAllComponents();
  230. fileName_ = String();
  231. checksum_ = 0;
  232. resolver_.Reset();
  233. }
  234. void Scene::SetActive(bool enable)
  235. {
  236. active_ = enable;
  237. }
  238. void Scene::SetSmoothingConstant(float constant)
  239. {
  240. smoothingConstant_ = Max(constant, M_EPSILON);
  241. }
  242. void Scene::SetSnapThreshold(float threshold)
  243. {
  244. snapThreshold_ = Max(threshold, 0.0f);
  245. }
  246. void Scene::AddRequiredPackageFile(PackageFile* package)
  247. {
  248. // Do not add packages that failed to load
  249. if (!package || !package->GetNumFiles())
  250. return;
  251. requiredPackageFiles_.Push(SharedPtr<PackageFile>(package));
  252. }
  253. void Scene::ClearRequiredPackageFiles()
  254. {
  255. requiredPackageFiles_.Clear();
  256. }
  257. void Scene::ResetOwner(Connection* owner)
  258. {
  259. for (Map<unsigned, Node*>::Iterator i = allNodes_.Begin(); i != allNodes_.End(); ++i)
  260. {
  261. if (i->second_->GetOwner() == owner)
  262. i->second_->SetOwner(0);
  263. }
  264. }
  265. void Scene::RegisterVar(const String& name)
  266. {
  267. varNames_[ShortStringHash(name)] = name;
  268. }
  269. void Scene::UnregisterVar(const String& name)
  270. {
  271. varNames_.Erase(ShortStringHash(name));
  272. }
  273. void Scene::UnregisterAllVars()
  274. {
  275. varNames_.Clear();
  276. }
  277. Node* Scene::GetNode(unsigned id) const
  278. {
  279. Map<unsigned, Node*>::ConstIterator i = allNodes_.Find(id);
  280. if (i != allNodes_.End())
  281. return i->second_;
  282. else
  283. return 0;
  284. }
  285. Component* Scene::GetComponent(unsigned id) const
  286. {
  287. Map<unsigned, Component*>::ConstIterator i = allComponents_.Find(id);
  288. if (i != allComponents_.End())
  289. return i->second_;
  290. else
  291. return 0;
  292. }
  293. float Scene::GetAsyncProgress() const
  294. {
  295. if (!asyncLoading_ || !asyncProgress_.totalNodes_)
  296. return 1.0f;
  297. else
  298. return (float)asyncProgress_.loadedNodes_ / (float)asyncProgress_.totalNodes_;
  299. }
  300. const String& Scene::GetVarName(ShortStringHash hash) const
  301. {
  302. Map<ShortStringHash, String>::ConstIterator i = varNames_.Find(hash);
  303. return i != varNames_.End() ? i->second_ : emptyVarName;
  304. }
  305. void Scene::Update(float timeStep)
  306. {
  307. if (asyncLoading_)
  308. {
  309. UpdateAsyncLoading();
  310. return;
  311. }
  312. PROFILE(UpdateScene);
  313. using namespace SceneUpdate;
  314. VariantMap eventData;
  315. eventData[P_SCENE] = (void*)this;
  316. eventData[P_TIMESTEP] = timeStep;
  317. // Update variable timestep logic
  318. SendEvent(E_SCENEUPDATE, eventData);
  319. // Update scene subsystems. If a physics world is present, it will be updated, triggering fixed timestep logic updates
  320. SendEvent(E_SCENESUBSYSTEMUPDATE, eventData);
  321. // Update smoothing if enabled (network client scenes)
  322. if (IsSmoothed())
  323. {
  324. PROFILE(UpdateSmoothing);
  325. float constant = 1.0f - Clamp(powf(2.0f, -timeStep * smoothingConstant_), 0.0f, 1.0f);
  326. float squaredSnapThreshold = snapThreshold_ * snapThreshold_;
  327. for (Map<unsigned, Node*>::ConstIterator i = allNodes_.Begin(); i != allNodes_.End() && i->first_ < FIRST_LOCAL_ID; ++i)
  328. i->second_->UpdateSmoothing(constant, squaredSnapThreshold);
  329. }
  330. // Post-update variable timestep logic
  331. SendEvent(E_SCENEPOSTUPDATE, eventData);
  332. }
  333. void Scene::BeginThreadedUpdate()
  334. {
  335. // Check the work queue subsystem whether it actually has created worker threads. If not, do not enter threaded mode.
  336. if (GetSubsystem<WorkQueue>()->GetNumThreads())
  337. threadedUpdate_ = true;
  338. }
  339. void Scene::EndThreadedUpdate()
  340. {
  341. if (!threadedUpdate_)
  342. return;
  343. threadedUpdate_ = false;
  344. if (!delayedDirtyComponents_.Empty())
  345. {
  346. PROFILE(EndThreadedUpdate);
  347. for (PODVector<Component*>::ConstIterator i = delayedDirtyComponents_.Begin(); i != delayedDirtyComponents_.End(); ++i)
  348. (*i)->OnMarkedDirty((*i)->GetNode());
  349. delayedDirtyComponents_.Clear();
  350. }
  351. }
  352. void Scene::DelayedMarkedDirty(Component* component)
  353. {
  354. MutexLock lock(sceneMutex_);
  355. delayedDirtyComponents_.Push(component);
  356. }
  357. unsigned Scene::GetFreeNodeID(CreateMode mode)
  358. {
  359. if (mode == REPLICATED)
  360. {
  361. for (;;)
  362. {
  363. if (!allNodes_.Contains(replicatedNodeID_))
  364. return replicatedNodeID_;
  365. if (replicatedNodeID_ != LAST_REPLICATED_ID)
  366. ++replicatedNodeID_;
  367. else
  368. replicatedNodeID_ = FIRST_REPLICATED_ID;
  369. }
  370. }
  371. else
  372. {
  373. for (;;)
  374. {
  375. if (!allNodes_.Contains(localNodeID_))
  376. return localNodeID_;
  377. if (localNodeID_ != LAST_LOCAL_ID)
  378. ++localNodeID_;
  379. else
  380. localNodeID_ = FIRST_LOCAL_ID;
  381. }
  382. }
  383. }
  384. unsigned Scene::GetFreeComponentID(CreateMode mode)
  385. {
  386. if (mode == REPLICATED)
  387. {
  388. for (;;)
  389. {
  390. if (!allComponents_.Contains(replicatedComponentID_))
  391. return replicatedComponentID_;
  392. if (replicatedComponentID_ != LAST_REPLICATED_ID)
  393. ++replicatedComponentID_;
  394. else
  395. replicatedComponentID_ = FIRST_REPLICATED_ID;
  396. }
  397. }
  398. else
  399. {
  400. for (;;)
  401. {
  402. if (!allComponents_.Contains(localComponentID_))
  403. return localComponentID_;
  404. if (localComponentID_ != LAST_LOCAL_ID)
  405. ++localComponentID_;
  406. else
  407. localComponentID_ = FIRST_LOCAL_ID;
  408. }
  409. }
  410. }
  411. void Scene::NodeAdded(Node* node)
  412. {
  413. if (!node || node->GetScene())
  414. return;
  415. node->SetScene(this);
  416. // If we already have an existing node with the same ID, must remove the scene reference from it
  417. unsigned id = node->GetID();
  418. Map<unsigned, Node*>::Iterator i = allNodes_.Find(id);
  419. if (i != allNodes_.End() && i->second_ != node)
  420. {
  421. LOGWARNING("Overwriting node with ID " + String(id));
  422. i->second_->SetScene(0);
  423. i->second_->SetOwner(0);
  424. }
  425. allNodes_[id] = node;
  426. }
  427. void Scene::NodeRemoved(Node* node)
  428. {
  429. if (!node || node->GetScene() != this)
  430. return;
  431. allNodes_.Erase(node->GetID());
  432. node->SetID(0);
  433. node->SetScene(0);
  434. }
  435. void Scene::ComponentAdded(Component* component)
  436. {
  437. if (!component)
  438. return;
  439. unsigned id = component->GetID();
  440. Map<unsigned, Component*>::Iterator i = allComponents_.Find(id);
  441. if (i != allComponents_.End() && i->second_ != component)
  442. LOGWARNING("Overwriting component with ID " + String(id));
  443. allComponents_[id] = component;
  444. }
  445. void Scene::ComponentRemoved(Component* component)
  446. {
  447. if (!component)
  448. return;
  449. allComponents_.Erase(component->GetID());
  450. component->SetID(0);
  451. }
  452. void Scene::SetVarNamesAttr(String value)
  453. {
  454. Vector<String> varNames = value.Split(';');
  455. varNames_.Clear();
  456. for (Vector<String>::ConstIterator i = varNames.Begin(); i != varNames.End(); ++i)
  457. varNames_[ShortStringHash(*i)] = *i;
  458. }
  459. String Scene::GetVarNamesAttr() const
  460. {
  461. String ret;
  462. for (Map<ShortStringHash, String>::ConstIterator i = varNames_.Begin(); i != varNames_.End(); ++i)
  463. {
  464. if (i != varNames_.Begin())
  465. ret += ';';
  466. ret += i->second_;
  467. }
  468. return ret;
  469. }
  470. void Scene::HandleUpdate(StringHash eventType, VariantMap& eventData)
  471. {
  472. using namespace Update;
  473. if (active_)
  474. Update(eventData[P_TIMESTEP].GetFloat());
  475. }
  476. void Scene::UpdateAsyncLoading()
  477. {
  478. PROFILE(UpdateAsyncLoading);
  479. Timer asyncLoadTimer;
  480. for (;;)
  481. {
  482. if (asyncProgress_.loadedNodes_ >= asyncProgress_.totalNodes_)
  483. {
  484. FinishAsyncLoading();
  485. return;
  486. }
  487. // Read one child node with its full sub-hierarchy from either from binary or XML
  488. if (!asyncProgress_.xmlFile_)
  489. {
  490. Node* newNode = CreateChild(asyncProgress_.file_->ReadUInt(), REPLICATED);
  491. newNode->Load(*asyncProgress_.file_, resolver_);
  492. }
  493. else
  494. {
  495. Node* newNode = CreateChild(asyncProgress_.xmlElement_.GetInt("id"), REPLICATED);
  496. newNode->LoadXML(asyncProgress_.xmlElement_, resolver_);
  497. asyncProgress_.xmlElement_ = asyncProgress_.xmlElement_.GetNext("node");
  498. }
  499. ++asyncProgress_.loadedNodes_;
  500. // Break if time limit exceeded, so that we keep sufficient FPS
  501. if (asyncLoadTimer.GetMSec(false) >= ASYNC_LOAD_MAX_MSEC)
  502. break;
  503. }
  504. using namespace AsyncLoadProgress;
  505. VariantMap eventData;
  506. eventData[P_SCENE] = (void*)this;
  507. eventData[P_PROGRESS] = (float)asyncProgress_.loadedNodes_ / (float)asyncProgress_.totalNodes_;
  508. eventData[P_LOADEDNODES] = asyncProgress_.loadedNodes_;
  509. eventData[P_TOTALNODES] = asyncProgress_.totalNodes_;
  510. SendEvent(E_ASYNCLOADPROGRESS, eventData);
  511. }
  512. void Scene::FinishAsyncLoading()
  513. {
  514. resolver_.Resolve();
  515. ApplyAttributes();
  516. FinishLoading(asyncProgress_.file_);
  517. StopAsyncLoading();
  518. using namespace AsyncLoadFinished;
  519. VariantMap eventData;
  520. eventData[P_SCENE] = (void*)this;
  521. SendEvent(E_ASYNCLOADFINISHED, eventData);
  522. }
  523. void Scene::FinishLoading(Deserializer* source)
  524. {
  525. if (source)
  526. {
  527. fileName_ = source->GetName();
  528. checksum_ = source->GetChecksum();
  529. }
  530. }
  531. void RegisterSceneLibrary(Context* context)
  532. {
  533. Node::RegisterObject(context);
  534. Scene::RegisterObject(context);
  535. }