CServerHandler.cpp 25 KB

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