BsProjectLibrary.cpp 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810
  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), 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)
  269. {
  270. FileEntry* newResource = bs_new<FileEntry>(filePath, filePath.getTail(), parent);
  271. parent->mChildren.push_back(newResource);
  272. reimportResourceInternal(newResource, importOptions, forceReimport);
  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)
  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. // If import is already queued for this file make the tasks dependant so they don't execute at the same time,
  389. // and so they execute in the proper order
  390. SPtr<Task> dependency;
  391. const auto iterFind = mQueuedImports.find(fileEntry);
  392. if (iterFind != mQueuedImports.end())
  393. {
  394. dependency = iterFind->second->importTask;
  395. // Note: We should cancel the task here so it doesn't run unnecessarily. But if the task is already
  396. // running it shouldn't be canceled as dependencies still need to wait on it (since cancelling a
  397. // running task doesn't actually stop it). Yet there is currently no good wait to check if task
  398. // is currently running.
  399. }
  400. if(!isNativeResource)
  401. {
  402. // Find UUIDs for any existing sub-resources
  403. if (fileEntry->meta != nullptr)
  404. {
  405. const Vector<SPtr<ProjectResourceMeta>>& resourceMetas = fileEntry->meta->getAllResourceMetaData();
  406. for (auto& entry : resourceMetas)
  407. queuedImport->resources.emplace_back(entry->getUniqueName(), nullptr, entry->getUUID());
  408. }
  409. // Perform import, register the resources and their UUID in the QueuedImport structure and save the
  410. // resource on disk
  411. const auto importAsync = [queuedImport, &projectFolder = mProjectFolder, &mutex = mQueuedImportMutex]()
  412. {
  413. Vector<SubResourceRaw> importedResources = gImporter()._importAll(queuedImport->filePath,
  414. queuedImport->importOptions);
  415. if (!importedResources.empty())
  416. {
  417. Path outputPath = projectFolder;
  418. outputPath.append(INTERNAL_RESOURCES_DIR);
  419. if (!FileSystem::isDirectory(outputPath))
  420. FileSystem::createDir(outputPath);
  421. for (auto& entry : importedResources)
  422. {
  423. String subresourceName = entry.name;
  424. Path::stripInvalid(subresourceName);
  425. UUID uuid;
  426. {
  427. // Any access to queuedImport->resources must be locked
  428. Lock lock(mutex);
  429. auto iterFind = std::find_if(queuedImport->resources.begin(), queuedImport->resources.end(),
  430. [&subresourceName](const QueuedImportResource& importResource)
  431. {
  432. return importResource.name == subresourceName;
  433. });
  434. if (iterFind != queuedImport->resources.end())
  435. iterFind->resource = entry.value;
  436. else
  437. {
  438. queuedImport->resources.push_back(QueuedImportResource(entry.name, entry.value,
  439. UUID::EMPTY));
  440. iterFind = queuedImport->resources.end() - 1;
  441. }
  442. if (iterFind->uuid.empty())
  443. iterFind->uuid = UUIDGenerator::generateRandom();
  444. uuid = iterFind->uuid;
  445. }
  446. const String uuidStr = uuid.toString();
  447. outputPath.setFilename(uuidStr + ".asset");
  448. gResources()._save(entry.value, outputPath, true);
  449. }
  450. }
  451. };
  452. queuedImport->importTask = Task::create("ProjectLibraryImport", importAsync, TaskPriority::Normal,
  453. dependency);
  454. }
  455. else
  456. {
  457. // If meta exists make sure it is registered in the manifest before load, otherwise it will get assigned a new UUID.
  458. // This can happen if library isn't properly saved before exiting the application.
  459. if (fileEntry->meta != nullptr)
  460. {
  461. auto& resourceMetas = fileEntry->meta->getResourceMetaData();
  462. mResourceManifest->registerResource(resourceMetas[0]->getUUID(), fileEntry->path);
  463. }
  464. const auto importAsync = [queuedImport, &projectFolder = mProjectFolder, &mutex = mQueuedImportMutex]()
  465. {
  466. // Don't load dependencies because we don't need them, but also because they might not be in the
  467. // manifest which would screw up their UUIDs.
  468. HResource resource = gResources().load(queuedImport->filePath, ResourceLoadFlag::KeepSourceData);
  469. if (resource)
  470. {
  471. Path outputPath = projectFolder;
  472. outputPath.append(INTERNAL_RESOURCES_DIR);
  473. if (!FileSystem::isDirectory(outputPath))
  474. FileSystem::createDir(outputPath);
  475. {
  476. // Any access to queuedImport->resources must be locked
  477. Lock lock(mutex);
  478. queuedImport->resources.push_back(QueuedImportResource("primary", resource.getInternalPtr(),
  479. resource.getUUID()));
  480. }
  481. const String uuidStr = resource.getUUID().toString();
  482. outputPath.setFilename(uuidStr + ".asset");
  483. gResources()._save(resource.getInternalPtr(), outputPath, true);
  484. }
  485. };
  486. queuedImport->importTask = Task::create("ProjectLibraryImport", importAsync, TaskPriority::Normal,
  487. dependency);
  488. }
  489. TaskScheduler::instance().addTask(queuedImport->importTask);
  490. mQueuedImports[fileEntry] = queuedImport;
  491. fileEntry->lastUpdateTime = std::time(nullptr);
  492. return true;
  493. }
  494. return false;
  495. }
  496. void ProjectLibrary::_finishQueuedImports(bool wait)
  497. {
  498. for(auto iter = mQueuedImports.begin(); iter != mQueuedImports.end();)
  499. {
  500. SPtr<QueuedImport> queuedImport = iter->second;
  501. if (!queuedImport->importTask->isComplete())
  502. {
  503. if (wait)
  504. queuedImport->importTask->wait();
  505. else
  506. {
  507. ++iter;
  508. continue;
  509. }
  510. }
  511. // The task is done, we can remove it
  512. FileEntry* fileEntry = iter->first;
  513. iter = mQueuedImports.erase(iter);
  514. // We wait on canceled task to finish and then just discard the results because any dependant tasks need to be
  515. // aware this tasks exists, so we can't just remove it straight away.
  516. if(queuedImport->canceled)
  517. {
  518. // Just move on to the next import...
  519. continue;
  520. }
  521. Path metaPath = fileEntry->path;
  522. metaPath.setFilename(metaPath.getFilename() + ".meta");
  523. Vector<SPtr<ProjectResourceMeta>> existingMetas;
  524. if(fileEntry->meta == nullptr) // Build a brand new meta-file
  525. fileEntry->meta = ProjectFileMeta::create(queuedImport->importOptions);
  526. else // Existing meta-file, which needs to be updated
  527. {
  528. // Remove existing dependencies (they will be re-added later)
  529. removeDependencies(fileEntry);
  530. existingMetas = fileEntry->meta->getAllResourceMetaData();
  531. fileEntry->meta->clearResourceMetaData();
  532. fileEntry->meta->mImportOptions = queuedImport->importOptions;
  533. }
  534. Path internalResourcesPath = mProjectFolder;
  535. internalResourcesPath.append(INTERNAL_RESOURCES_DIR);
  536. // See which sub-resource metas need to be updated, removed or added based on the new resource set
  537. bool isFirst = true;
  538. for (auto& entry : queuedImport->resources)
  539. {
  540. // Entries with no resources are sub-resources that used to exist in this file, but haven't been imported
  541. // this time
  542. if(!entry.resource)
  543. continue;
  544. Path::stripInvalid(entry.name);
  545. const ProjectResourceIcons icons = generatePreviewIcons(*entry.resource);
  546. bool foundMeta = false;
  547. for (auto iterMeta = existingMetas.begin(); iterMeta != existingMetas.end(); ++iterMeta)
  548. {
  549. const SPtr<ProjectResourceMeta>& metaEntry = *iterMeta;
  550. if (entry.name == metaEntry->getUniqueName())
  551. {
  552. // Make sure the UUID we used for saving the resource matches the current one (should always
  553. // be true unless the meta-data somehow changes while the async import is happening)
  554. assert(entry.uuid == metaEntry->getUUID());
  555. HResource importedResource = gResources()._getResourceHandle(metaEntry->getUUID());
  556. gResources().update(importedResource, entry.resource);
  557. metaEntry->setPreviewIcons(icons);
  558. fileEntry->meta->add(metaEntry);
  559. iterMeta = existingMetas.erase(iterMeta);
  560. foundMeta = true;
  561. break;
  562. }
  563. }
  564. if (!foundMeta)
  565. {
  566. HResource importedResource = gResources()._createResourceHandle(entry.resource, entry.uuid);
  567. SPtr<ResourceMetaData> subMeta = entry.resource->getMetaData();
  568. const UINT32 typeId = entry.resource->getTypeId();
  569. const UUID& UUID = importedResource.getUUID();
  570. SPtr<ProjectResourceMeta> resMeta = ProjectResourceMeta::create(entry.name, UUID, typeId,
  571. icons, subMeta);
  572. fileEntry->meta->add(resMeta);
  573. }
  574. // Keep resource metas that we are not currently using, in case they get restored so their references
  575. // don't get broken
  576. if (!queuedImport->pruneMetas)
  577. {
  578. for (auto& metaEntry : existingMetas)
  579. fileEntry->meta->addInactive(metaEntry);
  580. }
  581. // Update UUID to path mapping
  582. if(isFirst)
  583. mUUIDToPath[entry.uuid] = fileEntry->path;
  584. else
  585. mUUIDToPath[entry.uuid] = fileEntry->path + entry.name;
  586. isFirst = false;
  587. // Register path in manifest
  588. const String uuidStr = entry.uuid.toString();
  589. internalResourcesPath.setFilename(uuidStr + ".asset");
  590. mResourceManifest->registerResource(entry.uuid, internalResourcesPath);
  591. }
  592. // Save the meta file
  593. FileEncoder fs(metaPath);
  594. fs.encode(fileEntry->meta.get());
  595. // Register any dependencies this resource depends on
  596. addDependencies(fileEntry);
  597. // Notify the outside world import is doen
  598. onEntryImported(fileEntry->path);
  599. // Queue any resources dependant on this one for import
  600. reimportDependants(fileEntry->path);
  601. }
  602. }
  603. bool ProjectLibrary::isUpToDate(FileEntry* resource) const
  604. {
  605. if(resource->meta == nullptr)
  606. {
  607. // Allow no meta if import in progress
  608. const auto iterFind = mQueuedImports.find(resource);
  609. if(iterFind == mQueuedImports.end())
  610. return false;
  611. }
  612. else
  613. {
  614. auto& resourceMetas = resource->meta->getResourceMetaData();
  615. for (auto& resMeta : resourceMetas)
  616. {
  617. Path internalPath;
  618. if (!mResourceManifest->uuidToFilePath(resMeta->getUUID(), internalPath))
  619. return false;
  620. if (!FileSystem::isFile(internalPath))
  621. return false;
  622. }
  623. }
  624. const std::time_t lastModifiedTime = FileSystem::getLastModifiedTime(resource->path);
  625. return lastModifiedTime <= resource->lastUpdateTime;
  626. }
  627. Vector<ProjectLibrary::LibraryEntry*> ProjectLibrary::search(const String& pattern)
  628. {
  629. return search(pattern, {});
  630. }
  631. Vector<ProjectLibrary::LibraryEntry*> ProjectLibrary::search(const String& pattern, const Vector<UINT32>& typeIds)
  632. {
  633. Vector<LibraryEntry*> foundEntries;
  634. std::regex escape("[.^$|()\\[\\]{}*+?\\\\]");
  635. String replace("\\\\&");
  636. String escapedPattern = std::regex_replace(pattern, escape, replace, std::regex_constants::match_default | std::regex_constants::format_sed);
  637. // For some reason MSVC stdlib implementation requires a different pattern than stdlib one
  638. #if BS_PLATFORM == BS_PLATFORM_WIN32
  639. std::regex wildcard("\\\\\\*");
  640. #else
  641. std::regex wildcard("\\\\\\\\\\*");
  642. #endif
  643. String wildcardReplace(".*");
  644. String searchPattern = std::regex_replace(escapedPattern, wildcard, ".*");
  645. std::regex searchRegex(searchPattern, std::regex_constants::ECMAScript | std::regex_constants::icase);
  646. Stack<DirectoryEntry*> todo;
  647. todo.push(mRootEntry);
  648. while (!todo.empty())
  649. {
  650. DirectoryEntry* dirEntry = todo.top();
  651. todo.pop();
  652. for (auto& child : dirEntry->mChildren)
  653. {
  654. if (std::regex_match(child->elementName, searchRegex))
  655. {
  656. if (typeIds.size() == 0)
  657. foundEntries.push_back(child);
  658. else
  659. {
  660. if (child->type == LibraryEntryType::File)
  661. {
  662. FileEntry* childFileEntry = static_cast<FileEntry*>(child);
  663. if (childFileEntry->meta != nullptr)
  664. {
  665. auto& resourceMetas = childFileEntry->meta->getResourceMetaData();
  666. for (auto& typeId : typeIds)
  667. {
  668. bool found = false;
  669. for (auto& resMeta : resourceMetas)
  670. {
  671. if (resMeta->getTypeID() == typeId)
  672. {
  673. foundEntries.push_back(child);
  674. found = true;
  675. break;
  676. }
  677. }
  678. if (found)
  679. break;
  680. }
  681. }
  682. }
  683. }
  684. }
  685. if (child->type == LibraryEntryType::Directory)
  686. {
  687. DirectoryEntry* childDirEntry = static_cast<DirectoryEntry*>(child);
  688. todo.push(childDirEntry);
  689. }
  690. }
  691. }
  692. std::sort(foundEntries.begin(), foundEntries.end(),
  693. [&](const LibraryEntry* a, const LibraryEntry* b)
  694. {
  695. return a->elementName.compare(b->elementName) < 0;
  696. });
  697. return foundEntries;
  698. }
  699. ProjectLibrary::LibraryEntry* ProjectLibrary::findEntry(const Path& path) const
  700. {
  701. Path fullPath = path;
  702. if (fullPath.isAbsolute())
  703. {
  704. if (!mResourcesFolder.includes(fullPath))
  705. return nullptr;
  706. }
  707. else
  708. fullPath.makeAbsolute(mResourcesFolder);
  709. Path relPath = fullPath.getRelative(mRootEntry->path);
  710. UINT32 numElems = relPath.getNumDirectories() + (relPath.isFile() ? 1 : 0);
  711. UINT32 idx = 0;
  712. LibraryEntry* current = mRootEntry;
  713. while (current != nullptr)
  714. {
  715. if (idx == numElems)
  716. return current;
  717. String curElem;
  718. if (relPath.isFile() && idx == (numElems - 1))
  719. curElem = relPath.getFilename();
  720. else
  721. curElem = relPath[idx];
  722. if (current->type == LibraryEntryType::Directory)
  723. {
  724. DirectoryEntry* dirEntry = static_cast<DirectoryEntry*>(current);
  725. current = nullptr;
  726. for (auto& child : dirEntry->mChildren)
  727. {
  728. if (Path::comparePathElem(curElem, child->elementName))
  729. {
  730. idx++;
  731. current = child;
  732. break;
  733. }
  734. }
  735. }
  736. else // Found file
  737. {
  738. // If this is next to last element, next entry is assumed to be a sub-resource name, which we ignore
  739. if (idx == (numElems - 1))
  740. return current;
  741. else
  742. break; // Not a valid path
  743. }
  744. }
  745. return nullptr;
  746. }
  747. bool ProjectLibrary::isSubresource(const Path& path) const
  748. {
  749. UINT32 numElems = path.getNumDirectories() + (path.isFile() ? 1 : 0);
  750. if (numElems <= 1)
  751. return false;
  752. Path filePath = path;
  753. filePath.makeParent();
  754. LibraryEntry* entry = findEntry(filePath);
  755. if (entry != nullptr && entry->type == LibraryEntryType::File)
  756. return true;
  757. return false;
  758. }
  759. SPtr<ProjectResourceMeta> ProjectLibrary::findResourceMeta(const Path& path) const
  760. {
  761. UINT32 numElems = path.getNumDirectories() + (path.isFile() ? 1 : 0);
  762. // Check if it is a subresource path
  763. if(numElems > 1)
  764. {
  765. Path filePath = path;
  766. filePath.makeParent();
  767. LibraryEntry* entry = findEntry(filePath);
  768. if (entry == nullptr)
  769. return nullptr;
  770. // Entry is a subresource
  771. if (entry->type == LibraryEntryType::File)
  772. {
  773. FileEntry* fileEntry = static_cast<FileEntry*>(entry);
  774. if (fileEntry->meta == nullptr)
  775. return nullptr;
  776. auto& resourceMetas = fileEntry->meta->getResourceMetaData();
  777. for(auto& resMeta : resourceMetas)
  778. {
  779. if (resMeta->getUniqueName() == path.getTail())
  780. return resMeta;
  781. }
  782. // Found the file but no subresource or meta information
  783. return nullptr;
  784. }
  785. else // Entry not a subresource
  786. {
  787. DirectoryEntry* dirEntry = static_cast<DirectoryEntry*>(entry);
  788. for (auto& child : dirEntry->mChildren)
  789. {
  790. if (Path::comparePathElem(path.getTail(), child->elementName))
  791. {
  792. if (child->type == LibraryEntryType::File)
  793. {
  794. FileEntry* fileEntry = static_cast<FileEntry*>(child);
  795. if (fileEntry->meta == nullptr)
  796. return nullptr;
  797. return fileEntry->meta->getResourceMetaData()[0];
  798. }
  799. }
  800. }
  801. return nullptr;
  802. }
  803. }
  804. // Not a subresource path, load directly
  805. {
  806. LibraryEntry* entry = findEntry(path);
  807. if (entry == nullptr || entry->type == LibraryEntryType::Directory)
  808. return nullptr;
  809. FileEntry* fileEntry = static_cast<FileEntry*>(entry);
  810. if (fileEntry->meta == nullptr)
  811. return nullptr;
  812. return fileEntry->meta->getResourceMetaData()[0];
  813. }
  814. }
  815. Path ProjectLibrary::uuidToPath(const UUID& uuid) const
  816. {
  817. auto iterFind = mUUIDToPath.find(uuid);
  818. if (iterFind != mUUIDToPath.end())
  819. return iterFind->second;
  820. return Path::BLANK;
  821. }
  822. void ProjectLibrary::createEntry(const HResource& resource, const Path& path)
  823. {
  824. if (resource == nullptr)
  825. return;
  826. Path assetPath = path;
  827. if (path.isAbsolute())
  828. {
  829. if (!getResourcesFolder().includes(path))
  830. return;
  831. assetPath = path.getRelative(getResourcesFolder());
  832. }
  833. deleteEntry(assetPath);
  834. resource->setName(path.getFilename(false));
  835. Path absPath = assetPath.getAbsolute(getResourcesFolder());
  836. Resources::instance().save(resource, absPath, false);
  837. checkForModifications(absPath);
  838. }
  839. void ProjectLibrary::saveEntry(const HResource& resource)
  840. {
  841. if (resource == nullptr)
  842. return;
  843. Path filePath = uuidToPath(resource.getUUID());
  844. if(filePath.isEmpty())
  845. {
  846. LOGWRN("Trying to save a resource that hasn't been registered with the project library. Call ProjectLibrary::create first.");
  847. return;
  848. }
  849. filePath.makeAbsolute(getResourcesFolder());
  850. Resources::instance().save(resource, filePath, true);
  851. checkForModifications(filePath);
  852. }
  853. void ProjectLibrary::createFolderEntry(const Path& path)
  854. {
  855. Path fullPath = path;
  856. if (fullPath.isAbsolute())
  857. {
  858. if (!mResourcesFolder.includes(fullPath))
  859. return;
  860. }
  861. else
  862. fullPath.makeAbsolute(mResourcesFolder);
  863. if (FileSystem::isDirectory(fullPath))
  864. return; // Already exists
  865. FileSystem::createDir(fullPath);
  866. Path parentPath = fullPath.getParent();
  867. DirectoryEntry* newEntryParent = nullptr;
  868. LibraryEntry* newEntryParentLib = findEntry(parentPath);
  869. if (newEntryParentLib != nullptr)
  870. {
  871. assert(newEntryParentLib->type == LibraryEntryType::Directory);
  872. newEntryParent = static_cast<DirectoryEntry*>(newEntryParentLib);
  873. }
  874. DirectoryEntry* newHierarchyParent = nullptr;
  875. if (newEntryParent == nullptr) // New path parent doesn't exist, so we need to create the hierarchy
  876. createInternalParentHierarchy(fullPath, &newHierarchyParent, &newEntryParent);
  877. addDirectoryInternal(newEntryParent, fullPath);
  878. }
  879. void ProjectLibrary::moveEntry(const Path& oldPath, const Path& newPath, bool overwrite)
  880. {
  881. Path oldFullPath = oldPath;
  882. if (!oldFullPath.isAbsolute())
  883. oldFullPath.makeAbsolute(mResourcesFolder);
  884. Path newFullPath = newPath;
  885. if (!newFullPath.isAbsolute())
  886. newFullPath.makeAbsolute(mResourcesFolder);
  887. Path parentPath = newFullPath.getParent();
  888. if (!FileSystem::isDirectory(parentPath))
  889. {
  890. LOGWRN("Move operation failed. Destination directory \"" + parentPath.toString() + "\" doesn't exist.");
  891. return;
  892. }
  893. if(FileSystem::isFile(oldFullPath) || FileSystem::isDirectory(oldFullPath))
  894. FileSystem::move(oldFullPath, newFullPath, overwrite);
  895. Path oldMetaPath = getMetaPath(oldFullPath);
  896. Path newMetaPath = getMetaPath(newFullPath);
  897. LibraryEntry* oldEntry = findEntry(oldFullPath);
  898. if(oldEntry != nullptr) // Moving from the Resources folder
  899. {
  900. // Moved outside of Resources, delete entry & meta file
  901. if (!mResourcesFolder.includes(newFullPath))
  902. {
  903. if(oldEntry->type == LibraryEntryType::File)
  904. deleteResourceInternal(static_cast<FileEntry*>(oldEntry));
  905. else if(oldEntry->type == LibraryEntryType::Directory)
  906. deleteDirectoryInternal(static_cast<DirectoryEntry*>(oldEntry));
  907. }
  908. else // Just moving internally
  909. {
  910. onEntryRemoved(oldEntry->path);
  911. FileEntry* fileEntry = nullptr;
  912. if (oldEntry->type == LibraryEntryType::File)
  913. {
  914. fileEntry = static_cast<FileEntry*>(oldEntry);
  915. removeDependencies(fileEntry);
  916. // Update uuid <-> path mapping
  917. if(fileEntry->meta != nullptr)
  918. {
  919. auto& resourceMetas = fileEntry->meta->getResourceMetaData();
  920. if (resourceMetas.size() > 0)
  921. {
  922. mUUIDToPath[resourceMetas[0]->getUUID()] = newFullPath;
  923. for (UINT32 i = 1; i < (UINT32)resourceMetas.size(); i++)
  924. {
  925. SPtr<ProjectResourceMeta> resMeta = resourceMetas[i];
  926. const UUID& UUID = resMeta->getUUID();
  927. mUUIDToPath[UUID] = newFullPath + resMeta->getUniqueName();
  928. }
  929. }
  930. }
  931. }
  932. if(FileSystem::isFile(oldMetaPath))
  933. FileSystem::move(oldMetaPath, newMetaPath);
  934. DirectoryEntry* parent = oldEntry->parent;
  935. auto findIter = std::find(parent->mChildren.begin(), parent->mChildren.end(), oldEntry);
  936. if(findIter != parent->mChildren.end())
  937. parent->mChildren.erase(findIter);
  938. Path parentPath = newFullPath.getParent();
  939. DirectoryEntry* newEntryParent = nullptr;
  940. LibraryEntry* newEntryParentLib = findEntry(parentPath);
  941. if(newEntryParentLib != nullptr)
  942. {
  943. assert(newEntryParentLib->type == LibraryEntryType::Directory);
  944. newEntryParent = static_cast<DirectoryEntry*>(newEntryParentLib);
  945. }
  946. DirectoryEntry* newHierarchyParent = nullptr;
  947. if(newEntryParent == nullptr) // New path parent doesn't exist, so we need to create the hierarchy
  948. createInternalParentHierarchy(newFullPath, &newHierarchyParent, &newEntryParent);
  949. newEntryParent->mChildren.push_back(oldEntry);
  950. oldEntry->parent = newEntryParent;
  951. oldEntry->path = newFullPath;
  952. oldEntry->elementName = newFullPath.getTail();
  953. if(oldEntry->type == LibraryEntryType::Directory) // Update child paths
  954. {
  955. Stack<LibraryEntry*> todo;
  956. todo.push(oldEntry);
  957. while(!todo.empty())
  958. {
  959. LibraryEntry* curEntry = todo.top();
  960. todo.pop();
  961. DirectoryEntry* curDirEntry = static_cast<DirectoryEntry*>(curEntry);
  962. for(auto& child : curDirEntry->mChildren)
  963. {
  964. child->path = child->parent->path;
  965. child->path.append(child->elementName);
  966. if(child->type == LibraryEntryType::Directory)
  967. todo.push(child);
  968. }
  969. }
  970. }
  971. onEntryAdded(oldEntry->path);
  972. if (fileEntry != nullptr)
  973. {
  974. reimportDependants(oldFullPath);
  975. reimportDependants(newFullPath);
  976. }
  977. }
  978. }
  979. else // Moving from outside of the Resources folder (likely adding a new resource)
  980. {
  981. checkForModifications(newFullPath);
  982. }
  983. }
  984. void ProjectLibrary::copyEntry(const Path& oldPath, const Path& newPath, bool overwrite)
  985. {
  986. Path oldFullPath = oldPath;
  987. if (!oldFullPath.isAbsolute())
  988. oldFullPath.makeAbsolute(mResourcesFolder);
  989. Path newFullPath = newPath;
  990. if (!newFullPath.isAbsolute())
  991. newFullPath.makeAbsolute(mResourcesFolder);
  992. if (!FileSystem::exists(oldFullPath))
  993. return;
  994. FileSystem::copy(oldFullPath, newFullPath, overwrite);
  995. // Copying a file/folder outside of the Resources folder, no special handling needed
  996. if (!mResourcesFolder.includes(newFullPath))
  997. return;
  998. Path parentPath = newFullPath.getParent();
  999. DirectoryEntry* newEntryParent = nullptr;
  1000. LibraryEntry* newEntryParentLib = findEntry(parentPath);
  1001. if (newEntryParentLib != nullptr)
  1002. {
  1003. assert(newEntryParentLib->type == LibraryEntryType::Directory);
  1004. newEntryParent = static_cast<DirectoryEntry*>(newEntryParentLib);
  1005. }
  1006. // If the source is outside of Resources folder, just plain import the copy
  1007. LibraryEntry* oldEntry = findEntry(oldFullPath);
  1008. if (oldEntry == nullptr)
  1009. {
  1010. checkForModifications(newFullPath);
  1011. return;
  1012. }
  1013. // Both source and destination are within Resources folder, need to preserve import options on the copies
  1014. if (FileSystem::isFile(newFullPath))
  1015. {
  1016. assert(oldEntry->type == LibraryEntryType::File);
  1017. FileEntry* oldResEntry = static_cast<FileEntry*>(oldEntry);
  1018. SPtr<ImportOptions> importOptions;
  1019. if (oldResEntry->meta != nullptr)
  1020. importOptions = oldResEntry->meta->getImportOptions();
  1021. addResourceInternal(newEntryParent, newFullPath, importOptions, true);
  1022. }
  1023. else
  1024. {
  1025. assert(oldEntry->type == LibraryEntryType::File);
  1026. DirectoryEntry* oldDirEntry = static_cast<DirectoryEntry*>(oldEntry);
  1027. DirectoryEntry* newDirEntry = addDirectoryInternal(newEntryParent, newFullPath);
  1028. Stack<std::tuple<DirectoryEntry*, DirectoryEntry*>> todo;
  1029. todo.push(std::make_tuple(oldDirEntry, newDirEntry));
  1030. while (!todo.empty())
  1031. {
  1032. auto current = todo.top();
  1033. todo.pop();
  1034. DirectoryEntry* sourceDir = std::get<0>(current);
  1035. DirectoryEntry* destDir = std::get<1>(current);
  1036. for (auto& child : sourceDir->mChildren)
  1037. {
  1038. Path childDestPath = destDir->path;
  1039. childDestPath.append(child->path.getTail());
  1040. if (child->type == LibraryEntryType::File)
  1041. {
  1042. FileEntry* childResEntry = static_cast<FileEntry*>(child);
  1043. SPtr<ImportOptions> importOptions;
  1044. if (childResEntry->meta != nullptr)
  1045. importOptions = childResEntry->meta->getImportOptions();
  1046. addResourceInternal(destDir, childDestPath, importOptions, true);
  1047. }
  1048. else // Directory
  1049. {
  1050. DirectoryEntry* childSourceDirEntry = static_cast<DirectoryEntry*>(child);
  1051. DirectoryEntry* childDestDirEntry = addDirectoryInternal(destDir, childDestPath);
  1052. todo.push(std::make_tuple(childSourceDirEntry, childDestDirEntry));
  1053. }
  1054. }
  1055. }
  1056. }
  1057. }
  1058. void ProjectLibrary::deleteEntry(const Path& path)
  1059. {
  1060. Path fullPath = path;
  1061. if (!fullPath.isAbsolute())
  1062. fullPath.makeAbsolute(mResourcesFolder);
  1063. if(FileSystem::exists(fullPath))
  1064. FileSystem::remove(fullPath);
  1065. LibraryEntry* entry = findEntry(fullPath);
  1066. if(entry != nullptr)
  1067. {
  1068. if(entry->type == LibraryEntryType::File)
  1069. deleteResourceInternal(static_cast<FileEntry*>(entry));
  1070. else if(entry->type == LibraryEntryType::Directory)
  1071. deleteDirectoryInternal(static_cast<DirectoryEntry*>(entry));
  1072. }
  1073. }
  1074. void ProjectLibrary::reimport(const Path& path, const SPtr<ImportOptions>& importOptions, bool forceReimport)
  1075. {
  1076. LibraryEntry* entry = findEntry(path);
  1077. if (entry != nullptr)
  1078. {
  1079. if (entry->type == LibraryEntryType::File)
  1080. {
  1081. FileEntry* resEntry = static_cast<FileEntry*>(entry);
  1082. reimportResourceInternal(resEntry, importOptions, forceReimport);
  1083. }
  1084. }
  1085. }
  1086. void ProjectLibrary::setIncludeInBuild(const Path& path, bool include)
  1087. {
  1088. LibraryEntry* entry = findEntry(path);
  1089. if (entry == nullptr || entry->type == LibraryEntryType::Directory)
  1090. return;
  1091. FileEntry* resEntry = static_cast<FileEntry*>(entry);
  1092. if (resEntry->meta == nullptr)
  1093. return;
  1094. resEntry->meta->setIncludeInBuild(include);
  1095. Path metaPath = resEntry->path;
  1096. metaPath.setFilename(metaPath.getFilename() + ".meta");
  1097. FileEncoder fs(metaPath);
  1098. fs.encode(resEntry->meta.get());
  1099. }
  1100. void ProjectLibrary::setUserData(const Path& path, const SPtr<IReflectable>& userData)
  1101. {
  1102. LibraryEntry* entry = findEntry(path);
  1103. if (entry == nullptr || entry->type == LibraryEntryType::Directory)
  1104. return;
  1105. FileEntry* fileEntry = static_cast<FileEntry*>(entry);
  1106. SPtr<ProjectResourceMeta> resMeta = findResourceMeta(path);
  1107. if (resMeta == nullptr)
  1108. return;
  1109. resMeta->mUserData = userData;
  1110. Path metaPath = fileEntry->path;
  1111. metaPath.setFilename(metaPath.getFilename() + ".meta");
  1112. FileEncoder fs(metaPath);
  1113. fs.encode(fileEntry->meta.get());
  1114. }
  1115. Vector<ProjectLibrary::FileEntry*> ProjectLibrary::getResourcesForBuild() const
  1116. {
  1117. Vector<FileEntry*> output;
  1118. Stack<DirectoryEntry*> todo;
  1119. todo.push(mRootEntry);
  1120. while (!todo.empty())
  1121. {
  1122. DirectoryEntry* directory = todo.top();
  1123. todo.pop();
  1124. for (auto& child : directory->mChildren)
  1125. {
  1126. if (child->type == LibraryEntryType::File)
  1127. {
  1128. FileEntry* resEntry = static_cast<FileEntry*>(child);
  1129. if (resEntry->meta != nullptr && resEntry->meta->getIncludeInBuild())
  1130. output.push_back(resEntry);
  1131. }
  1132. else if (child->type == LibraryEntryType::Directory)
  1133. {
  1134. todo.push(static_cast<DirectoryEntry*>(child));
  1135. }
  1136. }
  1137. }
  1138. return output;
  1139. }
  1140. HResource ProjectLibrary::load(const Path& path)
  1141. {
  1142. SPtr<ProjectResourceMeta> meta = findResourceMeta(path);
  1143. if (meta == nullptr)
  1144. return HResource();
  1145. ResourceLoadFlags loadFlags = ResourceLoadFlag::Default | ResourceLoadFlag::KeepSourceData;
  1146. const UUID& resUUID = meta->getUUID();
  1147. return gResources().loadFromUUID(resUUID, false, loadFlags);
  1148. }
  1149. void ProjectLibrary::createInternalParentHierarchy(const Path& fullPath, DirectoryEntry** newHierarchyRoot, DirectoryEntry** newHierarchyLeaf)
  1150. {
  1151. Path parentPath = fullPath;
  1152. DirectoryEntry* newEntryParent = nullptr;
  1153. Stack<Path> parentPaths;
  1154. do
  1155. {
  1156. Path newParentPath = parentPath.getParent();
  1157. if(newParentPath == parentPath)
  1158. break;
  1159. LibraryEntry* newEntryParentLib = findEntry(newParentPath);
  1160. if(newEntryParentLib != nullptr)
  1161. {
  1162. assert(newEntryParentLib->type == LibraryEntryType::Directory);
  1163. newEntryParent = static_cast<DirectoryEntry*>(newEntryParentLib);
  1164. break;
  1165. }
  1166. parentPaths.push(newParentPath);
  1167. parentPath = newParentPath;
  1168. } while (true);
  1169. assert(newEntryParent != nullptr); // Must exist
  1170. if(newHierarchyRoot != nullptr)
  1171. *newHierarchyRoot = newEntryParent;
  1172. while(!parentPaths.empty())
  1173. {
  1174. Path curPath = parentPaths.top();
  1175. parentPaths.pop();
  1176. newEntryParent = addDirectoryInternal(newEntryParent, curPath);
  1177. }
  1178. if(newHierarchyLeaf != nullptr)
  1179. *newHierarchyLeaf = newEntryParent;
  1180. }
  1181. Path ProjectLibrary::getMetaPath(const Path& path) const
  1182. {
  1183. Path metaPath = path;
  1184. metaPath.setFilename(metaPath.getFilename() + ".meta");
  1185. return metaPath;
  1186. }
  1187. bool ProjectLibrary::isMeta(const Path& fullPath) const
  1188. {
  1189. return fullPath.getExtension() == ".meta";
  1190. }
  1191. bool ProjectLibrary::isNative(const Path& path) const
  1192. {
  1193. String extension = path.getExtension();
  1194. return extension == ".asset" || extension == ".prefab";
  1195. }
  1196. void ProjectLibrary::unloadLibrary()
  1197. {
  1198. if (!mIsLoaded)
  1199. return;
  1200. _finishQueuedImports(true);
  1201. mProjectFolder = Path::BLANK;
  1202. mResourcesFolder = Path::BLANK;
  1203. clearEntries();
  1204. mRootEntry = bs_new<DirectoryEntry>(mResourcesFolder, mResourcesFolder.getTail(), nullptr);
  1205. mDependencies.clear();
  1206. gResources().unregisterResourceManifest(mResourceManifest);
  1207. mResourceManifest = nullptr;
  1208. mIsLoaded = false;
  1209. }
  1210. void ProjectLibrary::makeEntriesRelative()
  1211. {
  1212. // Make all paths relative before saving
  1213. std::function<void(LibraryEntry*, const Path&)> makeRelative =
  1214. [&](LibraryEntry* entry, const Path& root)
  1215. {
  1216. entry->path.makeRelative(root);
  1217. if (entry->type == LibraryEntryType::Directory)
  1218. {
  1219. DirectoryEntry* dirEntry = static_cast<DirectoryEntry*>(entry);
  1220. for (auto& child : dirEntry->mChildren)
  1221. makeRelative(child, root);
  1222. }
  1223. };
  1224. Path root = getResourcesFolder();
  1225. makeRelative(mRootEntry, root);
  1226. }
  1227. void ProjectLibrary::makeEntriesAbsolute()
  1228. {
  1229. std::function<void(LibraryEntry*, const Path&)> makeAbsolute =
  1230. [&](LibraryEntry* entry, const Path& root)
  1231. {
  1232. entry->path.makeAbsolute(root);
  1233. if (entry->type == LibraryEntryType::Directory)
  1234. {
  1235. DirectoryEntry* dirEntry = static_cast<DirectoryEntry*>(entry);
  1236. for (auto& child : dirEntry->mChildren)
  1237. makeAbsolute(child, root);
  1238. }
  1239. };
  1240. Path root = getResourcesFolder();
  1241. makeAbsolute(mRootEntry, root);
  1242. }
  1243. void ProjectLibrary::saveLibrary()
  1244. {
  1245. if (!mIsLoaded)
  1246. return;
  1247. // Make all paths relative before saving
  1248. makeEntriesRelative();
  1249. SPtr<ProjectLibraryEntries> libEntries = ProjectLibraryEntries::create(*mRootEntry);
  1250. Path libraryEntriesPath = mProjectFolder;
  1251. libraryEntriesPath.append(PROJECT_INTERNAL_DIR);
  1252. libraryEntriesPath.append(LIBRARY_ENTRIES_FILENAME);
  1253. FileEncoder fs(libraryEntriesPath);
  1254. fs.encode(libEntries.get());
  1255. // Restore absolute entry paths
  1256. makeEntriesAbsolute();
  1257. Path resourceManifestPath = mProjectFolder;
  1258. resourceManifestPath.append(PROJECT_INTERNAL_DIR);
  1259. resourceManifestPath.append(RESOURCE_MANIFEST_FILENAME);
  1260. ResourceManifest::save(mResourceManifest, resourceManifestPath, mProjectFolder);
  1261. }
  1262. void ProjectLibrary::loadLibrary()
  1263. {
  1264. unloadLibrary();
  1265. mProjectFolder = gEditorApplication().getProjectPath();
  1266. mResourcesFolder = mProjectFolder;
  1267. mResourcesFolder.append(RESOURCES_DIR);
  1268. mRootEntry = bs_new<DirectoryEntry>(mResourcesFolder, mResourcesFolder.getTail(), nullptr);
  1269. Path libraryEntriesPath = mProjectFolder;
  1270. libraryEntriesPath.append(PROJECT_INTERNAL_DIR);
  1271. libraryEntriesPath.append(LIBRARY_ENTRIES_FILENAME);
  1272. if(FileSystem::exists(libraryEntriesPath))
  1273. {
  1274. FileDecoder fs(libraryEntriesPath);
  1275. SPtr<ProjectLibraryEntries> libEntries = std::static_pointer_cast<ProjectLibraryEntries>(fs.decode());
  1276. *mRootEntry = libEntries->getRootEntry();
  1277. for(auto& child : mRootEntry->mChildren)
  1278. child->parent = mRootEntry;
  1279. mRootEntry->parent = nullptr;
  1280. }
  1281. // Entries are stored relative to project folder, but we want their absolute paths now
  1282. makeEntriesAbsolute();
  1283. // Load resource manifest
  1284. Path resourceManifestPath = mProjectFolder;
  1285. resourceManifestPath.append(PROJECT_INTERNAL_DIR);
  1286. resourceManifestPath.append(RESOURCE_MANIFEST_FILENAME);
  1287. if (FileSystem::exists(resourceManifestPath))
  1288. mResourceManifest = ResourceManifest::load(resourceManifestPath, mProjectFolder);
  1289. else
  1290. mResourceManifest = ResourceManifest::create("ProjectLibrary");
  1291. gResources().registerResourceManifest(mResourceManifest);
  1292. // Load all meta files
  1293. Stack<DirectoryEntry*> todo;
  1294. todo.push(mRootEntry);
  1295. Vector<LibraryEntry*> deletedEntries;
  1296. while(!todo.empty())
  1297. {
  1298. DirectoryEntry* curDir = todo.top();
  1299. todo.pop();
  1300. for(auto& child : curDir->mChildren)
  1301. {
  1302. if(child->type == LibraryEntryType::File)
  1303. {
  1304. FileEntry* resEntry = static_cast<FileEntry*>(child);
  1305. if (FileSystem::isFile(resEntry->path))
  1306. {
  1307. if (resEntry->meta == nullptr)
  1308. {
  1309. Path metaPath = resEntry->path;
  1310. metaPath.setFilename(metaPath.getFilename() + ".meta");
  1311. if (FileSystem::isFile(metaPath))
  1312. {
  1313. FileDecoder fs(metaPath);
  1314. SPtr<IReflectable> loadedMeta = fs.decode();
  1315. if (loadedMeta != nullptr && loadedMeta->isDerivedFrom(ProjectFileMeta::getRTTIStatic()))
  1316. {
  1317. SPtr<ProjectFileMeta> fileMeta = std::static_pointer_cast<ProjectFileMeta>(loadedMeta);
  1318. resEntry->meta = fileMeta;
  1319. }
  1320. }
  1321. }
  1322. if (resEntry->meta != nullptr)
  1323. {
  1324. auto& resourceMetas = resEntry->meta->getResourceMetaData();
  1325. if (resourceMetas.size() > 0)
  1326. {
  1327. mUUIDToPath[resourceMetas[0]->getUUID()] = resEntry->path;
  1328. for (UINT32 i = 1; i < (UINT32)resourceMetas.size(); i++)
  1329. {
  1330. SPtr<ProjectResourceMeta> entry = resourceMetas[i];
  1331. mUUIDToPath[entry->getUUID()] = resEntry->path + entry->getUniqueName();
  1332. }
  1333. }
  1334. }
  1335. addDependencies(resEntry);
  1336. }
  1337. else
  1338. deletedEntries.push_back(resEntry);
  1339. }
  1340. else if(child->type == LibraryEntryType::Directory)
  1341. {
  1342. if (FileSystem::isDirectory(child->path))
  1343. todo.push(static_cast<DirectoryEntry*>(child));
  1344. else
  1345. deletedEntries.push_back(child);
  1346. }
  1347. }
  1348. }
  1349. // Remove entries that no longer have corresponding files
  1350. for (auto& deletedEntry : deletedEntries)
  1351. {
  1352. if (deletedEntry->type == LibraryEntryType::File)
  1353. {
  1354. FileEntry* resEntry = static_cast<FileEntry*>(deletedEntry);
  1355. deleteResourceInternal(resEntry);
  1356. }
  1357. else
  1358. {
  1359. DirectoryEntry* dirEntry = static_cast<DirectoryEntry*>(deletedEntry);
  1360. deleteDirectoryInternal(dirEntry);
  1361. }
  1362. }
  1363. // Clean up internal library folder from obsolete files
  1364. Path internalResourcesFolder = mProjectFolder;
  1365. internalResourcesFolder.append(INTERNAL_RESOURCES_DIR);
  1366. if (FileSystem::exists(internalResourcesFolder))
  1367. {
  1368. Vector<Path> toDelete;
  1369. auto processFile = [&](const Path& file)
  1370. {
  1371. UUID uuid = UUID(file.getFilename(false));
  1372. if (mUUIDToPath.find(uuid) == mUUIDToPath.end())
  1373. {
  1374. mResourceManifest->unregisterResource(uuid);
  1375. toDelete.push_back(file);
  1376. }
  1377. return true;
  1378. };
  1379. FileSystem::iterate(internalResourcesFolder, processFile);
  1380. for (auto& entry : toDelete)
  1381. FileSystem::remove(entry);
  1382. }
  1383. mIsLoaded = true;
  1384. }
  1385. void ProjectLibrary::clearEntries()
  1386. {
  1387. if (mRootEntry == nullptr)
  1388. return;
  1389. std::function<void(LibraryEntry*)> deleteRecursive =
  1390. [&](LibraryEntry* entry)
  1391. {
  1392. if (entry->type == LibraryEntryType::Directory)
  1393. {
  1394. DirectoryEntry* dirEntry = static_cast<DirectoryEntry*>(entry);
  1395. for (auto& child : dirEntry->mChildren)
  1396. deleteRecursive(child);
  1397. }
  1398. bs_delete(entry);
  1399. };
  1400. assert(mQueuedImports.empty());
  1401. deleteRecursive(mRootEntry);
  1402. mRootEntry = nullptr;
  1403. }
  1404. Vector<Path> ProjectLibrary::getImportDependencies(const FileEntry* entry)
  1405. {
  1406. Vector<Path> output;
  1407. if (entry->meta == nullptr)
  1408. return output;
  1409. auto& resourceMetas = entry->meta->getResourceMetaData();
  1410. for(auto& resMeta : resourceMetas)
  1411. {
  1412. if (resMeta->getTypeID() == TID_Shader)
  1413. {
  1414. SPtr<ShaderMetaData> metaData = std::static_pointer_cast<ShaderMetaData>(resMeta->getResourceMetaData());
  1415. for (auto& include : metaData->includes)
  1416. output.push_back(include);
  1417. }
  1418. }
  1419. return output;
  1420. }
  1421. void ProjectLibrary::addDependencies(const FileEntry* entry)
  1422. {
  1423. Vector<Path> dependencies = getImportDependencies(entry);
  1424. for (auto& dependency : dependencies)
  1425. mDependencies[dependency].push_back(entry->path);
  1426. }
  1427. void ProjectLibrary::removeDependencies(const FileEntry* entry)
  1428. {
  1429. Vector<Path> dependencies = getImportDependencies(entry);
  1430. for (auto& dependency : dependencies)
  1431. {
  1432. Vector<Path>& curDependencies = mDependencies[dependency];
  1433. auto iterRemove = std::remove_if(curDependencies.begin(), curDependencies.end(),
  1434. [&](const Path& x)
  1435. {
  1436. return x == entry->path;
  1437. });
  1438. curDependencies.erase(iterRemove, curDependencies.end());
  1439. }
  1440. }
  1441. void ProjectLibrary::reimportDependants(const Path& entryPath)
  1442. {
  1443. auto iterFind = mDependencies.find(entryPath);
  1444. if (iterFind == mDependencies.end())
  1445. return;
  1446. // Make a copy since we might modify this list during reimport
  1447. Vector<Path> dependencies = iterFind->second;
  1448. for (auto& dependency : dependencies)
  1449. {
  1450. LibraryEntry* entry = findEntry(dependency);
  1451. if (entry != nullptr && entry->type == LibraryEntryType::File)
  1452. {
  1453. FileEntry* resEntry = static_cast<FileEntry*>(entry);
  1454. SPtr<ImportOptions> importOptions;
  1455. if (resEntry->meta != nullptr)
  1456. importOptions = resEntry->meta->getImportOptions();
  1457. reimportResourceInternal(resEntry, importOptions, true);
  1458. }
  1459. }
  1460. }
  1461. BS_ED_EXPORT ProjectLibrary& gProjectLibrary()
  1462. {
  1463. return ProjectLibrary::instance();
  1464. }
  1465. }