CServerHandler.cpp 23 KB

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