ResourceFilesystem.cpp 9.7 KB

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