ResourceFilesystem.cpp 11 KB

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