CServerHandler.cpp 24 KB

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