Client.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844
  1. #include "CMusicHandler.h"
  2. #include "../lib/CCampaignHandler.h"
  3. #include "../CCallback.h"
  4. #include "../lib/CConsoleHandler.h"
  5. #include "CGameInfo.h"
  6. #include "../lib/CGameState.h"
  7. #include "CPlayerInterface.h"
  8. #include "../StartInfo.h"
  9. #include "../lib/BattleState.h"
  10. #include "../lib/CArtHandler.h"
  11. #include "../lib/CDefObjInfoHandler.h"
  12. #include "../lib/CGeneralTextHandler.h"
  13. #include "../lib/CHeroHandler.h"
  14. #include "../lib/CTownHandler.h"
  15. #include "../lib/CObjectHandler.h"
  16. #include "../lib/CBuildingHandler.h"
  17. #include "../lib/CSpellHandler.h"
  18. #include "../lib/Connection.h"
  19. #include "../lib/Interprocess.h"
  20. #include "../lib/NetPacks.h"
  21. #include "../lib/VCMI_Lib.h"
  22. #include "../lib/map.h"
  23. #include "../lib/JsonNode.h"
  24. #include "mapHandler.h"
  25. #include "CConfigHandler.h"
  26. #include "Client.h"
  27. #include "GUIBase.h"
  28. #include <boost/bind.hpp>
  29. #include <boost/foreach.hpp>
  30. #include <boost/thread.hpp>
  31. #include <boost/thread/shared_mutex.hpp>
  32. #include <boost/lexical_cast.hpp>
  33. #include <sstream>
  34. #include "CPreGame.h"
  35. #include "CBattleInterface.h"
  36. #include "../lib/CThreadHelper.h"
  37. #include "../lib/CScriptingModule.h"
  38. #include "../lib/CFileUtility.h"
  39. #define NOT_LIB
  40. #include "../lib/RegisterTypes.cpp"
  41. #include <fstream>
  42. extern std::string NAME;
  43. namespace intpr = boost::interprocess;
  44. /*
  45. * Client.cpp, part of VCMI engine
  46. *
  47. * Authors: listed in file AUTHORS in main folder
  48. *
  49. * License: GNU General Public License v2.0 or later
  50. * Full text of license available in license.txt file, in main folder
  51. *
  52. */
  53. template <typename T> class CApplyOnCL;
  54. class CBaseForCLApply
  55. {
  56. public:
  57. virtual void applyOnClAfter(CClient *cl, void *pack) const =0;
  58. virtual void applyOnClBefore(CClient *cl, void *pack) const =0;
  59. virtual ~CBaseForCLApply(){}
  60. template<typename U> static CBaseForCLApply *getApplier(const U * t=NULL)
  61. {
  62. return new CApplyOnCL<U>;
  63. }
  64. };
  65. template <typename T> class CApplyOnCL : public CBaseForCLApply
  66. {
  67. public:
  68. void applyOnClAfter(CClient *cl, void *pack) const
  69. {
  70. T *ptr = static_cast<T*>(pack);
  71. ptr->applyCl(cl);
  72. }
  73. void applyOnClBefore(CClient *cl, void *pack) const
  74. {
  75. T *ptr = static_cast<T*>(pack);
  76. ptr->applyFirstCl(cl);
  77. }
  78. };
  79. static CApplier<CBaseForCLApply> *applier = NULL;
  80. void CClient::init()
  81. {
  82. hotSeat = false;
  83. connectionHandler = NULL;
  84. pathInfo = NULL;
  85. applier = new CApplier<CBaseForCLApply>;
  86. registerTypes2(*applier);
  87. IObjectInterface::cb = this;
  88. serv = NULL;
  89. gs = NULL;
  90. cb = NULL;
  91. erm = NULL;
  92. terminate = false;
  93. }
  94. CClient::CClient(void)
  95. {
  96. init();
  97. }
  98. CClient::CClient(CConnection *con, StartInfo *si)
  99. {
  100. init();
  101. newGame(con,si);
  102. }
  103. CClient::~CClient(void)
  104. {
  105. delete pathInfo;
  106. delete applier;
  107. }
  108. void CClient::waitForMoveAndSend(int color)
  109. {
  110. try
  111. {
  112. assert(vstd::contains(battleints, color));
  113. BattleAction ba = battleints[color]->activeStack(gs->curB->getStack(gs->curB->activeStack, false));
  114. MakeAction temp_action(ba);
  115. *serv << &temp_action;
  116. return;
  117. }HANDLE_EXCEPTION
  118. tlog1 << "We should not be here!" << std::endl;
  119. }
  120. void CClient::run()
  121. {
  122. setThreadName(-1, "CClient::run");
  123. try
  124. {
  125. CPack *pack = NULL;
  126. while(!terminate)
  127. {
  128. pack = serv->retreivePack(); //get the package from the server
  129. if (terminate)
  130. {
  131. delete pack;
  132. pack = NULL;
  133. break;
  134. }
  135. handlePack(pack);
  136. pack = NULL;
  137. }
  138. }
  139. catch (const std::exception& e)
  140. {
  141. tlog3 << "Lost connection to server, ending listening thread!\n";
  142. tlog1 << e.what() << std::endl;
  143. if(!terminate) //rethrow (-> boom!) only if closing connection was unexpected
  144. {
  145. tlog1 << "Something wrong, lost connection while game is still ongoing...\n";
  146. throw;
  147. }
  148. }
  149. }
  150. void CClient::save(const std::string & fname)
  151. {
  152. if(gs->curB)
  153. {
  154. tlog1 << "Game cannot be saved during battle!\n";
  155. return;
  156. }
  157. SaveGame save_game(fname);
  158. *serv << &save_game;
  159. }
  160. void CClient::endGame( bool closeConnection /*= true*/ )
  161. {
  162. // Game is ending
  163. // Tell the network thread to reach a stable state
  164. if(closeConnection)
  165. stopConnection();
  166. tlog0 << "Closed connection." << std::endl;
  167. GH.curInt = NULL;
  168. LOCPLINT->terminate_cond.setn(true);
  169. LOCPLINT->pim->lock();
  170. tlog0 << "\n\nEnding current game!" << std::endl;
  171. if(GH.topInt())
  172. GH.topInt()->deactivate();
  173. GH.listInt.clear();
  174. GH.objsToBlit.clear();
  175. GH.statusbar = NULL;
  176. tlog0 << "Removed GUI." << std::endl;
  177. delete CGI->mh;
  178. const_cast<CGameInfo*>(CGI)->mh = NULL;
  179. const_cast<CGameInfo*>(CGI)->state.dellNull();
  180. tlog0 << "Deleted mapHandler and gameState." << std::endl;
  181. CPlayerInterface * oldInt = LOCPLINT;
  182. LOCPLINT = NULL;
  183. oldInt->pim->unlock();
  184. while (!playerint.empty())
  185. {
  186. CGameInterface *pint = playerint.begin()->second;
  187. playerint.erase(playerint.begin());
  188. delete pint;
  189. }
  190. callbacks.clear();
  191. tlog0 << "Deleted playerInts." << std::endl;
  192. tlog0 << "Client stopped." << std::endl;
  193. }
  194. void CClient::loadGame( const std::string & fname )
  195. {
  196. tlog0 <<"\n\nLoading procedure started!\n\n";
  197. CServerHandler sh;
  198. sh.startServer();
  199. timeHandler tmh;
  200. {
  201. char sig[8];
  202. CMapHeader dum;
  203. const_cast<CGameInfo*>(CGI)->mh = new CMapHandler();
  204. StartInfo *si;
  205. CLoadFile lf(fname + ".vlgm1");
  206. lf >> sig >> dum >> si;
  207. tlog0 <<"Reading save signature: "<<tmh.getDif()<<std::endl;
  208. lf >> *VLC;
  209. const_cast<CGameInfo*>(CGI)->setFromLib();
  210. tlog0 <<"Reading handlers: "<<tmh.getDif()<<std::endl;
  211. lf >> gs;
  212. tlog0 <<"Reading gamestate: "<<tmh.getDif()<<std::endl;
  213. const_cast<CGameInfo*>(CGI)->state = gs;
  214. const_cast<CGameInfo*>(CGI)->mh->map = gs->map;
  215. pathInfo = new CPathsInfo(int3(gs->map->width, gs->map->height, gs->map->twoLevel+1));
  216. CGI->mh->init();
  217. tlog0 <<"Initing maphandler: "<<tmh.getDif()<<std::endl;
  218. }
  219. serv = sh.connectToServer();
  220. serv->addStdVecItems(gs);
  221. tmh.update();
  222. ui8 pom8;
  223. *serv << ui8(3) << ui8(1); //load game; one client
  224. *serv << fname;
  225. *serv >> pom8;
  226. if(pom8)
  227. throw "Server cannot open the savegame!";
  228. else
  229. tlog0 << "Server opened savegame properly.\n";
  230. *serv << ui32(gs->scenarioOps->playerInfos.size()+1); //number of players + neutral
  231. for(std::map<int, PlayerSettings>::iterator it = gs->scenarioOps->playerInfos.begin();
  232. it != gs->scenarioOps->playerInfos.end(); ++it)
  233. {
  234. *serv << ui8(it->first); //players
  235. }
  236. *serv << ui8(255); // neutrals
  237. tlog0 <<"Sent info to server: "<<tmh.getDif()<<std::endl;
  238. {
  239. CLoadFile lf(fname + ".vcgm1");
  240. lf >> *this;
  241. }
  242. }
  243. void CClient::newGame( CConnection *con, StartInfo *si )
  244. {
  245. enum {SINGLE, HOST, GUEST} networkMode = SINGLE;
  246. std::set<ui8> myPlayers;
  247. if (con == NULL)
  248. {
  249. CServerHandler sh;
  250. serv = sh.connectToServer();
  251. }
  252. else
  253. {
  254. serv = con;
  255. networkMode = (con->connectionID == 1) ? HOST : GUEST;
  256. }
  257. for(std::map<int, PlayerSettings>::iterator it =si->playerInfos.begin();
  258. it != si->playerInfos.end(); ++it)
  259. {
  260. if((networkMode == SINGLE) //single - one client has all player
  261. || (networkMode != SINGLE && serv->connectionID == it->second.human) //multi - client has only "its players"
  262. || (networkMode == HOST && it->second.human == false)) //multi - host has all AI players
  263. {
  264. myPlayers.insert(ui8(it->first)); //add player
  265. }
  266. }
  267. if(networkMode != GUEST)
  268. myPlayers.insert(255); //neutral
  269. timeHandler tmh;
  270. const_cast<CGameInfo*>(CGI)->state = new CGameState();
  271. tlog0 <<"\tGamestate: "<<tmh.getDif()<<std::endl;
  272. CConnection &c(*serv);
  273. ////////////////////////////////////////////////////
  274. if(networkMode == SINGLE)
  275. {
  276. ui8 pom8;
  277. c << ui8(2) << ui8(1); //new game; one client
  278. c << *si;
  279. c >> pom8;
  280. if(pom8)
  281. throw "Server cannot open the map!";
  282. else
  283. tlog0 << "Server opened map properly.\n";
  284. }
  285. c << myPlayers;
  286. ui32 seed, sum;
  287. c >> si >> sum >> seed;
  288. tlog0 <<"\tSending/Getting info to/from the server: "<<tmh.getDif()<<std::endl;
  289. tlog0 << "\tUsing random seed: "<<seed << std::endl;
  290. gs = const_cast<CGameInfo*>(CGI)->state;
  291. gs->scenarioOps = si;
  292. gs->init(si, sum, seed);
  293. tlog0 <<"Initializing GameState (together): "<<tmh.getDif()<<std::endl;
  294. if(gs->map)
  295. {
  296. const_cast<CGameInfo*>(CGI)->mh = new CMapHandler();
  297. CGI->mh->map = gs->map;
  298. tlog0 <<"Creating mapHandler: "<<tmh.getDif()<<std::endl;
  299. CGI->mh->init();
  300. pathInfo = new CPathsInfo(int3(gs->map->width, gs->map->height, gs->map->twoLevel+1));
  301. tlog0 <<"Initializing mapHandler (together): "<<tmh.getDif()<<std::endl;
  302. }
  303. int humanPlayers = 0;
  304. for(std::map<int, PlayerSettings>::iterator it = gs->scenarioOps->playerInfos.begin();
  305. it != gs->scenarioOps->playerInfos.end(); ++it)//initializing interfaces for players
  306. {
  307. ui8 color = it->first;
  308. gs->currentPlayer = color;
  309. if(!vstd::contains(myPlayers, color))
  310. continue;
  311. if(si->mode != StartInfo::DUEL)
  312. {
  313. CCallback *cb = new CCallback(gs,color,this);
  314. if(!it->second.human)
  315. {
  316. playerint[color] = static_cast<CGameInterface*>(CDynLibHandler::getNewAI(conf.cc.defaultPlayerAI));
  317. }
  318. else
  319. {
  320. playerint[color] = new CPlayerInterface(color);
  321. humanPlayers++;
  322. }
  323. battleints[color] = playerint[color];
  324. playerint[color]->init(cb);
  325. callbacks[color] = boost::shared_ptr<CCallback>(cb);
  326. }
  327. else
  328. {
  329. CBattleCallback * cbc = new CBattleCallback(gs, color, this);
  330. battleints[color] = CDynLibHandler::getNewBattleAI("StupidAI");
  331. battleints[color]->init(cbc);
  332. }
  333. }
  334. if(si->mode == StartInfo::DUEL)
  335. {
  336. CPlayerInterface *p = new CPlayerInterface(-1);
  337. p->observerInDuelMode = true;
  338. battleints[254] = playerint[254] = p;
  339. GH.curInt = p;
  340. p->init(new CCallback(gs, -1, this));
  341. battleStarted(gs->curB);
  342. }
  343. else
  344. {
  345. loadNeutralBattleAI();
  346. }
  347. serv->addStdVecItems(const_cast<CGameInfo*>(CGI)->state);
  348. hotSeat = (humanPlayers > 1);
  349. // std::vector<FileInfo> scriptModules;
  350. // CFileUtility::getFilesWithExt(scriptModules, LIB_DIR "/Scripting", "." LIB_EXT);
  351. // BOOST_FOREACH(FileInfo &m, scriptModules)
  352. // {
  353. // CScriptingModule * nm = CDynLibHandler::getNewScriptingModule(m.name);
  354. // privilagedGameEventReceivers.push_back(nm);
  355. // privilagedBattleEventReceivers.push_back(nm);
  356. // nm->giveActionCB(this);
  357. // nm->giveInfoCB(this);
  358. // nm->init();
  359. //
  360. // erm = nm; //something tells me that there'll at most one module and it'll be ERM
  361. // }
  362. }
  363. void CClient::newDuel(CConnection *con, StartInfo *si)
  364. {
  365. if(si->mode == StartInfo::DUEL)
  366. {
  367. serv = con;
  368. if(!serv)
  369. {
  370. std::string host = "127.0.0.1";
  371. std::string port = "3030";
  372. int i = 3;
  373. while(!serv)
  374. {
  375. try
  376. {
  377. tlog0 << "Establishing connection...\n";
  378. serv = new CConnection(host, port, NAME);
  379. }
  380. catch(...)
  381. {
  382. tlog1 << "\nCannot establish connection! Retrying within 2 seconds" << std::endl;
  383. boost::this_thread::sleep(boost::posix_time::seconds(2));
  384. if(!--i)
  385. exit(0);
  386. }
  387. }
  388. }
  389. ui8 color;
  390. std::string battleAIName;
  391. *serv >> *si >> battleAIName >> color;
  392. assert(si->mode == StartInfo::DUEL);
  393. assert(color > 1); //we are NOT participants
  394. //tlog0 << format("Server wants us to be %s in battle %s as side %d") % battleAIName % si.mapname % (int)color;
  395. }
  396. else
  397. {
  398. si->mode = StartInfo::DUEL;
  399. }
  400. gs = new CGameState();
  401. const_cast<CGameInfo*>(CGI)->state = gs;
  402. //gs->scenarioOps = si;
  403. gs->init(si, 0, 0);
  404. CPlayerInterface *p = new CPlayerInterface(-1);
  405. privilagedBattleEventReceivers.push_back(p);
  406. p->observerInDuelMode = true;
  407. battleints[254] = playerint[254] = p;
  408. GH.curInt = p;
  409. p->init(new CCallback(gs, -1, this));
  410. battleStarted(gs->curB);
  411. if(serv)
  412. serv->addStdVecItems(const_cast<CGameInfo*>(CGI)->state);
  413. }
  414. template <typename Handler>
  415. void CClient::serialize( Handler &h, const int version )
  416. {
  417. h & hotSeat;
  418. if(h.saving)
  419. {
  420. ui8 players = playerint.size();
  421. h & players;
  422. for(std::map<ui8,CGameInterface *>::iterator i = playerint.begin(); i != playerint.end(); i++)
  423. {
  424. h & i->first & i->second->dllName;
  425. i->second->serialize(h,version);
  426. }
  427. }
  428. else
  429. {
  430. ui8 players;
  431. h & players;
  432. for(int i=0; i < players; i++)
  433. {
  434. std::string dllname;
  435. ui8 pid;
  436. h & pid & dllname;
  437. CGameInterface *nInt = NULL;
  438. if(dllname.length())
  439. {
  440. if(pid == 255)
  441. {
  442. //CBattleCallback * cbc = new CBattleCallback(gs, pid, this);//FIXME: unused?
  443. CBattleGameInterface *cbgi = CDynLibHandler::getNewBattleAI(dllname);
  444. battleints[pid] = cbgi;
  445. cbgi->init(cb);
  446. //TODO? consider serialization
  447. continue;
  448. }
  449. else
  450. nInt = CDynLibHandler::getNewAI(dllname);
  451. }
  452. else
  453. nInt = new CPlayerInterface(pid);
  454. callbacks[pid] = boost::shared_ptr<CCallback>(new CCallback(gs,pid,this));
  455. battleints[pid] = playerint[pid] = nInt;
  456. nInt->init(callbacks[pid].get());
  457. nInt->serialize(h, version);
  458. }
  459. if(!vstd::contains(battleints, NEUTRAL_PLAYER))
  460. loadNeutralBattleAI();
  461. }
  462. }
  463. void CClient::handlePack( CPack * pack )
  464. {
  465. CBaseForCLApply *apply = applier->apps[typeList.getTypeID(pack)]; //find the applier
  466. if(apply)
  467. {
  468. apply->applyOnClBefore(this,pack);
  469. tlog5 << "\tMade first apply on cl\n";
  470. gs->apply(pack);
  471. tlog5 << "\tApplied on gs\n";
  472. apply->applyOnClAfter(this,pack);
  473. tlog5 << "\tMade second apply on cl\n";
  474. }
  475. else
  476. {
  477. tlog1 << "Message cannot be applied, cannot find applier! TypeID " << typeList.getTypeID(pack) << std::endl;
  478. }
  479. delete pack;
  480. }
  481. void CClient::updatePaths()
  482. {
  483. //TODO? lazy evaluation? paths now can get recalculated multiple times upon various game events
  484. const CGHeroInstance *h = getSelectedHero();
  485. if (h)//if we have selected hero...
  486. calculatePaths(h);
  487. }
  488. void CClient::finishCampaign( CCampaignState * camp )
  489. {
  490. }
  491. void CClient::proposeNextMission( CCampaignState * camp )
  492. {
  493. GH.pushInt(new CBonusSelection(camp));
  494. GH.curInt = CGP;
  495. }
  496. void CClient::stopConnection()
  497. {
  498. terminate = true;
  499. if (serv) //request closing connection
  500. {
  501. tlog0 << "Connection has been requested to be closed.\n";
  502. boost::unique_lock<boost::mutex>(*serv->wmx);
  503. CloseServer close_server;
  504. *serv << &close_server;
  505. tlog0 << "Sent closing signal to the server\n";
  506. }
  507. if(connectionHandler)//end connection handler
  508. {
  509. if(connectionHandler->get_id() != boost::this_thread::get_id())
  510. connectionHandler->join();
  511. tlog0 << "Connection handler thread joined" << std::endl;
  512. delete connectionHandler;
  513. connectionHandler = NULL;
  514. }
  515. if (serv) //and delete connection
  516. {
  517. serv->close();
  518. delete serv;
  519. serv = NULL;
  520. tlog3 << "Our socket has been closed." << std::endl;
  521. }
  522. }
  523. void CClient::battleStarted(const BattleInfo * info)
  524. {
  525. CPlayerInterface * att, * def;
  526. if(vstd::contains(playerint, info->sides[0]) && playerint[info->sides[0]]->human)
  527. att = static_cast<CPlayerInterface*>( playerint[info->sides[0]] );
  528. else
  529. att = NULL;
  530. if(vstd::contains(playerint, info->sides[1]) && playerint[info->sides[1]]->human)
  531. def = static_cast<CPlayerInterface*>( playerint[info->sides[1]] );
  532. else
  533. def = NULL;
  534. if(att || def || gs->scenarioOps->mode == StartInfo::DUEL)
  535. 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);
  536. if(vstd::contains(battleints,info->sides[0]))
  537. battleints[info->sides[0]]->battleStart(info->belligerents[0], info->belligerents[1], info->tile, info->heroes[0], info->heroes[1], 0);
  538. if(vstd::contains(battleints,info->sides[1]))
  539. battleints[info->sides[1]]->battleStart(info->belligerents[0], info->belligerents[1], info->tile, info->heroes[0], info->heroes[1], 1);
  540. if(vstd::contains(battleints,254))
  541. battleints[254]->battleStart(info->belligerents[0], info->belligerents[1], info->tile, info->heroes[0], info->heroes[1], 1);
  542. if(info->tacticDistance && vstd::contains(battleints,info->sides[info->tacticsSide]))
  543. {
  544. boost::thread(&CClient::commenceTacticPhaseForInt, this, battleints[info->sides[info->tacticsSide]]);
  545. }
  546. }
  547. void CClient::loadNeutralBattleAI()
  548. {
  549. battleints[255] = CDynLibHandler::getNewBattleAI(conf.cc.defaultBattleAI);
  550. battleints[255]->init(new CBattleCallback(gs, 255, this));
  551. }
  552. void CClient::commitPackage( CPackForClient *pack )
  553. {
  554. CommitPackage cp;
  555. cp.freePack = false;
  556. cp.packToCommit = pack;
  557. *serv << &cp;
  558. }
  559. int CClient::getLocalPlayer() const
  560. {
  561. if(LOCPLINT)
  562. return LOCPLINT->playerID;
  563. return getCurrentPlayer();
  564. }
  565. void CClient::calculatePaths(const CGHeroInstance *h)
  566. {
  567. assert(h);
  568. boost::unique_lock<boost::mutex> pathLock(pathMx);
  569. gs->calculatePaths(h, *pathInfo);
  570. }
  571. void CClient::commenceTacticPhaseForInt(CBattleGameInterface *battleInt)
  572. {
  573. setThreadName(-1, "CClient::commenceTacticPhaseForInt");
  574. try
  575. {
  576. battleInt->yourTacticPhase(gs->curB->tacticDistance);
  577. if(gs && !!gs->curB && gs->curB->tacticDistance) //while awaiting for end of tactics phase, many things can happen (end of battle... or game)
  578. {
  579. MakeAction ma(BattleAction::makeEndOFTacticPhase(battleInt->playerID));
  580. serv->sendPack(ma);
  581. }
  582. } HANDLE_EXCEPTION
  583. }
  584. void CClient::invalidatePaths(const CGHeroInstance *h /*= NULL*/)
  585. {
  586. if(!h || pathInfo->hero == h)
  587. pathInfo->isValid = false;
  588. }
  589. std::string typeName(CPack * pack)
  590. {
  591. try
  592. {
  593. return typeid(*pack).name();
  594. }
  595. catch(...)
  596. {
  597. return "unknown type";
  598. //tlog1 << "\Unknown type!\t" << e.what() << std::endl;
  599. }
  600. }
  601. void CClient::runReplay(CLoadFile *f)
  602. {
  603. setThreadName(-1, "CClient::runReplay");
  604. try
  605. {
  606. f->sfile->exceptions(std::ifstream::failbit | std::ifstream::badbit | std::ifstream::eofbit);
  607. int i = 0;
  608. std::vector<CPack *> hlp;
  609. while(f->sfile)
  610. {
  611. i = hlp.size();
  612. tlog5 << i;
  613. ui8 magic;
  614. std::pair<ui8, CPack *> para;
  615. para.first = 254;
  616. para.second = NULL;
  617. try
  618. {
  619. *f >> para >> magic;
  620. }
  621. catch(...)
  622. {
  623. break;
  624. }
  625. if(magic != '*')
  626. throw std::runtime_error("Bad magic byte!");
  627. assert(para.second);
  628. if(para.first != 255)
  629. {
  630. tlog5 << "\tIgnoring message from player " << (int)para.first
  631. << " (" << typeName(para.second) << ")" << std::endl;
  632. }
  633. else
  634. {
  635. tlog5 << "\tRead message of type " << typeName(para.second) << std::endl;
  636. hlp.push_back(para.second);
  637. }
  638. }
  639. i = 0;
  640. while(!terminate && i < hlp.size())
  641. {
  642. tlog1 << i << "\tHandling pack of type " << typeName(hlp[i]) << std::endl;
  643. handlePack(hlp[i++]);
  644. }
  645. }
  646. catch (const std::exception& e)
  647. {
  648. tlog3 << "Failure when replaying from file, ending reading thread!\n";
  649. tlog1 << e.what() << std::endl;
  650. if(!terminate) //rethrow (-> boom!) only if closing connection was unexpected
  651. {
  652. tlog1 << "Something wrong, failed reading while game is still ongoing...\n";
  653. throw;
  654. }
  655. }
  656. }
  657. template void CClient::serialize( CISer<CLoadFile> &h, const int version );
  658. template void CClient::serialize( COSer<CSaveFile> &h, const int version );
  659. void CServerHandler::startServer()
  660. {
  661. th.update();
  662. serverThread = new boost::thread(&CServerHandler::callServer, this); //runs server executable;
  663. if(verbose)
  664. tlog0 << "Setting up thread calling server: " << th.getDif() << std::endl;
  665. }
  666. void CServerHandler::waitForServer()
  667. {
  668. if(!serverThread)
  669. startServer();
  670. th.update();
  671. intpr::scoped_lock<intpr::interprocess_mutex> slock(shared->sr->mutex);
  672. while(!shared->sr->ready)
  673. {
  674. shared->sr->cond.wait(slock);
  675. }
  676. if(verbose)
  677. tlog0 << "Waiting for server: " << th.getDif() << std::endl;
  678. }
  679. CConnection * CServerHandler::connectToServer()
  680. {
  681. if(!shared->sr->ready)
  682. waitForServer();
  683. th.update();
  684. CConnection *ret = justConnectToServer(conf.cc.server, port);
  685. if(verbose)
  686. tlog0<<"\tConnecting to the server: "<<th.getDif()<<std::endl;
  687. return ret;
  688. }
  689. CServerHandler::CServerHandler(bool runServer /*= false*/)
  690. {
  691. serverThread = NULL;
  692. shared = NULL;
  693. port = boost::lexical_cast<std::string>(conf.cc.port);
  694. verbose = false;
  695. 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
  696. try
  697. {
  698. shared = new SharedMem();
  699. } HANDLE_EXCEPTIONC(tlog1 << "Cannot open interprocess memory: ";)
  700. }
  701. CServerHandler::~CServerHandler()
  702. {
  703. delete shared;
  704. delete serverThread; //detaches, not kills thread
  705. }
  706. void CServerHandler::callServer()
  707. {
  708. setThreadName(-1, "CServerHandler::callServer");
  709. std::string comm = std::string(BIN_DIR PATH_SEPARATOR SERVER_NAME " ") + port + " > server_log.txt";
  710. std::system(comm.c_str());
  711. tlog0 << "Server finished\n";
  712. }
  713. CConnection * CServerHandler::justConnectToServer(const std::string &host, const std::string &port)
  714. {
  715. CConnection *ret = NULL;
  716. while(!ret)
  717. {
  718. try
  719. {
  720. tlog0 << "Establishing connection...\n";
  721. ret = new CConnection( host.size() ? host : conf.cc.server,
  722. port.size() ? port : boost::lexical_cast<std::string>(conf.cc.port),
  723. NAME);
  724. }
  725. catch(...)
  726. {
  727. tlog1 << "\nCannot establish connection! Retrying within 2 seconds" << std::endl;
  728. SDL_Delay(2000);
  729. }
  730. }
  731. return ret;
  732. }