CLodHandler.cpp 9.6 KB

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