CServerHandler.cpp 25 KB

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