2
0

CLodHandler.cpp 9.7 KB

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