BinaryDeserializer.h 13 KB

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