Client.cpp 12 KB

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