Connection.h 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314
  1. /*
  2. * Connection.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 <typeinfo> //XXX this is in namespace std if you want w/o use typeinfo.h?
  12. #include <boost/type_traits/is_fundamental.hpp>
  13. #include <boost/type_traits/is_enum.hpp>
  14. #include <boost/type_traits/is_pointer.hpp>
  15. #include <boost/type_traits/is_class.hpp>
  16. #include <boost/type_traits/is_base_of.hpp>
  17. #include <boost/type_traits/is_array.hpp>
  18. #include <boost/type_traits/remove_pointer.hpp>
  19. #include <boost/type_traits/remove_const.hpp>
  20. #include <boost/variant.hpp>
  21. #include <boost/mpl/eval_if.hpp>
  22. #include <boost/mpl/equal_to.hpp>
  23. #include <boost/mpl/int.hpp>
  24. #include <boost/mpl/identity.hpp>
  25. #include <boost/any.hpp>
  26. #include "ConstTransitivePtr.h"
  27. #include "CCreatureSet.h" //for CStackInstance
  28. #include "CObjectHandler.h" //for CArmedInstance
  29. #include "Mapping/CCampaignHandler.h" //for CCampaignState
  30. const ui32 version = 737;
  31. class CConnection;
  32. class CGObjectInstance;
  33. class CStackInstance;
  34. class CGameState;
  35. class CCreature;
  36. class LibClasses;
  37. class CHero;
  38. struct CPack;
  39. extern DLL_LINKAGE LibClasses * VLC;
  40. namespace mpl = boost::mpl;
  41. namespace boost
  42. {
  43. namespace asio
  44. {
  45. namespace ip
  46. {
  47. class tcp;
  48. }
  49. class io_service;
  50. template <typename Protocol> class stream_socket_service;
  51. template <typename Protocol,typename StreamSocketService>
  52. class basic_stream_socket;
  53. template <typename Protocol> class socket_acceptor_service;
  54. template <typename Protocol,typename SocketAcceptorService>
  55. class basic_socket_acceptor;
  56. }
  57. class mutex;
  58. }
  59. enum SerializationLvl
  60. {
  61. Wrong=0,
  62. Boolean,
  63. Primitive,
  64. Array,
  65. Pointer,
  66. Enum,
  67. Serializable,
  68. BooleanVector
  69. };
  70. struct TypeComparer
  71. {
  72. bool operator()(const std::type_info *a, const std::type_info *b) const
  73. {
  74. return a->before(*b);
  75. }
  76. };
  77. class DLL_LINKAGE CTypeList
  78. {
  79. typedef std::multimap<const std::type_info *,ui16,TypeComparer> TTypeMap;
  80. TTypeMap types;
  81. public:
  82. CTypeList();
  83. ui16 registerType(const std::type_info *type);
  84. template <typename T> ui16 registerType(const T * t = NULL)
  85. {
  86. return registerType(getTypeInfo(t));
  87. }
  88. ui16 getTypeID(const std::type_info *type);
  89. template <typename T> ui16 getTypeID(const T * t = NULL)
  90. {
  91. return getTypeID(getTypeInfo(t));
  92. }
  93. template <typename T> const std::type_info * getTypeInfo(const T * t = NULL)
  94. {
  95. if(t)
  96. return &typeid(*t);
  97. else
  98. return &typeid(T);
  99. }
  100. };
  101. extern DLL_LINKAGE CTypeList typeList;
  102. template<typename Ser>
  103. struct SaveBoolean
  104. {
  105. static void invoke(Ser &s, const bool &data)
  106. {
  107. s.saveBoolean(data);
  108. }
  109. };
  110. template<typename Ser>
  111. struct LoadBoolean
  112. {
  113. static void invoke(Ser &s, bool &data)
  114. {
  115. s.loadBoolean(data);
  116. }
  117. };
  118. template<typename Ser>
  119. struct SaveBooleanVector
  120. {
  121. static void invoke(Ser &s, const std::vector<bool> &data)
  122. {
  123. s.saveBooleanVector(data);
  124. }
  125. };
  126. template<typename Ser>
  127. struct LoadBooleanVector
  128. {
  129. static void invoke(Ser &s, std::vector<bool> &data)
  130. {
  131. s.loadBooleanVector(data);
  132. }
  133. };
  134. template<typename Ser,typename T>
  135. struct SavePrimitive
  136. {
  137. static void invoke(Ser &s, const T &data)
  138. {
  139. s.savePrimitive(data);
  140. }
  141. };
  142. template<typename Ser,typename T>
  143. struct SaveSerializable
  144. {
  145. static void invoke(Ser &s, const T &data)
  146. {
  147. s.saveSerializable(data);
  148. }
  149. };
  150. template<typename Ser,typename T>
  151. struct SaveEnum
  152. {
  153. static void invoke(Ser &s, const T &data)
  154. {
  155. s.saveEnum(data);
  156. }
  157. };
  158. template<typename Ser,typename T>
  159. struct LoadEnum
  160. {
  161. static void invoke(Ser &s, T &data)
  162. {
  163. s.loadEnum(data);
  164. }
  165. };
  166. template<typename Ser,typename T>
  167. struct LoadPrimitive
  168. {
  169. static void invoke(Ser &s, T &data)
  170. {
  171. s.loadPrimitive(data);
  172. }
  173. };
  174. template<typename Ser,typename T>
  175. struct SavePointer
  176. {
  177. static void invoke(Ser &s, const T &data)
  178. {
  179. s.savePointer(data);
  180. }
  181. };
  182. template<typename Ser,typename T>
  183. struct LoadPointer
  184. {
  185. static void invoke(Ser &s, T &data)
  186. {
  187. s.loadPointer(data);
  188. }
  189. };
  190. template<typename Ser,typename T>
  191. struct SaveArray
  192. {
  193. static void invoke(Ser &s, const T &data)
  194. {
  195. s.saveArray(data);
  196. }
  197. };
  198. template<typename Ser,typename T>
  199. struct LoadArray
  200. {
  201. static void invoke(Ser &s, T &data)
  202. {
  203. s.loadArray(data);
  204. }
  205. };
  206. template<typename Ser,typename T>
  207. struct LoadSerializable
  208. {
  209. static void invoke(Ser &s, T &data)
  210. {
  211. s.loadSerializable(data);
  212. }
  213. };
  214. template<typename Ser,typename T>
  215. struct SaveWrong
  216. {
  217. static void invoke(Ser &s, const T &data)
  218. {
  219. throw std::runtime_error("Wrong save serialization call!");
  220. }
  221. };
  222. template<typename Ser,typename T>
  223. struct LoadWrong
  224. {
  225. static void invoke(Ser &s, const T &data)
  226. {
  227. throw std::runtime_error("Wrong load serialization call!");
  228. }
  229. };
  230. template<typename T>
  231. struct SerializationLevel
  232. {
  233. typedef mpl::integral_c_tag tag;
  234. typedef
  235. typename mpl::eval_if<
  236. boost::is_same<T, bool>,
  237. mpl::int_<Boolean>,
  238. //else
  239. typename mpl::eval_if<
  240. boost::is_same<T, std::vector<bool> >,
  241. mpl::int_<BooleanVector>,
  242. //else
  243. typename mpl::eval_if<
  244. boost::is_fundamental<T>,
  245. mpl::int_<Primitive>,
  246. //else
  247. typename mpl::eval_if<
  248. boost::is_enum<T>,
  249. mpl::int_<Enum>,
  250. //else
  251. typename mpl::eval_if<
  252. boost::is_class<T>,
  253. mpl::int_<Serializable>,
  254. //else
  255. typename mpl::eval_if<
  256. boost::is_array<T>,
  257. mpl::int_<Array>,
  258. //else
  259. typename mpl::eval_if<
  260. boost::is_pointer<T>,
  261. mpl::int_<Pointer>,
  262. //else
  263. typename mpl::eval_if<
  264. boost::is_enum<T>,
  265. mpl::int_<Primitive>,
  266. //else
  267. mpl::int_<Wrong>
  268. >
  269. >
  270. >
  271. >
  272. >
  273. >
  274. >
  275. >::type type;
  276. static const int value = SerializationLevel::type::value;
  277. };
  278. template <typename T, typename U>
  279. struct VectorisedObjectInfo
  280. {
  281. const std::vector<ConstTransitivePtr<T> > *vector; //pointer to the appropriate vector
  282. const U T::*idPtr; //pointer to the field representing the position in the vector
  283. VectorisedObjectInfo(const std::vector< ConstTransitivePtr<T> > *Vector, const U T::*IdPtr)
  284. :vector(Vector), idPtr(IdPtr)
  285. {
  286. }
  287. };
  288. template<typename T>
  289. si32 idToNumber(const T &t, typename boost::enable_if<boost::is_convertible<T,si32> >::type * dummy = 0)
  290. {
  291. return t;
  292. }
  293. template<typename T>
  294. si32 idToNumber(const BaseForID<T> &t)
  295. {
  296. return t.getNum();
  297. }
  298. /// Class which is responsible for storing and loading data.
  299. class DLL_LINKAGE CSerializer
  300. {
  301. public:
  302. typedef std::map<const std::type_info *, boost::any, TypeComparer> TTypeVecMap;
  303. TTypeVecMap vectors; //entry must be a pointer to vector containing pointers to the objects of key type
  304. bool smartVectorMembersSerialization;
  305. bool sendStackInstanceByIds;
  306. CSerializer();
  307. ~CSerializer();
  308. virtual void reportState(CLogger &out){};
  309. template <typename T, typename U>
  310. void registerVectoredType(const std::vector<T*> *Vector, const U T::*IdPtr)
  311. {
  312. vectors[&typeid(T)] = VectorisedObjectInfo<T, U>(Vector, IdPtr);
  313. }
  314. template <typename T, typename U>
  315. void registerVectoredType(const std::vector<ConstTransitivePtr<T> > *Vector, const U T::*IdPtr)
  316. {
  317. vectors[&typeid(T)] = VectorisedObjectInfo<T, U>(Vector, IdPtr);
  318. }
  319. template <typename T, typename U>
  320. const VectorisedObjectInfo<T, U> *getVectorisedTypeInfo()
  321. {
  322. const std::type_info *myType = NULL;
  323. //
  324. // if(boost::is_base_of<CGObjectInstance, T>::value) //ugly workaround to support also types derived from CGObjectInstance -> if we encounter one, treat it aas CGObj..
  325. // myType = &typeid(CGObjectInstance);
  326. // else
  327. myType = &typeid(T);
  328. TTypeVecMap::iterator i = vectors.find(myType);
  329. if(i == vectors.end())
  330. return NULL;
  331. else
  332. {
  333. assert(!i->second.empty());
  334. assert(i->second.type() == typeid(VectorisedObjectInfo<T, U>));
  335. VectorisedObjectInfo<T, U> *ret = &(boost::any_cast<VectorisedObjectInfo<T, U>&>(i->second));
  336. return ret;
  337. }
  338. }
  339. template <typename T, typename U>
  340. T* getVectorItemFromId(const VectorisedObjectInfo<T, U> &oInfo, U id) const
  341. {
  342. /* if(id < 0)
  343. return NULL;*/
  344. si32 idAsNumber = idToNumber(id);
  345. assert(oInfo.vector);
  346. assert(oInfo.vector->size() > idAsNumber);
  347. return const_cast<T*>((*oInfo.vector)[idAsNumber].get());
  348. }
  349. template <typename T, typename U>
  350. U getIdFromVectorItem(const VectorisedObjectInfo<T, U> &oInfo, const T* obj) const
  351. {
  352. if(!obj)
  353. return U(-1);
  354. return obj->*oInfo.idPtr;
  355. }
  356. void addStdVecItems(CGameState *gs, LibClasses *lib = VLC);
  357. };
  358. class DLL_LINKAGE CSaverBase : public virtual CSerializer
  359. {
  360. };
  361. class CBasicPointerSaver
  362. {
  363. public:
  364. virtual void savePtr(CSaverBase &ar, const void *data) const =0;
  365. virtual ~CBasicPointerSaver(){}
  366. };
  367. template <typename Serializer, typename T> class CPointerSaver : public CBasicPointerSaver
  368. {
  369. public:
  370. void savePtr(CSaverBase &ar, const void *data) const
  371. {
  372. Serializer &s = static_cast<Serializer&>(ar);
  373. const T *ptr = static_cast<const T*>(data);
  374. //T is most derived known type, it's time to call actual serialize
  375. const_cast<T&>(*ptr).serialize(s,version);
  376. }
  377. };
  378. template <typename T> //metafunction returning CGObjectInstance if T is its derivate or T elsewise
  379. struct VectorisedTypeFor
  380. {
  381. typedef typename
  382. //if
  383. mpl::eval_if<boost::is_base_of<CGObjectInstance,T>,
  384. mpl::identity<CGObjectInstance>,
  385. //else
  386. mpl::identity<T>
  387. >::type type;
  388. };
  389. template <typename U>
  390. struct VectorizedIDType
  391. {
  392. typedef typename
  393. //if
  394. mpl::eval_if<boost::is_same<CArtifact,U>,
  395. mpl::identity<ArtifactID>,
  396. //else if
  397. mpl::eval_if<boost::is_same<CCreature,U>,
  398. mpl::identity<CreatureID>,
  399. //else if
  400. mpl::eval_if<boost::is_same<CArtifactInstance,U>,
  401. mpl::identity<ArtifactInstanceID>,
  402. //else if
  403. mpl::eval_if<boost::is_base_of<CGObjectInstance,U>,
  404. mpl::identity<ObjectInstanceID>,
  405. //else
  406. mpl::identity<si32>
  407. > > > >::type type;
  408. };
  409. template <typename Handler>
  410. struct VariantVisitorSaver : boost::static_visitor<>
  411. {
  412. Handler &h;
  413. VariantVisitorSaver(Handler &H):h(H)
  414. {
  415. }
  416. template <typename T>
  417. void operator()(const T &t)
  418. {
  419. h << t;
  420. }
  421. };
  422. template<typename Ser,typename T>
  423. struct SaveIfStackInstance
  424. {
  425. static bool invoke(Ser &s, const T &data)
  426. {
  427. return false;
  428. }
  429. };
  430. template<typename Ser>
  431. struct SaveIfStackInstance<Ser, CStackInstance *>
  432. {
  433. static bool invoke(Ser &s, const CStackInstance* const &data)
  434. {
  435. assert(data->armyObj);
  436. SlotID slot;
  437. if(data->getNodeType() == CBonusSystemNode::COMMANDER)
  438. slot = SlotID::COMMANDER_SLOT_PLACEHOLDER;
  439. else
  440. slot = data->armyObj->findStack(data);
  441. assert(slot != SlotID());
  442. s << data->armyObj << slot;
  443. return true;
  444. }
  445. };
  446. template<typename Ser,typename T>
  447. struct LoadIfStackInstance
  448. {
  449. static bool invoke(Ser &s, T &data)
  450. {
  451. return false;
  452. }
  453. };
  454. template<typename Ser>
  455. struct LoadIfStackInstance<Ser, CStackInstance *>
  456. {
  457. static bool invoke(Ser &s, CStackInstance* &data)
  458. {
  459. CArmedInstance *armedObj;
  460. SlotID slot;
  461. s >> armedObj >> slot;
  462. if(slot != SlotID::COMMANDER_SLOT_PLACEHOLDER)
  463. {
  464. assert(armedObj->hasStackAtSlot(slot));
  465. data = armedObj->stacks[slot];
  466. }
  467. else
  468. {
  469. auto hero = dynamic_cast<CGHeroInstance *>(armedObj);
  470. assert(hero);
  471. assert(hero->commander);
  472. data = hero->commander;
  473. }
  474. return true;
  475. }
  476. };
  477. /// The class which manages saving objects.
  478. template <typename Serializer> class DLL_LINKAGE COSer : public CSaverBase
  479. {
  480. public:
  481. bool saving;
  482. std::map<ui16,CBasicPointerSaver*> savers; // typeID => CPointerSaver<serializer,type>
  483. std::map<const void*, ui32> savedPointers;
  484. bool smartPointerSerialization;
  485. COSer()
  486. {
  487. saving=true;
  488. smartPointerSerialization = true;
  489. }
  490. ~COSer()
  491. {
  492. std::map<ui16,CBasicPointerSaver*>::iterator iter;
  493. for(iter = savers.begin(); iter != savers.end(); iter++)
  494. delete iter->second;
  495. }
  496. template<typename T> void registerType(const T * t=NULL)
  497. {
  498. ui16 ID = typeList.registerType(t);
  499. savers[ID] = new CPointerSaver<COSer<Serializer>,T>;
  500. }
  501. Serializer * This()
  502. {
  503. return static_cast<Serializer*>(this);
  504. }
  505. template<class T>
  506. Serializer & operator<<(const T &t)
  507. {
  508. this->This()->save(t);
  509. return * this->This();
  510. }
  511. template<class T>
  512. COSer & operator&(const T & t)
  513. {
  514. return * this->This() << t;
  515. }
  516. int write(const void * data, unsigned size);
  517. template <typename T>
  518. void savePrimitive(const T &data)
  519. {
  520. this->This()->write(&data,sizeof(data));
  521. }
  522. template <typename T>
  523. void savePointer(const T &data)
  524. {
  525. //write if pointer is not NULL
  526. ui8 hlp = (data!=NULL);
  527. *this << hlp;
  528. //if pointer is NULL then we don't need anything more...
  529. if(!hlp)
  530. return;
  531. if(smartVectorMembersSerialization)
  532. {
  533. typedef typename boost::remove_const<typename boost::remove_pointer<T>::type>::type TObjectType;
  534. typedef typename VectorisedTypeFor<TObjectType>::type VType;
  535. typedef typename VectorizedIDType<TObjectType>::type IDType;
  536. if(const auto *info = getVectorisedTypeInfo<VType, IDType>())
  537. {
  538. IDType id = getIdFromVectorItem<VType>(*info, data);
  539. *this << id;
  540. if(id != IDType(-1)) //vector id is enough
  541. return;
  542. }
  543. }
  544. if(sendStackInstanceByIds)
  545. {
  546. const bool gotSaved = SaveIfStackInstance<Serializer,T>::invoke(*This(), data);
  547. if(gotSaved)
  548. return;
  549. }
  550. if(smartPointerSerialization)
  551. {
  552. std::map<const void*,ui32>::iterator i = savedPointers.find(data);
  553. if(i != savedPointers.end())
  554. {
  555. //this pointer has been already serialized - write only it's id
  556. *this << i->second;
  557. return;
  558. }
  559. //give id to this pointer
  560. ui32 pid = (ui32)savedPointers.size();
  561. savedPointers[data] = pid;
  562. *this << pid;
  563. }
  564. //write type identifier
  565. ui16 tid = typeList.getTypeID(data);
  566. *this << tid;
  567. This()->savePointerHlp(tid, data);
  568. }
  569. //that part of ptr serialization was extracted to allow customization of its behavior in derived classes
  570. template <typename T>
  571. void savePointerHlp(ui16 tid, const T &data)
  572. {
  573. if(!tid)
  574. *this << *data; //if type is unregistered simply write all data in a standard way
  575. else
  576. savers[tid]->savePtr(*this,data); //call serializer specific for our real type
  577. }
  578. template <typename T>
  579. void saveArray(const T &data)
  580. {
  581. ui32 size = ARRAY_COUNT(data);
  582. for(ui32 i=0; i < size; i++)
  583. *this << data[i];
  584. }
  585. template <typename T>
  586. void save(const T &data)
  587. {
  588. typedef
  589. //if
  590. typename mpl::eval_if< mpl::equal_to<SerializationLevel<T>,mpl::int_<Boolean> >,
  591. mpl::identity<SaveBoolean<Serializer> >,
  592. //else if
  593. typename mpl::eval_if< mpl::equal_to<SerializationLevel<T>,mpl::int_<BooleanVector> >,
  594. mpl::identity<SaveBooleanVector<Serializer> >,
  595. //else if
  596. typename mpl::eval_if< mpl::equal_to<SerializationLevel<T>,mpl::int_<Primitive> >,
  597. mpl::identity<SavePrimitive<Serializer,T> >,
  598. //else if
  599. typename mpl::eval_if<mpl::equal_to<SerializationLevel<T>,mpl::int_<Enum> >,
  600. mpl::identity<SaveEnum<Serializer,T> >,
  601. //else if
  602. typename mpl::eval_if<mpl::equal_to<SerializationLevel<T>,mpl::int_<Pointer> >,
  603. mpl::identity<SavePointer<Serializer,T> >,
  604. //else if
  605. typename mpl::eval_if<mpl::equal_to<SerializationLevel<T>,mpl::int_<Array> >,
  606. mpl::identity<SaveArray<Serializer,T> >,
  607. //else if
  608. typename mpl::eval_if<mpl::equal_to<SerializationLevel<T>,mpl::int_<Serializable> >,
  609. mpl::identity<SaveSerializable<Serializer,T> >,
  610. //else
  611. mpl::identity<SaveWrong<Serializer,T> >
  612. >
  613. >
  614. >
  615. >
  616. >
  617. >
  618. >::type typex;
  619. typex::invoke(* this->This(), data);
  620. }
  621. template <typename T>
  622. void saveSerializable(const T &data)
  623. {
  624. const_cast<T&>(data).serialize(*this,version);
  625. }
  626. template <typename T>
  627. void saveSerializable(const shared_ptr<T> &data)
  628. {
  629. T *internalPtr = data.get();
  630. *this << internalPtr;
  631. }
  632. template <typename T>
  633. void saveSerializable(const unique_ptr<T> &data)
  634. {
  635. T *internalPtr = data.get();
  636. *this << internalPtr;
  637. }
  638. template <typename T>
  639. void saveSerializable(const std::vector<T> &data)
  640. {
  641. ui32 length = data.size();
  642. *this << length;
  643. for(ui32 i=0;i<length;i++)
  644. *this << data[i];
  645. }
  646. template <typename T>
  647. void saveSerializable(const std::set<T> &data)
  648. {
  649. std::set<T> &d = const_cast<std::set<T> &>(data);
  650. ui32 length = d.size();
  651. *this << length;
  652. for(typename std::set<T>::iterator i=d.begin();i!=d.end();i++)
  653. *this << *i;
  654. }
  655. template <typename T, typename U>
  656. void saveSerializable(const boost::unordered_set<T, U> &data)
  657. {
  658. boost::unordered_set<T, U> &d = const_cast<boost::unordered_set<T, U> &>(data);
  659. ui32 length = d.size();
  660. *this << length;
  661. for(typename boost::unordered_set<T, U>::iterator i=d.begin();i!=d.end();i++)
  662. *this << *i;
  663. }
  664. template <typename T>
  665. void saveSerializable(const std::list<T> &data)
  666. {
  667. std::list<T> &d = const_cast<std::list<T> &>(data);
  668. ui32 length = d.size();
  669. *this << length;
  670. for(typename std::list<T>::iterator i=d.begin();i!=d.end();i++)
  671. *this << *i;
  672. }
  673. void saveSerializable(const std::string &data)
  674. {
  675. *this << ui32(data.length());
  676. this->This()->write(data.c_str(),data.size());
  677. }
  678. template <typename T1, typename T2>
  679. void saveSerializable(const std::pair<T1,T2> &data)
  680. {
  681. *this << data.first << data.second;
  682. }
  683. template <typename T1, typename T2>
  684. void saveSerializable(const std::map<T1,T2> &data)
  685. {
  686. *this << ui32(data.size());
  687. for(typename std::map<T1,T2>::const_iterator i=data.begin();i!=data.end();i++)
  688. *this << i->first << i->second;
  689. }
  690. template <BOOST_VARIANT_ENUM_PARAMS(typename T)>
  691. void saveSerializable(const boost::variant<BOOST_VARIANT_ENUM_PARAMS(T)> &data)
  692. {
  693. si32 which = data.which();
  694. *this << which;
  695. VariantVisitorSaver<Serializer> visitor(*this->This());
  696. boost::apply_visitor(visitor, data);
  697. }
  698. template <typename T>
  699. void saveSerializable(const boost::optional<T> &data)
  700. {
  701. if(data)
  702. {
  703. *this << (ui8)1;
  704. *this << *data;
  705. }
  706. else
  707. {
  708. *this << (ui8)0;
  709. }
  710. }
  711. template <typename E>
  712. void saveEnum(const E &data)
  713. {
  714. si32 writ = static_cast<si32>(data);
  715. *this << writ;
  716. }
  717. void saveBoolean(const bool & data)
  718. {
  719. ui8 writ = static_cast<ui8>(data);
  720. *this << writ;
  721. }
  722. void saveBooleanVector(const std::vector<bool> & data)
  723. {
  724. std::vector<ui8> convData;
  725. std::copy(data.begin(), data.end(), std::back_inserter(convData));
  726. saveSerializable(convData);
  727. }
  728. };
  729. class DLL_LINKAGE CLoaderBase : public virtual CSerializer
  730. {};
  731. class CBasicPointerLoader
  732. {
  733. public:
  734. virtual void loadPtr(CLoaderBase &ar, void *data, ui32 pid) const =0; //data is pointer to the ACTUAL POINTER
  735. virtual ~CBasicPointerLoader(){}
  736. };
  737. template <typename Serializer, typename T> class CPointerLoader : public CBasicPointerLoader
  738. {
  739. public:
  740. void loadPtr(CLoaderBase &ar, void *data, ui32 pid) const //data is pointer to the ACTUAL POINTER
  741. {
  742. Serializer &s = static_cast<Serializer&>(ar);
  743. T *&ptr = *static_cast<T**>(data);
  744. //create new object under pointer
  745. typedef typename boost::remove_pointer<T>::type npT;
  746. ptr = new npT;
  747. s.ptrAllocated(ptr, pid);
  748. //T is most derived known type, it's time to call actual serialize
  749. ptr->serialize(s,version);
  750. }
  751. };
  752. /// The class which manages loading of objects.
  753. template <typename Serializer> class DLL_LINKAGE CISer : public CLoaderBase
  754. {
  755. public:
  756. bool saving;
  757. std::map<ui16,CBasicPointerLoader*> loaders; // typeID => CPointerSaver<serializer,type>
  758. ui32 fileVersion;
  759. bool reverseEndianess; //if source has different endianess than us, we reverse bytes
  760. std::map<ui32, void*> loadedPointers;
  761. bool smartPointerSerialization;
  762. CISer()
  763. {
  764. saving = false;
  765. fileVersion = 0;
  766. smartPointerSerialization = true;
  767. reverseEndianess = false;
  768. }
  769. ~CISer()
  770. {
  771. std::map<ui16,CBasicPointerLoader*>::iterator iter;
  772. for(iter = loaders.begin(); iter != loaders.end(); iter++)
  773. delete iter->second;
  774. }
  775. template<typename T> void registerType(const T * t=NULL)
  776. {
  777. ui16 ID = typeList.registerType(t);
  778. loaders[ID] = new CPointerLoader<CISer<Serializer>,T>;
  779. }
  780. Serializer * This()
  781. {
  782. return static_cast<Serializer*>(this);
  783. }
  784. template<class T>
  785. Serializer & operator>>(T &t)
  786. {
  787. this->This()->load(t);
  788. return * this->This();
  789. }
  790. template<class T>
  791. CISer & operator&(T & t)
  792. {
  793. return * this->This() >> t;
  794. }
  795. int write(const void * data, unsigned size);
  796. template <typename T>
  797. void load(T &data)
  798. {
  799. typedef
  800. //if
  801. typename mpl::eval_if< mpl::equal_to<SerializationLevel<T>,mpl::int_<Boolean> >,
  802. mpl::identity<LoadBoolean<Serializer> >,
  803. //else if
  804. typename mpl::eval_if< mpl::equal_to<SerializationLevel<T>,mpl::int_<BooleanVector> >,
  805. mpl::identity<LoadBooleanVector<Serializer> >,
  806. //else if
  807. typename mpl::eval_if< mpl::equal_to<SerializationLevel<T>,mpl::int_<Primitive> >,
  808. mpl::identity<LoadPrimitive<Serializer,T> >,
  809. //else if
  810. typename mpl::eval_if<mpl::equal_to<SerializationLevel<T>,mpl::int_<Enum> >,
  811. mpl::identity<LoadEnum<Serializer,T> >,
  812. //else if
  813. typename mpl::eval_if<mpl::equal_to<SerializationLevel<T>,mpl::int_<Pointer> >,
  814. mpl::identity<LoadPointer<Serializer,T> >,
  815. //else if
  816. typename mpl::eval_if<mpl::equal_to<SerializationLevel<T>,mpl::int_<Array> >,
  817. mpl::identity<LoadArray<Serializer,T> >,
  818. //else if
  819. typename mpl::eval_if<mpl::equal_to<SerializationLevel<T>,mpl::int_<Serializable> >,
  820. mpl::identity<LoadSerializable<Serializer,T> >,
  821. //else
  822. mpl::identity<LoadWrong<Serializer,T> >
  823. >
  824. >
  825. >
  826. >
  827. >
  828. >
  829. >::type typex;
  830. typex::invoke(* this->This(), data);
  831. }
  832. template <typename T>
  833. void loadPrimitive(T &data)
  834. {
  835. if(0) //for testing #989
  836. {
  837. this->This()->read(&data,sizeof(data));
  838. }
  839. else
  840. {
  841. unsigned length = sizeof(data);
  842. char* dataPtr = (char*)&data;
  843. this->This()->read(dataPtr,length);
  844. if(reverseEndianess)
  845. std::reverse(dataPtr, dataPtr + length);
  846. }
  847. }
  848. template <typename T>
  849. void loadSerializableBySerializeCall(T &data)
  850. {
  851. ////that const cast is evil because it allows to implicitly overwrite const objects when deserializing
  852. typedef typename boost::remove_const<T>::type nonConstT;
  853. nonConstT &hlp = const_cast<nonConstT&>(data);
  854. hlp.serialize(*this,fileVersion);
  855. //data.serialize(*this,myVersion);
  856. }
  857. template <typename T>
  858. void loadSerializable(T &data)
  859. {
  860. loadSerializableBySerializeCall(data);
  861. }
  862. template <typename T>
  863. void loadArray(T &data)
  864. {
  865. ui32 size = ARRAY_COUNT(data);
  866. for(ui32 i = 0; i < size; i++)
  867. *this >> data[i];
  868. }
  869. template <typename T>
  870. void loadPointer(T &data)
  871. {
  872. ui8 hlp;
  873. *this >> hlp;
  874. if(!hlp)
  875. {
  876. data = NULL;
  877. return;
  878. }
  879. if(smartVectorMembersSerialization)
  880. {
  881. typedef typename boost::remove_const<typename boost::remove_pointer<T>::type>::type TObjectType; //eg: const CGHeroInstance * => CGHeroInstance
  882. typedef typename VectorisedTypeFor<TObjectType>::type VType; //eg: CGHeroInstance -> CGobjectInstance
  883. typedef typename VectorizedIDType<TObjectType>::type IDType;
  884. if(const auto *info = getVectorisedTypeInfo<VType, IDType>())
  885. {
  886. IDType id;
  887. *this >> id;
  888. if(id != IDType(-1))
  889. {
  890. data = static_cast<T>(getVectorItemFromId<VType, IDType>(*info, id));
  891. return;
  892. }
  893. }
  894. }
  895. if(sendStackInstanceByIds)
  896. {
  897. bool gotLoaded = LoadIfStackInstance<Serializer,T>::invoke(*This(), data);
  898. if(gotLoaded)
  899. return;
  900. }
  901. ui32 pid = 0xffffffff; //pointer id (or maybe rather pointee id)
  902. if(smartPointerSerialization)
  903. {
  904. *this >> pid; //get the id
  905. std::map<ui32, void*>::iterator i = loadedPointers.find(pid); //lookup
  906. if(i != loadedPointers.end())
  907. {
  908. //we already got this pointer
  909. data = static_cast<T>(i->second);
  910. return;
  911. }
  912. }
  913. //get type id
  914. ui16 tid;
  915. *this >> tid;
  916. This()->loadPointerHlp(tid, data, pid);
  917. }
  918. //that part of ptr deserialization was extracted to allow customization of its behavior in derived classes
  919. template <typename T>
  920. void loadPointerHlp( ui16 tid, T & data, ui32 pid )
  921. {
  922. if(!tid)
  923. {
  924. typedef typename boost::remove_pointer<T>::type npT;
  925. typedef typename boost::remove_const<npT>::type ncpT;
  926. data = new ncpT;
  927. ptrAllocated(data, pid);
  928. *this >> *data;
  929. }
  930. else
  931. {
  932. loaders[tid]->loadPtr(*this,&data, pid);
  933. }
  934. }
  935. template <typename T>
  936. void ptrAllocated(const T *ptr, ui32 pid)
  937. {
  938. if(smartPointerSerialization && pid != 0xffffffff)
  939. loadedPointers[pid] = (void*)ptr; //add loaded pointer to our lookup map; cast is to avoid errors with const T* pt
  940. }
  941. #define READ_CHECK_U32(x) \
  942. ui32 length; \
  943. *this >> length; \
  944. if(length > 500000) \
  945. { \
  946. tlog2 << "Warning: very big length: " << length << "\n" ;\
  947. reportState(tlog2); \
  948. };
  949. template <typename T>
  950. void loadSerializable(shared_ptr<T> &data)
  951. {
  952. T *internalPtr;
  953. *this >> internalPtr;
  954. data.reset(internalPtr);
  955. }
  956. template <typename T>
  957. void loadSerializable(unique_ptr<T> &data)
  958. {
  959. T *internalPtr;
  960. *this >> internalPtr;
  961. data.reset(internalPtr);
  962. }
  963. template <typename T>
  964. void loadSerializable(std::vector<T> &data)
  965. {
  966. READ_CHECK_U32(length);
  967. data.resize(length);
  968. for(ui32 i=0;i<length;i++)
  969. *this >> data[i];
  970. }
  971. template <typename T>
  972. void loadSerializable(std::set<T> &data)
  973. {
  974. READ_CHECK_U32(length);
  975. T ins;
  976. for(ui32 i=0;i<length;i++)
  977. {
  978. *this >> ins;
  979. data.insert(ins);
  980. }
  981. }
  982. template <typename T, typename U>
  983. void loadSerializable(boost::unordered_set<T, U> &data)
  984. {
  985. READ_CHECK_U32(length);
  986. T ins;
  987. for(ui32 i=0;i<length;i++)
  988. {
  989. *this >> ins;
  990. data.insert(ins);
  991. }
  992. }
  993. template <typename T>
  994. void loadSerializable(std::list<T> &data)
  995. {
  996. READ_CHECK_U32(length);
  997. T ins;
  998. for(ui32 i=0;i<length;i++)
  999. {
  1000. *this >> ins;
  1001. data.push_back(ins);
  1002. }
  1003. }
  1004. template <typename T1, typename T2>
  1005. void loadSerializable(std::pair<T1,T2> &data)
  1006. {
  1007. *this >> data.first >> data.second;
  1008. }
  1009. template <typename T1, typename T2>
  1010. void loadSerializable(std::map<T1,T2> &data)
  1011. {
  1012. READ_CHECK_U32(length);
  1013. T1 t;
  1014. for(ui32 i=0;i<length;i++)
  1015. {
  1016. *this >> t;
  1017. *this >> data[t];
  1018. }
  1019. }
  1020. void loadSerializable(std::string &data)
  1021. {
  1022. READ_CHECK_U32(length);
  1023. data.resize(length);
  1024. this->This()->read((void*)data.c_str(),length);
  1025. }
  1026. template <BOOST_VARIANT_ENUM_PARAMS(typename T)>
  1027. void loadSerializable(boost::variant<BOOST_VARIANT_ENUM_PARAMS(T)> &data)
  1028. {
  1029. si32 which;
  1030. *this >> which;
  1031. if(which == 0)
  1032. {
  1033. T0 obj;
  1034. *this >> obj;
  1035. data = obj;
  1036. }
  1037. else if(which == 1)
  1038. {
  1039. T1 obj;
  1040. *this >> obj;
  1041. data = obj;
  1042. }
  1043. else
  1044. assert(0);
  1045. //TODO write more if needed, general solution would be much longer
  1046. }
  1047. template <typename T>
  1048. void loadSerializable(boost::optional<T> & data)
  1049. {
  1050. ui8 present;
  1051. *this >> present;
  1052. if(present)
  1053. {
  1054. T t;
  1055. *this >> t;
  1056. data = t;
  1057. }
  1058. else
  1059. {
  1060. data = boost::optional<T>();
  1061. }
  1062. }
  1063. void loadSerializable(CStackInstance *&s)
  1064. {
  1065. if(sendStackInstanceByIds)
  1066. {
  1067. CArmedInstance *armed;
  1068. SlotID slot;
  1069. *this >> armed >> slot;
  1070. assert(armed->hasStackAtSlot(slot));
  1071. s = armed->stacks[slot];
  1072. }
  1073. else
  1074. loadSerializableBySerializeCall(s);
  1075. }
  1076. template <typename E>
  1077. void loadEnum(E &data)
  1078. {
  1079. si32 read;
  1080. *this >> read;
  1081. data = static_cast<E>(read);
  1082. }
  1083. void loadBoolean(bool &data)
  1084. {
  1085. ui8 read;
  1086. *this >> read;
  1087. data = static_cast<bool>(read);
  1088. }
  1089. void loadBooleanVector(std::vector<bool> & data)
  1090. {
  1091. std::vector<ui8> convData;
  1092. loadSerializable(convData);
  1093. std::copy(convData.begin(), convData.end(), std::back_inserter(data));
  1094. }
  1095. };
  1096. class DLL_LINKAGE CSaveFile
  1097. : public COSer<CSaveFile>
  1098. {
  1099. void dummyMagicFunction()
  1100. {
  1101. *this << std::string("This function makes stuff working.");
  1102. }
  1103. public:
  1104. std::string fName;
  1105. unique_ptr<std::ofstream> sfile;
  1106. CSaveFile(const std::string &fname); //throws!
  1107. ~CSaveFile();
  1108. int write(const void * data, unsigned size);
  1109. void openNextFile(const std::string &fname); //throws!
  1110. void clear();
  1111. void reportState(CLogger &out);
  1112. };
  1113. class DLL_LINKAGE CLoadFile
  1114. : public CISer<CLoadFile>
  1115. {
  1116. void dummyMagicFunction()
  1117. {
  1118. std::string dummy = "This function makes stuff working.";
  1119. *this >> dummy;
  1120. }
  1121. public:
  1122. std::string fName;
  1123. unique_ptr<std::ifstream> sfile;
  1124. CLoadFile(const std::string &fname, int minimalVersion = version); //throws!
  1125. ~CLoadFile();
  1126. int read(const void * data, unsigned size); //throws!
  1127. void openNextFile(const std::string &fname, int minimalVersion); //throws!
  1128. void clear();
  1129. void reportState(CLogger &out);
  1130. };
  1131. typedef boost::asio::basic_stream_socket < boost::asio::ip::tcp , boost::asio::stream_socket_service<boost::asio::ip::tcp> > TSocket;
  1132. typedef boost::asio::basic_socket_acceptor<boost::asio::ip::tcp, boost::asio::socket_acceptor_service<boost::asio::ip::tcp> > TAcceptor;
  1133. class DLL_LINKAGE CConnection
  1134. :public CISer<CConnection>, public COSer<CConnection>
  1135. {
  1136. //CGameState *gs;
  1137. CConnection(void);
  1138. void init();
  1139. void reportState(CLogger &out);
  1140. public:
  1141. boost::mutex *rmx, *wmx; // read/write mutexes
  1142. TSocket * socket;
  1143. bool logging;
  1144. bool connected;
  1145. bool myEndianess, contactEndianess; //true if little endian, if endianess is different we'll have to revert received multi-byte vars
  1146. boost::asio::io_service *io_service;
  1147. std::string name; //who uses this connection
  1148. int connectionID;
  1149. boost::thread *handler;
  1150. bool receivedStop, sendStop;
  1151. CConnection(std::string host, std::string port, std::string Name);
  1152. CConnection(TAcceptor * acceptor, boost::asio::io_service *Io_service, std::string Name);
  1153. CConnection(TSocket * Socket, std::string Name); //use immediately after accepting connection into socket
  1154. int write(const void * data, unsigned size);
  1155. int read(void * data, unsigned size);
  1156. void close();
  1157. bool isOpen() const;
  1158. template<class T>
  1159. CConnection &operator&(const T&);
  1160. virtual ~CConnection(void);
  1161. CPack *retreivePack(); //gets from server next pack (allocates it with new)
  1162. void sendPackToServer(const CPack &pack, TPlayerColor player, ui32 requestID);
  1163. void disableStackSendingByID();
  1164. void enableStackSendingByID();
  1165. void disableSmartPointerSerialization();
  1166. void enableSmartPointerSerializatoin();
  1167. void prepareForSendingHeroes(); //disables sending vectorised, enables smart pointer serialization, clears saved/loaded ptr cache
  1168. void enterPregameConnectionMode();
  1169. };
  1170. DLL_LINKAGE std::ostream &operator<<(std::ostream &str, const CConnection &cpc);
  1171. template<typename T>
  1172. class CApplier
  1173. {
  1174. public:
  1175. std::map<ui16,T*> apps;
  1176. ~CApplier()
  1177. {
  1178. typename std::map<ui16, T*>::iterator iter;
  1179. for(iter = apps.begin(); iter != apps.end(); iter++)
  1180. delete iter->second;
  1181. }
  1182. template<typename U> void registerType(const U * t=NULL)
  1183. {
  1184. ui16 ID = typeList.registerType(t);
  1185. apps[ID] = T::getApplier(t);
  1186. }
  1187. };