Connection.h 26 KB

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