BsProjectLibrary.cpp 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. #include "Library/BsProjectLibrary.h"
  4. #include "FileSystem/BsFileSystem.h"
  5. #include "Error/BsException.h"
  6. #include "Resources/BsResources.h"
  7. #include "Resources/BsResourceManifest.h"
  8. #include "Importer/BsImporter.h"
  9. #include "Library/BsProjectResourceMeta.h"
  10. #include "Resources/BsResources.h"
  11. #include "Importer/BsImporter.h"
  12. #include "Importer/BsImportOptions.h"
  13. #include "Serialization/BsFileSerializer.h"
  14. #include "Serialization/BsSerializedObject.h"
  15. #include "Serialization/BsBinaryDiff.h"
  16. #include "Debug/BsDebug.h"
  17. #include "Library/BsProjectLibraryEntries.h"
  18. #include "Resources/BsResource.h"
  19. #include "BsEditorApplication.h"
  20. #include "Material/BsShader.h"
  21. #include "Image/BsTexture.h"
  22. #include "String/BsUnicode.h"
  23. #include "CoreThread/BsCoreThread.h"
  24. #include "Threading/BsTaskScheduler.h"
  25. #include "RenderAPI/BsRenderTexture.h"
  26. #include "Renderer/BsRendererUtility.h"
  27. #include <regex>
  28. using namespace std::placeholders;
  29. namespace bs
  30. {
  31. void coreGeneratePreviewPyramid(const SPtr<ct::Texture>& input, const SPtr<ct::RenderTexture>* outputs,
  32. UINT32 numOutputs)
  33. {
  34. if(numOutputs == 0)
  35. return;
  36. gProfilerGPU().beginFrame();
  37. ct::RenderAPI& rapi = ct::RenderAPI::instance();
  38. rapi.setRenderTarget(outputs[0]);
  39. ct::gRendererUtility().blit(input);
  40. for(UINT32 i = 1; i < numOutputs; i++)
  41. {
  42. rapi.setRenderTarget(outputs[i]);
  43. ct::gRendererUtility().blit(outputs[i - 1]->getColorTexture(0), Rect2I::EMPTY, false, false, true);
  44. }
  45. rapi.submitCommandBuffer(nullptr);
  46. gProfilerGPU().endFrame(true);
  47. }
  48. ProjectResourceIcons generatePreviewIcons(Resource& resource)
  49. {
  50. ProjectResourceIcons icons;
  51. const UINT32 typeId = resource.getTypeId();
  52. if(typeId == TID_Texture)
  53. {
  54. Texture& texture = static_cast<Texture&>(resource);
  55. SPtr<Texture> texturePtr = static_pointer_cast<Texture>(texture.getThisPtr());
  56. UINT32 sizes[] = { 256, 192, 128, 96, 64, 48, 32, 16 };
  57. constexpr UINT32 numSizes = (UINT32)bs_size(sizes);
  58. SPtr<RenderTexture> rts[numSizes];
  59. SPtr<ct::RenderTexture> coreRts[numSizes];
  60. for(UINT32 i = 0; i < numSizes; i++)
  61. {
  62. TEXTURE_DESC rtDesc;
  63. rtDesc.usage |= TU_CPUREADABLE;
  64. rtDesc.width = sizes[i];
  65. rtDesc.height = sizes[i];
  66. rts[i] = RenderTexture::create(rtDesc, false);
  67. coreRts[i] = rts[i]->getCore();
  68. }
  69. gCoreThread().queueCommand(
  70. [coreTex = texturePtr->getCore(), coreRts, numSizes]()
  71. {
  72. coreGeneratePreviewPyramid(coreTex, coreRts, numSizes);
  73. }, CTQF_BlockUntilComplete);
  74. icons.icon256 = rts[0]->getColorTexture(0);
  75. icons.icon192 = rts[1]->getColorTexture(0);
  76. icons.icon128 = rts[2]->getColorTexture(0);
  77. icons.icon96 = rts[3]->getColorTexture(0);
  78. icons.icon64 = rts[4]->getColorTexture(0);
  79. icons.icon48 = rts[5]->getColorTexture(0);
  80. icons.icon32 = rts[6]->getColorTexture(0);
  81. icons.icon16 = rts[7]->getColorTexture(0);
  82. }
  83. return icons;
  84. }
  85. const Path TEMP_DIR = "Temp/";
  86. const Path INTERNAL_TEMP_DIR = PROJECT_INTERNAL_DIR + TEMP_DIR;
  87. const Path ProjectLibrary::RESOURCES_DIR = "Resources/";
  88. const Path ProjectLibrary::INTERNAL_RESOURCES_DIR = PROJECT_INTERNAL_DIR + RESOURCES_DIR;
  89. const char* ProjectLibrary::LIBRARY_ENTRIES_FILENAME = "ProjectLibrary.asset";
  90. const char* ProjectLibrary::RESOURCE_MANIFEST_FILENAME = "ResourceManifest.asset";
  91. ProjectLibrary::LibraryEntry::LibraryEntry()
  92. :type(LibraryEntryType::Directory)
  93. { }
  94. ProjectLibrary::LibraryEntry::LibraryEntry(const Path& path, const String& name, DirectoryEntry* parent,
  95. LibraryEntryType type)
  96. :type(type), path(path), elementName(name), elementNameHash(bs_hash(UTF8::toLower(name))), parent(parent)
  97. { }
  98. ProjectLibrary::FileEntry::FileEntry(const Path& path, const String& name, DirectoryEntry* parent)
  99. :LibraryEntry(path, name, parent, LibraryEntryType::File)
  100. { }
  101. ProjectLibrary::DirectoryEntry::DirectoryEntry(const Path& path, const String& name, DirectoryEntry* parent)
  102. :LibraryEntry(path, name, parent, LibraryEntryType::Directory)
  103. { }
  104. ProjectLibrary::ProjectLibrary()
  105. : mRootEntry(nullptr), mIsLoaded(false)
  106. {
  107. mRootEntry = bs_ushared_ptr_new<DirectoryEntry>(mResourcesFolder, mResourcesFolder.getTail(), nullptr);
  108. }
  109. ProjectLibrary::~ProjectLibrary()
  110. {
  111. _finishQueuedImports(true);
  112. clearEntries();
  113. }
  114. UINT32 ProjectLibrary::checkForModifications(const Path& fullPath)
  115. {
  116. UINT32 resourcesToImport = 0;
  117. if (!mResourcesFolder.includes(fullPath))
  118. return resourcesToImport; // Folder not part of our resources path, so no modifications
  119. if(mRootEntry == nullptr)
  120. mRootEntry = bs_ushared_ptr_new<DirectoryEntry>(mResourcesFolder, mResourcesFolder.getTail(), nullptr);
  121. Path pathToSearch = fullPath;
  122. USPtr<LibraryEntry> entry = findEntry(pathToSearch);
  123. if (entry == nullptr) // File could be new, try to find parent directory entry
  124. {
  125. if (FileSystem::exists(pathToSearch))
  126. {
  127. if (isMeta(pathToSearch))
  128. {
  129. Path sourceFilePath = pathToSearch;
  130. sourceFilePath.setExtension("");
  131. if (!FileSystem::isFile(sourceFilePath))
  132. {
  133. BS_LOG(Warning, Editor, "Found a .meta file without a corresponding resource. Deleting.");
  134. FileSystem::remove(pathToSearch);
  135. }
  136. }
  137. else
  138. {
  139. Path parentDirPath = pathToSearch.getParent();
  140. entry = findEntry(parentDirPath);
  141. // Cannot find parent directory. Create the needed hierarchy.
  142. DirectoryEntry* entryParent = nullptr;
  143. DirectoryEntry* newHierarchyParent = nullptr;
  144. if (entry == nullptr)
  145. createInternalParentHierarchy(pathToSearch, &newHierarchyParent, &entryParent);
  146. else
  147. entryParent = static_cast<DirectoryEntry*>(entry.get());
  148. if (FileSystem::isFile(pathToSearch))
  149. addResourceInternal(entryParent, pathToSearch);
  150. else if (FileSystem::isDirectory(pathToSearch))
  151. {
  152. addDirectoryInternal(entryParent, pathToSearch);
  153. resourcesToImport += checkForModifications(pathToSearch);
  154. }
  155. }
  156. }
  157. }
  158. else if(entry->type == LibraryEntryType::File)
  159. {
  160. if(FileSystem::isFile(entry->path))
  161. {
  162. FileEntry* resEntry = static_cast<FileEntry*>(entry.get());
  163. if(reimportResourceInternal(resEntry))
  164. resourcesToImport++;
  165. }
  166. else
  167. deleteResourceInternal(static_pointer_cast<FileEntry>(entry));
  168. }
  169. else if(entry->type == LibraryEntryType::Directory) // Check folder and all subfolders for modifications
  170. {
  171. if(!FileSystem::isDirectory(entry->path))
  172. {
  173. deleteDirectoryInternal(static_pointer_cast<DirectoryEntry>(entry));
  174. }
  175. else
  176. {
  177. Stack<DirectoryEntry*> todo;
  178. todo.push(static_cast<DirectoryEntry*>(entry.get()));
  179. Vector<Path> childFiles;
  180. Vector<Path> childDirectories;
  181. Vector<bool> existingEntries;
  182. Vector<USPtr<LibraryEntry>> toDelete;
  183. while(!todo.empty())
  184. {
  185. DirectoryEntry* currentDir = todo.top();
  186. todo.pop();
  187. existingEntries.clear();
  188. existingEntries.resize(currentDir->mChildren.size());
  189. for(UINT32 i = 0; i < (UINT32)currentDir->mChildren.size(); i++)
  190. existingEntries[i] = false;
  191. childFiles.clear();
  192. childDirectories.clear();
  193. FileSystem::getChildren(currentDir->path, childFiles, childDirectories);
  194. for(auto& filePath : childFiles)
  195. {
  196. if(isMeta(filePath))
  197. {
  198. Path sourceFilePath = filePath;
  199. sourceFilePath.setExtension("");
  200. if(!FileSystem::isFile(sourceFilePath))
  201. {
  202. BS_LOG(Warning, Editor, "Found a .meta file without a corresponding resource. Deleting.");
  203. FileSystem::remove(filePath);
  204. }
  205. }
  206. else
  207. {
  208. FileEntry* existingEntry = nullptr;
  209. UINT32 idx = 0;
  210. for(auto& child : currentDir->mChildren)
  211. {
  212. if(child->type == LibraryEntryType::File && child->path == filePath)
  213. {
  214. existingEntries[idx] = true;
  215. existingEntry = static_cast<FileEntry*>(child.get());
  216. break;
  217. }
  218. idx++;
  219. }
  220. if(existingEntry != nullptr)
  221. {
  222. if(reimportResourceInternal(existingEntry))
  223. resourcesToImport++;
  224. }
  225. else
  226. {
  227. addResourceInternal(currentDir, filePath);
  228. resourcesToImport++;
  229. }
  230. }
  231. }
  232. for(auto& dirPath : childDirectories)
  233. {
  234. DirectoryEntry* existingEntry = nullptr;
  235. UINT32 idx = 0;
  236. for(auto& child : currentDir->mChildren)
  237. {
  238. if(child->type == LibraryEntryType::Directory && child->path == dirPath)
  239. {
  240. existingEntries[idx] = true;
  241. existingEntry = static_cast<DirectoryEntry*>(child.get());
  242. break;
  243. }
  244. idx++;
  245. }
  246. if(existingEntry == nullptr)
  247. addDirectoryInternal(currentDir, dirPath);
  248. }
  249. {
  250. for(UINT32 i = 0; i < (UINT32)existingEntries.size(); i++)
  251. {
  252. if(existingEntries[i])
  253. continue;
  254. toDelete.push_back(currentDir->mChildren[i]);
  255. }
  256. for(auto& child : toDelete)
  257. {
  258. if(child->type == LibraryEntryType::Directory)
  259. deleteDirectoryInternal(static_pointer_cast<DirectoryEntry>(child));
  260. else if(child->type == LibraryEntryType::File)
  261. deleteResourceInternal(static_pointer_cast<FileEntry>(child));
  262. }
  263. toDelete.clear();
  264. }
  265. for(auto& child : currentDir->mChildren)
  266. {
  267. if(child->type == LibraryEntryType::Directory)
  268. todo.push(static_cast<DirectoryEntry*>(child.get()));
  269. }
  270. }
  271. }
  272. }
  273. return resourcesToImport;
  274. }
  275. USPtr<ProjectLibrary::FileEntry> ProjectLibrary::addResourceInternal(DirectoryEntry* parent, const Path& filePath,
  276. const SPtr<ImportOptions>& importOptions, bool forceReimport, bool synchronous)
  277. {
  278. USPtr<FileEntry> newResource = bs_ushared_ptr_new<FileEntry>(filePath, filePath.getTail(), parent);
  279. parent->mChildren.push_back(newResource);
  280. reimportResourceInternal(newResource.get(), importOptions, forceReimport, false, synchronous);
  281. onEntryAdded(newResource->path);
  282. return newResource;
  283. }
  284. USPtr<ProjectLibrary::DirectoryEntry> ProjectLibrary::addDirectoryInternal(DirectoryEntry* parent, const Path& dirPath)
  285. {
  286. USPtr<DirectoryEntry> newEntry = bs_ushared_ptr_new<DirectoryEntry>(dirPath, dirPath.getTail(), parent);
  287. parent->mChildren.push_back(newEntry);
  288. onEntryAdded(newEntry->path);
  289. return newEntry;
  290. }
  291. void ProjectLibrary::deleteResourceInternal(USPtr<FileEntry> resource)
  292. {
  293. if(resource->meta != nullptr)
  294. {
  295. auto& resourceMetas = resource->meta->getResourceMetaData();
  296. for(auto& entry : resourceMetas)
  297. {
  298. const UUID& uuid = entry->getUUID();
  299. Path path;
  300. if (mResourceManifest->uuidToFilePath(uuid, path))
  301. {
  302. if (FileSystem::isFile(path))
  303. FileSystem::remove(path);
  304. mResourceManifest->unregisterResource(uuid);
  305. }
  306. mUUIDToPath.erase(uuid);
  307. }
  308. }
  309. Path metaPath = getMetaPath(resource->path);
  310. if (FileSystem::isFile(metaPath))
  311. FileSystem::remove(metaPath);
  312. DirectoryEntry* parent = resource->parent;
  313. auto findIter = std::find_if(parent->mChildren.begin(), parent->mChildren.end(),
  314. [&] (const USPtr<LibraryEntry>& entry) { return entry == resource; });
  315. parent->mChildren.erase(findIter);
  316. Path originalPath = resource->path;
  317. onEntryRemoved(originalPath);
  318. const auto iterQueuedImport = mQueuedImports.find(resource.get());
  319. if(iterQueuedImport != mQueuedImports.end())
  320. iterQueuedImport->second->canceled = true;
  321. removeDependencies(resource.get());
  322. *resource = FileEntry();
  323. reimportDependants(originalPath);
  324. }
  325. void ProjectLibrary::deleteDirectoryInternal(USPtr<DirectoryEntry> directory)
  326. {
  327. if(directory == mRootEntry)
  328. mRootEntry = nullptr;
  329. Vector<USPtr<LibraryEntry>> childrenToDestroy = directory->mChildren;
  330. for(auto& child : childrenToDestroy)
  331. {
  332. if(child->type == LibraryEntryType::Directory)
  333. deleteDirectoryInternal(static_pointer_cast<DirectoryEntry>(child));
  334. else
  335. deleteResourceInternal(static_pointer_cast<FileEntry>(child));
  336. }
  337. DirectoryEntry* parent = directory->parent;
  338. if(parent != nullptr)
  339. {
  340. auto findIter = std::find_if(parent->mChildren.begin(), parent->mChildren.end(),
  341. [&] (const USPtr<LibraryEntry>& entry) { return entry == directory; });
  342. parent->mChildren.erase(findIter);
  343. }
  344. onEntryRemoved(directory->path);
  345. *directory = DirectoryEntry();
  346. }
  347. bool ProjectLibrary::reimportResourceInternal(FileEntry* fileEntry, const SPtr<ImportOptions>& importOptions,
  348. bool forceReimport, bool pruneResourceMetas, bool synchronous)
  349. {
  350. Path metaPath = fileEntry->path;
  351. metaPath.setFilename(metaPath.getFilename() + ".meta");
  352. // If the file doesn't have meta-data, attempt to read it from a meta-file, if one exists. This can only happen
  353. // if library data is obsolete (e.g. when adding files from another copy of the project)
  354. if(fileEntry->meta == nullptr)
  355. {
  356. if(FileSystem::isFile(metaPath))
  357. {
  358. FileDecoder fs(metaPath);
  359. SPtr<IReflectable> loadedMeta = fs.decode();
  360. if(loadedMeta != nullptr && loadedMeta->isDerivedFrom(ProjectFileMeta::getRTTIStatic()))
  361. {
  362. const SPtr<ProjectFileMeta>& fileMeta = std::static_pointer_cast<ProjectFileMeta>(loadedMeta);
  363. fileEntry->meta = fileMeta;
  364. auto& resourceMetas = fileEntry->meta->getResourceMetaData();
  365. if (!resourceMetas.empty())
  366. {
  367. mUUIDToPath[resourceMetas[0]->getUUID()] = fileEntry->path;
  368. for (UINT32 i = 1; i < (UINT32)resourceMetas.size(); i++)
  369. {
  370. const SPtr<ProjectResourceMeta>& entry = resourceMetas[i];
  371. mUUIDToPath[entry->getUUID()] = fileEntry->path + entry->getUniqueName();
  372. }
  373. }
  374. }
  375. }
  376. }
  377. if (!isUpToDate(fileEntry) || forceReimport)
  378. {
  379. // Note: If resource is native we just copy it to the internal folder. We could avoid the copy and
  380. // load the resource directly from the Resources folder but that requires complicating library code.
  381. const bool isNativeResource = isNative(fileEntry->path);
  382. SPtr<ImportOptions> curImportOptions = nullptr;
  383. if (importOptions == nullptr && !isNativeResource)
  384. {
  385. if (fileEntry->meta != nullptr)
  386. curImportOptions = fileEntry->meta->getImportOptions();
  387. else
  388. curImportOptions = Importer::instance().createImportOptions(fileEntry->path);
  389. }
  390. else
  391. curImportOptions = importOptions;
  392. SPtr<QueuedImport> queuedImport = bs_shared_ptr_new<QueuedImport>();
  393. queuedImport->filePath = fileEntry->path;
  394. queuedImport->importOptions = curImportOptions;
  395. queuedImport->pruneMetas = pruneResourceMetas;
  396. queuedImport->native = isNativeResource;
  397. queuedImport->timestamp = std::time(nullptr);
  398. // If import is already queued for this file make the tasks dependant so they don't execute at the same time,
  399. // and so they execute in the proper order
  400. SPtr<Task> dependency;
  401. const auto iterFind = mQueuedImports.find(fileEntry);
  402. if (iterFind != mQueuedImports.end())
  403. {
  404. dependency = iterFind->second->importTask;
  405. // Need this reference just so the dependency is kept alive, otherwise it goes out of scope when we
  406. // remove or overwrite it from mQueuedImports map
  407. queuedImport->dependsOn = iterFind->second;
  408. // Note: We should cancel the task here so it doesn't run unnecessarily. But if the task is already
  409. // running it shouldn't be canceled as dependencies still need to wait on it (since cancelling a
  410. // running task doesn't actually stop it). Yet there is currently no good wait to check if task
  411. // is currently running.
  412. // Dependency being imported async but we want the current resource right away. Wait until dependency is
  413. // done otherwise when dependency finishes it will overwrite whatever we write now.
  414. if(synchronous && dependency)
  415. {
  416. if (finishQueuedImport(fileEntry, *iterFind->second, true))
  417. mQueuedImports.erase(iterFind);
  418. }
  419. }
  420. // Needs to be pass a weak pointer to worker methods since internally it holds a reference to the task itself,
  421. // and we can't have the task closure holding a reference back, otherwise it leaks
  422. std::weak_ptr<QueuedImport> queuedImportWeak = queuedImport;
  423. if(!isNativeResource)
  424. {
  425. // Find UUIDs for any existing sub-resources
  426. if (fileEntry->meta != nullptr)
  427. {
  428. const Vector<SPtr<ProjectResourceMeta>>& resourceMetas = fileEntry->meta->getAllResourceMetaData();
  429. for (auto& entry : resourceMetas)
  430. queuedImport->resources.emplace_back(entry->getUniqueName(), nullptr, entry->getUUID());
  431. }
  432. // Perform import, register the resources and their UUID in the QueuedImport structure and save the
  433. // resource on disk
  434. const auto importAsync = [queuedImportWeak, &projectFolder = mProjectFolder, &mutex = mQueuedImportMutex]()
  435. {
  436. SPtr<QueuedImport> queuedImport = queuedImportWeak.lock();
  437. Vector<SubResourceRaw> importedResources = gImporter()._importAll(queuedImport->filePath,
  438. queuedImport->importOptions);
  439. if (!importedResources.empty())
  440. {
  441. Path outputPath = projectFolder;
  442. outputPath.append(INTERNAL_TEMP_DIR);
  443. if (!FileSystem::isDirectory(outputPath))
  444. FileSystem::createDir(outputPath);
  445. for (auto& entry : importedResources)
  446. {
  447. String subresourceName = entry.name;
  448. Path::stripInvalid(subresourceName);
  449. UUID uuid;
  450. {
  451. // Any access to queuedImport->resources must be locked
  452. Lock lock(mutex);
  453. auto iterFind = std::find_if(queuedImport->resources.begin(), queuedImport->resources.end(),
  454. [&subresourceName](const QueuedImportResource& importResource)
  455. {
  456. return importResource.name == subresourceName;
  457. });
  458. if (iterFind != queuedImport->resources.end())
  459. iterFind->resource = entry.value;
  460. else
  461. {
  462. queuedImport->resources.push_back(QueuedImportResource(entry.name, entry.value,
  463. UUID::EMPTY));
  464. iterFind = queuedImport->resources.end() - 1;
  465. }
  466. if (iterFind->uuid.empty())
  467. iterFind->uuid = UUIDGenerator::generateRandom();
  468. uuid = iterFind->uuid;
  469. }
  470. const String uuidStr = uuid.toString();
  471. outputPath.setFilename(uuidStr + ".asset");
  472. gResources()._save(entry.value, outputPath, true);
  473. }
  474. }
  475. };
  476. if(!synchronous)
  477. {
  478. queuedImport->importTask = Task::create("ProjectLibraryImport", importAsync, TaskPriority::Normal,
  479. dependency);
  480. }
  481. else
  482. importAsync();
  483. }
  484. else
  485. {
  486. // If meta exists make sure it is registered in the manifest before load, otherwise it will get assigned a new UUID.
  487. // This can happen if library isn't properly saved before exiting the application.
  488. if (fileEntry->meta != nullptr)
  489. {
  490. auto& resourceMetas = fileEntry->meta->getResourceMetaData();
  491. mResourceManifest->registerResource(resourceMetas[0]->getUUID(), fileEntry->path);
  492. }
  493. const auto importAsync = [queuedImportWeak, &projectFolder = mProjectFolder, &mutex = mQueuedImportMutex]()
  494. {
  495. // Don't load dependencies because we don't need them, but also because they might not be in the
  496. // manifest which would screw up their UUIDs.
  497. SPtr<QueuedImport> queuedImport = queuedImportWeak.lock();
  498. HResource resource = gResources().load(queuedImport->filePath, ResourceLoadFlag::KeepSourceData);
  499. if (resource)
  500. {
  501. Path outputPath = projectFolder;
  502. outputPath.append(INTERNAL_TEMP_DIR);
  503. if (!FileSystem::isDirectory(outputPath))
  504. FileSystem::createDir(outputPath);
  505. {
  506. // Any access to queuedImport->resources must be locked
  507. Lock lock(mutex);
  508. queuedImport->resources.push_back(QueuedImportResource("primary", resource));
  509. }
  510. const String uuidStr = resource.getUUID().toString();
  511. outputPath.setFilename(uuidStr + ".asset");
  512. gResources()._save(resource.getInternalPtr(), outputPath, true);
  513. }
  514. };
  515. if(!synchronous)
  516. {
  517. queuedImport->importTask = Task::create("ProjectLibraryImport", importAsync, TaskPriority::Normal,
  518. dependency);
  519. }
  520. else
  521. importAsync();
  522. }
  523. if(!synchronous)
  524. {
  525. TaskScheduler::instance().addTask(queuedImport->importTask);
  526. mQueuedImports[fileEntry] = queuedImport;
  527. }
  528. if(synchronous)
  529. finishQueuedImport(fileEntry, *queuedImport, true);
  530. return true;
  531. }
  532. return false;
  533. }
  534. bool ProjectLibrary::finishQueuedImport(FileEntry* fileEntry, const QueuedImport& import, bool wait)
  535. {
  536. if (import.importTask != nullptr && !import.importTask->isComplete())
  537. {
  538. if (wait)
  539. import.importTask->wait();
  540. else
  541. return false;
  542. }
  543. // We wait on canceled task to finish and then just discard the results because any dependant tasks need to be
  544. // aware this tasks exists, so we can't just remove it straight away.
  545. if (import.canceled)
  546. return true;
  547. Path metaPath = fileEntry->path;
  548. metaPath.setFilename(metaPath.getFilename() + ".meta");
  549. SPtr<SerializedObject> orgMetaData;
  550. Vector<SPtr<ProjectResourceMeta>> existingMetas;
  551. if (fileEntry->meta == nullptr) // Build a brand new meta-file
  552. fileEntry->meta = ProjectFileMeta::create(import.importOptions);
  553. else // Existing meta-file, which needs to be updated
  554. {
  555. orgMetaData = SerializedObject::create(*fileEntry->meta);
  556. // Remove existing dependencies (they will be re-added later)
  557. removeDependencies(fileEntry);
  558. existingMetas = fileEntry->meta->getAllResourceMetaData();
  559. fileEntry->meta->clearResourceMetaData();
  560. fileEntry->meta->mImportOptions = import.importOptions;
  561. }
  562. fileEntry->lastUpdateTime = import.timestamp;
  563. Path internalResourcesPath = mProjectFolder;
  564. internalResourcesPath.append(INTERNAL_RESOURCES_DIR);
  565. if (!FileSystem::isDirectory(internalResourcesPath))
  566. FileSystem::createDir(internalResourcesPath);
  567. Path tempResourcesPath = mProjectFolder;
  568. tempResourcesPath.append(INTERNAL_TEMP_DIR);
  569. // See which sub-resource metas need to be updated, removed or added based on the new resource set
  570. bool isFirst = true;
  571. for (const auto& entry : import.resources)
  572. {
  573. // Entries with no resources are sub-resources that used to exist in this file, but haven't been imported
  574. // this time
  575. if (!entry.resource)
  576. continue;
  577. // Copy the resource file from the temporary directory
  578. const String uuidStr = entry.uuid.toString();
  579. tempResourcesPath.setFilename(uuidStr + ".asset");
  580. internalResourcesPath.setFilename(uuidStr + ".asset");
  581. FileSystem::move(tempResourcesPath, internalResourcesPath);
  582. String name = entry.name;
  583. Path::stripInvalid(name);
  584. const ProjectResourceIcons icons = generatePreviewIcons(*entry.resource);
  585. bool foundMeta = false;
  586. for (auto iterMeta = existingMetas.begin(); iterMeta != existingMetas.end();)
  587. {
  588. const SPtr<ProjectResourceMeta>& metaEntry = *iterMeta;
  589. if (name == metaEntry->getUniqueName())
  590. {
  591. if(!foundMeta)
  592. {
  593. // Make sure the UUID we used for saving the resource matches the current one (should always
  594. // be true unless the meta-data somehow changes while the async import is happening)
  595. assert(entry.uuid == metaEntry->getUUID());
  596. HResource importedResource = gResources()._getResourceHandle(metaEntry->getUUID());
  597. gResources().update(importedResource, entry.resource);
  598. metaEntry->setPreviewIcons(icons);
  599. fileEntry->meta->add(metaEntry);
  600. }
  601. foundMeta = true;
  602. iterMeta = existingMetas.erase(iterMeta);
  603. }
  604. else
  605. ++iterMeta;
  606. }
  607. if (!foundMeta)
  608. {
  609. HResource importedResource;
  610. // Native resources are always expected to have a handle since Resources::load was called during
  611. // the 'import' step
  612. if (import.native)
  613. importedResource = entry.handle;
  614. else
  615. importedResource = gResources()._createResourceHandle(entry.resource, entry.uuid);
  616. SPtr<ResourceMetaData> subMeta = entry.resource->getMetaData();
  617. const UINT32 typeId = entry.resource->getTypeId();
  618. const UUID& UUID = importedResource.getUUID();
  619. SPtr<ProjectResourceMeta> resMeta = ProjectResourceMeta::create(name, UUID, typeId,
  620. icons, subMeta);
  621. fileEntry->meta->add(resMeta);
  622. }
  623. // Update UUID to path mapping
  624. if (isFirst)
  625. mUUIDToPath[entry.uuid] = fileEntry->path;
  626. else
  627. mUUIDToPath[entry.uuid] = fileEntry->path + name;
  628. isFirst = false;
  629. // Register path in manifest
  630. mResourceManifest->registerResource(entry.uuid, internalResourcesPath);
  631. }
  632. // Keep resource metas that we are not currently using, in case they get restored so their references
  633. // don't get broken
  634. if (!import.pruneMetas)
  635. {
  636. for (auto& metaEntry : existingMetas)
  637. fileEntry->meta->addInactive(metaEntry);
  638. }
  639. // Note: Ideally we replace this with a specialized BinaryCompare method
  640. bool metaModified = true;
  641. if(orgMetaData != nullptr)
  642. {
  643. SPtr<SerializedObject> newMetaData = SerializedObject::create(*fileEntry->meta);
  644. BinaryDiff diffHandler;
  645. SPtr<SerializedObject> diff = diffHandler.generateDiff(orgMetaData, newMetaData);
  646. metaModified = diff != nullptr;
  647. }
  648. if(metaModified)
  649. {
  650. // Save the meta file
  651. FileEncoder fs(metaPath);
  652. fs.encode(fileEntry->meta.get());
  653. }
  654. // Register any dependencies this resource depends on
  655. addDependencies(fileEntry);
  656. // Notify the outside world import is doen
  657. onEntryImported(fileEntry->path);
  658. // Queue any resources dependant on this one for import
  659. reimportDependants(fileEntry->path);
  660. return true;
  661. }
  662. void ProjectLibrary::_finishQueuedImports(bool wait)
  663. {
  664. for(auto iter = mQueuedImports.begin(); iter != mQueuedImports.end();)
  665. {
  666. if(finishQueuedImport(iter->first, *iter->second, wait))
  667. iter = mQueuedImports.erase(iter);
  668. else
  669. ++iter;
  670. }
  671. }
  672. bool ProjectLibrary::isUpToDate(FileEntry* resource) const
  673. {
  674. SPtr<QueuedImport> queuedImport;
  675. if(resource->meta == nullptr)
  676. {
  677. // Allow no meta if import in progress
  678. const auto iterFind = mQueuedImports.find(resource);
  679. if(iterFind == mQueuedImports.end())
  680. return false;
  681. queuedImport = iterFind->second;
  682. }
  683. else
  684. {
  685. auto& resourceMetas = resource->meta->getResourceMetaData();
  686. for (auto& resMeta : resourceMetas)
  687. {
  688. Path internalPath;
  689. if (!mResourceManifest->uuidToFilePath(resMeta->getUUID(), internalPath))
  690. return false;
  691. if (!FileSystem::isFile(internalPath))
  692. return false;
  693. }
  694. }
  695. // Note: We're keeping separate update times for queued imports. This allows the import to be cancelled (either by
  696. // user or by app crashing), without updating the actual update time. This way the systems knows to try to reimport
  697. // the resource on the next check. At the same time we don't want our checkForModifications function to keep
  698. // trying to reimport a resource if it's already been queued for import.
  699. const std::time_t lastUpdateTime = queuedImport ? queuedImport->timestamp : resource->lastUpdateTime;
  700. const std::time_t lastModifiedTime = FileSystem::getLastModifiedTime(resource->path);
  701. return lastModifiedTime <= lastUpdateTime;
  702. }
  703. Vector<USPtr<ProjectLibrary::LibraryEntry>> ProjectLibrary::search(const String& pattern)
  704. {
  705. return search(pattern, {});
  706. }
  707. Vector<USPtr<ProjectLibrary::LibraryEntry>> ProjectLibrary::search(const String& pattern, const Vector<UINT32>& typeIds)
  708. {
  709. Vector<USPtr<LibraryEntry>> foundEntries;
  710. std::regex escape("[.^$|()\\[\\]{}*+?\\\\]");
  711. String replace("\\\\&");
  712. String escapedPattern = std::regex_replace(pattern, escape, replace, std::regex_constants::match_default | std::regex_constants::format_sed);
  713. // For some reason MSVC stdlib implementation requires a different pattern than stdlib one
  714. #if BS_PLATFORM == BS_PLATFORM_WIN32
  715. std::regex wildcard("\\\\\\*");
  716. #else
  717. std::regex wildcard("\\\\\\\\\\*");
  718. #endif
  719. String wildcardReplace(".*");
  720. String searchPattern = std::regex_replace(escapedPattern, wildcard, ".*");
  721. std::regex searchRegex(searchPattern, std::regex_constants::ECMAScript | std::regex_constants::icase);
  722. Stack<DirectoryEntry*> todo;
  723. todo.push(mRootEntry.get());
  724. while (!todo.empty())
  725. {
  726. DirectoryEntry* dirEntry = todo.top();
  727. todo.pop();
  728. for (auto& child : dirEntry->mChildren)
  729. {
  730. if (std::regex_match(child->elementName, searchRegex))
  731. {
  732. if (typeIds.empty())
  733. foundEntries.push_back(child);
  734. else
  735. {
  736. if (child->type == LibraryEntryType::File)
  737. {
  738. FileEntry* childFileEntry = static_cast<FileEntry*>(child.get());
  739. if (childFileEntry->meta != nullptr)
  740. {
  741. auto& resourceMetas = childFileEntry->meta->getResourceMetaData();
  742. for (auto& typeId : typeIds)
  743. {
  744. bool found = false;
  745. for (auto& resMeta : resourceMetas)
  746. {
  747. if (resMeta->getTypeID() == typeId)
  748. {
  749. foundEntries.push_back(child);
  750. found = true;
  751. break;
  752. }
  753. }
  754. if (found)
  755. break;
  756. }
  757. }
  758. }
  759. }
  760. }
  761. if (child->type == LibraryEntryType::Directory)
  762. {
  763. DirectoryEntry* childDirEntry = static_cast<DirectoryEntry*>(child.get());
  764. todo.push(childDirEntry);
  765. }
  766. }
  767. }
  768. std::sort(foundEntries.begin(), foundEntries.end(),
  769. [&](const USPtr<LibraryEntry>& a, const USPtr<LibraryEntry>& b)
  770. {
  771. return a->elementName.compare(b->elementName) < 0;
  772. });
  773. return foundEntries;
  774. }
  775. USPtr<ProjectLibrary::LibraryEntry> ProjectLibrary::findEntry(const Path& path) const
  776. {
  777. Path relPath;
  778. const Path* searchPath;
  779. if (path.isAbsolute())
  780. {
  781. if (!mResourcesFolder.includes(path))
  782. return nullptr;
  783. relPath = path.getRelative(mRootEntry->path);
  784. searchPath = &relPath;
  785. }
  786. else
  787. searchPath = &path;
  788. BS_ASSERT(mRootEntry->path == mResourcesFolder);
  789. UINT32 numElems = searchPath->getNumDirectories() + (searchPath->isFile() ? 1 : 0);
  790. UINT32 idx = 0;
  791. USPtr<LibraryEntry> rootLibEntry = mRootEntry;
  792. USPtr<LibraryEntry>* current = &rootLibEntry;
  793. while (current != nullptr)
  794. {
  795. if (idx == numElems)
  796. return *current;
  797. const String& curElem =
  798. (searchPath->isFile() && idx == (numElems - 1)) ? searchPath->getFilename() : (*searchPath)[idx];
  799. if ((*current)->type == LibraryEntryType::Directory)
  800. {
  801. DirectoryEntry* dirEntry = static_cast<DirectoryEntry*>(current->get());
  802. size_t curElemHash = bs_hash(UTF8::toLower(curElem));
  803. current = nullptr;
  804. for (auto& child : dirEntry->mChildren)
  805. {
  806. if(curElemHash != child->elementNameHash)
  807. continue;
  808. if (Path::comparePathElem(curElem, child->elementName))
  809. {
  810. idx++;
  811. current = &child;
  812. break;
  813. }
  814. }
  815. }
  816. else // Found file
  817. {
  818. // If this is next to last element, next entry is assumed to be a sub-resource name, which we ignore
  819. if (idx == (numElems - 1))
  820. return *current;
  821. else
  822. break; // Not a valid path
  823. }
  824. }
  825. return nullptr;
  826. }
  827. bool ProjectLibrary::isSubresource(const Path& path) const
  828. {
  829. UINT32 numElems = path.getNumDirectories() + (path.isFile() ? 1 : 0);
  830. if (numElems <= 1)
  831. return false;
  832. Path filePath = path;
  833. filePath.makeParent();
  834. LibraryEntry* entry = findEntry(filePath).get();
  835. return entry != nullptr && entry->type == LibraryEntryType::File;
  836. }
  837. SPtr<ProjectResourceMeta> ProjectLibrary::findResourceMeta(const Path& path) const
  838. {
  839. UINT32 numElems = path.getNumDirectories() + (path.isFile() ? 1 : 0);
  840. // Check if it is a subresource path
  841. if(numElems > 1)
  842. {
  843. Path filePath = path;
  844. filePath.makeParent();
  845. LibraryEntry* entry = findEntry(filePath).get();
  846. if (entry == nullptr)
  847. return nullptr;
  848. // Entry is a subresource
  849. if (entry->type == LibraryEntryType::File)
  850. {
  851. FileEntry* fileEntry = static_cast<FileEntry*>(entry);
  852. if (fileEntry->meta == nullptr)
  853. return nullptr;
  854. auto& resourceMetas = fileEntry->meta->getResourceMetaData();
  855. for(auto& resMeta : resourceMetas)
  856. {
  857. if (resMeta->getUniqueName() == path.getTail())
  858. return resMeta;
  859. }
  860. // Found the file but no subresource or meta information
  861. return nullptr;
  862. }
  863. else // Entry not a subresource
  864. {
  865. DirectoryEntry* dirEntry = static_cast<DirectoryEntry*>(entry);
  866. for (auto& child : dirEntry->mChildren)
  867. {
  868. if (Path::comparePathElem(path.getTail(), child->elementName))
  869. {
  870. if (child->type == LibraryEntryType::File)
  871. {
  872. FileEntry* fileEntry = static_cast<FileEntry*>(child.get());
  873. if (fileEntry->meta == nullptr)
  874. return nullptr;
  875. return fileEntry->meta->getResourceMetaData()[0];
  876. }
  877. }
  878. }
  879. return nullptr;
  880. }
  881. }
  882. // Not a subresource path, load directly
  883. {
  884. LibraryEntry* entry = findEntry(path).get();
  885. if (entry == nullptr || entry->type == LibraryEntryType::Directory)
  886. return nullptr;
  887. FileEntry* fileEntry = static_cast<FileEntry*>(entry);
  888. if (fileEntry->meta == nullptr)
  889. return nullptr;
  890. return fileEntry->meta->getResourceMetaData()[0];
  891. }
  892. }
  893. Path ProjectLibrary::uuidToPath(const UUID& uuid) const
  894. {
  895. auto iterFind = mUUIDToPath.find(uuid);
  896. if (iterFind != mUUIDToPath.end())
  897. return iterFind->second;
  898. return Path::BLANK;
  899. }
  900. void ProjectLibrary::createEntry(const HResource& resource, const Path& path)
  901. {
  902. if (resource == nullptr)
  903. return;
  904. Path assetPath = path;
  905. if (path.isAbsolute())
  906. {
  907. if (!getResourcesFolder().includes(path))
  908. return;
  909. assetPath = path.getRelative(getResourcesFolder());
  910. }
  911. deleteEntry(assetPath);
  912. resource->setName(path.getFilename(false));
  913. Path absPath = assetPath.getAbsolute(getResourcesFolder());
  914. Resources::instance().save(resource, absPath, false);
  915. Path parentDirPath = absPath.getParent();
  916. USPtr<LibraryEntry> parentEntry = findEntry(parentDirPath);
  917. // Register parent hierarchy if not found
  918. DirectoryEntry* entryParent = nullptr;
  919. if (parentEntry == nullptr)
  920. createInternalParentHierarchy(absPath, nullptr, &entryParent);
  921. else
  922. entryParent = static_cast<DirectoryEntry*>(parentEntry.get());
  923. addResourceInternal(entryParent, absPath, nullptr, true, true);
  924. }
  925. void ProjectLibrary::saveEntry(const HResource& resource)
  926. {
  927. if (resource == nullptr)
  928. return;
  929. Path filePath = uuidToPath(resource.getUUID());
  930. if(filePath.isEmpty())
  931. {
  932. BS_LOG(Warning, Editor, "Trying to save a resource that hasn't been registered with the project library. "
  933. "Call ProjectLibrary::create first.");
  934. return;
  935. }
  936. filePath.makeAbsolute(getResourcesFolder());
  937. Resources::instance().save(resource, filePath, true);
  938. LibraryEntry* fileEntry = findEntry(filePath).get();
  939. if(fileEntry)
  940. reimportResourceInternal(static_cast<FileEntry*>(fileEntry), nullptr, true, false, true);
  941. }
  942. void ProjectLibrary::createFolderEntry(const Path& path)
  943. {
  944. Path fullPath = path;
  945. if (fullPath.isAbsolute())
  946. {
  947. if (!mResourcesFolder.includes(fullPath))
  948. return;
  949. }
  950. else
  951. fullPath.makeAbsolute(mResourcesFolder);
  952. if (FileSystem::isDirectory(fullPath))
  953. return; // Already exists
  954. FileSystem::createDir(fullPath);
  955. Path parentPath = fullPath.getParent();
  956. DirectoryEntry* newEntryParent = nullptr;
  957. USPtr<LibraryEntry> newEntryParentLib = findEntry(parentPath);
  958. if (newEntryParentLib != nullptr)
  959. {
  960. assert(newEntryParentLib->type == LibraryEntryType::Directory);
  961. newEntryParent = static_cast<DirectoryEntry*>(newEntryParentLib.get());
  962. }
  963. DirectoryEntry* newHierarchyParent = nullptr;
  964. if (newEntryParent == nullptr) // New path parent doesn't exist, so we need to create the hierarchy
  965. createInternalParentHierarchy(fullPath, &newHierarchyParent, &newEntryParent);
  966. addDirectoryInternal(newEntryParent, fullPath);
  967. }
  968. void ProjectLibrary::moveEntry(const Path& oldPath, const Path& newPath, bool overwrite)
  969. {
  970. Path oldFullPath = oldPath;
  971. if (!oldFullPath.isAbsolute())
  972. oldFullPath.makeAbsolute(mResourcesFolder);
  973. Path newFullPath = newPath;
  974. if (!newFullPath.isAbsolute())
  975. newFullPath.makeAbsolute(mResourcesFolder);
  976. Path parentPath = newFullPath.getParent();
  977. if (!FileSystem::isDirectory(parentPath))
  978. {
  979. BS_LOG(Warning, Editor, "Move operation failed. Destination directory \"{0}\" doesn't exist.", parentPath);
  980. return;
  981. }
  982. if(FileSystem::isFile(oldFullPath) || FileSystem::isDirectory(oldFullPath))
  983. FileSystem::move(oldFullPath, newFullPath, overwrite);
  984. Path oldMetaPath = getMetaPath(oldFullPath);
  985. Path newMetaPath = getMetaPath(newFullPath);
  986. USPtr<LibraryEntry> oldEntry = findEntry(oldFullPath);
  987. if(oldEntry != nullptr) // Moving from the Resources folder
  988. {
  989. // Moved outside of Resources, delete entry & meta file
  990. if (!mResourcesFolder.includes(newFullPath))
  991. {
  992. if(oldEntry->type == LibraryEntryType::File)
  993. deleteResourceInternal(static_pointer_cast<FileEntry>(oldEntry));
  994. else if(oldEntry->type == LibraryEntryType::Directory)
  995. deleteDirectoryInternal(static_pointer_cast<DirectoryEntry>(oldEntry));
  996. }
  997. else // Just moving internally
  998. {
  999. onEntryRemoved(oldEntry->path);
  1000. USPtr<FileEntry> fileEntry = nullptr;
  1001. if (oldEntry->type == LibraryEntryType::File)
  1002. {
  1003. fileEntry = static_pointer_cast<FileEntry>(oldEntry);
  1004. removeDependencies(fileEntry.get());
  1005. // Update uuid <-> path mapping
  1006. if(fileEntry->meta != nullptr)
  1007. {
  1008. auto& resourceMetas = fileEntry->meta->getResourceMetaData();
  1009. if (!resourceMetas.empty())
  1010. {
  1011. mUUIDToPath[resourceMetas[0]->getUUID()] = newFullPath;
  1012. for (UINT32 i = 1; i < (UINT32)resourceMetas.size(); i++)
  1013. {
  1014. SPtr<ProjectResourceMeta> resMeta = resourceMetas[i];
  1015. const UUID& UUID = resMeta->getUUID();
  1016. mUUIDToPath[UUID] = newFullPath + resMeta->getUniqueName();
  1017. }
  1018. }
  1019. }
  1020. }
  1021. if(FileSystem::isFile(oldMetaPath))
  1022. FileSystem::move(oldMetaPath, newMetaPath);
  1023. DirectoryEntry* parent = oldEntry->parent;
  1024. auto findIter = std::find(parent->mChildren.begin(), parent->mChildren.end(), oldEntry);
  1025. if(findIter != parent->mChildren.end())
  1026. parent->mChildren.erase(findIter);
  1027. Path parentPath = newFullPath.getParent();
  1028. DirectoryEntry* newEntryParent = nullptr;
  1029. USPtr<LibraryEntry> newEntryParentLib = findEntry(parentPath);
  1030. if(newEntryParentLib != nullptr)
  1031. {
  1032. assert(newEntryParentLib->type == LibraryEntryType::Directory);
  1033. newEntryParent = static_cast<DirectoryEntry*>(newEntryParentLib.get());
  1034. }
  1035. DirectoryEntry* newHierarchyParent = nullptr;
  1036. if(newEntryParent == nullptr) // New path parent doesn't exist, so we need to create the hierarchy
  1037. createInternalParentHierarchy(newFullPath, &newHierarchyParent, &newEntryParent);
  1038. newEntryParent->mChildren.push_back(oldEntry);
  1039. oldEntry->parent = newEntryParent;
  1040. oldEntry->path = newFullPath;
  1041. oldEntry->elementName = newFullPath.getTail();
  1042. oldEntry->elementNameHash = bs_hash(UTF8::toLower(oldEntry->elementName));
  1043. if(oldEntry->type == LibraryEntryType::Directory) // Update child paths
  1044. {
  1045. Stack<LibraryEntry*> todo;
  1046. todo.push(oldEntry.get());
  1047. while(!todo.empty())
  1048. {
  1049. LibraryEntry* curEntry = todo.top();
  1050. todo.pop();
  1051. DirectoryEntry* curDirEntry = static_cast<DirectoryEntry*>(curEntry);
  1052. for(auto& child : curDirEntry->mChildren)
  1053. {
  1054. child->path = child->parent->path;
  1055. child->path.append(child->elementName);
  1056. if(child->type == LibraryEntryType::Directory)
  1057. todo.push(child.get());
  1058. }
  1059. }
  1060. }
  1061. onEntryAdded(oldEntry->path);
  1062. if (fileEntry != nullptr)
  1063. {
  1064. reimportDependants(oldFullPath);
  1065. reimportDependants(newFullPath);
  1066. }
  1067. }
  1068. }
  1069. else // Moving from outside of the Resources folder (likely adding a new resource)
  1070. {
  1071. checkForModifications(newFullPath);
  1072. }
  1073. }
  1074. void ProjectLibrary::copyEntry(const Path& oldPath, const Path& newPath, bool overwrite)
  1075. {
  1076. Path oldFullPath = oldPath;
  1077. if (!oldFullPath.isAbsolute())
  1078. oldFullPath.makeAbsolute(mResourcesFolder);
  1079. Path newFullPath = newPath;
  1080. if (!newFullPath.isAbsolute())
  1081. newFullPath.makeAbsolute(mResourcesFolder);
  1082. if (!FileSystem::exists(oldFullPath))
  1083. return;
  1084. FileSystem::copy(oldFullPath, newFullPath, overwrite);
  1085. // Copying a file/folder outside of the Resources folder, no special handling needed
  1086. if (!mResourcesFolder.includes(newFullPath))
  1087. return;
  1088. Path parentPath = newFullPath.getParent();
  1089. DirectoryEntry* newEntryParent = nullptr;
  1090. LibraryEntry* newEntryParentLib = findEntry(parentPath).get();
  1091. if (newEntryParentLib != nullptr)
  1092. {
  1093. assert(newEntryParentLib->type == LibraryEntryType::Directory);
  1094. newEntryParent = static_cast<DirectoryEntry*>(newEntryParentLib);
  1095. }
  1096. // If the source is outside of Resources folder, just plain import the copy
  1097. LibraryEntry* oldEntry = findEntry(oldFullPath).get();
  1098. if (oldEntry == nullptr)
  1099. {
  1100. checkForModifications(newFullPath);
  1101. return;
  1102. }
  1103. // Both source and destination are within Resources folder, need to preserve import options on the copies
  1104. if (FileSystem::isFile(newFullPath))
  1105. {
  1106. assert(oldEntry->type == LibraryEntryType::File);
  1107. FileEntry* oldResEntry = static_cast<FileEntry*>(oldEntry);
  1108. SPtr<ImportOptions> importOptions;
  1109. if (oldResEntry->meta != nullptr)
  1110. importOptions = oldResEntry->meta->getImportOptions();
  1111. addResourceInternal(newEntryParent, newFullPath, importOptions, true);
  1112. }
  1113. else
  1114. {
  1115. assert(oldEntry->type == LibraryEntryType::File);
  1116. DirectoryEntry* oldDirEntry = static_cast<DirectoryEntry*>(oldEntry);
  1117. DirectoryEntry* newDirEntry = addDirectoryInternal(newEntryParent, newFullPath).get();
  1118. Stack<std::tuple<DirectoryEntry*, DirectoryEntry*>> todo;
  1119. todo.push(std::make_tuple(oldDirEntry, newDirEntry));
  1120. while (!todo.empty())
  1121. {
  1122. auto current = todo.top();
  1123. todo.pop();
  1124. DirectoryEntry* sourceDir = std::get<0>(current);
  1125. DirectoryEntry* destDir = std::get<1>(current);
  1126. for (auto& child : sourceDir->mChildren)
  1127. {
  1128. Path childDestPath = destDir->path;
  1129. childDestPath.append(child->path.getTail());
  1130. if (child->type == LibraryEntryType::File)
  1131. {
  1132. FileEntry* childResEntry = static_cast<FileEntry*>(child.get());
  1133. SPtr<ImportOptions> importOptions;
  1134. if (childResEntry->meta != nullptr)
  1135. importOptions = childResEntry->meta->getImportOptions();
  1136. addResourceInternal(destDir, childDestPath, importOptions, true);
  1137. }
  1138. else // Directory
  1139. {
  1140. DirectoryEntry* childSourceDirEntry = static_cast<DirectoryEntry*>(child.get());
  1141. DirectoryEntry* childDestDirEntry = addDirectoryInternal(destDir, childDestPath).get();
  1142. todo.push(std::make_tuple(childSourceDirEntry, childDestDirEntry));
  1143. }
  1144. }
  1145. }
  1146. }
  1147. }
  1148. void ProjectLibrary::deleteEntry(const Path& path)
  1149. {
  1150. Path fullPath = path;
  1151. if (!fullPath.isAbsolute())
  1152. fullPath.makeAbsolute(mResourcesFolder);
  1153. if(FileSystem::exists(fullPath))
  1154. FileSystem::remove(fullPath);
  1155. USPtr<LibraryEntry> entry = findEntry(fullPath);
  1156. if(entry != nullptr)
  1157. {
  1158. if(entry->type == LibraryEntryType::File)
  1159. deleteResourceInternal(static_pointer_cast<FileEntry>(entry));
  1160. else if(entry->type == LibraryEntryType::Directory)
  1161. deleteDirectoryInternal(static_pointer_cast<DirectoryEntry>(entry));
  1162. }
  1163. }
  1164. void ProjectLibrary::reimport(const Path& path, const SPtr<ImportOptions>& importOptions, bool forceReimport,
  1165. bool synchronous)
  1166. {
  1167. LibraryEntry* entry = findEntry(path).get();
  1168. if (entry != nullptr)
  1169. {
  1170. if (entry->type == LibraryEntryType::File)
  1171. {
  1172. FileEntry* resEntry = static_cast<FileEntry*>(entry);
  1173. reimportResourceInternal(resEntry, importOptions, forceReimport, synchronous);
  1174. }
  1175. }
  1176. }
  1177. float ProjectLibrary::getImportProgress(const Path& path) const
  1178. {
  1179. LibraryEntry* entry = findEntry(path).get();
  1180. if (entry == nullptr)
  1181. return 0.0f;
  1182. if(entry->type == LibraryEntryType::Directory)
  1183. return 1.0f;
  1184. // Note: Only supporting binary progress reporting for now
  1185. const auto iterFind = mQueuedImports.find(static_cast<FileEntry*>(entry));
  1186. return iterFind != mQueuedImports.end() ? 0.0f : 1.0f;
  1187. }
  1188. void ProjectLibrary::cancelImport()
  1189. {
  1190. for(auto& entry : mQueuedImports)
  1191. entry.second->canceled = true;
  1192. }
  1193. void ProjectLibrary::waitForQueuedImport(FileEntry* fileEntry)
  1194. {
  1195. const auto iterFind = mQueuedImports.find(fileEntry);
  1196. if (iterFind != mQueuedImports.end())
  1197. {
  1198. if (finishQueuedImport(fileEntry, *iterFind->second, true))
  1199. mQueuedImports.erase(iterFind);
  1200. }
  1201. }
  1202. void ProjectLibrary::setIncludeInBuild(const Path& path, bool include)
  1203. {
  1204. LibraryEntry* entry = findEntry(path).get();
  1205. if (entry == nullptr || entry->type == LibraryEntryType::Directory)
  1206. return;
  1207. auto fileEntry = static_cast<FileEntry*>(entry);
  1208. // Any queued imports will overwrite the meta file, so make sure they finish first
  1209. waitForQueuedImport(fileEntry);
  1210. if (fileEntry->meta == nullptr)
  1211. return;
  1212. fileEntry->meta->setIncludeInBuild(include);
  1213. Path metaPath = fileEntry->path;
  1214. metaPath.setFilename(metaPath.getFilename() + ".meta");
  1215. FileEncoder fs(metaPath);
  1216. fs.encode(fileEntry->meta.get());
  1217. }
  1218. void ProjectLibrary::setUserData(const Path& path, const SPtr<IReflectable>& userData)
  1219. {
  1220. LibraryEntry* entry = findEntry(path).get();
  1221. if (entry == nullptr || entry->type == LibraryEntryType::Directory)
  1222. return;
  1223. auto fileEntry = static_cast<FileEntry*>(entry);
  1224. // Any queued imports will overwrite the meta file, so make sure they finish first
  1225. waitForQueuedImport(fileEntry);
  1226. SPtr<ProjectResourceMeta> resMeta = findResourceMeta(path);
  1227. if (resMeta == nullptr)
  1228. return;
  1229. resMeta->mUserData = userData;
  1230. Path metaPath = fileEntry->path;
  1231. metaPath.setFilename(metaPath.getFilename() + ".meta");
  1232. FileEncoder fs(metaPath);
  1233. fs.encode(fileEntry->meta.get());
  1234. }
  1235. Vector<USPtr<ProjectLibrary::FileEntry>> ProjectLibrary::getResourcesForBuild() const
  1236. {
  1237. Vector<USPtr<FileEntry>> output;
  1238. Stack<DirectoryEntry*> todo;
  1239. todo.push(mRootEntry.get());
  1240. while (!todo.empty())
  1241. {
  1242. DirectoryEntry* directory = todo.top();
  1243. todo.pop();
  1244. for (auto& child : directory->mChildren)
  1245. {
  1246. if (child->type == LibraryEntryType::File)
  1247. {
  1248. FileEntry* resEntry = static_cast<FileEntry*>(child.get());
  1249. if (resEntry->meta != nullptr && resEntry->meta->getIncludeInBuild())
  1250. output.push_back(static_pointer_cast<FileEntry>(child));
  1251. }
  1252. else if (child->type == LibraryEntryType::Directory)
  1253. {
  1254. todo.push(static_cast<DirectoryEntry*>(child.get()));
  1255. }
  1256. }
  1257. }
  1258. return output;
  1259. }
  1260. HResource ProjectLibrary::load(const Path& path)
  1261. {
  1262. SPtr<ProjectResourceMeta> meta = findResourceMeta(path);
  1263. if (meta == nullptr)
  1264. return HResource();
  1265. ResourceLoadFlags loadFlags = ResourceLoadFlag::Default | ResourceLoadFlag::KeepSourceData;
  1266. const UUID& resUUID = meta->getUUID();
  1267. return gResources().loadFromUUID(resUUID, false, loadFlags);
  1268. }
  1269. void ProjectLibrary::createInternalParentHierarchy(const Path& fullPath, DirectoryEntry** newHierarchyRoot,
  1270. DirectoryEntry** newHierarchyLeaf)
  1271. {
  1272. Path parentPath = fullPath;
  1273. DirectoryEntry* newEntryParent = nullptr;
  1274. Stack<Path> parentPaths;
  1275. do
  1276. {
  1277. Path newParentPath = parentPath.getParent();
  1278. if(newParentPath == parentPath)
  1279. break;
  1280. LibraryEntry* newEntryParentLib = findEntry(newParentPath).get();
  1281. if(newEntryParentLib != nullptr)
  1282. {
  1283. assert(newEntryParentLib->type == LibraryEntryType::Directory);
  1284. newEntryParent = static_cast<DirectoryEntry*>(newEntryParentLib);
  1285. break;
  1286. }
  1287. parentPaths.push(newParentPath);
  1288. parentPath = newParentPath;
  1289. } while (true);
  1290. assert(newEntryParent != nullptr); // Must exist
  1291. if(newHierarchyRoot != nullptr)
  1292. *newHierarchyRoot = newEntryParent;
  1293. while(!parentPaths.empty())
  1294. {
  1295. Path curPath = parentPaths.top();
  1296. parentPaths.pop();
  1297. newEntryParent = addDirectoryInternal(newEntryParent, curPath).get();
  1298. }
  1299. if(newHierarchyLeaf != nullptr)
  1300. *newHierarchyLeaf = newEntryParent;
  1301. }
  1302. Path ProjectLibrary::getMetaPath(const Path& path) const
  1303. {
  1304. Path metaPath = path;
  1305. metaPath.setFilename(metaPath.getFilename() + ".meta");
  1306. return metaPath;
  1307. }
  1308. bool ProjectLibrary::isMeta(const Path& fullPath) const
  1309. {
  1310. return fullPath.getExtension() == ".meta";
  1311. }
  1312. bool ProjectLibrary::isNative(const Path& path) const
  1313. {
  1314. String extension = path.getExtension();
  1315. return extension == ".asset" || extension == ".prefab";
  1316. }
  1317. void ProjectLibrary::unloadLibrary()
  1318. {
  1319. if (!mIsLoaded)
  1320. return;
  1321. _finishQueuedImports(true);
  1322. mProjectFolder = Path::BLANK;
  1323. mResourcesFolder = Path::BLANK;
  1324. clearEntries();
  1325. mRootEntry = bs_ushared_ptr_new<DirectoryEntry>(mResourcesFolder, mResourcesFolder.getTail(), nullptr);
  1326. mDependencies.clear();
  1327. gResources().unregisterResourceManifest(mResourceManifest);
  1328. mResourceManifest = nullptr;
  1329. mIsLoaded = false;
  1330. }
  1331. void ProjectLibrary::makeEntriesRelative()
  1332. {
  1333. // Make all paths relative before saving
  1334. std::function<void(LibraryEntry*, const Path&)> makeRelative =
  1335. [&](LibraryEntry* entry, const Path& root)
  1336. {
  1337. entry->path.makeRelative(root);
  1338. if (entry->type == LibraryEntryType::Directory)
  1339. {
  1340. DirectoryEntry* dirEntry = static_cast<DirectoryEntry*>(entry);
  1341. for (auto& child : dirEntry->mChildren)
  1342. makeRelative(child.get(), root);
  1343. }
  1344. };
  1345. Path root = getResourcesFolder();
  1346. makeRelative(mRootEntry.get(), root);
  1347. }
  1348. void ProjectLibrary::makeEntriesAbsolute()
  1349. {
  1350. std::function<void(LibraryEntry*, const Path&)> makeAbsolute =
  1351. [&](LibraryEntry* entry, const Path& root)
  1352. {
  1353. entry->path.makeAbsolute(root);
  1354. if (entry->type == LibraryEntryType::Directory)
  1355. {
  1356. DirectoryEntry* dirEntry = static_cast<DirectoryEntry*>(entry);
  1357. for (auto& child : dirEntry->mChildren)
  1358. makeAbsolute(child.get(), root);
  1359. }
  1360. };
  1361. Path root = getResourcesFolder();
  1362. makeAbsolute(mRootEntry.get(), root);
  1363. }
  1364. void ProjectLibrary::saveLibrary()
  1365. {
  1366. if (!mIsLoaded)
  1367. return;
  1368. // Make all paths relative before saving
  1369. makeEntriesRelative();
  1370. SPtr<ProjectLibraryEntries> libEntries = ProjectLibraryEntries::create(mRootEntry);
  1371. Path libraryEntriesPath = mProjectFolder;
  1372. libraryEntriesPath.append(PROJECT_INTERNAL_DIR);
  1373. libraryEntriesPath.append(LIBRARY_ENTRIES_FILENAME);
  1374. FileEncoder fs(libraryEntriesPath);
  1375. fs.encode(libEntries.get());
  1376. // Restore absolute entry paths
  1377. makeEntriesAbsolute();
  1378. Path resourceManifestPath = mProjectFolder;
  1379. resourceManifestPath.append(PROJECT_INTERNAL_DIR);
  1380. resourceManifestPath.append(RESOURCE_MANIFEST_FILENAME);
  1381. ResourceManifest::save(mResourceManifest, resourceManifestPath, mProjectFolder);
  1382. }
  1383. void ProjectLibrary::loadLibrary()
  1384. {
  1385. unloadLibrary();
  1386. mProjectFolder = gEditorApplication().getProjectPath();
  1387. mResourcesFolder = mProjectFolder;
  1388. mResourcesFolder.append(RESOURCES_DIR);
  1389. mRootEntry = bs_ushared_ptr_new<DirectoryEntry>(mResourcesFolder, mResourcesFolder.getTail(), nullptr);
  1390. Path libraryEntriesPath = mProjectFolder;
  1391. libraryEntriesPath.append(PROJECT_INTERNAL_DIR);
  1392. libraryEntriesPath.append(LIBRARY_ENTRIES_FILENAME);
  1393. if(FileSystem::exists(libraryEntriesPath))
  1394. {
  1395. FileDecoder fs(libraryEntriesPath);
  1396. SPtr<ProjectLibraryEntries> libEntries = std::static_pointer_cast<ProjectLibraryEntries>(fs.decode());
  1397. mRootEntry = libEntries->getRootEntry();
  1398. mRootEntry->parent = nullptr;
  1399. }
  1400. // Entries are stored relative to project folder, but we want their absolute paths now
  1401. makeEntriesAbsolute();
  1402. // Load resource manifest
  1403. Path resourceManifestPath = mProjectFolder;
  1404. resourceManifestPath.append(PROJECT_INTERNAL_DIR);
  1405. resourceManifestPath.append(RESOURCE_MANIFEST_FILENAME);
  1406. if (FileSystem::exists(resourceManifestPath))
  1407. mResourceManifest = ResourceManifest::load(resourceManifestPath, mProjectFolder);
  1408. else
  1409. mResourceManifest = ResourceManifest::create("ProjectLibrary");
  1410. gResources().registerResourceManifest(mResourceManifest);
  1411. // Load all meta files
  1412. Stack<DirectoryEntry*> todo;
  1413. todo.push(mRootEntry.get());
  1414. Vector<USPtr<LibraryEntry>> deletedEntries;
  1415. while(!todo.empty())
  1416. {
  1417. DirectoryEntry* curDir = todo.top();
  1418. todo.pop();
  1419. for(auto& child : curDir->mChildren)
  1420. {
  1421. if(child->type == LibraryEntryType::File)
  1422. {
  1423. USPtr<FileEntry> resEntry = static_pointer_cast<FileEntry>(child);
  1424. if (FileSystem::isFile(resEntry->path))
  1425. {
  1426. if (resEntry->meta == nullptr)
  1427. {
  1428. Path metaPath = resEntry->path;
  1429. metaPath.setFilename(metaPath.getFilename() + ".meta");
  1430. if (FileSystem::isFile(metaPath))
  1431. {
  1432. FileDecoder fs(metaPath);
  1433. SPtr<IReflectable> loadedMeta = fs.decode();
  1434. if (loadedMeta != nullptr && loadedMeta->isDerivedFrom(ProjectFileMeta::getRTTIStatic()))
  1435. {
  1436. SPtr<ProjectFileMeta> fileMeta = std::static_pointer_cast<ProjectFileMeta>(loadedMeta);
  1437. resEntry->meta = fileMeta;
  1438. }
  1439. }
  1440. }
  1441. if (resEntry->meta != nullptr)
  1442. {
  1443. auto& resourceMetas = resEntry->meta->getResourceMetaData();
  1444. if (!resourceMetas.empty())
  1445. {
  1446. mUUIDToPath[resourceMetas[0]->getUUID()] = resEntry->path;
  1447. for (UINT32 i = 1; i < (UINT32)resourceMetas.size(); i++)
  1448. {
  1449. SPtr<ProjectResourceMeta> entry = resourceMetas[i];
  1450. mUUIDToPath[entry->getUUID()] = resEntry->path + entry->getUniqueName();
  1451. }
  1452. }
  1453. }
  1454. addDependencies(resEntry.get());
  1455. }
  1456. else
  1457. deletedEntries.push_back(resEntry);
  1458. }
  1459. else if(child->type == LibraryEntryType::Directory)
  1460. {
  1461. if (FileSystem::isDirectory(child->path))
  1462. todo.push(static_cast<DirectoryEntry*>(child.get()));
  1463. else
  1464. deletedEntries.push_back(child);
  1465. }
  1466. }
  1467. }
  1468. // Remove entries that no longer have corresponding files
  1469. for (auto& deletedEntry : deletedEntries)
  1470. {
  1471. if (deletedEntry->type == LibraryEntryType::File)
  1472. deleteResourceInternal(static_pointer_cast<FileEntry>(deletedEntry));
  1473. else
  1474. deleteDirectoryInternal(static_pointer_cast<DirectoryEntry>(deletedEntry));
  1475. }
  1476. // Clean up internal library folder from obsolete files
  1477. Path internalResourcesFolder = mProjectFolder;
  1478. internalResourcesFolder.append(INTERNAL_RESOURCES_DIR);
  1479. if (FileSystem::exists(internalResourcesFolder))
  1480. {
  1481. Vector<Path> toDelete;
  1482. auto processFile = [&](const Path& file)
  1483. {
  1484. UUID uuid = UUID(file.getFilename(false));
  1485. if (mUUIDToPath.find(uuid) == mUUIDToPath.end())
  1486. {
  1487. mResourceManifest->unregisterResource(uuid);
  1488. toDelete.push_back(file);
  1489. }
  1490. return true;
  1491. };
  1492. FileSystem::iterate(internalResourcesFolder, processFile);
  1493. for (auto& entry : toDelete)
  1494. FileSystem::remove(entry);
  1495. }
  1496. mIsLoaded = true;
  1497. }
  1498. void ProjectLibrary::clearEntries()
  1499. {
  1500. if (mRootEntry == nullptr)
  1501. return;
  1502. std::function<void(LibraryEntry*)> invalidateRecursive =
  1503. [&](LibraryEntry* entry)
  1504. {
  1505. if (entry->type == LibraryEntryType::Directory)
  1506. {
  1507. DirectoryEntry* dirEntry = static_cast<DirectoryEntry*>(entry);
  1508. for (auto& child : dirEntry->mChildren)
  1509. invalidateRecursive(child.get());
  1510. *dirEntry = DirectoryEntry();
  1511. }
  1512. else
  1513. {
  1514. FileEntry* fileEntry = static_cast<FileEntry*>(entry);
  1515. *fileEntry = FileEntry();
  1516. }
  1517. };
  1518. assert(mQueuedImports.empty());
  1519. invalidateRecursive(mRootEntry.get());
  1520. mRootEntry = nullptr;
  1521. }
  1522. Vector<Path> ProjectLibrary::getImportDependencies(const FileEntry* entry)
  1523. {
  1524. Vector<Path> output;
  1525. if (entry->meta == nullptr)
  1526. return output;
  1527. auto& resourceMetas = entry->meta->getResourceMetaData();
  1528. for(auto& resMeta : resourceMetas)
  1529. {
  1530. if (resMeta->getTypeID() == TID_Shader)
  1531. {
  1532. SPtr<ShaderMetaData> metaData = std::static_pointer_cast<ShaderMetaData>(resMeta->getResourceMetaData());
  1533. for (auto& include : metaData->includes)
  1534. output.push_back(include);
  1535. }
  1536. }
  1537. return output;
  1538. }
  1539. void ProjectLibrary::addDependencies(const FileEntry* entry)
  1540. {
  1541. Vector<Path> dependencies = getImportDependencies(entry);
  1542. for (auto& dependency : dependencies)
  1543. mDependencies[dependency].push_back(entry->path);
  1544. }
  1545. void ProjectLibrary::removeDependencies(const FileEntry* entry)
  1546. {
  1547. Vector<Path> dependencies = getImportDependencies(entry);
  1548. for (auto& dependency : dependencies)
  1549. {
  1550. Vector<Path>& curDependencies = mDependencies[dependency];
  1551. auto iterRemove = std::remove_if(curDependencies.begin(), curDependencies.end(),
  1552. [&](const Path& x)
  1553. {
  1554. return x == entry->path;
  1555. });
  1556. curDependencies.erase(iterRemove, curDependencies.end());
  1557. }
  1558. }
  1559. void ProjectLibrary::reimportDependants(const Path& entryPath)
  1560. {
  1561. auto iterFind = mDependencies.find(entryPath);
  1562. if (iterFind == mDependencies.end())
  1563. return;
  1564. // Make a copy since we might modify this list during reimport
  1565. Vector<Path> dependencies = iterFind->second;
  1566. for (auto& dependency : dependencies)
  1567. {
  1568. LibraryEntry* entry = findEntry(dependency).get();
  1569. if (entry != nullptr && entry->type == LibraryEntryType::File)
  1570. {
  1571. FileEntry* resEntry = static_cast<FileEntry*>(entry);
  1572. SPtr<ImportOptions> importOptions;
  1573. if (resEntry->meta != nullptr)
  1574. importOptions = resEntry->meta->getImportOptions();
  1575. reimportResourceInternal(resEntry, importOptions, true);
  1576. }
  1577. }
  1578. }
  1579. BS_ED_EXPORT ProjectLibrary& gProjectLibrary()
  1580. {
  1581. return ProjectLibrary::instance();
  1582. }
  1583. }