2
0

BsResources.cpp 26 KB

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