BsResources.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. #include "BsResources.h"
  4. #include "BsResource.h"
  5. #include "BsResourceManifest.h"
  6. #include "BsException.h"
  7. #include "BsFileSerializer.h"
  8. #include "BsFileSystem.h"
  9. #include "BsTaskScheduler.h"
  10. #include "BsUUID.h"
  11. #include "BsDebug.h"
  12. #include "BsUtility.h"
  13. #include "BsSavedResourceData.h"
  14. #include "BsResourceListenerManager.h"
  15. namespace BansheeEngine
  16. {
  17. Resources::Resources()
  18. {
  19. mDefaultResourceManifest = ResourceManifest::create("Default");
  20. mResourceManifests.push_back(mDefaultResourceManifest);
  21. }
  22. Resources::~Resources()
  23. {
  24. // Unload and invalidate all resources
  25. UnorderedMap<String, LoadedResourceData> loadedResourcesCopy;
  26. {
  27. Lock lock(mLoadedResourceMutex);
  28. loadedResourcesCopy = mLoadedResources;
  29. }
  30. for (auto& loadedResourcePair : loadedResourcesCopy)
  31. destroy(loadedResourcePair.second.resource);
  32. }
  33. HResource Resources::load(const Path& filePath, ResourceLoadFlags loadFlags)
  34. {
  35. if (!FileSystem::isFile(filePath))
  36. {
  37. LOGWRN_VERBOSE("Cannot load resource. Specified file: " + filePath.toString() + " doesn't exist.");
  38. return HResource();
  39. }
  40. String uuid;
  41. bool foundUUID = getUUIDFromFilePath(filePath, uuid);
  42. if (!foundUUID)
  43. uuid = UUIDGenerator::generateRandom();
  44. return loadInternal(uuid, filePath, true, loadFlags);
  45. }
  46. HResource Resources::load(const WeakResourceHandle<Resource>& handle, ResourceLoadFlags loadFlags)
  47. {
  48. if (handle.mData == nullptr)
  49. return HResource();
  50. String uuid = handle.getUUID();
  51. return loadFromUUID(uuid, false, loadFlags);
  52. }
  53. HResource Resources::loadAsync(const Path& filePath, ResourceLoadFlags loadFlags)
  54. {
  55. if (!FileSystem::isFile(filePath))
  56. {
  57. LOGWRN_VERBOSE("Cannot load resource. Specified file: " + filePath.toString() + " doesn't exist.");
  58. return HResource();
  59. }
  60. String uuid;
  61. bool foundUUID = getUUIDFromFilePath(filePath, uuid);
  62. if (!foundUUID)
  63. uuid = UUIDGenerator::generateRandom();
  64. return loadInternal(uuid, filePath, false, loadFlags);
  65. }
  66. HResource Resources::loadFromUUID(const String& uuid, bool async, ResourceLoadFlags loadFlags)
  67. {
  68. Path filePath;
  69. // Default manifest is at 0th index but all other take priority since Default manifest could
  70. // contain obsolete data.
  71. for (auto iter = mResourceManifests.rbegin(); iter != mResourceManifests.rend(); ++iter)
  72. {
  73. if ((*iter)->uuidToFilePath(uuid, filePath))
  74. break;
  75. }
  76. return loadInternal(uuid, filePath, !async, loadFlags);
  77. }
  78. HResource Resources::loadInternal(const String& UUID, const Path& filePath, bool synchronous, ResourceLoadFlags loadFlags)
  79. {
  80. HResource outputResource;
  81. bool alreadyLoading = false;
  82. bool loadInProgress = false;
  83. {
  84. // Check if resource is already being loaded on a worker thread
  85. Lock inProgressLock(mInProgressResourcesMutex);
  86. auto iterFind2 = mInProgressResources.find(UUID);
  87. if (iterFind2 != mInProgressResources.end())
  88. {
  89. LoadedResourceData& resData = iterFind2->second->resData;
  90. outputResource = resData.resource.lock();
  91. if (loadFlags.isSet(ResourceLoadFlag::KeepInternalRef))
  92. {
  93. resData.numInternalRefs++;
  94. outputResource.addInternalRef();
  95. }
  96. alreadyLoading = true;
  97. loadInProgress = true;
  98. }
  99. // Previously being loaded as async but now we want it synced, so we wait
  100. if (loadInProgress && synchronous)
  101. outputResource.blockUntilLoaded();
  102. if (!alreadyLoading)
  103. {
  104. Lock loadedLock(mLoadedResourceMutex);
  105. auto iterFind = mLoadedResources.find(UUID);
  106. if (iterFind != mLoadedResources.end()) // Resource is already loaded
  107. {
  108. LoadedResourceData& resData = iterFind->second;
  109. outputResource = resData.resource.lock();
  110. if (loadFlags.isSet(ResourceLoadFlag::KeepInternalRef))
  111. {
  112. resData.numInternalRefs++;
  113. outputResource.addInternalRef();
  114. }
  115. alreadyLoading = true;
  116. }
  117. }
  118. }
  119. // Not loaded and not in progress, start loading of new resource
  120. // (or if already loaded or in progress, load any dependencies)
  121. if (!alreadyLoading)
  122. {
  123. // Check if the handle already exists
  124. Lock lock(mLoadedResourceMutex);
  125. auto iterFind = mHandles.find(UUID);
  126. if (iterFind != mHandles.end())
  127. outputResource = iterFind->second.lock();
  128. else
  129. {
  130. outputResource = HResource(UUID);
  131. mHandles[UUID] = outputResource.getWeak();
  132. }
  133. }
  134. // We have nowhere to load from, warn and complete load if a file path was provided,
  135. // otherwise pass through as we might just want to load from memory.
  136. if (filePath.isEmpty())
  137. {
  138. if (!alreadyLoading)
  139. {
  140. LOGWRN_VERBOSE("Cannot load resource. Resource with UUID '" + UUID + "' doesn't exist.");
  141. // Complete the load as that the depedency counter is properly reduced, in case this
  142. // is a dependency of some other resource.
  143. loadComplete(outputResource);
  144. return outputResource;
  145. }
  146. }
  147. else if (!FileSystem::isFile(filePath))
  148. {
  149. LOGWRN_VERBOSE("Cannot load resource. Specified file: " + filePath.toString() + " doesn't exist.");
  150. // Complete the load as that the depedency counter is properly reduced, in case this
  151. // is a dependency of some other resource.
  152. loadComplete(outputResource);
  153. assert(!loadInProgress); // Resource already being loaded but we can't find its path now?
  154. return outputResource;
  155. }
  156. // Load dependency data if a file path is provided
  157. SPtr<SavedResourceData> savedResourceData;
  158. if (!filePath.isEmpty())
  159. {
  160. FileDecoder fs(filePath);
  161. savedResourceData = std::static_pointer_cast<SavedResourceData>(fs.decode());
  162. }
  163. // If already loading keep the old load operation active, otherwise create a new one
  164. if (!alreadyLoading)
  165. {
  166. {
  167. Lock lock(mInProgressResourcesMutex);
  168. ResourceLoadData* loadData = bs_new<ResourceLoadData>(outputResource.getWeak(), 0);
  169. mInProgressResources[UUID] = loadData;
  170. loadData->resData = outputResource.getWeak();
  171. if (loadFlags.isSet(ResourceLoadFlag::KeepInternalRef))
  172. {
  173. loadData->resData.numInternalRefs++;
  174. outputResource.addInternalRef();
  175. }
  176. loadData->remainingDependencies = 1;
  177. loadData->notifyImmediately = synchronous; // Make resource listener trigger before exit if loading synchronously
  178. // Register dependencies and count them so we know when the resource is fully loaded
  179. if (loadFlags.isSet(ResourceLoadFlag::LoadDependencies) && savedResourceData != nullptr)
  180. {
  181. for (auto& dependency : savedResourceData->getDependencies())
  182. {
  183. if (dependency != UUID)
  184. {
  185. mDependantLoads[dependency].push_back(loadData);
  186. loadData->remainingDependencies++;
  187. }
  188. }
  189. }
  190. }
  191. if (loadFlags.isSet(ResourceLoadFlag::LoadDependencies) && savedResourceData != nullptr)
  192. {
  193. const Vector<String>& dependencyUUIDs = savedResourceData->getDependencies();
  194. UINT32 numDependencies = (UINT32)dependencyUUIDs.size();
  195. Vector<HResource> dependencies(numDependencies);
  196. ResourceLoadFlags depLoadFlags = ResourceLoadFlag::LoadDependencies;
  197. if (loadFlags.isSet(ResourceLoadFlag::KeepSourceData))
  198. depLoadFlags |= ResourceLoadFlag::KeepSourceData;
  199. for (UINT32 i = 0; i < numDependencies; i++)
  200. dependencies[i] = loadFromUUID(dependencyUUIDs[i], !synchronous, depLoadFlags);
  201. // Keep dependencies alive until the parent is done loading
  202. {
  203. Lock lock(mInProgressResourcesMutex);
  204. // At this point the resource is guaranteed to still be in-progress, so it's safe to update its dependency list
  205. mInProgressResources[UUID]->dependencies = dependencies;
  206. }
  207. }
  208. }
  209. else if (loadFlags.isSet(ResourceLoadFlag::LoadDependencies) && savedResourceData != nullptr) // Queue dependencies in case they aren't already loaded
  210. {
  211. const Vector<String>& dependencies = savedResourceData->getDependencies();
  212. if (!dependencies.empty())
  213. {
  214. {
  215. Lock lock(mInProgressResourcesMutex);
  216. ResourceLoadData* loadData = nullptr;
  217. auto iterFind = mInProgressResources.find(UUID);
  218. if (iterFind == mInProgressResources.end()) // Fully loaded
  219. {
  220. loadData = bs_new<ResourceLoadData>(outputResource.getWeak(), 0);
  221. loadData->resData = outputResource.getWeak();
  222. loadData->remainingDependencies = 0;
  223. loadData->notifyImmediately = synchronous; // Make resource listener trigger before exit if loading synchronously
  224. mInProgressResources[UUID] = loadData;
  225. }
  226. else
  227. {
  228. loadData = iterFind->second;
  229. }
  230. // Register dependencies and count them so we know when the resource is fully loaded
  231. for (auto& dependency : dependencies)
  232. {
  233. if (dependency != UUID)
  234. {
  235. bool registerDependency = true;
  236. auto iterFind2 = mDependantLoads.find(dependency);
  237. if (iterFind2 != mDependantLoads.end())
  238. {
  239. Vector<ResourceLoadData*>& dependantData = iterFind2->second;
  240. auto iterFind3 = std::find_if(dependantData.begin(), dependantData.end(),
  241. [&](ResourceLoadData* x)
  242. {
  243. return x->resData.resource.getUUID() == outputResource.getUUID();
  244. });
  245. registerDependency = iterFind3 == dependantData.end();
  246. }
  247. if (registerDependency)
  248. {
  249. mDependantLoads[dependency].push_back(loadData);
  250. loadData->remainingDependencies++;
  251. loadData->dependencies.push_back(_getResourceHandle(dependency));
  252. }
  253. }
  254. }
  255. }
  256. ResourceLoadFlags depLoadFlags = ResourceLoadFlag::LoadDependencies;
  257. if (loadFlags.isSet(ResourceLoadFlag::KeepSourceData))
  258. depLoadFlags |= ResourceLoadFlag::KeepSourceData;
  259. for (auto& dependency : dependencies)
  260. loadFromUUID(dependency, !synchronous, depLoadFlags);
  261. }
  262. }
  263. // Actually start the file read operation if not already loaded or in progress
  264. if (!alreadyLoading && !filePath.isEmpty())
  265. {
  266. // Synchronous or the resource doesn't support async, read the file immediately
  267. if (synchronous || !savedResourceData->allowAsyncLoading())
  268. {
  269. loadCallback(filePath, outputResource, loadFlags.isSet(ResourceLoadFlag::KeepSourceData));
  270. }
  271. else // Asynchronous, read the file on a worker thread
  272. {
  273. String fileName = filePath.getFilename();
  274. String taskName = "Resource load: " + fileName;
  275. bool keepSourceData = loadFlags.isSet(ResourceLoadFlag::KeepSourceData);
  276. SPtr<Task> task = Task::create(taskName,
  277. std::bind(&Resources::loadCallback, this, filePath, outputResource, keepSourceData));
  278. TaskScheduler::instance().addTask(task);
  279. }
  280. }
  281. else // File already loaded or in progress
  282. {
  283. // Complete the load unless its in progress in which case we wait for its worker thread to complete it.
  284. // In case file is already loaded this will only decrement dependency count in case this resource is a dependency.
  285. if (!loadInProgress)
  286. loadComplete(outputResource);
  287. else
  288. {
  289. // In case loading finished in the meantime we cannot be sure at what point ::loadComplete was triggered,
  290. // so trigger it manually so that the dependency count is properly decremented in case this resource
  291. // is a dependency.
  292. Lock lock(mLoadedResourceMutex);
  293. auto iterFind = mLoadedResources.find(UUID);
  294. if (iterFind != mLoadedResources.end())
  295. loadComplete(outputResource);
  296. }
  297. }
  298. return outputResource;
  299. }
  300. SPtr<Resource> Resources::loadFromDiskAndDeserialize(const Path& filePath, bool loadWithSaveData)
  301. {
  302. FileDecoder fs(filePath);
  303. fs.skip(); // Skipped over saved resource data
  304. UnorderedMap<String, UINT64> loadParams;
  305. if(loadWithSaveData)
  306. loadParams["keepSourceData"] = 1;
  307. SPtr<IReflectable> loadedData = fs.decode(loadParams);
  308. if (loadedData == nullptr)
  309. {
  310. LOGERR("Unable to load resource at path \"" + filePath.toString() + "\"");
  311. }
  312. else
  313. {
  314. if (!loadedData->isDerivedFrom(Resource::getRTTIStatic()))
  315. BS_EXCEPT(InternalErrorException, "Loaded class doesn't derive from Resource.");
  316. }
  317. SPtr<Resource> resource = std::static_pointer_cast<Resource>(loadedData);
  318. return resource;
  319. }
  320. void Resources::release(ResourceHandleBase& resource)
  321. {
  322. const String& UUID = resource.getUUID();
  323. {
  324. bool loadInProgress = false;
  325. Lock inProgressLock(mInProgressResourcesMutex);
  326. auto iterFind2 = mInProgressResources.find(UUID);
  327. if (iterFind2 != mInProgressResources.end())
  328. loadInProgress = true;
  329. // Technically we should be able to just cancel a load in progress instead of blocking until it finishes.
  330. // However that would mean the last reference could get lost on whatever thread did the loading, which
  331. // isn't something that's supported. If this ends up being a problem either make handle counting atomic
  332. // or add a separate queue for objects destroyed from the load threads.
  333. if (loadInProgress)
  334. resource.blockUntilLoaded();
  335. {
  336. Lock loadedLock(mLoadedResourceMutex);
  337. auto iterFind = mLoadedResources.find(UUID);
  338. if (iterFind != mLoadedResources.end()) // Resource is already loaded
  339. {
  340. LoadedResourceData& resData = iterFind->second;
  341. assert(resData.numInternalRefs > 0);
  342. resData.numInternalRefs--;
  343. resource.removeInternalRef();
  344. return;
  345. }
  346. }
  347. }
  348. }
  349. void Resources::unloadAllUnused()
  350. {
  351. Vector<HResource> resourcesToUnload;
  352. {
  353. Lock lock(mLoadedResourceMutex);
  354. for(auto iter = mLoadedResources.begin(); iter != mLoadedResources.end(); ++iter)
  355. {
  356. const LoadedResourceData& resData = iter->second;
  357. if (resData.resource.mData->mRefCount == resData.numInternalRefs) // Only internal references exist, free it
  358. resourcesToUnload.push_back(resData.resource.lock());
  359. }
  360. }
  361. // Note: When unloading multiple resources it's possible that unloading one will also unload
  362. // another resource in "resourcesToUnload". This is fine because "unload" deals with invalid
  363. // handles gracefully.
  364. for(auto iter = resourcesToUnload.begin(); iter != resourcesToUnload.end(); ++iter)
  365. {
  366. release(*iter);
  367. }
  368. }
  369. void Resources::destroy(ResourceHandleBase& resource)
  370. {
  371. if (resource.mData == nullptr)
  372. return;
  373. const String& uuid = resource.getUUID();
  374. if (!resource.isLoaded(false))
  375. {
  376. bool loadInProgress = false;
  377. {
  378. Lock lock(mInProgressResourcesMutex);
  379. auto iterFind2 = mInProgressResources.find(uuid);
  380. if (iterFind2 != mInProgressResources.end())
  381. loadInProgress = true;
  382. }
  383. if (loadInProgress) // If it's still loading wait until that finishes
  384. resource.blockUntilLoaded();
  385. else
  386. return; // Already unloaded
  387. }
  388. // Notify external systems before we actually destroy it
  389. onResourceDestroyed(uuid);
  390. resource.mData->mPtr->destroy();
  391. {
  392. Lock lock(mLoadedResourceMutex);
  393. auto iterFind = mLoadedResources.find(uuid);
  394. if (iterFind != mLoadedResources.end())
  395. {
  396. LoadedResourceData& resData = iterFind->second;
  397. while (resData.numInternalRefs > 0)
  398. {
  399. resData.numInternalRefs--;
  400. resData.resource.removeInternalRef();
  401. }
  402. mLoadedResources.erase(iterFind);
  403. }
  404. else
  405. {
  406. assert(false); // This should never happen but in case it does fail silently in release mode
  407. }
  408. }
  409. resource.setHandleData(nullptr, uuid);
  410. }
  411. void Resources::save(const HResource& resource, const Path& filePath, bool overwrite)
  412. {
  413. if (resource == nullptr)
  414. return;
  415. if (!resource.isLoaded(false))
  416. {
  417. bool loadInProgress = false;
  418. {
  419. Lock lock(mInProgressResourcesMutex);
  420. auto iterFind2 = mInProgressResources.find(resource.getUUID());
  421. if (iterFind2 != mInProgressResources.end())
  422. loadInProgress = true;
  423. }
  424. if (loadInProgress) // If it's still loading wait until that finishes
  425. resource.blockUntilLoaded();
  426. else
  427. return; // Nothing to save
  428. }
  429. bool fileExists = FileSystem::isFile(filePath);
  430. if(fileExists)
  431. {
  432. if(overwrite)
  433. FileSystem::remove(filePath);
  434. else
  435. BS_EXCEPT(InvalidParametersException, "Another file exists at the specified location.");
  436. }
  437. if (!resource->mKeepSourceData)
  438. {
  439. LOGWRN("Saving a resource that was created/loaded without ResourceLoadFlag::KeepSourceData. Some data might "
  440. "not be available for saving. File path: " + filePath.toString());
  441. }
  442. mDefaultResourceManifest->registerResource(resource.getUUID(), filePath);
  443. Vector<ResourceDependency> dependencyList = Utility::findResourceDependencies(*resource.get());
  444. Vector<String> dependencyUUIDs(dependencyList.size());
  445. for (UINT32 i = 0; i < (UINT32)dependencyList.size(); i++)
  446. dependencyUUIDs[i] = dependencyList[i].resource.getUUID();
  447. SPtr<SavedResourceData> resourceData = bs_shared_ptr_new<SavedResourceData>(dependencyUUIDs, resource->allowAsyncLoading());
  448. FileEncoder fs(filePath);
  449. fs.encode(resourceData.get());
  450. fs.encode(resource.get());
  451. }
  452. void Resources::save(const HResource& resource)
  453. {
  454. if (resource == nullptr)
  455. return;
  456. Path path;
  457. if (getFilePathFromUUID(resource.getUUID(), path))
  458. save(resource, path, true);
  459. }
  460. void Resources::update(HResource& handle, const SPtr<Resource>& resource)
  461. {
  462. const String& uuid = handle.getUUID();
  463. handle.setHandleData(resource, uuid);
  464. {
  465. Lock lock(mLoadedResourceMutex);
  466. auto iterFind = mLoadedResources.find(uuid);
  467. if (iterFind == mLoadedResources.end())
  468. {
  469. LoadedResourceData& resData = mLoadedResources[uuid];
  470. resData.resource = handle.getWeak();
  471. }
  472. }
  473. onResourceModified(handle);
  474. ResourceListenerManager::instance().notifyListeners(uuid);
  475. }
  476. Vector<String> Resources::getDependencies(const Path& filePath)
  477. {
  478. SPtr<SavedResourceData> savedResourceData;
  479. if (!filePath.isEmpty())
  480. {
  481. FileDecoder fs(filePath);
  482. savedResourceData = std::static_pointer_cast<SavedResourceData>(fs.decode());
  483. }
  484. return savedResourceData->getDependencies();
  485. }
  486. void Resources::registerResourceManifest(const SPtr<ResourceManifest>& manifest)
  487. {
  488. if(manifest->getName() == "Default")
  489. return;
  490. auto findIter = std::find(mResourceManifests.begin(), mResourceManifests.end(), manifest);
  491. if(findIter == mResourceManifests.end())
  492. mResourceManifests.push_back(manifest);
  493. else
  494. *findIter = manifest;
  495. }
  496. void Resources::unregisterResourceManifest(const SPtr<ResourceManifest>& manifest)
  497. {
  498. if (manifest->getName() == "Default")
  499. return;
  500. auto findIter = std::find(mResourceManifests.begin(), mResourceManifests.end(), manifest);
  501. if (findIter != mResourceManifests.end())
  502. mResourceManifests.erase(findIter);
  503. }
  504. SPtr<ResourceManifest> Resources::getResourceManifest(const String& name) const
  505. {
  506. for(auto iter = mResourceManifests.rbegin(); iter != mResourceManifests.rend(); ++iter)
  507. {
  508. if(name == (*iter)->getName())
  509. return (*iter);
  510. }
  511. return nullptr;
  512. }
  513. bool Resources::isLoaded(const String& uuid, bool checkInProgress)
  514. {
  515. if (checkInProgress)
  516. {
  517. Lock inProgressLock(mInProgressResourcesMutex);
  518. auto iterFind2 = mInProgressResources.find(uuid);
  519. if (iterFind2 != mInProgressResources.end())
  520. {
  521. return true;
  522. }
  523. {
  524. Lock loadedLock(mLoadedResourceMutex);
  525. auto iterFind = mLoadedResources.find(uuid);
  526. if (iterFind != mLoadedResources.end())
  527. {
  528. return true;
  529. }
  530. }
  531. }
  532. return false;
  533. }
  534. HResource Resources::_createResourceHandle(const SPtr<Resource>& obj)
  535. {
  536. String uuid = UUIDGenerator::generateRandom();
  537. HResource newHandle(obj, uuid);
  538. {
  539. Lock lock(mLoadedResourceMutex);
  540. LoadedResourceData& resData = mLoadedResources[uuid];
  541. resData.resource = newHandle.getWeak();
  542. mHandles[uuid] = newHandle.getWeak();
  543. }
  544. return newHandle;
  545. }
  546. HResource Resources::_getResourceHandle(const String& uuid)
  547. {
  548. Lock lock(mLoadedResourceMutex);
  549. auto iterFind3 = mHandles.find(uuid);
  550. if (iterFind3 != mHandles.end()) // Not loaded, but handle does exist
  551. {
  552. return iterFind3->second.lock();
  553. }
  554. // Create new handle
  555. HResource handle(uuid);
  556. mHandles[uuid] = handle.getWeak();
  557. return handle;
  558. }
  559. bool Resources::getFilePathFromUUID(const String& uuid, Path& filePath) const
  560. {
  561. for(auto iter = mResourceManifests.rbegin(); iter != mResourceManifests.rend(); ++iter)
  562. {
  563. if((*iter)->uuidToFilePath(uuid, filePath))
  564. return true;
  565. }
  566. return false;
  567. }
  568. bool Resources::getUUIDFromFilePath(const Path& path, String& uuid) const
  569. {
  570. Path manifestPath = path;
  571. if (!manifestPath.isAbsolute())
  572. manifestPath.makeAbsolute(FileSystem::getWorkingDirectoryPath());
  573. for(auto iter = mResourceManifests.rbegin(); iter != mResourceManifests.rend(); ++iter)
  574. {
  575. if ((*iter)->filePathToUUID(manifestPath, uuid))
  576. return true;
  577. }
  578. return false;
  579. }
  580. void Resources::loadComplete(HResource& resource)
  581. {
  582. String uuid = resource.getUUID();
  583. ResourceLoadData* myLoadData = nullptr;
  584. bool finishLoad = true;
  585. Vector<ResourceLoadData*> dependantLoads;
  586. {
  587. Lock inProgresslock(mInProgressResourcesMutex);
  588. auto iterFind = mInProgressResources.find(uuid);
  589. if (iterFind != mInProgressResources.end())
  590. {
  591. myLoadData = iterFind->second;
  592. finishLoad = myLoadData->remainingDependencies == 0;
  593. if (finishLoad)
  594. mInProgressResources.erase(iterFind);
  595. }
  596. auto iterFind2 = mDependantLoads.find(uuid);
  597. if (iterFind2 != mDependantLoads.end())
  598. dependantLoads = iterFind2->second;
  599. if (finishLoad)
  600. {
  601. mDependantLoads.erase(uuid);
  602. // If loadedData is null then we're probably completing load on an already loaded resource, triggered
  603. // by its dependencies.
  604. if (myLoadData != nullptr && myLoadData->loadedData != nullptr)
  605. {
  606. Lock loadedLock(mLoadedResourceMutex);
  607. mLoadedResources[uuid] = myLoadData->resData;
  608. resource.setHandleData(myLoadData->loadedData, uuid);
  609. }
  610. for (auto& dependantLoad : dependantLoads)
  611. dependantLoad->remainingDependencies--;
  612. }
  613. }
  614. for (auto& dependantLoad : dependantLoads)
  615. {
  616. HResource dependant = dependantLoad->resData.resource.lock();
  617. loadComplete(dependant);
  618. }
  619. if (finishLoad && myLoadData != nullptr)
  620. {
  621. onResourceLoaded(resource);
  622. // This should only ever be true on the main thread
  623. if (myLoadData->notifyImmediately)
  624. ResourceListenerManager::instance().notifyListeners(uuid);
  625. bs_delete(myLoadData);
  626. }
  627. }
  628. void Resources::loadCallback(const Path& filePath, HResource& resource, bool loadWithSaveData)
  629. {
  630. SPtr<Resource> rawResource = loadFromDiskAndDeserialize(filePath, loadWithSaveData);
  631. {
  632. Lock lock(mInProgressResourcesMutex);
  633. // Check if all my dependencies are loaded
  634. ResourceLoadData* myLoadData = mInProgressResources[resource.getUUID()];
  635. myLoadData->loadedData = rawResource;
  636. myLoadData->remainingDependencies--;
  637. }
  638. loadComplete(resource);
  639. }
  640. BS_CORE_EXPORT Resources& gResources()
  641. {
  642. return Resources::instance();
  643. }
  644. }