2
0

CVCMIServer.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083
  1. /*
  2. * CVCMIServer.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 "CVCMIServer.h"
  12. #include "CGameHandler.h"
  13. #include "GlobalLobbyProcessor.h"
  14. #include "LobbyNetPackVisitors.h"
  15. #include "processors/PlayerMessageProcessor.h"
  16. #include "../lib/CHeroHandler.h"
  17. #include "../lib/CPlayerState.h"
  18. #include "../lib/campaign/CampaignState.h"
  19. #include "../lib/gameState/CGameState.h"
  20. #include "../lib/mapping/CMapDefines.h"
  21. #include "../lib/mapping/CMapInfo.h"
  22. #include "../lib/mapping/CMapHeader.h"
  23. #include "../lib/rmg/CMapGenOptions.h"
  24. #include "../lib/serializer/CMemorySerializer.h"
  25. #include "../lib/serializer/Connection.h"
  26. #include "../lib/texts/CGeneralTextHandler.h"
  27. // UUID generation
  28. #include <boost/uuid/uuid.hpp>
  29. #include <boost/uuid/uuid_io.hpp>
  30. #include <boost/uuid/uuid_generators.hpp>
  31. #include <boost/program_options.hpp>
  32. class CVCMIServerPackVisitor : public VCMI_LIB_WRAP_NAMESPACE(ICPackVisitor)
  33. {
  34. private:
  35. CVCMIServer & handler;
  36. std::shared_ptr<CGameHandler> gh;
  37. public:
  38. CVCMIServerPackVisitor(CVCMIServer & handler, std::shared_ptr<CGameHandler> gh)
  39. :handler(handler), gh(gh)
  40. {
  41. }
  42. bool callTyped() override { return false; }
  43. void visitForLobby(CPackForLobby & packForLobby) override
  44. {
  45. handler.handleReceivedPack(std::unique_ptr<CPackForLobby>(&packForLobby));
  46. }
  47. void visitForServer(CPackForServer & serverPack) override
  48. {
  49. if (gh)
  50. gh->handleReceivedPack(&serverPack);
  51. else
  52. logNetwork->error("Received pack for game server while in lobby!");
  53. }
  54. void visitForClient(CPackForClient & clientPack) override
  55. {
  56. }
  57. };
  58. CVCMIServer::CVCMIServer(uint16_t port, bool runByClient)
  59. : currentClientId(1)
  60. , currentPlayerId(1)
  61. , port(port)
  62. , runByClient(runByClient)
  63. {
  64. uuid = boost::uuids::to_string(boost::uuids::random_generator()());
  65. logNetwork->trace("CVCMIServer created! UUID: %s", uuid);
  66. networkHandler = INetworkHandler::createHandler();
  67. }
  68. CVCMIServer::~CVCMIServer() = default;
  69. uint16_t CVCMIServer::prepare(bool connectToLobby) {
  70. if(connectToLobby) {
  71. lobbyProcessor = std::make_unique<GlobalLobbyProcessor>(*this);
  72. return 0;
  73. } else {
  74. return startAcceptingIncomingConnections();
  75. }
  76. }
  77. uint16_t CVCMIServer::startAcceptingIncomingConnections()
  78. {
  79. port
  80. ? logNetwork->info("Port %d will be used", port)
  81. : logNetwork->info("Randomly assigned port will be used");
  82. // config port may be 0 => srvport will contain the OS-assigned port value
  83. networkServer = networkHandler->createServerTCP(*this);
  84. auto srvport = networkServer->start(port);
  85. logNetwork->info("Listening for connections at port %d", srvport);
  86. return srvport;
  87. }
  88. void CVCMIServer::onNewConnection(const std::shared_ptr<INetworkConnection> & connection)
  89. {
  90. if(getState() == EServerState::LOBBY)
  91. {
  92. activeConnections.push_back(std::make_shared<CConnection>(connection));
  93. activeConnections.back()->enterLobbyConnectionMode();
  94. }
  95. else
  96. {
  97. // TODO: reconnection support
  98. connection->close();
  99. }
  100. }
  101. void CVCMIServer::onPacketReceived(const std::shared_ptr<INetworkConnection> & connection, const std::vector<std::byte> & message)
  102. {
  103. std::shared_ptr<CConnection> c = findConnection(connection);
  104. if (c == nullptr)
  105. throw std::out_of_range("Unknown connection received in CVCMIServer::findConnection");
  106. auto pack = c->retrievePack(message);
  107. pack->c = c;
  108. CVCMIServerPackVisitor visitor(*this, this->gh);
  109. pack->visit(visitor);
  110. }
  111. void CVCMIServer::setState(EServerState value)
  112. {
  113. if (value == EServerState::SHUTDOWN && state == EServerState::SHUTDOWN)
  114. logGlobal->warn("Attempt to shutdown already shutdown server!");
  115. // do not attempt to restart dying server
  116. assert(state != EServerState::SHUTDOWN || state == value);
  117. state = value;
  118. if (state == EServerState::SHUTDOWN)
  119. networkHandler->stop();
  120. }
  121. EServerState CVCMIServer::getState() const
  122. {
  123. return state;
  124. }
  125. std::shared_ptr<CConnection> CVCMIServer::findConnection(const std::shared_ptr<INetworkConnection> & netConnection)
  126. {
  127. for(const auto & gameConnection : activeConnections)
  128. {
  129. if (gameConnection->isMyConnection(netConnection))
  130. return gameConnection;
  131. }
  132. return nullptr;
  133. }
  134. bool CVCMIServer::wasStartedByClient() const
  135. {
  136. return runByClient;
  137. }
  138. void CVCMIServer::run()
  139. {
  140. networkHandler->run();
  141. }
  142. void CVCMIServer::onTimer()
  143. {
  144. // we might receive onTimer call after transitioning from GAMEPLAY to LOBBY state, e.g. on game restart
  145. if (getState() != EServerState::GAMEPLAY)
  146. return;
  147. static const auto serverUpdateInterval = std::chrono::milliseconds(100);
  148. auto timeNow = std::chrono::steady_clock::now();
  149. auto timePassedBefore = lastTimerUpdateTime - gameplayStartTime;
  150. auto timePassedNow = timeNow - gameplayStartTime;
  151. lastTimerUpdateTime = timeNow;
  152. auto msPassedBefore = std::chrono::duration_cast<std::chrono::milliseconds>(timePassedBefore);
  153. auto msPassedNow = std::chrono::duration_cast<std::chrono::milliseconds>(timePassedNow);
  154. auto msDelta = msPassedNow - msPassedBefore;
  155. if (msDelta.count())
  156. gh->tick(msDelta.count());
  157. networkHandler->createTimer(*this, serverUpdateInterval);
  158. }
  159. void CVCMIServer::prepareToRestart()
  160. {
  161. if(getState() != EServerState::GAMEPLAY)
  162. {
  163. assert(0);
  164. return;
  165. }
  166. * si = * gh->gs->initialOpts;
  167. setState(EServerState::LOBBY);
  168. if (si->campState)
  169. {
  170. assert(si->campState->currentScenario().has_value());
  171. campaignMap = si->campState->currentScenario().value_or(CampaignScenarioID(0));
  172. campaignBonus = si->campState->getBonusID(campaignMap).value_or(-1);
  173. }
  174. for(auto activeConnection : activeConnections)
  175. activeConnection->enterLobbyConnectionMode();
  176. gh = nullptr;
  177. }
  178. bool CVCMIServer::prepareToStartGame()
  179. {
  180. Load::ProgressAccumulator progressTracking;
  181. Load::Progress current(1);
  182. progressTracking.include(current);
  183. if (lobbyProcessor)
  184. lobbyProcessor->sendGameStarted();
  185. auto progressTrackingThread = boost::thread([this, &progressTracking]()
  186. {
  187. auto currentProgress = std::numeric_limits<Load::Type>::max();
  188. while(!progressTracking.finished())
  189. {
  190. if(progressTracking.get() != currentProgress)
  191. {
  192. //FIXME: UNGUARDED MULTITHREADED ACCESS!!!
  193. currentProgress = progressTracking.get();
  194. std::unique_ptr<LobbyLoadProgress> loadProgress(new LobbyLoadProgress);
  195. loadProgress->progress = currentProgress;
  196. announcePack(std::move(loadProgress));
  197. }
  198. boost::this_thread::sleep(boost::posix_time::milliseconds(50));
  199. }
  200. });
  201. gh = std::make_shared<CGameHandler>(this);
  202. switch(si->mode)
  203. {
  204. case EStartMode::CAMPAIGN:
  205. logNetwork->info("Preparing to start new campaign");
  206. si->startTimeIso8601 = vstd::getDateTimeISO8601Basic(std::time(nullptr));
  207. si->fileURI = mi->fileURI;
  208. si->campState->setCurrentMap(campaignMap);
  209. si->campState->setCurrentMapBonus(campaignBonus);
  210. gh->init(si.get(), progressTracking);
  211. break;
  212. case EStartMode::NEW_GAME:
  213. logNetwork->info("Preparing to start new game");
  214. si->startTimeIso8601 = vstd::getDateTimeISO8601Basic(std::time(nullptr));
  215. si->fileURI = mi->fileURI;
  216. gh->init(si.get(), progressTracking);
  217. break;
  218. case EStartMode::LOAD_GAME:
  219. logNetwork->info("Preparing to start loaded game");
  220. if(!gh->load(si->mapname))
  221. {
  222. current.finish();
  223. progressTrackingThread.join();
  224. return false;
  225. }
  226. break;
  227. default:
  228. logNetwork->error("Wrong mode in StartInfo!");
  229. assert(0);
  230. break;
  231. }
  232. current.finish();
  233. progressTrackingThread.join();
  234. return true;
  235. }
  236. void CVCMIServer::startGameImmediately()
  237. {
  238. for(auto activeConnection : activeConnections)
  239. activeConnection->enterGameplayConnectionMode(gh->gs);
  240. gh->start(si->mode == EStartMode::LOAD_GAME);
  241. setState(EServerState::GAMEPLAY);
  242. lastTimerUpdateTime = gameplayStartTime = std::chrono::steady_clock::now();
  243. onTimer();
  244. multiplayerWelcomeMessage();
  245. }
  246. void CVCMIServer::onDisconnected(const std::shared_ptr<INetworkConnection> & connection, const std::string & errorMessage)
  247. {
  248. logNetwork->error("Network error receiving a pack. Connection has been closed");
  249. std::shared_ptr<CConnection> c = findConnection(connection);
  250. // player may have already disconnected via clientDisconnected call
  251. if (c)
  252. {
  253. //clientDisconnected(c);
  254. if(gh && getState() == EServerState::GAMEPLAY)
  255. {
  256. auto lcd = std::make_unique<LobbyClientDisconnected>();
  257. lcd->c = c;
  258. lcd->clientId = c->connectionID;
  259. handleReceivedPack(std::move(lcd));
  260. }
  261. }
  262. }
  263. void CVCMIServer::handleReceivedPack(std::unique_ptr<CPackForLobby> pack)
  264. {
  265. ClientPermissionsCheckerNetPackVisitor checker(*this);
  266. pack->visit(checker);
  267. if(checker.getResult())
  268. {
  269. ApplyOnServerNetPackVisitor applier(*this);
  270. pack->visit(applier);
  271. if (applier.getResult())
  272. announcePack(std::move(pack));
  273. }
  274. }
  275. void CVCMIServer::announcePack(std::unique_ptr<CPackForLobby> pack)
  276. {
  277. for(auto activeConnection : activeConnections)
  278. {
  279. // FIXME: we need to avoid sending something to client that not yet get answer for LobbyClientConnected
  280. // Until UUID set we only pass LobbyClientConnected to this client
  281. //if(c->uuid == uuid && !dynamic_cast<LobbyClientConnected *>(pack.get()))
  282. // continue;
  283. activeConnection->sendPack(pack.get());
  284. }
  285. ApplyOnServerAfterAnnounceNetPackVisitor applier(*this);
  286. pack->visit(applier);
  287. }
  288. void CVCMIServer::announceMessage(const MetaString & txt)
  289. {
  290. logNetwork->info("Show message: %s", txt.toString());
  291. auto cm = std::make_unique<LobbyShowMessage>();
  292. cm->message = txt;
  293. announcePack(std::move(cm));
  294. }
  295. void CVCMIServer::announceMessage(const std::string & txt)
  296. {
  297. MetaString str;
  298. str.appendRawString(txt);
  299. announceMessage(str);
  300. }
  301. void CVCMIServer::announceTxt(const MetaString & txt, const std::string & playerName)
  302. {
  303. logNetwork->info("%s says: %s", playerName, txt.toString());
  304. auto cm = std::make_unique<LobbyChatMessage>();
  305. cm->playerName = playerName;
  306. cm->message = txt;
  307. announcePack(std::move(cm));
  308. }
  309. void CVCMIServer::announceTxt(const std::string & txt, const std::string & playerName)
  310. {
  311. MetaString str;
  312. str.appendRawString(txt);
  313. announceTxt(str, playerName);
  314. }
  315. bool CVCMIServer::passHost(int toConnectionId)
  316. {
  317. for(auto activeConnection : activeConnections)
  318. {
  319. if(isClientHost(activeConnection->connectionID))
  320. continue;
  321. if(activeConnection->connectionID != toConnectionId)
  322. continue;
  323. hostClientId = activeConnection->connectionID;
  324. announceTxt(boost::str(boost::format("Pass host to connection %d") % toConnectionId));
  325. return true;
  326. }
  327. return false;
  328. }
  329. void CVCMIServer::clientConnected(std::shared_ptr<CConnection> c, std::vector<std::string> & names, const std::string & uuid, EStartMode mode)
  330. {
  331. assert(getState() == EServerState::LOBBY);
  332. c->connectionID = currentClientId++;
  333. if(hostClientId == -1)
  334. {
  335. hostClientId = c->connectionID;
  336. si->mode = mode;
  337. }
  338. logNetwork->info("Connection with client %d established. UUID: %s", c->connectionID, c->uuid);
  339. for(auto & name : names)
  340. {
  341. logNetwork->info("Client %d player: %s", c->connectionID, name);
  342. ui8 id = currentPlayerId++;
  343. ClientPlayer cp;
  344. cp.connection = c->connectionID;
  345. cp.name = name;
  346. playerNames.insert(std::make_pair(id, cp));
  347. announceTxt(boost::str(boost::format("%s (pid %d cid %d) joins the game") % name % id % c->connectionID));
  348. //put new player in first slot with AI
  349. for(auto & elem : si->playerInfos)
  350. {
  351. if(elem.second.isControlledByAI() && !elem.second.compOnly)
  352. {
  353. setPlayerConnectedId(elem.second, id);
  354. break;
  355. }
  356. }
  357. }
  358. }
  359. void CVCMIServer::clientDisconnected(std::shared_ptr<CConnection> connection)
  360. {
  361. assert(vstd::contains(activeConnections, connection));
  362. logGlobal->trace("Received disconnection request");
  363. vstd::erase(activeConnections, connection);
  364. if(activeConnections.empty() || hostClientId == connection->connectionID)
  365. {
  366. setState(EServerState::SHUTDOWN);
  367. return;
  368. }
  369. if(gh && getState() == EServerState::GAMEPLAY)
  370. {
  371. gh->handleClientDisconnection(connection);
  372. }
  373. // PlayerReinitInterface startAiPack;
  374. // startAiPack.playerConnectionId = PlayerSettings::PLAYER_AI;
  375. //
  376. // for(auto it = playerNames.begin(); it != playerNames.end();)
  377. // {
  378. // if(it->second.connection != c->connectionID)
  379. // {
  380. // ++it;
  381. // continue;
  382. // }
  383. //
  384. // int id = it->first;
  385. // std::string playerLeftMsgText = boost::str(boost::format("%s (pid %d cid %d) left the game") % id % playerNames[id].name % c->connectionID);
  386. // announceTxt(playerLeftMsgText); //send lobby text, it will be ignored for non-lobby clients
  387. // auto * playerSettings = si->getPlayersSettings(id);
  388. // if(!playerSettings)
  389. // {
  390. // ++it;
  391. // continue;
  392. // }
  393. //
  394. // it = playerNames.erase(it);
  395. // setPlayerConnectedId(*playerSettings, PlayerSettings::PLAYER_AI);
  396. //
  397. // if(gh && si && state == EServerState::GAMEPLAY)
  398. // {
  399. // gh->playerMessages->broadcastMessage(playerSettings->color, playerLeftMsgText);
  400. // // gh->connections[playerSettings->color].insert(hostClient);
  401. // startAiPack.players.push_back(playerSettings->color);
  402. // }
  403. // }
  404. //
  405. // if(!startAiPack.players.empty())
  406. // gh->sendAndApply(&startAiPack);
  407. }
  408. void CVCMIServer::reconnectPlayer(int connId)
  409. {
  410. PlayerReinitInterface startAiPack;
  411. startAiPack.playerConnectionId = connId;
  412. if(gh && si && getState() == EServerState::GAMEPLAY)
  413. {
  414. for(auto it = playerNames.begin(); it != playerNames.end(); ++it)
  415. {
  416. if(it->second.connection != connId)
  417. continue;
  418. int id = it->first;
  419. auto * playerSettings = si->getPlayersSettings(id);
  420. if(!playerSettings)
  421. continue;
  422. std::string messageText = boost::str(boost::format("%s (cid %d) is connected") % playerSettings->name % connId);
  423. gh->playerMessages->broadcastMessage(playerSettings->color, messageText);
  424. startAiPack.players.push_back(playerSettings->color);
  425. }
  426. if(!startAiPack.players.empty())
  427. gh->sendAndApply(&startAiPack);
  428. }
  429. }
  430. void CVCMIServer::setPlayerConnectedId(PlayerSettings & pset, ui8 player) const
  431. {
  432. if(vstd::contains(playerNames, player))
  433. pset.name = playerNames.find(player)->second.name;
  434. else
  435. pset.name = VLC->generaltexth->allTexts[468]; //Computer
  436. pset.connectedPlayerIDs.clear();
  437. if(player != PlayerSettings::PLAYER_AI)
  438. pset.connectedPlayerIDs.insert(player);
  439. }
  440. void CVCMIServer::updateStartInfoOnMapChange(std::shared_ptr<CMapInfo> mapInfo, std::shared_ptr<CMapGenOptions> mapGenOpts)
  441. {
  442. mi = mapInfo;
  443. if(!mi)
  444. return;
  445. auto namesIt = playerNames.cbegin();
  446. si->playerInfos.clear();
  447. if(mi->scenarioOptionsOfSave)
  448. {
  449. si = CMemorySerializer::deepCopy(*mi->scenarioOptionsOfSave);
  450. si->mode = EStartMode::LOAD_GAME;
  451. if(si->campState)
  452. campaignMap = si->campState->currentScenario().value();
  453. for(auto & ps : si->playerInfos)
  454. {
  455. if(!ps.second.compOnly && ps.second.connectedPlayerIDs.size() && namesIt != playerNames.cend())
  456. {
  457. setPlayerConnectedId(ps.second, namesIt++->first);
  458. }
  459. else
  460. {
  461. setPlayerConnectedId(ps.second, PlayerSettings::PLAYER_AI);
  462. }
  463. }
  464. }
  465. else if(si->mode == EStartMode::NEW_GAME || si->mode == EStartMode::CAMPAIGN)
  466. {
  467. if(mi->campaign)
  468. return;
  469. for(int i = 0; i < mi->mapHeader->players.size(); i++)
  470. {
  471. const PlayerInfo & pinfo = mi->mapHeader->players[i];
  472. //neither computer nor human can play - no player
  473. if(!(pinfo.canHumanPlay || pinfo.canComputerPlay))
  474. continue;
  475. PlayerSettings & pset = si->playerInfos[PlayerColor(i)];
  476. pset.color = PlayerColor(i);
  477. if(pinfo.canHumanPlay && namesIt != playerNames.cend())
  478. {
  479. setPlayerConnectedId(pset, namesIt++->first);
  480. }
  481. else
  482. {
  483. setPlayerConnectedId(pset, PlayerSettings::PLAYER_AI);
  484. if(!pinfo.canHumanPlay)
  485. {
  486. pset.compOnly = true;
  487. }
  488. }
  489. pset.castle = pinfo.defaultCastle();
  490. pset.hero = pinfo.defaultHero();
  491. if(pset.hero != HeroTypeID::RANDOM && pinfo.hasCustomMainHero())
  492. {
  493. pset.hero = pinfo.mainCustomHeroId;
  494. pset.heroNameTextId = pinfo.mainCustomHeroNameTextId;
  495. pset.heroPortrait = pinfo.mainCustomHeroPortrait;
  496. }
  497. }
  498. if(mi->isRandomMap && mapGenOpts)
  499. si->mapGenOptions = std::shared_ptr<CMapGenOptions>(mapGenOpts);
  500. else
  501. si->mapGenOptions.reset();
  502. }
  503. if (lobbyProcessor)
  504. {
  505. std::string roomDescription;
  506. if (si->mapGenOptions)
  507. {
  508. if (si->mapGenOptions->getMapTemplate())
  509. roomDescription = si->mapGenOptions->getMapTemplate()->getName();
  510. // else - no template selected.
  511. // TODO: handle this somehow?
  512. }
  513. else
  514. roomDescription = mi->getNameTranslated();
  515. lobbyProcessor->sendChangeRoomDescription(roomDescription);
  516. }
  517. si->mapname = mi->fileURI;
  518. }
  519. void CVCMIServer::updateAndPropagateLobbyState()
  520. {
  521. // Update player settings for RMG
  522. // TODO: find appropriate location for this code
  523. if(si->mapGenOptions && si->mode == EStartMode::NEW_GAME)
  524. {
  525. for(const auto & psetPair : si->playerInfos)
  526. {
  527. const auto & pset = psetPair.second;
  528. si->mapGenOptions->setStartingTownForPlayer(pset.color, pset.castle);
  529. si->mapGenOptions->setStartingHeroForPlayer(pset.color, pset.hero);
  530. if(pset.isControlledByHuman())
  531. {
  532. si->mapGenOptions->setPlayerTypeForStandardPlayer(pset.color, EPlayerType::HUMAN);
  533. }
  534. else
  535. {
  536. si->mapGenOptions->setPlayerTypeForStandardPlayer(pset.color, EPlayerType::AI);
  537. }
  538. }
  539. }
  540. auto lus = std::make_unique<LobbyUpdateState>();
  541. lus->state = *this;
  542. announcePack(std::move(lus));
  543. }
  544. void CVCMIServer::setPlayer(PlayerColor clickedColor)
  545. {
  546. struct PlayerToRestore
  547. {
  548. PlayerColor color;
  549. int id;
  550. void reset() { id = -1; color = PlayerColor::CANNOT_DETERMINE; }
  551. PlayerToRestore(){ reset(); }
  552. } playerToRestore;
  553. PlayerSettings & clicked = si->playerInfos[clickedColor];
  554. //identify clicked player
  555. int clickedNameID = 0; //number of player - zero means AI, assume it initially
  556. if(clicked.isControlledByHuman())
  557. clickedNameID = *(clicked.connectedPlayerIDs.begin()); //if not AI - set appropriate ID
  558. if(clickedNameID > 0 && playerToRestore.id == clickedNameID) //player to restore is about to being replaced -> put him back to the old place
  559. {
  560. PlayerSettings & restPos = si->playerInfos[playerToRestore.color];
  561. setPlayerConnectedId(restPos, playerToRestore.id);
  562. playerToRestore.reset();
  563. }
  564. int newPlayer; //which player will take clicked position
  565. //who will be put here?
  566. if(!clickedNameID) //AI player clicked -> if possible replace computer with unallocated player
  567. {
  568. newPlayer = getIdOfFirstUnallocatedPlayer();
  569. if(!newPlayer) //no "free" player -> get just first one
  570. newPlayer = playerNames.begin()->first;
  571. }
  572. else //human clicked -> take next
  573. {
  574. auto i = playerNames.find(clickedNameID); //clicked one
  575. i++; //player AFTER clicked one
  576. if(i != playerNames.end())
  577. newPlayer = i->first;
  578. else
  579. newPlayer = 0; //AI if we scrolled through all players
  580. }
  581. setPlayerConnectedId(clicked, newPlayer); //put player
  582. //if that player was somewhere else, we need to replace him with computer
  583. if(newPlayer) //not AI
  584. {
  585. for(auto i = si->playerInfos.begin(); i != si->playerInfos.end(); i++)
  586. {
  587. int curNameID = *(i->second.connectedPlayerIDs.begin());
  588. if(i->first != clickedColor && curNameID == newPlayer)
  589. {
  590. assert(i->second.connectedPlayerIDs.size());
  591. playerToRestore.color = i->first;
  592. playerToRestore.id = newPlayer;
  593. setPlayerConnectedId(i->second, PlayerSettings::PLAYER_AI); //set computer
  594. break;
  595. }
  596. }
  597. }
  598. }
  599. void CVCMIServer::setPlayerName(PlayerColor color, std::string name)
  600. {
  601. if(color == PlayerColor::CANNOT_DETERMINE)
  602. return;
  603. PlayerSettings & player = si->playerInfos.at(color);
  604. if(!player.isControlledByHuman())
  605. return;
  606. if(player.connectedPlayerIDs.empty())
  607. return;
  608. int nameID = *(player.connectedPlayerIDs.begin()); //if not AI - set appropriate ID
  609. playerNames[nameID].name = name;
  610. setPlayerConnectedId(player, nameID);
  611. }
  612. void CVCMIServer::setPlayerHandicap(PlayerColor color, Handicap handicap)
  613. {
  614. if(color == PlayerColor::CANNOT_DETERMINE)
  615. return;
  616. si->playerInfos[color].handicap = handicap;
  617. int humanPlayer = 0;
  618. for (const auto & pi : si->playerInfos)
  619. if(pi.second.isControlledByHuman())
  620. humanPlayer++;
  621. if(humanPlayer < 2) // Singleplayer
  622. return;
  623. MetaString str;
  624. str.appendTextID("vcmi.lobby.handicap");
  625. str.appendRawString(" ");
  626. str.appendName(color);
  627. str.appendRawString(":");
  628. if(handicap.startBonus.empty() && handicap.percentIncome == 100 && handicap.percentGrowth == 100)
  629. {
  630. str.appendRawString(" ");
  631. str.appendTextID("core.genrltxt.523");
  632. announceTxt(str);
  633. return;
  634. }
  635. for(auto & res : EGameResID::ALL_RESOURCES())
  636. if(handicap.startBonus[res] != 0)
  637. {
  638. str.appendRawString(" ");
  639. str.appendName(res);
  640. str.appendRawString(":");
  641. str.appendRawString(std::to_string(handicap.startBonus[res]));
  642. }
  643. if(handicap.percentIncome != 100)
  644. {
  645. str.appendRawString(" ");
  646. str.appendTextID("core.jktext.32");
  647. str.appendRawString(":");
  648. str.appendRawString(std::to_string(handicap.percentIncome) + "%");
  649. }
  650. if(handicap.percentGrowth != 100)
  651. {
  652. str.appendRawString(" ");
  653. str.appendTextID("core.genrltxt.194");
  654. str.appendRawString(":");
  655. str.appendRawString(std::to_string(handicap.percentGrowth) + "%");
  656. }
  657. announceTxt(str);
  658. }
  659. void CVCMIServer::optionNextCastle(PlayerColor player, int dir)
  660. {
  661. PlayerSettings & s = si->playerInfos[player];
  662. FactionID & cur = s.castle;
  663. auto & allowed = getPlayerInfo(player).allowedFactions;
  664. const bool allowRandomTown = getPlayerInfo(player).isFactionRandom;
  665. if(cur == FactionID::NONE) //no change
  666. return;
  667. if(cur == FactionID::RANDOM) //first/last available
  668. {
  669. if(dir > 0)
  670. cur = *allowed.begin(); //id of first town
  671. else
  672. cur = *allowed.rbegin(); //id of last town
  673. }
  674. else // next/previous available
  675. {
  676. if((cur == *allowed.begin() && dir < 0) || (cur == *allowed.rbegin() && dir > 0))
  677. {
  678. if(allowRandomTown)
  679. {
  680. cur = FactionID::RANDOM;
  681. }
  682. else
  683. {
  684. if(dir > 0)
  685. cur = *allowed.begin();
  686. else
  687. cur = *allowed.rbegin();
  688. }
  689. }
  690. else
  691. {
  692. assert(dir >= -1 && dir <= 1); //othervice std::advance may go out of range
  693. auto iter = allowed.find(cur);
  694. std::advance(iter, dir);
  695. cur = *iter;
  696. }
  697. }
  698. if(s.hero.isValid() && !getPlayerInfo(player).hasCustomMainHero()) // remove hero unless it set to fixed one in map editor
  699. {
  700. s.hero = HeroTypeID::RANDOM;
  701. }
  702. if(!cur.isValid() && s.bonus == PlayerStartingBonus::RESOURCE)
  703. s.bonus = PlayerStartingBonus::RANDOM;
  704. }
  705. void CVCMIServer::optionSetCastle(PlayerColor player, FactionID id)
  706. {
  707. PlayerSettings & s = si->playerInfos[player];
  708. FactionID & cur = s.castle;
  709. auto & allowed = getPlayerInfo(player).allowedFactions;
  710. if(cur == FactionID::NONE) //no change
  711. return;
  712. if(allowed.find(id) == allowed.end() && id != FactionID::RANDOM) // valid id
  713. return;
  714. cur = static_cast<FactionID>(id);
  715. if(s.hero.isValid() && !getPlayerInfo(player).hasCustomMainHero()) // remove hero unless it set to fixed one in map editor
  716. {
  717. s.hero = HeroTypeID::RANDOM;
  718. }
  719. if(!cur.isValid() && s.bonus == PlayerStartingBonus::RESOURCE)
  720. s.bonus = PlayerStartingBonus::RANDOM;
  721. }
  722. void CVCMIServer::setCampaignMap(CampaignScenarioID mapId)
  723. {
  724. campaignMap = mapId;
  725. si->difficulty = si->campState->scenario(mapId).difficulty;
  726. campaignBonus = -1;
  727. updateStartInfoOnMapChange(si->campState->getMapInfo(mapId));
  728. }
  729. void CVCMIServer::setCampaignBonus(int bonusId)
  730. {
  731. campaignBonus = bonusId;
  732. const CampaignScenario & scenario = si->campState->scenario(campaignMap);
  733. const std::vector<CampaignBonus> & bonDescs = scenario.travelOptions.bonusesToChoose;
  734. if(bonDescs[bonusId].type == CampaignBonusType::HERO)
  735. {
  736. for(auto & elem : si->playerInfos)
  737. {
  738. if(elem.first == PlayerColor(bonDescs[bonusId].info1))
  739. setPlayerConnectedId(elem.second, 1);
  740. else
  741. setPlayerConnectedId(elem.second, PlayerSettings::PLAYER_AI);
  742. }
  743. }
  744. }
  745. void CVCMIServer::optionNextHero(PlayerColor player, int dir)
  746. {
  747. PlayerSettings & s = si->playerInfos[player];
  748. if(!s.castle.isValid() || s.hero == HeroTypeID::NONE)
  749. return;
  750. if(s.hero == HeroTypeID::RANDOM) // first/last available
  751. {
  752. if (dir > 0)
  753. s.hero = nextAllowedHero(player, HeroTypeID(-1), dir);
  754. else
  755. s.hero = nextAllowedHero(player, HeroTypeID(VLC->heroh->size()), dir);
  756. }
  757. else
  758. {
  759. s.hero = nextAllowedHero(player, s.hero, dir);
  760. }
  761. }
  762. void CVCMIServer::optionSetHero(PlayerColor player, HeroTypeID id)
  763. {
  764. PlayerSettings & s = si->playerInfos[player];
  765. if(!s.castle.isValid() || s.hero == HeroTypeID::NONE)
  766. return;
  767. if(id == HeroTypeID::RANDOM)
  768. {
  769. s.hero = HeroTypeID::RANDOM;
  770. }
  771. if(canUseThisHero(player, id))
  772. s.hero = static_cast<HeroTypeID>(id);
  773. }
  774. HeroTypeID CVCMIServer::nextAllowedHero(PlayerColor player, HeroTypeID initial, int direction)
  775. {
  776. HeroTypeID first(initial.getNum() + direction);
  777. if(direction > 0)
  778. {
  779. for (auto i = first; i.getNum() < VLC->heroh->size(); ++i)
  780. if(canUseThisHero(player, i))
  781. return i;
  782. }
  783. else
  784. {
  785. for (auto i = first; i.getNum() >= 0; --i)
  786. if(canUseThisHero(player, i))
  787. return i;
  788. }
  789. return HeroTypeID::RANDOM;
  790. }
  791. void CVCMIServer::optionNextBonus(PlayerColor player, int dir)
  792. {
  793. PlayerSettings & s = si->playerInfos[player];
  794. PlayerStartingBonus & ret = s.bonus = static_cast<PlayerStartingBonus>(static_cast<int>(s.bonus) + dir);
  795. if(s.hero == HeroTypeID::NONE &&
  796. !getPlayerInfo(player).heroesNames.size() &&
  797. ret == PlayerStartingBonus::ARTIFACT) //no hero - can't be artifact
  798. {
  799. if(dir < 0)
  800. ret = PlayerStartingBonus::RANDOM;
  801. else
  802. ret = PlayerStartingBonus::GOLD;
  803. }
  804. if(ret > PlayerStartingBonus::RESOURCE)
  805. ret = PlayerStartingBonus::RANDOM;
  806. if(ret < PlayerStartingBonus::RANDOM)
  807. ret = PlayerStartingBonus::RESOURCE;
  808. if(s.castle == FactionID::RANDOM && ret == PlayerStartingBonus::RESOURCE) //random castle - can't be resource
  809. {
  810. if(dir < 0)
  811. ret = PlayerStartingBonus::GOLD;
  812. else
  813. ret = PlayerStartingBonus::RANDOM;
  814. }
  815. }
  816. void CVCMIServer::optionSetBonus(PlayerColor player, PlayerStartingBonus id)
  817. {
  818. PlayerSettings & s = si->playerInfos[player];
  819. if(s.hero == HeroTypeID::NONE &&
  820. !getPlayerInfo(player).heroesNames.size() &&
  821. id == PlayerStartingBonus::ARTIFACT) //no hero - can't be artifact
  822. return;
  823. if(id > PlayerStartingBonus::RESOURCE)
  824. return;
  825. if(id < PlayerStartingBonus::RANDOM)
  826. return;
  827. if(s.castle == FactionID::RANDOM && id == PlayerStartingBonus::RESOURCE) //random castle - can't be resource
  828. return;
  829. s.bonus = id;
  830. }
  831. bool CVCMIServer::canUseThisHero(PlayerColor player, HeroTypeID ID)
  832. {
  833. return VLC->heroh->size() > ID
  834. && si->playerInfos[player].castle == VLC->heroh->objects[ID]->heroClass->faction
  835. && !vstd::contains(getUsedHeroes(), ID)
  836. && mi->mapHeader->allowedHeroes.count(ID);
  837. }
  838. std::vector<HeroTypeID> CVCMIServer::getUsedHeroes()
  839. {
  840. std::vector<HeroTypeID> heroIds;
  841. for(auto & p : si->playerInfos)
  842. {
  843. const auto & heroes = getPlayerInfo(p.first).heroesNames;
  844. for(auto & hero : heroes)
  845. if(hero.heroId >= 0) //in VCMI map format heroId = -1 means random hero
  846. heroIds.push_back(hero.heroId);
  847. if(p.second.hero != HeroTypeID::RANDOM)
  848. heroIds.push_back(p.second.hero);
  849. }
  850. return heroIds;
  851. }
  852. ui8 CVCMIServer::getIdOfFirstUnallocatedPlayer() const
  853. {
  854. for(auto i = playerNames.cbegin(); i != playerNames.cend(); i++)
  855. {
  856. if(!si->getPlayersSettings(i->first))
  857. return i->first;
  858. }
  859. return 0;
  860. }
  861. void CVCMIServer::multiplayerWelcomeMessage()
  862. {
  863. int humanPlayer = 0;
  864. for (const auto & pi : si->playerInfos)
  865. if(pi.second.isControlledByHuman())
  866. humanPlayer++;
  867. if(humanPlayer < 2) // Singleplayer
  868. return;
  869. gh->playerMessages->broadcastSystemMessage("Use '!help' to list available commands");
  870. for (const auto & pi : si->playerInfos)
  871. if(!pi.second.handicap.startBonus.empty() || pi.second.handicap.percentIncome != 100 || pi.second.handicap.percentGrowth != 100)
  872. {
  873. MetaString str;
  874. str.appendTextID("vcmi.lobby.handicap");
  875. str.appendRawString(" ");
  876. str.appendName(pi.first);
  877. str.appendRawString(":");
  878. for(auto & res : EGameResID::ALL_RESOURCES())
  879. if(pi.second.handicap.startBonus[res] != 0)
  880. {
  881. str.appendRawString(" ");
  882. str.appendName(res);
  883. str.appendRawString(":");
  884. str.appendRawString(std::to_string(pi.second.handicap.startBonus[res]));
  885. }
  886. if(pi.second.handicap.percentIncome != 100)
  887. {
  888. str.appendRawString(" ");
  889. str.appendTextID("core.jktext.32");
  890. str.appendRawString(":");
  891. str.appendRawString(std::to_string(pi.second.handicap.percentIncome) + "%");
  892. }
  893. if(pi.second.handicap.percentGrowth != 100)
  894. {
  895. str.appendRawString(" ");
  896. str.appendTextID("core.genrltxt.194");
  897. str.appendRawString(":");
  898. str.appendRawString(std::to_string(pi.second.handicap.percentGrowth) + "%");
  899. }
  900. gh->playerMessages->broadcastSystemMessage(str);
  901. }
  902. std::vector<std::string> optionIds;
  903. if(si->extraOptionsInfo.cheatsAllowed)
  904. optionIds.emplace_back("vcmi.optionsTab.cheatAllowed.hover");
  905. if(si->extraOptionsInfo.unlimitedReplay)
  906. optionIds.emplace_back("vcmi.optionsTab.unlimitedReplay.hover");
  907. if(!optionIds.size()) // No settings to publish
  908. return;
  909. MetaString str;
  910. str.appendTextID("vcmi.optionsTab.extraOptions.hover");
  911. str.appendRawString(": ");
  912. for(int i = 0; i < optionIds.size(); i++)
  913. {
  914. str.appendTextID(optionIds[i]);
  915. if(i < optionIds.size() - 1)
  916. str.appendRawString(", ");
  917. }
  918. gh->playerMessages->broadcastSystemMessage(str);
  919. }
  920. INetworkHandler & CVCMIServer::getNetworkHandler()
  921. {
  922. return *networkHandler;
  923. }