2
0

CServerHandler.cpp 25 KB

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