BackgroundLoader.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. //
  2. // Copyright (c) 2008-2015 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "../Resource/BackgroundLoader.h"
  23. #include "../Core/Context.h"
  24. #include "../IO/Log.h"
  25. #include "../Core/Profiler.h"
  26. #include "../Resource/ResourceCache.h"
  27. #include "../Resource/ResourceEvents.h"
  28. #include "../Core/Timer.h"
  29. #include "../DebugNew.h"
  30. namespace Urho3D
  31. {
  32. BackgroundLoader::BackgroundLoader(ResourceCache* owner) :
  33. owner_(owner)
  34. {
  35. }
  36. void BackgroundLoader::ThreadFunction()
  37. {
  38. while (shouldRun_)
  39. {
  40. backgroundLoadMutex_.Acquire();
  41. // Search for a queued resource that has not been loaded yet
  42. HashMap<Pair<StringHash, StringHash>, BackgroundLoadItem>::Iterator i = backgroundLoadQueue_.Begin();
  43. while (i != backgroundLoadQueue_.End())
  44. {
  45. if (i->second_.resource_->GetAsyncLoadState() == ASYNC_QUEUED)
  46. break;
  47. else
  48. ++i;
  49. }
  50. if (i == backgroundLoadQueue_.End())
  51. {
  52. // No resources to load found
  53. backgroundLoadMutex_.Release();
  54. Time::Sleep(5);
  55. }
  56. else
  57. {
  58. BackgroundLoadItem& item = i->second_;
  59. Resource* resource = item.resource_;
  60. // We can be sure that the item is not removed from the queue as long as it is in the
  61. // "queued" or "loading" state
  62. backgroundLoadMutex_.Release();
  63. bool success = false;
  64. SharedPtr<File> file = owner_->GetFile(resource->GetName(), item.sendEventOnFailure_);
  65. if (file)
  66. {
  67. resource->SetAsyncLoadState(ASYNC_LOADING);
  68. success = resource->BeginLoad(*file);
  69. }
  70. // Process dependencies now
  71. // Need to lock the queue again when manipulating other entries
  72. Pair<StringHash, StringHash> key = MakePair(resource->GetType(), resource->GetNameHash());
  73. backgroundLoadMutex_.Acquire();
  74. if (item.dependents_.Size())
  75. {
  76. for (HashSet<Pair<StringHash, StringHash> >::Iterator i = item.dependents_.Begin(); i != item.dependents_.End();
  77. ++i)
  78. {
  79. HashMap<Pair<StringHash, StringHash>, BackgroundLoadItem>::Iterator j =
  80. backgroundLoadQueue_.Find(*i);
  81. if (j != backgroundLoadQueue_.End())
  82. j->second_.dependencies_.Erase(key);
  83. }
  84. item.dependents_.Clear();
  85. }
  86. resource->SetAsyncLoadState(success ? ASYNC_SUCCESS : ASYNC_FAIL);
  87. backgroundLoadMutex_.Release();
  88. }
  89. }
  90. }
  91. bool BackgroundLoader::QueueResource(StringHash type, const String& name, bool sendEventOnFailure, Resource* caller)
  92. {
  93. StringHash nameHash(name);
  94. Pair<StringHash, StringHash> key = MakePair(type, nameHash);
  95. MutexLock lock(backgroundLoadMutex_);
  96. // Check if already exists in the queue
  97. if (backgroundLoadQueue_.Find(key) != backgroundLoadQueue_.End())
  98. return false;
  99. BackgroundLoadItem& item = backgroundLoadQueue_[key];
  100. item.sendEventOnFailure_ = sendEventOnFailure;
  101. // Make sure the pointer is non-null and is a Resource subclass
  102. item.resource_ = DynamicCast<Resource>(owner_->GetContext()->CreateObject(type));
  103. if (!item.resource_)
  104. {
  105. LOGERROR("Could not load unknown resource type " + String(type));
  106. if (sendEventOnFailure && Thread::IsMainThread())
  107. {
  108. using namespace UnknownResourceType;
  109. VariantMap& eventData = owner_->GetEventDataMap();
  110. eventData[P_RESOURCETYPE] = type;
  111. owner_->SendEvent(E_UNKNOWNRESOURCETYPE, eventData);
  112. }
  113. backgroundLoadQueue_.Erase(key);
  114. return false;
  115. }
  116. LOGDEBUG("Background loading resource " + name);
  117. item.resource_->SetName(name);
  118. item.resource_->SetAsyncLoadState(ASYNC_QUEUED);
  119. // If this is a resource calling for the background load of more resources, mark the dependency as necessary
  120. if (caller)
  121. {
  122. Pair<StringHash, StringHash> callerKey = MakePair(caller->GetType(), caller->GetNameHash());
  123. HashMap<Pair<StringHash, StringHash>, BackgroundLoadItem>::Iterator j = backgroundLoadQueue_.Find(callerKey);
  124. if (j != backgroundLoadQueue_.End())
  125. {
  126. BackgroundLoadItem& callerItem = j->second_;
  127. item.dependents_.Insert(callerKey);
  128. callerItem.dependencies_.Insert(key);
  129. }
  130. else
  131. LOGWARNING("Resource " + caller->GetName() + " requested for a background loaded resource but was not in the background load queue");
  132. }
  133. // Start the background loader thread now
  134. if (!IsStarted())
  135. Run();
  136. return true;
  137. }
  138. void BackgroundLoader::WaitForResource(StringHash type, StringHash nameHash)
  139. {
  140. backgroundLoadMutex_.Acquire();
  141. // Check if the resource in question is being background loaded
  142. Pair<StringHash, StringHash> key = MakePair(type, nameHash);
  143. HashMap<Pair<StringHash, StringHash>, BackgroundLoadItem>::Iterator i = backgroundLoadQueue_.Find(key);
  144. if (i != backgroundLoadQueue_.End())
  145. {
  146. backgroundLoadMutex_.Release();
  147. {
  148. Resource* resource = i->second_.resource_;
  149. HiresTimer waitTimer;
  150. bool didWait = false;
  151. for (;;)
  152. {
  153. unsigned numDeps = i->second_.dependencies_.Size();
  154. AsyncLoadState state = resource->GetAsyncLoadState();
  155. if (numDeps > 0 || state == ASYNC_QUEUED || state == ASYNC_LOADING)
  156. {
  157. didWait = true;
  158. Time::Sleep(1);
  159. }
  160. else
  161. break;
  162. }
  163. if (didWait)
  164. LOGDEBUG("Waited " + String(waitTimer.GetUSec(false) / 1000) + " ms for background loaded resource " + resource->GetName());
  165. }
  166. // 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
  167. FinishBackgroundLoading(i->second_);
  168. backgroundLoadMutex_.Acquire();
  169. backgroundLoadQueue_.Erase(i);
  170. backgroundLoadMutex_.Release();
  171. }
  172. else
  173. backgroundLoadMutex_.Release();
  174. }
  175. void BackgroundLoader::FinishResources(int maxMs)
  176. {
  177. if (IsStarted())
  178. {
  179. HiresTimer timer;
  180. backgroundLoadMutex_.Acquire();
  181. for (HashMap<Pair<StringHash, StringHash>, BackgroundLoadItem>::Iterator i = backgroundLoadQueue_.Begin();
  182. i != backgroundLoadQueue_.End();)
  183. {
  184. Resource* resource = i->second_.resource_;
  185. unsigned numDeps = i->second_.dependencies_.Size();
  186. AsyncLoadState state = resource->GetAsyncLoadState();
  187. if (numDeps > 0 || state == ASYNC_QUEUED || state == ASYNC_LOADING)
  188. ++i;
  189. else
  190. {
  191. // Finishing a resource may need it to wait for other resources to load, in which case we can not
  192. // hold on to the mutex
  193. backgroundLoadMutex_.Release();
  194. FinishBackgroundLoading(i->second_);
  195. backgroundLoadMutex_.Acquire();
  196. i = backgroundLoadQueue_.Erase(i);
  197. }
  198. // Break when the time limit passed so that we keep sufficient FPS
  199. if (timer.GetUSec(false) >= maxMs * 1000)
  200. break;
  201. }
  202. backgroundLoadMutex_.Release();
  203. }
  204. }
  205. unsigned BackgroundLoader::GetNumQueuedResources() const
  206. {
  207. MutexLock lock(backgroundLoadMutex_);
  208. return backgroundLoadQueue_.Size();
  209. }
  210. void BackgroundLoader::FinishBackgroundLoading(BackgroundLoadItem& item)
  211. {
  212. Resource* resource = item.resource_;
  213. bool success = resource->GetAsyncLoadState() == ASYNC_SUCCESS;
  214. // If BeginLoad() phase was successful, call EndLoad() and get the final success/failure result
  215. if (success)
  216. {
  217. #ifdef URHO3D_PROFILING
  218. String profileBlockName("Finish" + resource->GetTypeName());
  219. Profiler* profiler = owner_->GetSubsystem<Profiler>();
  220. if (profiler)
  221. profiler->BeginBlock(profileBlockName.CString());
  222. #endif
  223. LOGDEBUG("Finishing background loaded resource " + resource->GetName());
  224. success = resource->EndLoad();
  225. #ifdef URHO3D_PROFILING
  226. if (profiler)
  227. profiler->EndBlock();
  228. #endif
  229. }
  230. resource->SetAsyncLoadState(ASYNC_DONE);
  231. if (!success && item.sendEventOnFailure_)
  232. {
  233. using namespace LoadFailed;
  234. VariantMap& eventData = owner_->GetEventDataMap();
  235. eventData[P_RESOURCENAME] = resource->GetName();
  236. owner_->SendEvent(E_LOADFAILED, eventData);
  237. }
  238. // Send event, either success or failure
  239. {
  240. using namespace ResourceBackgroundLoaded;
  241. VariantMap& eventData = owner_->GetEventDataMap();
  242. eventData[P_RESOURCENAME] = resource->GetName();
  243. eventData[P_SUCCESS] = success;
  244. eventData[P_RESOURCE] = resource;
  245. owner_->SendEvent(E_RESOURCEBACKGROUNDLOADED, eventData);
  246. }
  247. // Store to the cache; use same mechanism as for manual resources
  248. if (success || owner_->GetReturnFailedResources())
  249. owner_->AddManualResource(resource);
  250. }
  251. }