BsResources.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  1. #include "BsResources.h"
  2. #include "BsResource.h"
  3. #include "BsResourceManifest.h"
  4. #include "BsException.h"
  5. #include "BsFileSerializer.h"
  6. #include "BsFileSystem.h"
  7. #include "BsTaskScheduler.h"
  8. #include "BsUUID.h"
  9. #include "BsPath.h"
  10. #include "BsDebug.h"
  11. #include "BsUtility.h"
  12. #include "BsSavedResourceData.h"
  13. #include "BsResourceListenerManager.h"
  14. namespace BansheeEngine
  15. {
  16. Resources::Resources()
  17. {
  18. mDefaultResourceManifest = ResourceManifest::create("Default");
  19. mResourceManifests.push_back(mDefaultResourceManifest);
  20. }
  21. Resources::~Resources()
  22. {
  23. // Unload and invalidate all resources
  24. UnorderedMap<String, HResource> loadedResourcesCopy = mLoadedResources;
  25. for (auto& loadedResourcePair : loadedResourcesCopy)
  26. {
  27. unload(loadedResourcePair.second);
  28. // Invalidate the handle
  29. loadedResourcePair.second._setHandleData(nullptr, "");
  30. }
  31. }
  32. HResource Resources::load(const Path& filePath)
  33. {
  34. return loadInternal(filePath, true);
  35. }
  36. HResource Resources::loadAsync(const Path& filePath)
  37. {
  38. return loadInternal(filePath, false);
  39. }
  40. HResource Resources::loadFromUUID(const String& uuid, bool async)
  41. {
  42. Path filePath;
  43. bool foundPath = false;
  44. // Default manifest is at 0th index but all other take priority since Default manifest could
  45. // contain obsolete data.
  46. for(auto iter = mResourceManifests.rbegin(); iter != mResourceManifests.rend(); ++iter)
  47. {
  48. if((*iter)->uuidToFilePath(uuid, filePath))
  49. {
  50. foundPath = true;
  51. break;
  52. }
  53. }
  54. if(!foundPath)
  55. {
  56. gDebug().logWarning("Cannot load resource. Resource with UUID '" + uuid + "' doesn't exist.");
  57. HResource outputResource(uuid);
  58. loadComplete(outputResource);
  59. return outputResource;
  60. }
  61. return loadInternal(filePath, !async);
  62. }
  63. HResource Resources::loadInternal(const Path& filePath, bool synchronous)
  64. {
  65. String uuid;
  66. bool foundUUID = false;
  67. for(auto iter = mResourceManifests.rbegin(); iter != mResourceManifests.rend(); ++iter)
  68. {
  69. if((*iter)->filePathToUUID(filePath, uuid))
  70. {
  71. foundUUID = true;
  72. break;
  73. }
  74. }
  75. if(!foundUUID)
  76. uuid = UUIDGenerator::instance().generateRandom();
  77. HResource outputResource;
  78. bool alreadyLoading = false;
  79. {
  80. BS_LOCK_MUTEX(mLoadedResourceMutex);
  81. auto iterFind = mLoadedResources.find(uuid);
  82. if(iterFind != mLoadedResources.end()) // Resource is already loaded
  83. {
  84. outputResource = iterFind->second;
  85. alreadyLoading = true;
  86. }
  87. }
  88. if (!alreadyLoading) // If not already detected as loaded
  89. {
  90. BS_LOCK_MUTEX(mInProgressResourcesMutex);
  91. auto iterFind2 = mInProgressResources.find(uuid);
  92. if(iterFind2 != mInProgressResources.end())
  93. {
  94. outputResource = iterFind2->second->resource;
  95. // Previously being loaded as async but now we want it synced, so we wait
  96. if (synchronous)
  97. outputResource.blockUntilLoaded();
  98. alreadyLoading = true;
  99. }
  100. }
  101. // Not loaded and not in progress, start loading of new resource
  102. // (or if already loaded or in progress, load any dependencies)
  103. if (!alreadyLoading)
  104. outputResource = HResource(uuid);
  105. if(!FileSystem::isFile(filePath))
  106. {
  107. gDebug().logWarning("Specified file: " + filePath.toString() + " doesn't exist.");
  108. loadComplete(outputResource);
  109. return outputResource;
  110. }
  111. // Load saved resource data
  112. FileDecoder fs(filePath);
  113. SPtr<SavedResourceData> savedResourceData = std::static_pointer_cast<SavedResourceData>(fs.decode());
  114. // If already loading keep the old load operation active,
  115. // otherwise create a new one
  116. if (!alreadyLoading)
  117. {
  118. BS_LOCK_MUTEX(mInProgressResourcesMutex);
  119. ResourceLoadData* loadData = bs_new<ResourceLoadData>(outputResource, 0);
  120. mInProgressResources[uuid] = loadData;
  121. loadData->resource = outputResource;
  122. loadData->remainingDependencies = 1;
  123. loadData->notifyImmediately = synchronous; // Make resource listener trigger before exit if loading synchronously
  124. for (auto& dependency : savedResourceData->getDependencies())
  125. {
  126. if (dependency != uuid)
  127. {
  128. mDependantLoads[dependency].push_back(loadData);
  129. loadData->remainingDependencies++;
  130. }
  131. }
  132. }
  133. // Load dependencies
  134. {
  135. for (auto& dependency : savedResourceData->getDependencies())
  136. {
  137. loadFromUUID(dependency, !synchronous);
  138. }
  139. }
  140. // Actually queue the load
  141. if (!alreadyLoading)
  142. {
  143. if (synchronous || !savedResourceData->allowAsyncLoading())
  144. {
  145. loadCallback(filePath, outputResource);
  146. }
  147. else
  148. {
  149. String fileName = filePath.getFilename();
  150. String taskName = "Resource load: " + fileName;
  151. TaskPtr task = Task::create(taskName, std::bind(&Resources::loadCallback, this, filePath, outputResource));
  152. TaskScheduler::instance().addTask(task);
  153. }
  154. }
  155. else
  156. loadComplete(outputResource);
  157. return outputResource;
  158. }
  159. ResourcePtr Resources::loadFromDiskAndDeserialize(const Path& filePath)
  160. {
  161. FileDecoder fs(filePath);
  162. fs.skip(); // Skipped over saved resource data
  163. std::shared_ptr<IReflectable> loadedData = fs.decode();
  164. if(loadedData == nullptr)
  165. BS_EXCEPT(InternalErrorException, "Unable to load resource.");
  166. if(!loadedData->isDerivedFrom(Resource::getRTTIStatic()))
  167. BS_EXCEPT(InternalErrorException, "Loaded class doesn't derive from Resource.");
  168. ResourcePtr resource = std::static_pointer_cast<Resource>(loadedData);
  169. return resource;
  170. }
  171. void Resources::unload(HResource resource)
  172. {
  173. if (resource == nullptr)
  174. return;
  175. if (!resource.isLoaded()) // If it's still loading wait until that finishes
  176. {
  177. LOGWRN("Performance warning: Unloading a resource that is still in process of loading "
  178. "causes a stall until resource finishes loading.");
  179. resource.blockUntilLoaded();
  180. }
  181. Vector<ResourceDependency> dependencies = Utility::findResourceDependencies(*resource.get());
  182. // Call this before we actually destroy it
  183. onResourceDestroyed(resource);
  184. resource->destroy();
  185. {
  186. BS_LOCK_MUTEX(mLoadedResourceMutex);
  187. mLoadedResources.erase(resource.getUUID());
  188. }
  189. resource._setHandleData(nullptr, "");
  190. for (auto& dependency : dependencies)
  191. {
  192. HResource dependantResource = dependency.resource;
  193. // Last reference was kept by the unloaded resource, so unload the dependency too
  194. if ((UINT32)dependantResource.mData.use_count() == (dependency.numReferences + 1))
  195. {
  196. // TODO - Use count is not thread safe. Meaning it might increase after above check, in
  197. // which case we will be unloading a resource that is in use. I don't see a way around
  198. // it at the moment.
  199. unload(dependantResource);
  200. }
  201. }
  202. }
  203. void Resources::unloadAllUnused()
  204. {
  205. Vector<HResource> resourcesToUnload;
  206. {
  207. BS_LOCK_MUTEX(mLoadedResourceMutex);
  208. for(auto iter = mLoadedResources.begin(); iter != mLoadedResources.end(); ++iter)
  209. {
  210. if (iter->second.mData.unique()) // We just have this one reference, meaning nothing is using this resource
  211. resourcesToUnload.push_back(iter->second);
  212. }
  213. }
  214. // Note: When unloading multiple resources it's possible that unloading one will also unload
  215. // another resource in "resourcesToUnload". This is fine because "unload" deals with invalid
  216. // handles gracefully.
  217. for(auto iter = resourcesToUnload.begin(); iter != resourcesToUnload.end(); ++iter)
  218. {
  219. unload(*iter);
  220. }
  221. }
  222. void Resources::save(HResource resource, const Path& filePath, bool overwrite)
  223. {
  224. if(!resource.isLoaded())
  225. resource.blockUntilLoaded();
  226. bool fileExists = FileSystem::isFile(filePath);
  227. if(fileExists)
  228. {
  229. if(overwrite)
  230. FileSystem::remove(filePath);
  231. else
  232. BS_EXCEPT(InvalidParametersException, "Another file exists at the specified location.");
  233. }
  234. mDefaultResourceManifest->registerResource(resource.getUUID(), filePath);
  235. Vector<ResourceDependency> dependencyList = Utility::findResourceDependencies(*resource.get());
  236. Vector<String> dependencyUUIDs(dependencyList.size());
  237. for (UINT32 i = 0; i < (UINT32)dependencyList.size(); i++)
  238. dependencyUUIDs[i] = dependencyList[i].resource.getUUID();
  239. SPtr<SavedResourceData> resourceData = bs_shared_ptr<SavedResourceData>(dependencyUUIDs, resource->allowAsyncLoading());
  240. FileEncoder fs(filePath);
  241. fs.encode(resourceData.get());
  242. fs.encode(resource.get());
  243. }
  244. void Resources::registerResourceManifest(const ResourceManifestPtr& manifest)
  245. {
  246. if(manifest->getName() == "Default")
  247. return;
  248. auto findIter = std::find(mResourceManifests.begin(), mResourceManifests.end(), manifest);
  249. if(findIter == mResourceManifests.end())
  250. mResourceManifests.push_back(manifest);
  251. else
  252. *findIter = manifest;
  253. }
  254. ResourceManifestPtr Resources::getResourceManifest(const String& name) const
  255. {
  256. for(auto iter = mResourceManifests.rbegin(); iter != mResourceManifests.rend(); ++iter)
  257. {
  258. if(name == (*iter)->getName())
  259. return (*iter);
  260. }
  261. return nullptr;
  262. }
  263. HResource Resources::_createResourceHandle(const ResourcePtr& obj)
  264. {
  265. String uuid = UUIDGenerator::instance().generateRandom();
  266. HResource newHandle(obj, uuid);
  267. {
  268. BS_LOCK_MUTEX(mLoadedResourceMutex);
  269. mLoadedResources[uuid] = newHandle;
  270. }
  271. return newHandle;
  272. }
  273. HResource Resources::_getResourceHandle(const String& uuid)
  274. {
  275. {
  276. BS_LOCK_MUTEX(mLoadedResourceMutex);
  277. auto iterFind = mLoadedResources.find(uuid);
  278. if (iterFind != mLoadedResources.end()) // Resource is already loaded
  279. {
  280. return iterFind->second;
  281. }
  282. }
  283. {
  284. BS_LOCK_MUTEX(mInProgressResourcesMutex);
  285. auto iterFind2 = mInProgressResources.find(uuid);
  286. if (iterFind2 != mInProgressResources.end())
  287. {
  288. return iterFind2->second->resource;
  289. }
  290. }
  291. return HResource();
  292. }
  293. bool Resources::getFilePathFromUUID(const String& uuid, Path& filePath) const
  294. {
  295. for(auto iter = mResourceManifests.rbegin(); iter != mResourceManifests.rend(); ++iter)
  296. {
  297. if((*iter)->uuidToFilePath(uuid, filePath))
  298. return true;
  299. }
  300. return false;
  301. }
  302. bool Resources::getUUIDFromFilePath(const Path& path, String& uuid) const
  303. {
  304. for(auto iter = mResourceManifests.rbegin(); iter != mResourceManifests.rend(); ++iter)
  305. {
  306. if((*iter)->filePathToUUID(path, uuid))
  307. return true;
  308. }
  309. return false;
  310. }
  311. void Resources::loadComplete(HResource& resource)
  312. {
  313. String uuid = resource.getUUID();
  314. ResourceLoadData* myLoadData = nullptr;
  315. Vector<ResourceLoadData*> dependantLoads;
  316. {
  317. BS_LOCK_MUTEX(mInProgressResourcesMutex);
  318. auto iterFind = mInProgressResources.find(uuid);
  319. if (iterFind != mInProgressResources.end())
  320. {
  321. myLoadData = iterFind->second;
  322. mInProgressResources.erase(iterFind);
  323. }
  324. dependantLoads = mDependantLoads[uuid];
  325. mDependantLoads.erase(uuid);
  326. }
  327. if (myLoadData != nullptr)
  328. {
  329. {
  330. BS_LOCK_MUTEX(mLoadedResourceMutex);
  331. mLoadedResources[uuid] = resource;
  332. }
  333. resource._setHandleData(myLoadData->loadedData, uuid);
  334. onResourceLoaded(resource);
  335. if (myLoadData->notifyImmediately)
  336. ResourceListenerManager::instance().notifyListeners(uuid);
  337. bs_delete(myLoadData);
  338. }
  339. for (auto& dependantLoad : dependantLoads)
  340. {
  341. dependantLoad->remainingDependencies--;
  342. if (dependantLoad->remainingDependencies == 0)
  343. loadComplete(dependantLoad->resource);
  344. }
  345. }
  346. void Resources::loadCallback(const Path& filePath, HResource& resource)
  347. {
  348. ResourcePtr rawResource = loadFromDiskAndDeserialize(filePath);
  349. bool finishLoad = false;
  350. {
  351. BS_LOCK_MUTEX(mInProgressResourcesMutex);
  352. // Check if all my dependencies are loaded
  353. ResourceLoadData* myLoadData = mInProgressResources[resource.getUUID()];
  354. myLoadData->loadedData = rawResource;
  355. myLoadData->remainingDependencies--;
  356. finishLoad = myLoadData->remainingDependencies == 0;
  357. }
  358. if (finishLoad)
  359. loadComplete(resource);
  360. }
  361. BS_CORE_EXPORT Resources& gResources()
  362. {
  363. return Resources::instance();
  364. }
  365. }