CResourceLoader.cpp 12 KB

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