Scene.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  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 "XMLFile.h"
  34. static const int ASYNC_LOAD_MIN_FPS = 50;
  35. static const int ASYNC_LOAD_MAX_MSEC = (int)(1000.0f / ASYNC_LOAD_MIN_FPS);
  36. OBJECTTYPESTATIC(Scene);
  37. Scene::Scene(Context* context) :
  38. Node(context),
  39. nonLocalNodeID_(FIRST_NONLOCAL_ID),
  40. nonLocalComponentID_(FIRST_NONLOCAL_ID),
  41. localNodeID_(FIRST_LOCAL_ID),
  42. localComponentID_(FIRST_LOCAL_ID),
  43. checksum_(0),
  44. active_(true),
  45. asyncLoading_(false)
  46. {
  47. // Assign an ID to self so that nodes can refer to this node as a parent
  48. SetID(GetFreeNodeID(false));
  49. NodeAdded(this);
  50. SubscribeToEvent(E_UPDATE, HANDLER(Scene, HandleUpdate));
  51. }
  52. Scene::~Scene()
  53. {
  54. // Remove scene reference and owner from all nodes that still exist
  55. for (Map<unsigned, Node*>::Iterator i = allNodes_.Begin(); i != allNodes_.End(); ++i)
  56. {
  57. i->second_->SetScene(0);
  58. i->second_->SetOwner(0);
  59. }
  60. }
  61. void Scene::RegisterObject(Context* context)
  62. {
  63. context->RegisterFactory<Scene>();
  64. context->CopyBaseAttributes<Node, Scene>();
  65. ATTRIBUTE(Scene, VAR_INT, "Next Non-Local Node ID", nonLocalNodeID_, FIRST_NONLOCAL_ID, AM_DEFAULT);
  66. ATTRIBUTE(Scene, VAR_INT, "Next Non-Local Component ID", nonLocalComponentID_, FIRST_NONLOCAL_ID, AM_DEFAULT);
  67. ATTRIBUTE(Scene, VAR_INT, "Next Local Node ID", localNodeID_, FIRST_LOCAL_ID, AM_DEFAULT);
  68. ATTRIBUTE(Scene, VAR_INT, "Next Local Component ID", localComponentID_, FIRST_LOCAL_ID, AM_DEFAULT);
  69. }
  70. bool Scene::Load(Deserializer& source)
  71. {
  72. StopAsyncLoading();
  73. // Check ID
  74. if (source.ReadID() != "USCN")
  75. {
  76. LOGERROR(source.GetName() + " is not a valid scene file");
  77. return false;
  78. }
  79. // Load the whole scene, then perform post-load if successfully loaded
  80. if (Node::Load(source))
  81. {
  82. FinishLoading(&source);
  83. return true;
  84. }
  85. else
  86. return false;
  87. }
  88. bool Scene::Save(Serializer& dest)
  89. {
  90. // Write ID first
  91. if (!dest.WriteID("USCN"))
  92. {
  93. LOGERROR("Could not save scene, writing to stream failed");
  94. return false;
  95. }
  96. return Node::Save(dest);
  97. }
  98. bool Scene::LoadXML(const XMLElement& source)
  99. {
  100. StopAsyncLoading();
  101. // Load the whole scene, then perform post-load if successfully loaded
  102. // Note: the scene filename and checksum can not be set, as we only used an XML element
  103. if (Node::LoadXML(source))
  104. {
  105. FinishLoading(0);
  106. return true;
  107. }
  108. else
  109. return false;
  110. }
  111. void Scene::Update(float timeStep)
  112. {
  113. if (asyncLoading_)
  114. {
  115. UpdateAsyncLoading();
  116. return;
  117. }
  118. PROFILE(UpdateScene);
  119. using namespace SceneUpdate;
  120. VariantMap eventData;
  121. eventData[P_SCENE] = (void*)this;
  122. eventData[P_TIMESTEP] = timeStep;
  123. // Update variable timestep logic
  124. SendEvent(E_SCENEUPDATE, eventData);
  125. // Update scene subsystems. If a physics world is present, it will be updated, triggering fixed timestep logic updates
  126. SendEvent(E_SCENESUBSYSTEMUPDATE, eventData);
  127. // Post-update variable timestep logic
  128. SendEvent(E_SCENEPOSTUPDATE, eventData);
  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. // Load the whole scene, then perform post-load if successfully loaded
  137. if (Node::LoadXML(xml->GetRoot()))
  138. {
  139. FinishLoading(&source);
  140. return true;
  141. }
  142. else
  143. return false;
  144. }
  145. bool Scene::SaveXML(Serializer& dest)
  146. {
  147. SharedPtr<XMLFile> xml(new XMLFile(context_));
  148. XMLElement rootElem = xml->CreateRoot("scene");
  149. if (!SaveXML(rootElem))
  150. return false;
  151. return xml->Save(dest);
  152. }
  153. bool Scene::LoadAsync(File* file)
  154. {
  155. if (!file)
  156. {
  157. LOGERROR("Null file for async loading");
  158. return false;
  159. }
  160. StopAsyncLoading();
  161. // Check ID
  162. if (file->ReadID() != "USCN")
  163. {
  164. LOGERROR(file->GetName() + " is not a valid scene file");
  165. return false;
  166. }
  167. // Clear the previous scene and load the root level components first
  168. Clear();
  169. if (!Node::Load(*file, false))
  170. return false;
  171. // Then prepare for loading all root level child nodes in the async update
  172. asyncLoading_ = true;
  173. asyncProgress_.file_ = file;
  174. asyncProgress_.xmlFile_.Reset();
  175. asyncProgress_.xmlElement_ = XMLElement();
  176. asyncProgress_.loadedNodes_ = 0;
  177. asyncProgress_.totalNodes_ = file->ReadVLE();
  178. return true;
  179. }
  180. bool Scene::LoadAsyncXML(File* file)
  181. {
  182. if (!file)
  183. {
  184. LOGERROR("Null file for async loading");
  185. return false;
  186. }
  187. StopAsyncLoading();
  188. SharedPtr<XMLFile> xmlFile(new XMLFile(context_));
  189. if (!xmlFile->Load(*file))
  190. return false;
  191. // Clear the previous scene and load the root level components first
  192. Clear();
  193. XMLElement rootElement = xmlFile->GetRoot();
  194. if (!Node::LoadXML(rootElement, false))
  195. return false;
  196. // Then prepare for loading all root level child nodes in the async update
  197. XMLElement childNodeElement = rootElement.GetChild("node");
  198. asyncLoading_ = true;
  199. asyncProgress_.file_ = file;
  200. asyncProgress_.xmlFile_ = xmlFile;
  201. asyncProgress_.xmlElement_ = childNodeElement;
  202. asyncProgress_.loadedNodes_ = 0;
  203. asyncProgress_.totalNodes_ = 0;
  204. // Count the amount of child nodes
  205. while (childNodeElement)
  206. {
  207. ++asyncProgress_.totalNodes_;
  208. childNodeElement = childNodeElement.GetNext("node");
  209. }
  210. return true;
  211. }
  212. void Scene::StopAsyncLoading()
  213. {
  214. asyncLoading_ = false;
  215. asyncProgress_.file_.Reset();
  216. asyncProgress_.xmlFile_.Reset();
  217. asyncProgress_.xmlElement_ = XMLElement();
  218. }
  219. void Scene::SetActive(bool enable)
  220. {
  221. active_ = enable;
  222. }
  223. void Scene::Clear()
  224. {
  225. RemoveAllChildren();
  226. RemoveAllComponents();
  227. fileName_ = String();
  228. checksum_ = 0;
  229. }
  230. void Scene::AddRequiredPackageFile(PackageFile* file)
  231. {
  232. if (file)
  233. requiredPackageFiles_.Push(SharedPtr<PackageFile>(file));
  234. }
  235. void Scene::ClearRequiredPackageFiles()
  236. {
  237. requiredPackageFiles_.Clear();
  238. }
  239. void Scene::ResetOwner(Connection* owner)
  240. {
  241. for (Map<unsigned, Node*>::Iterator i = allNodes_.Begin(); i != allNodes_.End(); ++i)
  242. {
  243. if (i->second_->GetOwner() == owner)
  244. i->second_->SetOwner(0);
  245. }
  246. }
  247. Node* Scene::GetNodeByID(unsigned id) const
  248. {
  249. Map<unsigned, Node*>::ConstIterator i = allNodes_.Find(id);
  250. if (i != allNodes_.End())
  251. return i->second_;
  252. else
  253. return 0;
  254. }
  255. Component* Scene::GetComponentByID(unsigned id) const
  256. {
  257. Map<unsigned, Component*>::ConstIterator i = allComponents_.Find(id);
  258. if (i != allComponents_.End())
  259. return i->second_;
  260. else
  261. return 0;
  262. }
  263. float Scene::GetAsyncProgress() const
  264. {
  265. if (!asyncLoading_ || !asyncProgress_.totalNodes_)
  266. return 1.0f;
  267. else
  268. return (float)asyncProgress_.loadedNodes_ / (float)asyncProgress_.totalNodes_;
  269. }
  270. unsigned Scene::GetFreeNodeID(bool local)
  271. {
  272. if (!local)
  273. {
  274. for (;;)
  275. {
  276. if (allNodes_.Find(nonLocalNodeID_) == allNodes_.End())
  277. return nonLocalNodeID_;
  278. if (nonLocalNodeID_ != LAST_NONLOCAL_ID)
  279. ++nonLocalNodeID_;
  280. else
  281. nonLocalNodeID_ = FIRST_NONLOCAL_ID;
  282. }
  283. }
  284. else
  285. {
  286. for (;;)
  287. {
  288. if (allNodes_.Find(localNodeID_) == allNodes_.End())
  289. return localNodeID_;
  290. if (localNodeID_ != LAST_LOCAL_ID)
  291. ++localNodeID_;
  292. else
  293. localNodeID_ = FIRST_LOCAL_ID;
  294. }
  295. }
  296. }
  297. unsigned Scene::GetFreeComponentID(bool local)
  298. {
  299. if (!local)
  300. {
  301. for (;;)
  302. {
  303. if (allComponents_.Find(nonLocalComponentID_) == allComponents_.End())
  304. return nonLocalComponentID_;
  305. if (nonLocalComponentID_ != LAST_NONLOCAL_ID)
  306. ++nonLocalComponentID_;
  307. else
  308. nonLocalComponentID_ = FIRST_NONLOCAL_ID;
  309. }
  310. }
  311. else
  312. {
  313. for (;;)
  314. {
  315. if (allComponents_.Find(localComponentID_) == allComponents_.End())
  316. return localComponentID_;
  317. if (localComponentID_ != LAST_LOCAL_ID)
  318. ++localComponentID_;
  319. else
  320. localComponentID_ = FIRST_LOCAL_ID;
  321. }
  322. }
  323. }
  324. void Scene::NodeAdded(Node* node)
  325. {
  326. if (!node || node->GetScene())
  327. return;
  328. node->SetScene(this);
  329. // If we already have an existing node with the same ID, must remove the scene reference from it
  330. unsigned id = node->GetID();
  331. Map<unsigned, Node*>::Iterator i = allNodes_.Find(id);
  332. if (i != allNodes_.End() && i->second_ != node)
  333. {
  334. LOGWARNING("Overwriting node with ID " + String(id));
  335. i->second_->SetScene(0);
  336. i->second_->SetOwner(0);
  337. }
  338. allNodes_[id] = node;
  339. }
  340. void Scene::NodeRemoved(Node* node)
  341. {
  342. if (!node || node->GetScene() != this)
  343. return;
  344. allNodes_.Erase(node->GetID());
  345. node->SetID(0);
  346. node->SetScene(0);
  347. }
  348. void Scene::ComponentAdded(Component* component)
  349. {
  350. if (!component)
  351. return;
  352. allComponents_[component->GetID()] = component;
  353. }
  354. void Scene::ComponentRemoved(Component* component)
  355. {
  356. if (!component)
  357. return;
  358. allComponents_.Erase(component->GetID());
  359. component->SetID(0);
  360. }
  361. void Scene::HandleUpdate(StringHash eventType, VariantMap& eventData)
  362. {
  363. using namespace Update;
  364. if (active_)
  365. Update(eventData[P_TIMESTEP].GetFloat());
  366. }
  367. void Scene::UpdateAsyncLoading()
  368. {
  369. PROFILE(UpdateAsyncLoading);
  370. Timer asyncLoadTimer;
  371. for (;;)
  372. {
  373. if (asyncProgress_.loadedNodes_ >= asyncProgress_.totalNodes_)
  374. {
  375. FinishAsyncLoading();
  376. return;
  377. }
  378. // Read one child node either from binary or XML
  379. if (!asyncProgress_.xmlFile_)
  380. {
  381. Node* newNode = CreateChild(asyncProgress_.file_->ReadUInt(), false);
  382. newNode->Load(*asyncProgress_.file_);
  383. }
  384. else
  385. {
  386. Node* newNode = CreateChild(asyncProgress_.xmlElement_.GetInt("id"), false);
  387. newNode->LoadXML(asyncProgress_.xmlElement_);
  388. asyncProgress_.xmlElement_ = asyncProgress_.xmlElement_.GetNext("node");
  389. }
  390. ++asyncProgress_.loadedNodes_;
  391. // Break if time limit exceeded, so that we keep sufficient FPS
  392. if (asyncLoadTimer.GetMSec(false) >= ASYNC_LOAD_MAX_MSEC)
  393. break;
  394. }
  395. using namespace AsyncLoadProgress;
  396. VariantMap eventData;
  397. eventData[P_SCENE] = (void*)this;
  398. eventData[P_PROGRESS] = (float)asyncProgress_.loadedNodes_ / (float)asyncProgress_.totalNodes_;
  399. eventData[P_LOADEDNODES] = asyncProgress_.loadedNodes_;
  400. eventData[P_TOTALNODES] = asyncProgress_.totalNodes_;
  401. SendEvent(E_ASYNCLOADPROGRESS, eventData);
  402. }
  403. void Scene::FinishAsyncLoading()
  404. {
  405. FinishLoading(asyncProgress_.file_);
  406. StopAsyncLoading();
  407. using namespace AsyncLoadFinished;
  408. VariantMap eventData;
  409. eventData[P_SCENE] = (void*)this;
  410. SendEvent(E_ASYNCLOADFINISHED, eventData);
  411. }
  412. void Scene::FinishLoading(Deserializer* source)
  413. {
  414. OnFinishUpdate();
  415. if (source)
  416. {
  417. fileName_ = source->GetName();
  418. checksum_ = source->GetChecksum();
  419. }
  420. }
  421. void RegisterSceneLibrary(Context* context)
  422. {
  423. Node::RegisterObject(context);
  424. Scene::RegisterObject(context);
  425. }