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