BinaryDeserializer.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607
  1. /*
  2. * BinaryDeserializer.h, 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. #pragma once
  11. #include <boost/mpl/for_each.hpp>
  12. #include "CTypeList.h"
  13. #include "../mapObjects/CGHeroInstance.h"
  14. #include "../../Global.h"
  15. VCMI_LIB_NAMESPACE_BEGIN
  16. class CStackInstance;
  17. class FileStream;
  18. class DLL_LINKAGE CLoaderBase
  19. {
  20. protected:
  21. IBinaryReader * reader;
  22. public:
  23. CLoaderBase(IBinaryReader * r): reader(r){};
  24. inline int read(void * data, unsigned size)
  25. {
  26. return reader->read(data, size);
  27. };
  28. };
  29. /// Main class for deserialization of classes from binary form
  30. /// Effectively revesed version of BinarySerializer
  31. class DLL_LINKAGE BinaryDeserializer : public CLoaderBase
  32. {
  33. template<typename Variant, typename Source>
  34. struct VariantLoaderHelper
  35. {
  36. Source & source;
  37. std::vector<std::function<Variant()>> funcs;
  38. VariantLoaderHelper(Source & source):
  39. source(source)
  40. {
  41. boost::mpl::for_each<typename Variant::types>(std::ref(*this));
  42. }
  43. template<typename Type>
  44. void operator()(Type)
  45. {
  46. funcs.push_back([&]() -> Variant
  47. {
  48. Type obj;
  49. source.load(obj);
  50. return Variant(obj);
  51. });
  52. }
  53. };
  54. template<typename Ser,typename T>
  55. struct LoadIfStackInstance
  56. {
  57. static bool invoke(Ser &s, T &data)
  58. {
  59. return false;
  60. }
  61. };
  62. template<typename Ser>
  63. struct LoadIfStackInstance<Ser, CStackInstance *>
  64. {
  65. static bool invoke(Ser &s, CStackInstance* &data)
  66. {
  67. CArmedInstance *armedObj;
  68. SlotID slot;
  69. s.load(armedObj);
  70. s.load(slot);
  71. if(slot != SlotID::COMMANDER_SLOT_PLACEHOLDER)
  72. {
  73. assert(armedObj->hasStackAtSlot(slot));
  74. data = armedObj->stacks[slot];
  75. }
  76. else
  77. {
  78. auto hero = dynamic_cast<CGHeroInstance *>(armedObj);
  79. assert(hero);
  80. assert(hero->commander);
  81. data = hero->commander;
  82. }
  83. return true;
  84. }
  85. };
  86. template <typename T, typename Enable = void>
  87. struct ClassObjectCreator
  88. {
  89. static T *invoke()
  90. {
  91. static_assert(!std::is_abstract<T>::value, "Cannot call new upon abstract classes!");
  92. return new T();
  93. }
  94. };
  95. template<typename T>
  96. struct ClassObjectCreator<T, typename std::enable_if<std::is_abstract<T>::value>::type>
  97. {
  98. static T *invoke()
  99. {
  100. throw std::runtime_error("Something went really wrong during deserialization. Attempted creating an object of an abstract class " + std::string(typeid(T).name()));
  101. }
  102. };
  103. STRONG_INLINE ui32 readAndCheckLength()
  104. {
  105. ui32 length;
  106. load(length);
  107. if(length > 500000)
  108. {
  109. logGlobal->warn("Warning: very big length: %d", length);
  110. reader->reportState(logGlobal);
  111. };
  112. return length;
  113. }
  114. template <typename T> class CPointerLoader;
  115. class CBasicPointerLoader
  116. {
  117. public:
  118. virtual const std::type_info * loadPtr(CLoaderBase &ar, void *data, ui32 pid) const =0; //data is pointer to the ACTUAL POINTER
  119. virtual ~CBasicPointerLoader(){}
  120. template<typename T> static CBasicPointerLoader *getApplier(const T * t=nullptr)
  121. {
  122. return new CPointerLoader<T>();
  123. }
  124. };
  125. template <typename T> class CPointerLoader : public CBasicPointerLoader
  126. {
  127. public:
  128. const std::type_info * loadPtr(CLoaderBase &ar, void *data, ui32 pid) const override //data is pointer to the ACTUAL POINTER
  129. {
  130. BinaryDeserializer &s = static_cast<BinaryDeserializer&>(ar);
  131. T *&ptr = *static_cast<T**>(data);
  132. //create new object under pointer
  133. typedef typename std::remove_pointer<T>::type npT;
  134. ptr = ClassObjectCreator<npT>::invoke(); //does new npT or throws for abstract classes
  135. s.ptrAllocated(ptr, pid);
  136. //T is most derived known type, it's time to call actual serialize
  137. assert(s.fileVersion != 0);
  138. ptr->serialize(s,s.fileVersion);
  139. return &typeid(T);
  140. }
  141. };
  142. CApplier<CBasicPointerLoader> applier;
  143. int write(const void * data, unsigned size);
  144. public:
  145. bool reverseEndianess; //if source has different endianness than us, we reverse bytes
  146. si32 fileVersion;
  147. std::map<ui32, void*> loadedPointers;
  148. std::map<ui32, const std::type_info*> loadedPointersTypes;
  149. std::map<const void*, boost::any> loadedSharedPointers;
  150. bool smartPointerSerialization;
  151. bool saving;
  152. BinaryDeserializer(IBinaryReader * r): CLoaderBase(r)
  153. {
  154. saving = false;
  155. fileVersion = 0;
  156. smartPointerSerialization = true;
  157. reverseEndianess = false;
  158. }
  159. template<class T>
  160. BinaryDeserializer & operator&(T & t)
  161. {
  162. this->load(t);
  163. return * this;
  164. }
  165. template < class T, typename std::enable_if < std::is_fundamental<T>::value && !std::is_same<T, bool>::value, int >::type = 0 >
  166. void load(T &data)
  167. {
  168. unsigned length = sizeof(data);
  169. char* dataPtr = (char*)&data;
  170. this->read(dataPtr,length);
  171. if(reverseEndianess)
  172. std::reverse(dataPtr, dataPtr + length);
  173. }
  174. template < typename T, typename std::enable_if < is_serializeable<BinaryDeserializer, T>::value, int >::type = 0 >
  175. void load(T &data)
  176. {
  177. assert( fileVersion != 0 );
  178. ////that const cast is evil because it allows to implicitly overwrite const objects when deserializing
  179. typedef typename std::remove_const<T>::type nonConstT;
  180. nonConstT &hlp = const_cast<nonConstT&>(data);
  181. hlp.serialize(*this,fileVersion);
  182. }
  183. template < typename T, typename std::enable_if < std::is_array<T>::value, int >::type = 0 >
  184. void load(T &data)
  185. {
  186. ui32 size = ARRAY_COUNT(data);
  187. for(ui32 i = 0; i < size; i++)
  188. load(data[i]);
  189. }
  190. template < typename T, typename std::enable_if < std::is_enum<T>::value, int >::type = 0 >
  191. void load(T &data)
  192. {
  193. si32 read;
  194. load( read );
  195. data = static_cast<T>(read);
  196. }
  197. template < typename T, typename std::enable_if < std::is_same<T, bool>::value, int >::type = 0 >
  198. void load(T &data)
  199. {
  200. ui8 read;
  201. load( read );
  202. data = static_cast<bool>(read);
  203. }
  204. template < typename T, typename std::enable_if < std::is_same<T, std::vector<bool> >::value, int >::type = 0 >
  205. void load(T & data)
  206. {
  207. std::vector<ui8> convData;
  208. load(convData);
  209. convData.resize(data.size());
  210. range::copy(convData, data.begin());
  211. }
  212. template <typename T, typename std::enable_if < !std::is_same<T, bool >::value, int >::type = 0>
  213. void load(std::vector<T> &data)
  214. {
  215. ui32 length = readAndCheckLength();
  216. data.resize(length);
  217. for(ui32 i=0;i<length;i++)
  218. load( data[i]);
  219. }
  220. template < typename T, typename std::enable_if < std::is_pointer<T>::value, int >::type = 0 >
  221. void load(T &data)
  222. {
  223. ui8 hlp;
  224. load( hlp );
  225. if(!hlp)
  226. {
  227. data = nullptr;
  228. return;
  229. }
  230. if(reader->smartVectorMembersSerialization)
  231. {
  232. typedef typename std::remove_const<typename std::remove_pointer<T>::type>::type TObjectType; //eg: const CGHeroInstance * => CGHeroInstance
  233. typedef typename VectorizedTypeFor<TObjectType>::type VType; //eg: CGHeroInstance -> CGobjectInstance
  234. typedef typename VectorizedIDType<TObjectType>::type IDType;
  235. if(const auto *info = reader->getVectorizedTypeInfo<VType, IDType>())
  236. {
  237. IDType id;
  238. load(id);
  239. if(id != IDType(-1))
  240. {
  241. data = static_cast<T>(reader->getVectorItemFromId<VType, IDType>(*info, id));
  242. return;
  243. }
  244. }
  245. }
  246. if(reader->sendStackInstanceByIds)
  247. {
  248. bool gotLoaded = LoadIfStackInstance<BinaryDeserializer,T>::invoke(* this, data);
  249. if(gotLoaded)
  250. return;
  251. }
  252. ui32 pid = 0xffffffff; //pointer id (or maybe rather pointee id)
  253. if(smartPointerSerialization)
  254. {
  255. load( pid ); //get the id
  256. std::map<ui32, void*>::iterator i = loadedPointers.find(pid); //lookup
  257. if(i != loadedPointers.end())
  258. {
  259. // We already got this pointer
  260. // Cast it in case we are loading it to a non-first base pointer
  261. assert(loadedPointersTypes.count(pid));
  262. data = reinterpret_cast<T>(typeList.castRaw(i->second, loadedPointersTypes.at(pid), &typeid(typename std::remove_const<typename std::remove_pointer<T>::type>::type)));
  263. return;
  264. }
  265. }
  266. //get type id
  267. ui16 tid;
  268. load( tid );
  269. if(!tid)
  270. {
  271. typedef typename std::remove_pointer<T>::type npT;
  272. typedef typename std::remove_const<npT>::type ncpT;
  273. data = ClassObjectCreator<ncpT>::invoke();
  274. ptrAllocated(data, pid);
  275. load(*data);
  276. }
  277. else
  278. {
  279. auto app = applier.getApplier(tid);
  280. if(app == nullptr)
  281. {
  282. logGlobal->error("load %d %d - no loader exists", tid, pid);
  283. data = nullptr;
  284. return;
  285. }
  286. auto typeInfo = app->loadPtr(*this,&data, pid);
  287. data = reinterpret_cast<T>(typeList.castRaw((void*)data, typeInfo, &typeid(typename std::remove_const<typename std::remove_pointer<T>::type>::type)));
  288. }
  289. }
  290. template <typename T>
  291. void ptrAllocated(const T *ptr, ui32 pid)
  292. {
  293. if(smartPointerSerialization && pid != 0xffffffff)
  294. {
  295. loadedPointersTypes[pid] = &typeid(T);
  296. loadedPointers[pid] = (void*)ptr; //add loaded pointer to our lookup map; cast is to avoid errors with const T* pt
  297. }
  298. }
  299. template<typename Base, typename Derived> void registerType(const Base * b = nullptr, const Derived * d = nullptr)
  300. {
  301. applier.registerType(b, d);
  302. }
  303. template <typename T>
  304. void load(std::shared_ptr<T> &data)
  305. {
  306. typedef typename std::remove_const<T>::type NonConstT;
  307. NonConstT *internalPtr;
  308. load(internalPtr);
  309. void *internalPtrDerived = typeList.castToMostDerived(internalPtr);
  310. if(internalPtr)
  311. {
  312. auto itr = loadedSharedPointers.find(internalPtrDerived);
  313. if(itr != loadedSharedPointers.end())
  314. {
  315. // This pointers is already loaded. The "data" needs to be pointed to it,
  316. // so their shared state is actually shared.
  317. try
  318. {
  319. auto actualType = typeList.getTypeInfo(internalPtr);
  320. auto typeWeNeedToReturn = typeList.getTypeInfo<T>();
  321. if(*actualType == *typeWeNeedToReturn)
  322. {
  323. // No casting needed, just unpack already stored shared_ptr and return it
  324. data = boost::any_cast<std::shared_ptr<T>>(itr->second);
  325. }
  326. else
  327. {
  328. // We need to perform series of casts
  329. auto ret = typeList.castShared(itr->second, actualType, typeWeNeedToReturn);
  330. data = boost::any_cast<std::shared_ptr<T>>(ret);
  331. }
  332. }
  333. catch(std::exception &e)
  334. {
  335. logGlobal->error(e.what());
  336. logGlobal->error("Failed to cast stored shared ptr. Real type: %s. Needed type %s. FIXME FIXME FIXME", itr->second.type().name(), typeid(std::shared_ptr<T>).name());
  337. //TODO scenario with inheritance -> we can have stored ptr to base and load ptr to derived (or vice versa)
  338. throw;
  339. }
  340. }
  341. else
  342. {
  343. auto hlp = std::shared_ptr<NonConstT>(internalPtr);
  344. data = hlp;
  345. loadedSharedPointers[internalPtrDerived] = typeList.castSharedToMostDerived(hlp);
  346. }
  347. }
  348. else
  349. data.reset();
  350. }
  351. template <typename T>
  352. void load(std::shared_ptr<const T> &data) //version of the above for const ptr
  353. {
  354. typedef typename std::remove_const<T>::type NonConstT;
  355. NonConstT *internalPtr;
  356. load(internalPtr);
  357. void *internalPtrDerived = typeList.castToMostDerived(internalPtr);
  358. if(internalPtr)
  359. {
  360. auto itr = loadedSharedPointers.find(internalPtrDerived);
  361. if(itr != loadedSharedPointers.end())
  362. {
  363. // This pointer is already loaded. The "data" needs to be pointed to it,
  364. // so their shared state is actually shared.
  365. try
  366. {
  367. auto actualType = typeList.getTypeInfo(internalPtr);
  368. auto typeWeNeedToReturn = typeList.getTypeInfo<T>();
  369. if(*actualType == *typeWeNeedToReturn)
  370. {
  371. // No casting needed, just unpack already stored shared_ptr and return it
  372. data = boost::any_cast<std::shared_ptr<const T>>(itr->second);
  373. }
  374. else
  375. {
  376. // We need to perform series of casts
  377. auto ret = typeList.castShared(itr->second, actualType, typeWeNeedToReturn);
  378. data = boost::any_cast<std::shared_ptr<const T>>(ret);
  379. }
  380. }
  381. catch(std::exception &e)
  382. {
  383. logGlobal->error(e.what());
  384. logGlobal->error("Failed to cast stored shared ptr. Real type: %s. Needed type %s. FIXME FIXME FIXME", itr->second.type().name(), typeid(std::shared_ptr<T>).name());
  385. //TODO scenario with inheritance -> we can have stored ptr to base and load ptr to derived (or vice versa)
  386. throw;
  387. }
  388. }
  389. else
  390. {
  391. auto hlp = std::shared_ptr<const T>(internalPtr);
  392. data = hlp; //possibly adds const
  393. loadedSharedPointers[internalPtrDerived] = typeList.castSharedToMostDerived(hlp);
  394. }
  395. }
  396. else
  397. data.reset();
  398. }
  399. template <typename T>
  400. void load(std::unique_ptr<T> &data)
  401. {
  402. T *internalPtr;
  403. load( internalPtr );
  404. data.reset(internalPtr);
  405. }
  406. template <typename T, size_t N>
  407. void load(std::array<T, N> &data)
  408. {
  409. for(ui32 i = 0; i < N; i++)
  410. load( data[i] );
  411. }
  412. template <typename T>
  413. void load(std::set<T> &data)
  414. {
  415. ui32 length = readAndCheckLength();
  416. data.clear();
  417. T ins;
  418. for(ui32 i=0;i<length;i++)
  419. {
  420. load( ins );
  421. data.insert(ins);
  422. }
  423. }
  424. template <typename T, typename U>
  425. void load(std::unordered_set<T, U> &data)
  426. {
  427. ui32 length = readAndCheckLength();
  428. data.clear();
  429. T ins;
  430. for(ui32 i=0;i<length;i++)
  431. {
  432. load(ins);
  433. data.insert(ins);
  434. }
  435. }
  436. template <typename T>
  437. void load(std::list<T> &data)
  438. {
  439. ui32 length = readAndCheckLength();
  440. data.clear();
  441. T ins;
  442. for(ui32 i=0;i<length;i++)
  443. {
  444. load(ins);
  445. data.push_back(ins);
  446. }
  447. }
  448. template <typename T1, typename T2>
  449. void load(std::pair<T1,T2> &data)
  450. {
  451. load(data.first);
  452. load(data.second);
  453. }
  454. template <typename T1, typename T2>
  455. void load(std::map<T1,T2> &data)
  456. {
  457. ui32 length = readAndCheckLength();
  458. data.clear();
  459. T1 key;
  460. T2 value;
  461. for(ui32 i=0;i<length;i++)
  462. {
  463. load(key);
  464. load(value);
  465. data.insert(std::pair<T1, T2>(std::move(key), std::move(value)));
  466. }
  467. }
  468. template <typename T1, typename T2>
  469. void load(std::multimap<T1, T2> &data)
  470. {
  471. ui32 length = readAndCheckLength();
  472. data.clear();
  473. T1 key;
  474. T2 value;
  475. for(ui32 i = 0; i < length; i++)
  476. {
  477. load(key);
  478. load(value);
  479. data.insert(std::pair<T1, T2>(std::move(key), std::move(value)));
  480. }
  481. }
  482. void load(std::string &data)
  483. {
  484. ui32 length = readAndCheckLength();
  485. data.resize(length);
  486. this->read((void*)data.c_str(),length);
  487. }
  488. template <BOOST_VARIANT_ENUM_PARAMS(typename T)>
  489. void load(boost::variant<BOOST_VARIANT_ENUM_PARAMS(T)> &data)
  490. {
  491. typedef boost::variant<BOOST_VARIANT_ENUM_PARAMS(T)> TVariant;
  492. VariantLoaderHelper<TVariant, BinaryDeserializer> loader(*this);
  493. si32 which;
  494. load( which );
  495. assert(which < loader.funcs.size());
  496. data = loader.funcs.at(which)();
  497. }
  498. template <typename T>
  499. void load(boost::optional<T> & data)
  500. {
  501. ui8 present;
  502. load( present );
  503. if(present)
  504. {
  505. //TODO: replace with emplace once we start request Boost 1.56+, see PR360
  506. T t;
  507. load(t);
  508. data = boost::make_optional(std::move(t));
  509. }
  510. else
  511. {
  512. data = boost::optional<T>();
  513. }
  514. }
  515. template <typename T>
  516. void load(boost::multi_array<T, 3> & data)
  517. {
  518. ui32 length = readAndCheckLength();
  519. ui32 x, y, z;
  520. load(x);
  521. load(y);
  522. load(z);
  523. data.resize(boost::extents[x][y][z]);
  524. assert(length == data.num_elements()); //x*y*z should be equal to number of elements
  525. for(ui32 i = 0; i < length; i++)
  526. load(data.data()[i]);
  527. }
  528. };
  529. class DLL_LINKAGE CLoadFile : public IBinaryReader
  530. {
  531. public:
  532. BinaryDeserializer serializer;
  533. std::string fName;
  534. std::unique_ptr<FileStream> sfile;
  535. CLoadFile(const boost::filesystem::path & fname, int minimalVersion = SERIALIZATION_VERSION); //throws!
  536. virtual ~CLoadFile();
  537. int read(void * data, unsigned size) override; //throws!
  538. void openNextFile(const boost::filesystem::path & fname, int minimalVersion); //throws!
  539. void clear();
  540. void reportState(vstd::CLoggerBase * out) override;
  541. void checkMagicBytes(const std::string & text);
  542. template<class T>
  543. CLoadFile & operator>>(T &t)
  544. {
  545. serializer & t;
  546. return * this;
  547. }
  548. };
  549. VCMI_LIB_NAMESPACE_END