CServerHandler.cpp 25 KB

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