CLodHandler.cpp 9.4 KB

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