BsResources.cpp 25 KB

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