CServerHandler.cpp 25 KB

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