CServerHandler.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940
  1. /*
  2. * CServerHandler.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "CServerHandler.h"
  12. #include "Client.h"
  13. #include "CGameInfo.h"
  14. #include "ServerRunner.h"
  15. #include "CPlayerInterface.h"
  16. #include "gui/CGuiHandler.h"
  17. #include "gui/WindowHandler.h"
  18. #include "globalLobby/GlobalLobbyClient.h"
  19. #include "lobby/CSelectionBase.h"
  20. #include "lobby/CLobbyScreen.h"
  21. #include "windows/InfoWindows.h"
  22. #include "mainmenu/CMainMenu.h"
  23. #include "mainmenu/CPrologEpilogVideo.h"
  24. #include "mainmenu/CHighScoreScreen.h"
  25. #include "../lib/CConfigHandler.h"
  26. #include "../lib/CGeneralTextHandler.h"
  27. #include "../lib/CThreadHelper.h"
  28. #include "../lib/StartInfo.h"
  29. #include "../lib/TurnTimerInfo.h"
  30. #include "../lib/VCMIDirs.h"
  31. #include "../lib/campaign/CampaignState.h"
  32. #include "../lib/mapping/CMapInfo.h"
  33. #include "../lib/mapObjects/MiscObjects.h"
  34. #include "../lib/modding/ModIncompatibility.h"
  35. #include "../lib/rmg/CMapGenOptions.h"
  36. #include "../lib/serializer/Connection.h"
  37. #include "../lib/filesystem/Filesystem.h"
  38. #include "../lib/registerTypes/RegisterTypesLobbyPacks.h"
  39. #include "../lib/serializer/CMemorySerializer.h"
  40. #include "../lib/UnlockGuard.h"
  41. #include <boost/uuid/uuid.hpp>
  42. #include <boost/uuid/uuid_io.hpp>
  43. #include <boost/uuid/uuid_generators.hpp>
  44. #include "../lib/serializer/Cast.h"
  45. #include "LobbyClientNetPackVisitors.h"
  46. #include <vcmi/events/EventBus.h>
  47. template<typename T> class CApplyOnLobby;
  48. class CBaseForLobbyApply
  49. {
  50. public:
  51. virtual bool applyOnLobbyHandler(CServerHandler * handler, CPackForLobby & pack) const = 0;
  52. virtual void applyOnLobbyScreen(CLobbyScreen * lobby, CServerHandler * handler, CPackForLobby & pack) const = 0;
  53. virtual ~CBaseForLobbyApply(){};
  54. template<typename U> static CBaseForLobbyApply * getApplier(const U * t = nullptr)
  55. {
  56. return new CApplyOnLobby<U>();
  57. }
  58. };
  59. template<typename T> class CApplyOnLobby : public CBaseForLobbyApply
  60. {
  61. public:
  62. bool applyOnLobbyHandler(CServerHandler * handler, CPackForLobby & pack) const override
  63. {
  64. auto & ref = static_cast<T&>(pack);
  65. ApplyOnLobbyHandlerNetPackVisitor visitor(*handler);
  66. logNetwork->trace("\tImmediately apply on lobby: %s", typeid(ref).name());
  67. ref.visit(visitor);
  68. return visitor.getResult();
  69. }
  70. void applyOnLobbyScreen(CLobbyScreen * lobby, CServerHandler * handler, CPackForLobby & pack) const override
  71. {
  72. auto & ref = static_cast<T &>(pack);
  73. ApplyOnLobbyScreenNetPackVisitor visitor(*handler, lobby);
  74. logNetwork->trace("\tApply on lobby from queue: %s", typeid(ref).name());
  75. ref.visit(visitor);
  76. }
  77. };
  78. template<> class CApplyOnLobby<CPack>: public CBaseForLobbyApply
  79. {
  80. public:
  81. bool applyOnLobbyHandler(CServerHandler * handler, CPackForLobby & pack) const override
  82. {
  83. logGlobal->error("Cannot apply plain CPack!");
  84. assert(0);
  85. return false;
  86. }
  87. void applyOnLobbyScreen(CLobbyScreen * lobby, CServerHandler * handler, CPackForLobby & pack) const override
  88. {
  89. logGlobal->error("Cannot apply plain CPack!");
  90. assert(0);
  91. }
  92. };
  93. CServerHandler::~CServerHandler()
  94. {
  95. if (serverRunner)
  96. serverRunner->shutdown();
  97. networkHandler->stop();
  98. try
  99. {
  100. if (serverRunner)
  101. serverRunner->wait();
  102. serverRunner.reset();
  103. threadNetwork.join();
  104. }
  105. catch (const std::runtime_error & e)
  106. {
  107. logGlobal->error("Failed to shut down network thread! Reason: %s", e.what());
  108. assert(0);
  109. }
  110. }
  111. CServerHandler::CServerHandler()
  112. : networkHandler(INetworkHandler::createHandler())
  113. , lobbyClient(std::make_unique<GlobalLobbyClient>())
  114. , applier(std::make_unique<CApplier<CBaseForLobbyApply>>())
  115. , threadNetwork(&CServerHandler::threadRunNetwork, this)
  116. , state(EClientState::NONE)
  117. , serverPort(0)
  118. , campaignStateToSend(nullptr)
  119. , screenType(ESelectionScreen::unknown)
  120. , serverMode(EServerMode::NONE)
  121. , loadMode(ELoadMode::NONE)
  122. , client(nullptr)
  123. {
  124. uuid = boost::uuids::to_string(boost::uuids::random_generator()());
  125. registerTypesLobbyPacks(*applier);
  126. }
  127. void CServerHandler::threadRunNetwork()
  128. {
  129. logGlobal->info("Starting network thread");
  130. setThreadName("runNetwork");
  131. networkHandler->run();
  132. logGlobal->info("Ending network thread");
  133. }
  134. void CServerHandler::resetStateForLobby(EStartMode mode, ESelectionScreen screen, EServerMode newServerMode, const std::vector<std::string> & playerNames)
  135. {
  136. hostClientId = -1;
  137. setState(EClientState::NONE);
  138. serverMode = newServerMode;
  139. mapToStart = nullptr;
  140. th = std::make_unique<CStopWatch>();
  141. logicConnection.reset();
  142. si = std::make_shared<StartInfo>();
  143. localPlayerNames.clear();
  144. si->difficulty = 1;
  145. si->mode = mode;
  146. screenType = screen;
  147. localPlayerNames.clear();
  148. if(!playerNames.empty()) //if have custom set of player names - use it
  149. localPlayerNames = playerNames;
  150. else
  151. localPlayerNames.push_back(settings["general"]["playerName"].String());
  152. }
  153. GlobalLobbyClient & CServerHandler::getGlobalLobby()
  154. {
  155. return *lobbyClient;
  156. }
  157. INetworkHandler & CServerHandler::getNetworkHandler()
  158. {
  159. return *networkHandler;
  160. }
  161. void CServerHandler::startLocalServerAndConnect(bool connectToLobby)
  162. {
  163. logNetwork->trace("\tLocal server startup has been requested");
  164. #ifdef VCMI_MOBILE
  165. // mobile apps can't spawn separate processes - only thread mode is available
  166. serverRunner.reset(new ServerThreadRunner());
  167. #else
  168. if (settings["server"]["useProcess"].Bool())
  169. serverRunner.reset(new ServerProcessRunner());
  170. else
  171. serverRunner.reset(new ServerThreadRunner());
  172. #endif
  173. auto si = std::make_shared<StartInfo>();
  174. auto lastDifficulty = settings["general"]["lastDifficulty"];
  175. if (lastDifficulty.isNumber())
  176. {
  177. si->difficulty = lastDifficulty.Integer();
  178. }
  179. logNetwork->trace("\tStarting local server");
  180. serverRunner->start(getLocalPort(), connectToLobby, si);
  181. logNetwork->trace("\tConnecting to local server");
  182. connectToServer(getLocalHostname(), getLocalPort());
  183. logNetwork->trace("\tWaiting for connection");
  184. }
  185. void CServerHandler::connectToServer(const std::string & addr, const ui16 port)
  186. {
  187. logNetwork->info("Establishing connection to %s:%d...", addr, port);
  188. setState(EClientState::CONNECTING);
  189. serverHostname = addr;
  190. serverPort = port;
  191. if (!isServerLocal())
  192. {
  193. Settings remoteAddress = settings.write["server"]["remoteHostname"];
  194. remoteAddress->String() = addr;
  195. Settings remotePort = settings.write["server"]["remotePort"];
  196. remotePort->Integer() = port;
  197. }
  198. networkHandler->connectToRemote(*this, addr, port);
  199. }
  200. void CServerHandler::onConnectionFailed(const std::string & errorMessage)
  201. {
  202. assert(getState() == EClientState::CONNECTING);
  203. boost::mutex::scoped_lock interfaceLock(GH.interfaceMutex);
  204. if (isServerLocal())
  205. {
  206. // retry - local server might be still starting up
  207. logNetwork->debug("\nCannot establish connection. %s. Retrying...", errorMessage);
  208. networkHandler->createTimer(*this, std::chrono::milliseconds(100));
  209. }
  210. else
  211. {
  212. // remote server refused connection - show error message
  213. setState(EClientState::NONE);
  214. CInfoWindow::showInfoDialog(CGI->generaltexth->translate("vcmi.mainMenu.serverConnectionFailed"), {});
  215. }
  216. }
  217. void CServerHandler::onTimer()
  218. {
  219. boost::mutex::scoped_lock interfaceLock(GH.interfaceMutex);
  220. if(getState() == EClientState::CONNECTION_CANCELLED)
  221. {
  222. logNetwork->info("Connection aborted by player!");
  223. serverRunner->wait();
  224. serverRunner.reset();
  225. if (GH.windows().topWindow<CSimpleJoinScreen>() != nullptr)
  226. GH.windows().popWindows(1);
  227. return;
  228. }
  229. assert(isServerLocal());
  230. networkHandler->connectToRemote(*this, getLocalHostname(), getLocalPort());
  231. }
  232. void CServerHandler::onConnectionEstablished(const NetworkConnectionPtr & netConnection)
  233. {
  234. assert(getState() == EClientState::CONNECTING);
  235. boost::mutex::scoped_lock interfaceLock(GH.interfaceMutex);
  236. networkConnection = netConnection;
  237. logNetwork->info("Connection established");
  238. if (serverMode == EServerMode::LOBBY_GUEST)
  239. {
  240. // say hello to lobby to switch connection to proxy mode
  241. getGlobalLobby().sendProxyConnectionLogin(netConnection);
  242. }
  243. logicConnection = std::make_shared<CConnection>(netConnection);
  244. logicConnection->uuid = uuid;
  245. logicConnection->enterLobbyConnectionMode();
  246. sendClientConnecting();
  247. }
  248. void CServerHandler::applyPackOnLobbyScreen(CPackForLobby & pack)
  249. {
  250. const CBaseForLobbyApply * apply = applier->getApplier(CTypeList::getInstance().getTypeID(&pack)); //find the applier
  251. apply->applyOnLobbyScreen(dynamic_cast<CLobbyScreen *>(SEL), this, pack);
  252. GH.windows().totalRedraw();
  253. }
  254. std::set<PlayerColor> CServerHandler::getHumanColors()
  255. {
  256. return clientHumanColors(logicConnection->connectionID);
  257. }
  258. PlayerColor CServerHandler::myFirstColor() const
  259. {
  260. return clientFirstColor(logicConnection->connectionID);
  261. }
  262. bool CServerHandler::isMyColor(PlayerColor color) const
  263. {
  264. return isClientColor(logicConnection->connectionID, color);
  265. }
  266. ui8 CServerHandler::myFirstId() const
  267. {
  268. return clientFirstId(logicConnection->connectionID);
  269. }
  270. EClientState CServerHandler::getState() const
  271. {
  272. return state;
  273. }
  274. void CServerHandler::setState(EClientState newState)
  275. {
  276. if (newState == EClientState::CONNECTION_CANCELLED && serverRunner != nullptr)
  277. serverRunner->shutdown();
  278. state = newState;
  279. }
  280. bool CServerHandler::isServerLocal() const
  281. {
  282. return serverRunner != nullptr;
  283. }
  284. bool CServerHandler::isHost() const
  285. {
  286. return logicConnection && hostClientId == logicConnection->connectionID;
  287. }
  288. bool CServerHandler::isGuest() const
  289. {
  290. return !logicConnection || hostClientId != logicConnection->connectionID;
  291. }
  292. const std::string & CServerHandler::getLocalHostname() const
  293. {
  294. return settings["server"]["localHostname"].String();
  295. }
  296. ui16 CServerHandler::getLocalPort() const
  297. {
  298. return settings["server"]["localPort"].Integer();
  299. }
  300. const std::string & CServerHandler::getRemoteHostname() const
  301. {
  302. return settings["server"]["remoteHostname"].String();
  303. }
  304. ui16 CServerHandler::getRemotePort() const
  305. {
  306. return settings["server"]["remotePort"].Integer();
  307. }
  308. const std::string & CServerHandler::getCurrentHostname() const
  309. {
  310. return serverHostname;
  311. }
  312. ui16 CServerHandler::getCurrentPort() const
  313. {
  314. return serverPort;
  315. }
  316. void CServerHandler::sendClientConnecting() const
  317. {
  318. LobbyClientConnected lcc;
  319. lcc.uuid = uuid;
  320. lcc.names = localPlayerNames;
  321. lcc.mode = si->mode;
  322. sendLobbyPack(lcc);
  323. }
  324. void CServerHandler::sendClientDisconnecting()
  325. {
  326. // FIXME: This is workaround needed to make sure client not trying to sent anything to non existed server
  327. if(getState() == EClientState::DISCONNECTING)
  328. {
  329. assert(0);
  330. return;
  331. }
  332. setState(EClientState::DISCONNECTING);
  333. mapToStart = nullptr;
  334. LobbyClientDisconnected lcd;
  335. lcd.clientId = logicConnection->connectionID;
  336. logNetwork->info("Connection has been requested to be closed.");
  337. if(isServerLocal())
  338. {
  339. lcd.shutdownServer = true;
  340. logNetwork->info("Sent closing signal to the server");
  341. }
  342. else
  343. {
  344. logNetwork->info("Sent leaving signal to the server");
  345. }
  346. sendLobbyPack(lcd);
  347. networkConnection->close();
  348. networkConnection.reset();
  349. logicConnection.reset();
  350. }
  351. void CServerHandler::setCampaignState(std::shared_ptr<CampaignState> newCampaign)
  352. {
  353. setState(EClientState::LOBBY_CAMPAIGN);
  354. LobbySetCampaign lsc;
  355. lsc.ourCampaign = newCampaign;
  356. sendLobbyPack(lsc);
  357. }
  358. void CServerHandler::setCampaignMap(CampaignScenarioID mapId) const
  359. {
  360. if(getState() == EClientState::GAMEPLAY) // FIXME: UI shouldn't sent commands in first place
  361. return;
  362. LobbySetCampaignMap lscm;
  363. lscm.mapId = mapId;
  364. sendLobbyPack(lscm);
  365. }
  366. void CServerHandler::setCampaignBonus(int bonusId) const
  367. {
  368. if(getState() == EClientState::GAMEPLAY) // FIXME: UI shouldn't sent commands in first place
  369. return;
  370. LobbySetCampaignBonus lscb;
  371. lscb.bonusId = bonusId;
  372. sendLobbyPack(lscb);
  373. }
  374. void CServerHandler::setMapInfo(std::shared_ptr<CMapInfo> to, std::shared_ptr<CMapGenOptions> mapGenOpts) const
  375. {
  376. LobbySetMap lsm;
  377. lsm.mapInfo = to;
  378. lsm.mapGenOpts = mapGenOpts;
  379. sendLobbyPack(lsm);
  380. }
  381. void CServerHandler::setPlayer(PlayerColor color) const
  382. {
  383. LobbySetPlayer lsp;
  384. lsp.clickedColor = color;
  385. sendLobbyPack(lsp);
  386. }
  387. void CServerHandler::setPlayerName(PlayerColor color, const std::string & name) const
  388. {
  389. LobbySetPlayerName lspn;
  390. lspn.color = color;
  391. lspn.name = name;
  392. sendLobbyPack(lspn);
  393. }
  394. void CServerHandler::setPlayerOption(ui8 what, int32_t value, PlayerColor player) const
  395. {
  396. LobbyChangePlayerOption lcpo;
  397. lcpo.what = what;
  398. lcpo.value = value;
  399. lcpo.color = player;
  400. sendLobbyPack(lcpo);
  401. }
  402. void CServerHandler::setDifficulty(int to) const
  403. {
  404. LobbySetDifficulty lsd;
  405. lsd.difficulty = to;
  406. sendLobbyPack(lsd);
  407. }
  408. void CServerHandler::setSimturnsInfo(const SimturnsInfo & info) const
  409. {
  410. LobbySetSimturns pack;
  411. pack.simturnsInfo = info;
  412. sendLobbyPack(pack);
  413. }
  414. void CServerHandler::setTurnTimerInfo(const TurnTimerInfo & info) const
  415. {
  416. LobbySetTurnTime lstt;
  417. lstt.turnTimerInfo = info;
  418. sendLobbyPack(lstt);
  419. }
  420. void CServerHandler::setExtraOptionsInfo(const ExtraOptionsInfo & info) const
  421. {
  422. LobbySetExtraOptions lseo;
  423. lseo.extraOptionsInfo = info;
  424. sendLobbyPack(lseo);
  425. }
  426. void CServerHandler::sendMessage(const std::string & txt) const
  427. {
  428. std::istringstream readed;
  429. readed.str(txt);
  430. std::string command;
  431. readed >> command;
  432. if(command == "!passhost")
  433. {
  434. std::string id;
  435. readed >> id;
  436. if(id.length())
  437. {
  438. LobbyChangeHost lch;
  439. lch.newHostConnectionId = boost::lexical_cast<int>(id);
  440. sendLobbyPack(lch);
  441. }
  442. }
  443. else if(command == "!forcep")
  444. {
  445. std::string connectedId;
  446. std::string playerColorId;
  447. readed >> connectedId;
  448. readed >> playerColorId;
  449. if(connectedId.length() && playerColorId.length())
  450. {
  451. ui8 connected = boost::lexical_cast<int>(connectedId);
  452. auto color = PlayerColor(boost::lexical_cast<int>(playerColorId));
  453. if(color.isValidPlayer() && playerNames.find(connected) != playerNames.end())
  454. {
  455. LobbyForceSetPlayer lfsp;
  456. lfsp.targetConnectedPlayer = connected;
  457. lfsp.targetPlayerColor = color;
  458. sendLobbyPack(lfsp);
  459. }
  460. }
  461. }
  462. else
  463. {
  464. LobbyChatMessage lcm;
  465. lcm.message = txt;
  466. lcm.playerName = playerNames.find(myFirstId())->second.name;
  467. sendLobbyPack(lcm);
  468. }
  469. }
  470. void CServerHandler::sendGuiAction(ui8 action) const
  471. {
  472. LobbyGuiAction lga;
  473. lga.action = static_cast<LobbyGuiAction::EAction>(action);
  474. sendLobbyPack(lga);
  475. }
  476. void CServerHandler::sendRestartGame() const
  477. {
  478. GH.windows().createAndPushWindow<CLoadingScreen>();
  479. LobbyRestartGame endGame;
  480. sendLobbyPack(endGame);
  481. }
  482. bool CServerHandler::validateGameStart(bool allowOnlyAI) const
  483. {
  484. try
  485. {
  486. verifyStateBeforeStart(allowOnlyAI ? true : settings["session"]["onlyai"].Bool());
  487. }
  488. catch(ModIncompatibility & e)
  489. {
  490. logGlobal->warn("Incompatibility exception during start scenario: %s", e.what());
  491. std::string errorMsg;
  492. if(!e.whatMissing().empty())
  493. {
  494. errorMsg += VLC->generaltexth->translate("vcmi.server.errors.modsToEnable") + '\n';
  495. errorMsg += e.whatMissing();
  496. }
  497. if(!e.whatExcessive().empty())
  498. {
  499. errorMsg += VLC->generaltexth->translate("vcmi.server.errors.modsToDisable") + '\n';
  500. errorMsg += e.whatExcessive();
  501. }
  502. showServerError(errorMsg);
  503. return false;
  504. }
  505. catch(std::exception & e)
  506. {
  507. logGlobal->error("Exception during startScenario: %s", e.what());
  508. showServerError( std::string("Unable to start map! Reason: ") + e.what());
  509. return false;
  510. }
  511. return true;
  512. }
  513. void CServerHandler::sendStartGame(bool allowOnlyAI) const
  514. {
  515. verifyStateBeforeStart(allowOnlyAI ? true : settings["session"]["onlyai"].Bool());
  516. if(!settings["session"]["headless"].Bool())
  517. GH.windows().createAndPushWindow<CLoadingScreen>();
  518. LobbyPrepareStartGame lpsg;
  519. sendLobbyPack(lpsg);
  520. LobbyStartGame lsg;
  521. if(client)
  522. {
  523. lsg.initializedStartInfo = std::make_shared<StartInfo>(* const_cast<StartInfo *>(client->getStartInfo(true)));
  524. lsg.initializedStartInfo->mode = EStartMode::NEW_GAME;
  525. lsg.initializedStartInfo->seedToBeUsed = lsg.initializedStartInfo->seedPostInit = 0;
  526. * si = * lsg.initializedStartInfo;
  527. }
  528. sendLobbyPack(lsg);
  529. }
  530. void CServerHandler::startMapAfterConnection(std::shared_ptr<CMapInfo> to)
  531. {
  532. mapToStart = to;
  533. }
  534. void CServerHandler::startGameplay(VCMI_LIB_WRAP_NAMESPACE(CGameState) * gameState)
  535. {
  536. if(CMM)
  537. CMM->disable();
  538. highScoreCalc = nullptr;
  539. switch(si->mode)
  540. {
  541. case EStartMode::NEW_GAME:
  542. client->newGame(gameState);
  543. break;
  544. case EStartMode::CAMPAIGN:
  545. client->newGame(gameState);
  546. break;
  547. case EStartMode::LOAD_GAME:
  548. client->loadGame(gameState);
  549. break;
  550. default:
  551. throw std::runtime_error("Invalid mode");
  552. }
  553. // After everything initialized we can accept CPackToClient netpacks
  554. logicConnection->enterGameplayConnectionMode(client->gameState());
  555. setState(EClientState::GAMEPLAY);
  556. }
  557. void CServerHandler::endGameplay()
  558. {
  559. // Game is ending
  560. // Tell the network thread to reach a stable state
  561. CSH->sendClientDisconnecting();
  562. logNetwork->info("Closed connection.");
  563. client->endGame();
  564. client.reset();
  565. if(CMM)
  566. {
  567. GH.curInt = CMM.get();
  568. CMM->enable();
  569. }
  570. else
  571. {
  572. GH.curInt = CMainMenu::create().get();
  573. }
  574. }
  575. void CServerHandler::restartGameplay()
  576. {
  577. client->endGame();
  578. client.reset();
  579. logicConnection->enterLobbyConnectionMode();
  580. }
  581. void CServerHandler::startCampaignScenario(HighScoreParameter param, std::shared_ptr<CampaignState> cs)
  582. {
  583. std::shared_ptr<CampaignState> ourCampaign = cs;
  584. if (!cs)
  585. ourCampaign = si->campState;
  586. if(highScoreCalc == nullptr)
  587. {
  588. highScoreCalc = std::make_shared<HighScoreCalculation>();
  589. highScoreCalc->isCampaign = true;
  590. highScoreCalc->parameters.clear();
  591. }
  592. param.campaignName = cs->getNameTranslated();
  593. highScoreCalc->parameters.push_back(param);
  594. GH.dispatchMainThread([ourCampaign, this]()
  595. {
  596. CSH->endGameplay();
  597. auto & epilogue = ourCampaign->scenario(*ourCampaign->lastScenario()).epilog;
  598. auto finisher = [=]()
  599. {
  600. if(ourCampaign->campaignSet != "" && ourCampaign->isCampaignFinished())
  601. {
  602. Settings entry = persistentStorage.write["completedCampaigns"][ourCampaign->getFilename()];
  603. entry->Bool() = true;
  604. }
  605. GH.windows().pushWindow(CMM);
  606. GH.windows().pushWindow(CMM->menu);
  607. if(!ourCampaign->isCampaignFinished())
  608. CMM->openCampaignLobby(ourCampaign);
  609. else
  610. {
  611. CMM->openCampaignScreen(ourCampaign->campaignSet);
  612. GH.windows().createAndPushWindow<CHighScoreInputScreen>(true, *highScoreCalc);
  613. }
  614. };
  615. if(epilogue.hasPrologEpilog)
  616. {
  617. GH.windows().createAndPushWindow<CPrologEpilogVideo>(epilogue, finisher);
  618. }
  619. else
  620. {
  621. finisher();
  622. }
  623. });
  624. }
  625. void CServerHandler::showServerError(const std::string & txt) const
  626. {
  627. if(auto w = GH.windows().topWindow<CLoadingScreen>())
  628. GH.windows().popWindow(w);
  629. CInfoWindow::showInfoDialog(txt, {});
  630. }
  631. int CServerHandler::howManyPlayerInterfaces()
  632. {
  633. int playerInts = 0;
  634. for(auto pint : client->playerint)
  635. {
  636. if(dynamic_cast<CPlayerInterface *>(pint.second.get()))
  637. playerInts++;
  638. }
  639. return playerInts;
  640. }
  641. ELoadMode CServerHandler::getLoadMode()
  642. {
  643. if(loadMode != ELoadMode::TUTORIAL && getState() == EClientState::GAMEPLAY)
  644. {
  645. if(si->campState)
  646. return ELoadMode::CAMPAIGN;
  647. for(auto pn : playerNames)
  648. {
  649. if(pn.second.connection != logicConnection->connectionID)
  650. return ELoadMode::MULTI;
  651. }
  652. if(howManyPlayerInterfaces() > 1) //this condition will work for hotseat mode OR multiplayer with allowed more than 1 color per player to control
  653. return ELoadMode::MULTI;
  654. return ELoadMode::SINGLE;
  655. }
  656. return loadMode;
  657. }
  658. void CServerHandler::debugStartTest(std::string filename, bool save)
  659. {
  660. logGlobal->info("Starting debug test with file: %s", filename);
  661. auto mapInfo = std::make_shared<CMapInfo>();
  662. if(save)
  663. {
  664. resetStateForLobby(EStartMode::LOAD_GAME, ESelectionScreen::loadGame, EServerMode::LOCAL, {});
  665. mapInfo->saveInit(ResourcePath(filename, EResType::SAVEGAME));
  666. }
  667. else
  668. {
  669. resetStateForLobby(EStartMode::NEW_GAME, ESelectionScreen::newGame, EServerMode::LOCAL, {});
  670. mapInfo->mapInit(filename);
  671. }
  672. if(settings["session"]["donotstartserver"].Bool())
  673. connectToServer(getLocalHostname(), getLocalPort());
  674. else
  675. startLocalServerAndConnect(false);
  676. boost::this_thread::sleep_for(boost::chrono::milliseconds(100));
  677. while(!settings["session"]["headless"].Bool() && !GH.windows().topWindow<CLobbyScreen>())
  678. boost::this_thread::sleep_for(boost::chrono::milliseconds(50));
  679. while(!mi || mapInfo->fileURI != CSH->mi->fileURI)
  680. {
  681. setMapInfo(mapInfo);
  682. boost::this_thread::sleep_for(boost::chrono::milliseconds(50));
  683. }
  684. // "Click" on color to remove us from it
  685. setPlayer(myFirstColor());
  686. while(myFirstColor() != PlayerColor::CANNOT_DETERMINE)
  687. boost::this_thread::sleep_for(boost::chrono::milliseconds(50));
  688. while(true)
  689. {
  690. try
  691. {
  692. sendStartGame();
  693. break;
  694. }
  695. catch(...)
  696. {
  697. }
  698. boost::this_thread::sleep_for(boost::chrono::milliseconds(50));
  699. }
  700. }
  701. class ServerHandlerCPackVisitor : public VCMI_LIB_WRAP_NAMESPACE(ICPackVisitor)
  702. {
  703. private:
  704. CServerHandler & handler;
  705. public:
  706. ServerHandlerCPackVisitor(CServerHandler & handler)
  707. :handler(handler)
  708. {
  709. }
  710. bool callTyped() override { return false; }
  711. void visitForLobby(CPackForLobby & lobbyPack) override
  712. {
  713. handler.visitForLobby(lobbyPack);
  714. }
  715. void visitForClient(CPackForClient & clientPack) override
  716. {
  717. handler.visitForClient(clientPack);
  718. }
  719. };
  720. void CServerHandler::onPacketReceived(const std::shared_ptr<INetworkConnection> &, const std::vector<std::byte> & message)
  721. {
  722. boost::mutex::scoped_lock interfaceLock(GH.interfaceMutex);
  723. if(getState() == EClientState::DISCONNECTING)
  724. return;
  725. CPack * pack = logicConnection->retrievePack(message);
  726. ServerHandlerCPackVisitor visitor(*this);
  727. pack->visit(visitor);
  728. }
  729. void CServerHandler::onDisconnected(const std::shared_ptr<INetworkConnection> & connection, const std::string & errorMessage)
  730. {
  731. waitForServerShutdown();
  732. if(getState() == EClientState::DISCONNECTING)
  733. {
  734. assert(networkConnection == nullptr);
  735. // Note: this branch can be reached on app shutdown, when main thread holds mutex till destruction
  736. logNetwork->info("Successfully closed connection to server!");
  737. return;
  738. }
  739. boost::mutex::scoped_lock interfaceLock(GH.interfaceMutex);
  740. logNetwork->error("Lost connection to server! Connection has been closed");
  741. if(client)
  742. {
  743. CSH->endGameplay();
  744. GH.defActionsDef = 63;
  745. CMM->menu->switchToTab("main");
  746. CSH->showServerError(CGI->generaltexth->translate("vcmi.server.errors.disconnected"));
  747. }
  748. else
  749. {
  750. LobbyClientDisconnected lcd;
  751. lcd.clientId = logicConnection->connectionID;
  752. applyPackOnLobbyScreen(lcd);
  753. }
  754. networkConnection.reset();
  755. }
  756. void CServerHandler::waitForServerShutdown()
  757. {
  758. if (!serverRunner)
  759. return; // may not exist for guest in MP
  760. serverRunner->wait();
  761. int exitCode = serverRunner->exitCode();
  762. serverRunner.reset();
  763. if (exitCode == 0)
  764. {
  765. logNetwork->info("Server closed correctly");
  766. }
  767. else
  768. {
  769. boost::mutex::scoped_lock interfaceLock(GH.interfaceMutex);
  770. if (getState() == EClientState::CONNECTING)
  771. {
  772. showServerError(CGI->generaltexth->translate("vcmi.server.errors.existingProcess"));
  773. setState(EClientState::CONNECTION_CANCELLED); // stop attempts to reconnect
  774. }
  775. logNetwork->error("Error: server failed to close correctly or crashed!");
  776. logNetwork->error("Check log file for more info");
  777. }
  778. serverRunner.reset();
  779. }
  780. void CServerHandler::visitForLobby(CPackForLobby & lobbyPack)
  781. {
  782. if(applier->getApplier(CTypeList::getInstance().getTypeID(&lobbyPack))->applyOnLobbyHandler(this, lobbyPack))
  783. {
  784. if(!settings["session"]["headless"].Bool())
  785. applyPackOnLobbyScreen(lobbyPack);
  786. }
  787. }
  788. void CServerHandler::visitForClient(CPackForClient & clientPack)
  789. {
  790. client->handlePack(&clientPack);
  791. }
  792. void CServerHandler::sendLobbyPack(const CPackForLobby & pack) const
  793. {
  794. if(getState() != EClientState::STARTING)
  795. logicConnection->sendPack(&pack);
  796. }
  797. bool CServerHandler::inLobbyRoom() const
  798. {
  799. return CSH->serverMode == EServerMode::LOBBY_HOST || CSH->serverMode == EServerMode::LOBBY_GUEST;
  800. }
  801. bool CServerHandler::inGame() const
  802. {
  803. return logicConnection != nullptr;
  804. }