CLoadFile.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /*
  2. * CLoadFile.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "CLoadFile.h"
  12. VCMI_LIB_NAMESPACE_BEGIN
  13. template <typename From, typename To>
  14. struct static_caster
  15. {
  16. To operator()(From p) {return static_cast<To>(p);}
  17. };
  18. CLoadFile::CLoadFile(const boost::filesystem::path & fname, IGameCallback * cb)
  19. : serializer(this)
  20. , sfile(fname.c_str(), std::ios::in | std::ios::binary)
  21. {
  22. serializer.cb = cb;
  23. serializer.loadingGamestate = true;
  24. assert(!serializer.reverseEndianness);
  25. sfile.exceptions(std::ifstream::failbit | std::ifstream::badbit); //we throw a lot anyway
  26. if(!sfile)
  27. throw std::runtime_error("Error: cannot open file '" + fname.string() + "' for reading!");
  28. static const std::string MAGIC = "VCMI";
  29. std::string readMagic = MAGIC;
  30. sfile.read(readMagic.data(), 4);
  31. if(readMagic != MAGIC)
  32. throw std::runtime_error("Error: '" + fname.string() + "' is not a VCMI file!");
  33. sfile.read(reinterpret_cast<char*>(&serializer.version), sizeof(serializer.version));
  34. if(serializer.version < ESerializationVersion::MINIMAL)
  35. throw std::runtime_error("Error: too old file format detected in '" + fname.string() + "'!");
  36. if(serializer.version > ESerializationVersion::CURRENT)
  37. {
  38. logGlobal->warn("Warning format version mismatch: found %d when current is %d! (file %s)\n", vstd::to_underlying(serializer.version), vstd::to_underlying(ESerializationVersion::CURRENT), fname.string());
  39. auto * versionptr = reinterpret_cast<char *>(&serializer.version);
  40. std::reverse(versionptr, versionptr + 4);
  41. logGlobal->warn("Version number reversed is %x, checking...", vstd::to_underlying(serializer.version));
  42. if(serializer.version == ESerializationVersion::CURRENT)
  43. {
  44. logGlobal->warn("%s seems to have different endianness! Entering reversing mode.", fname.string());
  45. serializer.reverseEndianness = true;
  46. }
  47. else
  48. throw std::runtime_error("Error: too new file format detected in '" + fname.string() + "'!");
  49. }
  50. std::string loaded = SAVEGAME_MAGIC;
  51. sfile.read(loaded.data(), SAVEGAME_MAGIC.length());
  52. if(loaded != SAVEGAME_MAGIC)
  53. throw std::runtime_error("Magic bytes doesn't match!");
  54. }
  55. int CLoadFile::read(std::byte * data, unsigned size)
  56. {
  57. sfile.read(reinterpret_cast<char *>(data), size);
  58. return size;
  59. }
  60. VCMI_LIB_NAMESPACE_END