CServerHandler.cpp 23 KB

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