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. CServerHandler::~CServerHandler()
  55. {
  56. if (serverRunner)
  57. serverRunner->shutdown();
  58. networkHandler->stop();
  59. if (serverRunner)
  60. serverRunner->wait();
  61. serverRunner.reset();
  62. if (threadNetwork.joinable())
  63. {
  64. auto unlockInterface = vstd::makeUnlockGuard(ENGINE->interfaceMutex);
  65. threadNetwork.join();
  66. }
  67. }
  68. void CServerHandler::endNetwork()
  69. {
  70. if (client)
  71. client->endNetwork();
  72. networkHandler->stop();
  73. if (threadNetwork.joinable())
  74. {
  75. auto unlockInterface = vstd::makeUnlockGuard(ENGINE->interfaceMutex);
  76. threadNetwork.join();
  77. }
  78. }
  79. CServerHandler::CServerHandler()
  80. : networkHandler(INetworkHandler::createHandler())
  81. , lobbyClient(std::make_unique<GlobalLobbyClient>())
  82. , gameChat(std::make_unique<GameChatHandler>())
  83. , threadNetwork(&CServerHandler::threadRunNetwork, this)
  84. , state(EClientState::NONE)
  85. , serverPort(0)
  86. , campaignStateToSend(nullptr)
  87. , screenType(ESelectionScreen::unknown)
  88. , serverMode(EServerMode::NONE)
  89. , loadMode(ELoadMode::NONE)
  90. , client(nullptr)
  91. {
  92. uuid = boost::uuids::to_string(boost::uuids::random_generator()());
  93. }
  94. void CServerHandler::threadRunNetwork()
  95. {
  96. setThreadName("runNetwork");
  97. logGlobal->info("Starting network thread");
  98. try {
  99. networkHandler->run();
  100. }
  101. catch (const TerminationRequestedException &)
  102. {
  103. logGlobal->info("Terminating network thread");
  104. return;
  105. }
  106. logGlobal->info("Ending network thread");
  107. }
  108. void CServerHandler::resetStateForLobby(EStartMode mode, ESelectionScreen screen, EServerMode newServerMode, const std::vector<std::string> & playerNames)
  109. {
  110. hostClientId = -1;
  111. setState(EClientState::NONE);
  112. serverMode = newServerMode;
  113. mapToStart = nullptr;
  114. th = std::make_unique<CStopWatch>();
  115. logicConnection.reset();
  116. si = std::make_shared<StartInfo>();
  117. localPlayerNames.clear();
  118. si->difficulty = 1;
  119. si->mode = mode;
  120. screenType = screen;
  121. localPlayerNames.clear();
  122. if(!playerNames.empty()) //if have custom set of player names - use it
  123. localPlayerNames = playerNames;
  124. else
  125. {
  126. std::string playerName = settings["general"]["playerName"].String();
  127. if(playerName == "Player")
  128. playerName = LIBRARY->generaltexth->translate("core.genrltxt.434");
  129. localPlayerNames.push_back(playerName);
  130. }
  131. gameChat->resetMatchState();
  132. lobbyClient->resetMatchState();
  133. }
  134. GameChatHandler & CServerHandler::getGameChat()
  135. {
  136. return *gameChat;
  137. }
  138. GlobalLobbyClient & CServerHandler::getGlobalLobby()
  139. {
  140. return *lobbyClient;
  141. }
  142. INetworkHandler & CServerHandler::getNetworkHandler()
  143. {
  144. return *networkHandler;
  145. }
  146. void CServerHandler::startLocalServerAndConnect(bool connectToLobby)
  147. {
  148. logNetwork->trace("\tLocal server startup has been requested");
  149. #ifdef VCMI_MOBILE
  150. // mobile apps can't spawn separate processes - only thread mode is available
  151. serverRunner.reset(new ServerThreadRunner());
  152. #else
  153. if (settings["server"]["useProcess"].Bool())
  154. serverRunner.reset(new ServerProcessRunner());
  155. else
  156. serverRunner.reset(new ServerThreadRunner());
  157. #endif
  158. auto si = std::make_shared<StartInfo>();
  159. auto lastDifficulty = settings["general"]["lastDifficulty"];
  160. si->difficulty = lastDifficulty.Integer();
  161. logNetwork->trace("\tStarting local server");
  162. serverRunner->start(loadMode == ELoadMode::MULTI, connectToLobby, si);
  163. logNetwork->trace("\tConnecting to local server");
  164. connectToServer(getLocalHostname(), getLocalPort());
  165. logNetwork->trace("\tWaiting for connection");
  166. }
  167. void CServerHandler::connectToServer(const std::string & addr, const ui16 port)
  168. {
  169. setState(EClientState::CONNECTING);
  170. serverHostname = addr;
  171. serverPort = port;
  172. if (!isServerLocal())
  173. {
  174. Settings remoteAddress = settings.write["server"]["remoteHostname"];
  175. remoteAddress->String() = addr;
  176. Settings remotePort = settings.write["server"]["remotePort"];
  177. remotePort->Integer() = port;
  178. networkHandler->connectToRemote(*this, addr, port);
  179. }
  180. else
  181. {
  182. serverRunner->connect(*networkHandler, *this);
  183. }
  184. }
  185. void CServerHandler::onConnectionFailed(const std::string & errorMessage)
  186. {
  187. assert(getState() == EClientState::CONNECTING);
  188. std::scoped_lock interfaceLock(ENGINE->interfaceMutex);
  189. if (isServerLocal())
  190. {
  191. // retry - local server might be still starting up
  192. logNetwork->debug("\nCannot establish connection. %s. Retrying...", errorMessage);
  193. networkHandler->createTimer(*this, std::chrono::milliseconds(100));
  194. }
  195. else
  196. {
  197. // remote server refused connection - show error message
  198. setState(EClientState::NONE);
  199. CInfoWindow::showInfoDialog(LIBRARY->generaltexth->translate("vcmi.mainMenu.serverConnectionFailed"), {});
  200. }
  201. }
  202. void CServerHandler::onTimer()
  203. {
  204. std::scoped_lock interfaceLock(ENGINE->interfaceMutex);
  205. if(getState() == EClientState::CONNECTION_CANCELLED)
  206. {
  207. logNetwork->info("Connection aborted by player!");
  208. serverRunner->wait();
  209. serverRunner.reset();
  210. if (ENGINE->windows().topWindow<CSimpleJoinScreen>() != nullptr)
  211. ENGINE->windows().popWindows(1);
  212. return;
  213. }
  214. assert(isServerLocal());
  215. serverRunner->connect(*networkHandler, *this);
  216. }
  217. void CServerHandler::onConnectionEstablished(const NetworkConnectionPtr & netConnection)
  218. {
  219. assert(getState() == EClientState::CONNECTING);
  220. std::scoped_lock interfaceLock(ENGINE->interfaceMutex);
  221. networkConnection = netConnection;
  222. logNetwork->info("Connection established");
  223. if (serverMode == EServerMode::LOBBY_GUEST)
  224. {
  225. // say hello to lobby to switch connection to proxy mode
  226. getGlobalLobby().sendProxyConnectionLogin(netConnection);
  227. }
  228. logicConnection = std::make_shared<CConnection>(netConnection);
  229. logicConnection->uuid = uuid;
  230. logicConnection->enterLobbyConnectionMode();
  231. sendClientConnecting();
  232. }
  233. void CServerHandler::applyPackOnLobbyScreen(CPackForLobby & pack)
  234. {
  235. ApplyOnLobbyScreenNetPackVisitor visitor(*this, dynamic_cast<CLobbyScreen *>(SEL));
  236. pack.visit(visitor);
  237. ENGINE->windows().totalRedraw();
  238. }
  239. std::set<PlayerColor> CServerHandler::getHumanColors()
  240. {
  241. return clientHumanColors(logicConnection->connectionID);
  242. }
  243. PlayerColor CServerHandler::myFirstColor() const
  244. {
  245. return clientFirstColor(logicConnection->connectionID);
  246. }
  247. bool CServerHandler::isMyColor(PlayerColor color) const
  248. {
  249. return isClientColor(logicConnection->connectionID, color);
  250. }
  251. ui8 CServerHandler::myFirstId() const
  252. {
  253. return clientFirstId(logicConnection->connectionID);
  254. }
  255. EClientState CServerHandler::getState() const
  256. {
  257. return state;
  258. }
  259. void CServerHandler::setState(EClientState newState)
  260. {
  261. if (newState == EClientState::CONNECTION_CANCELLED && serverRunner != nullptr)
  262. serverRunner->shutdown();
  263. state = newState;
  264. }
  265. bool CServerHandler::isServerLocal() const
  266. {
  267. return serverRunner != nullptr;
  268. }
  269. bool CServerHandler::isHost() const
  270. {
  271. return logicConnection && hostClientId == logicConnection->connectionID;
  272. }
  273. bool CServerHandler::isGuest() const
  274. {
  275. return !logicConnection || hostClientId != logicConnection->connectionID;
  276. }
  277. const std::string & CServerHandler::getLocalHostname() const
  278. {
  279. return settings["server"]["localHostname"].String();
  280. }
  281. ui16 CServerHandler::getLocalPort() const
  282. {
  283. return settings["server"]["localPort"].Integer();
  284. }
  285. const std::string & CServerHandler::getRemoteHostname() const
  286. {
  287. return settings["server"]["remoteHostname"].String();
  288. }
  289. ui16 CServerHandler::getRemotePort() const
  290. {
  291. return settings["server"]["remotePort"].Integer();
  292. }
  293. const std::string & CServerHandler::getCurrentHostname() const
  294. {
  295. return serverHostname;
  296. }
  297. ui16 CServerHandler::getCurrentPort() const
  298. {
  299. return serverPort;
  300. }
  301. void CServerHandler::sendClientConnecting() const
  302. {
  303. LobbyClientConnected lcc;
  304. lcc.uuid = uuid;
  305. lcc.names = localPlayerNames;
  306. lcc.mode = si->mode;
  307. sendLobbyPack(lcc);
  308. }
  309. void CServerHandler::sendClientDisconnecting()
  310. {
  311. // FIXME: This is workaround needed to make sure client not trying to sent anything to non existed server
  312. if(getState() == EClientState::DISCONNECTING)
  313. {
  314. assert(0);
  315. return;
  316. }
  317. setState(EClientState::DISCONNECTING);
  318. mapToStart = nullptr;
  319. LobbyClientDisconnected lcd;
  320. lcd.clientId = logicConnection->connectionID;
  321. logNetwork->info("Connection has been requested to be closed.");
  322. if(isServerLocal())
  323. {
  324. lcd.shutdownServer = true;
  325. logNetwork->info("Sent closing signal to the server");
  326. }
  327. else
  328. {
  329. logNetwork->info("Sent leaving signal to the server");
  330. }
  331. sendLobbyPack(lcd);
  332. networkConnection->close();
  333. networkConnection.reset();
  334. logicConnection.reset();
  335. waitForServerShutdown();
  336. }
  337. void CServerHandler::setCampaignState(std::shared_ptr<CampaignState> newCampaign)
  338. {
  339. setState(EClientState::LOBBY_CAMPAIGN);
  340. LobbySetCampaign lsc;
  341. lsc.ourCampaign = newCampaign;
  342. sendLobbyPack(lsc);
  343. }
  344. void CServerHandler::setCampaignMap(CampaignScenarioID mapId) const
  345. {
  346. if(getState() == EClientState::GAMEPLAY) // FIXME: UI shouldn't sent commands in first place
  347. return;
  348. LobbySetCampaignMap lscm;
  349. lscm.mapId = mapId;
  350. sendLobbyPack(lscm);
  351. }
  352. void CServerHandler::setCampaignBonus(int bonusId) const
  353. {
  354. if(getState() == EClientState::GAMEPLAY) // FIXME: UI shouldn't sent commands in first place
  355. return;
  356. LobbySetCampaignBonus lscb;
  357. lscb.bonusId = bonusId;
  358. sendLobbyPack(lscb);
  359. }
  360. void CServerHandler::setMapInfo(std::shared_ptr<CMapInfo> to, std::shared_ptr<CMapGenOptions> mapGenOpts) const
  361. {
  362. LobbySetMap lsm;
  363. lsm.mapInfo = to;
  364. lsm.mapGenOpts = mapGenOpts;
  365. sendLobbyPack(lsm);
  366. }
  367. void CServerHandler::setPlayer(PlayerColor color) const
  368. {
  369. LobbySetPlayer lsp;
  370. lsp.clickedColor = color;
  371. sendLobbyPack(lsp);
  372. }
  373. void CServerHandler::setPlayerName(PlayerColor color, const std::string & name) const
  374. {
  375. LobbySetPlayerName lspn;
  376. lspn.color = color;
  377. lspn.name = name;
  378. sendLobbyPack(lspn);
  379. }
  380. void CServerHandler::setPlayerHandicap(PlayerColor color, Handicap handicap) const
  381. {
  382. LobbySetPlayerHandicap lsph;
  383. lsph.color = color;
  384. lsph.handicap = handicap;
  385. sendLobbyPack(lsph);
  386. }
  387. void CServerHandler::setPlayerOption(ui8 what, int32_t value, PlayerColor player) const
  388. {
  389. LobbyChangePlayerOption lcpo;
  390. lcpo.what = what;
  391. lcpo.value = value;
  392. lcpo.color = player;
  393. sendLobbyPack(lcpo);
  394. }
  395. void CServerHandler::setDifficulty(int to) const
  396. {
  397. LobbySetDifficulty lsd;
  398. lsd.difficulty = to;
  399. sendLobbyPack(lsd);
  400. }
  401. void CServerHandler::setSimturnsInfo(const SimturnsInfo & info) const
  402. {
  403. LobbySetSimturns pack;
  404. pack.simturnsInfo = info;
  405. sendLobbyPack(pack);
  406. }
  407. void CServerHandler::setTurnTimerInfo(const TurnTimerInfo & info) const
  408. {
  409. LobbySetTurnTime lstt;
  410. lstt.turnTimerInfo = info;
  411. sendLobbyPack(lstt);
  412. }
  413. void CServerHandler::setExtraOptionsInfo(const ExtraOptionsInfo & info) const
  414. {
  415. LobbySetExtraOptions lseo;
  416. lseo.extraOptionsInfo = info;
  417. sendLobbyPack(lseo);
  418. }
  419. void CServerHandler::sendMessage(const std::string & txt) const
  420. {
  421. std::istringstream readed;
  422. readed.str(txt);
  423. std::string command;
  424. readed >> command;
  425. if(command == "!passhost")
  426. {
  427. std::string id;
  428. readed >> id;
  429. if(id.length())
  430. {
  431. LobbyChangeHost lch;
  432. lch.newHostConnectionId = boost::lexical_cast<int>(id);
  433. sendLobbyPack(lch);
  434. }
  435. }
  436. else if(command == "!forcep")
  437. {
  438. std::string connectedId;
  439. std::string playerColorId;
  440. readed >> connectedId;
  441. readed >> playerColorId;
  442. if(connectedId.length() && playerColorId.length())
  443. {
  444. ui8 connected = boost::lexical_cast<int>(connectedId);
  445. auto color = PlayerColor(boost::lexical_cast<int>(playerColorId));
  446. if(color.isValidPlayer() && playerNames.find(connected) != playerNames.end())
  447. {
  448. LobbyForceSetPlayer lfsp;
  449. lfsp.targetConnectedPlayer = connected;
  450. lfsp.targetPlayerColor = color;
  451. sendLobbyPack(lfsp);
  452. }
  453. }
  454. }
  455. else
  456. {
  457. gameChat->sendMessageLobby(playerNames.find(myFirstId())->second.name, txt);
  458. }
  459. }
  460. void CServerHandler::sendGuiAction(ui8 action) const
  461. {
  462. LobbyGuiAction lga;
  463. lga.action = static_cast<LobbyGuiAction::EAction>(action);
  464. sendLobbyPack(lga);
  465. }
  466. void CServerHandler::sendRestartGame() const
  467. {
  468. if(si->campState && !si->campState->getLoadingBackground().empty())
  469. ENGINE->windows().createAndPushWindow<CLoadingScreen>(si->campState->getLoadingBackground());
  470. else
  471. ENGINE->windows().createAndPushWindow<CLoadingScreen>();
  472. LobbyRestartGame endGame;
  473. sendLobbyPack(endGame);
  474. }
  475. bool CServerHandler::validateGameStart(bool allowOnlyAI) const
  476. {
  477. try
  478. {
  479. verifyStateBeforeStart(allowOnlyAI ? true : settings["session"]["onlyai"].Bool());
  480. }
  481. catch(ModIncompatibility & e)
  482. {
  483. logGlobal->warn("Incompatibility exception during start scenario: %s", e.what());
  484. std::string errorMsg;
  485. if(!e.whatMissing().empty())
  486. {
  487. errorMsg += LIBRARY->generaltexth->translate("vcmi.server.errors.modsToEnable") + '\n';
  488. errorMsg += e.whatMissing();
  489. }
  490. if(!e.whatExcessive().empty())
  491. {
  492. errorMsg += LIBRARY->generaltexth->translate("vcmi.server.errors.modsToDisable") + '\n';
  493. errorMsg += e.whatExcessive();
  494. }
  495. showServerError(errorMsg);
  496. return false;
  497. }
  498. catch(std::exception & e)
  499. {
  500. logGlobal->error("Exception during startScenario: %s", e.what());
  501. showServerError( std::string("Unable to start map! Reason: ") + e.what());
  502. return false;
  503. }
  504. return true;
  505. }
  506. void CServerHandler::sendStartGame(bool allowOnlyAI) const
  507. {
  508. verifyStateBeforeStart(allowOnlyAI ? true : settings["session"]["onlyai"].Bool());
  509. if(!settings["session"]["headless"].Bool())
  510. {
  511. if(si->campState && !si->campState->getLoadingBackground().empty())
  512. ENGINE->windows().createAndPushWindow<CLoadingScreen>(si->campState->getLoadingBackground());
  513. else
  514. ENGINE->windows().createAndPushWindow<CLoadingScreen>();
  515. }
  516. LobbyPrepareStartGame lpsg;
  517. sendLobbyPack(lpsg);
  518. LobbyStartGame lsg;
  519. sendLobbyPack(lsg);
  520. }
  521. void CServerHandler::startMapAfterConnection(std::shared_ptr<CMapInfo> to)
  522. {
  523. mapToStart = to;
  524. }
  525. void CServerHandler::startGameplay(VCMI_LIB_WRAP_NAMESPACE(CGameState) * gameState)
  526. {
  527. if(GAME->mainmenu())
  528. GAME->mainmenu()->disable();
  529. switch(si->mode)
  530. {
  531. case EStartMode::NEW_GAME:
  532. client->newGame(gameState);
  533. break;
  534. case EStartMode::CAMPAIGN:
  535. if(si->campState->conqueredScenarios().empty())
  536. si->campState->highscoreParameters.clear();
  537. client->newGame(gameState);
  538. break;
  539. case EStartMode::LOAD_GAME:
  540. client->loadGame(gameState);
  541. break;
  542. default:
  543. throw std::runtime_error("Invalid mode");
  544. }
  545. // After everything initialized we can accept CPackToClient netpacks
  546. logicConnection->enterGameplayConnectionMode(client->gameState());
  547. setState(EClientState::GAMEPLAY);
  548. }
  549. void CServerHandler::showHighScoresAndEndGameplay(PlayerColor player, bool victory, const StatisticDataSet & statistic)
  550. {
  551. HighScoreParameter param = HighScore::prepareHighScores(client->gameState(), player, victory);
  552. if(victory && client->gameState()->getStartInfo()->campState)
  553. {
  554. startCampaignScenario(param, client->gameState()->getStartInfo()->campState, statistic);
  555. }
  556. else
  557. {
  558. HighScoreCalculation scenarioHighScores;
  559. scenarioHighScores.parameters.push_back(param);
  560. scenarioHighScores.isCampaign = false;
  561. endGameplay();
  562. GAME->mainmenu()->menu->switchToTab("main");
  563. ENGINE->windows().createAndPushWindow<CHighScoreInputScreen>(victory, scenarioHighScores, statistic);
  564. }
  565. }
  566. void CServerHandler::endGameplay()
  567. {
  568. client->finishGameplay();
  569. // Game is ending
  570. // Tell the network thread to reach a stable state
  571. sendClientDisconnecting();
  572. logNetwork->info("Closed connection.");
  573. client->endGame();
  574. client.reset();
  575. if (GAME->mainmenu())
  576. {
  577. GAME->mainmenu()->enable();
  578. GAME->mainmenu()->playMusic();
  579. GAME->mainmenu()->makeActiveInterface();
  580. }
  581. }
  582. void CServerHandler::restartGameplay()
  583. {
  584. client->finishGameplay();
  585. client->endGame();
  586. client.reset();
  587. logicConnection->enterLobbyConnectionMode();
  588. }
  589. void CServerHandler::startCampaignScenario(HighScoreParameter param, std::shared_ptr<CampaignState> cs, const StatisticDataSet & statistic)
  590. {
  591. std::shared_ptr<CampaignState> ourCampaign = cs;
  592. if (!cs)
  593. ourCampaign = si->campState;
  594. param.campaignName = cs->getNameTranslated();
  595. cs->highscoreParameters.push_back(param);
  596. auto campaignScoreCalculator = std::make_shared<HighScoreCalculation>();
  597. campaignScoreCalculator->isCampaign = true;
  598. campaignScoreCalculator->parameters = cs->highscoreParameters;
  599. endGameplay();
  600. auto & epilogue = ourCampaign->scenario(*ourCampaign->lastScenario()).epilog;
  601. auto finisher = [ourCampaign, campaignScoreCalculator, statistic]()
  602. {
  603. if(ourCampaign->campaignSet != "" && ourCampaign->isCampaignFinished())
  604. {
  605. Settings entry = persistentStorage.write["completedCampaigns"][ourCampaign->getFilename()];
  606. entry->Bool() = true;
  607. }
  608. GAME->mainmenu()->makeActiveInterface();
  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. }