CServerHandler.cpp 24 KB

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