Client.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714
  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/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/VCMIDirs.h"
  23. #include "../lib/map.h"
  24. #include "../lib/JsonNode.h"
  25. #include "mapHandler.h"
  26. #include "CConfigHandler.h"
  27. #include "Client.h"
  28. #include "GUIBase.h"
  29. #include <boost/bind.hpp>
  30. #include <boost/foreach.hpp>
  31. #include <boost/thread.hpp>
  32. #include <boost/thread/shared_mutex.hpp>
  33. #include <boost/lexical_cast.hpp>
  34. #include <sstream>
  35. #include "CPreGame.h"
  36. #include "CBattleInterface.h"
  37. #include "../CThreadHelper.h"
  38. #include "../lib/CScriptingModule.h"
  39. #include "../lib/CFileUtility.h"
  40. #define NOT_LIB
  41. #include "../lib/RegisterTypes.cpp"
  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. :waitingRequest(0)
  96. {
  97. init();
  98. }
  99. CClient::CClient(CConnection *con, StartInfo *si)
  100. :waitingRequest(0)
  101. {
  102. init();
  103. newGame(con,si);
  104. }
  105. CClient::~CClient(void)
  106. {
  107. delete pathInfo;
  108. delete applier;
  109. }
  110. void CClient::waitForMoveAndSend(int color)
  111. {
  112. try
  113. {
  114. assert(vstd::contains(battleints, color));
  115. BattleAction ba = battleints[color]->activeStack(gs->curB->getStack(gs->curB->activeStack, false));
  116. MakeAction temp_action(ba);
  117. *serv << &temp_action;
  118. return;
  119. }HANDLE_EXCEPTION
  120. tlog1 << "We should not be here!" << std::endl;
  121. }
  122. void CClient::run()
  123. {
  124. setThreadName(-1, "CClient::run");
  125. try
  126. {
  127. CPack *pack = NULL;
  128. while(!terminate)
  129. {
  130. pack = serv->retreivePack(); //get the package from the server
  131. if (terminate)
  132. {
  133. delete pack;
  134. pack = NULL;
  135. break;
  136. }
  137. handlePack(pack);
  138. pack = NULL;
  139. }
  140. }
  141. catch (const std::exception& e)
  142. {
  143. tlog3 << "Lost connection to server, ending listening thread!\n";
  144. tlog1 << e.what() << std::endl;
  145. if(!terminate) //rethrow (-> boom!) only if closing connection was unexpected
  146. {
  147. tlog1 << "Something wrong, lost connection while game is still ongoing...\n";
  148. throw;
  149. }
  150. }
  151. }
  152. void CClient::save(const std::string & fname)
  153. {
  154. if(gs->curB)
  155. {
  156. tlog1 << "Game cannot be saved during battle!\n";
  157. return;
  158. }
  159. SaveGame save_game(fname);
  160. *serv << &save_game;
  161. }
  162. void CClient::endGame( bool closeConnection /*= true*/ )
  163. {
  164. // Game is ending
  165. // Tell the network thread to reach a stable state
  166. if(closeConnection)
  167. stopConnection();
  168. tlog0 << "Closed connection." << std::endl;
  169. GH.curInt = NULL;
  170. LOCPLINT->terminate_cond.setn(true);
  171. LOCPLINT->pim->lock();
  172. tlog0 << "\n\nEnding current game!" << std::endl;
  173. if(GH.topInt())
  174. GH.topInt()->deactivate();
  175. GH.listInt.clear();
  176. GH.objsToBlit.clear();
  177. GH.statusbar = NULL;
  178. tlog0 << "Removed GUI." << std::endl;
  179. delete CGI->mh;
  180. const_cast<CGameInfo*>(CGI)->mh = NULL;
  181. const_cast<CGameInfo*>(CGI)->state.dellNull();
  182. tlog0 << "Deleted mapHandler and gameState." << std::endl;
  183. CPlayerInterface * oldInt = LOCPLINT;
  184. LOCPLINT = NULL;
  185. oldInt->pim->unlock();
  186. while (!playerint.empty())
  187. {
  188. CGameInterface *pint = playerint.begin()->second;
  189. playerint.erase(playerint.begin());
  190. delete pint;
  191. }
  192. callbacks.clear();
  193. tlog0 << "Deleted playerInts." << std::endl;
  194. tlog0 << "Client stopped." << std::endl;
  195. }
  196. void CClient::loadGame( const std::string & fname )
  197. {
  198. tlog0 <<"\n\nLoading procedure started!\n\n";
  199. CServerHandler sh;
  200. sh.startServer();
  201. timeHandler tmh;
  202. {
  203. char sig[8];
  204. CMapHeader dum;
  205. const_cast<CGameInfo*>(CGI)->mh = new CMapHandler();
  206. StartInfo *si;
  207. CLoadFile lf(fname + ".vlgm1");
  208. lf >> sig >> dum >> si;
  209. tlog0 <<"Reading save signature: "<<tmh.getDif()<<std::endl;
  210. lf >> *VLC;
  211. const_cast<CGameInfo*>(CGI)->setFromLib();
  212. tlog0 <<"Reading handlers: "<<tmh.getDif()<<std::endl;
  213. lf >> gs;
  214. tlog0 <<"Reading gamestate: "<<tmh.getDif()<<std::endl;
  215. const_cast<CGameInfo*>(CGI)->state = gs;
  216. const_cast<CGameInfo*>(CGI)->mh->map = gs->map;
  217. pathInfo = new CPathsInfo(int3(gs->map->width, gs->map->height, gs->map->twoLevel+1));
  218. CGI->mh->init();
  219. tlog0 <<"Initing maphandler: "<<tmh.getDif()<<std::endl;
  220. }
  221. serv = sh.connectToServer();
  222. serv->addStdVecItems(gs);
  223. tmh.update();
  224. ui8 pom8;
  225. *serv << ui8(3) << ui8(1); //load game; one client
  226. *serv << fname;
  227. *serv >> pom8;
  228. if(pom8)
  229. throw "Server cannot open the savegame!";
  230. else
  231. tlog0 << "Server opened savegame properly.\n";
  232. *serv << ui32(gs->scenarioOps->playerInfos.size()+1); //number of players + neutral
  233. for(std::map<int, PlayerSettings>::iterator it = gs->scenarioOps->playerInfos.begin();
  234. it != gs->scenarioOps->playerInfos.end(); ++it)
  235. {
  236. *serv << ui8(it->first); //players
  237. }
  238. *serv << ui8(255); // neutrals
  239. tlog0 <<"Sent info to server: "<<tmh.getDif()<<std::endl;
  240. {
  241. CLoadFile lf(fname + ".vcgm1");
  242. lf >> *this;
  243. }
  244. }
  245. void CClient::newGame( CConnection *con, StartInfo *si )
  246. {
  247. enum {SINGLE, HOST, GUEST} networkMode = SINGLE;
  248. std::set<ui8> myPlayers;
  249. if (con == NULL)
  250. {
  251. CServerHandler sh;
  252. serv = sh.connectToServer();
  253. }
  254. else
  255. {
  256. serv = con;
  257. networkMode = (con->connectionID == 1) ? HOST : GUEST;
  258. }
  259. for(std::map<int, PlayerSettings>::iterator it =si->playerInfos.begin();
  260. it != si->playerInfos.end(); ++it)
  261. {
  262. if((networkMode == SINGLE) //single - one client has all player
  263. || (networkMode != SINGLE && serv->connectionID == it->second.human) //multi - client has only "its players"
  264. || (networkMode == HOST && it->second.human == false)) //multi - host has all AI players
  265. {
  266. myPlayers.insert(ui8(it->first)); //add player
  267. }
  268. }
  269. if(networkMode != GUEST)
  270. myPlayers.insert(255); //neutral
  271. timeHandler tmh;
  272. const_cast<CGameInfo*>(CGI)->state = new CGameState();
  273. tlog0 <<"\tGamestate: "<<tmh.getDif()<<std::endl;
  274. CConnection &c(*serv);
  275. ////////////////////////////////////////////////////
  276. if(networkMode == SINGLE)
  277. {
  278. ui8 pom8;
  279. c << ui8(2) << ui8(1); //new game; one client
  280. c << *si;
  281. c >> pom8;
  282. if(pom8)
  283. throw "Server cannot open the map!";
  284. else
  285. tlog0 << "Server opened map properly.\n";
  286. }
  287. c << myPlayers;
  288. ui32 seed, sum;
  289. c >> si >> sum >> seed;
  290. tlog0 <<"\tSending/Getting info to/from the server: "<<tmh.getDif()<<std::endl;
  291. tlog0 << "\tUsing random seed: "<<seed << std::endl;
  292. gs = const_cast<CGameInfo*>(CGI)->state;
  293. gs->scenarioOps = si;
  294. gs->init(si, sum, seed);
  295. tlog0 <<"Initializing GameState (together): "<<tmh.getDif()<<std::endl;
  296. if(gs->map)
  297. {
  298. const_cast<CGameInfo*>(CGI)->mh = new CMapHandler();
  299. CGI->mh->map = gs->map;
  300. tlog0 <<"Creating mapHandler: "<<tmh.getDif()<<std::endl;
  301. CGI->mh->init();
  302. pathInfo = new CPathsInfo(int3(gs->map->width, gs->map->height, gs->map->twoLevel+1));
  303. tlog0 <<"Initializing mapHandler (together): "<<tmh.getDif()<<std::endl;
  304. }
  305. int humanPlayers = 0;
  306. for(std::map<int, PlayerSettings>::iterator it = gs->scenarioOps->playerInfos.begin();
  307. it != gs->scenarioOps->playerInfos.end(); ++it)//initializing interfaces for players
  308. {
  309. ui8 color = it->first;
  310. gs->currentPlayer = color;
  311. if(!vstd::contains(myPlayers, color))
  312. continue;
  313. if(si->mode != StartInfo::DUEL)
  314. {
  315. CCallback *cb = new CCallback(gs,color,this);
  316. if(!it->second.human)
  317. {
  318. playerint[color] = static_cast<CGameInterface*>(CDynLibHandler::getNewAI(conf.cc.defaultPlayerAI));
  319. }
  320. else
  321. {
  322. playerint[color] = new CPlayerInterface(color);
  323. humanPlayers++;
  324. }
  325. battleints[color] = playerint[color];
  326. playerint[color]->init(cb);
  327. callbacks[color] = boost::shared_ptr<CCallback>(cb);
  328. }
  329. else
  330. {
  331. CBattleCallback * cbc = new CBattleCallback(gs, color, this);
  332. battleints[color] = CDynLibHandler::getNewBattleAI("StupidAI");
  333. battleints[color]->init(cbc);
  334. }
  335. }
  336. if(si->mode == StartInfo::DUEL)
  337. {
  338. CPlayerInterface *p = new CPlayerInterface(-1);
  339. p->observerInDuelMode = true;
  340. battleints[254] = playerint[254] = p;
  341. GH.curInt = p;
  342. p->init(new CCallback(gs, -1, this));
  343. battleStarted(gs->curB);
  344. }
  345. else
  346. {
  347. loadNeutralBattleAI();
  348. }
  349. serv->addStdVecItems(const_cast<CGameInfo*>(CGI)->state);
  350. hotSeat = (humanPlayers > 1);
  351. // std::vector<FileInfo> scriptModules;
  352. // CFileUtility::getFilesWithExt(scriptModules, LIB_DIR "/Scripting", "." LIB_EXT);
  353. // BOOST_FOREACH(FileInfo &m, scriptModules)
  354. // {
  355. // CScriptingModule * nm = CDynLibHandler::getNewScriptingModule(m.name);
  356. // privilagedGameEventReceivers.push_back(nm);
  357. // privilagedBattleEventReceivers.push_back(nm);
  358. // nm->giveActionCB(this);
  359. // nm->giveInfoCB(this);
  360. // nm->init();
  361. //
  362. // erm = nm; //something tells me that there'll at most one module and it'll be ERM
  363. // }
  364. }
  365. template <typename Handler>
  366. void CClient::serialize( Handler &h, const int version )
  367. {
  368. h & hotSeat;
  369. if(h.saving)
  370. {
  371. ui8 players = playerint.size();
  372. h & players;
  373. for(std::map<ui8,CGameInterface *>::iterator i = playerint.begin(); i != playerint.end(); i++)
  374. {
  375. h & i->first & i->second->dllName;
  376. i->second->serialize(h,version);
  377. }
  378. }
  379. else
  380. {
  381. ui8 players;
  382. h & players;
  383. for(int i=0; i < players; i++)
  384. {
  385. std::string dllname;
  386. ui8 pid;
  387. h & pid & dllname;
  388. CGameInterface *nInt = NULL;
  389. if(dllname.length())
  390. {
  391. if(pid == 255)
  392. {
  393. //CBattleCallback * cbc = new CBattleCallback(gs, pid, this);//FIXME: unused?
  394. CBattleGameInterface *cbgi = CDynLibHandler::getNewBattleAI(dllname);
  395. battleints[pid] = cbgi;
  396. cbgi->init(cb);
  397. //TODO? consider serialization
  398. continue;
  399. }
  400. else
  401. nInt = CDynLibHandler::getNewAI(dllname);
  402. }
  403. else
  404. nInt = new CPlayerInterface(pid);
  405. callbacks[pid] = boost::shared_ptr<CCallback>(new CCallback(gs,pid,this));
  406. battleints[pid] = playerint[pid] = nInt;
  407. nInt->init(callbacks[pid].get());
  408. nInt->serialize(h, version);
  409. }
  410. if(!vstd::contains(battleints, NEUTRAL_PLAYER))
  411. loadNeutralBattleAI();
  412. }
  413. }
  414. void CClient::handlePack( CPack * pack )
  415. {
  416. CBaseForCLApply *apply = applier->apps[typeList.getTypeID(pack)]; //find the applier
  417. if(apply)
  418. {
  419. apply->applyOnClBefore(this,pack);
  420. tlog5 << "\tMade first apply on cl\n";
  421. gs->apply(pack);
  422. tlog5 << "\tApplied on gs\n";
  423. apply->applyOnClAfter(this,pack);
  424. tlog5 << "\tMade second apply on cl\n";
  425. }
  426. else
  427. {
  428. tlog1 << "Message cannot be applied, cannot find applier! TypeID " << typeList.getTypeID(pack) << std::endl;
  429. }
  430. delete pack;
  431. }
  432. void CClient::updatePaths()
  433. {
  434. //TODO? lazy evaluation? paths now can get recalculated multiple times upon various game events
  435. const CGHeroInstance *h = getSelectedHero();
  436. if (h)//if we have selected hero...
  437. calculatePaths(h);
  438. }
  439. void CClient::finishCampaign( CCampaignState * camp )
  440. {
  441. }
  442. void CClient::proposeNextMission( CCampaignState * camp )
  443. {
  444. GH.pushInt(new CBonusSelection(camp));
  445. GH.curInt = CGP;
  446. }
  447. void CClient::stopConnection()
  448. {
  449. terminate = true;
  450. if (serv) //request closing connection
  451. {
  452. tlog0 << "Connection has been requested to be closed.\n";
  453. boost::unique_lock<boost::mutex>(*serv->wmx);
  454. CloseServer close_server;
  455. *serv << &close_server;
  456. tlog0 << "Sent closing signal to the server\n";
  457. }
  458. if(connectionHandler)//end connection handler
  459. {
  460. if(connectionHandler->get_id() != boost::this_thread::get_id())
  461. connectionHandler->join();
  462. tlog0 << "Connection handler thread joined" << std::endl;
  463. delete connectionHandler;
  464. connectionHandler = NULL;
  465. }
  466. if (serv) //and delete connection
  467. {
  468. serv->close();
  469. delete serv;
  470. serv = NULL;
  471. tlog3 << "Our socket has been closed." << std::endl;
  472. }
  473. }
  474. void CClient::battleStarted(const BattleInfo * info)
  475. {
  476. CPlayerInterface * att, * def;
  477. if(vstd::contains(playerint, info->sides[0]) && playerint[info->sides[0]]->human)
  478. att = static_cast<CPlayerInterface*>( playerint[info->sides[0]] );
  479. else
  480. att = NULL;
  481. if(vstd::contains(playerint, info->sides[1]) && playerint[info->sides[1]]->human)
  482. def = static_cast<CPlayerInterface*>( playerint[info->sides[1]] );
  483. else
  484. def = NULL;
  485. if(att || def || gs->scenarioOps->mode == StartInfo::DUEL)
  486. 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);
  487. if(vstd::contains(battleints,info->sides[0]))
  488. battleints[info->sides[0]]->battleStart(info->belligerents[0], info->belligerents[1], info->tile, info->heroes[0], info->heroes[1], 0);
  489. if(vstd::contains(battleints,info->sides[1]))
  490. battleints[info->sides[1]]->battleStart(info->belligerents[0], info->belligerents[1], info->tile, info->heroes[0], info->heroes[1], 1);
  491. if(vstd::contains(battleints,254))
  492. battleints[254]->battleStart(info->belligerents[0], info->belligerents[1], info->tile, info->heroes[0], info->heroes[1], 1);
  493. if(info->tacticDistance && vstd::contains(battleints,info->sides[info->tacticsSide]))
  494. {
  495. boost::thread(&CClient::commenceTacticPhaseForInt, this, battleints[info->sides[info->tacticsSide]]);
  496. }
  497. }
  498. void CClient::loadNeutralBattleAI()
  499. {
  500. battleints[255] = CDynLibHandler::getNewBattleAI(conf.cc.defaultBattleAI);
  501. battleints[255]->init(new CBattleCallback(gs, 255, this));
  502. }
  503. void CClient::commitPackage( CPackForClient *pack )
  504. {
  505. CommitPackage cp;
  506. cp.freePack = false;
  507. cp.packToCommit = pack;
  508. *serv << &cp;
  509. }
  510. int CClient::getLocalPlayer() const
  511. {
  512. if(LOCPLINT)
  513. return LOCPLINT->playerID;
  514. return getCurrentPlayer();
  515. }
  516. void CClient::calculatePaths(const CGHeroInstance *h)
  517. {
  518. assert(h);
  519. boost::unique_lock<boost::mutex> pathLock(pathMx);
  520. gs->calculatePaths(h, *pathInfo);
  521. }
  522. void CClient::commenceTacticPhaseForInt(CBattleGameInterface *battleInt)
  523. {
  524. setThreadName(-1, "CClient::commenceTacticPhaseForInt");
  525. try
  526. {
  527. battleInt->yourTacticPhase(gs->curB->tacticDistance);
  528. if(gs && !!gs->curB && gs->curB->tacticDistance) //while awaiting for end of tactics phase, many things can happen (end of battle... or game)
  529. {
  530. MakeAction ma(BattleAction::makeEndOFTacticPhase(battleInt->playerID));
  531. serv->sendPack(ma);
  532. }
  533. } HANDLE_EXCEPTION
  534. }
  535. void CClient::invalidatePaths(const CGHeroInstance *h /*= NULL*/)
  536. {
  537. if(!h || pathInfo->hero == h)
  538. pathInfo->isValid = false;
  539. }
  540. template void CClient::serialize( CISer<CLoadFile> &h, const int version );
  541. template void CClient::serialize( COSer<CSaveFile> &h, const int version );
  542. void CServerHandler::startServer()
  543. {
  544. th.update();
  545. serverThread = new boost::thread(&CServerHandler::callServer, this); //runs server executable;
  546. if(verbose)
  547. tlog0 << "Setting up thread calling server: " << th.getDif() << std::endl;
  548. }
  549. void CServerHandler::waitForServer()
  550. {
  551. if(!serverThread)
  552. startServer();
  553. th.update();
  554. intpr::scoped_lock<intpr::interprocess_mutex> slock(shared->sr->mutex);
  555. while(!shared->sr->ready)
  556. {
  557. shared->sr->cond.wait(slock);
  558. }
  559. if(verbose)
  560. tlog0 << "Waiting for server: " << th.getDif() << std::endl;
  561. }
  562. CConnection * CServerHandler::connectToServer()
  563. {
  564. if(!shared->sr->ready)
  565. waitForServer();
  566. th.update();
  567. CConnection *ret = justConnectToServer(conf.cc.server, port);
  568. if(verbose)
  569. tlog0<<"\tConnecting to the server: "<<th.getDif()<<std::endl;
  570. return ret;
  571. }
  572. CServerHandler::CServerHandler(bool runServer /*= false*/)
  573. {
  574. serverThread = NULL;
  575. shared = NULL;
  576. port = boost::lexical_cast<std::string>(conf.cc.port);
  577. verbose = false;
  578. 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
  579. try
  580. {
  581. shared = new SharedMem();
  582. } HANDLE_EXCEPTIONC(tlog1 << "Cannot open interprocess memory: ";)
  583. }
  584. CServerHandler::~CServerHandler()
  585. {
  586. delete shared;
  587. delete serverThread; //detaches, not kills thread
  588. }
  589. void CServerHandler::callServer()
  590. {
  591. setThreadName(-1, "CServerHandler::callServer");
  592. std::string logName = GVCMIDirs.UserPath + "/server_log.txt";
  593. std::string comm = std::string(BIN_DIR PATH_SEPARATOR SERVER_NAME " ") + port + " > " + logName;
  594. std::system(comm.c_str());
  595. tlog0 << "Server finished\n";
  596. }
  597. CConnection * CServerHandler::justConnectToServer(const std::string &host, const std::string &port)
  598. {
  599. CConnection *ret = NULL;
  600. while(!ret)
  601. {
  602. try
  603. {
  604. tlog0 << "Establishing connection...\n";
  605. ret = new CConnection( host.size() ? host : conf.cc.server,
  606. port.size() ? port : boost::lexical_cast<std::string>(conf.cc.port),
  607. NAME);
  608. }
  609. catch(...)
  610. {
  611. tlog1 << "\nCannot establish connection! Retrying within 2 seconds" << std::endl;
  612. SDL_Delay(2000);
  613. }
  614. }
  615. return ret;
  616. }