CLodHandler.cpp 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  1. #include "StdInc.h"
  2. #include "CLodHandler.h"
  3. #include "zlib.h"
  4. #include "vcmi_endian.h"
  5. #include "VCMIDirs.h"
  6. #ifdef max
  7. #undef max
  8. #endif
  9. extern VCMIDirs GVCMIDirs;
  10. /*
  11. * CLodHandler.cpp, part of VCMI engine
  12. *
  13. * Authors: listed in file AUTHORS in main folder
  14. *
  15. * License: GNU General Public License v2.0 or later
  16. * Full text of license available in license.txt file, in main folder
  17. *
  18. */
  19. std::string readString(const ui8 * bufor, int &i)
  20. {
  21. int len = read_le_u32(bufor + i); i+=4;
  22. assert(len >= 0 && len <= 500000); //not too long
  23. std::string ret; ret.reserve(len);
  24. for(int gg=0; gg<len; ++gg)
  25. {
  26. ret += bufor[i++];
  27. }
  28. return ret;
  29. }
  30. void CLodHandler::convertName(std::string &filename, std::string *extension)
  31. {
  32. std::transform(filename.begin(), filename.end(), filename.begin(), toupper);
  33. size_t dotPos = filename.find_last_of("/.");
  34. if ( dotPos != std::string::npos && filename[dotPos] == '.')
  35. {
  36. if (extension)
  37. *extension = filename.substr(dotPos);
  38. filename.erase(dotPos);
  39. }
  40. }
  41. ui8 * CLodHandler::giveFile(std::string fname, LodFileType type, int * length)
  42. {
  43. convertName(fname);
  44. boost::unordered_set<Entry>::const_iterator en_it = entries.find(Entry(fname, type));
  45. if(en_it == entries.end()) //nothing's been found
  46. {
  47. tlog1 << "Cannot find file: " << fname << std::endl;
  48. return NULL;
  49. }
  50. Entry ourEntry = *en_it;
  51. if(length) *length = ourEntry.realSize;
  52. boost::unique_lock<boost::mutex> lock(*mutex);
  53. ui8 * outp;
  54. if (ourEntry.offset<0) //file is in the sprites/ folder; no compression
  55. {
  56. int result;
  57. outp = new ui8[ourEntry.realSize];
  58. FILE * f = fopen((myDir + "/" + ourEntry.realName).c_str(), "rb");
  59. if (f)
  60. {
  61. result = fread(outp,1,ourEntry.realSize,f);
  62. fclose(f);
  63. }
  64. else
  65. result = -1;
  66. if(result<0)
  67. {
  68. tlog1<<"Error in file reading: " << ourEntry.realName << std::endl;
  69. perror("Last error was: ");//print system error message
  70. delete[] outp;
  71. return NULL;
  72. }
  73. else
  74. return outp;
  75. }
  76. else if (ourEntry.size==0) //file is not compressed
  77. {
  78. outp = new ui8[ourEntry.realSize];
  79. LOD.seekg(ourEntry.offset, std::ios::beg);
  80. LOD.read((char*)outp, ourEntry.realSize);
  81. return outp;
  82. }
  83. else //we will decompress file
  84. {
  85. outp = new ui8[ourEntry.size];
  86. LOD.seekg(ourEntry.offset, std::ios::beg);
  87. LOD.read((char*)outp, ourEntry.size);
  88. ui8 * decomp = NULL;
  89. infs2(outp, ourEntry.size, ourEntry.realSize, decomp);
  90. delete[] outp;
  91. return decomp;
  92. }
  93. return NULL;
  94. }
  95. std::string CLodHandler::getFileName(std::string lodFile, LodFileType type)
  96. {
  97. convertName(lodFile);
  98. boost::unordered_set<Entry>::const_iterator it = entries.find(Entry(lodFile, type));
  99. if (it != entries.end())
  100. return it->realName;
  101. return "";
  102. }
  103. bool CLodHandler::haveFile(std::string name, LodFileType type)
  104. {
  105. convertName(name);
  106. return vstd::contains(entries, Entry(name, type));
  107. }
  108. DLL_LINKAGE int CLodHandler::infs2(ui8 * in, int size, int realSize, ui8 *& out, int wBits)
  109. {
  110. int ret;
  111. unsigned have;
  112. z_stream strm;
  113. out = new ui8 [realSize];
  114. int latPosOut = 0;
  115. /* allocate inflate state */
  116. strm.zalloc = Z_NULL;
  117. strm.zfree = Z_NULL;
  118. strm.opaque = Z_NULL;
  119. strm.avail_in = 0;
  120. strm.next_in = Z_NULL;
  121. ret = inflateInit2(&strm, wBits);
  122. if (ret != Z_OK)
  123. return ret;
  124. int chunkNumber = 0;
  125. do
  126. {
  127. if(size < chunkNumber * NLoadHandlerHelp::fCHUNK)
  128. break;
  129. strm.avail_in = std::min(NLoadHandlerHelp::fCHUNK, size - chunkNumber * NLoadHandlerHelp::fCHUNK);
  130. if (strm.avail_in == 0)
  131. break;
  132. strm.next_in = in + chunkNumber * NLoadHandlerHelp::fCHUNK;
  133. /* run inflate() on input until output buffer not full */
  134. do
  135. {
  136. strm.avail_out = realSize - latPosOut;
  137. strm.next_out = out + latPosOut;
  138. ret = inflate(&strm, Z_NO_FLUSH);
  139. //assert(ret != Z_STREAM_ERROR); /* state not clobbered */
  140. bool breakLoop = false;
  141. switch (ret)
  142. {
  143. case Z_STREAM_END:
  144. breakLoop = true;
  145. break;
  146. case Z_NEED_DICT:
  147. ret = Z_DATA_ERROR; /* and fall through */
  148. case Z_DATA_ERROR:
  149. case Z_MEM_ERROR:
  150. (void)inflateEnd(&strm);
  151. return ret;
  152. }
  153. if(breakLoop)
  154. break;
  155. have = realSize - latPosOut - strm.avail_out;
  156. latPosOut += have;
  157. } while (strm.avail_out == 0);
  158. ++chunkNumber;
  159. /* done when inflate() says it's done */
  160. } while (ret != Z_STREAM_END);
  161. /* clean up and return */
  162. (void)inflateEnd(&strm);
  163. return ret == Z_STREAM_END ? Z_OK : Z_DATA_ERROR;
  164. }
  165. void CLodHandler::extractFile(const std::string FName, const std::string name, LodFileType type)
  166. {
  167. int len; //length of file to write
  168. ui8 * outp = giveFile(name, type, &len);
  169. std::ofstream out;
  170. out.open(FName.c_str(), std::ios::binary);
  171. if(!out.is_open())
  172. {
  173. tlog1<<"Unable to create "<<FName<<std::endl;
  174. }
  175. else
  176. {
  177. out.write(reinterpret_cast<char*>(outp), len);
  178. out.close();
  179. }
  180. }
  181. void CLodHandler::initEntry(Entry &e, std::string name)
  182. {
  183. std::string ext;
  184. convertName(name, &ext);
  185. e.name = name;
  186. std::map<std::string, LodFileType>::iterator it = extMap.find(ext);
  187. if (it == extMap.end())
  188. e.type = FILE_OTHER;
  189. else
  190. e.type = it->second;
  191. }
  192. void CLodHandler::init(const std::string lodFile, const std::string dirName)
  193. {
  194. #define EXT(NAME, TYPE) extMap.insert(std::pair<std::string, LodFileType>(NAME, TYPE));
  195. EXT(".TXT", FILE_TEXT);
  196. EXT(".JSON",FILE_TEXT);
  197. EXT(".DEF", FILE_ANIMATION);
  198. EXT(".MSK", FILE_MASK);
  199. EXT(".MSG", FILE_MASK);
  200. EXT(".H3C", FILE_CAMPAIGN);
  201. EXT(".H3M", FILE_MAP);
  202. EXT(".FNT", FILE_FONT);
  203. EXT(".BMP", FILE_GRAPHICS);
  204. EXT(".JPG", FILE_GRAPHICS);
  205. EXT(".PCX", FILE_GRAPHICS);
  206. EXT(".PNG", FILE_GRAPHICS);
  207. EXT(".TGA", FILE_GRAPHICS);
  208. #undef EXT
  209. myDir = dirName;
  210. LOD.open(lodFile.c_str(), std::ios::in | std::ios::binary);
  211. if (!LOD.is_open())
  212. {
  213. tlog1 << "Cannot open " << lodFile << std::endl;
  214. return;
  215. }
  216. Uint32 temp;
  217. LOD.seekg(8);
  218. LOD.read((char *)&temp, 4);
  219. totalFiles = SDL_SwapLE32(temp);
  220. LOD.seekg(0x5c, std::ios::beg);
  221. if(!LOD)
  222. {
  223. tlog2 << lodFile << " doesn't store anything!\n";
  224. return;
  225. }
  226. struct LodEntry *lodEntries = new struct LodEntry[totalFiles];
  227. LOD.read((char *)lodEntries, sizeof(struct LodEntry) * totalFiles);
  228. for (ui32 i=0; i<totalFiles; i++)
  229. {
  230. Entry entry;
  231. initEntry(entry, lodEntries[i].filename);
  232. entry.offset= SDL_SwapLE32(lodEntries[i].offset);
  233. entry.realSize = SDL_SwapLE32(lodEntries[i].uncompressedSize);
  234. entry.size = SDL_SwapLE32(lodEntries[i].size);
  235. entries.insert(entry);
  236. }
  237. delete [] lodEntries;
  238. boost::filesystem::recursive_directory_iterator enddir;
  239. if(boost::filesystem::exists(dirName))
  240. {
  241. std::vector<std::string> path;
  242. for (boost::filesystem::recursive_directory_iterator dir(dirName); dir!=enddir; dir++)
  243. {
  244. //If a directory was found - add name to vector to recreate full path later
  245. if (boost::filesystem::is_directory(dir->status()))
  246. {
  247. path.resize(dir.level()+1);
  248. path.back() = dir->path().leaf();
  249. }
  250. if(boost::filesystem::is_regular(dir->status()))
  251. {
  252. Entry e;
  253. //we can't get relative path with boost at the moment - need to create path to file manually
  254. for (size_t i=0; i<dir.level() && i<path.size(); i++)
  255. e.realName += path[i] + '/';
  256. e.realName += dir->path().leaf();
  257. initEntry(e, e.realName);
  258. if(vstd::contains(entries, e)) //file present in .lod - overwrite its entry
  259. entries.erase(e);
  260. e.offset = -1;
  261. e.realSize = e.size = boost::filesystem::file_size(dir->path());
  262. entries.insert(e);
  263. }
  264. }
  265. }
  266. else
  267. {
  268. if (!dirName.empty())
  269. tlog1<<"Warning: No "+dirName+"/ folder!"<<std::endl;
  270. }
  271. }
  272. std::string CLodHandler::getTextFile(std::string name, LodFileType type)
  273. {
  274. int length=-1;
  275. ui8* data = giveFile(name, type, &length);
  276. if (!data) {
  277. tlog1<<"Fatal error. Missing game file: " << name << ". Aborting!"<<std::endl;
  278. exit(1);
  279. }
  280. std::string ret(data, data+length);
  281. delete [] data;
  282. return ret;
  283. }
  284. CLodHandler::CLodHandler()
  285. {
  286. mutex = new boost::mutex;
  287. totalFiles = 0;
  288. }
  289. CLodHandler::~CLodHandler()
  290. {
  291. delete mutex;
  292. }
  293. //It is possible to use uncompress function from zlib but we need to know decompressed size (not present in compressed data)
  294. ui8 * CLodHandler::getUnpackedData(ui8 *data, size_t inputSize, int * outputSize)
  295. {
  296. std::string filename = GVCMIDirs.UserPath + "/tmp_gzip";
  297. FILE * file = fopen(filename.c_str(), "wb");
  298. fwrite(data, 1, inputSize, file);
  299. fclose(file);
  300. ui8 * ret = getUnpackedFile(filename, outputSize);
  301. remove(filename.c_str());
  302. delete [] data;
  303. return ret;
  304. }
  305. ui8 * CLodHandler::getUnpackedFile( const std::string & path, int * sizeOut )
  306. {
  307. const int bufsize = 65536;
  308. int mapsize = 0;
  309. gzFile map = gzopen(path.c_str(), "rb");
  310. assert(map);
  311. std::vector<ui8 *> mapstr;
  312. // Read a map by chunks
  313. // We could try to read the map size directly (cf RFC 1952) and then read
  314. // directly the whole map, but that would create more problems.
  315. do {
  316. ui8 *buf = new ui8[bufsize];
  317. int ret = gzread(map, buf, bufsize);
  318. if (ret == 0 || ret == -1) {
  319. delete [] buf;
  320. break;
  321. }
  322. mapstr.push_back(buf);
  323. mapsize += ret;
  324. } while(1);
  325. gzclose(map);
  326. // Now that we know the uncompressed size, reassemble the chunks
  327. ui8 *initTable = new ui8[mapsize];
  328. std::vector<ui8 *>::iterator it;
  329. int offset;
  330. int tocopy = mapsize;
  331. for (it = mapstr.begin(), offset = 0;
  332. it != mapstr.end();
  333. it++, offset+=bufsize ) {
  334. memcpy(&initTable[offset], *it, tocopy > bufsize ? bufsize : tocopy);
  335. tocopy -= bufsize;
  336. delete [] *it;
  337. }
  338. *sizeOut = mapsize;
  339. return initTable;
  340. }