Scene.cpp 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238
  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. 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("Next Replicated Node ID", int, replicatedNodeID_, FIRST_REPLICATED_ID, AM_FILE | AM_NOEDIT);
  93. ATTRIBUTE("Next Replicated Component ID", int, replicatedComponentID_, FIRST_REPLICATED_ID, AM_FILE | AM_NOEDIT);
  94. ATTRIBUTE("Next Local Node ID", int, localNodeID_, FIRST_LOCAL_ID, AM_FILE | AM_NOEDIT);
  95. ATTRIBUTE("Next Local Component ID", int, localComponentID_, FIRST_LOCAL_ID, AM_FILE | AM_NOEDIT);
  96. ATTRIBUTE("Variables", VariantMap, 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. // Remove components and child nodes as well
  685. const Vector<SharedPtr<Component> >& components = node->GetComponents();
  686. for (Vector<SharedPtr<Component> >::ConstIterator i = components.Begin(); i != components.End(); ++i)
  687. ComponentRemoved(*i);
  688. const Vector<SharedPtr<Node> >& children = node->GetChildren();
  689. for (Vector<SharedPtr<Node> >::ConstIterator i = children.Begin(); i != children.End(); ++i)
  690. NodeRemoved(*i);
  691. }
  692. void Scene::ComponentAdded(Component* component)
  693. {
  694. if (!component)
  695. return;
  696. unsigned id = component->GetID();
  697. if (id < FIRST_LOCAL_ID)
  698. {
  699. HashMap<unsigned, Component*>::Iterator i = replicatedComponents_.Find(id);
  700. if (i != replicatedComponents_.End() && i->second_ != component)
  701. {
  702. LOGWARNING("Overwriting component with ID " + String(id));
  703. i->second_->SetID(0);
  704. }
  705. replicatedComponents_[id] = component;
  706. }
  707. else
  708. {
  709. HashMap<unsigned, Component*>::Iterator i = localComponents_.Find(id);
  710. if (i != localComponents_.End() && i->second_ != component)
  711. {
  712. LOGWARNING("Overwriting component with ID " + String(id));
  713. i->second_->SetID(0);
  714. }
  715. localComponents_[id] = component;
  716. }
  717. }
  718. void Scene::ComponentRemoved(Component* component)
  719. {
  720. if (!component)
  721. return;
  722. unsigned id = component->GetID();
  723. if (id < FIRST_LOCAL_ID)
  724. replicatedComponents_.Erase(id);
  725. else
  726. localComponents_.Erase(id);
  727. component->SetID(0);
  728. }
  729. void Scene::SetVarNamesAttr(const String& value)
  730. {
  731. Vector<String> varNames = value.Split(';');
  732. varNames_.Clear();
  733. for (Vector<String>::ConstIterator i = varNames.Begin(); i != varNames.End(); ++i)
  734. varNames_[*i] = *i;
  735. }
  736. String Scene::GetVarNamesAttr() const
  737. {
  738. String ret;
  739. if (!varNames_.Empty())
  740. {
  741. for (HashMap<StringHash, String>::ConstIterator i = varNames_.Begin(); i != varNames_.End(); ++i)
  742. ret += i->second_ + ';';
  743. ret.Resize(ret.Length() - 1);
  744. }
  745. return ret;
  746. }
  747. void Scene::PrepareNetworkUpdate()
  748. {
  749. for (HashSet<unsigned>::Iterator i = networkUpdateNodes_.Begin(); i != networkUpdateNodes_.End(); ++i)
  750. {
  751. Node* node = GetNode(*i);
  752. if (node)
  753. node->PrepareNetworkUpdate();
  754. }
  755. for (HashSet<unsigned>::Iterator i = networkUpdateComponents_.Begin(); i != networkUpdateComponents_.End(); ++i)
  756. {
  757. Component* component = GetComponent(*i);
  758. if (component)
  759. component->PrepareNetworkUpdate();
  760. }
  761. networkUpdateNodes_.Clear();
  762. networkUpdateComponents_.Clear();
  763. }
  764. void Scene::CleanupConnection(Connection* connection)
  765. {
  766. Node::CleanupConnection(connection);
  767. for (HashMap<unsigned, Node*>::Iterator i = replicatedNodes_.Begin(); i != replicatedNodes_.End(); ++i)
  768. i->second_->CleanupConnection(connection);
  769. for (HashMap<unsigned, Component*>::Iterator i = replicatedComponents_.Begin(); i != replicatedComponents_.End(); ++i)
  770. i->second_->CleanupConnection(connection);
  771. }
  772. void Scene::MarkNetworkUpdate(Node* node)
  773. {
  774. if (node)
  775. {
  776. if (!threadedUpdate_)
  777. networkUpdateNodes_.Insert(node->GetID());
  778. else
  779. {
  780. MutexLock lock(sceneMutex_);
  781. networkUpdateNodes_.Insert(node->GetID());
  782. }
  783. }
  784. }
  785. void Scene::MarkNetworkUpdate(Component* component)
  786. {
  787. if (component)
  788. {
  789. if (!threadedUpdate_)
  790. networkUpdateComponents_.Insert(component->GetID());
  791. else
  792. {
  793. MutexLock lock(sceneMutex_);
  794. networkUpdateComponents_.Insert(component->GetID());
  795. }
  796. }
  797. }
  798. void Scene::MarkReplicationDirty(Node* node)
  799. {
  800. unsigned id = node->GetID();
  801. if (id < FIRST_LOCAL_ID && networkState_)
  802. {
  803. for (PODVector<ReplicationState*>::Iterator i = networkState_->replicationStates_.Begin(); i !=
  804. networkState_->replicationStates_.End(); ++i)
  805. {
  806. NodeReplicationState* nodeState = static_cast<NodeReplicationState*>(*i);
  807. nodeState->sceneState_->dirtyNodes_.Insert(id);
  808. }
  809. }
  810. }
  811. void Scene::HandleUpdate(StringHash eventType, VariantMap& eventData)
  812. {
  813. using namespace Update;
  814. if (updateEnabled_)
  815. Update(eventData[P_TIMESTEP].GetFloat());
  816. }
  817. void Scene::HandleResourceBackgroundLoaded(StringHash eventType, VariantMap& eventData)
  818. {
  819. using namespace ResourceBackgroundLoaded;
  820. if (asyncLoading_)
  821. {
  822. Resource* resource = static_cast<Resource*>(eventData[P_RESOURCE].GetPtr());
  823. if (asyncProgress_.resources_.Contains(resource->GetNameHash()))
  824. {
  825. asyncProgress_.resources_.Erase(resource->GetNameHash());
  826. ++asyncProgress_.loadedResources_;
  827. }
  828. }
  829. }
  830. void Scene::UpdateAsyncLoading()
  831. {
  832. PROFILE(UpdateAsyncLoading);
  833. // If resources left to load, do not load nodes yet
  834. if (asyncProgress_.loadedResources_ < asyncProgress_.totalResources_)
  835. return;
  836. HiresTimer asyncLoadTimer;
  837. for (;;)
  838. {
  839. if (asyncProgress_.loadedNodes_ >= asyncProgress_.totalNodes_)
  840. {
  841. FinishAsyncLoading();
  842. return;
  843. }
  844. // Read one child node with its full sub-hierarchy either from binary or XML
  845. /// \todo Works poorly in scenes where one root-level child node contains all content
  846. if (!asyncProgress_.xmlFile_)
  847. {
  848. unsigned nodeID = asyncProgress_.file_->ReadUInt();
  849. Node* newNode = CreateChild(nodeID, nodeID < FIRST_LOCAL_ID ? REPLICATED : LOCAL);
  850. resolver_.AddNode(nodeID, newNode);
  851. newNode->Load(*asyncProgress_.file_, resolver_);
  852. }
  853. else
  854. {
  855. unsigned nodeID = asyncProgress_.xmlElement_.GetInt("id");
  856. Node* newNode = CreateChild(nodeID, nodeID < FIRST_LOCAL_ID ? REPLICATED : LOCAL);
  857. resolver_.AddNode(nodeID, newNode);
  858. newNode->LoadXML(asyncProgress_.xmlElement_, resolver_);
  859. asyncProgress_.xmlElement_ = asyncProgress_.xmlElement_.GetNext("node");
  860. }
  861. ++asyncProgress_.loadedNodes_;
  862. // Break if time limit exceeded, so that we keep sufficient FPS
  863. if (asyncLoadTimer.GetUSec(false) >= asyncLoadingMs_ * 1000)
  864. break;
  865. }
  866. using namespace AsyncLoadProgress;
  867. VariantMap& eventData = GetEventDataMap();
  868. eventData[P_SCENE] = this;
  869. eventData[P_PROGRESS] = GetAsyncProgress();
  870. eventData[P_LOADEDNODES] = asyncProgress_.loadedNodes_;
  871. eventData[P_TOTALNODES] = asyncProgress_.totalNodes_;
  872. eventData[P_LOADEDRESOURCES] = asyncProgress_.loadedResources_;
  873. eventData[P_TOTALRESOURCES] = asyncProgress_.totalResources_;
  874. SendEvent(E_ASYNCLOADPROGRESS, eventData);
  875. }
  876. void Scene::FinishAsyncLoading()
  877. {
  878. if (asyncProgress_.mode_ > LOAD_RESOURCES_ONLY)
  879. {
  880. resolver_.Resolve();
  881. ApplyAttributes();
  882. FinishLoading(asyncProgress_.file_);
  883. }
  884. StopAsyncLoading();
  885. using namespace AsyncLoadFinished;
  886. VariantMap& eventData = GetEventDataMap();
  887. eventData[P_SCENE] = this;
  888. SendEvent(E_ASYNCLOADFINISHED, eventData);
  889. }
  890. void Scene::FinishLoading(Deserializer* source)
  891. {
  892. if (source)
  893. {
  894. fileName_ = source->GetName();
  895. checksum_ = source->GetChecksum();
  896. }
  897. }
  898. void Scene::FinishSaving(Serializer* dest) const
  899. {
  900. Deserializer* ptr = dynamic_cast<Deserializer*>(dest);
  901. if (ptr)
  902. {
  903. fileName_ = ptr->GetName();
  904. checksum_ = ptr->GetChecksum();
  905. }
  906. }
  907. void Scene::PreloadResources(File* file, bool isSceneFile)
  908. {
  909. ResourceCache* cache = GetSubsystem<ResourceCache>();
  910. // Read node ID (not needed)
  911. /*unsigned nodeID = */file->ReadUInt();
  912. // Read Node or Scene attributes; these do not include any resources
  913. const Vector<AttributeInfo>* attributes = context_->GetAttributes(isSceneFile ? Scene::GetTypeStatic() : Node::GetTypeStatic());
  914. assert(attributes);
  915. for (unsigned i = 0; i < attributes->Size(); ++i)
  916. {
  917. const AttributeInfo& attr = attributes->At(i);
  918. if (!(attr.mode_ & AM_FILE))
  919. continue;
  920. Variant varValue = file->ReadVariant(attr.type_);
  921. }
  922. // Read component attributes
  923. unsigned numComponents = file->ReadVLE();
  924. for (unsigned i = 0; i < numComponents; ++i)
  925. {
  926. VectorBuffer compBuffer(*file, file->ReadVLE());
  927. StringHash compType = compBuffer.ReadStringHash();
  928. // Read component ID (not needed)
  929. /*unsigned compID = */compBuffer.ReadUInt();
  930. attributes = context_->GetAttributes(compType);
  931. if (attributes)
  932. {
  933. for (unsigned j = 0; j < attributes->Size(); ++j)
  934. {
  935. const AttributeInfo& attr = attributes->At(j);
  936. if (!(attr.mode_ & AM_FILE))
  937. continue;
  938. Variant varValue = compBuffer.ReadVariant(attr.type_);
  939. if (attr.type_ == VAR_RESOURCEREF)
  940. {
  941. const ResourceRef& ref = varValue.GetResourceRef();
  942. // Sanitate resource name beforehand so that when we get the background load event, the name matches exactly
  943. String name = cache->SanitateResourceName(ref.name_);
  944. bool success = cache->BackgroundLoadResource(ref.type_, name);
  945. if (success)
  946. {
  947. ++asyncProgress_.totalResources_;
  948. asyncProgress_.resources_.Insert(StringHash(name));
  949. }
  950. }
  951. else if (attr.type_ == VAR_RESOURCEREFLIST)
  952. {
  953. const ResourceRefList& refList = varValue.GetResourceRefList();
  954. for (unsigned k = 0; k < refList.names_.Size(); ++k)
  955. {
  956. String name = cache->SanitateResourceName(refList.names_[k]);
  957. bool success = cache->BackgroundLoadResource(refList.type_, name);
  958. if (success)
  959. {
  960. ++asyncProgress_.totalResources_;
  961. asyncProgress_.resources_.Insert(StringHash(name));
  962. }
  963. }
  964. }
  965. }
  966. }
  967. }
  968. // Read child nodes
  969. unsigned numChildren = file->ReadVLE();
  970. for (unsigned i = 0; i < numChildren; ++i)
  971. PreloadResources(file, false);
  972. }
  973. void Scene::PreloadResourcesXML(const XMLElement& element)
  974. {
  975. ResourceCache* cache = GetSubsystem<ResourceCache>();
  976. // Node or Scene attributes do not include any resources; therefore skip to the components
  977. XMLElement compElem = element.GetChild("component");
  978. while (compElem)
  979. {
  980. String typeName = compElem.GetAttribute("type");
  981. const Vector<AttributeInfo>* attributes = context_->GetAttributes(StringHash(typeName));
  982. if (attributes)
  983. {
  984. XMLElement attrElem = compElem.GetChild("attribute");
  985. unsigned startIndex = 0;
  986. while (attrElem)
  987. {
  988. String name = attrElem.GetAttribute("name");
  989. unsigned i = startIndex;
  990. unsigned attempts = attributes->Size();
  991. while (attempts)
  992. {
  993. const AttributeInfo& attr = attributes->At(i);
  994. if ((attr.mode_ & AM_FILE) && !attr.name_.Compare(name, true))
  995. {
  996. if (attr.type_ == VAR_RESOURCEREF)
  997. {
  998. ResourceRef ref = attrElem.GetVariantValue(attr.type_).GetResourceRef();
  999. String name = cache->SanitateResourceName(ref.name_);
  1000. bool success = cache->BackgroundLoadResource(ref.type_, name);
  1001. if (success)
  1002. {
  1003. ++asyncProgress_.totalResources_;
  1004. asyncProgress_.resources_.Insert(StringHash(name));
  1005. }
  1006. }
  1007. else if (attr.type_ == VAR_RESOURCEREFLIST)
  1008. {
  1009. ResourceRefList refList = attrElem.GetVariantValue(attr.type_).GetResourceRefList();
  1010. for (unsigned k = 0; k < refList.names_.Size(); ++k)
  1011. {
  1012. String name = cache->SanitateResourceName(refList.names_[k]);
  1013. bool success = cache->BackgroundLoadResource(refList.type_, name);
  1014. if (success)
  1015. {
  1016. ++asyncProgress_.totalResources_;
  1017. asyncProgress_.resources_.Insert(StringHash(name));
  1018. }
  1019. }
  1020. }
  1021. startIndex = (i + 1) % attributes->Size();
  1022. break;
  1023. }
  1024. else
  1025. {
  1026. i = (i + 1) % attributes->Size();
  1027. --attempts;
  1028. }
  1029. }
  1030. attrElem = attrElem.GetNext("attribute");
  1031. }
  1032. }
  1033. compElem = compElem.GetNext("component");
  1034. }
  1035. XMLElement childElem = element.GetChild("node");
  1036. while (childElem)
  1037. {
  1038. PreloadResourcesXML(childElem);
  1039. childElem = childElem.GetNext("node");
  1040. }
  1041. }
  1042. void RegisterSceneLibrary(Context* context)
  1043. {
  1044. ValueAnimation::RegisterObject(context);
  1045. ObjectAnimation::RegisterObject(context);
  1046. Node::RegisterObject(context);
  1047. Scene::RegisterObject(context);
  1048. SmoothedTransform::RegisterObject(context);
  1049. UnknownComponent::RegisterObject(context);
  1050. SplinePath::RegisterObject(context);
  1051. }
  1052. }