CServerHandler.cpp 24 KB

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