ResourceFilesystem.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  1. // Copyright (C) 2009-2021, Panagiotis Christopoulos Charitos and contributors.
  2. // All rights reserved.
  3. // Code licensed under the BSD License.
  4. // http://www.anki3d.org/LICENSE
  5. #include <AnKi/Resource/ResourceFilesystem.h>
  6. #include <AnKi/Util/Filesystem.h>
  7. #include <AnKi/Core/ConfigSet.h>
  8. #include <AnKi/Util/Tracer.h>
  9. #include <ZLib/contrib/minizip/unzip.h>
  10. namespace anki
  11. {
  12. /// C resource file
  13. class CResourceFile final : public ResourceFile
  14. {
  15. public:
  16. File m_file;
  17. CResourceFile(GenericMemoryPoolAllocator<U8> alloc)
  18. : ResourceFile(alloc)
  19. {
  20. }
  21. ANKI_USE_RESULT Error read(void* buff, PtrSize size) override
  22. {
  23. ANKI_TRACE_SCOPED_EVENT(RSRC_FILE_READ);
  24. return m_file.read(buff, size);
  25. }
  26. ANKI_USE_RESULT Error readAllText(StringAuto& out) override
  27. {
  28. ANKI_TRACE_SCOPED_EVENT(RSRC_FILE_READ);
  29. return m_file.readAllText(out);
  30. }
  31. ANKI_USE_RESULT Error readU32(U32& u) override
  32. {
  33. ANKI_TRACE_SCOPED_EVENT(RSRC_FILE_READ);
  34. return m_file.readU32(u);
  35. }
  36. ANKI_USE_RESULT Error readF32(F32& f) override
  37. {
  38. ANKI_TRACE_SCOPED_EVENT(RSRC_FILE_READ);
  39. return m_file.readF32(f);
  40. }
  41. ANKI_USE_RESULT Error seek(PtrSize offset, FileSeekOrigin origin) override
  42. {
  43. return m_file.seek(offset, origin);
  44. }
  45. PtrSize getSize() const override
  46. {
  47. return m_file.getSize();
  48. }
  49. };
  50. /// ZIP file
  51. class ZipResourceFile final : public ResourceFile
  52. {
  53. public:
  54. unzFile m_archive = nullptr;
  55. PtrSize m_size = 0;
  56. ZipResourceFile(GenericMemoryPoolAllocator<U8> alloc)
  57. : ResourceFile(alloc)
  58. {
  59. }
  60. ~ZipResourceFile()
  61. {
  62. if(m_archive)
  63. {
  64. // It's open
  65. unzClose(m_archive);
  66. m_archive = nullptr;
  67. m_size = 0;
  68. }
  69. }
  70. ANKI_USE_RESULT Error open(const CString& archive, const CString& archivedFname)
  71. {
  72. // Open archive
  73. m_archive = unzOpen(&archive[0]);
  74. if(m_archive == nullptr)
  75. {
  76. ANKI_RESOURCE_LOGE("Failed to open archive");
  77. return Error::FILE_ACCESS;
  78. }
  79. // Locate archived
  80. const int caseSensitive = 1;
  81. if(unzLocateFile(m_archive, &archivedFname[0], caseSensitive) != UNZ_OK)
  82. {
  83. ANKI_RESOURCE_LOGE("Failed to locate file in archive");
  84. return Error::FILE_ACCESS;
  85. }
  86. // Open file
  87. if(unzOpenCurrentFile(m_archive) != UNZ_OK)
  88. {
  89. ANKI_RESOURCE_LOGE("unzOpenCurrentFile() failed");
  90. return Error::FILE_ACCESS;
  91. }
  92. // Get size just in case
  93. unz_file_info zinfo;
  94. zinfo.uncompressed_size = 0;
  95. unzGetCurrentFileInfo(m_archive, &zinfo, nullptr, 0, nullptr, 0, nullptr, 0);
  96. m_size = zinfo.uncompressed_size;
  97. ANKI_ASSERT(m_size != 0);
  98. return Error::NONE;
  99. }
  100. void close()
  101. {
  102. if(m_archive)
  103. {
  104. unzClose(m_archive);
  105. m_archive = nullptr;
  106. m_size = 0;
  107. }
  108. }
  109. ANKI_USE_RESULT Error read(void* buff, PtrSize size) override
  110. {
  111. ANKI_TRACE_SCOPED_EVENT(RSRC_FILE_READ);
  112. I64 readSize = unzReadCurrentFile(m_archive, buff, U32(size));
  113. if(I64(size) != readSize)
  114. {
  115. ANKI_RESOURCE_LOGE("File read failed");
  116. return Error::FILE_ACCESS;
  117. }
  118. return Error::NONE;
  119. }
  120. ANKI_USE_RESULT Error readAllText(StringAuto& out) override
  121. {
  122. ANKI_ASSERT(m_size);
  123. out.create('?', m_size);
  124. return read(&out[0], m_size);
  125. }
  126. ANKI_USE_RESULT Error readU32(U32& u) override
  127. {
  128. // Assume machine and file have same endianness
  129. ANKI_CHECK(read(&u, sizeof(u)));
  130. return Error::NONE;
  131. }
  132. ANKI_USE_RESULT Error readF32(F32& u) override
  133. {
  134. // Assume machine and file have same endianness
  135. ANKI_CHECK(read(&u, sizeof(u)));
  136. return Error::NONE;
  137. }
  138. ANKI_USE_RESULT Error seek(PtrSize offset, FileSeekOrigin origin) override
  139. {
  140. // Rewind if needed
  141. if(origin == FileSeekOrigin::BEGINNING)
  142. {
  143. if(unzCloseCurrentFile(m_archive) || unzOpenCurrentFile(m_archive))
  144. {
  145. ANKI_RESOURCE_LOGE("Rewind failed");
  146. return Error::FUNCTION_FAILED;
  147. }
  148. }
  149. // Move forward by reading dummy data
  150. Array<char, 128> buff;
  151. while(offset != 0)
  152. {
  153. PtrSize toRead = min<PtrSize>(offset, sizeof(buff));
  154. ANKI_CHECK(read(&buff[0], toRead));
  155. offset -= toRead;
  156. }
  157. return Error::NONE;
  158. }
  159. PtrSize getSize() const override
  160. {
  161. ANKI_ASSERT(m_size > 0);
  162. return m_size;
  163. }
  164. };
  165. ResourceFilesystem::~ResourceFilesystem()
  166. {
  167. for(Path& p : m_paths)
  168. {
  169. p.m_files.destroy(m_alloc);
  170. p.m_path.destroy(m_alloc);
  171. }
  172. m_paths.destroy(m_alloc);
  173. m_cacheDir.destroy(m_alloc);
  174. }
  175. Error ResourceFilesystem::init(const ConfigSet& config, const CString& cacheDir)
  176. {
  177. StringListAuto paths(m_alloc);
  178. paths.splitString(config.getString("rsrc_dataPaths"), ':');
  179. StringListAuto excludedStrings(m_alloc);
  180. excludedStrings.splitString(config.getString("rsrc_dataPathExcludedStrings"), ':');
  181. // Workaround the fact that : is used in drives in Windows
  182. #if ANKI_OS_WINDOWS
  183. StringListAuto paths2(m_alloc);
  184. StringListAuto::Iterator it = paths.getBegin();
  185. while(it != paths.getEnd())
  186. {
  187. const String& s = *it;
  188. StringListAuto::Iterator it2 = it + 1;
  189. if(s.getLength() == 1 && (s[0] >= 'a' && s[0] <= 'z') || (s[0] >= 'A' && s[0] <= 'Z') && it2 != paths.getEnd())
  190. {
  191. paths2.pushBackSprintf("%s:%s", s.cstr(), it2->cstr());
  192. ++it;
  193. }
  194. else
  195. {
  196. paths2.pushBack(s);
  197. }
  198. ++it;
  199. }
  200. paths.destroy();
  201. paths = std::move(paths2);
  202. #endif
  203. if(paths.getSize() < 1)
  204. {
  205. ANKI_RESOURCE_LOGE("Config option \"rsrc_dataPaths\" is empty");
  206. return Error::USER_DATA;
  207. }
  208. #if ANKI_OS_ANDROID
  209. // Add the files of the .apk
  210. ANKI_CHECK(addNewPath("APK package", excludedStrings, true));
  211. #endif
  212. for(auto& path : paths)
  213. {
  214. ANKI_CHECK(addNewPath(path.toCString(), excludedStrings));
  215. }
  216. addCachePath(cacheDir);
  217. return Error::NONE;
  218. }
  219. void ResourceFilesystem::addCachePath(const CString& path)
  220. {
  221. Path p;
  222. p.m_path.create(m_alloc, path);
  223. p.m_isCache = true;
  224. m_paths.emplaceBack(m_alloc, std::move(p));
  225. }
  226. Error ResourceFilesystem::addNewPath(const CString& filepath, const StringListAuto& excludedStrings, Bool special)
  227. {
  228. U32 fileCount = 0; // Count files manually because it's slower to get that number from the list
  229. static const CString extension(".ankizip");
  230. auto rejectPath = [&](CString p) -> Bool {
  231. for(const String& s : excludedStrings)
  232. {
  233. if(p.find(s) != CString::NPOS)
  234. {
  235. return true;
  236. }
  237. }
  238. return false;
  239. };
  240. PtrSize pos;
  241. Path path;
  242. if(special)
  243. {
  244. // Android apk, read the file that contains the directory structure
  245. // Read the file
  246. File dirStructure;
  247. ANKI_CHECK(dirStructure.open("DirStructure.txt", FileOpenFlag::READ | FileOpenFlag::SPECIAL));
  248. StringAuto txt(m_alloc);
  249. ANKI_CHECK(dirStructure.readAllText(txt));
  250. StringListAuto filenames(m_alloc);
  251. filenames.splitString(txt, '\n');
  252. // Create the Path
  253. for(const String& filename : filenames)
  254. {
  255. if(!rejectPath(filename))
  256. {
  257. path.m_files.pushBack(m_alloc, filename);
  258. ++fileCount;
  259. }
  260. }
  261. path.m_isSpecial = true;
  262. }
  263. else if((pos = filepath.find(extension)) != CString::NPOS && pos == filepath.getLength() - extension.getLength())
  264. {
  265. // It's an archive
  266. // Open
  267. unzFile zfile = unzOpen(&filepath[0]);
  268. if(!zfile)
  269. {
  270. ANKI_RESOURCE_LOGE("Failed to open archive");
  271. return Error::FILE_ACCESS;
  272. }
  273. // List files
  274. if(unzGoToFirstFile(zfile) != UNZ_OK)
  275. {
  276. unzClose(zfile);
  277. ANKI_RESOURCE_LOGE("unzGoToFirstFile() failed. Empty archive?");
  278. return Error::FILE_ACCESS;
  279. }
  280. do
  281. {
  282. Array<char, 1024> filename;
  283. unz_file_info info;
  284. if(unzGetCurrentFileInfo(zfile, &info, &filename[0], filename.getSize(), nullptr, 0, nullptr, 0) != UNZ_OK)
  285. {
  286. unzClose(zfile);
  287. ANKI_RESOURCE_LOGE("unzGetCurrentFileInfo() failed");
  288. return Error::FILE_ACCESS;
  289. }
  290. const Bool itsADir = info.uncompressed_size == 0;
  291. if(!itsADir && !rejectPath(&filename[0]))
  292. {
  293. path.m_files.pushBackSprintf(m_alloc, "%s", &filename[0]);
  294. ++fileCount;
  295. }
  296. } while(unzGoToNextFile(zfile) == UNZ_OK);
  297. unzClose(zfile);
  298. path.m_isArchive = true;
  299. }
  300. else
  301. {
  302. // It's simple directory
  303. ANKI_CHECK(walkDirectoryTree(filepath, m_alloc, [&, this](const CString& fname, Bool isDir) -> Error {
  304. if(!isDir && !rejectPath(fname))
  305. {
  306. path.m_files.pushBackSprintf(m_alloc, "%s", fname.cstr());
  307. ++fileCount;
  308. }
  309. return Error::NONE;
  310. }));
  311. }
  312. ANKI_ASSERT(path.m_files.getSize() == fileCount);
  313. if(fileCount == 0)
  314. {
  315. ANKI_RESOURCE_LOGW("Ignoring empty resource path: %s", &filepath[0]);
  316. }
  317. else
  318. {
  319. path.m_path.sprintf(m_alloc, "%s", &filepath[0]);
  320. m_paths.emplaceFront(m_alloc, std::move(path));
  321. ANKI_RESOURCE_LOGI("Added new data path \"%s\" that contains %u files", &filepath[0], fileCount);
  322. }
  323. return Error::NONE;
  324. }
  325. Error ResourceFilesystem::openFile(const ResourceFilename& filename, ResourceFilePtr& filePtr)
  326. {
  327. ResourceFile* rfile = nullptr;
  328. Error err = Error::NONE;
  329. // Search for the fname in reverse order
  330. for(const Path& p : m_paths)
  331. {
  332. // Check if it's cache
  333. if(p.m_isCache)
  334. {
  335. StringAuto newFname(m_alloc);
  336. newFname.sprintf("%s/%s", &p.m_path[0], &filename[0]);
  337. if(fileExists(newFname.toCString()))
  338. {
  339. // In cache
  340. CResourceFile* file = m_alloc.newInstance<CResourceFile>(m_alloc);
  341. rfile = file;
  342. err = file->m_file.open(&newFname[0], FileOpenFlag::READ);
  343. }
  344. }
  345. else
  346. {
  347. // In data path or archive
  348. for(const String& pfname : p.m_files)
  349. {
  350. if(pfname != filename)
  351. {
  352. continue;
  353. }
  354. // Found
  355. if(p.m_isArchive)
  356. {
  357. ZipResourceFile* file = m_alloc.newInstance<ZipResourceFile>(m_alloc);
  358. rfile = file;
  359. err = file->open(p.m_path.toCString(), filename);
  360. }
  361. else
  362. {
  363. StringAuto newFname(m_alloc);
  364. if(!p.m_isSpecial)
  365. {
  366. newFname.sprintf("%s/%s", &p.m_path[0], &filename[0]);
  367. }
  368. else
  369. {
  370. newFname.sprintf("%s", &filename[0]);
  371. }
  372. CResourceFile* file = m_alloc.newInstance<CResourceFile>(m_alloc);
  373. rfile = file;
  374. FileOpenFlag fopenFlags = FileOpenFlag::READ;
  375. if(p.m_isSpecial)
  376. {
  377. fopenFlags |= FileOpenFlag::SPECIAL;
  378. }
  379. err = file->m_file.open(&newFname[0], fopenFlags);
  380. #if 0
  381. printf("Opening asset %s\n", &newFname[0]);
  382. #endif
  383. }
  384. }
  385. } // end if cache
  386. if(rfile)
  387. {
  388. break;
  389. }
  390. } // end for all paths
  391. if(err)
  392. {
  393. m_alloc.deleteInstance(rfile);
  394. return err;
  395. }
  396. // File not found? Try to find it outside the resource dirs
  397. if(!rfile && fileExists(filename))
  398. {
  399. CResourceFile* file = m_alloc.newInstance<CResourceFile>(m_alloc);
  400. err = file->m_file.open(filename, FileOpenFlag::READ);
  401. if(err)
  402. {
  403. m_alloc.deleteInstance(file);
  404. return err;
  405. }
  406. rfile = file;
  407. ANKI_RESOURCE_LOGW(
  408. "Loading resource outside the resource paths/archives. This is only OK for tools and debugging: %s",
  409. filename.cstr());
  410. }
  411. if(!rfile)
  412. {
  413. ANKI_RESOURCE_LOGE("File not found: %s", &filename[0]);
  414. return Error::USER_DATA;
  415. }
  416. // Done
  417. filePtr.reset(rfile);
  418. return Error::NONE;
  419. }
  420. } // end namespace anki