BsResources.cpp 12 KB

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