CVCMIServer.cpp 30 KB

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