CVCMIServer.cpp 28 KB

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