2
0

Client.cpp 25 KB

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