CServerHandler.cpp 24 KB

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