BsResources.cpp 11 KB

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