2
0

CVCMIServer.cpp 28 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078
  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(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. LobbyLoadProgress loadProgress;
  195. loadProgress.progress = currentProgress;
  196. announcePack(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 && gh && getState() == EServerState::GAMEPLAY)
  252. {
  253. LobbyClientDisconnected lcd;
  254. lcd.c = c;
  255. lcd.clientId = c->connectionID;
  256. handleReceivedPack(lcd);
  257. }
  258. }
  259. void CVCMIServer::handleReceivedPack(CPackForLobby & pack)
  260. {
  261. ClientPermissionsCheckerNetPackVisitor checker(*this);
  262. pack.visit(checker);
  263. if(checker.getResult())
  264. {
  265. ApplyOnServerNetPackVisitor applier(*this);
  266. pack.visit(applier);
  267. if (applier.getResult())
  268. announcePack(pack);
  269. }
  270. }
  271. void CVCMIServer::announcePack(CPackForLobby & pack)
  272. {
  273. for(auto activeConnection : activeConnections)
  274. {
  275. // FIXME: we need to avoid sending something to client that not yet get answer for LobbyClientConnected
  276. // Until UUID set we only pass LobbyClientConnected to this client
  277. //if(c->uuid == uuid && !dynamic_cast<LobbyClientConnected *>(pack.get()))
  278. // continue;
  279. activeConnection->sendPack(pack);
  280. }
  281. ApplyOnServerAfterAnnounceNetPackVisitor applier(*this);
  282. pack.visit(applier);
  283. }
  284. void CVCMIServer::announceMessage(const MetaString & txt)
  285. {
  286. logNetwork->info("Show message: %s", txt.toString());
  287. LobbyShowMessage cm;
  288. cm.message = txt;
  289. announcePack(cm);
  290. }
  291. void CVCMIServer::announceMessage(const std::string & txt)
  292. {
  293. MetaString str;
  294. str.appendRawString(txt);
  295. announceMessage(str);
  296. }
  297. void CVCMIServer::announceTxt(const MetaString & txt, const std::string & playerName)
  298. {
  299. logNetwork->info("%s says: %s", playerName, txt.toString());
  300. LobbyChatMessage cm;
  301. cm.playerName = playerName;
  302. cm.message = txt;
  303. announcePack(cm);
  304. }
  305. void CVCMIServer::announceTxt(const std::string & txt, const std::string & playerName)
  306. {
  307. MetaString str;
  308. str.appendRawString(txt);
  309. announceTxt(str, playerName);
  310. }
  311. bool CVCMIServer::passHost(int toConnectionId)
  312. {
  313. for(auto activeConnection : activeConnections)
  314. {
  315. if(isClientHost(activeConnection->connectionID))
  316. continue;
  317. if(activeConnection->connectionID != toConnectionId)
  318. continue;
  319. hostClientId = activeConnection->connectionID;
  320. announceTxt(boost::str(boost::format("Pass host to connection %d") % toConnectionId));
  321. return true;
  322. }
  323. return false;
  324. }
  325. void CVCMIServer::clientConnected(std::shared_ptr<CConnection> c, std::vector<std::string> & names, const std::string & uuid, EStartMode mode)
  326. {
  327. assert(getState() == EServerState::LOBBY);
  328. c->connectionID = currentClientId++;
  329. if(hostClientId == -1)
  330. {
  331. hostClientId = c->connectionID;
  332. si->mode = mode;
  333. }
  334. logNetwork->info("Connection with client %d established. UUID: %s", c->connectionID, c->uuid);
  335. for(auto & name : names)
  336. {
  337. logNetwork->info("Client %d player: %s", c->connectionID, name);
  338. ui8 id = currentPlayerId++;
  339. ClientPlayer cp;
  340. cp.connection = c->connectionID;
  341. cp.name = name;
  342. playerNames.insert(std::make_pair(id, cp));
  343. announceTxt(boost::str(boost::format("%s (pid %d cid %d) joins the game") % name % id % c->connectionID));
  344. //put new player in first slot with AI
  345. for(auto & elem : si->playerInfos)
  346. {
  347. if(elem.second.isControlledByAI() && !elem.second.compOnly)
  348. {
  349. setPlayerConnectedId(elem.second, id);
  350. break;
  351. }
  352. }
  353. }
  354. }
  355. void CVCMIServer::clientDisconnected(std::shared_ptr<CConnection> connection)
  356. {
  357. assert(vstd::contains(activeConnections, connection));
  358. logGlobal->trace("Received disconnection request");
  359. vstd::erase(activeConnections, connection);
  360. if(activeConnections.empty() || hostClientId == connection->connectionID)
  361. {
  362. setState(EServerState::SHUTDOWN);
  363. return;
  364. }
  365. if(gh && getState() == EServerState::GAMEPLAY)
  366. {
  367. gh->handleClientDisconnection(connection);
  368. }
  369. // PlayerReinitInterface startAiPack;
  370. // startAiPack.playerConnectionId = PlayerSettings::PLAYER_AI;
  371. //
  372. // for(auto it = playerNames.begin(); it != playerNames.end();)
  373. // {
  374. // if(it->second.connection != c->connectionID)
  375. // {
  376. // ++it;
  377. // continue;
  378. // }
  379. //
  380. // int id = it->first;
  381. // std::string playerLeftMsgText = boost::str(boost::format("%s (pid %d cid %d) left the game") % id % playerNames[id].name % c->connectionID);
  382. // announceTxt(playerLeftMsgText); //send lobby text, it will be ignored for non-lobby clients
  383. // auto * playerSettings = si->getPlayersSettings(id);
  384. // if(!playerSettings)
  385. // {
  386. // ++it;
  387. // continue;
  388. // }
  389. //
  390. // it = playerNames.erase(it);
  391. // setPlayerConnectedId(*playerSettings, PlayerSettings::PLAYER_AI);
  392. //
  393. // if(gh && si && state == EServerState::GAMEPLAY)
  394. // {
  395. // gh->playerMessages->broadcastMessage(playerSettings->color, playerLeftMsgText);
  396. // // gh->connections[playerSettings->color].insert(hostClient);
  397. // startAiPack.players.push_back(playerSettings->color);
  398. // }
  399. // }
  400. //
  401. // if(!startAiPack.players.empty())
  402. // gh->sendAndApply(startAiPack);
  403. }
  404. void CVCMIServer::reconnectPlayer(int connId)
  405. {
  406. PlayerReinitInterface startAiPack;
  407. startAiPack.playerConnectionId = connId;
  408. if(gh && si && getState() == EServerState::GAMEPLAY)
  409. {
  410. for(auto it = playerNames.begin(); it != playerNames.end(); ++it)
  411. {
  412. if(it->second.connection != connId)
  413. continue;
  414. int id = it->first;
  415. auto * playerSettings = si->getPlayersSettings(id);
  416. if(!playerSettings)
  417. continue;
  418. std::string messageText = boost::str(boost::format("%s (cid %d) is connected") % playerSettings->name % connId);
  419. gh->playerMessages->broadcastMessage(playerSettings->color, messageText);
  420. startAiPack.players.push_back(playerSettings->color);
  421. }
  422. if(!startAiPack.players.empty())
  423. gh->sendAndApply(startAiPack);
  424. }
  425. }
  426. void CVCMIServer::setPlayerConnectedId(PlayerSettings & pset, ui8 player) const
  427. {
  428. if(vstd::contains(playerNames, player))
  429. pset.name = playerNames.find(player)->second.name;
  430. else
  431. pset.name = VLC->generaltexth->allTexts[468]; //Computer
  432. pset.connectedPlayerIDs.clear();
  433. if(player != PlayerSettings::PLAYER_AI)
  434. pset.connectedPlayerIDs.insert(player);
  435. }
  436. void CVCMIServer::updateStartInfoOnMapChange(std::shared_ptr<CMapInfo> mapInfo, std::shared_ptr<CMapGenOptions> mapGenOpts)
  437. {
  438. mi = mapInfo;
  439. if(!mi)
  440. return;
  441. auto namesIt = playerNames.cbegin();
  442. si->playerInfos.clear();
  443. if(mi->scenarioOptionsOfSave)
  444. {
  445. si = CMemorySerializer::deepCopy(*mi->scenarioOptionsOfSave);
  446. si->mode = EStartMode::LOAD_GAME;
  447. if(si->campState)
  448. campaignMap = si->campState->currentScenario().value();
  449. for(auto & ps : si->playerInfos)
  450. {
  451. if(!ps.second.compOnly && ps.second.connectedPlayerIDs.size() && namesIt != playerNames.cend())
  452. {
  453. setPlayerConnectedId(ps.second, namesIt++->first);
  454. }
  455. else
  456. {
  457. setPlayerConnectedId(ps.second, PlayerSettings::PLAYER_AI);
  458. }
  459. }
  460. }
  461. else if(si->mode == EStartMode::NEW_GAME || si->mode == EStartMode::CAMPAIGN)
  462. {
  463. if(mi->campaign)
  464. return;
  465. for(int i = 0; i < mi->mapHeader->players.size(); i++)
  466. {
  467. const PlayerInfo & pinfo = mi->mapHeader->players[i];
  468. //neither computer nor human can play - no player
  469. if(!(pinfo.canHumanPlay || pinfo.canComputerPlay))
  470. continue;
  471. PlayerSettings & pset = si->playerInfos[PlayerColor(i)];
  472. pset.color = PlayerColor(i);
  473. if(pinfo.canHumanPlay && namesIt != playerNames.cend())
  474. {
  475. setPlayerConnectedId(pset, namesIt++->first);
  476. }
  477. else
  478. {
  479. setPlayerConnectedId(pset, PlayerSettings::PLAYER_AI);
  480. if(!pinfo.canHumanPlay)
  481. {
  482. pset.compOnly = true;
  483. }
  484. }
  485. pset.castle = pinfo.defaultCastle();
  486. pset.hero = pinfo.defaultHero();
  487. if(pset.hero != HeroTypeID::RANDOM && pinfo.hasCustomMainHero())
  488. {
  489. pset.hero = pinfo.mainCustomHeroId;
  490. pset.heroNameTextId = pinfo.mainCustomHeroNameTextId;
  491. pset.heroPortrait = pinfo.mainCustomHeroPortrait;
  492. }
  493. }
  494. if(mi->isRandomMap && mapGenOpts)
  495. si->mapGenOptions = std::shared_ptr<CMapGenOptions>(mapGenOpts);
  496. else
  497. si->mapGenOptions.reset();
  498. }
  499. if (lobbyProcessor)
  500. {
  501. std::string roomDescription;
  502. if (si->mapGenOptions)
  503. {
  504. if (si->mapGenOptions->getMapTemplate())
  505. roomDescription = si->mapGenOptions->getMapTemplate()->getName();
  506. // else - no template selected.
  507. // TODO: handle this somehow?
  508. }
  509. else
  510. roomDescription = mi->getNameTranslated();
  511. lobbyProcessor->sendChangeRoomDescription(roomDescription);
  512. }
  513. si->mapname = mi->fileURI;
  514. }
  515. void CVCMIServer::updateAndPropagateLobbyState()
  516. {
  517. // Update player settings for RMG
  518. // TODO: find appropriate location for this code
  519. if(si->mapGenOptions && si->mode == EStartMode::NEW_GAME)
  520. {
  521. for(const auto & psetPair : si->playerInfos)
  522. {
  523. const auto & pset = psetPair.second;
  524. si->mapGenOptions->setStartingTownForPlayer(pset.color, pset.castle);
  525. si->mapGenOptions->setStartingHeroForPlayer(pset.color, pset.hero);
  526. if(pset.isControlledByHuman())
  527. {
  528. si->mapGenOptions->setPlayerTypeForStandardPlayer(pset.color, EPlayerType::HUMAN);
  529. }
  530. else
  531. {
  532. si->mapGenOptions->setPlayerTypeForStandardPlayer(pset.color, EPlayerType::AI);
  533. }
  534. }
  535. }
  536. LobbyUpdateState lus;
  537. lus.state = *this;
  538. announcePack(lus);
  539. }
  540. void CVCMIServer::setPlayer(PlayerColor clickedColor)
  541. {
  542. struct PlayerToRestore
  543. {
  544. PlayerColor color;
  545. int id;
  546. void reset() { id = -1; color = PlayerColor::CANNOT_DETERMINE; }
  547. PlayerToRestore(){ reset(); }
  548. } playerToRestore;
  549. PlayerSettings & clicked = si->playerInfos[clickedColor];
  550. //identify clicked player
  551. int clickedNameID = 0; //number of player - zero means AI, assume it initially
  552. if(clicked.isControlledByHuman())
  553. clickedNameID = *(clicked.connectedPlayerIDs.begin()); //if not AI - set appropriate ID
  554. if(clickedNameID > 0 && playerToRestore.id == clickedNameID) //player to restore is about to being replaced -> put him back to the old place
  555. {
  556. PlayerSettings & restPos = si->playerInfos[playerToRestore.color];
  557. setPlayerConnectedId(restPos, playerToRestore.id);
  558. playerToRestore.reset();
  559. }
  560. int newPlayer; //which player will take clicked position
  561. //who will be put here?
  562. if(!clickedNameID) //AI player clicked -> if possible replace computer with unallocated player
  563. {
  564. newPlayer = getIdOfFirstUnallocatedPlayer();
  565. if(!newPlayer) //no "free" player -> get just first one
  566. newPlayer = playerNames.begin()->first;
  567. }
  568. else //human clicked -> take next
  569. {
  570. auto i = playerNames.find(clickedNameID); //clicked one
  571. i++; //player AFTER clicked one
  572. if(i != playerNames.end())
  573. newPlayer = i->first;
  574. else
  575. newPlayer = 0; //AI if we scrolled through all players
  576. }
  577. setPlayerConnectedId(clicked, newPlayer); //put player
  578. //if that player was somewhere else, we need to replace him with computer
  579. if(newPlayer) //not AI
  580. {
  581. for(auto i = si->playerInfos.begin(); i != si->playerInfos.end(); i++)
  582. {
  583. int curNameID = *(i->second.connectedPlayerIDs.begin());
  584. if(i->first != clickedColor && curNameID == newPlayer)
  585. {
  586. assert(i->second.connectedPlayerIDs.size());
  587. playerToRestore.color = i->first;
  588. playerToRestore.id = newPlayer;
  589. setPlayerConnectedId(i->second, PlayerSettings::PLAYER_AI); //set computer
  590. break;
  591. }
  592. }
  593. }
  594. }
  595. void CVCMIServer::setPlayerName(PlayerColor color, std::string name)
  596. {
  597. if(color == PlayerColor::CANNOT_DETERMINE)
  598. return;
  599. PlayerSettings & player = si->playerInfos.at(color);
  600. if(!player.isControlledByHuman())
  601. return;
  602. if(player.connectedPlayerIDs.empty())
  603. return;
  604. int nameID = *(player.connectedPlayerIDs.begin()); //if not AI - set appropriate ID
  605. playerNames[nameID].name = name;
  606. setPlayerConnectedId(player, nameID);
  607. }
  608. void CVCMIServer::setPlayerHandicap(PlayerColor color, Handicap handicap)
  609. {
  610. if(color == PlayerColor::CANNOT_DETERMINE)
  611. return;
  612. si->playerInfos[color].handicap = handicap;
  613. int humanPlayer = 0;
  614. for (const auto & pi : si->playerInfos)
  615. if(pi.second.isControlledByHuman())
  616. humanPlayer++;
  617. if(humanPlayer < 2) // Singleplayer
  618. return;
  619. MetaString str;
  620. str.appendTextID("vcmi.lobby.handicap");
  621. str.appendRawString(" ");
  622. str.appendName(color);
  623. str.appendRawString(":");
  624. if(handicap.startBonus.empty() && handicap.percentIncome == 100 && handicap.percentGrowth == 100)
  625. {
  626. str.appendRawString(" ");
  627. str.appendTextID("core.genrltxt.523");
  628. announceTxt(str);
  629. return;
  630. }
  631. for(auto & res : EGameResID::ALL_RESOURCES())
  632. if(handicap.startBonus[res] != 0)
  633. {
  634. str.appendRawString(" ");
  635. str.appendName(res);
  636. str.appendRawString(":");
  637. str.appendRawString(std::to_string(handicap.startBonus[res]));
  638. }
  639. if(handicap.percentIncome != 100)
  640. {
  641. str.appendRawString(" ");
  642. str.appendTextID("core.jktext.32");
  643. str.appendRawString(":");
  644. str.appendRawString(std::to_string(handicap.percentIncome) + "%");
  645. }
  646. if(handicap.percentGrowth != 100)
  647. {
  648. str.appendRawString(" ");
  649. str.appendTextID("core.genrltxt.194");
  650. str.appendRawString(":");
  651. str.appendRawString(std::to_string(handicap.percentGrowth) + "%");
  652. }
  653. announceTxt(str);
  654. }
  655. void CVCMIServer::optionNextCastle(PlayerColor player, int dir)
  656. {
  657. PlayerSettings & s = si->playerInfos[player];
  658. FactionID & cur = s.castle;
  659. auto & allowed = getPlayerInfo(player).allowedFactions;
  660. const bool allowRandomTown = getPlayerInfo(player).isFactionRandom;
  661. if(cur == FactionID::NONE) //no change
  662. return;
  663. if(cur == FactionID::RANDOM) //first/last available
  664. {
  665. if(dir > 0)
  666. cur = *allowed.begin(); //id of first town
  667. else
  668. cur = *allowed.rbegin(); //id of last town
  669. }
  670. else // next/previous available
  671. {
  672. if((cur == *allowed.begin() && dir < 0) || (cur == *allowed.rbegin() && dir > 0))
  673. {
  674. if(allowRandomTown)
  675. {
  676. cur = FactionID::RANDOM;
  677. }
  678. else
  679. {
  680. if(dir > 0)
  681. cur = *allowed.begin();
  682. else
  683. cur = *allowed.rbegin();
  684. }
  685. }
  686. else
  687. {
  688. assert(dir >= -1 && dir <= 1); //othervice std::advance may go out of range
  689. auto iter = allowed.find(cur);
  690. std::advance(iter, dir);
  691. cur = *iter;
  692. }
  693. }
  694. if(s.hero.isValid() && !getPlayerInfo(player).hasCustomMainHero()) // remove hero unless it set to fixed one in map editor
  695. {
  696. s.hero = HeroTypeID::RANDOM;
  697. }
  698. if(!cur.isValid() && s.bonus == PlayerStartingBonus::RESOURCE)
  699. s.bonus = PlayerStartingBonus::RANDOM;
  700. }
  701. void CVCMIServer::optionSetCastle(PlayerColor player, FactionID id)
  702. {
  703. PlayerSettings & s = si->playerInfos[player];
  704. FactionID & cur = s.castle;
  705. auto & allowed = getPlayerInfo(player).allowedFactions;
  706. if(cur == FactionID::NONE) //no change
  707. return;
  708. if(allowed.find(id) == allowed.end() && id != FactionID::RANDOM) // valid id
  709. return;
  710. cur = static_cast<FactionID>(id);
  711. if(s.hero.isValid() && !getPlayerInfo(player).hasCustomMainHero()) // remove hero unless it set to fixed one in map editor
  712. {
  713. s.hero = HeroTypeID::RANDOM;
  714. }
  715. if(!cur.isValid() && s.bonus == PlayerStartingBonus::RESOURCE)
  716. s.bonus = PlayerStartingBonus::RANDOM;
  717. }
  718. void CVCMIServer::setCampaignMap(CampaignScenarioID mapId)
  719. {
  720. campaignMap = mapId;
  721. si->difficulty = si->campState->scenario(mapId).difficulty;
  722. campaignBonus = -1;
  723. updateStartInfoOnMapChange(si->campState->getMapInfo(mapId));
  724. }
  725. void CVCMIServer::setCampaignBonus(int bonusId)
  726. {
  727. campaignBonus = bonusId;
  728. const CampaignScenario & scenario = si->campState->scenario(campaignMap);
  729. const std::vector<CampaignBonus> & bonDescs = scenario.travelOptions.bonusesToChoose;
  730. if(bonDescs[bonusId].type == CampaignBonusType::HERO)
  731. {
  732. for(auto & elem : si->playerInfos)
  733. {
  734. if(elem.first == PlayerColor(bonDescs[bonusId].info1))
  735. setPlayerConnectedId(elem.second, 1);
  736. else
  737. setPlayerConnectedId(elem.second, PlayerSettings::PLAYER_AI);
  738. }
  739. }
  740. }
  741. void CVCMIServer::optionNextHero(PlayerColor player, int dir)
  742. {
  743. PlayerSettings & s = si->playerInfos[player];
  744. if(!s.castle.isValid() || s.hero == HeroTypeID::NONE)
  745. return;
  746. if(s.hero == HeroTypeID::RANDOM) // first/last available
  747. {
  748. if (dir > 0)
  749. s.hero = nextAllowedHero(player, HeroTypeID(-1), dir);
  750. else
  751. s.hero = nextAllowedHero(player, HeroTypeID(VLC->heroh->size()), dir);
  752. }
  753. else
  754. {
  755. s.hero = nextAllowedHero(player, s.hero, dir);
  756. }
  757. }
  758. void CVCMIServer::optionSetHero(PlayerColor player, HeroTypeID id)
  759. {
  760. PlayerSettings & s = si->playerInfos[player];
  761. if(!s.castle.isValid() || s.hero == HeroTypeID::NONE)
  762. return;
  763. if(id == HeroTypeID::RANDOM)
  764. {
  765. s.hero = HeroTypeID::RANDOM;
  766. }
  767. if(canUseThisHero(player, id))
  768. s.hero = static_cast<HeroTypeID>(id);
  769. }
  770. HeroTypeID CVCMIServer::nextAllowedHero(PlayerColor player, HeroTypeID initial, int direction)
  771. {
  772. HeroTypeID first(initial.getNum() + direction);
  773. if(direction > 0)
  774. {
  775. for (auto i = first; i.getNum() < VLC->heroh->size(); ++i)
  776. if(canUseThisHero(player, i))
  777. return i;
  778. }
  779. else
  780. {
  781. for (auto i = first; i.getNum() >= 0; --i)
  782. if(canUseThisHero(player, i))
  783. return i;
  784. }
  785. return HeroTypeID::RANDOM;
  786. }
  787. void CVCMIServer::optionNextBonus(PlayerColor player, int dir)
  788. {
  789. PlayerSettings & s = si->playerInfos[player];
  790. PlayerStartingBonus & ret = s.bonus = static_cast<PlayerStartingBonus>(static_cast<int>(s.bonus) + dir);
  791. if(s.hero == HeroTypeID::NONE &&
  792. !getPlayerInfo(player).heroesNames.size() &&
  793. ret == PlayerStartingBonus::ARTIFACT) //no hero - can't be artifact
  794. {
  795. if(dir < 0)
  796. ret = PlayerStartingBonus::RANDOM;
  797. else
  798. ret = PlayerStartingBonus::GOLD;
  799. }
  800. if(ret > PlayerStartingBonus::RESOURCE)
  801. ret = PlayerStartingBonus::RANDOM;
  802. if(ret < PlayerStartingBonus::RANDOM)
  803. ret = PlayerStartingBonus::RESOURCE;
  804. if(s.castle == FactionID::RANDOM && ret == PlayerStartingBonus::RESOURCE) //random castle - can't be resource
  805. {
  806. if(dir < 0)
  807. ret = PlayerStartingBonus::GOLD;
  808. else
  809. ret = PlayerStartingBonus::RANDOM;
  810. }
  811. }
  812. void CVCMIServer::optionSetBonus(PlayerColor player, PlayerStartingBonus id)
  813. {
  814. PlayerSettings & s = si->playerInfos[player];
  815. if(s.hero == HeroTypeID::NONE &&
  816. !getPlayerInfo(player).heroesNames.size() &&
  817. id == PlayerStartingBonus::ARTIFACT) //no hero - can't be artifact
  818. return;
  819. if(id > PlayerStartingBonus::RESOURCE)
  820. return;
  821. if(id < PlayerStartingBonus::RANDOM)
  822. return;
  823. if(s.castle == FactionID::RANDOM && id == PlayerStartingBonus::RESOURCE) //random castle - can't be resource
  824. return;
  825. s.bonus = id;
  826. }
  827. bool CVCMIServer::canUseThisHero(PlayerColor player, HeroTypeID ID)
  828. {
  829. return VLC->heroh->size() > ID
  830. && si->playerInfos[player].castle == VLC->heroh->objects[ID]->heroClass->faction
  831. && !vstd::contains(getUsedHeroes(), ID)
  832. && mi->mapHeader->allowedHeroes.count(ID);
  833. }
  834. std::vector<HeroTypeID> CVCMIServer::getUsedHeroes()
  835. {
  836. std::vector<HeroTypeID> heroIds;
  837. for(auto & p : si->playerInfos)
  838. {
  839. const auto & heroes = getPlayerInfo(p.first).heroesNames;
  840. for(auto & hero : heroes)
  841. if(hero.heroId >= 0) //in VCMI map format heroId = -1 means random hero
  842. heroIds.push_back(hero.heroId);
  843. if(p.second.hero != HeroTypeID::RANDOM)
  844. heroIds.push_back(p.second.hero);
  845. }
  846. return heroIds;
  847. }
  848. ui8 CVCMIServer::getIdOfFirstUnallocatedPlayer() const
  849. {
  850. for(auto i = playerNames.cbegin(); i != playerNames.cend(); i++)
  851. {
  852. if(!si->getPlayersSettings(i->first))
  853. return i->first;
  854. }
  855. return 0;
  856. }
  857. void CVCMIServer::multiplayerWelcomeMessage()
  858. {
  859. int humanPlayer = 0;
  860. for (const auto & pi : si->playerInfos)
  861. if(pi.second.isControlledByHuman())
  862. humanPlayer++;
  863. if(humanPlayer < 2) // Singleplayer
  864. return;
  865. gh->playerMessages->broadcastSystemMessage("Use '!help' to list available commands");
  866. for (const auto & pi : si->playerInfos)
  867. if(!pi.second.handicap.startBonus.empty() || pi.second.handicap.percentIncome != 100 || pi.second.handicap.percentGrowth != 100)
  868. {
  869. MetaString str;
  870. str.appendTextID("vcmi.lobby.handicap");
  871. str.appendRawString(" ");
  872. str.appendName(pi.first);
  873. str.appendRawString(":");
  874. for(auto & res : EGameResID::ALL_RESOURCES())
  875. if(pi.second.handicap.startBonus[res] != 0)
  876. {
  877. str.appendRawString(" ");
  878. str.appendName(res);
  879. str.appendRawString(":");
  880. str.appendRawString(std::to_string(pi.second.handicap.startBonus[res]));
  881. }
  882. if(pi.second.handicap.percentIncome != 100)
  883. {
  884. str.appendRawString(" ");
  885. str.appendTextID("core.jktext.32");
  886. str.appendRawString(":");
  887. str.appendRawString(std::to_string(pi.second.handicap.percentIncome) + "%");
  888. }
  889. if(pi.second.handicap.percentGrowth != 100)
  890. {
  891. str.appendRawString(" ");
  892. str.appendTextID("core.genrltxt.194");
  893. str.appendRawString(":");
  894. str.appendRawString(std::to_string(pi.second.handicap.percentGrowth) + "%");
  895. }
  896. gh->playerMessages->broadcastSystemMessage(str);
  897. }
  898. std::vector<std::string> optionIds;
  899. if(si->extraOptionsInfo.cheatsAllowed)
  900. optionIds.emplace_back("vcmi.optionsTab.cheatAllowed.hover");
  901. if(si->extraOptionsInfo.unlimitedReplay)
  902. optionIds.emplace_back("vcmi.optionsTab.unlimitedReplay.hover");
  903. if(!optionIds.size()) // No settings to publish
  904. return;
  905. MetaString str;
  906. str.appendTextID("vcmi.optionsTab.extraOptions.hover");
  907. str.appendRawString(": ");
  908. for(int i = 0; i < optionIds.size(); i++)
  909. {
  910. str.appendTextID(optionIds[i]);
  911. if(i < optionIds.size() - 1)
  912. str.appendRawString(", ");
  913. }
  914. gh->playerMessages->broadcastSystemMessage(str);
  915. }
  916. INetworkHandler & CVCMIServer::getNetworkHandler()
  917. {
  918. return *networkHandler;
  919. }