BsResources.cpp 14 KB

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