ResourceFilesystem.cpp 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  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. #if ANKI_OS_ANDROID
  11. # include <android_native_app_glue.h>
  12. #endif
  13. namespace anki {
  14. /// C resource file
  15. class CResourceFile final : public ResourceFile
  16. {
  17. public:
  18. File m_file;
  19. CResourceFile(GenericMemoryPoolAllocator<U8> alloc)
  20. : ResourceFile(alloc)
  21. {
  22. }
  23. Error read(void* buff, PtrSize size) override
  24. {
  25. ANKI_TRACE_SCOPED_EVENT(RSRC_FILE_READ);
  26. return m_file.read(buff, size);
  27. }
  28. Error readAllText(StringAuto& out) override
  29. {
  30. ANKI_TRACE_SCOPED_EVENT(RSRC_FILE_READ);
  31. return m_file.readAllText(out);
  32. }
  33. Error readU32(U32& u) override
  34. {
  35. ANKI_TRACE_SCOPED_EVENT(RSRC_FILE_READ);
  36. return m_file.readU32(u);
  37. }
  38. Error readF32(F32& f) override
  39. {
  40. ANKI_TRACE_SCOPED_EVENT(RSRC_FILE_READ);
  41. return m_file.readF32(f);
  42. }
  43. Error seek(PtrSize offset, FileSeekOrigin origin) override
  44. {
  45. return m_file.seek(offset, origin);
  46. }
  47. PtrSize getSize() const override
  48. {
  49. return m_file.getSize();
  50. }
  51. };
  52. /// ZIP file
  53. class ZipResourceFile final : public ResourceFile
  54. {
  55. public:
  56. unzFile m_archive = nullptr;
  57. PtrSize m_size = 0;
  58. ZipResourceFile(GenericMemoryPoolAllocator<U8> alloc)
  59. : ResourceFile(alloc)
  60. {
  61. }
  62. ~ZipResourceFile()
  63. {
  64. if(m_archive)
  65. {
  66. // It's open
  67. unzClose(m_archive);
  68. m_archive = nullptr;
  69. m_size = 0;
  70. }
  71. }
  72. Error open(const CString& archive, const CString& archivedFname)
  73. {
  74. // Open archive
  75. m_archive = unzOpen(&archive[0]);
  76. if(m_archive == nullptr)
  77. {
  78. ANKI_RESOURCE_LOGE("Failed to open archive");
  79. return Error::kFileAccess;
  80. }
  81. // Locate archived
  82. const int caseSensitive = 1;
  83. if(unzLocateFile(m_archive, &archivedFname[0], caseSensitive) != UNZ_OK)
  84. {
  85. ANKI_RESOURCE_LOGE("Failed to locate file in archive");
  86. return Error::kFileAccess;
  87. }
  88. // Open file
  89. if(unzOpenCurrentFile(m_archive) != UNZ_OK)
  90. {
  91. ANKI_RESOURCE_LOGE("unzOpenCurrentFile() failed");
  92. return Error::kFileAccess;
  93. }
  94. // Get size just in case
  95. unz_file_info zinfo;
  96. zinfo.uncompressed_size = 0;
  97. unzGetCurrentFileInfo(m_archive, &zinfo, nullptr, 0, nullptr, 0, nullptr, 0);
  98. m_size = zinfo.uncompressed_size;
  99. ANKI_ASSERT(m_size != 0);
  100. return Error::kNone;
  101. }
  102. void close()
  103. {
  104. if(m_archive)
  105. {
  106. unzClose(m_archive);
  107. m_archive = nullptr;
  108. m_size = 0;
  109. }
  110. }
  111. Error read(void* buff, PtrSize size) override
  112. {
  113. ANKI_TRACE_SCOPED_EVENT(RSRC_FILE_READ);
  114. I64 readSize = unzReadCurrentFile(m_archive, buff, U32(size));
  115. if(I64(size) != readSize)
  116. {
  117. ANKI_RESOURCE_LOGE("File read failed");
  118. return Error::kFileAccess;
  119. }
  120. return Error::kNone;
  121. }
  122. Error readAllText(StringAuto& out) override
  123. {
  124. ANKI_ASSERT(m_size);
  125. out.create('?', m_size);
  126. return read(&out[0], m_size);
  127. }
  128. Error readU32(U32& u) override
  129. {
  130. // Assume machine and file have same endianness
  131. ANKI_CHECK(read(&u, sizeof(u)));
  132. return Error::kNone;
  133. }
  134. Error readF32(F32& u) override
  135. {
  136. // Assume machine and file have same endianness
  137. ANKI_CHECK(read(&u, sizeof(u)));
  138. return Error::kNone;
  139. }
  140. Error seek(PtrSize offset, FileSeekOrigin origin) override
  141. {
  142. // Rewind if needed
  143. if(origin == FileSeekOrigin::BEGINNING)
  144. {
  145. if(unzCloseCurrentFile(m_archive) || unzOpenCurrentFile(m_archive))
  146. {
  147. ANKI_RESOURCE_LOGE("Rewind failed");
  148. return Error::kFunctionFailed;
  149. }
  150. }
  151. // Move forward by reading dummy data
  152. Array<char, 128> buff;
  153. while(offset != 0)
  154. {
  155. PtrSize toRead = min<PtrSize>(offset, sizeof(buff));
  156. ANKI_CHECK(read(&buff[0], toRead));
  157. offset -= toRead;
  158. }
  159. return Error::kNone;
  160. }
  161. PtrSize getSize() const override
  162. {
  163. ANKI_ASSERT(m_size > 0);
  164. return m_size;
  165. }
  166. };
  167. ResourceFilesystem::~ResourceFilesystem()
  168. {
  169. for(Path& p : m_paths)
  170. {
  171. p.m_files.destroy(m_alloc);
  172. p.m_path.destroy(m_alloc);
  173. }
  174. m_paths.destroy(m_alloc);
  175. m_cacheDir.destroy(m_alloc);
  176. }
  177. Error ResourceFilesystem::init(const ConfigSet& config)
  178. {
  179. StringListAuto paths(m_alloc);
  180. paths.splitString(config.getRsrcDataPaths(), ':');
  181. StringListAuto excludedStrings(m_alloc);
  182. excludedStrings.splitString(config.getRsrcDataPathExcludedStrings(), ':');
  183. // Workaround the fact that : is used in drives in Windows
  184. #if ANKI_OS_WINDOWS
  185. StringListAuto paths2(m_alloc);
  186. StringListAuto::Iterator it = paths.getBegin();
  187. while(it != paths.getEnd())
  188. {
  189. const String& s = *it;
  190. StringListAuto::Iterator it2 = it + 1;
  191. if(s.getLength() == 1 && (s[0] >= 'a' && s[0] <= 'z') || (s[0] >= 'A' && s[0] <= 'Z') && it2 != paths.getEnd())
  192. {
  193. paths2.pushBackSprintf("%s:%s", s.cstr(), it2->cstr());
  194. ++it;
  195. }
  196. else
  197. {
  198. paths2.pushBack(s);
  199. }
  200. ++it;
  201. }
  202. paths.destroy();
  203. paths = std::move(paths2);
  204. #endif
  205. if(paths.getSize() < 1)
  206. {
  207. ANKI_RESOURCE_LOGE("Config option \"RsrcDataPaths\" is empty");
  208. return Error::kUserData;
  209. }
  210. for(auto& path : paths)
  211. {
  212. ANKI_CHECK(addNewPath(path.toCString(), excludedStrings));
  213. }
  214. #if ANKI_OS_ANDROID
  215. // Add the external storage
  216. ANKI_CHECK(addNewPath(g_androidApp->activity->externalDataPath, excludedStrings));
  217. #endif
  218. return Error::kNone;
  219. }
  220. Error ResourceFilesystem::addNewPath(const CString& filepath, const StringListAuto& excludedStrings)
  221. {
  222. ANKI_RESOURCE_LOGV("Adding new resource path: %s", filepath.cstr());
  223. U32 fileCount = 0; // Count files manually because it's slower to get that number from the list
  224. constexpr CString extension(".ankizip");
  225. auto rejectPath = [&](CString p) -> Bool {
  226. for(const String& s : excludedStrings)
  227. {
  228. if(p.find(s) != CString::kNpos)
  229. {
  230. return true;
  231. }
  232. }
  233. return false;
  234. };
  235. PtrSize pos;
  236. Path path;
  237. if((pos = filepath.find(extension)) != CString::kNpos && 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::kFileAccess;
  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::kFileAccess;
  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::kFileAccess;
  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::kNone;
  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::kNone;
  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. for(const String& pfname : p.m_files)
  329. {
  330. if(pfname != filename)
  331. {
  332. continue;
  333. }
  334. // Found
  335. if(p.m_isArchive)
  336. {
  337. ZipResourceFile* file = m_alloc.newInstance<ZipResourceFile>(m_alloc);
  338. rfile = file;
  339. ANKI_CHECK(file->open(p.m_path.toCString(), filename));
  340. }
  341. else
  342. {
  343. StringAuto newFname(m_alloc);
  344. newFname.sprintf("%s/%s", &p.m_path[0], &filename[0]);
  345. CResourceFile* file = m_alloc.newInstance<CResourceFile>(m_alloc);
  346. rfile = file;
  347. ANKI_CHECK(file->m_file.open(newFname, FileOpenFlag::READ));
  348. #if 0
  349. printf("Opening asset %s\n", &newFname[0]);
  350. #endif
  351. }
  352. }
  353. if(rfile)
  354. {
  355. break;
  356. }
  357. } // end for all paths
  358. // File not found? On Win/Linux try to find it outside the resource dirs. On Android try the archive
  359. if(!rfile)
  360. {
  361. CResourceFile* file = m_alloc.newInstance<CResourceFile>(m_alloc);
  362. rfile = file;
  363. FileOpenFlag openFlags = FileOpenFlag::READ;
  364. #if ANKI_OS_ANDROID
  365. openFlags |= FileOpenFlag::SPECIAL;
  366. #endif
  367. ANKI_CHECK(file->m_file.open(filename, openFlags));
  368. #if !ANKI_OS_ANDROID
  369. ANKI_RESOURCE_LOGW(
  370. "Loading resource outside the resource paths/archives. This is only OK for tools and debugging: %s",
  371. filename.cstr());
  372. #endif
  373. }
  374. return Error::kNone;
  375. }
  376. } // end namespace anki