CServerHandler.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937
  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. auto si = std::make_shared<StartInfo>();
  174. auto lastDifficulty = settings["general"]["lastDifficulty"];
  175. si->difficulty = lastDifficulty.Integer();
  176. logNetwork->trace("\tStarting local server");
  177. serverRunner->start(getLocalPort(), connectToLobby, si);
  178. logNetwork->trace("\tConnecting to local server");
  179. connectToServer(getLocalHostname(), getLocalPort());
  180. logNetwork->trace("\tWaiting for connection");
  181. }
  182. void CServerHandler::connectToServer(const std::string & addr, const ui16 port)
  183. {
  184. logNetwork->info("Establishing connection to %s:%d...", addr, port);
  185. setState(EClientState::CONNECTING);
  186. serverHostname = addr;
  187. serverPort = port;
  188. if (!isServerLocal())
  189. {
  190. Settings remoteAddress = settings.write["server"]["remoteHostname"];
  191. remoteAddress->String() = addr;
  192. Settings remotePort = settings.write["server"]["remotePort"];
  193. remotePort->Integer() = port;
  194. }
  195. networkHandler->connectToRemote(*this, addr, port);
  196. }
  197. void CServerHandler::onConnectionFailed(const std::string & errorMessage)
  198. {
  199. assert(getState() == EClientState::CONNECTING);
  200. boost::mutex::scoped_lock interfaceLock(GH.interfaceMutex);
  201. if (isServerLocal())
  202. {
  203. // retry - local server might be still starting up
  204. logNetwork->debug("\nCannot establish connection. %s. Retrying...", errorMessage);
  205. networkHandler->createTimer(*this, std::chrono::milliseconds(100));
  206. }
  207. else
  208. {
  209. // remote server refused connection - show error message
  210. setState(EClientState::NONE);
  211. CInfoWindow::showInfoDialog(CGI->generaltexth->translate("vcmi.mainMenu.serverConnectionFailed"), {});
  212. }
  213. }
  214. void CServerHandler::onTimer()
  215. {
  216. boost::mutex::scoped_lock interfaceLock(GH.interfaceMutex);
  217. if(getState() == EClientState::CONNECTION_CANCELLED)
  218. {
  219. logNetwork->info("Connection aborted by player!");
  220. serverRunner->wait();
  221. serverRunner.reset();
  222. if (GH.windows().topWindow<CSimpleJoinScreen>() != nullptr)
  223. GH.windows().popWindows(1);
  224. return;
  225. }
  226. assert(isServerLocal());
  227. networkHandler->connectToRemote(*this, getLocalHostname(), getLocalPort());
  228. }
  229. void CServerHandler::onConnectionEstablished(const NetworkConnectionPtr & netConnection)
  230. {
  231. assert(getState() == EClientState::CONNECTING);
  232. boost::mutex::scoped_lock interfaceLock(GH.interfaceMutex);
  233. networkConnection = netConnection;
  234. logNetwork->info("Connection established");
  235. if (serverMode == EServerMode::LOBBY_GUEST)
  236. {
  237. // say hello to lobby to switch connection to proxy mode
  238. getGlobalLobby().sendProxyConnectionLogin(netConnection);
  239. }
  240. logicConnection = std::make_shared<CConnection>(netConnection);
  241. logicConnection->uuid = uuid;
  242. logicConnection->enterLobbyConnectionMode();
  243. sendClientConnecting();
  244. }
  245. void CServerHandler::applyPackOnLobbyScreen(CPackForLobby & pack)
  246. {
  247. const CBaseForLobbyApply * apply = applier->getApplier(CTypeList::getInstance().getTypeID(&pack)); //find the applier
  248. apply->applyOnLobbyScreen(dynamic_cast<CLobbyScreen *>(SEL), this, pack);
  249. GH.windows().totalRedraw();
  250. }
  251. std::set<PlayerColor> CServerHandler::getHumanColors()
  252. {
  253. return clientHumanColors(logicConnection->connectionID);
  254. }
  255. PlayerColor CServerHandler::myFirstColor() const
  256. {
  257. return clientFirstColor(logicConnection->connectionID);
  258. }
  259. bool CServerHandler::isMyColor(PlayerColor color) const
  260. {
  261. return isClientColor(logicConnection->connectionID, color);
  262. }
  263. ui8 CServerHandler::myFirstId() const
  264. {
  265. return clientFirstId(logicConnection->connectionID);
  266. }
  267. EClientState CServerHandler::getState() const
  268. {
  269. return state;
  270. }
  271. void CServerHandler::setState(EClientState newState)
  272. {
  273. if (newState == EClientState::CONNECTION_CANCELLED && serverRunner != nullptr)
  274. serverRunner->shutdown();
  275. state = newState;
  276. }
  277. bool CServerHandler::isServerLocal() const
  278. {
  279. return serverRunner != nullptr;
  280. }
  281. bool CServerHandler::isHost() const
  282. {
  283. return logicConnection && hostClientId == logicConnection->connectionID;
  284. }
  285. bool CServerHandler::isGuest() const
  286. {
  287. return !logicConnection || hostClientId != logicConnection->connectionID;
  288. }
  289. const std::string & CServerHandler::getLocalHostname() const
  290. {
  291. return settings["server"]["localHostname"].String();
  292. }
  293. ui16 CServerHandler::getLocalPort() const
  294. {
  295. return settings["server"]["localPort"].Integer();
  296. }
  297. const std::string & CServerHandler::getRemoteHostname() const
  298. {
  299. return settings["server"]["remoteHostname"].String();
  300. }
  301. ui16 CServerHandler::getRemotePort() const
  302. {
  303. return settings["server"]["remotePort"].Integer();
  304. }
  305. const std::string & CServerHandler::getCurrentHostname() const
  306. {
  307. return serverHostname;
  308. }
  309. ui16 CServerHandler::getCurrentPort() const
  310. {
  311. return serverPort;
  312. }
  313. void CServerHandler::sendClientConnecting() const
  314. {
  315. LobbyClientConnected lcc;
  316. lcc.uuid = uuid;
  317. lcc.names = localPlayerNames;
  318. lcc.mode = si->mode;
  319. sendLobbyPack(lcc);
  320. }
  321. void CServerHandler::sendClientDisconnecting()
  322. {
  323. // FIXME: This is workaround needed to make sure client not trying to sent anything to non existed server
  324. if(getState() == EClientState::DISCONNECTING)
  325. {
  326. assert(0);
  327. return;
  328. }
  329. setState(EClientState::DISCONNECTING);
  330. mapToStart = nullptr;
  331. LobbyClientDisconnected lcd;
  332. lcd.clientId = logicConnection->connectionID;
  333. logNetwork->info("Connection has been requested to be closed.");
  334. if(isServerLocal())
  335. {
  336. lcd.shutdownServer = true;
  337. logNetwork->info("Sent closing signal to the server");
  338. }
  339. else
  340. {
  341. logNetwork->info("Sent leaving signal to the server");
  342. }
  343. sendLobbyPack(lcd);
  344. networkConnection->close();
  345. networkConnection.reset();
  346. logicConnection.reset();
  347. }
  348. void CServerHandler::setCampaignState(std::shared_ptr<CampaignState> newCampaign)
  349. {
  350. setState(EClientState::LOBBY_CAMPAIGN);
  351. LobbySetCampaign lsc;
  352. lsc.ourCampaign = newCampaign;
  353. sendLobbyPack(lsc);
  354. }
  355. void CServerHandler::setCampaignMap(CampaignScenarioID mapId) const
  356. {
  357. if(getState() == EClientState::GAMEPLAY) // FIXME: UI shouldn't sent commands in first place
  358. return;
  359. LobbySetCampaignMap lscm;
  360. lscm.mapId = mapId;
  361. sendLobbyPack(lscm);
  362. }
  363. void CServerHandler::setCampaignBonus(int bonusId) const
  364. {
  365. if(getState() == EClientState::GAMEPLAY) // FIXME: UI shouldn't sent commands in first place
  366. return;
  367. LobbySetCampaignBonus lscb;
  368. lscb.bonusId = bonusId;
  369. sendLobbyPack(lscb);
  370. }
  371. void CServerHandler::setMapInfo(std::shared_ptr<CMapInfo> to, std::shared_ptr<CMapGenOptions> mapGenOpts) const
  372. {
  373. LobbySetMap lsm;
  374. lsm.mapInfo = to;
  375. lsm.mapGenOpts = mapGenOpts;
  376. sendLobbyPack(lsm);
  377. }
  378. void CServerHandler::setPlayer(PlayerColor color) const
  379. {
  380. LobbySetPlayer lsp;
  381. lsp.clickedColor = color;
  382. sendLobbyPack(lsp);
  383. }
  384. void CServerHandler::setPlayerName(PlayerColor color, const std::string & name) const
  385. {
  386. LobbySetPlayerName lspn;
  387. lspn.color = color;
  388. lspn.name = name;
  389. sendLobbyPack(lspn);
  390. }
  391. void CServerHandler::setPlayerOption(ui8 what, int32_t value, PlayerColor player) const
  392. {
  393. LobbyChangePlayerOption lcpo;
  394. lcpo.what = what;
  395. lcpo.value = value;
  396. lcpo.color = player;
  397. sendLobbyPack(lcpo);
  398. }
  399. void CServerHandler::setDifficulty(int to) const
  400. {
  401. LobbySetDifficulty lsd;
  402. lsd.difficulty = to;
  403. sendLobbyPack(lsd);
  404. }
  405. void CServerHandler::setSimturnsInfo(const SimturnsInfo & info) const
  406. {
  407. LobbySetSimturns pack;
  408. pack.simturnsInfo = info;
  409. sendLobbyPack(pack);
  410. }
  411. void CServerHandler::setTurnTimerInfo(const TurnTimerInfo & info) const
  412. {
  413. LobbySetTurnTime lstt;
  414. lstt.turnTimerInfo = info;
  415. sendLobbyPack(lstt);
  416. }
  417. void CServerHandler::setExtraOptionsInfo(const ExtraOptionsInfo & info) const
  418. {
  419. LobbySetExtraOptions lseo;
  420. lseo.extraOptionsInfo = info;
  421. sendLobbyPack(lseo);
  422. }
  423. void CServerHandler::sendMessage(const std::string & txt) const
  424. {
  425. std::istringstream readed;
  426. readed.str(txt);
  427. std::string command;
  428. readed >> command;
  429. if(command == "!passhost")
  430. {
  431. std::string id;
  432. readed >> id;
  433. if(id.length())
  434. {
  435. LobbyChangeHost lch;
  436. lch.newHostConnectionId = boost::lexical_cast<int>(id);
  437. sendLobbyPack(lch);
  438. }
  439. }
  440. else if(command == "!forcep")
  441. {
  442. std::string connectedId;
  443. std::string playerColorId;
  444. readed >> connectedId;
  445. readed >> playerColorId;
  446. if(connectedId.length() && playerColorId.length())
  447. {
  448. ui8 connected = boost::lexical_cast<int>(connectedId);
  449. auto color = PlayerColor(boost::lexical_cast<int>(playerColorId));
  450. if(color.isValidPlayer() && playerNames.find(connected) != playerNames.end())
  451. {
  452. LobbyForceSetPlayer lfsp;
  453. lfsp.targetConnectedPlayer = connected;
  454. lfsp.targetPlayerColor = color;
  455. sendLobbyPack(lfsp);
  456. }
  457. }
  458. }
  459. else
  460. {
  461. LobbyChatMessage lcm;
  462. lcm.message = txt;
  463. lcm.playerName = playerNames.find(myFirstId())->second.name;
  464. sendLobbyPack(lcm);
  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. GH.windows().createAndPushWindow<CLoadingScreen>();
  476. LobbyRestartGame endGame;
  477. sendLobbyPack(endGame);
  478. }
  479. bool CServerHandler::validateGameStart(bool allowOnlyAI) const
  480. {
  481. try
  482. {
  483. verifyStateBeforeStart(allowOnlyAI ? true : settings["session"]["onlyai"].Bool());
  484. }
  485. catch(ModIncompatibility & e)
  486. {
  487. logGlobal->warn("Incompatibility exception during start scenario: %s", e.what());
  488. std::string errorMsg;
  489. if(!e.whatMissing().empty())
  490. {
  491. errorMsg += VLC->generaltexth->translate("vcmi.server.errors.modsToEnable") + '\n';
  492. errorMsg += e.whatMissing();
  493. }
  494. if(!e.whatExcessive().empty())
  495. {
  496. errorMsg += VLC->generaltexth->translate("vcmi.server.errors.modsToDisable") + '\n';
  497. errorMsg += e.whatExcessive();
  498. }
  499. showServerError(errorMsg);
  500. return false;
  501. }
  502. catch(std::exception & e)
  503. {
  504. logGlobal->error("Exception during startScenario: %s", e.what());
  505. showServerError( std::string("Unable to start map! Reason: ") + e.what());
  506. return false;
  507. }
  508. return true;
  509. }
  510. void CServerHandler::sendStartGame(bool allowOnlyAI) const
  511. {
  512. verifyStateBeforeStart(allowOnlyAI ? true : settings["session"]["onlyai"].Bool());
  513. if(!settings["session"]["headless"].Bool())
  514. GH.windows().createAndPushWindow<CLoadingScreen>();
  515. LobbyPrepareStartGame lpsg;
  516. sendLobbyPack(lpsg);
  517. LobbyStartGame lsg;
  518. if(client)
  519. {
  520. lsg.initializedStartInfo = std::make_shared<StartInfo>(* const_cast<StartInfo *>(client->getStartInfo(true)));
  521. lsg.initializedStartInfo->mode = EStartMode::NEW_GAME;
  522. lsg.initializedStartInfo->seedToBeUsed = lsg.initializedStartInfo->seedPostInit = 0;
  523. * si = * lsg.initializedStartInfo;
  524. }
  525. sendLobbyPack(lsg);
  526. }
  527. void CServerHandler::startMapAfterConnection(std::shared_ptr<CMapInfo> to)
  528. {
  529. mapToStart = to;
  530. }
  531. void CServerHandler::startGameplay(VCMI_LIB_WRAP_NAMESPACE(CGameState) * gameState)
  532. {
  533. if(CMM)
  534. CMM->disable();
  535. highScoreCalc = nullptr;
  536. switch(si->mode)
  537. {
  538. case EStartMode::NEW_GAME:
  539. client->newGame(gameState);
  540. break;
  541. case EStartMode::CAMPAIGN:
  542. client->newGame(gameState);
  543. break;
  544. case EStartMode::LOAD_GAME:
  545. client->loadGame(gameState);
  546. break;
  547. default:
  548. throw std::runtime_error("Invalid mode");
  549. }
  550. // After everything initialized we can accept CPackToClient netpacks
  551. logicConnection->enterGameplayConnectionMode(client->gameState());
  552. setState(EClientState::GAMEPLAY);
  553. }
  554. void CServerHandler::endGameplay()
  555. {
  556. // Game is ending
  557. // Tell the network thread to reach a stable state
  558. CSH->sendClientDisconnecting();
  559. logNetwork->info("Closed connection.");
  560. client->endGame();
  561. client.reset();
  562. if(CMM)
  563. {
  564. GH.curInt = CMM.get();
  565. CMM->enable();
  566. }
  567. else
  568. {
  569. GH.curInt = CMainMenu::create().get();
  570. }
  571. }
  572. void CServerHandler::restartGameplay()
  573. {
  574. client->endGame();
  575. client.reset();
  576. logicConnection->enterLobbyConnectionMode();
  577. }
  578. void CServerHandler::startCampaignScenario(HighScoreParameter param, std::shared_ptr<CampaignState> cs)
  579. {
  580. std::shared_ptr<CampaignState> ourCampaign = cs;
  581. if (!cs)
  582. ourCampaign = si->campState;
  583. if(highScoreCalc == nullptr)
  584. {
  585. highScoreCalc = std::make_shared<HighScoreCalculation>();
  586. highScoreCalc->isCampaign = true;
  587. highScoreCalc->parameters.clear();
  588. }
  589. param.campaignName = cs->getNameTranslated();
  590. highScoreCalc->parameters.push_back(param);
  591. GH.dispatchMainThread([ourCampaign, this]()
  592. {
  593. CSH->endGameplay();
  594. auto & epilogue = ourCampaign->scenario(*ourCampaign->lastScenario()).epilog;
  595. auto finisher = [=]()
  596. {
  597. if(ourCampaign->campaignSet != "" && ourCampaign->isCampaignFinished())
  598. {
  599. Settings entry = persistentStorage.write["completedCampaigns"][ourCampaign->getFilename()];
  600. entry->Bool() = true;
  601. }
  602. GH.windows().pushWindow(CMM);
  603. GH.windows().pushWindow(CMM->menu);
  604. if(!ourCampaign->isCampaignFinished())
  605. CMM->openCampaignLobby(ourCampaign);
  606. else
  607. {
  608. CMM->openCampaignScreen(ourCampaign->campaignSet);
  609. GH.windows().createAndPushWindow<CHighScoreInputScreen>(true, *highScoreCalc);
  610. }
  611. };
  612. if(epilogue.hasPrologEpilog)
  613. {
  614. GH.windows().createAndPushWindow<CPrologEpilogVideo>(epilogue, finisher);
  615. }
  616. else
  617. {
  618. finisher();
  619. }
  620. });
  621. }
  622. void CServerHandler::showServerError(const std::string & txt) const
  623. {
  624. if(auto w = GH.windows().topWindow<CLoadingScreen>())
  625. GH.windows().popWindow(w);
  626. CInfoWindow::showInfoDialog(txt, {});
  627. }
  628. int CServerHandler::howManyPlayerInterfaces()
  629. {
  630. int playerInts = 0;
  631. for(auto pint : client->playerint)
  632. {
  633. if(dynamic_cast<CPlayerInterface *>(pint.second.get()))
  634. playerInts++;
  635. }
  636. return playerInts;
  637. }
  638. ELoadMode CServerHandler::getLoadMode()
  639. {
  640. if(loadMode != ELoadMode::TUTORIAL && getState() == EClientState::GAMEPLAY)
  641. {
  642. if(si->campState)
  643. return ELoadMode::CAMPAIGN;
  644. for(auto pn : playerNames)
  645. {
  646. if(pn.second.connection != logicConnection->connectionID)
  647. return ELoadMode::MULTI;
  648. }
  649. if(howManyPlayerInterfaces() > 1) //this condition will work for hotseat mode OR multiplayer with allowed more than 1 color per player to control
  650. return ELoadMode::MULTI;
  651. return ELoadMode::SINGLE;
  652. }
  653. return loadMode;
  654. }
  655. void CServerHandler::debugStartTest(std::string filename, bool save)
  656. {
  657. logGlobal->info("Starting debug test with file: %s", filename);
  658. auto mapInfo = std::make_shared<CMapInfo>();
  659. if(save)
  660. {
  661. resetStateForLobby(EStartMode::LOAD_GAME, ESelectionScreen::loadGame, EServerMode::LOCAL, {});
  662. mapInfo->saveInit(ResourcePath(filename, EResType::SAVEGAME));
  663. }
  664. else
  665. {
  666. resetStateForLobby(EStartMode::NEW_GAME, ESelectionScreen::newGame, EServerMode::LOCAL, {});
  667. mapInfo->mapInit(filename);
  668. }
  669. if(settings["session"]["donotstartserver"].Bool())
  670. connectToServer(getLocalHostname(), getLocalPort());
  671. else
  672. startLocalServerAndConnect(false);
  673. boost::this_thread::sleep_for(boost::chrono::milliseconds(100));
  674. while(!settings["session"]["headless"].Bool() && !GH.windows().topWindow<CLobbyScreen>())
  675. boost::this_thread::sleep_for(boost::chrono::milliseconds(50));
  676. while(!mi || mapInfo->fileURI != CSH->mi->fileURI)
  677. {
  678. setMapInfo(mapInfo);
  679. boost::this_thread::sleep_for(boost::chrono::milliseconds(50));
  680. }
  681. // "Click" on color to remove us from it
  682. setPlayer(myFirstColor());
  683. while(myFirstColor() != PlayerColor::CANNOT_DETERMINE)
  684. boost::this_thread::sleep_for(boost::chrono::milliseconds(50));
  685. while(true)
  686. {
  687. try
  688. {
  689. sendStartGame();
  690. break;
  691. }
  692. catch(...)
  693. {
  694. }
  695. boost::this_thread::sleep_for(boost::chrono::milliseconds(50));
  696. }
  697. }
  698. class ServerHandlerCPackVisitor : public VCMI_LIB_WRAP_NAMESPACE(ICPackVisitor)
  699. {
  700. private:
  701. CServerHandler & handler;
  702. public:
  703. ServerHandlerCPackVisitor(CServerHandler & handler)
  704. :handler(handler)
  705. {
  706. }
  707. bool callTyped() override { return false; }
  708. void visitForLobby(CPackForLobby & lobbyPack) override
  709. {
  710. handler.visitForLobby(lobbyPack);
  711. }
  712. void visitForClient(CPackForClient & clientPack) override
  713. {
  714. handler.visitForClient(clientPack);
  715. }
  716. };
  717. void CServerHandler::onPacketReceived(const std::shared_ptr<INetworkConnection> &, const std::vector<std::byte> & message)
  718. {
  719. boost::mutex::scoped_lock interfaceLock(GH.interfaceMutex);
  720. if(getState() == EClientState::DISCONNECTING)
  721. return;
  722. CPack * pack = logicConnection->retrievePack(message);
  723. ServerHandlerCPackVisitor visitor(*this);
  724. pack->visit(visitor);
  725. }
  726. void CServerHandler::onDisconnected(const std::shared_ptr<INetworkConnection> & connection, const std::string & errorMessage)
  727. {
  728. waitForServerShutdown();
  729. if(getState() == EClientState::DISCONNECTING)
  730. {
  731. assert(networkConnection == nullptr);
  732. // Note: this branch can be reached on app shutdown, when main thread holds mutex till destruction
  733. logNetwork->info("Successfully closed connection to server!");
  734. return;
  735. }
  736. boost::mutex::scoped_lock interfaceLock(GH.interfaceMutex);
  737. logNetwork->error("Lost connection to server! Connection has been closed");
  738. if(client)
  739. {
  740. CSH->endGameplay();
  741. GH.defActionsDef = 63;
  742. CMM->menu->switchToTab("main");
  743. CSH->showServerError(CGI->generaltexth->translate("vcmi.server.errors.disconnected"));
  744. }
  745. else
  746. {
  747. LobbyClientDisconnected lcd;
  748. lcd.clientId = logicConnection->connectionID;
  749. applyPackOnLobbyScreen(lcd);
  750. }
  751. networkConnection.reset();
  752. }
  753. void CServerHandler::waitForServerShutdown()
  754. {
  755. if (!serverRunner)
  756. return; // may not exist for guest in MP
  757. serverRunner->wait();
  758. int exitCode = serverRunner->exitCode();
  759. serverRunner.reset();
  760. if (exitCode == 0)
  761. {
  762. logNetwork->info("Server closed correctly");
  763. }
  764. else
  765. {
  766. boost::mutex::scoped_lock interfaceLock(GH.interfaceMutex);
  767. if (getState() == EClientState::CONNECTING)
  768. {
  769. showServerError(CGI->generaltexth->translate("vcmi.server.errors.existingProcess"));
  770. setState(EClientState::CONNECTION_CANCELLED); // stop attempts to reconnect
  771. }
  772. logNetwork->error("Error: server failed to close correctly or crashed!");
  773. logNetwork->error("Check log file for more info");
  774. }
  775. serverRunner.reset();
  776. }
  777. void CServerHandler::visitForLobby(CPackForLobby & lobbyPack)
  778. {
  779. if(applier->getApplier(CTypeList::getInstance().getTypeID(&lobbyPack))->applyOnLobbyHandler(this, lobbyPack))
  780. {
  781. if(!settings["session"]["headless"].Bool())
  782. applyPackOnLobbyScreen(lobbyPack);
  783. }
  784. }
  785. void CServerHandler::visitForClient(CPackForClient & clientPack)
  786. {
  787. client->handlePack(&clientPack);
  788. }
  789. void CServerHandler::sendLobbyPack(const CPackForLobby & pack) const
  790. {
  791. if(getState() != EClientState::STARTING)
  792. logicConnection->sendPack(&pack);
  793. }
  794. bool CServerHandler::inLobbyRoom() const
  795. {
  796. return CSH->serverMode == EServerMode::LOBBY_HOST || CSH->serverMode == EServerMode::LOBBY_GUEST;
  797. }
  798. bool CServerHandler::inGame() const
  799. {
  800. return logicConnection != nullptr;
  801. }