BackgroundLoader.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. //
  2. // Copyright (c) 2008-2022 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. #ifdef URHO3D_THREADING
  23. #include "../Precompiled.h"
  24. #include "../Core/Context.h"
  25. #include "../Core/Profiler.h"
  26. #include "../IO/Log.h"
  27. #include "../Resource/BackgroundLoader.h"
  28. #include "../Resource/ResourceCache.h"
  29. #include "../Resource/ResourceEvents.h"
  30. #include "../DebugNew.h"
  31. namespace Urho3D
  32. {
  33. BackgroundLoader::BackgroundLoader(ResourceCache* owner) :
  34. owner_(owner)
  35. {
  36. }
  37. BackgroundLoader::~BackgroundLoader()
  38. {
  39. MutexLock lock(backgroundLoadMutex_);
  40. backgroundLoadQueue_.Clear();
  41. }
  42. void BackgroundLoader::ThreadFunction()
  43. {
  44. URHO3D_PROFILE_THREAD("BackgroundLoader Thread");
  45. while (shouldRun_)
  46. {
  47. backgroundLoadMutex_.Acquire();
  48. // Search for a queued resource that has not been loaded yet
  49. HashMap<Pair<StringHash, StringHash>, BackgroundLoadItem>::Iterator i = backgroundLoadQueue_.Begin();
  50. while (i != backgroundLoadQueue_.End())
  51. {
  52. if (i->second_.resource_->GetAsyncLoadState() == ASYNC_QUEUED)
  53. break;
  54. else
  55. ++i;
  56. }
  57. if (i == backgroundLoadQueue_.End())
  58. {
  59. // No resources to load found
  60. backgroundLoadMutex_.Release();
  61. Time::Sleep(5);
  62. }
  63. else
  64. {
  65. BackgroundLoadItem& item = i->second_;
  66. Resource* resource = item.resource_;
  67. // We can be sure that the item is not removed from the queue as long as it is in the
  68. // "queued" or "loading" state
  69. backgroundLoadMutex_.Release();
  70. bool success = false;
  71. SharedPtr<File> file = owner_->GetFile(resource->GetName(), item.sendEventOnFailure_);
  72. if (file)
  73. {
  74. resource->SetAsyncLoadState(ASYNC_LOADING);
  75. success = resource->BeginLoad(*file);
  76. }
  77. // Process dependencies now
  78. // Need to lock the queue again when manipulating other entries
  79. Pair<StringHash, StringHash> key = MakePair(resource->GetType(), resource->GetNameHash());
  80. backgroundLoadMutex_.Acquire();
  81. if (item.dependents_.Size())
  82. {
  83. for (HashSet<Pair<StringHash, StringHash> >::Iterator i = item.dependents_.Begin();
  84. i != item.dependents_.End(); ++i)
  85. {
  86. HashMap<Pair<StringHash, StringHash>, BackgroundLoadItem>::Iterator j = backgroundLoadQueue_.Find(*i);
  87. if (j != backgroundLoadQueue_.End())
  88. j->second_.dependencies_.Erase(key);
  89. }
  90. item.dependents_.Clear();
  91. }
  92. resource->SetAsyncLoadState(success ? ASYNC_SUCCESS : ASYNC_FAIL);
  93. backgroundLoadMutex_.Release();
  94. }
  95. }
  96. }
  97. bool BackgroundLoader::QueueResource(StringHash type, const String& name, bool sendEventOnFailure, Resource* caller)
  98. {
  99. StringHash nameHash(name);
  100. Pair<StringHash, StringHash> key = MakePair(type, nameHash);
  101. MutexLock lock(backgroundLoadMutex_);
  102. // Check if already exists in the queue
  103. if (backgroundLoadQueue_.Find(key) != backgroundLoadQueue_.End())
  104. return false;
  105. BackgroundLoadItem& item = backgroundLoadQueue_[key];
  106. item.sendEventOnFailure_ = sendEventOnFailure;
  107. // Make sure the pointer is non-null and is a Resource subclass
  108. item.resource_ = DynamicCast<Resource>(owner_->GetContext()->CreateObject(type));
  109. if (!item.resource_)
  110. {
  111. URHO3D_LOGERROR("Could not load unknown resource type " + String(type));
  112. if (sendEventOnFailure && Thread::IsMainThread())
  113. {
  114. using namespace UnknownResourceType;
  115. VariantMap& eventData = owner_->GetEventDataMap();
  116. eventData[P_RESOURCETYPE] = type;
  117. owner_->SendEvent(E_UNKNOWNRESOURCETYPE, eventData);
  118. }
  119. backgroundLoadQueue_.Erase(key);
  120. return false;
  121. }
  122. URHO3D_LOGDEBUG("Background loading resource " + name);
  123. item.resource_->SetName(name);
  124. item.resource_->SetAsyncLoadState(ASYNC_QUEUED);
  125. // If this is a resource calling for the background load of more resources, mark the dependency as necessary
  126. if (caller)
  127. {
  128. Pair<StringHash, StringHash> callerKey = MakePair(caller->GetType(), caller->GetNameHash());
  129. HashMap<Pair<StringHash, StringHash>, BackgroundLoadItem>::Iterator j = backgroundLoadQueue_.Find(callerKey);
  130. if (j != backgroundLoadQueue_.End())
  131. {
  132. BackgroundLoadItem& callerItem = j->second_;
  133. item.dependents_.Insert(callerKey);
  134. callerItem.dependencies_.Insert(key);
  135. }
  136. else
  137. URHO3D_LOGWARNING("Resource " + caller->GetName() +
  138. " requested for a background loaded resource but was not in the background load queue");
  139. }
  140. // Start the background loader thread now
  141. if (!IsStarted())
  142. Run();
  143. return true;
  144. }
  145. void BackgroundLoader::WaitForResource(StringHash type, StringHash nameHash)
  146. {
  147. backgroundLoadMutex_.Acquire();
  148. // Check if the resource in question is being background loaded
  149. Pair<StringHash, StringHash> key = MakePair(type, nameHash);
  150. HashMap<Pair<StringHash, StringHash>, BackgroundLoadItem>::Iterator i = backgroundLoadQueue_.Find(key);
  151. if (i != backgroundLoadQueue_.End())
  152. {
  153. backgroundLoadMutex_.Release();
  154. {
  155. Resource* resource = i->second_.resource_;
  156. HiresTimer waitTimer;
  157. bool didWait = false;
  158. for (;;)
  159. {
  160. unsigned numDeps = i->second_.dependencies_.Size();
  161. AsyncLoadState state = resource->GetAsyncLoadState();
  162. if (numDeps > 0 || state == ASYNC_QUEUED || state == ASYNC_LOADING)
  163. {
  164. didWait = true;
  165. Time::Sleep(1);
  166. }
  167. else
  168. break;
  169. }
  170. if (didWait)
  171. URHO3D_LOGDEBUG("Waited " + String(waitTimer.GetUSec(false) / 1000) + " ms for background loaded resource " +
  172. resource->GetName());
  173. }
  174. // This may take a long time and may potentially wait on other resources, so it is important we do not hold the mutex during this
  175. FinishBackgroundLoading(i->second_);
  176. backgroundLoadMutex_.Acquire();
  177. backgroundLoadQueue_.Erase(i);
  178. backgroundLoadMutex_.Release();
  179. }
  180. else
  181. backgroundLoadMutex_.Release();
  182. }
  183. void BackgroundLoader::FinishResources(int maxMs)
  184. {
  185. if (IsStarted())
  186. {
  187. HiresTimer timer;
  188. backgroundLoadMutex_.Acquire();
  189. for (HashMap<Pair<StringHash, StringHash>, BackgroundLoadItem>::Iterator i = backgroundLoadQueue_.Begin();
  190. i != backgroundLoadQueue_.End();)
  191. {
  192. Resource* resource = i->second_.resource_;
  193. unsigned numDeps = i->second_.dependencies_.Size();
  194. AsyncLoadState state = resource->GetAsyncLoadState();
  195. if (numDeps > 0 || state == ASYNC_QUEUED || state == ASYNC_LOADING)
  196. ++i;
  197. else
  198. {
  199. // Finishing a resource may need it to wait for other resources to load, in which case we can not
  200. // hold on to the mutex
  201. backgroundLoadMutex_.Release();
  202. FinishBackgroundLoading(i->second_);
  203. backgroundLoadMutex_.Acquire();
  204. i = backgroundLoadQueue_.Erase(i);
  205. }
  206. // Break when the time limit passed so that we keep sufficient FPS
  207. if (timer.GetUSec(false) >= maxMs * 1000LL)
  208. break;
  209. }
  210. backgroundLoadMutex_.Release();
  211. }
  212. }
  213. unsigned BackgroundLoader::GetNumQueuedResources() const
  214. {
  215. MutexLock lock(backgroundLoadMutex_);
  216. return backgroundLoadQueue_.Size();
  217. }
  218. void BackgroundLoader::FinishBackgroundLoading(BackgroundLoadItem& item)
  219. {
  220. Resource* resource = item.resource_;
  221. bool success = resource->GetAsyncLoadState() == ASYNC_SUCCESS;
  222. // If BeginLoad() phase was successful, call EndLoad() and get the final success/failure result
  223. if (success)
  224. {
  225. #ifdef URHO3D_TRACY_PROFILING
  226. URHO3D_PROFILE_COLOR(FinishBackgroundLoading, URHO3D_PROFILE_RESOURCE_COLOR);
  227. String profileBlockName("Finish" + resource->GetTypeName());
  228. URHO3D_PROFILE_STR(profileBlockName.CString(), profileBlockName.Length());
  229. #elif defined(URHO3D_PROFILING)
  230. String profileBlockName("Finish" + resource->GetTypeName());
  231. auto* profiler = owner_->GetSubsystem<Profiler>();
  232. if (profiler)
  233. profiler->BeginBlock(profileBlockName.CString());
  234. #endif
  235. URHO3D_LOGDEBUG("Finishing background loaded resource " + resource->GetName());
  236. success = resource->EndLoad();
  237. #ifdef URHO3D_PROFILING
  238. if (profiler)
  239. profiler->EndBlock();
  240. #endif
  241. }
  242. resource->SetAsyncLoadState(ASYNC_DONE);
  243. if (!success && item.sendEventOnFailure_)
  244. {
  245. using namespace LoadFailed;
  246. VariantMap& eventData = owner_->GetEventDataMap();
  247. eventData[P_RESOURCENAME] = resource->GetName();
  248. owner_->SendEvent(E_LOADFAILED, eventData);
  249. }
  250. // Store to the cache just before sending the event; use same mechanism as for manual resources
  251. if (success || owner_->GetReturnFailedResources())
  252. owner_->AddManualResource(resource);
  253. // Send event, either success or failure
  254. {
  255. using namespace ResourceBackgroundLoaded;
  256. VariantMap& eventData = owner_->GetEventDataMap();
  257. eventData[P_RESOURCENAME] = resource->GetName();
  258. eventData[P_SUCCESS] = success;
  259. eventData[P_RESOURCE] = resource;
  260. owner_->SendEvent(E_RESOURCEBACKGROUNDLOADED, eventData);
  261. }
  262. }
  263. }
  264. #endif