CServerHandler.cpp 25 KB

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