CResourceLoader.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  1. #include "StdInc.h"
  2. #include "CResourceLoader.h"
  3. #include "CFileInfo.h"
  4. #include "CLodArchiveLoader.h"
  5. #include "CFilesystemLoader.h"
  6. #include "CMappedFileLoader.h"
  7. //For filesystem initialization
  8. #include "../JsonNode.h"
  9. #include "../GameConstants.h"
  10. #include "../VCMIDirs.h"
  11. #include "../CStopWatch.h"
  12. CResourceLoader * CResourceHandler::resourceLoader = nullptr;
  13. CResourceLoader * CResourceHandler::initialLoader = nullptr;
  14. ResourceID::ResourceID()
  15. :type(EResType::OTHER)
  16. {
  17. }
  18. ResourceID::ResourceID(std::string name)
  19. {
  20. CFileInfo info(std::move(name));
  21. setName(info.getStem());
  22. setType(info.getType());
  23. }
  24. ResourceID::ResourceID(std::string name, EResType::Type type)
  25. {
  26. setName(std::move(name));
  27. setType(type);
  28. }
  29. ResourceID::ResourceID(const std::string & prefix, const std::string & name, EResType::Type type)
  30. {
  31. this->name = name;
  32. size_t dotPos = this->name.find_last_of("/.");
  33. if(dotPos != std::string::npos && this->name[dotPos] == '.')
  34. this->name.erase(dotPos);
  35. this->name = prefix + this->name;
  36. setType(type);
  37. }
  38. std::string ResourceID::getName() const
  39. {
  40. return name;
  41. }
  42. EResType::Type ResourceID::getType() const
  43. {
  44. return type;
  45. }
  46. void ResourceID::setName(std::string name)
  47. {
  48. this->name = std::move(name);
  49. size_t dotPos = this->name.find_last_of("/.");
  50. if(dotPos != std::string::npos && this->name[dotPos] == '.')
  51. this->name.erase(dotPos);
  52. // strangely enough but this line takes 40-50% of filesystem loading time
  53. boost::to_upper(this->name);
  54. }
  55. void ResourceID::setType(EResType::Type type)
  56. {
  57. this->type = type;
  58. }
  59. CResourceLoader::CResourceLoader()
  60. {
  61. }
  62. std::unique_ptr<CInputStream> CResourceLoader::load(const ResourceID & resourceIdent) const
  63. {
  64. auto resource = resources.find(resourceIdent);
  65. if(resource == resources.end())
  66. {
  67. throw std::runtime_error("Resource with name " + resourceIdent.getName() + " and type "
  68. + EResTypeHelper::getEResTypeAsString(resourceIdent.getType()) + " wasn't found.");
  69. }
  70. // get the last added resource(most overriden)
  71. const ResourceLocator & locator = resource->second.back();
  72. // load the resource and return it
  73. return locator.getLoader()->load(locator.getResourceName());
  74. }
  75. std::pair<std::unique_ptr<ui8[]>, ui64> CResourceLoader::loadData(const ResourceID & resourceIdent) const
  76. {
  77. auto stream = load(resourceIdent);
  78. std::unique_ptr<ui8[]> data(new ui8[stream->getSize()]);
  79. size_t readSize = stream->read(data.get(), stream->getSize());
  80. assert(readSize == stream->getSize());
  81. return std::make_pair(std::move(data), stream->getSize());
  82. }
  83. ResourceLocator CResourceLoader::getResource(const ResourceID & resourceIdent) const
  84. {
  85. auto resource = resources.find(resourceIdent);
  86. if (resource == resources.end())
  87. return ResourceLocator(nullptr, "");
  88. return resource->second.back();
  89. }
  90. const std::vector<ResourceLocator> & CResourceLoader::getResourcesWithName(const ResourceID & resourceIdent) const
  91. {
  92. static const std::vector<ResourceLocator> emptyList;
  93. auto resource = resources.find(resourceIdent);
  94. if (resource == resources.end())
  95. return emptyList;
  96. return resource->second;
  97. }
  98. std::string CResourceLoader::getResourceName(const ResourceID & resourceIdent) const
  99. {
  100. auto locator = getResource(resourceIdent);
  101. if (locator.getLoader())
  102. return locator.getLoader()->getFullName(locator.getResourceName());
  103. return "";
  104. }
  105. bool CResourceLoader::existsResource(const ResourceID & resourceIdent) const
  106. {
  107. return resources.find(resourceIdent) != resources.end();
  108. }
  109. bool CResourceLoader::createResource(std::string URI, bool update)
  110. {
  111. std::string filename = URI;
  112. boost::to_upper(URI);
  113. for (auto & entry : boost::adaptors::reverse(loaders))
  114. {
  115. if (entry.writeable && boost::algorithm::starts_with(URI, entry.prefix))
  116. {
  117. // remove loader prefix from filename
  118. filename = filename.substr(entry.prefix.size());
  119. if (!entry.loader->createEntry(filename))
  120. continue;
  121. resources[ResourceID(URI)].push_back(ResourceLocator(entry.loader.get(), filename));
  122. // Check if resource was created successfully. Possible reasons for this to fail
  123. // a) loader failed to create resource (e.g. read-only FS)
  124. // b) in update mode, call with filename that does not exists
  125. assert(load(ResourceID(URI)));
  126. return true;
  127. }
  128. }
  129. return false;
  130. }
  131. void CResourceLoader::addLoader(std::string mountPoint, shared_ptr<ISimpleResourceLoader> loader, bool writeable)
  132. {
  133. LoaderEntry loaderEntry;
  134. loaderEntry.loader = loader;
  135. loaderEntry.prefix = mountPoint;
  136. loaderEntry.writeable = writeable;
  137. loaders.push_back(loaderEntry);
  138. // Get entries and add them to the resources list
  139. const std::unordered_map<ResourceID, std::string> & entries = loader->getEntries();
  140. boost::to_upper(mountPoint);
  141. for (auto & entry : entries)
  142. {
  143. // Create identifier and locator and add them to the resources list
  144. ResourceID ident(mountPoint, entry.first.getName(), entry.first.getType());
  145. ResourceLocator locator(loader.get(), entry.second);
  146. resources[ident].push_back(locator);
  147. }
  148. }
  149. CResourceLoader * CResourceHandler::get()
  150. {
  151. if(resourceLoader != nullptr)
  152. {
  153. return resourceLoader;
  154. }
  155. else
  156. {
  157. std::stringstream string;
  158. string << "Error: Resource loader wasn't initialized. "
  159. << "Make sure that you set one via CResourceLoaderFactory::initialize";
  160. throw std::runtime_error(string.str());
  161. }
  162. }
  163. void CResourceHandler::clear()
  164. {
  165. delete resourceLoader;
  166. delete initialLoader;
  167. }
  168. //void CResourceLoaderFactory::setInstance(CResourceLoader * resourceLoader)
  169. //{
  170. // CResourceLoaderFactory::resourceLoader = resourceLoader;
  171. //}
  172. ResourceLocator::ResourceLocator(ISimpleResourceLoader * loader, const std::string & resourceName)
  173. : loader(loader), resourceName(resourceName)
  174. {
  175. }
  176. ISimpleResourceLoader * ResourceLocator::getLoader() const
  177. {
  178. return loader;
  179. }
  180. std::string ResourceLocator::getResourceName() const
  181. {
  182. return resourceName;
  183. }
  184. EResType::Type EResTypeHelper::getTypeFromExtension(std::string extension)
  185. {
  186. boost::to_upper(extension);
  187. static const std::map<std::string, EResType::Type> stringToRes =
  188. boost::assign::map_list_of
  189. (".TXT", EResType::TEXT)
  190. (".JSON", EResType::TEXT)
  191. (".DEF", EResType::ANIMATION)
  192. (".MSK", EResType::MASK)
  193. (".MSG", EResType::MASK)
  194. (".H3C", EResType::CAMPAIGN)
  195. (".H3M", EResType::MAP)
  196. (".FNT", EResType::BMP_FONT)
  197. (".TTF", EResType::TTF_FONT)
  198. (".BMP", EResType::IMAGE)
  199. (".JPG", EResType::IMAGE)
  200. (".PCX", EResType::IMAGE)
  201. (".PNG", EResType::IMAGE)
  202. (".TGA", EResType::IMAGE)
  203. (".WAV", EResType::SOUND)
  204. (".82M", EResType::SOUND)
  205. (".SMK", EResType::VIDEO)
  206. (".BIK", EResType::VIDEO)
  207. (".MJPG", EResType::VIDEO)
  208. (".MPG", EResType::VIDEO)
  209. (".AVI", EResType::VIDEO)
  210. (".MP3", EResType::MUSIC)
  211. (".OGG", EResType::MUSIC)
  212. (".LOD", EResType::ARCHIVE_LOD)
  213. (".PAC", EResType::ARCHIVE_LOD)
  214. (".VID", EResType::ARCHIVE_VID)
  215. (".SND", EResType::ARCHIVE_SND)
  216. (".PAL", EResType::PALETTE)
  217. (".VCGM1", EResType::CLIENT_SAVEGAME)
  218. (".VSGM1", EResType::SERVER_SAVEGAME)
  219. (".ERM", EResType::ERM)
  220. (".ERT", EResType::ERT)
  221. (".ERS", EResType::ERS);
  222. auto iter = stringToRes.find(extension);
  223. if (iter == stringToRes.end())
  224. return EResType::OTHER;
  225. return iter->second;
  226. }
  227. std::string EResTypeHelper::getEResTypeAsString(EResType::Type type)
  228. {
  229. #define MAP_ENUM(value) (EResType::value, #value)
  230. static const std::map<EResType::Type, std::string> stringToRes = boost::assign::map_list_of
  231. MAP_ENUM(TEXT)
  232. MAP_ENUM(ANIMATION)
  233. MAP_ENUM(MASK)
  234. MAP_ENUM(CAMPAIGN)
  235. MAP_ENUM(MAP)
  236. MAP_ENUM(BMP_FONT)
  237. MAP_ENUM(TTF_FONT)
  238. MAP_ENUM(IMAGE)
  239. MAP_ENUM(VIDEO)
  240. MAP_ENUM(SOUND)
  241. MAP_ENUM(MUSIC)
  242. MAP_ENUM(ARCHIVE_LOD)
  243. MAP_ENUM(ARCHIVE_SND)
  244. MAP_ENUM(ARCHIVE_VID)
  245. MAP_ENUM(PALETTE)
  246. MAP_ENUM(CLIENT_SAVEGAME)
  247. MAP_ENUM(SERVER_SAVEGAME)
  248. MAP_ENUM(DIRECTORY)
  249. MAP_ENUM(ERM)
  250. MAP_ENUM(ERT)
  251. MAP_ENUM(ERS)
  252. MAP_ENUM(OTHER);
  253. #undef MAP_ENUM
  254. auto iter = stringToRes.find(type);
  255. assert(iter != stringToRes.end());
  256. return iter->second;
  257. }
  258. void CResourceHandler::initialize()
  259. {
  260. //recurse only into specific directories
  261. auto recurseInDir = [](std::string URI, int depth)
  262. {
  263. auto resources = initialLoader->getResourcesWithName(ResourceID(URI, EResType::DIRECTORY));
  264. for(const ResourceLocator & entry : resources)
  265. {
  266. std::string filename = entry.getLoader()->getOrigin() + '/' + entry.getResourceName();
  267. if (!filename.empty())
  268. {
  269. shared_ptr<ISimpleResourceLoader> dir(new CFilesystemLoader(filename, depth, true));
  270. initialLoader->addLoader(URI + '/', dir, false);
  271. }
  272. }
  273. };
  274. //temporary filesystem that will be used to initialize main one.
  275. //used to solve several case-sensivity issues like Mp3 vs MP3
  276. initialLoader = new CResourceLoader;
  277. resourceLoader = new CResourceLoader;
  278. for (auto path : VCMIDirs::get().dataPaths())
  279. {
  280. shared_ptr<ISimpleResourceLoader> loader(new CFilesystemLoader(path, 0, true));
  281. initialLoader->addLoader("GLOBAL/", loader, false);
  282. initialLoader->addLoader("ALL/", loader, false);
  283. }
  284. {
  285. shared_ptr<ISimpleResourceLoader> loader(new CFilesystemLoader(VCMIDirs::get().userDataPath(), 0, true));
  286. initialLoader->addLoader("LOCAL/", loader, false);
  287. if (!vstd::contains(VCMIDirs::get().dataPaths(), VCMIDirs::get().userDataPath()))
  288. initialLoader->addLoader("ALL/", loader, false);
  289. }
  290. recurseInDir("ALL/CONFIG", 0);// look for configs
  291. recurseInDir("ALL/DATA", 0); // look for archives
  292. recurseInDir("ALL/MODS", 2); // look for mods. Depth 2 is required for now but won't cause spped issues if no mods present
  293. }
  294. void CResourceHandler::loadDirectory(const std::string &prefix, const std::string &mountPoint, const JsonNode & config)
  295. {
  296. std::string URI = prefix + config["path"].String();
  297. bool writeable = config["writeable"].Bool();
  298. int depth = 16;
  299. if (!config["depth"].isNull())
  300. depth = config["depth"].Float();
  301. auto resources = initialLoader->getResourcesWithName(ResourceID(URI, EResType::DIRECTORY));
  302. for(const ResourceLocator & entry : resources)
  303. {
  304. std::string filename = entry.getLoader()->getOrigin() + '/' + entry.getResourceName();
  305. resourceLoader->addLoader(mountPoint,
  306. shared_ptr<ISimpleResourceLoader>(new CFilesystemLoader(filename, depth)), writeable);
  307. }
  308. }
  309. void CResourceHandler::loadArchive(const std::string &prefix, const std::string &mountPoint, const JsonNode & config, EResType::Type archiveType)
  310. {
  311. std::string URI = prefix + config["path"].String();
  312. std::string filename = initialLoader->getResourceName(ResourceID(URI, archiveType));
  313. if (!filename.empty())
  314. resourceLoader->addLoader(mountPoint,
  315. shared_ptr<ISimpleResourceLoader>(new CLodArchiveLoader(filename)), false);
  316. }
  317. void CResourceHandler::loadJsonMap(const std::string &prefix, const std::string &mountPoint, const JsonNode & config)
  318. {
  319. std::string URI = prefix + config["path"].String();
  320. std::string filename = initialLoader->getResourceName(ResourceID(URI, EResType::TEXT));
  321. if (!filename.empty())
  322. {
  323. auto configData = initialLoader->loadData(ResourceID(URI, EResType::TEXT));
  324. const JsonNode config((char*)configData.first.get(), configData.second);
  325. resourceLoader->addLoader(mountPoint,
  326. shared_ptr<ISimpleResourceLoader>(new CMappedFileLoader(config)), false);
  327. }
  328. }
  329. void CResourceHandler::loadFileSystem(const std::string & prefix, const std::string &fsConfigURI)
  330. {
  331. auto fsConfigData = initialLoader->loadData(ResourceID(fsConfigURI, EResType::TEXT));
  332. const JsonNode fsConfig((char*)fsConfigData.first.get(), fsConfigData.second);
  333. loadFileSystem(prefix, fsConfig["filesystem"]);
  334. }
  335. void CResourceHandler::loadFileSystem(const std::string & prefix, const JsonNode &fsConfig)
  336. {
  337. for(auto & mountPoint : fsConfig.Struct())
  338. {
  339. for(auto & entry : mountPoint.second.Vector())
  340. {
  341. CStopWatch timer;
  342. logGlobal->debugStream() << "\t\tLoading resource at " << prefix + entry["path"].String();
  343. if (entry["type"].String() == "map")
  344. loadJsonMap(prefix, mountPoint.first, entry);
  345. if (entry["type"].String() == "dir")
  346. loadDirectory(prefix, mountPoint.first, entry);
  347. if (entry["type"].String() == "lod")
  348. loadArchive(prefix, mountPoint.first, entry, EResType::ARCHIVE_LOD);
  349. if (entry["type"].String() == "snd")
  350. loadArchive(prefix, mountPoint.first, entry, EResType::ARCHIVE_SND);
  351. if (entry["type"].String() == "vid")
  352. loadArchive(prefix, mountPoint.first, entry, EResType::ARCHIVE_VID);
  353. logGlobal->debugStream() << "Resource loaded in " << timer.getDiff() << " ms.";
  354. }
  355. }
  356. }
  357. std::vector<std::string> CResourceHandler::getAvailableMods()
  358. {
  359. auto iterator = initialLoader->getIterator([](const ResourceID & ident) -> bool
  360. {
  361. std::string name = ident.getName();
  362. return ident.getType() == EResType::DIRECTORY
  363. && std::count(name.begin(), name.end(), '/') == 2
  364. && boost::algorithm::starts_with(name, "ALL/MODS/");
  365. });
  366. //storage for found mods
  367. std::vector<std::string> foundMods;
  368. while (iterator.hasNext())
  369. {
  370. std::string name = iterator->getName();
  371. name.erase(0, name.find_last_of('/') + 1); //Remove path prefix
  372. if (name == "WOG") // check if wog is actually present. Hack-ish but better than crash
  373. {
  374. if (!initialLoader->existsResource(ResourceID("ALL/DATA/ZVS", EResType::DIRECTORY)) &&
  375. !initialLoader->existsResource(ResourceID("ALL/MODS/WOG/DATA/ZVS", EResType::DIRECTORY)))
  376. {
  377. ++iterator;
  378. continue;
  379. }
  380. }
  381. if (!name.empty()) // this is also triggered for "ALL/MODS/" entry
  382. foundMods.push_back(name);
  383. ++iterator;
  384. }
  385. return foundMods;
  386. }
  387. void CResourceHandler::setActiveMods(std::vector<std::string> enabledMods)
  388. {
  389. // default FS config for mods: directory "Content" that acts as H3 root directory
  390. JsonNode defaultFS;
  391. defaultFS[""].Vector().resize(1);
  392. defaultFS[""].Vector()[0]["type"].String() = "dir";
  393. defaultFS[""].Vector()[0]["path"].String() = "/Content";
  394. for(std::string & modName : enabledMods)
  395. {
  396. ResourceID modConfFile("all/mods/" + modName + "/mod", EResType::TEXT);
  397. auto fsConfigData = initialLoader->loadData(modConfFile);
  398. const JsonNode fsConfig((char*)fsConfigData.first.get(), fsConfigData.second);
  399. if (!fsConfig["filesystem"].isNull())
  400. loadFileSystem("all/mods/" + modName, fsConfig["filesystem"]);
  401. else
  402. loadFileSystem("all/mods/" + modName, defaultFS);
  403. }
  404. }