Client.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878
  1. #include "StdInc.h"
  2. #include "CMusicHandler.h"
  3. #include "../lib/mapping/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/CModHandler.h"
  12. #include "../lib/CArtHandler.h"
  13. #include "../lib/CDefObjInfoHandler.h"
  14. #include "../lib/CGeneralTextHandler.h"
  15. #include "../lib/CHeroHandler.h"
  16. #include "../lib/CTownHandler.h"
  17. #include "../lib/CObjectHandler.h"
  18. #include "../lib/CBuildingHandler.h"
  19. #include "../lib/CSpellHandler.h"
  20. #include "../lib/Connection.h"
  21. #include "../lib/Interprocess.h"
  22. #include "../lib/NetPacks.h"
  23. #include "../lib/VCMI_Lib.h"
  24. #include "../lib/VCMIDirs.h"
  25. #include "../lib/mapping/CMap.h"
  26. #include "../lib/JsonNode.h"
  27. #include "mapHandler.h"
  28. #include "../lib/CConfigHandler.h"
  29. #include "Client.h"
  30. #include "CPreGame.h"
  31. #include "battle/CBattleInterface.h"
  32. #include "../lib/CThreadHelper.h"
  33. #include "../lib/CScriptingModule.h"
  34. #include "../lib/RegisterTypes.h"
  35. #include "gui/CGuiHandler.h"
  36. #include "CMT.h"
  37. extern std::string NAME;
  38. namespace intpr = boost::interprocess;
  39. /*
  40. * Client.cpp, part of VCMI engine
  41. *
  42. * Authors: listed in file AUTHORS in main folder
  43. *
  44. * License: GNU General Public License v2.0 or later
  45. * Full text of license available in license.txt file, in main folder
  46. *
  47. */
  48. template <typename T> class CApplyOnCL;
  49. class CBaseForCLApply
  50. {
  51. public:
  52. virtual void applyOnClAfter(CClient *cl, void *pack) const =0;
  53. virtual void applyOnClBefore(CClient *cl, void *pack) const =0;
  54. virtual ~CBaseForCLApply(){}
  55. template<typename U> static CBaseForCLApply *getApplier(const U * t=nullptr)
  56. {
  57. return new CApplyOnCL<U>;
  58. }
  59. };
  60. template <typename T> class CApplyOnCL : public CBaseForCLApply
  61. {
  62. public:
  63. void applyOnClAfter(CClient *cl, void *pack) const
  64. {
  65. T *ptr = static_cast<T*>(pack);
  66. ptr->applyCl(cl);
  67. }
  68. void applyOnClBefore(CClient *cl, void *pack) const
  69. {
  70. T *ptr = static_cast<T*>(pack);
  71. ptr->applyFirstCl(cl);
  72. }
  73. };
  74. static CApplier<CBaseForCLApply> *applier = nullptr;
  75. void CClient::init()
  76. {
  77. hotSeat = false;
  78. connectionHandler = nullptr;
  79. pathInfo = nullptr;
  80. applier = new CApplier<CBaseForCLApply>;
  81. registerTypes2(*applier);
  82. IObjectInterface::cb = this;
  83. serv = nullptr;
  84. gs = nullptr;
  85. erm = nullptr;
  86. terminate = false;
  87. }
  88. CClient::CClient(void)
  89. {
  90. init();
  91. }
  92. CClient::CClient(CConnection *con, StartInfo *si)
  93. {
  94. init();
  95. newGame(con,si);
  96. }
  97. CClient::~CClient(void)
  98. {
  99. delete applier;
  100. }
  101. void CClient::waitForMoveAndSend(PlayerColor color)
  102. {
  103. try
  104. {
  105. setThreadName("CClient::waitForMoveAndSend");
  106. assert(vstd::contains(battleints, color));
  107. BattleAction ba = battleints[color]->activeStack(gs->curB->battleGetStackByID(gs->curB->activeStack, false));
  108. MakeAction temp_action(ba);
  109. sendRequest(&temp_action, color);
  110. return;
  111. }
  112. catch(boost::thread_interrupted&)
  113. {
  114. logNetwork->debugStream() << "Wait for move thread was interrupted and no action will be send. Was a battle ended by spell?";
  115. return;
  116. }
  117. HANDLE_EXCEPTION
  118. logNetwork->errorStream() << "We should not be here!";
  119. }
  120. void CClient::run()
  121. {
  122. setThreadName("CClient::run");
  123. try
  124. {
  125. CPack *pack = nullptr;
  126. while(!terminate)
  127. {
  128. pack = serv->retreivePack(); //get the package from the server
  129. if (terminate)
  130. {
  131. delete pack;
  132. pack = nullptr;
  133. break;
  134. }
  135. handlePack(pack);
  136. pack = nullptr;
  137. }
  138. }
  139. //catch only asio exceptions
  140. catch (const boost::system::system_error& e)
  141. {
  142. logNetwork->errorStream() << "Lost connection to server, ending listening thread!";
  143. logNetwork->errorStream() << e.what();
  144. if(!terminate) //rethrow (-> boom!) only if closing connection was unexpected
  145. {
  146. logNetwork->errorStream() << "Something wrong, lost connection while game is still ongoing...";
  147. throw;
  148. }
  149. }
  150. }
  151. void CClient::save(const std::string & fname)
  152. {
  153. if(gs->curB)
  154. {
  155. logNetwork->errorStream() << "Game cannot be saved during battle!";
  156. return;
  157. }
  158. SaveGame save_game(fname);
  159. sendRequest((CPackForClient*)&save_game, PlayerColor::NEUTRAL);
  160. }
  161. void CClient::endGame( bool closeConnection /*= true*/ )
  162. {
  163. //suggest interfaces to finish their stuff (AI should interrupt any bg working threads)
  164. for(auto i : playerint)
  165. i.second->finish();
  166. // Game is ending
  167. // Tell the network thread to reach a stable state
  168. if(closeConnection)
  169. stopConnection();
  170. logNetwork->infoStream() << "Closed connection.";
  171. GH.curInt = nullptr;
  172. {
  173. boost::unique_lock<boost::recursive_mutex> un(*LOCPLINT->pim);
  174. logNetwork->infoStream() << "Ending current game!";
  175. if(GH.topInt())
  176. GH.topInt()->deactivate();
  177. GH.listInt.clear();
  178. GH.objsToBlit.clear();
  179. GH.statusbar = nullptr;
  180. logNetwork->infoStream() << "Removed GUI.";
  181. vstd::clear_pointer(const_cast<CGameInfo*>(CGI)->mh);
  182. vstd::clear_pointer(gs);
  183. logNetwork->infoStream() << "Deleted mapHandler and gameState.";
  184. LOCPLINT = nullptr;
  185. }
  186. playerint.clear();
  187. callbacks.clear();
  188. battleCallbacks.clear();
  189. logNetwork->infoStream() << "Deleted playerInts.";
  190. logNetwork->infoStream() << "Client stopped.";
  191. }
  192. void CClient::loadGame( const std::string & fname )
  193. {
  194. logNetwork->infoStream() <<"Loading procedure started!";
  195. CServerHandler sh;
  196. sh.startServer();
  197. CStopWatch tmh;
  198. try
  199. {
  200. std::string clientSaveName = *CResourceHandler::get()->getResourceName(ResourceID(fname, EResType::CLIENT_SAVEGAME));
  201. std::string controlServerSaveName;
  202. if (CResourceHandler::get()->existsResource(ResourceID(fname, EResType::SERVER_SAVEGAME)))
  203. {
  204. controlServerSaveName = *CResourceHandler::get()->getResourceName(ResourceID(fname, EResType::SERVER_SAVEGAME));
  205. }
  206. else// create entry for server savegame. Triggered if save was made after launch and not yet present in res handler
  207. {
  208. controlServerSaveName = clientSaveName.substr(0, clientSaveName.find_last_of(".")) + ".vsgm1";
  209. CResourceHandler::get()->createResource(controlServerSaveName, true);
  210. }
  211. if(clientSaveName.empty())
  212. throw std::runtime_error("Cannot open client part of " + fname);
  213. if(controlServerSaveName.empty())
  214. throw std::runtime_error("Cannot open server part of " + fname);
  215. unique_ptr<CLoadFile> loader;
  216. {
  217. CLoadIntegrityValidator checkingLoader(clientSaveName, controlServerSaveName);
  218. loadCommonState(checkingLoader);
  219. loader = checkingLoader.decay();
  220. }
  221. logNetwork->infoStream() << "Loaded common part of save " << tmh.getDiff();
  222. const_cast<CGameInfo*>(CGI)->mh = new CMapHandler();
  223. const_cast<CGameInfo*>(CGI)->mh->map = gs->map;
  224. pathInfo = make_unique<CPathsInfo>(getMapSize());
  225. CGI->mh->init();
  226. logNetwork->infoStream() <<"Initing maphandler: "<<tmh.getDiff();
  227. *loader >> *this;
  228. logNetwork->infoStream() << "Loaded client part of save " << tmh.getDiff();
  229. }
  230. catch(std::exception &e)
  231. {
  232. logGlobal->errorStream() << "Cannot load game " << fname << ". Error: " << e.what();
  233. throw; //obviously we cannot continue here
  234. }
  235. serv = sh.connectToServer();
  236. serv->addStdVecItems(gs);
  237. tmh.update();
  238. ui8 pom8;
  239. *serv << ui8(3) << ui8(1); //load game; one client
  240. *serv << fname;
  241. *serv >> pom8;
  242. if(pom8)
  243. throw std::runtime_error("Server cannot open the savegame!");
  244. else
  245. logNetwork->infoStream() << "Server opened savegame properly.";
  246. *serv << ui32(gs->scenarioOps->playerInfos.size()+1); //number of players + neutral
  247. for(auto & elem : gs->scenarioOps->playerInfos)
  248. {
  249. *serv << ui8(elem.first.getNum()); //players
  250. }
  251. *serv << ui8(PlayerColor::NEUTRAL.getNum());
  252. logNetwork->infoStream() <<"Sent info to server: "<<tmh.getDiff();
  253. serv->enableStackSendingByID();
  254. serv->disableSmartPointerSerialization();
  255. // logGlobal->traceStream() << "Objects:";
  256. // for(int i = 0; i < gs->map->objects.size(); i++)
  257. // {
  258. // auto o = gs->map->objects[i];
  259. // if(o)
  260. // logGlobal->traceStream() << boost::format("\tindex=%5d, id=%5d; address=%5d, pos=%s, name=%s") % i % o->id % (int)o.get() % o->pos % o->getHoverText();
  261. // else
  262. // logGlobal->traceStream() << boost::format("\tindex=%5d --- nullptr") % i;
  263. // }
  264. }
  265. void CClient::newGame( CConnection *con, StartInfo *si )
  266. {
  267. enum {SINGLE, HOST, GUEST} networkMode = SINGLE;
  268. if (con == nullptr)
  269. {
  270. CServerHandler sh;
  271. serv = sh.connectToServer();
  272. }
  273. else
  274. {
  275. serv = con;
  276. networkMode = (con->connectionID == 1) ? HOST : GUEST;
  277. }
  278. CConnection &c = *serv;
  279. ////////////////////////////////////////////////////
  280. logNetwork->infoStream() <<"\tWill send info to server...";
  281. CStopWatch tmh;
  282. if(networkMode == SINGLE)
  283. {
  284. ui8 pom8;
  285. c << ui8(2) << ui8(1); //new game; one client
  286. c << *si;
  287. c >> pom8;
  288. if(pom8)
  289. throw std::runtime_error("Server cannot open the map!");
  290. else
  291. logNetwork->infoStream() << "Server opened map properly.";
  292. }
  293. c >> si;
  294. logNetwork->infoStream() <<"\tSending/Getting info to/from the server: "<<tmh.getDiff();
  295. c.enableStackSendingByID();
  296. c.disableSmartPointerSerialization();
  297. // Initialize game state
  298. gs = new CGameState();
  299. logNetwork->infoStream() <<"\tCreating gamestate: "<<tmh.getDiff();
  300. gs->scenarioOps = si;
  301. gs->init(si);
  302. logNetwork->infoStream() <<"Initializing GameState (together): "<<tmh.getDiff();
  303. // Now after possible random map gen, we know exact player count.
  304. // Inform server about how many players client handles
  305. std::set<PlayerColor> myPlayers;
  306. for(auto & elem : gs->scenarioOps->playerInfos)
  307. {
  308. if((networkMode == SINGLE) //single - one client has all player
  309. || (networkMode != SINGLE && serv->connectionID == elem.second.playerID) //multi - client has only "its players"
  310. || (networkMode == HOST && elem.second.playerID == PlayerSettings::PLAYER_AI))//multi - host has all AI players
  311. {
  312. myPlayers.insert(elem.first); //add player
  313. }
  314. }
  315. if(networkMode != GUEST)
  316. myPlayers.insert(PlayerColor::NEUTRAL);
  317. c << myPlayers;
  318. // Init map handler
  319. if(gs->map)
  320. {
  321. const_cast<CGameInfo*>(CGI)->mh = new CMapHandler();
  322. CGI->mh->map = gs->map;
  323. logNetwork->infoStream() <<"Creating mapHandler: "<<tmh.getDiff();
  324. CGI->mh->init();
  325. pathInfo = make_unique<CPathsInfo>(getMapSize());
  326. logNetwork->infoStream() <<"Initializing mapHandler (together): "<<tmh.getDiff();
  327. }
  328. int humanPlayers = 0;
  329. for(auto & elem : gs->scenarioOps->playerInfos)//initializing interfaces for players
  330. {
  331. PlayerColor color = elem.first;
  332. gs->currentPlayer = color;
  333. if(!vstd::contains(myPlayers, color))
  334. continue;
  335. logNetwork->traceStream() << "Preparing interface for player " << color;
  336. if(si->mode != StartInfo::DUEL)
  337. {
  338. if(elem.second.playerID == PlayerSettings::PLAYER_AI)
  339. {
  340. auto AiToGive = aiNameForPlayer(elem.second, false);
  341. logNetwork->infoStream() << boost::format("Player %s will be lead by %s") % color % AiToGive;
  342. installNewPlayerInterface(CDynLibHandler::getNewAI(AiToGive), color);
  343. }
  344. else
  345. {
  346. installNewPlayerInterface(make_shared<CPlayerInterface>(color), color);
  347. humanPlayers++;
  348. }
  349. }
  350. else
  351. {
  352. std::string AItoGive = aiNameForPlayer(elem.second, true);
  353. installNewBattleInterface(CDynLibHandler::getNewBattleAI(AItoGive), color);
  354. }
  355. }
  356. if(si->mode == StartInfo::DUEL)
  357. {
  358. if(!gNoGUI)
  359. {
  360. boost::unique_lock<boost::recursive_mutex> un(*LOCPLINT->pim);
  361. auto p = make_shared<CPlayerInterface>(PlayerColor::NEUTRAL);
  362. p->observerInDuelMode = true;
  363. installNewPlayerInterface(p, boost::none);
  364. GH.curInt = p.get();
  365. }
  366. battleStarted(gs->curB);
  367. }
  368. else
  369. {
  370. loadNeutralBattleAI();
  371. }
  372. serv->addStdVecItems(gs);
  373. hotSeat = (humanPlayers > 1);
  374. // std::vector<FileInfo> scriptModules;
  375. // CFileUtility::getFilesWithExt(scriptModules, LIB_DIR "/scripting", "." LIB_EXT);
  376. // for(FileInfo &m : scriptModules)
  377. // {
  378. // CScriptingModule * nm = CDynLibHandler::getNewScriptingModule(m.name);
  379. // privilagedGameEventReceivers.push_back(nm);
  380. // privilagedBattleEventReceivers.push_back(nm);
  381. // nm->giveActionCB(this);
  382. // nm->giveInfoCB(this);
  383. // nm->init();
  384. //
  385. // erm = nm; //something tells me that there'll at most one module and it'll be ERM
  386. // }
  387. }
  388. template <typename Handler>
  389. void CClient::serialize( Handler &h, const int version )
  390. {
  391. h & hotSeat;
  392. if(h.saving)
  393. {
  394. ui8 players = playerint.size();
  395. h & players;
  396. for(auto i = playerint.begin(); i != playerint.end(); i++)
  397. {
  398. LOG_TRACE_PARAMS(logGlobal, "Saving player %s interface", i->first);
  399. assert(i->first == i->second->playerID);
  400. h & i->first & i->second->dllName & i->second->human;
  401. i->second->saveGame(dynamic_cast<COSer<CSaveFile>&>(h), version);
  402. //evil cast that i still like better than sfinae-magic. If I had a "static if"...
  403. }
  404. }
  405. else
  406. {
  407. ui8 players = 0; //fix for uninitialized warning
  408. h & players;
  409. for(int i=0; i < players; i++)
  410. {
  411. std::string dllname;
  412. PlayerColor pid;
  413. bool isHuman = false;
  414. h & pid & dllname & isHuman;
  415. LOG_TRACE_PARAMS(logGlobal, "Loading player %s interface", pid);
  416. shared_ptr<CGameInterface> nInt;
  417. if(dllname.length())
  418. {
  419. if(pid == PlayerColor::NEUTRAL)
  420. {
  421. installNewBattleInterface(CDynLibHandler::getNewBattleAI(dllname), pid);
  422. //TODO? consider serialization
  423. continue;
  424. }
  425. else
  426. {
  427. assert(!isHuman);
  428. nInt = CDynLibHandler::getNewAI(dllname);
  429. }
  430. }
  431. else
  432. {
  433. assert(isHuman);
  434. nInt = make_shared<CPlayerInterface>(pid);
  435. }
  436. nInt->dllName = dllname;
  437. nInt->human = isHuman;
  438. nInt->playerID = pid;
  439. installNewPlayerInterface(nInt, pid);
  440. nInt->loadGame(dynamic_cast<CISer<CLoadFile>&>(h), version); //another evil cast, check above
  441. }
  442. if(!vstd::contains(battleints, PlayerColor::NEUTRAL))
  443. loadNeutralBattleAI();
  444. }
  445. }
  446. void CClient::handlePack( CPack * pack )
  447. {
  448. CBaseForCLApply *apply = applier->apps[typeList.getTypeID(pack)]; //find the applier
  449. if(apply)
  450. {
  451. boost::unique_lock<boost::recursive_mutex> guiLock(*LOCPLINT->pim);
  452. apply->applyOnClBefore(this,pack);
  453. logNetwork->traceStream() << "\tMade first apply on cl";
  454. gs->apply(pack);
  455. logNetwork->traceStream() << "\tApplied on gs";
  456. apply->applyOnClAfter(this,pack);
  457. logNetwork->traceStream() << "\tMade second apply on cl";
  458. }
  459. else
  460. {
  461. logNetwork->errorStream() << "Message cannot be applied, cannot find applier! TypeID " << typeList.getTypeID(pack);
  462. }
  463. delete pack;
  464. }
  465. void CClient::updatePaths()
  466. {
  467. //TODO? lazy evaluation? paths now can get recalculated multiple times upon various game events
  468. const CGHeroInstance *h = getSelectedHero();
  469. if (h)//if we have selected hero...
  470. calculatePaths(h);
  471. }
  472. void CClient::finishCampaign( shared_ptr<CCampaignState> camp )
  473. {
  474. }
  475. void CClient::proposeNextMission(shared_ptr<CCampaignState> camp)
  476. {
  477. GH.pushInt(new CBonusSelection(camp));
  478. }
  479. void CClient::stopConnection()
  480. {
  481. terminate = true;
  482. if (serv) //request closing connection
  483. {
  484. logNetwork->infoStream() << "Connection has been requested to be closed.";
  485. boost::unique_lock<boost::mutex>(*serv->wmx);
  486. CloseServer close_server;
  487. sendRequest(&close_server, PlayerColor::NEUTRAL);
  488. logNetwork->infoStream() << "Sent closing signal to the server";
  489. }
  490. if(connectionHandler)//end connection handler
  491. {
  492. if(connectionHandler->get_id() != boost::this_thread::get_id())
  493. connectionHandler->join();
  494. logNetwork->infoStream() << "Connection handler thread joined";
  495. delete connectionHandler;
  496. connectionHandler = nullptr;
  497. }
  498. if (serv) //and delete connection
  499. {
  500. serv->close();
  501. delete serv;
  502. serv = nullptr;
  503. logNetwork->warnStream() << "Our socket has been closed.";
  504. }
  505. }
  506. void CClient::battleStarted(const BattleInfo * info)
  507. {
  508. for(auto &battleCb : battleCallbacks)
  509. {
  510. if(vstd::contains_if(info->sides, [&](const SideInBattle& side) {return side.color == battleCb.first; })
  511. || battleCb.first >= PlayerColor::PLAYER_LIMIT)
  512. {
  513. battleCb.second->setBattle(info);
  514. }
  515. }
  516. // for(ui8 side : info->sides)
  517. // if(battleCallbacks.count(side))
  518. // battleCallbacks[side]->setBattle(info);
  519. shared_ptr<CPlayerInterface> att, def;
  520. auto &leftSide = info->sides[0], &rightSide = info->sides[1];
  521. //If quick combat is not, do not prepare interfaces for battleint
  522. if(!settings["adventure"]["quickCombat"].Bool())
  523. {
  524. if(vstd::contains(playerint, leftSide.color) && playerint[leftSide.color]->human)
  525. att = std::dynamic_pointer_cast<CPlayerInterface>( playerint[leftSide.color] );
  526. if(vstd::contains(playerint, rightSide.color) && playerint[rightSide.color]->human)
  527. def = std::dynamic_pointer_cast<CPlayerInterface>( playerint[rightSide.color] );
  528. }
  529. if(!gNoGUI && (!!att || !!def || gs->scenarioOps->mode == StartInfo::DUEL))
  530. {
  531. boost::unique_lock<boost::recursive_mutex> un(*LOCPLINT->pim);
  532. auto bi = new CBattleInterface(leftSide.armyObject, rightSide.armyObject, leftSide.hero, rightSide.hero,
  533. Rect((screen->w - 800)/2,
  534. (screen->h - 600)/2, 800, 600), att, def);
  535. GH.pushInt(bi);
  536. }
  537. auto callBattleStart = [&](PlayerColor color, ui8 side){
  538. if(vstd::contains(battleints, color))
  539. battleints[color]->battleStart(leftSide.armyObject, rightSide.armyObject, info->tile, leftSide.hero, rightSide.hero, side);
  540. };
  541. callBattleStart(leftSide.color, 0);
  542. callBattleStart(rightSide.color, 1);
  543. callBattleStart(PlayerColor::UNFLAGGABLE, 1);
  544. if(info->tacticDistance && vstd::contains(battleints,info->sides[info->tacticsSide].color))
  545. {
  546. boost::thread(&CClient::commenceTacticPhaseForInt, this, battleints[info->sides[info->tacticsSide].color]);
  547. }
  548. }
  549. void CClient::battleFinished()
  550. {
  551. for(auto & side : gs->curB->sides)
  552. if(battleCallbacks.count(side.color))
  553. battleCallbacks[side.color]->setBattle(nullptr);
  554. }
  555. void CClient::loadNeutralBattleAI()
  556. {
  557. installNewBattleInterface(CDynLibHandler::getNewBattleAI(settings["server"]["neutralAI"].String()), PlayerColor::NEUTRAL);
  558. }
  559. void CClient::commitPackage( CPackForClient *pack )
  560. {
  561. CommitPackage cp;
  562. cp.freePack = false;
  563. cp.packToCommit = pack;
  564. sendRequest(&cp, PlayerColor::NEUTRAL);
  565. }
  566. PlayerColor CClient::getLocalPlayer() const
  567. {
  568. if(LOCPLINT)
  569. return LOCPLINT->playerID;
  570. return getCurrentPlayer();
  571. }
  572. void CClient::calculatePaths(const CGHeroInstance *h)
  573. {
  574. assert(h);
  575. boost::unique_lock<boost::mutex> pathLock(pathMx);
  576. gs->calculatePaths(h, *pathInfo);
  577. }
  578. void CClient::commenceTacticPhaseForInt(shared_ptr<CBattleGameInterface> battleInt)
  579. {
  580. setThreadName("CClient::commenceTacticPhaseForInt");
  581. try
  582. {
  583. battleInt->yourTacticPhase(gs->curB->tacticDistance);
  584. if(gs && !!gs->curB && gs->curB->tacticDistance) //while awaiting for end of tactics phase, many things can happen (end of battle... or game)
  585. {
  586. MakeAction ma(BattleAction::makeEndOFTacticPhase(gs->curB->playerToSide(battleInt->playerID)));
  587. sendRequest(&ma, battleInt->playerID);
  588. }
  589. } HANDLE_EXCEPTION
  590. }
  591. void CClient::invalidatePaths(const CGHeroInstance *h /*= nullptr*/)
  592. {
  593. if(!h || pathInfo->hero == h)
  594. pathInfo->isValid = false;
  595. }
  596. int CClient::sendRequest(const CPack *request, PlayerColor player)
  597. {
  598. static ui32 requestCounter = 0;
  599. ui32 requestID = requestCounter++;
  600. logNetwork->traceStream() << boost::format("Sending a request \"%s\". It'll have an ID=%d.")
  601. % typeid(*request).name() % requestID;
  602. waitingRequest.pushBack(requestID);
  603. serv->sendPackToServer(*request, player, requestID);
  604. if(vstd::contains(playerint, player))
  605. playerint[player]->requestSent(dynamic_cast<const CPackForServer*>(request), requestID);
  606. return requestID;
  607. }
  608. void CClient::campaignMapFinished( shared_ptr<CCampaignState> camp )
  609. {
  610. endGame(false);
  611. LOCPLINT = nullptr; //TODO free res
  612. GH.curInt = CGPreGame::create();
  613. auto & epilogue = camp->camp->scenarios[camp->mapsConquered.back()].epilog;
  614. auto finisher = [&]()
  615. {
  616. if(camp->mapsRemaining.size())
  617. proposeNextMission(camp);
  618. else
  619. finishCampaign(camp);
  620. };
  621. if(epilogue.hasPrologEpilog)
  622. {
  623. GH.pushInt(new CPrologEpilogVideo(epilogue, finisher));
  624. }
  625. else
  626. {
  627. finisher();
  628. }
  629. }
  630. void CClient::installNewPlayerInterface(shared_ptr<CGameInterface> gameInterface, boost::optional<PlayerColor> color)
  631. {
  632. boost::unique_lock<boost::recursive_mutex> un(*LOCPLINT->pim);
  633. PlayerColor colorUsed = color.get_value_or(PlayerColor::UNFLAGGABLE);
  634. if(!color)
  635. privilagedGameEventReceivers.push_back(gameInterface);
  636. playerint[colorUsed] = gameInterface;
  637. logGlobal->traceStream() << boost::format("\tInitializing the interface for player %s") % colorUsed;
  638. auto cb = make_shared<CCallback>(gs, color, this);
  639. callbacks[colorUsed] = cb;
  640. battleCallbacks[colorUsed] = cb;
  641. gameInterface->init(cb);
  642. installNewBattleInterface(gameInterface, color, false);
  643. }
  644. void CClient::installNewBattleInterface(shared_ptr<CBattleGameInterface> battleInterface, boost::optional<PlayerColor> color, bool needCallback /*= true*/)
  645. {
  646. boost::unique_lock<boost::recursive_mutex> un(*LOCPLINT->pim);
  647. PlayerColor colorUsed = color.get_value_or(PlayerColor::UNFLAGGABLE);
  648. if(!color)
  649. privilagedBattleEventReceivers.push_back(battleInterface);
  650. battleints[colorUsed] = battleInterface;
  651. if(needCallback)
  652. {
  653. logGlobal->traceStream() << boost::format("\tInitializing the battle interface for player %s") % *color;
  654. auto cbc = make_shared<CBattleCallback>(gs, color, this);
  655. battleCallbacks[colorUsed] = cbc;
  656. battleInterface->init(cbc);
  657. }
  658. }
  659. std::string CClient::aiNameForPlayer(const PlayerSettings &ps, bool battleAI)
  660. {
  661. if(ps.name.size())
  662. {
  663. std::string filename = VCMIDirs::get().libraryPath() + "/AI/" + VCMIDirs::get().libraryName(ps.name);
  664. if(boost::filesystem::exists(filename))
  665. return ps.name;
  666. }
  667. const int sensibleAILimit = settings["session"]["oneGoodAI"].Bool() ? 1 : PlayerColor::PLAYER_LIMIT_I;
  668. std::string goodAI = battleAI ? settings["server"]["neutralAI"].String() : settings["server"]["playerAI"].String();
  669. std::string badAI = battleAI ? "StupidAI" : "EmptyAI";
  670. //TODO what about human players
  671. if(battleints.size() >= sensibleAILimit)
  672. return badAI;
  673. return goodAI;
  674. }
  675. template void CClient::serialize( CISer<CLoadFile> &h, const int version );
  676. template void CClient::serialize( COSer<CSaveFile> &h, const int version );
  677. void CServerHandler::startServer()
  678. {
  679. th.update();
  680. serverThread = new boost::thread(&CServerHandler::callServer, this); //runs server executable;
  681. if(verbose)
  682. logNetwork->infoStream() << "Setting up thread calling server: " << th.getDiff();
  683. }
  684. void CServerHandler::waitForServer()
  685. {
  686. if(!serverThread)
  687. startServer();
  688. th.update();
  689. intpr::scoped_lock<intpr::interprocess_mutex> slock(shared->sr->mutex);
  690. while(!shared->sr->ready)
  691. {
  692. shared->sr->cond.wait(slock);
  693. }
  694. if(verbose)
  695. logNetwork->infoStream() << "Waiting for server: " << th.getDiff();
  696. }
  697. CConnection * CServerHandler::connectToServer()
  698. {
  699. if(!shared->sr->ready)
  700. waitForServer();
  701. th.update(); //put breakpoint here to attach to server before it does something stupid
  702. CConnection *ret = justConnectToServer(settings["server"]["server"].String(), port);
  703. if(verbose)
  704. logNetwork->infoStream()<<"\tConnecting to the server: "<<th.getDiff();
  705. return ret;
  706. }
  707. CServerHandler::CServerHandler(bool runServer /*= false*/)
  708. {
  709. serverThread = nullptr;
  710. shared = nullptr;
  711. port = boost::lexical_cast<std::string>(settings["server"]["port"].Float());
  712. verbose = true;
  713. 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
  714. try
  715. {
  716. shared = new SharedMem();
  717. } HANDLE_EXCEPTIONC(logNetwork->errorStream() << "Cannot open interprocess memory: ";)
  718. }
  719. CServerHandler::~CServerHandler()
  720. {
  721. delete shared;
  722. delete serverThread; //detaches, not kills thread
  723. }
  724. void CServerHandler::callServer()
  725. {
  726. setThreadName("CServerHandler::callServer");
  727. std::string logName = VCMIDirs::get().userCachePath() + "/server_log.txt";
  728. std::string comm = VCMIDirs::get().serverPath() + " --port=" + port + " > " + logName;
  729. int result = std::system(comm.c_str());
  730. if (result == 0)
  731. logNetwork->infoStream() << "Server closed correctly";
  732. else
  733. {
  734. logNetwork->errorStream() << "Error: server failed to close correctly or crashed!";
  735. logNetwork->errorStream() << "Check " << logName << " for more info";
  736. exit(1);// exit in case of error. Othervice without working server VCMI will hang
  737. }
  738. }
  739. CConnection * CServerHandler::justConnectToServer(const std::string &host, const std::string &port)
  740. {
  741. CConnection *ret = nullptr;
  742. while(!ret)
  743. {
  744. try
  745. {
  746. logNetwork->infoStream() << "Establishing connection...";
  747. ret = new CConnection( host.size() ? host : settings["server"]["server"].String(),
  748. port.size() ? port : boost::lexical_cast<std::string>(settings["server"]["port"].Float()),
  749. NAME);
  750. }
  751. catch(...)
  752. {
  753. logNetwork->errorStream() << "\nCannot establish connection! Retrying within 2 seconds";
  754. SDL_Delay(2000);
  755. }
  756. }
  757. return ret;
  758. }