Client.cpp 13 KB

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