Client.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650
  1. #include "CMusicHandler.h"
  2. #include "../lib/CCampaignHandler.h"
  3. #include "../CCallback.h"
  4. #include "../CConsoleHandler.h"
  5. #include "CGameInfo.h"
  6. #include "../lib/CGameState.h"
  7. #include "CPlayerInterface.h"
  8. #include "../StartInfo.h"
  9. #include "../lib/CArtHandler.h"
  10. #include "../lib/CDefObjInfoHandler.h"
  11. #include "../lib/CGeneralTextHandler.h"
  12. #include "../lib/CHeroHandler.h"
  13. #include "../lib/CTownHandler.h"
  14. #include "../lib/CObjectHandler.h"
  15. #include "../lib/CBuildingHandler.h"
  16. #include "../lib/CSpellHandler.h"
  17. #include "../lib/Connection.h"
  18. #include "../lib/Interprocess.h"
  19. #include "../lib/NetPacks.h"
  20. #include "../lib/VCMI_Lib.h"
  21. #include "../lib/map.h"
  22. #include "mapHandler.h"
  23. #include "CConfigHandler.h"
  24. #include "Client.h"
  25. #include "GUIBase.h"
  26. #include <boost/bind.hpp>
  27. #include <boost/foreach.hpp>
  28. #include <boost/thread.hpp>
  29. #include <boost/thread/shared_mutex.hpp>
  30. #include <boost/lexical_cast.hpp>
  31. #include <sstream>
  32. #include "CPreGame.h"
  33. #define NOT_LIB
  34. #include "../lib/RegisterTypes.cpp"
  35. #include "CBattleInterface.h"
  36. extern std::string NAME;
  37. namespace intpr = boost::interprocess;
  38. /*
  39. * Client.cpp, part of VCMI engine
  40. *
  41. * Authors: listed in file AUTHORS in main folder
  42. *
  43. * License: GNU General Public License v2.0 or later
  44. * Full text of license available in license.txt file, in main folder
  45. *
  46. */
  47. template <typename T> class CApplyOnCL;
  48. class CBaseForCLApply
  49. {
  50. public:
  51. virtual void applyOnClAfter(CClient *cl, void *pack) const =0;
  52. virtual void applyOnClBefore(CClient *cl, void *pack) const =0;
  53. virtual ~CBaseForCLApply(){}
  54. template<typename U> static CBaseForCLApply *getApplier(const U * t=NULL)
  55. {
  56. return new CApplyOnCL<U>;
  57. }
  58. };
  59. template <typename T> class CApplyOnCL : public CBaseForCLApply
  60. {
  61. public:
  62. void applyOnClAfter(CClient *cl, void *pack) const
  63. {
  64. T *ptr = static_cast<T*>(pack);
  65. ptr->applyCl(cl);
  66. }
  67. void applyOnClBefore(CClient *cl, void *pack) const
  68. {
  69. T *ptr = static_cast<T*>(pack);
  70. ptr->applyFirstCl(cl);
  71. }
  72. };
  73. static CApplier<CBaseForCLApply> *applier = NULL;
  74. void CClient::init()
  75. {
  76. hotSeat = false;
  77. connectionHandler = NULL;
  78. pathInfo = NULL;
  79. applier = new CApplier<CBaseForCLApply>;
  80. registerTypes2(*applier);
  81. IObjectInterface::cb = this;
  82. serv = NULL;
  83. gs = NULL;
  84. cb = NULL;
  85. terminate = false;
  86. }
  87. CClient::CClient(void)
  88. :waitingRequest(false)
  89. {
  90. init();
  91. }
  92. CClient::CClient(CConnection *con, StartInfo *si)
  93. :waitingRequest(false)
  94. {
  95. init();
  96. newGame(con,si);
  97. }
  98. CClient::~CClient(void)
  99. {
  100. delete pathInfo;
  101. delete applier;
  102. }
  103. void CClient::waitForMoveAndSend(int color)
  104. {
  105. try
  106. {
  107. BattleAction ba = playerint[color]->activeStack(gs->curB->activeStack);
  108. *serv << &MakeAction(ba);
  109. return;
  110. }HANDLE_EXCEPTION
  111. tlog1 << "We should not be here!" << std::endl;
  112. }
  113. void CClient::run()
  114. {
  115. try
  116. {
  117. CPack *pack = NULL;
  118. while(!terminate)
  119. {
  120. pack = serv->retreivePack(); //get the package from the server
  121. if (terminate)
  122. {
  123. delete pack;
  124. pack = NULL;
  125. break;
  126. }
  127. handlePack(pack);
  128. pack = NULL;
  129. }
  130. }
  131. catch (const std::exception& e)
  132. {
  133. tlog3 << "Lost connection to server, ending listening thread!\n";
  134. tlog1 << e.what() << std::endl;
  135. if(!terminate) //rethrow (-> boom!) only if closing connection was unexpected
  136. {
  137. tlog1 << "Something wrong, lost connection while game is still ongoing...\n";
  138. throw;
  139. }
  140. }
  141. }
  142. void CClient::save(const std::string & fname)
  143. {
  144. if(gs->curB)
  145. {
  146. tlog1 << "Game cannot be saved during battle!\n";
  147. return;
  148. }
  149. *serv << &SaveGame(fname);
  150. }
  151. #include <fstream>
  152. void initVillagesCapitols(Mapa * map)
  153. {
  154. std::ifstream ifs(DATA_DIR "/config/townsDefs.txt");
  155. int ccc;
  156. ifs>>ccc;
  157. for(int i=0;i<ccc*2;i++)
  158. {
  159. const CGDefInfo *n;
  160. if(i<ccc)
  161. {
  162. n = CGI->state->villages[i];
  163. map->defy.push_back(CGI->state->forts[i]);
  164. }
  165. else
  166. n = CGI->state->capitols[i%ccc];
  167. ifs >> const_cast<CGDefInfo*>(n)->name;
  168. if(!n)
  169. tlog1 << "*HUGE* Warning - missing town def for " << i << std::endl;
  170. else
  171. map->defy.push_back(const_cast<CGDefInfo*>(n));
  172. }
  173. }
  174. void CClient::endGame( bool closeConnection /*= true*/ )
  175. {
  176. // Game is ending
  177. // Tell the network thread to reach a stable state
  178. GH.curInt = NULL;
  179. LOCPLINT->terminate_cond.setn(true);
  180. LOCPLINT->pim->lock();
  181. tlog0 << "\n\nEnding current game!" << std::endl;
  182. if(GH.topInt())
  183. GH.topInt()->deactivate();
  184. GH.listInt.clear();
  185. GH.objsToBlit.clear();
  186. GH.statusbar = NULL;
  187. tlog0 << "Removed GUI." << std::endl;
  188. delete CGI->mh;
  189. const_cast<CGameInfo*>(CGI)->mh = NULL;
  190. delete CGI->state;
  191. const_cast<CGameInfo*>(CGI)->state = NULL;
  192. tlog0 << "Deleted mapHandler and gameState." << std::endl;
  193. LOCPLINT = NULL;
  194. while (!playerint.empty())
  195. {
  196. CGameInterface *pint = playerint.begin()->second;
  197. playerint.erase(playerint.begin());
  198. delete pint;
  199. }
  200. BOOST_FOREACH(CCallback *cb, callbacks)
  201. {
  202. delete cb;
  203. }
  204. tlog0 << "Deleted playerInts." << std::endl;
  205. if(closeConnection)
  206. stopConnection();
  207. tlog0 << "Client stopped." << std::endl;
  208. }
  209. void CClient::loadGame( const std::string & fname )
  210. {
  211. tlog0 <<"\n\nLoading procedure started!\n\n";
  212. CServerHandler sh;
  213. sh.startServer();
  214. timeHandler tmh;
  215. {
  216. char sig[8];
  217. CMapHeader dum;
  218. const_cast<CGameInfo*>(CGI)->mh = new CMapHandler();
  219. StartInfo *si;
  220. CLoadFile lf(fname + ".vlgm1");
  221. lf >> sig >> dum >> si;
  222. tlog0 <<"Reading save signature: "<<tmh.getDif()<<std::endl;
  223. lf >> *VLC;
  224. const_cast<CGameInfo*>(CGI)->setFromLib();
  225. tlog0 <<"Reading handlers: "<<tmh.getDif()<<std::endl;
  226. lf >> gs;
  227. tlog0 <<"Reading gamestate: "<<tmh.getDif()<<std::endl;
  228. const_cast<CGameInfo*>(CGI)->state = gs;
  229. const_cast<CGameInfo*>(CGI)->mh->map = gs->map;
  230. pathInfo = new CPathsInfo(int3(gs->map->width, gs->map->height, gs->map->twoLevel+1));
  231. CGI->mh->init();
  232. initVillagesCapitols(gs->map);
  233. tlog0 <<"Initing maphandler: "<<tmh.getDif()<<std::endl;
  234. }
  235. serv = sh.connectToServer();
  236. serv->addStdVecItems(gs);
  237. tmh.update();
  238. ui8 pom8;
  239. *serv << ui8(3) << ui8(1); //load game; one client
  240. *serv << fname;
  241. *serv >> pom8;
  242. if(pom8)
  243. throw "Server cannot open the savegame!";
  244. else
  245. tlog0 << "Server opened savegame properly.\n";
  246. *serv << ui32(gs->scenarioOps->playerInfos.size()+1); //number of players + neutral
  247. for(std::map<int, PlayerSettings>::iterator it = gs->scenarioOps->playerInfos.begin();
  248. it != gs->scenarioOps->playerInfos.end(); ++it)
  249. {
  250. *serv << ui8(it->first); //players
  251. }
  252. *serv << ui8(255); // neutrals
  253. tlog0 <<"Sent info to server: "<<tmh.getDif()<<std::endl;
  254. {
  255. CLoadFile lf(fname + ".vcgm1");
  256. lf >> *this;
  257. }
  258. }
  259. int CClient::getCurrentPlayer()
  260. {
  261. return gs->currentPlayer;
  262. }
  263. int CClient::getSelectedHero()
  264. {
  265. if(const CGHeroInstance *selHero = IGameCallback::getSelectedHero(getCurrentPlayer()))
  266. return selHero->id;
  267. else
  268. return -1;
  269. }
  270. void CClient::newGame( CConnection *con, StartInfo *si )
  271. {
  272. enum {SINGLE, HOST, GUEST} networkMode = SINGLE;
  273. std::set<ui8> myPlayers;
  274. if (con == NULL)
  275. {
  276. CServerHandler sh;
  277. serv = sh.connectToServer();
  278. }
  279. else
  280. {
  281. serv = con;
  282. networkMode = (con->connectionID == 1) ? HOST : GUEST;
  283. }
  284. for(std::map<int, PlayerSettings>::iterator it =si->playerInfos.begin();
  285. it != si->playerInfos.end(); ++it)
  286. {
  287. if(networkMode == SINGLE //single - one client has all player
  288. || networkMode != SINGLE && serv->connectionID == it->second.human //multi - client has only "its players"
  289. || networkMode == HOST && it->second.human == false) //multi - host has all AI players
  290. {
  291. myPlayers.insert(ui8(it->first)); //add player
  292. }
  293. }
  294. if(networkMode != GUEST)
  295. myPlayers.insert(255); //neutral
  296. timeHandler tmh;
  297. const_cast<CGameInfo*>(CGI)->state = new CGameState();
  298. tlog0 <<"\tGamestate: "<<tmh.getDif()<<std::endl;
  299. CConnection &c(*serv);
  300. ////////////////////////////////////////////////////
  301. if(networkMode == SINGLE)
  302. {
  303. ui8 pom8;
  304. c << ui8(2) << ui8(1); //new game; one client
  305. c << *si;
  306. c >> pom8;
  307. if(pom8)
  308. throw "Server cannot open the map!";
  309. else
  310. tlog0 << "Server opened map properly.\n";
  311. }
  312. c << myPlayers;
  313. ui32 seed, sum;
  314. c >> si >> sum >> seed;
  315. tlog0 <<"\tSending/Getting info to/from the server: "<<tmh.getDif()<<std::endl;
  316. tlog0 << "\tUsing random seed: "<<seed << std::endl;
  317. gs = const_cast<CGameInfo*>(CGI)->state;
  318. gs->scenarioOps = si;
  319. gs->init(si, sum, seed);
  320. tlog0 <<"Initializing GameState (together): "<<tmh.getDif()<<std::endl;
  321. if(gs->map)
  322. {
  323. const_cast<CGameInfo*>(CGI)->mh = new CMapHandler();
  324. CGI->mh->map = gs->map;
  325. tlog0 <<"Creating mapHandler: "<<tmh.getDif()<<std::endl;
  326. CGI->mh->init();
  327. initVillagesCapitols(gs->map);
  328. pathInfo = new CPathsInfo(int3(gs->map->width, gs->map->height, gs->map->twoLevel+1));
  329. tlog0 <<"Initializing mapHandler (together): "<<tmh.getDif()<<std::endl;
  330. }
  331. int humanPlayers = 0;
  332. for(std::map<int, PlayerSettings>::iterator it = gs->scenarioOps->playerInfos.begin();
  333. it != gs->scenarioOps->playerInfos.end(); ++it)//initializing interfaces for players
  334. {
  335. ui8 color = it->first;
  336. gs->currentPlayer = color;
  337. if(!vstd::contains(myPlayers, color))
  338. continue;
  339. if(si->mode != StartInfo::DUEL)
  340. {
  341. CCallback *cb = new CCallback(gs,color,this);
  342. if(!it->second.human)
  343. {
  344. playerint[color] = static_cast<CGameInterface*>(CAIHandler::getNewAI(cb,conf.cc.defaultAI));
  345. }
  346. else
  347. {
  348. playerint[color] = new CPlayerInterface(color);
  349. humanPlayers++;
  350. }
  351. playerint[color]->init(cb);
  352. }
  353. else
  354. {
  355. CBattleCallback * cbc = new CBattleCallback(gs, color, this);
  356. battleints[color] = CAIHandler::getNewBattleAI(cb,conf.cc.defaultAI);
  357. battleints[color]->init(cbc);
  358. }
  359. }
  360. if(si->mode == StartInfo::DUEL)
  361. {
  362. CPlayerInterface *p = new CPlayerInterface(-1);
  363. p->observerInDuelMode = true;
  364. playerint[254] = p;
  365. p->init(new CCallback(gs, -1, this));
  366. battleStarted(gs->curB);
  367. }
  368. serv->addStdVecItems(const_cast<CGameInfo*>(CGI)->state);
  369. hotSeat = (humanPlayers > 1);
  370. playerint[255] = CAIHandler::getNewAI(cb,conf.cc.defaultAI);
  371. playerint[255]->init(new CCallback(gs,255,this));
  372. }
  373. template <typename Handler>
  374. void CClient::serialize( Handler &h, const int version )
  375. {
  376. h & hotSeat;
  377. if(h.saving)
  378. {
  379. ui8 players = playerint.size();
  380. h & players;
  381. for(std::map<ui8,CGameInterface *>::iterator i = playerint.begin(); i != playerint.end(); i++)
  382. {
  383. h & i->first & i->second->dllName;
  384. i->second->serialize(h,version);
  385. }
  386. }
  387. else
  388. {
  389. ui8 players;
  390. h & players;
  391. for(int i=0; i < players; i++)
  392. {
  393. std::string dllname;
  394. ui8 pid;
  395. h & pid & dllname;
  396. CCallback *callback = new CCallback(gs,pid,this);
  397. callbacks.insert(callback);
  398. CGameInterface *nInt = NULL;
  399. if(dllname.length())
  400. nInt = CAIHandler::getNewAI(callback,dllname);
  401. else
  402. nInt = new CPlayerInterface(pid);
  403. playerint[pid] = nInt;
  404. nInt->init(callback);
  405. nInt->serialize(h, version);
  406. }
  407. }
  408. }
  409. void CClient::handlePack( CPack * pack )
  410. {
  411. CBaseForCLApply *apply = applier->apps[typeList.getTypeID(pack)]; //find the applier
  412. if(apply)
  413. {
  414. apply->applyOnClBefore(this,pack);
  415. tlog5 << "\tMade first apply on cl\n";
  416. gs->apply(pack);
  417. tlog5 << "\tApplied on gs\n";
  418. apply->applyOnClAfter(this,pack);
  419. tlog5 << "\tMade second apply on cl\n";
  420. }
  421. else
  422. {
  423. tlog1 << "Message cannot be applied, cannot find applier!\n";
  424. }
  425. delete pack;
  426. }
  427. void CClient::updatePaths()
  428. {
  429. const CGHeroInstance *h = getHero(getSelectedHero());
  430. if (h)//if we have selected hero...
  431. gs->calculatePaths(h, *pathInfo);
  432. }
  433. void CClient::finishCampaign( CCampaignState * camp )
  434. {
  435. }
  436. void CClient::proposeNextMission( CCampaignState * camp )
  437. {
  438. GH.pushInt(new CBonusSelection(camp));
  439. GH.curInt = CGP;
  440. }
  441. void CClient::stopConnection()
  442. {
  443. terminate = true;
  444. if (serv)
  445. {
  446. tlog0 << "Connection has been requested to be closed.\n";
  447. boost::unique_lock<boost::mutex>(*serv->wmx);
  448. *serv << &CloseServer();
  449. tlog0 << "Sent closing signal to the server\n";
  450. serv->close();
  451. delete serv;
  452. serv = NULL;
  453. tlog3 << "Our socket has been closed." << std::endl;
  454. }
  455. if(connectionHandler)
  456. {
  457. if(connectionHandler->get_id() != boost::this_thread::get_id())
  458. connectionHandler->join();
  459. tlog0 << "Connection handler thread joined" << std::endl;
  460. delete connectionHandler;
  461. connectionHandler = NULL;
  462. }
  463. }
  464. void CClient::battleStarted(const BattleInfo * info)
  465. {
  466. CPlayerInterface * att, * def;
  467. if(vstd::contains(playerint, info->side1) && playerint[info->side1]->human)
  468. att = static_cast<CPlayerInterface*>( playerint[info->side1] );
  469. else
  470. att = NULL;
  471. if(vstd::contains(playerint, info->side2) && playerint[info->side2]->human)
  472. def = static_cast<CPlayerInterface*>( playerint[info->side2] );
  473. else
  474. def = NULL;
  475. new CBattleInterface(info->belligerents[0], info->belligerents[1], info->heroes[0], info->heroes[1], Rect((conf.cc.resx - 800)/2, (conf.cc.resy - 600)/2, 800, 600), att, def);
  476. if(vstd::contains(playerint,info->side1))
  477. playerint[info->side1]->battleStart(info->belligerents[0], info->belligerents[1], info->tile, info->heroes[0], info->heroes[1], 0);
  478. if(vstd::contains(playerint,info->side2))
  479. playerint[info->side2]->battleStart(info->belligerents[0], info->belligerents[1], info->tile, info->heroes[0], info->heroes[1], 1);
  480. if(vstd::contains(playerint,254))
  481. playerint[254]->battleStart(info->belligerents[0], info->belligerents[1], info->tile, info->heroes[0], info->heroes[1], 1);
  482. }
  483. template void CClient::serialize( CISer<CLoadFile> &h, const int version );
  484. template void CClient::serialize( COSer<CSaveFile> &h, const int version );
  485. void CServerHandler::startServer()
  486. {
  487. th.update();
  488. serverThread = new boost::thread(&CServerHandler::callServer, this); //runs server executable; //TODO: will it work on non-windows platforms?
  489. if(verbose)
  490. tlog0 << "Setting up thread calling server: " << th.getDif() << std::endl;
  491. }
  492. void CServerHandler::waitForServer()
  493. {
  494. if(!serverThread)
  495. startServer();
  496. th.update();
  497. intpr::scoped_lock<intpr::interprocess_mutex> slock(shared->sr->mutex);
  498. while(!shared->sr->ready)
  499. {
  500. shared->sr->cond.wait(slock);
  501. }
  502. if(verbose)
  503. tlog0 << "Waiting for server: " << th.getDif() << std::endl;
  504. }
  505. CConnection * CServerHandler::connectToServer()
  506. {
  507. if(!shared->sr->ready)
  508. waitForServer();
  509. th.update();
  510. CConnection *ret = justConnectToServer(conf.cc.server, port);
  511. if(verbose)
  512. tlog0<<"\tConnecting to the server: "<<th.getDif()<<std::endl;
  513. return ret;
  514. }
  515. CServerHandler::CServerHandler(bool runServer /*= false*/)
  516. {
  517. serverThread = NULL;
  518. shared = NULL;
  519. port = boost::lexical_cast<std::string>(conf.cc.port);
  520. 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
  521. try
  522. {
  523. shared = new SharedMem();
  524. } HANDLE_EXCEPTIONC(tlog1 << "Cannot open interprocess memory: ";)
  525. }
  526. CServerHandler::~CServerHandler()
  527. {
  528. delete shared;
  529. delete serverThread; //detaches, not kills thread
  530. }
  531. void CServerHandler::callServer()
  532. {
  533. std::string comm = std::string(BIN_DIR PATH_SEPARATOR SERVER_NAME " ") + port + " > server_log.txt";
  534. std::system(comm.c_str());
  535. tlog0 << "Server finished\n";
  536. }
  537. CConnection * CServerHandler::justConnectToServer(const std::string &host, const std::string &port)
  538. {
  539. CConnection *ret = NULL;
  540. while(!ret)
  541. {
  542. try
  543. {
  544. tlog0 << "Establishing connection...\n";
  545. ret = new CConnection( host.size() ? host : conf.cc.server,
  546. port.size() ? port : boost::lexical_cast<std::string>(conf.cc.port),
  547. NAME);
  548. }
  549. catch(...)
  550. {
  551. tlog1 << "\nCannot establish connection! Retrying within 2 seconds" << std::endl;
  552. SDL_Delay(2000);
  553. }
  554. }
  555. return ret;
  556. }