BsResources.cpp 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  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)
  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 load(filePath);
  59. }
  60. HResource Resources::loadFromUUIDAsync(const String& uuid)
  61. {
  62. Path filePath;
  63. bool foundPath = false;
  64. for(auto iter = mResourceManifests.rbegin(); iter != mResourceManifests.rend(); ++iter)
  65. {
  66. if((*iter)->uuidToFilePath(uuid, filePath))
  67. {
  68. foundPath = true;
  69. break;
  70. }
  71. }
  72. if(!foundPath)
  73. {
  74. gDebug().logWarning("Cannot load resource. Resource with UUID '" + uuid + "' doesn't exist.");
  75. return HResource();
  76. }
  77. return loadAsync(filePath);
  78. }
  79. HResource Resources::loadInternal(const Path& filePath, bool synchronous)
  80. {
  81. String uuid;
  82. bool foundUUID = false;
  83. for(auto iter = mResourceManifests.rbegin(); iter != mResourceManifests.rend(); ++iter)
  84. {
  85. if((*iter)->filePathToUUID(filePath, uuid))
  86. {
  87. foundUUID = true;
  88. break;
  89. }
  90. }
  91. if(!foundUUID)
  92. uuid = UUIDGenerator::instance().generateRandom();
  93. // Load saved resource data
  94. {
  95. }
  96. {
  97. BS_LOCK_MUTEX(mLoadedResourceMutex);
  98. auto iterFind = mLoadedResources.find(uuid);
  99. if(iterFind != mLoadedResources.end()) // Resource is already loaded
  100. {
  101. return iterFind->second;
  102. }
  103. }
  104. bool resourceLoadingInProgress = false;
  105. HResource existingResource;
  106. {
  107. BS_LOCK_MUTEX(mInProgressResourcesMutex);
  108. auto iterFind2 = mInProgressResources.find(uuid);
  109. if(iterFind2 != mInProgressResources.end())
  110. {
  111. existingResource = iterFind2->second;
  112. resourceLoadingInProgress = true;
  113. }
  114. }
  115. if(resourceLoadingInProgress) // We're already loading this resource
  116. {
  117. if(!synchronous)
  118. return existingResource;
  119. else
  120. {
  121. // Previously being loaded as async but now we want it synced, so we wait
  122. existingResource.blockUntilLoaded();
  123. return existingResource;
  124. }
  125. }
  126. if(!FileSystem::isFile(filePath))
  127. {
  128. gDebug().logWarning("Specified file: " + filePath.toString() + " doesn't exist.");
  129. return HResource();
  130. }
  131. HResource newResource(uuid);
  132. {
  133. BS_LOCK_MUTEX(mInProgressResourcesMutex);
  134. mInProgressResources[uuid] = newResource;
  135. }
  136. if(synchronous)
  137. {
  138. loadCallback(filePath, newResource);
  139. }
  140. else
  141. {
  142. String fileName = filePath.getFilename();
  143. String taskName = "Resource load: " + fileName;
  144. TaskPtr task = Task::create(taskName, std::bind(&Resources::loadCallback, this, filePath, newResource));
  145. TaskScheduler::instance().addTask(task);
  146. }
  147. return newResource;
  148. }
  149. ResourcePtr Resources::loadFromDiskAndDeserialize(const Path& filePath)
  150. {
  151. FileDecoder fs(filePath);
  152. fs.skip(); // Skipped over saved resource data
  153. std::shared_ptr<IReflectable> loadedData = fs.decode();
  154. if(loadedData == nullptr)
  155. BS_EXCEPT(InternalErrorException, "Unable to load resource.");
  156. if(!loadedData->isDerivedFrom(Resource::getRTTIStatic()))
  157. BS_EXCEPT(InternalErrorException, "Loaded class doesn't derive from Resource.");
  158. ResourcePtr resource = std::static_pointer_cast<Resource>(loadedData);
  159. return resource;
  160. }
  161. void Resources::unload(HResource resource)
  162. {
  163. if(!resource.isLoaded()) // If it's still loading wait until that finishes
  164. resource.blockUntilLoaded();
  165. // Call this before we actually destroy it
  166. onResourceDestroyed(resource);
  167. resource->destroy();
  168. {
  169. BS_LOCK_MUTEX(mLoadedResourceMutex);
  170. mLoadedResources.erase(resource.getUUID());
  171. }
  172. resource._setHandleData(nullptr, "");
  173. }
  174. void Resources::unloadAllUnused()
  175. {
  176. Vector<HResource> resourcesToUnload;
  177. {
  178. BS_LOCK_MUTEX(mLoadedResourceMutex);
  179. for(auto iter = mLoadedResources.begin(); iter != mLoadedResources.end(); ++iter)
  180. {
  181. if (iter->second.mData.unique()) // We just have this one reference, meaning nothing is using this resource
  182. resourcesToUnload.push_back(iter->second);
  183. }
  184. }
  185. for(auto iter = resourcesToUnload.begin(); iter != resourcesToUnload.end(); ++iter)
  186. {
  187. unload(*iter);
  188. }
  189. }
  190. void Resources::save(HResource resource, const Path& filePath, bool overwrite)
  191. {
  192. if(!resource.isLoaded())
  193. resource.blockUntilLoaded();
  194. bool fileExists = FileSystem::isFile(filePath);
  195. if(fileExists)
  196. {
  197. if(overwrite)
  198. FileSystem::remove(filePath);
  199. else
  200. BS_EXCEPT(InvalidParametersException, "Another file exists at the specified location.");
  201. }
  202. mDefaultResourceManifest->registerResource(resource.getUUID(), filePath);
  203. Vector<HResource> dependencyList = Utility::findResourceDependencies(*resource.get(), false);
  204. SPtr<SavedResourceData> resourceData = bs_shared_ptr<SavedResourceData>(dependencyList, resource->allowAsyncLoading());
  205. FileEncoder fs(filePath);
  206. fs.encode(resourceData.get());
  207. fs.encode(resource.get());
  208. }
  209. void Resources::registerResourceManifest(const ResourceManifestPtr& manifest)
  210. {
  211. if(manifest->getName() == "Default")
  212. return;
  213. auto findIter = std::find(mResourceManifests.begin(), mResourceManifests.end(), manifest);
  214. if(findIter == mResourceManifests.end())
  215. mResourceManifests.push_back(manifest);
  216. else
  217. *findIter = manifest;
  218. }
  219. ResourceManifestPtr Resources::getResourceManifest(const String& name) const
  220. {
  221. for(auto iter = mResourceManifests.rbegin(); iter != mResourceManifests.rend(); ++iter)
  222. {
  223. if(name == (*iter)->getName())
  224. return (*iter);
  225. }
  226. return nullptr;
  227. }
  228. HResource Resources::_createResourceHandle(const ResourcePtr& obj)
  229. {
  230. String uuid = UUIDGenerator::instance().generateRandom();
  231. HResource newHandle(obj, uuid);
  232. {
  233. BS_LOCK_MUTEX(mLoadedResourceMutex);
  234. mLoadedResources[uuid] = newHandle;
  235. }
  236. return newHandle;
  237. }
  238. bool Resources::getFilePathFromUUID(const String& uuid, Path& filePath) const
  239. {
  240. for(auto iter = mResourceManifests.rbegin(); iter != mResourceManifests.rend(); ++iter)
  241. {
  242. if((*iter)->uuidToFilePath(uuid, filePath))
  243. return true;
  244. }
  245. return false;
  246. }
  247. bool Resources::getUUIDFromFilePath(const Path& path, String& uuid) const
  248. {
  249. for(auto iter = mResourceManifests.rbegin(); iter != mResourceManifests.rend(); ++iter)
  250. {
  251. if((*iter)->filePathToUUID(path, uuid))
  252. return true;
  253. }
  254. return false;
  255. }
  256. void Resources::loadCallback(const Path& filePath, HResource& resource)
  257. {
  258. ResourcePtr rawResource = loadFromDiskAndDeserialize(filePath);
  259. {
  260. BS_LOCK_MUTEX(mInProgressResourcesMutex);
  261. mInProgressResources.erase(resource.getUUID());
  262. }
  263. resource._setHandleData(rawResource, resource.getUUID());
  264. onResourceLoaded(resource);
  265. {
  266. BS_LOCK_MUTEX(mLoadedResourceMutex);
  267. mLoadedResources[resource.getUUID()] = resource;
  268. }
  269. }
  270. BS_CORE_EXPORT Resources& gResources()
  271. {
  272. return Resources::instance();
  273. }
  274. }