CVCMIServer.cpp 27 KB

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