CServerHandler.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978
  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::setMapInfo(std::shared_ptr<CMapInfo> to, std::shared_ptr<CMapGenOptions> mapGenOpts) const
  368. {
  369. LobbySetMap lsm;
  370. lsm.mapInfo = to;
  371. lsm.mapGenOpts = mapGenOpts;
  372. sendLobbyPack(lsm);
  373. }
  374. void CServerHandler::setPlayer(PlayerColor color) const
  375. {
  376. LobbySetPlayer lsp;
  377. lsp.clickedColor = color;
  378. sendLobbyPack(lsp);
  379. }
  380. void CServerHandler::setPlayerName(PlayerColor color, const std::string & name) const
  381. {
  382. LobbySetPlayerName lspn;
  383. lspn.color = color;
  384. lspn.name = name;
  385. sendLobbyPack(lspn);
  386. }
  387. void CServerHandler::setPlayerHandicap(PlayerColor color, Handicap handicap) const
  388. {
  389. LobbySetPlayerHandicap lsph;
  390. lsph.color = color;
  391. lsph.handicap = handicap;
  392. sendLobbyPack(lsph);
  393. }
  394. void CServerHandler::setPlayerOption(ui8 what, int32_t value, PlayerColor player) const
  395. {
  396. LobbyChangePlayerOption lcpo;
  397. lcpo.what = what;
  398. lcpo.value = value;
  399. lcpo.color = player;
  400. sendLobbyPack(lcpo);
  401. }
  402. void CServerHandler::setDifficulty(int to) const
  403. {
  404. LobbySetDifficulty lsd;
  405. lsd.difficulty = to;
  406. sendLobbyPack(lsd);
  407. }
  408. void CServerHandler::setSimturnsInfo(const SimturnsInfo & info) const
  409. {
  410. LobbySetSimturns pack;
  411. pack.simturnsInfo = info;
  412. sendLobbyPack(pack);
  413. }
  414. void CServerHandler::setTurnTimerInfo(const TurnTimerInfo & info) const
  415. {
  416. LobbySetTurnTime lstt;
  417. lstt.turnTimerInfo = info;
  418. sendLobbyPack(lstt);
  419. }
  420. void CServerHandler::setExtraOptionsInfo(const ExtraOptionsInfo & info) const
  421. {
  422. LobbySetExtraOptions lseo;
  423. lseo.extraOptionsInfo = info;
  424. sendLobbyPack(lseo);
  425. }
  426. void CServerHandler::sendMessage(const std::string & txt) const
  427. {
  428. std::istringstream readed;
  429. readed.str(txt);
  430. std::string command;
  431. readed >> command;
  432. if(command == "!passhost")
  433. {
  434. std::string id;
  435. readed >> id;
  436. if(id.length())
  437. {
  438. LobbyChangeHost lch;
  439. lch.newHostConnectionId = static_cast<GameConnectionID>(boost::lexical_cast<int>(id));
  440. sendLobbyPack(lch);
  441. }
  442. }
  443. else if(command == "!forcep")
  444. {
  445. std::string connectedId;
  446. std::string playerColorId;
  447. readed >> connectedId;
  448. readed >> playerColorId;
  449. if(connectedId.length() && playerColorId.length())
  450. {
  451. auto connected = static_cast<PlayerConnectionID>(boost::lexical_cast<int>(connectedId));
  452. auto color = PlayerColor(boost::lexical_cast<int>(playerColorId));
  453. if(color.isValidPlayer() && playerNames.find(connected) != playerNames.end())
  454. {
  455. LobbyForceSetPlayer lfsp;
  456. lfsp.targetConnectedPlayer = connected;
  457. lfsp.targetPlayerColor = color;
  458. sendLobbyPack(lfsp);
  459. }
  460. }
  461. }
  462. else
  463. {
  464. gameChat->sendMessageLobby(playerNames.find(myFirstId())->second.name, txt);
  465. }
  466. }
  467. void CServerHandler::sendGuiAction(ui8 action) const
  468. {
  469. LobbyGuiAction lga;
  470. lga.action = static_cast<LobbyGuiAction::EAction>(action);
  471. sendLobbyPack(lga);
  472. }
  473. void CServerHandler::sendRestartGame() const
  474. {
  475. if(si->campState && !si->campState->getLoadingBackground().empty())
  476. ENGINE->windows().createAndPushWindow<CLoadingScreen>(si->campState->getLoadingBackground());
  477. else
  478. ENGINE->windows().createAndPushWindow<CLoadingScreen>();
  479. LobbyRestartGame endGame;
  480. sendLobbyPack(endGame);
  481. }
  482. bool CServerHandler::validateGameStart(bool allowOnlyAI) const
  483. {
  484. try
  485. {
  486. verifyStateBeforeStart(allowOnlyAI ? true : settings["session"]["onlyai"].Bool());
  487. }
  488. catch(ModIncompatibility & e)
  489. {
  490. logGlobal->warn("Incompatibility exception during start scenario: %s", e.what());
  491. showServerError(e.getFullErrorMsg());
  492. return false;
  493. }
  494. catch(std::exception & e)
  495. {
  496. logGlobal->error("Exception during startScenario: %s", e.what());
  497. showServerError(std::string("Unable to start map!\nReason: ") + e.what());
  498. return false;
  499. }
  500. return true;
  501. }
  502. void CServerHandler::sendStartGame(bool allowOnlyAI) const
  503. {
  504. verifyStateBeforeStart(allowOnlyAI ? true : settings["session"]["onlyai"].Bool());
  505. if(!settings["session"]["headless"].Bool())
  506. {
  507. if(si->campState && !si->campState->getLoadingBackground().empty())
  508. ENGINE->windows().createAndPushWindow<CLoadingScreen>(si->campState->getLoadingBackground());
  509. else
  510. ENGINE->windows().createAndPushWindow<CLoadingScreen>();
  511. }
  512. LobbyPrepareStartGame lpsg;
  513. sendLobbyPack(lpsg);
  514. LobbyStartGame lsg;
  515. sendLobbyPack(lsg);
  516. }
  517. void CServerHandler::startMapAfterConnection(std::shared_ptr<CMapInfo> to)
  518. {
  519. mapToStart = to;
  520. }
  521. void CServerHandler::enableLagCompensation(bool on)
  522. {
  523. if (on)
  524. networkLagCompensator = std::make_unique<NetworkLagCompensator>(getNetworkHandler(), client->gameStatePtr());
  525. else
  526. networkLagCompensator.reset();
  527. }
  528. void CServerHandler::startGameplay(std::shared_ptr<CGameState> gameState)
  529. {
  530. if(GAME->mainmenu())
  531. GAME->mainmenu()->disable();
  532. if (isGuest())
  533. networkLagCompensator = std::make_unique<NetworkLagCompensator>(getNetworkHandler(), gameState);
  534. switch(si->mode)
  535. {
  536. case EStartMode::NEW_GAME:
  537. client->newGame(gameState);
  538. break;
  539. case EStartMode::CAMPAIGN:
  540. if(si->campState->conqueredScenarios().empty())
  541. si->campState->highscoreParameters.clear();
  542. client->newGame(gameState);
  543. break;
  544. case EStartMode::LOAD_GAME:
  545. client->loadGame(gameState);
  546. break;
  547. default:
  548. throw std::runtime_error("Invalid mode");
  549. }
  550. // After everything initialized we can accept CPackToClient netpacks
  551. setState(EClientState::GAMEPLAY);
  552. }
  553. void CServerHandler::showHighScoresAndEndGameplay(PlayerColor player, bool victory, const StatisticDataSet & statistic)
  554. {
  555. HighScoreParameter param = HighScore::prepareHighScores(&client->gameState(), player, victory);
  556. if(victory && client->gameState().getStartInfo()->campState)
  557. {
  558. startCampaignScenario(param, client->gameState().getStartInfo()->campState, statistic);
  559. }
  560. else
  561. {
  562. HighScoreCalculation scenarioHighScores;
  563. scenarioHighScores.parameters.push_back(param);
  564. scenarioHighScores.isCampaign = false;
  565. endGameplay();
  566. GAME->mainmenu()->menu->switchToTab("main");
  567. ENGINE->windows().createAndPushWindow<CHighScoreInputScreen>(victory, scenarioHighScores, statistic);
  568. }
  569. }
  570. void CServerHandler::endGameplay()
  571. {
  572. client->finishGameplay();
  573. // Game is ending
  574. // Tell the network thread to reach a stable state
  575. sendClientDisconnecting();
  576. logNetwork->info("Closed connection.");
  577. client->endGame();
  578. client.reset();
  579. if (GAME->mainmenu())
  580. {
  581. GAME->mainmenu()->enable();
  582. GAME->mainmenu()->playMusic();
  583. GAME->mainmenu()->makeActiveInterface();
  584. }
  585. }
  586. void CServerHandler::restartGameplay()
  587. {
  588. client->finishGameplay();
  589. client->endGame();
  590. client.reset();
  591. logicConnection->enterLobbyConnectionMode();
  592. }
  593. void CServerHandler::startCampaignScenario(HighScoreParameter param, std::shared_ptr<CampaignState> cs, const StatisticDataSet & statistic)
  594. {
  595. std::shared_ptr<CampaignState> ourCampaign = cs;
  596. if (!cs)
  597. ourCampaign = si->campState;
  598. param.campaignName = cs->getNameTranslated();
  599. cs->highscoreParameters.push_back(param);
  600. auto campaignScoreCalculator = std::make_shared<HighScoreCalculation>();
  601. campaignScoreCalculator->isCampaign = true;
  602. campaignScoreCalculator->parameters = cs->highscoreParameters;
  603. endGameplay();
  604. auto & epilogue = ourCampaign->scenario(*ourCampaign->lastScenario()).epilog;
  605. auto finisher = [ourCampaign, campaignScoreCalculator, statistic]()
  606. {
  607. if(ourCampaign->campaignSet != "" && ourCampaign->isCampaignFinished())
  608. {
  609. Settings entry = persistentStorage.write["completedCampaigns"][ourCampaign->getFilename()];
  610. entry->Bool() = true;
  611. }
  612. if(!ourCampaign->isCampaignFinished())
  613. GAME->mainmenu()->openCampaignLobby(ourCampaign);
  614. else
  615. {
  616. GAME->mainmenu()->openCampaignScreen(ourCampaign->campaignSet);
  617. if(!ourCampaign->getOutroVideo().empty() && ENGINE->video().open(ourCampaign->getOutroVideo(), 1))
  618. {
  619. ENGINE->music().stopMusic();
  620. ENGINE->windows().createAndPushWindow<VideoWindow>(ourCampaign->getOutroVideo(), ourCampaign->getVideoRim().empty() ? ImagePath::builtin("INTRORIM") : ourCampaign->getVideoRim(), false, 1, [campaignScoreCalculator, statistic](bool skipped){
  621. ENGINE->windows().createAndPushWindow<CHighScoreInputScreen>(true, *campaignScoreCalculator, statistic);
  622. });
  623. }
  624. else
  625. ENGINE->windows().createAndPushWindow<CHighScoreInputScreen>(true, *campaignScoreCalculator, statistic);
  626. }
  627. };
  628. if(epilogue.hasPrologEpilog)
  629. {
  630. ENGINE->windows().createAndPushWindow<CPrologEpilogVideo>(epilogue, finisher);
  631. }
  632. else
  633. {
  634. finisher();
  635. }
  636. }
  637. void CServerHandler::showServerError(const std::string & txt) const
  638. {
  639. if(auto w = ENGINE->windows().topWindow<CLoadingScreen>())
  640. ENGINE->windows().popWindow(w);
  641. CInfoWindow::showInfoDialog(txt, {});
  642. }
  643. int CServerHandler::howManyPlayerInterfaces()
  644. {
  645. int playerInts = 0;
  646. for(auto pint : client->playerint)
  647. {
  648. if(dynamic_cast<CPlayerInterface *>(pint.second.get()))
  649. playerInts++;
  650. }
  651. return playerInts;
  652. }
  653. ELoadMode CServerHandler::getLoadMode()
  654. {
  655. if(loadMode != ELoadMode::TUTORIAL && getState() == EClientState::GAMEPLAY)
  656. {
  657. if(si->campState)
  658. return ELoadMode::CAMPAIGN;
  659. for(auto pn : playerNames)
  660. {
  661. if(pn.second.connection != logicConnection->connectionID)
  662. return ELoadMode::MULTI;
  663. }
  664. if(howManyPlayerInterfaces() > 1) //this condition will work for hotseat mode OR multiplayer with allowed more than 1 color per player to control
  665. return ELoadMode::MULTI;
  666. return ELoadMode::SINGLE;
  667. }
  668. return loadMode;
  669. }
  670. void CServerHandler::debugStartTest(std::string filename, bool save)
  671. {
  672. logGlobal->info("Starting debug test with file: %s", filename);
  673. auto mapInfo = std::make_shared<CMapInfo>();
  674. if(save)
  675. {
  676. resetStateForLobby(EStartMode::LOAD_GAME, ESelectionScreen::loadGame, EServerMode::LOCAL, {});
  677. mapInfo->saveInit(ResourcePath(filename, EResType::SAVEGAME));
  678. }
  679. else
  680. {
  681. resetStateForLobby(EStartMode::NEW_GAME, ESelectionScreen::newGame, EServerMode::LOCAL, {});
  682. mapInfo->mapInit(filename);
  683. }
  684. if(settings["session"]["donotstartserver"].Bool())
  685. connectToServer(getLocalHostname(), getLocalPort());
  686. else
  687. startLocalServerAndConnect(false);
  688. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  689. while(!settings["session"]["headless"].Bool() && !ENGINE->windows().topWindow<CLobbyScreen>())
  690. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  691. while(!mi || mapInfo->fileURI != mi->fileURI)
  692. {
  693. setMapInfo(mapInfo);
  694. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  695. }
  696. // "Click" on color to remove us from it
  697. setPlayer(myFirstColor());
  698. while(myFirstColor() != PlayerColor::CANNOT_DETERMINE)
  699. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  700. while(true)
  701. {
  702. try
  703. {
  704. sendStartGame();
  705. break;
  706. }
  707. catch(...)
  708. {
  709. }
  710. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  711. }
  712. }
  713. class ServerHandlerCPackVisitor : public VCMI_LIB_WRAP_NAMESPACE(ICPackVisitor)
  714. {
  715. private:
  716. CServerHandler & handler;
  717. public:
  718. ServerHandlerCPackVisitor(CServerHandler & handler)
  719. :handler(handler)
  720. {
  721. }
  722. bool callTyped() override { return false; }
  723. void visitForLobby(CPackForLobby & lobbyPack) override
  724. {
  725. handler.visitForLobby(lobbyPack);
  726. }
  727. void visitForClient(CPackForClient & clientPack) override
  728. {
  729. handler.visitForClient(clientPack);
  730. }
  731. };
  732. void CServerHandler::onPacketReceived(const std::shared_ptr<INetworkConnection> &, const std::vector<std::byte> & message)
  733. {
  734. std::scoped_lock interfaceLock(ENGINE->interfaceMutex);
  735. if(getState() == EClientState::DISCONNECTING)
  736. return;
  737. auto pack = logicConnection->retrievePack(message);
  738. ServerHandlerCPackVisitor visitor(*this);
  739. pack->visit(visitor);
  740. }
  741. void CServerHandler::onDisconnected(const std::shared_ptr<INetworkConnection> & connection, const std::string & errorMessage)
  742. {
  743. std::scoped_lock interfaceLock(ENGINE->interfaceMutex);
  744. if (connection != networkConnection)
  745. {
  746. // ServerHandler already closed this connection on its own
  747. // This is the final call from network thread that informs serverHandler that connection has died
  748. // ignore it since serverHandler have already shut down this connection (and possibly started a new one)
  749. return;
  750. }
  751. waitForServerShutdown();
  752. if(getState() == EClientState::DISCONNECTING)
  753. {
  754. // Note: this branch can be reached on app shutdown, when main thread holds mutex till destruction
  755. logNetwork->info("Successfully closed connection to server!");
  756. return;
  757. }
  758. logNetwork->error("Lost connection to server! Connection has been closed");
  759. if(client)
  760. {
  761. endGameplay();
  762. GAME->mainmenu()->menu->switchToTab("main");
  763. showServerError(LIBRARY->generaltexth->translate("vcmi.server.errors.disconnected"));
  764. }
  765. else
  766. {
  767. LobbyClientDisconnected lcd;
  768. lcd.clientId = logicConnection->connectionID;
  769. applyPackOnLobbyScreen(lcd);
  770. }
  771. networkConnection.reset();
  772. }
  773. void CServerHandler::waitForServerShutdown()
  774. {
  775. if (!serverRunner)
  776. return; // may not exist for guest in MP
  777. serverRunner->wait();
  778. int exitCode = serverRunner->exitCode();
  779. serverRunner.reset();
  780. if (exitCode == 0)
  781. {
  782. logNetwork->info("Server closed correctly");
  783. }
  784. else
  785. {
  786. if (getState() == EClientState::CONNECTING)
  787. {
  788. showServerError(LIBRARY->generaltexth->translate("vcmi.server.errors.existingProcess"));
  789. setState(EClientState::CONNECTION_CANCELLED); // stop attempts to reconnect
  790. }
  791. logNetwork->error("Error: server failed to close correctly or crashed!");
  792. logNetwork->error("Check log file for more info");
  793. }
  794. serverRunner.reset();
  795. }
  796. void CServerHandler::visitForLobby(CPackForLobby & lobbyPack)
  797. {
  798. ApplyOnLobbyHandlerNetPackVisitor visitor(*this);
  799. lobbyPack.visit(visitor);
  800. if(visitor.getResult())
  801. {
  802. if(!settings["session"]["headless"].Bool())
  803. applyPackOnLobbyScreen(lobbyPack);
  804. }
  805. }
  806. void CServerHandler::visitForClient(CPackForClient & clientPack)
  807. {
  808. if (networkLagCompensator && networkLagCompensator->verifyReply(clientPack))
  809. return;
  810. client->handlePack(clientPack);
  811. }
  812. void CServerHandler::sendLobbyPack(const CPackForLobby & pack) const
  813. {
  814. if(getState() != EClientState::STARTING)
  815. logicConnection->sendPack(pack);
  816. }
  817. bool CServerHandler::inLobbyRoom() const
  818. {
  819. return serverMode == EServerMode::LOBBY_HOST || serverMode == EServerMode::LOBBY_GUEST;
  820. }
  821. bool CServerHandler::inGame() const
  822. {
  823. return logicConnection != nullptr;
  824. }
  825. void CServerHandler::sendGamePack(const CPackForServer & pack) const
  826. {
  827. if (networkLagCompensator)
  828. networkLagCompensator->tryPredictReply(pack);
  829. logicConnection->sendPack(pack);
  830. }