BsResources.cpp 18 KB

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