CServerHandler.cpp 24 KB

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