Client.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  1. #include "../CCallback.h"
  2. #include "../CConsoleHandler.h"
  3. #include "CGameInfo.h"
  4. #include "../lib/CGameState.h"
  5. #include "CPlayerInterface.h"
  6. #include "../StartInfo.h"
  7. #include "../hch/CArtHandler.h"
  8. #include "../hch/CDefObjInfoHandler.h"
  9. #include "../hch/CGeneralTextHandler.h"
  10. #include "../hch/CHeroHandler.h"
  11. #include "../hch/CTownHandler.h"
  12. #include "../hch/CObjectHandler.h"
  13. #include "../hch/CBuildingHandler.h"
  14. #include "../hch/CSpellHandler.h"
  15. #include "../lib/Connection.h"
  16. #include "../lib/Interprocess.h"
  17. #include "../lib/NetPacks.h"
  18. #include "../lib/VCMI_Lib.h"
  19. #include "../lib/map.h"
  20. #include "../mapHandler.h"
  21. #include "CConfigHandler.h"
  22. #include "Client.h"
  23. #include "GUIBase.h"
  24. #include <boost/bind.hpp>
  25. #include <boost/foreach.hpp>
  26. #include <boost/thread.hpp>
  27. #include <boost/thread/shared_mutex.hpp>
  28. #include <sstream>
  29. #undef DLL_EXPORT
  30. #define DLL_EXPORT
  31. #include "../lib/RegisterTypes.cpp"
  32. extern std::string NAME;
  33. namespace intpr = boost::interprocess;
  34. /*
  35. * Client.cpp, part of VCMI engine
  36. *
  37. * Authors: listed in file AUTHORS in main folder
  38. *
  39. * License: GNU General Public License v2.0 or later
  40. * Full text of license available in license.txt file, in main folder
  41. *
  42. */
  43. class CBaseForCLApply
  44. {
  45. public:
  46. virtual void applyOnClAfter(CClient *cl, void *pack) const =0;
  47. virtual void applyOnClBefore(CClient *cl, void *pack) const =0;
  48. };
  49. template <typename T> class CApplyOnCL : public CBaseForCLApply
  50. {
  51. public:
  52. void applyOnClAfter(CClient *cl, void *pack) const
  53. {
  54. T *ptr = static_cast<T*>(pack);
  55. ptr->applyCl(cl);
  56. }
  57. void applyOnClBefore(CClient *cl, void *pack) const
  58. {
  59. T *ptr = static_cast<T*>(pack);
  60. ptr->applyFirstCl(cl);
  61. }
  62. };
  63. class CCLApplier
  64. {
  65. public:
  66. std::map<ui16,CBaseForCLApply*> apps;
  67. CCLApplier()
  68. {
  69. registerTypes2(*this);
  70. }
  71. template<typename T> void registerType(const T * t=NULL)
  72. {
  73. ui16 ID = typeList.registerType(t);
  74. apps[ID] = new CApplyOnCL<T>;
  75. }
  76. } *applier = NULL;
  77. void CClient::init()
  78. {
  79. connectionHandler = NULL;
  80. pathInfo = NULL;
  81. applier = new CCLApplier;
  82. IObjectInterface::cb = this;
  83. serv = NULL;
  84. gs = NULL;
  85. cb = NULL;
  86. terminate = false;
  87. boost::interprocess::shared_memory_object::remove("vcmi_memory"); //if the application has previously crashed, the memory may not have been removed. to avoid problems - try to destroy it
  88. try
  89. {
  90. shared = new SharedMem();
  91. } HANDLE_EXCEPTIONC(tlog1 << "Cannot open interprocess memory: ";)
  92. }
  93. CClient::CClient(void)
  94. :waitingRequest(false)
  95. {
  96. init();
  97. }
  98. CClient::CClient(CConnection *con, StartInfo *si)
  99. :waitingRequest(false)
  100. {
  101. init();
  102. newGame(con,si);
  103. }
  104. CClient::~CClient(void)
  105. {
  106. delete pathInfo;
  107. delete applier;
  108. delete shared;
  109. }
  110. void CClient::waitForMoveAndSend(int color)
  111. {
  112. try
  113. {
  114. BattleAction ba = playerint[color]->activeStack(gs->curB->activeStack);
  115. *serv << &MakeAction(ba);
  116. return;
  117. }HANDLE_EXCEPTION
  118. tlog1 << "We should not be here!" << std::endl;
  119. }
  120. void CClient::run()
  121. {
  122. try
  123. {
  124. CPack *pack;
  125. while(!terminate)
  126. {
  127. //get the package from the server
  128. {
  129. boost::unique_lock<boost::mutex> lock(*serv->rmx);
  130. tlog5 << "Listening... ";
  131. *serv >> pack;
  132. tlog5 << "\treceived server message of type " << typeid(*pack).name() << std::endl;
  133. }
  134. if (terminate)
  135. {
  136. delete pack;
  137. break;
  138. }
  139. CBaseForCLApply *apply = applier->apps[typeList.getTypeID(pack)]; //find the applier
  140. if(apply)
  141. {
  142. apply->applyOnClBefore(this,pack);
  143. tlog5 << "\tMade first apply on cl\n";
  144. gs->apply(pack);
  145. tlog5 << "\tApplied on gs\n";
  146. apply->applyOnClAfter(this,pack);
  147. tlog5 << "\tMade second apply on cl\n";
  148. }
  149. else
  150. {
  151. tlog1 << "Message cannot be applied, cannot find applier!\n";
  152. }
  153. delete pack;
  154. pack = NULL;
  155. }
  156. } HANDLE_EXCEPTION(tlog1 << "Lost connection to server, ending listening thread!\n");
  157. }
  158. void CClient::stop()
  159. {
  160. // Game is ending
  161. // Tell the network thread and interface thread to reach a stable state
  162. terminate = true;
  163. LOCPLINT->terminate = true;
  164. endGame();
  165. }
  166. void CClient::save(const std::string & fname)
  167. {
  168. if(gs->curB)
  169. {
  170. tlog1 << "Game cannot be saved during battle!\n";
  171. return;
  172. }
  173. *serv << &SaveGame(fname);
  174. }
  175. void CClient::endGame()
  176. {
  177. tlog0 << "\n\nEnding current game!" << std::endl;
  178. GH.curInt = NULL;
  179. GH.topInt()->deactivate();
  180. GH.listInt.clear();
  181. GH.objsToBlit.clear();
  182. delete CGI->mh;
  183. CGI->mh = NULL;
  184. delete CGI->state;
  185. CGI->state = NULL;
  186. LOCPLINT = NULL;
  187. while (!playerint.empty())
  188. {
  189. delete playerint.begin()->second;
  190. playerint.erase(playerint.begin());
  191. }
  192. BOOST_FOREACH(CCallback *cb, callbacks)
  193. {
  194. delete cb;
  195. }
  196. if (serv)
  197. {
  198. tlog3 << "Connection has been requested to be closed.\n";
  199. boost::unique_lock<boost::mutex>(*serv->wmx);
  200. *serv << &CloseServer();
  201. tlog3 << "Sent closing signal to the server\n";
  202. serv->close();
  203. delete serv;
  204. serv = NULL;
  205. tlog3 << "Our socket has been closed." << std::endl;
  206. }
  207. connectionHandler->join();
  208. delete connectionHandler;
  209. connectionHandler = NULL;
  210. }
  211. void CClient::loadGame( const std::string & fname )
  212. {
  213. tlog0 <<"\n\nLoading procedure started!\n\n";
  214. timeHandler tmh;
  215. char portc[10];
  216. SDL_itoa(conf.cc.port,portc,10);
  217. runServer(portc); //create new server
  218. tlog0 <<"Restarting server: "<<tmh.getDif()<<std::endl;
  219. {
  220. ui32 ver;
  221. char sig[8];
  222. CMapHeader dum;
  223. CGI->mh = new CMapHandler();
  224. CLoadFile lf(fname + ".vlgm1");
  225. lf >> sig >> dum >> *sig;
  226. tlog0 <<"Reading save signature: "<<tmh.getDif()<<std::endl;
  227. lf >> *VLC;
  228. CGI->setFromLib();
  229. tlog0 <<"Reading handlers: "<<tmh.getDif()<<std::endl;
  230. lf >> gs;
  231. tlog0 <<"Reading gamestate: "<<tmh.getDif()<<std::endl;
  232. CGI->state = gs;
  233. CGI->mh->map = gs->map;
  234. pathInfo = new CPathsInfo(int3(gs->map->width, gs->map->height, gs->map->twoLevel+1));
  235. CGI->mh->init();
  236. tlog0 <<"Initing maphandler: "<<tmh.getDif()<<std::endl;
  237. }
  238. waitForServer();
  239. tlog0 <<"Waiting for server: "<<tmh.getDif()<<std::endl;
  240. serv = new CConnection(conf.cc.server,portc,NAME);
  241. serv->setGS(gs);
  242. tlog0 <<"Setting up connection: "<<tmh.getDif()<<std::endl;
  243. ui8 pom8;
  244. *serv << ui8(3) << ui8(1); //load game; one client
  245. *serv << fname;
  246. *serv >> pom8;
  247. if(pom8)
  248. throw "Server cannot open the savegame!";
  249. else
  250. tlog0 << "Server opened savegame properly.\n";
  251. *serv << ui8(gs->scenarioOps->playerInfos.size()+1); //number of players + neutral
  252. for(size_t i=0;i<gs->scenarioOps->playerInfos.size();i++)
  253. {
  254. *serv << ui8(gs->scenarioOps->playerInfos[i].color); //players
  255. }
  256. *serv << ui8(255); // neutrals
  257. tlog0 <<"Sent info to server: "<<tmh.getDif()<<std::endl;
  258. {
  259. CLoadFile lf(fname + ".vcgm1");
  260. lf >> *this;
  261. }
  262. //for (size_t i=0; i<gs->scenarioOps->playerInfos.size();++i) //initializing interfaces for players
  263. //{
  264. // ui8 color = gs->scenarioOps->playerInfos[i].color;
  265. // CCallback *cb = new CCallback(gs,color,this);
  266. // if(!gs->scenarioOps->playerInfos[i].human) {
  267. // playerint[color] = static_cast<CGameInterface*>(CAIHandler::getNewAI(cb,conf.cc.defaultAI));
  268. // }
  269. // else {
  270. // playerint[color] = new CPlayerInterface(color,i);
  271. // }
  272. // gs->currentPlayer = color;
  273. // playerint[color]->init(cb);
  274. // tlog0 <<"Setting up interface for player "<< (int)color <<": "<<tmh.getDif()<<std::endl;
  275. //}
  276. //playerint[255] = CAIHandler::getNewAI(cb,conf.cc.defaultAI);
  277. //playerint[255]->init(new CCallback(gs,255,this));
  278. //tlog0 <<"Setting up interface for neutral \"player\"" << tmh.getDif() << std::endl;
  279. }
  280. int CClient::getCurrentPlayer()
  281. {
  282. return gs->currentPlayer;
  283. }
  284. int CClient::getSelectedHero()
  285. {
  286. return IGameCallback::getSelectedHero(getCurrentPlayer())->id;
  287. }
  288. void CClient::newGame( CConnection *con, StartInfo *si )
  289. {
  290. if (con == NULL)
  291. {
  292. timeHandler pomtime;
  293. char portc[10];
  294. SDL_itoa(conf.cc.port,portc,10);
  295. CClient::runServer(portc);
  296. tlog0<<"Preparing shared memory and starting server: "<<pomtime.getDif()<<std::endl;
  297. pomtime.getDif();//reset timers
  298. //wait until server is ready
  299. tlog0<<"Waiting for server... ";
  300. waitForServer();
  301. tlog0 << pomtime.getDif()<<std::endl;
  302. while(!con)
  303. {
  304. try
  305. {
  306. tlog0 << "Establishing connection...\n";
  307. con = new CConnection(conf.cc.server,portc,NAME);
  308. }
  309. catch(...)
  310. {
  311. tlog1 << "\nCannot establish connection! Retrying within 2 seconds" <<std::endl;
  312. SDL_Delay(2000);
  313. }
  314. }
  315. THC tlog0<<"\tConnecting to the server: "<<pomtime.getDif()<<std::endl;
  316. }
  317. timeHandler tmh;
  318. CGI->state = new CGameState();
  319. tlog0 <<"\tGamestate: "<<tmh.getDif()<<std::endl;
  320. serv = con;
  321. serv->setGS(CGI->state);
  322. CConnection &c(*con);
  323. ////////////////////////////////////////////////////
  324. ui8 pom8;
  325. c << ui8(2) << ui8(1); //new game; one client
  326. c << *si;
  327. c >> pom8;
  328. if(pom8)
  329. throw "Server cannot open the map!";
  330. else
  331. tlog0 << "Server opened map properly.\n";
  332. c << ui8(si->playerInfos.size()+1); //number of players + neutral
  333. for(size_t i=0;i<si->playerInfos.size();i++)
  334. {
  335. c << ui8(si->playerInfos[i].color); //players
  336. }
  337. c << ui8(255); // neutrals
  338. ui32 seed, sum;
  339. std::string mapname;
  340. c >> mapname >> sum >> seed;
  341. tlog0 <<"\tSending/Getting info to/from the server: "<<tmh.getDif()<<std::endl;
  342. Mapa * mapa = new Mapa(mapname);
  343. tlog0 <<"Reading and detecting map file (together): "<<tmh.getDif()<<std::endl;
  344. tlog0 << "\tServer checksum for "<<mapname <<": "<<sum << std::endl;
  345. tlog0 << "\tOur checksum for the map: "<< mapa->checksum << std::endl;
  346. if(mapa->checksum != sum)
  347. {
  348. tlog1 << "Wrong map checksum!!!" << std::endl;
  349. throw std::string("Wrong checksum");
  350. }
  351. tlog0 << "\tUsing random seed: "<<seed << std::endl;
  352. gs = CGI->state;
  353. gs->scenarioOps = si;
  354. gs->init(si,mapa,seed);
  355. CGI->mh = new CMapHandler();
  356. tlog0 <<"Initializing GameState (together): "<<tmh.getDif()<<std::endl;
  357. CGI->mh->map = mapa;
  358. tlog0 <<"Creating mapHandler: "<<tmh.getDif()<<std::endl;
  359. CGI->mh->init();
  360. pathInfo = new CPathsInfo(int3(mapa->width, mapa->height, mapa->twoLevel+1));
  361. tlog0 <<"Initializing mapHandler (together): "<<tmh.getDif()<<std::endl;
  362. for (size_t i=0; i<gs->scenarioOps->playerInfos.size();++i) //initializing interfaces for players
  363. {
  364. ui8 color = gs->scenarioOps->playerInfos[i].color;
  365. CCallback *cb = new CCallback(gs,color,this);
  366. if(!gs->scenarioOps->playerInfos[i].human) {
  367. playerint[color] = static_cast<CGameInterface*>(CAIHandler::getNewAI(cb,conf.cc.defaultAI));
  368. }
  369. else {
  370. playerint[color] = new CPlayerInterface(color,i);
  371. }
  372. gs->currentPlayer = color;
  373. playerint[color]->init(cb);
  374. }
  375. playerint[255] = CAIHandler::getNewAI(cb,conf.cc.defaultAI);
  376. playerint[255]->init(new CCallback(gs,255,this));
  377. }
  378. void CClient::runServer(const char * portc)
  379. {
  380. static std::string comm = std::string(BIN_DIR PATH_SEPARATOR SERVER_NAME " ") + portc + " > server_log.txt"; //needs to be static, if not - will be probably destroyed before new thread reads it
  381. boost::thread servthr(boost::bind(system,comm.c_str())); //runs server executable; //TODO: will it work on non-windows platforms?
  382. }
  383. void CClient::waitForServer()
  384. {
  385. intpr::scoped_lock<intpr::interprocess_mutex> slock(shared->sr->mutex);
  386. while(!shared->sr->ready)
  387. {
  388. shared->sr->cond.wait(slock);
  389. }
  390. }
  391. template <typename Handler>
  392. void CClient::serialize( Handler &h, const int version )
  393. {
  394. if(h.saving)
  395. {
  396. ui8 players = playerint.size();
  397. h & players;
  398. for(std::map<ui8,CGameInterface *>::iterator i = playerint.begin(); i != playerint.end(); i++)
  399. {
  400. h & i->first & i->second->dllName;
  401. i->second->serialize(h,version);
  402. }
  403. }
  404. else
  405. {
  406. ui8 players;
  407. h & players;
  408. for(int i=0; i < players; i++)
  409. {
  410. std::string dllname;
  411. ui8 pid;
  412. h & pid & dllname;
  413. CCallback *callback = new CCallback(gs,pid,this);
  414. callbacks.insert(callback);
  415. CGameInterface *nInt = NULL;
  416. if(dllname.length())
  417. nInt = CAIHandler::getNewAI(callback,dllname);
  418. else
  419. nInt = new CPlayerInterface(pid,i);
  420. playerint[pid] = nInt;
  421. nInt->init(callback);
  422. nInt->serialize(h, version);
  423. }
  424. }
  425. }
  426. //void CClient::sendRequest( const CPackForServer *request, bool waitForRealization )
  427. //{
  428. // if(waitForRealization)
  429. // waitingRequest.set(true);
  430. //
  431. // *serv << request;
  432. //
  433. // if(waitForRealization)
  434. // waitingRequest.waitWhileTrue();
  435. //}
  436. template void CClient::serialize( CISer<CLoadFile> &h, const int version );
  437. template void CClient::serialize( COSer<CSaveFile> &h, const int version );