CServerHandler.cpp 24 KB

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