CServerHandler.cpp 26 KB

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