Connection.h 29 KB

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