2
0

Scene.cpp 36 KB

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