Client.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744
  1. #include "StdInc.h"
  2. #include "CMusicHandler.h"
  3. #include "../lib/CCampaignHandler.h"
  4. #include "../CCallback.h"
  5. #include "../lib/CConsoleHandler.h"
  6. #include "CGameInfo.h"
  7. #include "../lib/CGameState.h"
  8. #include "CPlayerInterface.h"
  9. #include "../lib/StartInfo.h"
  10. #include "../lib/BattleState.h"
  11. #include "../lib/CArtHandler.h"
  12. #include "../lib/CDefObjInfoHandler.h"
  13. #include "../lib/CGeneralTextHandler.h"
  14. #include "../lib/CHeroHandler.h"
  15. #include "../lib/CTownHandler.h"
  16. #include "../lib/CObjectHandler.h"
  17. #include "../lib/CBuildingHandler.h"
  18. #include "../lib/CSpellHandler.h"
  19. #include "../lib/Connection.h"
  20. #include "../lib/Interprocess.h"
  21. #include "../lib/NetPacks.h"
  22. #include "../lib/VCMI_Lib.h"
  23. #include "../lib/VCMIDirs.h"
  24. #include "../lib/map.h"
  25. #include "../lib/JsonNode.h"
  26. #include "mapHandler.h"
  27. #include "CConfigHandler.h"
  28. #include "Client.h"
  29. #include "CPreGame.h"
  30. #include "BattleInterface/CBattleInterface.h"
  31. #include "../lib/CThreadHelper.h"
  32. #include "../lib/CScriptingModule.h"
  33. #include "../lib/RegisterTypes.h"
  34. #include "UIFramework/CGuiHandler.h"
  35. extern std::string NAME;
  36. namespace intpr = boost::interprocess;
  37. /*
  38. * Client.cpp, part of VCMI engine
  39. *
  40. * Authors: listed in file AUTHORS in main folder
  41. *
  42. * License: GNU General Public License v2.0 or later
  43. * Full text of license available in license.txt file, in main folder
  44. *
  45. */
  46. template <typename T> class CApplyOnCL;
  47. class CBaseForCLApply
  48. {
  49. public:
  50. virtual void applyOnClAfter(CClient *cl, void *pack) const =0;
  51. virtual void applyOnClBefore(CClient *cl, void *pack) const =0;
  52. virtual ~CBaseForCLApply(){}
  53. template<typename U> static CBaseForCLApply *getApplier(const U * t=NULL)
  54. {
  55. return new CApplyOnCL<U>;
  56. }
  57. };
  58. template <typename T> class CApplyOnCL : public CBaseForCLApply
  59. {
  60. public:
  61. void applyOnClAfter(CClient *cl, void *pack) const
  62. {
  63. T *ptr = static_cast<T*>(pack);
  64. ptr->applyCl(cl);
  65. }
  66. void applyOnClBefore(CClient *cl, void *pack) const
  67. {
  68. T *ptr = static_cast<T*>(pack);
  69. ptr->applyFirstCl(cl);
  70. }
  71. };
  72. static CApplier<CBaseForCLApply> *applier = NULL;
  73. void CClient::init()
  74. {
  75. hotSeat = false;
  76. connectionHandler = NULL;
  77. pathInfo = NULL;
  78. applier = new CApplier<CBaseForCLApply>;
  79. registerTypes2(*applier);
  80. IObjectInterface::cb = this;
  81. serv = NULL;
  82. gs = NULL;
  83. cb = NULL;
  84. erm = NULL;
  85. terminate = false;
  86. }
  87. CClient::CClient(void)
  88. {
  89. init();
  90. }
  91. CClient::CClient(CConnection *con, StartInfo *si)
  92. {
  93. init();
  94. newGame(con,si);
  95. }
  96. CClient::~CClient(void)
  97. {
  98. delete pathInfo;
  99. delete applier;
  100. }
  101. void CClient::waitForMoveAndSend(int color)
  102. {
  103. try
  104. {
  105. assert(vstd::contains(battleints, color));
  106. BattleAction ba = battleints[color]->activeStack(gs->curB->getStack(gs->curB->activeStack, false));
  107. MakeAction temp_action(ba);
  108. sendRequest(&temp_action, color);
  109. return;
  110. }
  111. catch(boost::thread_interrupted&)
  112. {
  113. tlog5 << "Wait for move thread was interrupted and no action will be send. Was a battle ended by spell?\n";
  114. return;
  115. }
  116. HANDLE_EXCEPTION
  117. tlog1 << "We should not be here!" << std::endl;
  118. }
  119. void CClient::run()
  120. {
  121. setThreadName("CClient::run");
  122. try
  123. {
  124. CPack *pack = NULL;
  125. while(!terminate)
  126. {
  127. pack = serv->retreivePack(); //get the package from the server
  128. if (terminate)
  129. {
  130. delete pack;
  131. pack = NULL;
  132. break;
  133. }
  134. handlePack(pack);
  135. pack = NULL;
  136. }
  137. }
  138. //catch only asio exceptions
  139. catch (const boost::system::system_error& 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. sendRequest((CPackForClient*)&save_game, 255);
  159. }
  160. void CClient::endGame( bool closeConnection /*= true*/ )
  161. {
  162. //suggest interfaces to finish their stuff (AI should interrupt any bg working threads)
  163. BOOST_FOREACH(auto i, playerint)
  164. i.second->finish();
  165. // Game is ending
  166. // Tell the network thread to reach a stable state
  167. if(closeConnection)
  168. stopConnection();
  169. tlog0 << "Closed connection." << std::endl;
  170. GH.curInt = NULL;
  171. LOCPLINT->terminate_cond.setn(true);
  172. {
  173. boost::unique_lock<boost::recursive_mutex> un(*LOCPLINT->pim);
  174. tlog0 << "\n\nEnding current game!" << std::endl;
  175. if(GH.topInt())
  176. GH.topInt()->deactivate();
  177. GH.listInt.clear();
  178. GH.objsToBlit.clear();
  179. GH.statusbar = NULL;
  180. tlog0 << "Removed GUI." << std::endl;
  181. delete CGI->mh;
  182. const_cast<CGameInfo*>(CGI)->mh = NULL;
  183. const_cast<CGameInfo*>(CGI)->state.dellNull();
  184. tlog0 << "Deleted mapHandler and gameState." << std::endl;
  185. LOCPLINT = NULL;
  186. }
  187. while (!playerint.empty())
  188. {
  189. CGameInterface *pint = playerint.begin()->second;
  190. playerint.erase(playerint.begin());
  191. delete pint;
  192. }
  193. callbacks.clear();
  194. tlog0 << "Deleted playerInts." << std::endl;
  195. tlog0 << "Client stopped." << std::endl;
  196. }
  197. void CClient::loadGame( const std::string & fname )
  198. {
  199. tlog0 <<"\n\nLoading procedure started!\n\n";
  200. CServerHandler sh;
  201. sh.startServer();
  202. CStopWatch tmh;
  203. {
  204. char sig[8];
  205. CMapHeader dum;
  206. const_cast<CGameInfo*>(CGI)->mh = new CMapHandler();
  207. StartInfo *si;
  208. CLoadFile lf(CResourceHandler::get()->getResourceName(ResourceID(fname, EResType::LIB_SAVEGAME)));
  209. lf >> sig >> dum >> si;
  210. tlog0 <<"Reading save signature: "<<tmh.getDiff()<<std::endl;
  211. lf >> *VLC;
  212. const_cast<CGameInfo*>(CGI)->setFromLib();
  213. tlog0 <<"Reading handlers: "<<tmh.getDiff()<<std::endl;
  214. lf >> gs;
  215. tlog0 <<"Reading gamestate: "<<tmh.getDiff()<<std::endl;
  216. const_cast<CGameInfo*>(CGI)->state = gs;
  217. const_cast<CGameInfo*>(CGI)->mh->map = gs->map;
  218. pathInfo = new CPathsInfo(int3(gs->map->width, gs->map->height, gs->map->twoLevel+1));
  219. CGI->mh->init();
  220. tlog0 <<"Initing maphandler: "<<tmh.getDiff()<<std::endl;
  221. }
  222. serv = sh.connectToServer();
  223. serv->addStdVecItems(gs);
  224. tmh.update();
  225. ui8 pom8;
  226. *serv << ui8(3) << ui8(1); //load game; one client
  227. *serv << fname;
  228. *serv >> pom8;
  229. if(pom8)
  230. throw std::runtime_error("Server cannot open the savegame!");
  231. else
  232. tlog0 << "Server opened savegame properly.\n";
  233. *serv << ui32(gs->scenarioOps->playerInfos.size()+1); //number of players + neutral
  234. for(std::map<int, PlayerSettings>::iterator it = gs->scenarioOps->playerInfos.begin();
  235. it != gs->scenarioOps->playerInfos.end(); ++it)
  236. {
  237. *serv << ui8(it->first); //players
  238. }
  239. *serv << ui8(255); // neutrals
  240. tlog0 <<"Sent info to server: "<<tmh.getDiff()<<std::endl;
  241. {
  242. CLoadFile lf(CResourceHandler::get()->getResourceName(ResourceID(fname, EResType::CLIENT_SAVEGAME)));
  243. lf >> *this;
  244. }
  245. }
  246. void CClient::newGame( CConnection *con, StartInfo *si )
  247. {
  248. enum {SINGLE, HOST, GUEST} networkMode = SINGLE;
  249. std::set<ui8> myPlayers;
  250. if (con == NULL)
  251. {
  252. CServerHandler sh;
  253. serv = sh.connectToServer();
  254. }
  255. else
  256. {
  257. serv = con;
  258. networkMode = (con->connectionID == 1) ? HOST : GUEST;
  259. }
  260. for(std::map<int, PlayerSettings>::iterator it =si->playerInfos.begin();
  261. it != si->playerInfos.end(); ++it)
  262. {
  263. if((networkMode == SINGLE) //single - one client has all player
  264. || (networkMode != SINGLE && serv->connectionID == it->second.human) //multi - client has only "its players"
  265. || (networkMode == HOST && it->second.human == false)) //multi - host has all AI players
  266. {
  267. myPlayers.insert(ui8(it->first)); //add player
  268. }
  269. }
  270. if(networkMode != GUEST)
  271. myPlayers.insert(255); //neutral
  272. CStopWatch tmh;
  273. const_cast<CGameInfo*>(CGI)->state = new CGameState();
  274. tlog0 <<"\tGamestate: "<<tmh.getDiff()<<std::endl;
  275. CConnection &c(*serv);
  276. ////////////////////////////////////////////////////
  277. if(networkMode == SINGLE)
  278. {
  279. ui8 pom8;
  280. c << ui8(2) << ui8(1); //new game; one client
  281. c << *si;
  282. c >> pom8;
  283. if(pom8)
  284. throw std::runtime_error("Server cannot open the map!");
  285. else
  286. tlog0 << "Server opened map properly.\n";
  287. }
  288. c << myPlayers;
  289. c >> si;
  290. tlog0 <<"\tSending/Getting info to/from the server: "<<tmh.getDiff()<<std::endl;
  291. gs = const_cast<CGameInfo*>(CGI)->state;
  292. gs->scenarioOps = si;
  293. gs->init(si);
  294. tlog0 <<"Initializing GameState (together): "<<tmh.getDiff()<<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.getDiff()<<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.getDiff()<<std::endl;
  303. }
  304. int humanPlayers = 0;
  305. int sensibleAILimit = settings["session"]["oneGoodAI"].Bool() ? 1 : GameConstants::PLAYER_LIMIT;
  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. auto cb = make_shared<CCallback>(gs,color,this);
  316. if(!it->second.human)
  317. {
  318. std::string AItoGive = settings["server"]["playerAI"].String();
  319. if(!sensibleAILimit)
  320. AItoGive = "EmptyAI";
  321. else
  322. sensibleAILimit--;
  323. playerint[color] = static_cast<CGameInterface*>(CDynLibHandler::getNewAI(AItoGive));
  324. tlog1 << "Player " << (int)color << " will be lead by " << AItoGive << std::endl;
  325. }
  326. else
  327. {
  328. playerint[color] = new CPlayerInterface(color);
  329. humanPlayers++;
  330. }
  331. battleints[color] = playerint[color];
  332. playerint[color]->init(cb.get());
  333. callbacks[color] = cb;
  334. }
  335. else
  336. {
  337. CBattleCallback * cbc = new CBattleCallback(gs, color, this);
  338. battleints[color] = CDynLibHandler::getNewBattleAI("StupidAI");
  339. battleints[color]->init(cbc);
  340. }
  341. }
  342. if(si->mode == StartInfo::DUEL)
  343. {
  344. boost::unique_lock<boost::recursive_mutex> un(*LOCPLINT->pim);
  345. CPlayerInterface *p = new CPlayerInterface(-1);
  346. p->observerInDuelMode = true;
  347. battleints[254] = playerint[254] = p;
  348. privilagedBattleEventReceivers.push_back(p);
  349. GH.curInt = p;
  350. p->init(new CCallback(gs, -1, this));
  351. battleStarted(gs->curB);
  352. }
  353. else
  354. {
  355. loadNeutralBattleAI();
  356. }
  357. serv->addStdVecItems(const_cast<CGameInfo*>(CGI)->state);
  358. hotSeat = (humanPlayers > 1);
  359. // std::vector<FileInfo> scriptModules;
  360. // CFileUtility::getFilesWithExt(scriptModules, LIB_DIR "/Scripting", "." LIB_EXT);
  361. // BOOST_FOREACH(FileInfo &m, scriptModules)
  362. // {
  363. // CScriptingModule * nm = CDynLibHandler::getNewScriptingModule(m.name);
  364. // privilagedGameEventReceivers.push_back(nm);
  365. // privilagedBattleEventReceivers.push_back(nm);
  366. // nm->giveActionCB(this);
  367. // nm->giveInfoCB(this);
  368. // nm->init();
  369. //
  370. // erm = nm; //something tells me that there'll at most one module and it'll be ERM
  371. // }
  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. CGameInterface *nInt = NULL;
  397. if(dllname.length())
  398. {
  399. if(pid == 255)
  400. {
  401. //CBattleCallback * cbc = new CBattleCallback(gs, pid, this);//FIXME: unused?
  402. CBattleGameInterface *cbgi = CDynLibHandler::getNewBattleAI(dllname);
  403. battleints[pid] = cbgi;
  404. cbgi->init(cb);
  405. //TODO? consider serialization
  406. continue;
  407. }
  408. else
  409. nInt = CDynLibHandler::getNewAI(dllname);
  410. }
  411. else
  412. nInt = new CPlayerInterface(pid);
  413. callbacks[pid] = make_shared<CCallback>(gs,pid,this);
  414. battleints[pid] = playerint[pid] = nInt;
  415. nInt->init(callbacks[pid].get());
  416. nInt->serialize(h, version);
  417. }
  418. if(!vstd::contains(battleints, GameConstants::NEUTRAL_PLAYER))
  419. loadNeutralBattleAI();
  420. }
  421. }
  422. void CClient::handlePack( CPack * pack )
  423. {
  424. CBaseForCLApply *apply = applier->apps[typeList.getTypeID(pack)]; //find the applier
  425. if(apply)
  426. {
  427. boost::unique_lock<boost::recursive_mutex> guiLock(*LOCPLINT->pim);
  428. apply->applyOnClBefore(this,pack);
  429. tlog5 << "\tMade first apply on cl\n";
  430. gs->apply(pack);
  431. tlog5 << "\tApplied on gs\n";
  432. apply->applyOnClAfter(this,pack);
  433. tlog5 << "\tMade second apply on cl\n";
  434. }
  435. else
  436. {
  437. tlog1 << "Message cannot be applied, cannot find applier! TypeID " << typeList.getTypeID(pack) << std::endl;
  438. }
  439. delete pack;
  440. }
  441. void CClient::updatePaths()
  442. {
  443. //TODO? lazy evaluation? paths now can get recalculated multiple times upon various game events
  444. const CGHeroInstance *h = getSelectedHero();
  445. if (h)//if we have selected hero...
  446. calculatePaths(h);
  447. }
  448. void CClient::finishCampaign( CCampaignState * camp )
  449. {
  450. }
  451. void CClient::proposeNextMission( CCampaignState * camp )
  452. {
  453. GH.pushInt(new CBonusSelection(camp));
  454. GH.curInt = CGP;
  455. }
  456. void CClient::stopConnection()
  457. {
  458. terminate = true;
  459. if (serv) //request closing connection
  460. {
  461. tlog0 << "Connection has been requested to be closed.\n";
  462. boost::unique_lock<boost::mutex>(*serv->wmx);
  463. CloseServer close_server;
  464. sendRequest(&close_server, 255);
  465. tlog0 << "Sent closing signal to the server\n";
  466. }
  467. if(connectionHandler)//end connection handler
  468. {
  469. if(connectionHandler->get_id() != boost::this_thread::get_id())
  470. connectionHandler->join();
  471. tlog0 << "Connection handler thread joined" << std::endl;
  472. delete connectionHandler;
  473. connectionHandler = NULL;
  474. }
  475. if (serv) //and delete connection
  476. {
  477. serv->close();
  478. delete serv;
  479. serv = NULL;
  480. tlog3 << "Our socket has been closed." << std::endl;
  481. }
  482. }
  483. void CClient::battleStarted(const BattleInfo * info)
  484. {
  485. CPlayerInterface * att, * def;
  486. if(vstd::contains(playerint, info->sides[0]) && playerint[info->sides[0]]->human)
  487. att = static_cast<CPlayerInterface*>( playerint[info->sides[0]] );
  488. else
  489. att = NULL;
  490. if(vstd::contains(playerint, info->sides[1]) && playerint[info->sides[1]]->human)
  491. def = static_cast<CPlayerInterface*>( playerint[info->sides[1]] );
  492. else
  493. def = NULL;
  494. if(att || def || gs->scenarioOps->mode == StartInfo::DUEL)
  495. {
  496. boost::unique_lock<boost::recursive_mutex> un(*LOCPLINT->pim);
  497. new CBattleInterface(info->belligerents[0], info->belligerents[1], info->heroes[0], info->heroes[1],
  498. Rect((screen->w - 800)/2,
  499. (screen->h - 600)/2, 800, 600), att, def);
  500. }
  501. if(vstd::contains(battleints,info->sides[0]))
  502. battleints[info->sides[0]]->battleStart(info->belligerents[0], info->belligerents[1], info->tile, info->heroes[0], info->heroes[1], 0);
  503. if(vstd::contains(battleints,info->sides[1]))
  504. battleints[info->sides[1]]->battleStart(info->belligerents[0], info->belligerents[1], info->tile, info->heroes[0], info->heroes[1], 1);
  505. if(vstd::contains(battleints,254))
  506. battleints[254]->battleStart(info->belligerents[0], info->belligerents[1], info->tile, info->heroes[0], info->heroes[1], 1);
  507. if(info->tacticDistance && vstd::contains(battleints,info->sides[info->tacticsSide]))
  508. {
  509. boost::thread(&CClient::commenceTacticPhaseForInt, this, battleints[info->sides[info->tacticsSide]]);
  510. }
  511. }
  512. void CClient::loadNeutralBattleAI()
  513. {
  514. battleints[255] = CDynLibHandler::getNewBattleAI(settings["server"]["neutralAI"].String());
  515. battleints[255]->init(new CBattleCallback(gs, 255, this));
  516. }
  517. void CClient::commitPackage( CPackForClient *pack )
  518. {
  519. CommitPackage cp;
  520. cp.freePack = false;
  521. cp.packToCommit = pack;
  522. sendRequest(&cp, 255);
  523. }
  524. int CClient::getLocalPlayer() const
  525. {
  526. if(LOCPLINT)
  527. return LOCPLINT->playerID;
  528. return getCurrentPlayer();
  529. }
  530. void CClient::calculatePaths(const CGHeroInstance *h)
  531. {
  532. assert(h);
  533. boost::unique_lock<boost::mutex> pathLock(pathMx);
  534. gs->calculatePaths(h, *pathInfo);
  535. }
  536. void CClient::commenceTacticPhaseForInt(CBattleGameInterface *battleInt)
  537. {
  538. setThreadName("CClient::commenceTacticPhaseForInt");
  539. try
  540. {
  541. battleInt->yourTacticPhase(gs->curB->tacticDistance);
  542. if(gs && !!gs->curB && gs->curB->tacticDistance) //while awaiting for end of tactics phase, many things can happen (end of battle... or game)
  543. {
  544. MakeAction ma(BattleAction::makeEndOFTacticPhase(battleInt->playerID));
  545. sendRequest(&ma, battleInt->playerID);
  546. }
  547. } HANDLE_EXCEPTION
  548. }
  549. void CClient::invalidatePaths(const CGHeroInstance *h /*= NULL*/)
  550. {
  551. if(!h || pathInfo->hero == h)
  552. pathInfo->isValid = false;
  553. }
  554. int CClient::sendRequest(const CPack *request, int player)
  555. {
  556. static ui32 requestCounter = 0;
  557. ui32 requestID = requestCounter++;
  558. tlog5 << boost::format("Sending a request \"%s\". It'll have an ID=%d.\n")
  559. % typeid(*request).name() % requestID;
  560. waitingRequest.pushBack(requestID);
  561. serv->sendPackToServer(*request, player, requestID);
  562. if(vstd::contains(playerint, player))
  563. playerint[player]->requestSent(dynamic_cast<const CPackForServer*>(request), requestID);
  564. return requestID;
  565. }
  566. template void CClient::serialize( CISer<CLoadFile> &h, const int version );
  567. template void CClient::serialize( COSer<CSaveFile> &h, const int version );
  568. void CServerHandler::startServer()
  569. {
  570. th.update();
  571. serverThread = new boost::thread(&CServerHandler::callServer, this); //runs server executable;
  572. if(verbose)
  573. tlog0 << "Setting up thread calling server: " << th.getDiff() << std::endl;
  574. }
  575. void CServerHandler::waitForServer()
  576. {
  577. if(!serverThread)
  578. startServer();
  579. th.update();
  580. intpr::scoped_lock<intpr::interprocess_mutex> slock(shared->sr->mutex);
  581. while(!shared->sr->ready)
  582. {
  583. shared->sr->cond.wait(slock);
  584. }
  585. if(verbose)
  586. tlog0 << "Waiting for server: " << th.getDiff() << std::endl;
  587. }
  588. CConnection * CServerHandler::connectToServer()
  589. {
  590. if(!shared->sr->ready)
  591. waitForServer();
  592. th.update();
  593. CConnection *ret = justConnectToServer(settings["server"]["server"].String(), port);
  594. if(verbose)
  595. tlog0<<"\tConnecting to the server: "<<th.getDiff()<<std::endl;
  596. return ret;
  597. }
  598. CServerHandler::CServerHandler(bool runServer /*= false*/)
  599. {
  600. serverThread = NULL;
  601. shared = NULL;
  602. port = boost::lexical_cast<std::string>(settings["server"]["port"].Float());
  603. verbose = false;
  604. 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
  605. try
  606. {
  607. shared = new SharedMem();
  608. } HANDLE_EXCEPTIONC(tlog1 << "Cannot open interprocess memory: ";)
  609. }
  610. CServerHandler::~CServerHandler()
  611. {
  612. delete shared;
  613. delete serverThread; //detaches, not kills thread
  614. }
  615. void CServerHandler::callServer()
  616. {
  617. setThreadName("CServerHandler::callServer");
  618. std::string logName = GVCMIDirs.UserPath + "/server_log.txt";
  619. std::string comm = GameConstants::BIN_DIR + GameConstants::PATH_SEPARATOR + GameConstants::SERVER_NAME + " " + port + " > " + logName;
  620. int result = std::system(comm.c_str());
  621. if (result == 0)
  622. tlog1 << "Server closed correctly\n";
  623. else
  624. tlog0 << "Error: server failed to close correctly or crashed!\n";
  625. }
  626. CConnection * CServerHandler::justConnectToServer(const std::string &host, const std::string &port)
  627. {
  628. CConnection *ret = NULL;
  629. while(!ret)
  630. {
  631. try
  632. {
  633. tlog0 << "Establishing connection...\n";
  634. ret = new CConnection( host.size() ? host : settings["server"]["server"].String(),
  635. port.size() ? port : boost::lexical_cast<std::string>(settings["server"]["port"].Float()),
  636. NAME);
  637. }
  638. catch(...)
  639. {
  640. tlog1 << "\nCannot establish connection! Retrying within 2 seconds" << std::endl;
  641. SDL_Delay(2000);
  642. }
  643. }
  644. return ret;
  645. }