Client.cpp 18 KB

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