Scene.cpp 36 KB

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