CServerHandler.cpp 27 KB

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