Scene.cpp 17 KB

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