Scene.cpp 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245
  1. //
  2. // Copyright (c) 2008-2015 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 "../Core/Context.h"
  24. #include "../Core/CoreEvents.h"
  25. #include "../Core/Profiler.h"
  26. #include "../Core/WorkQueue.h"
  27. #include "../IO/File.h"
  28. #include "../IO/Log.h"
  29. #include "../IO/PackageFile.h"
  30. #include "../Resource/ResourceCache.h"
  31. #include "../Resource/ResourceEvents.h"
  32. #include "../Resource/XMLFile.h"
  33. #include "../Scene/Component.h"
  34. #include "../Scene/ObjectAnimation.h"
  35. #include "../Scene/ReplicationState.h"
  36. #include "../Scene/Scene.h"
  37. #include "../Scene/SceneEvents.h"
  38. #include "../Scene/SmoothedTransform.h"
  39. #include "../Scene/SplinePath.h"
  40. #include "../Scene/UnknownComponent.h"
  41. #include "../Scene/ValueAnimation.h"
  42. #include "../DebugNew.h"
  43. namespace Urho3D
  44. {
  45. const char* SCENE_CATEGORY = "Scene";
  46. const char* LOGIC_CATEGORY = "Logic";
  47. const char* SUBSYSTEM_CATEGORY = "Subsystem";
  48. static const float DEFAULT_SMOOTHING_CONSTANT = 50.0f;
  49. static const float DEFAULT_SNAP_THRESHOLD = 5.0f;
  50. Scene::Scene(Context* context) :
  51. Node(context),
  52. replicatedNodeID_(FIRST_REPLICATED_ID),
  53. replicatedComponentID_(FIRST_REPLICATED_ID),
  54. localNodeID_(FIRST_LOCAL_ID),
  55. localComponentID_(FIRST_LOCAL_ID),
  56. checksum_(0),
  57. asyncLoadingMs_(5),
  58. timeScale_(1.0f),
  59. elapsedTime_(0),
  60. smoothingConstant_(DEFAULT_SMOOTHING_CONSTANT),
  61. snapThreshold_(DEFAULT_SNAP_THRESHOLD),
  62. updateEnabled_(true),
  63. asyncLoading_(false),
  64. threadedUpdate_(false)
  65. {
  66. // Assign an ID to self so that nodes can refer to this node as a parent
  67. SetID(GetFreeNodeID(REPLICATED));
  68. NodeAdded(this);
  69. SubscribeToEvent(E_UPDATE, URHO3D_HANDLER(Scene, HandleUpdate));
  70. SubscribeToEvent(E_RESOURCEBACKGROUNDLOADED, URHO3D_HANDLER(Scene, HandleResourceBackgroundLoaded));
  71. }
  72. Scene::~Scene()
  73. {
  74. // Remove root-level components first, so that scene subsystems such as the octree destroy themselves. This will speed up
  75. // the removal of child nodes' components
  76. RemoveAllComponents();
  77. RemoveAllChildren();
  78. // Remove scene reference and owner from all nodes that still exist
  79. for (HashMap<unsigned, Node*>::Iterator i = replicatedNodes_.Begin(); i != replicatedNodes_.End(); ++i)
  80. i->second_->ResetScene();
  81. for (HashMap<unsigned, Node*>::Iterator i = localNodes_.Begin(); i != localNodes_.End(); ++i)
  82. i->second_->ResetScene();
  83. }
  84. void Scene::RegisterObject(Context* context)
  85. {
  86. context->RegisterFactory<Scene>();
  87. URHO3D_ACCESSOR_ATTRIBUTE("Name", GetName, SetName, String, String::EMPTY, AM_DEFAULT);
  88. URHO3D_ACCESSOR_ATTRIBUTE("Time Scale", GetTimeScale, SetTimeScale, float, 1.0f, AM_DEFAULT);
  89. URHO3D_ACCESSOR_ATTRIBUTE("Smoothing Constant", GetSmoothingConstant, SetSmoothingConstant, float, DEFAULT_SMOOTHING_CONSTANT,
  90. AM_DEFAULT);
  91. URHO3D_ACCESSOR_ATTRIBUTE("Snap Threshold", GetSnapThreshold, SetSnapThreshold, float, DEFAULT_SNAP_THRESHOLD, AM_DEFAULT);
  92. URHO3D_ACCESSOR_ATTRIBUTE("Elapsed Time", GetElapsedTime, SetElapsedTime, float, 0.0f, AM_FILE);
  93. URHO3D_ATTRIBUTE("Next Replicated Node ID", unsigned, replicatedNodeID_, FIRST_REPLICATED_ID, AM_FILE | AM_NOEDIT);
  94. URHO3D_ATTRIBUTE("Next Replicated Component ID", unsigned, replicatedComponentID_, FIRST_REPLICATED_ID, AM_FILE | AM_NOEDIT);
  95. URHO3D_ATTRIBUTE("Next Local Node ID", unsigned, localNodeID_, FIRST_LOCAL_ID, AM_FILE | AM_NOEDIT);
  96. URHO3D_ATTRIBUTE("Next Local Component ID", unsigned, localComponentID_, FIRST_LOCAL_ID, AM_FILE | AM_NOEDIT);
  97. URHO3D_ATTRIBUTE("Variables", VariantMap, vars_, Variant::emptyVariantMap, AM_FILE); // Network replication of vars uses custom data
  98. URHO3D_MIXED_ACCESSOR_ATTRIBUTE("Variable Names", GetVarNamesAttr, SetVarNamesAttr, String, String::EMPTY, AM_FILE | AM_NOEDIT);
  99. }
  100. bool Scene::Load(Deserializer& source, bool setInstanceDefault)
  101. {
  102. URHO3D_PROFILE(LoadScene);
  103. StopAsyncLoading();
  104. // Check ID
  105. if (source.ReadFileID() != "USCN")
  106. {
  107. URHO3D_LOGERROR(source.GetName() + " is not a valid scene file");
  108. return false;
  109. }
  110. URHO3D_LOGINFO("Loading scene from " + source.GetName());
  111. Clear();
  112. // Load the whole scene, then perform post-load if successfully loaded
  113. if (Node::Load(source, setInstanceDefault))
  114. {
  115. FinishLoading(&source);
  116. return true;
  117. }
  118. else
  119. return false;
  120. }
  121. bool Scene::Save(Serializer& dest) const
  122. {
  123. URHO3D_PROFILE(SaveScene);
  124. // Write ID first
  125. if (!dest.WriteFileID("USCN"))
  126. {
  127. URHO3D_LOGERROR("Could not save scene, writing to stream failed");
  128. return false;
  129. }
  130. Deserializer* ptr = dynamic_cast<Deserializer*>(&dest);
  131. if (ptr)
  132. URHO3D_LOGINFO("Saving scene to " + ptr->GetName());
  133. if (Node::Save(dest))
  134. {
  135. FinishSaving(&dest);
  136. return true;
  137. }
  138. else
  139. return false;
  140. }
  141. bool Scene::LoadXML(const XMLElement& source, bool setInstanceDefault)
  142. {
  143. URHO3D_PROFILE(LoadSceneXML);
  144. StopAsyncLoading();
  145. // Load the whole scene, then perform post-load if successfully loaded
  146. // Note: the scene filename and checksum can not be set, as we only used an XML element
  147. if (Node::LoadXML(source, setInstanceDefault))
  148. {
  149. FinishLoading(0);
  150. return true;
  151. }
  152. else
  153. return false;
  154. }
  155. void Scene::MarkNetworkUpdate()
  156. {
  157. if (!networkUpdate_)
  158. {
  159. MarkNetworkUpdate(this);
  160. networkUpdate_ = true;
  161. }
  162. }
  163. void Scene::AddReplicationState(NodeReplicationState* state)
  164. {
  165. Node::AddReplicationState(state);
  166. // This is the first update for a new connection. Mark all replicated nodes dirty
  167. for (HashMap<unsigned, Node*>::ConstIterator i = replicatedNodes_.Begin(); i != replicatedNodes_.End(); ++i)
  168. state->sceneState_->dirtyNodes_.Insert(i->first_);
  169. }
  170. bool Scene::LoadXML(Deserializer& source)
  171. {
  172. URHO3D_PROFILE(LoadSceneXML);
  173. StopAsyncLoading();
  174. SharedPtr<XMLFile> xml(new XMLFile(context_));
  175. if (!xml->Load(source))
  176. return false;
  177. URHO3D_LOGINFO("Loading scene from " + source.GetName());
  178. Clear();
  179. if (Node::LoadXML(xml->GetRoot()))
  180. {
  181. FinishLoading(&source);
  182. return true;
  183. }
  184. else
  185. return false;
  186. }
  187. bool Scene::SaveXML(Serializer& dest, const String& indentation) const
  188. {
  189. URHO3D_PROFILE(SaveSceneXML);
  190. SharedPtr<XMLFile> xml(new XMLFile(context_));
  191. XMLElement rootElem = xml->CreateRoot("scene");
  192. if (!SaveXML(rootElem))
  193. return false;
  194. Deserializer* ptr = dynamic_cast<Deserializer*>(&dest);
  195. if (ptr)
  196. URHO3D_LOGINFO("Saving scene to " + ptr->GetName());
  197. if (xml->Save(dest, indentation))
  198. {
  199. FinishSaving(&dest);
  200. return true;
  201. }
  202. else
  203. return false;
  204. }
  205. bool Scene::LoadAsync(File* file, LoadMode mode)
  206. {
  207. if (!file)
  208. {
  209. URHO3D_LOGERROR("Null file for async loading");
  210. return false;
  211. }
  212. StopAsyncLoading();
  213. // Check ID
  214. bool isSceneFile = file->ReadFileID() == "USCN";
  215. if (!isSceneFile)
  216. {
  217. // In resource load mode can load also object prefabs, which have no identifier
  218. if (mode > LOAD_RESOURCES_ONLY)
  219. {
  220. URHO3D_LOGERROR(file->GetName() + " is not a valid scene file");
  221. return false;
  222. }
  223. else
  224. file->Seek(0);
  225. }
  226. if (mode > LOAD_RESOURCES_ONLY)
  227. {
  228. URHO3D_LOGINFO("Loading scene from " + file->GetName());
  229. Clear();
  230. }
  231. asyncLoading_ = true;
  232. asyncProgress_.file_ = file;
  233. asyncProgress_.mode_ = mode;
  234. asyncProgress_.loadedNodes_ = asyncProgress_.totalNodes_ = asyncProgress_.loadedResources_ = asyncProgress_.totalResources_ = 0;
  235. asyncProgress_.resources_.Clear();
  236. if (mode > LOAD_RESOURCES_ONLY)
  237. {
  238. // Preload resources if appropriate, then return to the original position for loading the scene content
  239. if (mode != LOAD_SCENE)
  240. {
  241. URHO3D_PROFILE(FindResourcesToPreload);
  242. unsigned currentPos = file->GetPosition();
  243. PreloadResources(file, isSceneFile);
  244. file->Seek(currentPos);
  245. }
  246. // Store own old ID for resolving possible root node references
  247. unsigned nodeID = file->ReadUInt();
  248. resolver_.AddNode(nodeID, this);
  249. // Load root level components first
  250. if (!Node::Load(*file, resolver_, false))
  251. {
  252. StopAsyncLoading();
  253. return false;
  254. }
  255. // Then prepare to load child nodes in the async updates
  256. asyncProgress_.totalNodes_ = file->ReadVLE();
  257. }
  258. else
  259. {
  260. URHO3D_PROFILE(FindResourcesToPreload);
  261. URHO3D_LOGINFO("Preloading resources from " + file->GetName());
  262. PreloadResources(file, isSceneFile);
  263. }
  264. return true;
  265. }
  266. bool Scene::LoadAsyncXML(File* file, LoadMode mode)
  267. {
  268. if (!file)
  269. {
  270. URHO3D_LOGERROR("Null file for async loading");
  271. return false;
  272. }
  273. StopAsyncLoading();
  274. SharedPtr<XMLFile> xml(new XMLFile(context_));
  275. if (!xml->Load(*file))
  276. return false;
  277. if (mode > LOAD_RESOURCES_ONLY)
  278. {
  279. URHO3D_LOGINFO("Loading scene from " + file->GetName());
  280. Clear();
  281. }
  282. asyncLoading_ = true;
  283. asyncProgress_.xmlFile_ = xml;
  284. asyncProgress_.file_ = file;
  285. asyncProgress_.mode_ = mode;
  286. asyncProgress_.loadedNodes_ = asyncProgress_.totalNodes_ = asyncProgress_.loadedResources_ = asyncProgress_.totalResources_ = 0;
  287. asyncProgress_.resources_.Clear();
  288. if (mode > LOAD_RESOURCES_ONLY)
  289. {
  290. XMLElement rootElement = xml->GetRoot();
  291. // Preload resources if appropriate
  292. if (mode != LOAD_SCENE)
  293. {
  294. URHO3D_PROFILE(FindResourcesToPreload);
  295. PreloadResourcesXML(rootElement);
  296. }
  297. // Store own old ID for resolving possible root node references
  298. unsigned nodeID = rootElement.GetUInt("id");
  299. resolver_.AddNode(nodeID, this);
  300. // Load the root level components first
  301. if (!Node::LoadXML(rootElement, resolver_, false))
  302. return false;
  303. // Then prepare for loading all root level child nodes in the async update
  304. XMLElement childNodeElement = rootElement.GetChild("node");
  305. asyncProgress_.xmlElement_ = childNodeElement;
  306. // Count the amount of child nodes
  307. while (childNodeElement)
  308. {
  309. ++asyncProgress_.totalNodes_;
  310. childNodeElement = childNodeElement.GetNext("node");
  311. }
  312. }
  313. else
  314. {
  315. URHO3D_PROFILE(FindResourcesToPreload);
  316. URHO3D_LOGINFO("Preloading resources from " + file->GetName());
  317. PreloadResourcesXML(xml->GetRoot());
  318. }
  319. return true;
  320. }
  321. void Scene::StopAsyncLoading()
  322. {
  323. asyncLoading_ = false;
  324. asyncProgress_.file_.Reset();
  325. asyncProgress_.xmlFile_.Reset();
  326. asyncProgress_.xmlElement_ = XMLElement::EMPTY;
  327. asyncProgress_.resources_.Clear();
  328. resolver_.Reset();
  329. }
  330. Node* Scene::Instantiate(Deserializer& source, const Vector3& position, const Quaternion& rotation, CreateMode mode)
  331. {
  332. URHO3D_PROFILE(Instantiate);
  333. SceneResolver resolver;
  334. unsigned nodeID = source.ReadUInt();
  335. // Rewrite IDs when instantiating
  336. Node* node = CreateChild(0, mode);
  337. resolver.AddNode(nodeID, node);
  338. if (node->Load(source, resolver, true, true, mode))
  339. {
  340. resolver.Resolve();
  341. node->ApplyAttributes();
  342. node->SetTransform(position, rotation);
  343. return node;
  344. }
  345. else
  346. {
  347. node->Remove();
  348. return 0;
  349. }
  350. }
  351. Node* Scene::InstantiateXML(const XMLElement& source, const Vector3& position, const Quaternion& rotation, CreateMode mode)
  352. {
  353. URHO3D_PROFILE(InstantiateXML);
  354. SceneResolver resolver;
  355. unsigned nodeID = source.GetUInt("id");
  356. // Rewrite IDs when instantiating
  357. Node* node = CreateChild(0, mode);
  358. resolver.AddNode(nodeID, node);
  359. if (node->LoadXML(source, resolver, true, true, mode))
  360. {
  361. resolver.Resolve();
  362. node->ApplyAttributes();
  363. node->SetTransform(position, rotation);
  364. return node;
  365. }
  366. else
  367. {
  368. node->Remove();
  369. return 0;
  370. }
  371. }
  372. Node* Scene::InstantiateXML(Deserializer& source, const Vector3& position, const Quaternion& rotation, CreateMode mode)
  373. {
  374. SharedPtr<XMLFile> xml(new XMLFile(context_));
  375. if (!xml->Load(source))
  376. return 0;
  377. return InstantiateXML(xml->GetRoot(), position, rotation, mode);
  378. }
  379. void Scene::Clear(bool clearReplicated, bool clearLocal)
  380. {
  381. StopAsyncLoading();
  382. RemoveChildren(clearReplicated, clearLocal, true);
  383. RemoveComponents(clearReplicated, clearLocal);
  384. // Only clear name etc. if clearing completely
  385. if (clearReplicated && clearLocal)
  386. {
  387. UnregisterAllVars();
  388. SetName(String::EMPTY);
  389. fileName_.Clear();
  390. checksum_ = 0;
  391. }
  392. // Reset ID generators
  393. if (clearReplicated)
  394. {
  395. replicatedNodeID_ = FIRST_REPLICATED_ID;
  396. replicatedComponentID_ = FIRST_REPLICATED_ID;
  397. }
  398. if (clearLocal)
  399. {
  400. localNodeID_ = FIRST_LOCAL_ID;
  401. localComponentID_ = FIRST_LOCAL_ID;
  402. }
  403. }
  404. void Scene::SetUpdateEnabled(bool enable)
  405. {
  406. updateEnabled_ = enable;
  407. }
  408. void Scene::SetTimeScale(float scale)
  409. {
  410. timeScale_ = Max(scale, M_EPSILON);
  411. Node::MarkNetworkUpdate();
  412. }
  413. void Scene::SetSmoothingConstant(float constant)
  414. {
  415. smoothingConstant_ = Max(constant, M_EPSILON);
  416. Node::MarkNetworkUpdate();
  417. }
  418. void Scene::SetSnapThreshold(float threshold)
  419. {
  420. snapThreshold_ = Max(threshold, 0.0f);
  421. Node::MarkNetworkUpdate();
  422. }
  423. void Scene::SetAsyncLoadingMs(int ms)
  424. {
  425. asyncLoadingMs_ = Max(ms, 1);
  426. }
  427. void Scene::SetElapsedTime(float time)
  428. {
  429. elapsedTime_ = time;
  430. }
  431. void Scene::AddRequiredPackageFile(PackageFile* package)
  432. {
  433. // Do not add packages that failed to load
  434. if (!package || !package->GetNumFiles())
  435. return;
  436. requiredPackageFiles_.Push(SharedPtr<PackageFile>(package));
  437. }
  438. void Scene::ClearRequiredPackageFiles()
  439. {
  440. requiredPackageFiles_.Clear();
  441. }
  442. void Scene::RegisterVar(const String& name)
  443. {
  444. varNames_[name] = name;
  445. }
  446. void Scene::UnregisterVar(const String& name)
  447. {
  448. varNames_.Erase(name);
  449. }
  450. void Scene::UnregisterAllVars()
  451. {
  452. varNames_.Clear();
  453. }
  454. Node* Scene::GetNode(unsigned id) const
  455. {
  456. if (id < FIRST_LOCAL_ID)
  457. {
  458. HashMap<unsigned, Node*>::ConstIterator i = replicatedNodes_.Find(id);
  459. return i != replicatedNodes_.End() ? i->second_ : 0;
  460. }
  461. else
  462. {
  463. HashMap<unsigned, Node*>::ConstIterator i = localNodes_.Find(id);
  464. return i != localNodes_.End() ? i->second_ : 0;
  465. }
  466. }
  467. Component* Scene::GetComponent(unsigned id) const
  468. {
  469. if (id < FIRST_LOCAL_ID)
  470. {
  471. HashMap<unsigned, Component*>::ConstIterator i = replicatedComponents_.Find(id);
  472. return i != replicatedComponents_.End() ? i->second_ : 0;
  473. }
  474. else
  475. {
  476. HashMap<unsigned, Component*>::ConstIterator i = localComponents_.Find(id);
  477. return i != localComponents_.End() ? i->second_ : 0;
  478. }
  479. }
  480. float Scene::GetAsyncProgress() const
  481. {
  482. return !asyncLoading_ || asyncProgress_.totalNodes_ + asyncProgress_.totalResources_ == 0 ? 1.0f :
  483. (float)(asyncProgress_.loadedNodes_ + asyncProgress_.loadedResources_) /
  484. (float)(asyncProgress_.totalNodes_ + asyncProgress_.totalResources_);
  485. }
  486. const String& Scene::GetVarName(StringHash hash) const
  487. {
  488. HashMap<StringHash, String>::ConstIterator i = varNames_.Find(hash);
  489. return i != varNames_.End() ? i->second_ : String::EMPTY;
  490. }
  491. void Scene::Update(float timeStep)
  492. {
  493. if (asyncLoading_)
  494. {
  495. UpdateAsyncLoading();
  496. // If only preloading resources, scene update can continue
  497. if (asyncProgress_.mode_ > LOAD_RESOURCES_ONLY)
  498. return;
  499. }
  500. URHO3D_PROFILE(UpdateScene);
  501. timeStep *= timeScale_;
  502. using namespace SceneUpdate;
  503. VariantMap& eventData = GetEventDataMap();
  504. eventData[P_SCENE] = this;
  505. eventData[P_TIMESTEP] = timeStep;
  506. // Update variable timestep logic
  507. SendEvent(E_SCENEUPDATE, eventData);
  508. // Update scene attribute animation.
  509. SendEvent(E_ATTRIBUTEANIMATIONUPDATE, eventData);
  510. // Update scene subsystems. If a physics world is present, it will be updated, triggering fixed timestep logic updates
  511. SendEvent(E_SCENESUBSYSTEMUPDATE, eventData);
  512. // Update transform smoothing
  513. {
  514. URHO3D_PROFILE(UpdateSmoothing);
  515. float constant = 1.0f - Clamp(powf(2.0f, -timeStep * smoothingConstant_), 0.0f, 1.0f);
  516. float squaredSnapThreshold = snapThreshold_ * snapThreshold_;
  517. using namespace UpdateSmoothing;
  518. smoothingData_[P_CONSTANT] = constant;
  519. smoothingData_[P_SQUAREDSNAPTHRESHOLD] = squaredSnapThreshold;
  520. SendEvent(E_UPDATESMOOTHING, smoothingData_);
  521. }
  522. // Post-update variable timestep logic
  523. SendEvent(E_SCENEPOSTUPDATE, eventData);
  524. // Note: using a float for elapsed time accumulation is inherently inaccurate. The purpose of this value is
  525. // primarily to update material animation effects, as it is available to shaders. It can be reset by calling
  526. // SetElapsedTime()
  527. elapsedTime_ += timeStep;
  528. }
  529. void Scene::BeginThreadedUpdate()
  530. {
  531. // Check the work queue subsystem whether it actually has created worker threads. If not, do not enter threaded mode.
  532. if (GetSubsystem<WorkQueue>()->GetNumThreads())
  533. threadedUpdate_ = true;
  534. }
  535. void Scene::EndThreadedUpdate()
  536. {
  537. if (!threadedUpdate_)
  538. return;
  539. threadedUpdate_ = false;
  540. if (!delayedDirtyComponents_.Empty())
  541. {
  542. URHO3D_PROFILE(EndThreadedUpdate);
  543. for (PODVector<Component*>::ConstIterator i = delayedDirtyComponents_.Begin(); i != delayedDirtyComponents_.End(); ++i)
  544. (*i)->OnMarkedDirty((*i)->GetNode());
  545. delayedDirtyComponents_.Clear();
  546. }
  547. }
  548. void Scene::DelayedMarkedDirty(Component* component)
  549. {
  550. MutexLock lock(sceneMutex_);
  551. delayedDirtyComponents_.Push(component);
  552. }
  553. unsigned Scene::GetFreeNodeID(CreateMode mode)
  554. {
  555. if (mode == REPLICATED)
  556. {
  557. for (;;)
  558. {
  559. unsigned ret = replicatedNodeID_;
  560. if (replicatedNodeID_ < LAST_REPLICATED_ID)
  561. ++replicatedNodeID_;
  562. else
  563. replicatedNodeID_ = FIRST_REPLICATED_ID;
  564. if (!replicatedNodes_.Contains(ret))
  565. return ret;
  566. }
  567. }
  568. else
  569. {
  570. for (;;)
  571. {
  572. unsigned ret = localNodeID_;
  573. if (localNodeID_ < LAST_LOCAL_ID)
  574. ++localNodeID_;
  575. else
  576. localNodeID_ = FIRST_LOCAL_ID;
  577. if (!localNodes_.Contains(ret))
  578. return ret;
  579. }
  580. }
  581. }
  582. unsigned Scene::GetFreeComponentID(CreateMode mode)
  583. {
  584. if (mode == REPLICATED)
  585. {
  586. for (;;)
  587. {
  588. unsigned ret = replicatedComponentID_;
  589. if (replicatedComponentID_ < LAST_REPLICATED_ID)
  590. ++replicatedComponentID_;
  591. else
  592. replicatedComponentID_ = FIRST_REPLICATED_ID;
  593. if (!replicatedComponents_.Contains(ret))
  594. return ret;
  595. }
  596. }
  597. else
  598. {
  599. for (;;)
  600. {
  601. unsigned ret = localComponentID_;
  602. if (localComponentID_ < LAST_LOCAL_ID)
  603. ++localComponentID_;
  604. else
  605. localComponentID_ = FIRST_LOCAL_ID;
  606. if (!localComponents_.Contains(ret))
  607. return ret;
  608. }
  609. }
  610. }
  611. void Scene::NodeAdded(Node* node)
  612. {
  613. if (!node || node->GetScene() == this)
  614. return;
  615. // Remove from old scene first
  616. Scene* oldScene = node->GetScene();
  617. if (oldScene)
  618. oldScene->NodeRemoved(node);
  619. node->SetScene(this);
  620. // If the new node has an ID of zero (default), assign a replicated ID now
  621. unsigned id = node->GetID();
  622. if (!id)
  623. {
  624. id = GetFreeNodeID(REPLICATED);
  625. node->SetID(id);
  626. }
  627. // If node with same ID exists, remove the scene reference from it and overwrite with the new node
  628. if (id < FIRST_LOCAL_ID)
  629. {
  630. HashMap<unsigned, Node*>::Iterator i = replicatedNodes_.Find(id);
  631. if (i != replicatedNodes_.End() && i->second_ != node)
  632. {
  633. URHO3D_LOGWARNING("Overwriting node with ID " + String(id));
  634. NodeRemoved(i->second_);
  635. }
  636. replicatedNodes_[id] = node;
  637. MarkNetworkUpdate(node);
  638. MarkReplicationDirty(node);
  639. }
  640. else
  641. {
  642. HashMap<unsigned, Node*>::Iterator i = localNodes_.Find(id);
  643. if (i != localNodes_.End() && i->second_ != node)
  644. {
  645. URHO3D_LOGWARNING("Overwriting node with ID " + String(id));
  646. NodeRemoved(i->second_);
  647. }
  648. localNodes_[id] = node;
  649. }
  650. // Add already created components and child nodes now
  651. const Vector<SharedPtr<Component> >& components = node->GetComponents();
  652. for (Vector<SharedPtr<Component> >::ConstIterator i = components.Begin(); i != components.End(); ++i)
  653. ComponentAdded(*i);
  654. const Vector<SharedPtr<Node> >& children = node->GetChildren();
  655. for (Vector<SharedPtr<Node> >::ConstIterator i = children.Begin(); i != children.End(); ++i)
  656. NodeAdded(*i);
  657. }
  658. void Scene::NodeRemoved(Node* node)
  659. {
  660. if (!node || node->GetScene() != this)
  661. return;
  662. unsigned id = node->GetID();
  663. if (id < FIRST_LOCAL_ID)
  664. {
  665. replicatedNodes_.Erase(id);
  666. MarkReplicationDirty(node);
  667. }
  668. else
  669. localNodes_.Erase(id);
  670. node->ResetScene();
  671. // Remove components and child nodes as well
  672. const Vector<SharedPtr<Component> >& components = node->GetComponents();
  673. for (Vector<SharedPtr<Component> >::ConstIterator i = components.Begin(); i != components.End(); ++i)
  674. ComponentRemoved(*i);
  675. const Vector<SharedPtr<Node> >& children = node->GetChildren();
  676. for (Vector<SharedPtr<Node> >::ConstIterator i = children.Begin(); i != children.End(); ++i)
  677. NodeRemoved(*i);
  678. }
  679. void Scene::ComponentAdded(Component* component)
  680. {
  681. if (!component)
  682. return;
  683. unsigned id = component->GetID();
  684. // If the new component has an ID of zero (default), assign a replicated ID now
  685. if (!id)
  686. {
  687. id = GetFreeComponentID(REPLICATED);
  688. component->SetID(id);
  689. }
  690. if (id < FIRST_LOCAL_ID)
  691. {
  692. HashMap<unsigned, Component*>::Iterator i = replicatedComponents_.Find(id);
  693. if (i != replicatedComponents_.End() && i->second_ != component)
  694. {
  695. URHO3D_LOGWARNING("Overwriting component with ID " + String(id));
  696. ComponentRemoved(i->second_);
  697. }
  698. replicatedComponents_[id] = component;
  699. }
  700. else
  701. {
  702. HashMap<unsigned, Component*>::Iterator i = localComponents_.Find(id);
  703. if (i != localComponents_.End() && i->second_ != component)
  704. {
  705. URHO3D_LOGWARNING("Overwriting component with ID " + String(id));
  706. ComponentRemoved(i->second_);
  707. }
  708. localComponents_[id] = component;
  709. }
  710. component->OnSceneSet(this);
  711. }
  712. void Scene::ComponentRemoved(Component* component)
  713. {
  714. if (!component)
  715. return;
  716. unsigned id = component->GetID();
  717. if (id < FIRST_LOCAL_ID)
  718. replicatedComponents_.Erase(id);
  719. else
  720. localComponents_.Erase(id);
  721. component->SetID(0);
  722. component->OnSceneSet(0);
  723. }
  724. void Scene::SetVarNamesAttr(const String& value)
  725. {
  726. Vector<String> varNames = value.Split(';');
  727. varNames_.Clear();
  728. for (Vector<String>::ConstIterator i = varNames.Begin(); i != varNames.End(); ++i)
  729. varNames_[*i] = *i;
  730. }
  731. String Scene::GetVarNamesAttr() const
  732. {
  733. String ret;
  734. if (!varNames_.Empty())
  735. {
  736. for (HashMap<StringHash, String>::ConstIterator i = varNames_.Begin(); i != varNames_.End(); ++i)
  737. ret += i->second_ + ';';
  738. ret.Resize(ret.Length() - 1);
  739. }
  740. return ret;
  741. }
  742. void Scene::PrepareNetworkUpdate()
  743. {
  744. for (HashSet<unsigned>::Iterator i = networkUpdateNodes_.Begin(); i != networkUpdateNodes_.End(); ++i)
  745. {
  746. Node* node = GetNode(*i);
  747. if (node)
  748. node->PrepareNetworkUpdate();
  749. }
  750. for (HashSet<unsigned>::Iterator i = networkUpdateComponents_.Begin(); i != networkUpdateComponents_.End(); ++i)
  751. {
  752. Component* component = GetComponent(*i);
  753. if (component)
  754. component->PrepareNetworkUpdate();
  755. }
  756. networkUpdateNodes_.Clear();
  757. networkUpdateComponents_.Clear();
  758. }
  759. void Scene::CleanupConnection(Connection* connection)
  760. {
  761. Node::CleanupConnection(connection);
  762. for (HashMap<unsigned, Node*>::Iterator i = replicatedNodes_.Begin(); i != replicatedNodes_.End(); ++i)
  763. i->second_->CleanupConnection(connection);
  764. for (HashMap<unsigned, Component*>::Iterator i = replicatedComponents_.Begin(); i != replicatedComponents_.End(); ++i)
  765. i->second_->CleanupConnection(connection);
  766. }
  767. void Scene::MarkNetworkUpdate(Node* node)
  768. {
  769. if (node)
  770. {
  771. if (!threadedUpdate_)
  772. networkUpdateNodes_.Insert(node->GetID());
  773. else
  774. {
  775. MutexLock lock(sceneMutex_);
  776. networkUpdateNodes_.Insert(node->GetID());
  777. }
  778. }
  779. }
  780. void Scene::MarkNetworkUpdate(Component* component)
  781. {
  782. if (component)
  783. {
  784. if (!threadedUpdate_)
  785. networkUpdateComponents_.Insert(component->GetID());
  786. else
  787. {
  788. MutexLock lock(sceneMutex_);
  789. networkUpdateComponents_.Insert(component->GetID());
  790. }
  791. }
  792. }
  793. void Scene::MarkReplicationDirty(Node* node)
  794. {
  795. unsigned id = node->GetID();
  796. if (id < FIRST_LOCAL_ID && networkState_)
  797. {
  798. for (PODVector<ReplicationState*>::Iterator i = networkState_->replicationStates_.Begin();
  799. i != networkState_->replicationStates_.End(); ++i)
  800. {
  801. NodeReplicationState* nodeState = static_cast<NodeReplicationState*>(*i);
  802. nodeState->sceneState_->dirtyNodes_.Insert(id);
  803. }
  804. }
  805. }
  806. void Scene::HandleUpdate(StringHash eventType, VariantMap& eventData)
  807. {
  808. if (!updateEnabled_)
  809. return;
  810. using namespace Update;
  811. Update(eventData[P_TIMESTEP].GetFloat());
  812. }
  813. void Scene::HandleResourceBackgroundLoaded(StringHash eventType, VariantMap& eventData)
  814. {
  815. using namespace ResourceBackgroundLoaded;
  816. if (asyncLoading_)
  817. {
  818. Resource* resource = static_cast<Resource*>(eventData[P_RESOURCE].GetPtr());
  819. if (asyncProgress_.resources_.Contains(resource->GetNameHash()))
  820. {
  821. asyncProgress_.resources_.Erase(resource->GetNameHash());
  822. ++asyncProgress_.loadedResources_;
  823. }
  824. }
  825. }
  826. void Scene::UpdateAsyncLoading()
  827. {
  828. URHO3D_PROFILE(UpdateAsyncLoading);
  829. // If resources left to load, do not load nodes yet
  830. if (asyncProgress_.loadedResources_ < asyncProgress_.totalResources_)
  831. return;
  832. HiresTimer asyncLoadTimer;
  833. for (;;)
  834. {
  835. if (asyncProgress_.loadedNodes_ >= asyncProgress_.totalNodes_)
  836. {
  837. FinishAsyncLoading();
  838. return;
  839. }
  840. // Read one child node with its full sub-hierarchy either from binary or XML
  841. /// \todo Works poorly in scenes where one root-level child node contains all content
  842. if (!asyncProgress_.xmlFile_)
  843. {
  844. unsigned nodeID = asyncProgress_.file_->ReadUInt();
  845. Node* newNode = CreateChild(nodeID, nodeID < FIRST_LOCAL_ID ? REPLICATED : LOCAL);
  846. resolver_.AddNode(nodeID, newNode);
  847. newNode->Load(*asyncProgress_.file_, resolver_);
  848. }
  849. else
  850. {
  851. unsigned nodeID = asyncProgress_.xmlElement_.GetUInt("id");
  852. Node* newNode = CreateChild(nodeID, nodeID < FIRST_LOCAL_ID ? REPLICATED : LOCAL);
  853. resolver_.AddNode(nodeID, newNode);
  854. newNode->LoadXML(asyncProgress_.xmlElement_, resolver_);
  855. asyncProgress_.xmlElement_ = asyncProgress_.xmlElement_.GetNext("node");
  856. }
  857. ++asyncProgress_.loadedNodes_;
  858. // Break if time limit exceeded, so that we keep sufficient FPS
  859. if (asyncLoadTimer.GetUSec(false) >= asyncLoadingMs_ * 1000)
  860. break;
  861. }
  862. using namespace AsyncLoadProgress;
  863. VariantMap& eventData = GetEventDataMap();
  864. eventData[P_SCENE] = this;
  865. eventData[P_PROGRESS] = GetAsyncProgress();
  866. eventData[P_LOADEDNODES] = asyncProgress_.loadedNodes_;
  867. eventData[P_TOTALNODES] = asyncProgress_.totalNodes_;
  868. eventData[P_LOADEDRESOURCES] = asyncProgress_.loadedResources_;
  869. eventData[P_TOTALRESOURCES] = asyncProgress_.totalResources_;
  870. SendEvent(E_ASYNCLOADPROGRESS, eventData);
  871. }
  872. void Scene::FinishAsyncLoading()
  873. {
  874. if (asyncProgress_.mode_ > LOAD_RESOURCES_ONLY)
  875. {
  876. resolver_.Resolve();
  877. ApplyAttributes();
  878. FinishLoading(asyncProgress_.file_);
  879. }
  880. StopAsyncLoading();
  881. using namespace AsyncLoadFinished;
  882. VariantMap& eventData = GetEventDataMap();
  883. eventData[P_SCENE] = this;
  884. SendEvent(E_ASYNCLOADFINISHED, eventData);
  885. }
  886. void Scene::FinishLoading(Deserializer* source)
  887. {
  888. if (source)
  889. {
  890. fileName_ = source->GetName();
  891. checksum_ = source->GetChecksum();
  892. }
  893. }
  894. void Scene::FinishSaving(Serializer* dest) const
  895. {
  896. Deserializer* ptr = dynamic_cast<Deserializer*>(dest);
  897. if (ptr)
  898. {
  899. fileName_ = ptr->GetName();
  900. checksum_ = ptr->GetChecksum();
  901. }
  902. }
  903. void Scene::PreloadResources(File* file, bool isSceneFile)
  904. {
  905. // If not threaded, can not background load resources, so rather load synchronously later when needed
  906. #ifdef URHO3D_THREADING
  907. ResourceCache* cache = GetSubsystem<ResourceCache>();
  908. // Read node ID (not needed)
  909. /*unsigned nodeID = */file->ReadUInt();
  910. // Read Node or Scene attributes; these do not include any resources
  911. const Vector<AttributeInfo>* attributes = context_->GetAttributes(isSceneFile ? Scene::GetTypeStatic() : Node::GetTypeStatic());
  912. assert(attributes);
  913. for (unsigned i = 0; i < attributes->Size(); ++i)
  914. {
  915. const AttributeInfo& attr = attributes->At(i);
  916. if (!(attr.mode_ & AM_FILE))
  917. continue;
  918. /*Variant varValue = */file->ReadVariant(attr.type_);
  919. }
  920. // Read component attributes
  921. unsigned numComponents = file->ReadVLE();
  922. for (unsigned i = 0; i < numComponents; ++i)
  923. {
  924. VectorBuffer compBuffer(*file, file->ReadVLE());
  925. StringHash compType = compBuffer.ReadStringHash();
  926. // Read component ID (not needed)
  927. /*unsigned compID = */compBuffer.ReadUInt();
  928. attributes = context_->GetAttributes(compType);
  929. if (attributes)
  930. {
  931. for (unsigned j = 0; j < attributes->Size(); ++j)
  932. {
  933. const AttributeInfo& attr = attributes->At(j);
  934. if (!(attr.mode_ & AM_FILE))
  935. continue;
  936. Variant varValue = compBuffer.ReadVariant(attr.type_);
  937. if (attr.type_ == VAR_RESOURCEREF)
  938. {
  939. const ResourceRef& ref = varValue.GetResourceRef();
  940. // Sanitate resource name beforehand so that when we get the background load event, the name matches exactly
  941. String name = cache->SanitateResourceName(ref.name_);
  942. bool success = cache->BackgroundLoadResource(ref.type_, name);
  943. if (success)
  944. {
  945. ++asyncProgress_.totalResources_;
  946. asyncProgress_.resources_.Insert(StringHash(name));
  947. }
  948. }
  949. else if (attr.type_ == VAR_RESOURCEREFLIST)
  950. {
  951. const ResourceRefList& refList = varValue.GetResourceRefList();
  952. for (unsigned k = 0; k < refList.names_.Size(); ++k)
  953. {
  954. String name = cache->SanitateResourceName(refList.names_[k]);
  955. bool success = cache->BackgroundLoadResource(refList.type_, name);
  956. if (success)
  957. {
  958. ++asyncProgress_.totalResources_;
  959. asyncProgress_.resources_.Insert(StringHash(name));
  960. }
  961. }
  962. }
  963. }
  964. }
  965. }
  966. // Read child nodes
  967. unsigned numChildren = file->ReadVLE();
  968. for (unsigned i = 0; i < numChildren; ++i)
  969. PreloadResources(file, false);
  970. #endif
  971. }
  972. void Scene::PreloadResourcesXML(const XMLElement& element)
  973. {
  974. // If not threaded, can not background load resources, so rather load synchronously later when needed
  975. #ifdef URHO3D_THREADING
  976. ResourceCache* cache = GetSubsystem<ResourceCache>();
  977. // Node or Scene attributes do not include any resources; therefore skip to the components
  978. XMLElement compElem = element.GetChild("component");
  979. while (compElem)
  980. {
  981. String typeName = compElem.GetAttribute("type");
  982. const Vector<AttributeInfo>* attributes = context_->GetAttributes(StringHash(typeName));
  983. if (attributes)
  984. {
  985. XMLElement attrElem = compElem.GetChild("attribute");
  986. unsigned startIndex = 0;
  987. while (attrElem)
  988. {
  989. String name = attrElem.GetAttribute("name");
  990. unsigned i = startIndex;
  991. unsigned attempts = attributes->Size();
  992. while (attempts)
  993. {
  994. const AttributeInfo& attr = attributes->At(i);
  995. if ((attr.mode_ & AM_FILE) && !attr.name_.Compare(name, true))
  996. {
  997. if (attr.type_ == VAR_RESOURCEREF)
  998. {
  999. ResourceRef ref = attrElem.GetVariantValue(attr.type_).GetResourceRef();
  1000. String name = cache->SanitateResourceName(ref.name_);
  1001. bool success = cache->BackgroundLoadResource(ref.type_, name);
  1002. if (success)
  1003. {
  1004. ++asyncProgress_.totalResources_;
  1005. asyncProgress_.resources_.Insert(StringHash(name));
  1006. }
  1007. }
  1008. else if (attr.type_ == VAR_RESOURCEREFLIST)
  1009. {
  1010. ResourceRefList refList = attrElem.GetVariantValue(attr.type_).GetResourceRefList();
  1011. for (unsigned k = 0; k < refList.names_.Size(); ++k)
  1012. {
  1013. String name = cache->SanitateResourceName(refList.names_[k]);
  1014. bool success = cache->BackgroundLoadResource(refList.type_, name);
  1015. if (success)
  1016. {
  1017. ++asyncProgress_.totalResources_;
  1018. asyncProgress_.resources_.Insert(StringHash(name));
  1019. }
  1020. }
  1021. }
  1022. startIndex = (i + 1) % attributes->Size();
  1023. break;
  1024. }
  1025. else
  1026. {
  1027. i = (i + 1) % attributes->Size();
  1028. --attempts;
  1029. }
  1030. }
  1031. attrElem = attrElem.GetNext("attribute");
  1032. }
  1033. }
  1034. compElem = compElem.GetNext("component");
  1035. }
  1036. XMLElement childElem = element.GetChild("node");
  1037. while (childElem)
  1038. {
  1039. PreloadResourcesXML(childElem);
  1040. childElem = childElem.GetNext("node");
  1041. }
  1042. #endif
  1043. }
  1044. void RegisterSceneLibrary(Context* context)
  1045. {
  1046. ValueAnimation::RegisterObject(context);
  1047. ObjectAnimation::RegisterObject(context);
  1048. Node::RegisterObject(context);
  1049. Scene::RegisterObject(context);
  1050. SmoothedTransform::RegisterObject(context);
  1051. UnknownComponent::RegisterObject(context);
  1052. SplinePath::RegisterObject(context);
  1053. }
  1054. }