BackgroundLoader.cpp 10 KB

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