CLodHandler.cpp 9.3 KB

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