BsProjectLibrary.cpp 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957
  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. LOGWRN("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. LOGWRN("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. LOGWRN("Trying to save a resource that hasn't been registered with the project library. Call ProjectLibrary::create first.");
  933. return;
  934. }
  935. filePath.makeAbsolute(getResourcesFolder());
  936. Resources::instance().save(resource, filePath, true);
  937. LibraryEntry* fileEntry = findEntry(filePath).get();
  938. if(fileEntry)
  939. reimportResourceInternal(static_cast<FileEntry*>(fileEntry), nullptr, true, false, true);
  940. }
  941. void ProjectLibrary::createFolderEntry(const Path& path)
  942. {
  943. Path fullPath = path;
  944. if (fullPath.isAbsolute())
  945. {
  946. if (!mResourcesFolder.includes(fullPath))
  947. return;
  948. }
  949. else
  950. fullPath.makeAbsolute(mResourcesFolder);
  951. if (FileSystem::isDirectory(fullPath))
  952. return; // Already exists
  953. FileSystem::createDir(fullPath);
  954. Path parentPath = fullPath.getParent();
  955. DirectoryEntry* newEntryParent = nullptr;
  956. USPtr<LibraryEntry> newEntryParentLib = findEntry(parentPath);
  957. if (newEntryParentLib != nullptr)
  958. {
  959. assert(newEntryParentLib->type == LibraryEntryType::Directory);
  960. newEntryParent = static_cast<DirectoryEntry*>(newEntryParentLib.get());
  961. }
  962. DirectoryEntry* newHierarchyParent = nullptr;
  963. if (newEntryParent == nullptr) // New path parent doesn't exist, so we need to create the hierarchy
  964. createInternalParentHierarchy(fullPath, &newHierarchyParent, &newEntryParent);
  965. addDirectoryInternal(newEntryParent, fullPath);
  966. }
  967. void ProjectLibrary::moveEntry(const Path& oldPath, const Path& newPath, bool overwrite)
  968. {
  969. Path oldFullPath = oldPath;
  970. if (!oldFullPath.isAbsolute())
  971. oldFullPath.makeAbsolute(mResourcesFolder);
  972. Path newFullPath = newPath;
  973. if (!newFullPath.isAbsolute())
  974. newFullPath.makeAbsolute(mResourcesFolder);
  975. Path parentPath = newFullPath.getParent();
  976. if (!FileSystem::isDirectory(parentPath))
  977. {
  978. LOGWRN("Move operation failed. Destination directory \"" + parentPath.toString() + "\" doesn't exist.");
  979. return;
  980. }
  981. if(FileSystem::isFile(oldFullPath) || FileSystem::isDirectory(oldFullPath))
  982. FileSystem::move(oldFullPath, newFullPath, overwrite);
  983. Path oldMetaPath = getMetaPath(oldFullPath);
  984. Path newMetaPath = getMetaPath(newFullPath);
  985. USPtr<LibraryEntry> oldEntry = findEntry(oldFullPath);
  986. if(oldEntry != nullptr) // Moving from the Resources folder
  987. {
  988. // Moved outside of Resources, delete entry & meta file
  989. if (!mResourcesFolder.includes(newFullPath))
  990. {
  991. if(oldEntry->type == LibraryEntryType::File)
  992. deleteResourceInternal(static_pointer_cast<FileEntry>(oldEntry));
  993. else if(oldEntry->type == LibraryEntryType::Directory)
  994. deleteDirectoryInternal(static_pointer_cast<DirectoryEntry>(oldEntry));
  995. }
  996. else // Just moving internally
  997. {
  998. onEntryRemoved(oldEntry->path);
  999. USPtr<FileEntry> fileEntry = nullptr;
  1000. if (oldEntry->type == LibraryEntryType::File)
  1001. {
  1002. fileEntry = static_pointer_cast<FileEntry>(oldEntry);
  1003. removeDependencies(fileEntry.get());
  1004. // Update uuid <-> path mapping
  1005. if(fileEntry->meta != nullptr)
  1006. {
  1007. auto& resourceMetas = fileEntry->meta->getResourceMetaData();
  1008. if (!resourceMetas.empty())
  1009. {
  1010. mUUIDToPath[resourceMetas[0]->getUUID()] = newFullPath;
  1011. for (UINT32 i = 1; i < (UINT32)resourceMetas.size(); i++)
  1012. {
  1013. SPtr<ProjectResourceMeta> resMeta = resourceMetas[i];
  1014. const UUID& UUID = resMeta->getUUID();
  1015. mUUIDToPath[UUID] = newFullPath + resMeta->getUniqueName();
  1016. }
  1017. }
  1018. }
  1019. }
  1020. if(FileSystem::isFile(oldMetaPath))
  1021. FileSystem::move(oldMetaPath, newMetaPath);
  1022. DirectoryEntry* parent = oldEntry->parent;
  1023. auto findIter = std::find(parent->mChildren.begin(), parent->mChildren.end(), oldEntry);
  1024. if(findIter != parent->mChildren.end())
  1025. parent->mChildren.erase(findIter);
  1026. Path parentPath = newFullPath.getParent();
  1027. DirectoryEntry* newEntryParent = nullptr;
  1028. USPtr<LibraryEntry> newEntryParentLib = findEntry(parentPath);
  1029. if(newEntryParentLib != nullptr)
  1030. {
  1031. assert(newEntryParentLib->type == LibraryEntryType::Directory);
  1032. newEntryParent = static_cast<DirectoryEntry*>(newEntryParentLib.get());
  1033. }
  1034. DirectoryEntry* newHierarchyParent = nullptr;
  1035. if(newEntryParent == nullptr) // New path parent doesn't exist, so we need to create the hierarchy
  1036. createInternalParentHierarchy(newFullPath, &newHierarchyParent, &newEntryParent);
  1037. newEntryParent->mChildren.push_back(oldEntry);
  1038. oldEntry->parent = newEntryParent;
  1039. oldEntry->path = newFullPath;
  1040. oldEntry->elementName = newFullPath.getTail();
  1041. oldEntry->elementNameHash = bs_hash(UTF8::toLower(oldEntry->elementName));
  1042. if(oldEntry->type == LibraryEntryType::Directory) // Update child paths
  1043. {
  1044. Stack<LibraryEntry*> todo;
  1045. todo.push(oldEntry.get());
  1046. while(!todo.empty())
  1047. {
  1048. LibraryEntry* curEntry = todo.top();
  1049. todo.pop();
  1050. DirectoryEntry* curDirEntry = static_cast<DirectoryEntry*>(curEntry);
  1051. for(auto& child : curDirEntry->mChildren)
  1052. {
  1053. child->path = child->parent->path;
  1054. child->path.append(child->elementName);
  1055. if(child->type == LibraryEntryType::Directory)
  1056. todo.push(child.get());
  1057. }
  1058. }
  1059. }
  1060. onEntryAdded(oldEntry->path);
  1061. if (fileEntry != nullptr)
  1062. {
  1063. reimportDependants(oldFullPath);
  1064. reimportDependants(newFullPath);
  1065. }
  1066. }
  1067. }
  1068. else // Moving from outside of the Resources folder (likely adding a new resource)
  1069. {
  1070. checkForModifications(newFullPath);
  1071. }
  1072. }
  1073. void ProjectLibrary::copyEntry(const Path& oldPath, const Path& newPath, bool overwrite)
  1074. {
  1075. Path oldFullPath = oldPath;
  1076. if (!oldFullPath.isAbsolute())
  1077. oldFullPath.makeAbsolute(mResourcesFolder);
  1078. Path newFullPath = newPath;
  1079. if (!newFullPath.isAbsolute())
  1080. newFullPath.makeAbsolute(mResourcesFolder);
  1081. if (!FileSystem::exists(oldFullPath))
  1082. return;
  1083. FileSystem::copy(oldFullPath, newFullPath, overwrite);
  1084. // Copying a file/folder outside of the Resources folder, no special handling needed
  1085. if (!mResourcesFolder.includes(newFullPath))
  1086. return;
  1087. Path parentPath = newFullPath.getParent();
  1088. DirectoryEntry* newEntryParent = nullptr;
  1089. LibraryEntry* newEntryParentLib = findEntry(parentPath).get();
  1090. if (newEntryParentLib != nullptr)
  1091. {
  1092. assert(newEntryParentLib->type == LibraryEntryType::Directory);
  1093. newEntryParent = static_cast<DirectoryEntry*>(newEntryParentLib);
  1094. }
  1095. // If the source is outside of Resources folder, just plain import the copy
  1096. LibraryEntry* oldEntry = findEntry(oldFullPath).get();
  1097. if (oldEntry == nullptr)
  1098. {
  1099. checkForModifications(newFullPath);
  1100. return;
  1101. }
  1102. // Both source and destination are within Resources folder, need to preserve import options on the copies
  1103. if (FileSystem::isFile(newFullPath))
  1104. {
  1105. assert(oldEntry->type == LibraryEntryType::File);
  1106. FileEntry* oldResEntry = static_cast<FileEntry*>(oldEntry);
  1107. SPtr<ImportOptions> importOptions;
  1108. if (oldResEntry->meta != nullptr)
  1109. importOptions = oldResEntry->meta->getImportOptions();
  1110. addResourceInternal(newEntryParent, newFullPath, importOptions, true);
  1111. }
  1112. else
  1113. {
  1114. assert(oldEntry->type == LibraryEntryType::File);
  1115. DirectoryEntry* oldDirEntry = static_cast<DirectoryEntry*>(oldEntry);
  1116. DirectoryEntry* newDirEntry = addDirectoryInternal(newEntryParent, newFullPath).get();
  1117. Stack<std::tuple<DirectoryEntry*, DirectoryEntry*>> todo;
  1118. todo.push(std::make_tuple(oldDirEntry, newDirEntry));
  1119. while (!todo.empty())
  1120. {
  1121. auto current = todo.top();
  1122. todo.pop();
  1123. DirectoryEntry* sourceDir = std::get<0>(current);
  1124. DirectoryEntry* destDir = std::get<1>(current);
  1125. for (auto& child : sourceDir->mChildren)
  1126. {
  1127. Path childDestPath = destDir->path;
  1128. childDestPath.append(child->path.getTail());
  1129. if (child->type == LibraryEntryType::File)
  1130. {
  1131. FileEntry* childResEntry = static_cast<FileEntry*>(child.get());
  1132. SPtr<ImportOptions> importOptions;
  1133. if (childResEntry->meta != nullptr)
  1134. importOptions = childResEntry->meta->getImportOptions();
  1135. addResourceInternal(destDir, childDestPath, importOptions, true);
  1136. }
  1137. else // Directory
  1138. {
  1139. DirectoryEntry* childSourceDirEntry = static_cast<DirectoryEntry*>(child.get());
  1140. DirectoryEntry* childDestDirEntry = addDirectoryInternal(destDir, childDestPath).get();
  1141. todo.push(std::make_tuple(childSourceDirEntry, childDestDirEntry));
  1142. }
  1143. }
  1144. }
  1145. }
  1146. }
  1147. void ProjectLibrary::deleteEntry(const Path& path)
  1148. {
  1149. Path fullPath = path;
  1150. if (!fullPath.isAbsolute())
  1151. fullPath.makeAbsolute(mResourcesFolder);
  1152. if(FileSystem::exists(fullPath))
  1153. FileSystem::remove(fullPath);
  1154. USPtr<LibraryEntry> entry = findEntry(fullPath);
  1155. if(entry != nullptr)
  1156. {
  1157. if(entry->type == LibraryEntryType::File)
  1158. deleteResourceInternal(static_pointer_cast<FileEntry>(entry));
  1159. else if(entry->type == LibraryEntryType::Directory)
  1160. deleteDirectoryInternal(static_pointer_cast<DirectoryEntry>(entry));
  1161. }
  1162. }
  1163. void ProjectLibrary::reimport(const Path& path, const SPtr<ImportOptions>& importOptions, bool forceReimport,
  1164. bool synchronous)
  1165. {
  1166. LibraryEntry* entry = findEntry(path).get();
  1167. if (entry != nullptr)
  1168. {
  1169. if (entry->type == LibraryEntryType::File)
  1170. {
  1171. FileEntry* resEntry = static_cast<FileEntry*>(entry);
  1172. reimportResourceInternal(resEntry, importOptions, forceReimport, synchronous);
  1173. }
  1174. }
  1175. }
  1176. float ProjectLibrary::getImportProgress(const Path& path) const
  1177. {
  1178. LibraryEntry* entry = findEntry(path).get();
  1179. if (entry == nullptr)
  1180. return 0.0f;
  1181. if(entry->type == LibraryEntryType::Directory)
  1182. return 1.0f;
  1183. // Note: Only supporting binary progress reporting for now
  1184. const auto iterFind = mQueuedImports.find(static_cast<FileEntry*>(entry));
  1185. return iterFind != mQueuedImports.end() ? 0.0f : 1.0f;
  1186. }
  1187. void ProjectLibrary::cancelImport()
  1188. {
  1189. for(auto& entry : mQueuedImports)
  1190. entry.second->canceled = true;
  1191. }
  1192. void ProjectLibrary::waitForQueuedImport(FileEntry* fileEntry)
  1193. {
  1194. const auto iterFind = mQueuedImports.find(fileEntry);
  1195. if (iterFind != mQueuedImports.end())
  1196. {
  1197. if (finishQueuedImport(fileEntry, *iterFind->second, true))
  1198. mQueuedImports.erase(iterFind);
  1199. }
  1200. }
  1201. void ProjectLibrary::setIncludeInBuild(const Path& path, bool include)
  1202. {
  1203. LibraryEntry* entry = findEntry(path).get();
  1204. if (entry == nullptr || entry->type == LibraryEntryType::Directory)
  1205. return;
  1206. auto fileEntry = static_cast<FileEntry*>(entry);
  1207. // Any queued imports will overwrite the meta file, so make sure they finish first
  1208. waitForQueuedImport(fileEntry);
  1209. if (fileEntry->meta == nullptr)
  1210. return;
  1211. fileEntry->meta->setIncludeInBuild(include);
  1212. Path metaPath = fileEntry->path;
  1213. metaPath.setFilename(metaPath.getFilename() + ".meta");
  1214. FileEncoder fs(metaPath);
  1215. fs.encode(fileEntry->meta.get());
  1216. }
  1217. void ProjectLibrary::setUserData(const Path& path, const SPtr<IReflectable>& userData)
  1218. {
  1219. LibraryEntry* entry = findEntry(path).get();
  1220. if (entry == nullptr || entry->type == LibraryEntryType::Directory)
  1221. return;
  1222. auto fileEntry = static_cast<FileEntry*>(entry);
  1223. // Any queued imports will overwrite the meta file, so make sure they finish first
  1224. waitForQueuedImport(fileEntry);
  1225. SPtr<ProjectResourceMeta> resMeta = findResourceMeta(path);
  1226. if (resMeta == nullptr)
  1227. return;
  1228. resMeta->mUserData = userData;
  1229. Path metaPath = fileEntry->path;
  1230. metaPath.setFilename(metaPath.getFilename() + ".meta");
  1231. FileEncoder fs(metaPath);
  1232. fs.encode(fileEntry->meta.get());
  1233. }
  1234. Vector<USPtr<ProjectLibrary::FileEntry>> ProjectLibrary::getResourcesForBuild() const
  1235. {
  1236. Vector<USPtr<FileEntry>> output;
  1237. Stack<DirectoryEntry*> todo;
  1238. todo.push(mRootEntry.get());
  1239. while (!todo.empty())
  1240. {
  1241. DirectoryEntry* directory = todo.top();
  1242. todo.pop();
  1243. for (auto& child : directory->mChildren)
  1244. {
  1245. if (child->type == LibraryEntryType::File)
  1246. {
  1247. FileEntry* resEntry = static_cast<FileEntry*>(child.get());
  1248. if (resEntry->meta != nullptr && resEntry->meta->getIncludeInBuild())
  1249. output.push_back(static_pointer_cast<FileEntry>(child));
  1250. }
  1251. else if (child->type == LibraryEntryType::Directory)
  1252. {
  1253. todo.push(static_cast<DirectoryEntry*>(child.get()));
  1254. }
  1255. }
  1256. }
  1257. return output;
  1258. }
  1259. HResource ProjectLibrary::load(const Path& path)
  1260. {
  1261. SPtr<ProjectResourceMeta> meta = findResourceMeta(path);
  1262. if (meta == nullptr)
  1263. return HResource();
  1264. ResourceLoadFlags loadFlags = ResourceLoadFlag::Default | ResourceLoadFlag::KeepSourceData;
  1265. const UUID& resUUID = meta->getUUID();
  1266. return gResources().loadFromUUID(resUUID, false, loadFlags);
  1267. }
  1268. void ProjectLibrary::createInternalParentHierarchy(const Path& fullPath, DirectoryEntry** newHierarchyRoot,
  1269. DirectoryEntry** newHierarchyLeaf)
  1270. {
  1271. Path parentPath = fullPath;
  1272. DirectoryEntry* newEntryParent = nullptr;
  1273. Stack<Path> parentPaths;
  1274. do
  1275. {
  1276. Path newParentPath = parentPath.getParent();
  1277. if(newParentPath == parentPath)
  1278. break;
  1279. LibraryEntry* newEntryParentLib = findEntry(newParentPath).get();
  1280. if(newEntryParentLib != nullptr)
  1281. {
  1282. assert(newEntryParentLib->type == LibraryEntryType::Directory);
  1283. newEntryParent = static_cast<DirectoryEntry*>(newEntryParentLib);
  1284. break;
  1285. }
  1286. parentPaths.push(newParentPath);
  1287. parentPath = newParentPath;
  1288. } while (true);
  1289. assert(newEntryParent != nullptr); // Must exist
  1290. if(newHierarchyRoot != nullptr)
  1291. *newHierarchyRoot = newEntryParent;
  1292. while(!parentPaths.empty())
  1293. {
  1294. Path curPath = parentPaths.top();
  1295. parentPaths.pop();
  1296. newEntryParent = addDirectoryInternal(newEntryParent, curPath).get();
  1297. }
  1298. if(newHierarchyLeaf != nullptr)
  1299. *newHierarchyLeaf = newEntryParent;
  1300. }
  1301. Path ProjectLibrary::getMetaPath(const Path& path) const
  1302. {
  1303. Path metaPath = path;
  1304. metaPath.setFilename(metaPath.getFilename() + ".meta");
  1305. return metaPath;
  1306. }
  1307. bool ProjectLibrary::isMeta(const Path& fullPath) const
  1308. {
  1309. return fullPath.getExtension() == ".meta";
  1310. }
  1311. bool ProjectLibrary::isNative(const Path& path) const
  1312. {
  1313. String extension = path.getExtension();
  1314. return extension == ".asset" || extension == ".prefab";
  1315. }
  1316. void ProjectLibrary::unloadLibrary()
  1317. {
  1318. if (!mIsLoaded)
  1319. return;
  1320. _finishQueuedImports(true);
  1321. mProjectFolder = Path::BLANK;
  1322. mResourcesFolder = Path::BLANK;
  1323. clearEntries();
  1324. mRootEntry = bs_ushared_ptr_new<DirectoryEntry>(mResourcesFolder, mResourcesFolder.getTail(), nullptr);
  1325. mDependencies.clear();
  1326. gResources().unregisterResourceManifest(mResourceManifest);
  1327. mResourceManifest = nullptr;
  1328. mIsLoaded = false;
  1329. }
  1330. void ProjectLibrary::makeEntriesRelative()
  1331. {
  1332. // Make all paths relative before saving
  1333. std::function<void(LibraryEntry*, const Path&)> makeRelative =
  1334. [&](LibraryEntry* entry, const Path& root)
  1335. {
  1336. entry->path.makeRelative(root);
  1337. if (entry->type == LibraryEntryType::Directory)
  1338. {
  1339. DirectoryEntry* dirEntry = static_cast<DirectoryEntry*>(entry);
  1340. for (auto& child : dirEntry->mChildren)
  1341. makeRelative(child.get(), root);
  1342. }
  1343. };
  1344. Path root = getResourcesFolder();
  1345. makeRelative(mRootEntry.get(), root);
  1346. }
  1347. void ProjectLibrary::makeEntriesAbsolute()
  1348. {
  1349. std::function<void(LibraryEntry*, const Path&)> makeAbsolute =
  1350. [&](LibraryEntry* entry, const Path& root)
  1351. {
  1352. entry->path.makeAbsolute(root);
  1353. if (entry->type == LibraryEntryType::Directory)
  1354. {
  1355. DirectoryEntry* dirEntry = static_cast<DirectoryEntry*>(entry);
  1356. for (auto& child : dirEntry->mChildren)
  1357. makeAbsolute(child.get(), root);
  1358. }
  1359. };
  1360. Path root = getResourcesFolder();
  1361. makeAbsolute(mRootEntry.get(), root);
  1362. }
  1363. void ProjectLibrary::saveLibrary()
  1364. {
  1365. if (!mIsLoaded)
  1366. return;
  1367. // Make all paths relative before saving
  1368. makeEntriesRelative();
  1369. SPtr<ProjectLibraryEntries> libEntries = ProjectLibraryEntries::create(mRootEntry);
  1370. Path libraryEntriesPath = mProjectFolder;
  1371. libraryEntriesPath.append(PROJECT_INTERNAL_DIR);
  1372. libraryEntriesPath.append(LIBRARY_ENTRIES_FILENAME);
  1373. FileEncoder fs(libraryEntriesPath);
  1374. fs.encode(libEntries.get());
  1375. // Restore absolute entry paths
  1376. makeEntriesAbsolute();
  1377. Path resourceManifestPath = mProjectFolder;
  1378. resourceManifestPath.append(PROJECT_INTERNAL_DIR);
  1379. resourceManifestPath.append(RESOURCE_MANIFEST_FILENAME);
  1380. ResourceManifest::save(mResourceManifest, resourceManifestPath, mProjectFolder);
  1381. }
  1382. void ProjectLibrary::loadLibrary()
  1383. {
  1384. unloadLibrary();
  1385. mProjectFolder = gEditorApplication().getProjectPath();
  1386. mResourcesFolder = mProjectFolder;
  1387. mResourcesFolder.append(RESOURCES_DIR);
  1388. mRootEntry = bs_ushared_ptr_new<DirectoryEntry>(mResourcesFolder, mResourcesFolder.getTail(), nullptr);
  1389. Path libraryEntriesPath = mProjectFolder;
  1390. libraryEntriesPath.append(PROJECT_INTERNAL_DIR);
  1391. libraryEntriesPath.append(LIBRARY_ENTRIES_FILENAME);
  1392. if(FileSystem::exists(libraryEntriesPath))
  1393. {
  1394. FileDecoder fs(libraryEntriesPath);
  1395. SPtr<ProjectLibraryEntries> libEntries = std::static_pointer_cast<ProjectLibraryEntries>(fs.decode());
  1396. mRootEntry = libEntries->getRootEntry();
  1397. mRootEntry->parent = nullptr;
  1398. }
  1399. // Entries are stored relative to project folder, but we want their absolute paths now
  1400. makeEntriesAbsolute();
  1401. // Load resource manifest
  1402. Path resourceManifestPath = mProjectFolder;
  1403. resourceManifestPath.append(PROJECT_INTERNAL_DIR);
  1404. resourceManifestPath.append(RESOURCE_MANIFEST_FILENAME);
  1405. if (FileSystem::exists(resourceManifestPath))
  1406. mResourceManifest = ResourceManifest::load(resourceManifestPath, mProjectFolder);
  1407. else
  1408. mResourceManifest = ResourceManifest::create("ProjectLibrary");
  1409. gResources().registerResourceManifest(mResourceManifest);
  1410. // Load all meta files
  1411. Stack<DirectoryEntry*> todo;
  1412. todo.push(mRootEntry.get());
  1413. Vector<USPtr<LibraryEntry>> deletedEntries;
  1414. while(!todo.empty())
  1415. {
  1416. DirectoryEntry* curDir = todo.top();
  1417. todo.pop();
  1418. for(auto& child : curDir->mChildren)
  1419. {
  1420. if(child->type == LibraryEntryType::File)
  1421. {
  1422. USPtr<FileEntry> resEntry = static_pointer_cast<FileEntry>(child);
  1423. if (FileSystem::isFile(resEntry->path))
  1424. {
  1425. if (resEntry->meta == nullptr)
  1426. {
  1427. Path metaPath = resEntry->path;
  1428. metaPath.setFilename(metaPath.getFilename() + ".meta");
  1429. if (FileSystem::isFile(metaPath))
  1430. {
  1431. FileDecoder fs(metaPath);
  1432. SPtr<IReflectable> loadedMeta = fs.decode();
  1433. if (loadedMeta != nullptr && loadedMeta->isDerivedFrom(ProjectFileMeta::getRTTIStatic()))
  1434. {
  1435. SPtr<ProjectFileMeta> fileMeta = std::static_pointer_cast<ProjectFileMeta>(loadedMeta);
  1436. resEntry->meta = fileMeta;
  1437. }
  1438. }
  1439. }
  1440. if (resEntry->meta != nullptr)
  1441. {
  1442. auto& resourceMetas = resEntry->meta->getResourceMetaData();
  1443. if (!resourceMetas.empty())
  1444. {
  1445. mUUIDToPath[resourceMetas[0]->getUUID()] = resEntry->path;
  1446. for (UINT32 i = 1; i < (UINT32)resourceMetas.size(); i++)
  1447. {
  1448. SPtr<ProjectResourceMeta> entry = resourceMetas[i];
  1449. mUUIDToPath[entry->getUUID()] = resEntry->path + entry->getUniqueName();
  1450. }
  1451. }
  1452. }
  1453. addDependencies(resEntry.get());
  1454. }
  1455. else
  1456. deletedEntries.push_back(resEntry);
  1457. }
  1458. else if(child->type == LibraryEntryType::Directory)
  1459. {
  1460. if (FileSystem::isDirectory(child->path))
  1461. todo.push(static_cast<DirectoryEntry*>(child.get()));
  1462. else
  1463. deletedEntries.push_back(child);
  1464. }
  1465. }
  1466. }
  1467. // Remove entries that no longer have corresponding files
  1468. for (auto& deletedEntry : deletedEntries)
  1469. {
  1470. if (deletedEntry->type == LibraryEntryType::File)
  1471. deleteResourceInternal(static_pointer_cast<FileEntry>(deletedEntry));
  1472. else
  1473. deleteDirectoryInternal(static_pointer_cast<DirectoryEntry>(deletedEntry));
  1474. }
  1475. // Clean up internal library folder from obsolete files
  1476. Path internalResourcesFolder = mProjectFolder;
  1477. internalResourcesFolder.append(INTERNAL_RESOURCES_DIR);
  1478. if (FileSystem::exists(internalResourcesFolder))
  1479. {
  1480. Vector<Path> toDelete;
  1481. auto processFile = [&](const Path& file)
  1482. {
  1483. UUID uuid = UUID(file.getFilename(false));
  1484. if (mUUIDToPath.find(uuid) == mUUIDToPath.end())
  1485. {
  1486. mResourceManifest->unregisterResource(uuid);
  1487. toDelete.push_back(file);
  1488. }
  1489. return true;
  1490. };
  1491. FileSystem::iterate(internalResourcesFolder, processFile);
  1492. for (auto& entry : toDelete)
  1493. FileSystem::remove(entry);
  1494. }
  1495. mIsLoaded = true;
  1496. }
  1497. void ProjectLibrary::clearEntries()
  1498. {
  1499. if (mRootEntry == nullptr)
  1500. return;
  1501. std::function<void(LibraryEntry*)> invalidateRecursive =
  1502. [&](LibraryEntry* entry)
  1503. {
  1504. if (entry->type == LibraryEntryType::Directory)
  1505. {
  1506. DirectoryEntry* dirEntry = static_cast<DirectoryEntry*>(entry);
  1507. for (auto& child : dirEntry->mChildren)
  1508. invalidateRecursive(child.get());
  1509. *dirEntry = DirectoryEntry();
  1510. }
  1511. else
  1512. {
  1513. FileEntry* fileEntry = static_cast<FileEntry*>(entry);
  1514. *fileEntry = FileEntry();
  1515. }
  1516. };
  1517. assert(mQueuedImports.empty());
  1518. invalidateRecursive(mRootEntry.get());
  1519. mRootEntry = nullptr;
  1520. }
  1521. Vector<Path> ProjectLibrary::getImportDependencies(const FileEntry* entry)
  1522. {
  1523. Vector<Path> output;
  1524. if (entry->meta == nullptr)
  1525. return output;
  1526. auto& resourceMetas = entry->meta->getResourceMetaData();
  1527. for(auto& resMeta : resourceMetas)
  1528. {
  1529. if (resMeta->getTypeID() == TID_Shader)
  1530. {
  1531. SPtr<ShaderMetaData> metaData = std::static_pointer_cast<ShaderMetaData>(resMeta->getResourceMetaData());
  1532. for (auto& include : metaData->includes)
  1533. output.push_back(include);
  1534. }
  1535. }
  1536. return output;
  1537. }
  1538. void ProjectLibrary::addDependencies(const FileEntry* entry)
  1539. {
  1540. Vector<Path> dependencies = getImportDependencies(entry);
  1541. for (auto& dependency : dependencies)
  1542. mDependencies[dependency].push_back(entry->path);
  1543. }
  1544. void ProjectLibrary::removeDependencies(const FileEntry* entry)
  1545. {
  1546. Vector<Path> dependencies = getImportDependencies(entry);
  1547. for (auto& dependency : dependencies)
  1548. {
  1549. Vector<Path>& curDependencies = mDependencies[dependency];
  1550. auto iterRemove = std::remove_if(curDependencies.begin(), curDependencies.end(),
  1551. [&](const Path& x)
  1552. {
  1553. return x == entry->path;
  1554. });
  1555. curDependencies.erase(iterRemove, curDependencies.end());
  1556. }
  1557. }
  1558. void ProjectLibrary::reimportDependants(const Path& entryPath)
  1559. {
  1560. auto iterFind = mDependencies.find(entryPath);
  1561. if (iterFind == mDependencies.end())
  1562. return;
  1563. // Make a copy since we might modify this list during reimport
  1564. Vector<Path> dependencies = iterFind->second;
  1565. for (auto& dependency : dependencies)
  1566. {
  1567. LibraryEntry* entry = findEntry(dependency).get();
  1568. if (entry != nullptr && entry->type == LibraryEntryType::File)
  1569. {
  1570. FileEntry* resEntry = static_cast<FileEntry*>(entry);
  1571. SPtr<ImportOptions> importOptions;
  1572. if (resEntry->meta != nullptr)
  1573. importOptions = resEntry->meta->getImportOptions();
  1574. reimportResourceInternal(resEntry, importOptions, true);
  1575. }
  1576. }
  1577. }
  1578. BS_ED_EXPORT ProjectLibrary& gProjectLibrary()
  1579. {
  1580. return ProjectLibrary::instance();
  1581. }
  1582. }