BsProjectLibrary.cpp 53 KB

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