Client.cpp 26 KB

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